CombinedText
stringlengths 8
3.42M
|
---|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs03.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs03.C
/// @brief Run and manage the DDR4 DDR4 loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs03_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
mrs03_data::mrs03_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_mpr_mode(0),
iv_mpr_page(0),
iv_geardown(0),
iv_pda(0),
iv_crc_wr_latency(0),
iv_temp_readout(0),
iv_fine_refresh(0),
iv_read_format(0)
{
FAPI_TRY( mss::eff_mpr_mode(i_target, iv_mpr_mode) );
FAPI_TRY( mss::eff_mpr_page(i_target, iv_mpr_page) );
FAPI_TRY( mss::eff_geardown_mode(i_target, iv_geardown) );
FAPI_TRY( mss::eff_per_dram_access(i_target, iv_pda) );
FAPI_TRY( mss::eff_temp_readout(i_target, iv_temp_readout) );
FAPI_TRY( mss::mrw_fine_refresh_mode(iv_fine_refresh) );
FAPI_TRY( mss::eff_crc_wr_latency(i_target, iv_crc_wr_latency) );
FAPI_TRY( mss::eff_mpr_rd_format(i_target, iv_read_format) );
FAPI_INF("MR3 attributes: MPR_MODE: 0x%x, MPR_PAGE: 0x%x, GD: 0x%x, PDA: 0x%x, "
"TEMP: 0x%x FR: 0x%x, CRC_WL: 0x%x, RF: 0x%x",
iv_mpr_mode, iv_mpr_page, iv_geardown, iv_pda, iv_temp_readout,
iv_fine_refresh, iv_crc_wr_latency, iv_read_format);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs03
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs03(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs03_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS03 data from attributes");
FAPI_TRY( mrs03(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs03, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs00_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs03(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs03_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
constexpr uint64_t LOWEST_WL = 4;
constexpr uint64_t WL_COUNT = 3;
// 4 5 6
constexpr uint8_t crc_wr_latency_map[WL_COUNT] = { 1, 2, 3 };
fapi2::buffer<uint8_t> l_crc_wr_latency_buffer;
FAPI_ASSERT((i_data.iv_crc_wr_latency >= LOWEST_WL) && (i_data.iv_crc_wr_latency < (LOWEST_WL + WL_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(3)
.set_PARAMETER(WRITE_CMD_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_crc_wr_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for Write CMD Latency: %d (%s)", i_data.iv_crc_wr_latency, mss::c_str(i_target));
l_crc_wr_latency_buffer = crc_wr_latency_map[i_data.iv_crc_wr_latency - LOWEST_WL];
mss::swizzle<A0, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_mpr_mode), io_inst.arr0);
io_inst.arr0.writeBit<A2>(i_data.iv_mpr_page);
io_inst.arr0.writeBit<A3>(i_data.iv_geardown);
io_inst.arr0.writeBit<A4>(i_data.iv_pda);
io_inst.arr0.writeBit<A5>(i_data.iv_temp_readout);
mss::swizzle<A6 , 3, 7>(fapi2::buffer<uint8_t>(i_data.iv_fine_refresh), io_inst.arr0);
mss::swizzle<A9 , 2, 7>(l_crc_wr_latency_buffer, io_inst.arr0);
mss::swizzle<A11, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_read_format), io_inst.arr0);
FAPI_INF("MR3: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS3,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return void
///
fapi2::ReturnCode mrs03_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
fapi2::buffer<uint8_t> l_mpr_mode;
fapi2::buffer<uint8_t> l_fine_refresh;
fapi2::buffer<uint8_t> l_crc_wr_latency_buffer;
fapi2::buffer<uint8_t> l_read_format;
uint8_t l_mpr_page = i_inst.arr0.getBit<A2>();
uint8_t l_geardown = i_inst.arr0.getBit<A3>();
uint8_t l_pda = i_inst.arr0.getBit<A4>();
uint8_t l_temp_readout = i_inst.arr0.getBit<A5>();
mss::swizzle<6, 2, A1>(i_inst.arr0, l_mpr_mode);
mss::swizzle<5, 3, A7>(i_inst.arr0, l_fine_refresh);
mss::swizzle<6, 2, A10>(i_inst.arr0, l_crc_wr_latency_buffer);
mss::swizzle<6, 2, A12>(i_inst.arr0, l_read_format);
FAPI_INF("MR3 rank %d decode: MPR_MODE: 0x%x, MPR_PAGE: 0x%x, GD: 0x%x, PDA: 0x%x, "
"TEMP: 0x%x FR: 0x%x, CRC_WL: 0x%x, RF: 0x%x", i_rank,
uint8_t(l_mpr_mode), l_mpr_page, l_geardown, l_pda, uint8_t(l_temp_readout),
uint8_t(l_fine_refresh), uint8_t(l_crc_wr_latency_buffer), uint8_t(l_read_format));
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs03_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs03_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs03;
fapi2::ReturnCode (*mrs03_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs03_decode;
} // ns ddr4
} // ns mss
Updated MR3 attributes in effective config
Removed the following attributes:
mpr page
mpr mode
per-dram addressability
temperature sensor readout
mpr read format
Updated the following attribute in effective config:
wr cmd latency
Change-Id: I8d417700ed1d89e0205de61051a42f6e435da082
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/28335
Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com>
Reviewed-by: Brian R. Silver <af0eed78d989d9597decc8b92fa6db01ef8b58e0@us.ibm.com>
Reviewed-by: JACOB L. HARVEY <3228c361e36065d481020c968085ab1d20e47d22@us.ibm.com>
Tested-by: Hostboot CI <52521565bd8ea18a2b112942dce4f4220a97c2c8@us.ibm.com>
Reviewed-by: Jennifer A. Stofer <ab93eca12e43608f33daa16a67357cd7b7e867ab@us.ibm.com>
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs03.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs03.C
/// @brief Run and manage the DDR4 DDR4 loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs03_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
mrs03_data::mrs03_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_mpr_mode(fapi2::ENUM_ATTR_EFF_MPR_MODE_DISABLE),
iv_mpr_page(fapi2::ENUM_ATTR_EFF_MPR_PAGE_PG0),
iv_geardown(0),
iv_pda(fapi2::ENUM_ATTR_EFF_PER_DRAM_ACCESS_DISABLE),
iv_crc_wr_latency(0),
iv_temp_readout(fapi2::ENUM_ATTR_EFF_TEMP_READOUT_DISABLE),
iv_fine_refresh(0),
iv_read_format(fapi2::ENUM_ATTR_EFF_MPR_RD_FORMAT_SERIAL)
{
FAPI_TRY( mss::eff_mpr_mode(i_target, iv_mpr_mode) );
FAPI_TRY( mss::eff_mpr_page(i_target, iv_mpr_page) );
FAPI_TRY( mss::eff_geardown_mode(i_target, iv_geardown) );
FAPI_TRY( mss::eff_per_dram_access(i_target, iv_pda) );
FAPI_TRY( mss::eff_temp_readout(i_target, iv_temp_readout) );
FAPI_TRY( mss::mrw_fine_refresh_mode(iv_fine_refresh) );
FAPI_TRY( mss::eff_crc_wr_latency(i_target, iv_crc_wr_latency) );
FAPI_TRY( mss::eff_mpr_rd_format(i_target, iv_read_format) );
FAPI_INF("MR3 attributes: MPR_MODE: 0x%x, MPR_PAGE: 0x%x, GD: 0x%x, PDA: 0x%x, "
"TEMP: 0x%x FR: 0x%x, CRC_WL: 0x%x, RF: 0x%x",
iv_mpr_mode, iv_mpr_page, iv_geardown, iv_pda, iv_temp_readout,
iv_fine_refresh, iv_crc_wr_latency, iv_read_format);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs03
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs03(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs03_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS03 data from attributes");
FAPI_TRY( mrs03(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs03, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs00_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs03(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs03_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
constexpr uint64_t LOWEST_WL = 4;
constexpr uint64_t WL_COUNT = 3;
// 4 5 6
constexpr uint8_t crc_wr_latency_map[WL_COUNT] = { 0, 1, 2 };
fapi2::buffer<uint8_t> l_crc_wr_latency_buffer;
FAPI_ASSERT((i_data.iv_crc_wr_latency >= LOWEST_WL) && (i_data.iv_crc_wr_latency < (LOWEST_WL + WL_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(3)
.set_PARAMETER(WRITE_CMD_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_crc_wr_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for Write CMD Latency: %d (%s)", i_data.iv_crc_wr_latency, mss::c_str(i_target));
l_crc_wr_latency_buffer = crc_wr_latency_map[i_data.iv_crc_wr_latency - LOWEST_WL];
mss::swizzle<A0, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_mpr_mode), io_inst.arr0);
io_inst.arr0.writeBit<A2>(i_data.iv_mpr_page);
io_inst.arr0.writeBit<A3>(i_data.iv_geardown);
io_inst.arr0.writeBit<A4>(i_data.iv_pda);
io_inst.arr0.writeBit<A5>(i_data.iv_temp_readout);
mss::swizzle<A6 , 3, 7>(fapi2::buffer<uint8_t>(i_data.iv_fine_refresh), io_inst.arr0);
mss::swizzle<A9 , 2, 7>(l_crc_wr_latency_buffer, io_inst.arr0);
mss::swizzle<A11, 2, 7>(fapi2::buffer<uint8_t>(i_data.iv_read_format), io_inst.arr0);
FAPI_INF("MR3: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS3,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return void
///
fapi2::ReturnCode mrs03_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
fapi2::buffer<uint8_t> l_mpr_mode;
fapi2::buffer<uint8_t> l_fine_refresh;
fapi2::buffer<uint8_t> l_crc_wr_latency_buffer;
fapi2::buffer<uint8_t> l_read_format;
uint8_t l_mpr_page = i_inst.arr0.getBit<A2>();
uint8_t l_geardown = i_inst.arr0.getBit<A3>();
uint8_t l_pda = i_inst.arr0.getBit<A4>();
uint8_t l_temp_readout = i_inst.arr0.getBit<A5>();
mss::swizzle<6, 2, A1>(i_inst.arr0, l_mpr_mode);
mss::swizzle<5, 3, A7>(i_inst.arr0, l_fine_refresh);
mss::swizzle<6, 2, A10>(i_inst.arr0, l_crc_wr_latency_buffer);
mss::swizzle<6, 2, A12>(i_inst.arr0, l_read_format);
FAPI_INF("MR3 rank %d decode: MPR_MODE: 0x%x, MPR_PAGE: 0x%x, GD: 0x%x, PDA: 0x%x, "
"TEMP: 0x%x FR: 0x%x, CRC_WL: 0x%x, RF: 0x%x", i_rank,
uint8_t(l_mpr_mode), l_mpr_page, l_geardown, l_pda, uint8_t(l_temp_readout),
uint8_t(l_fine_refresh), uint8_t(l_crc_wr_latency_buffer), uint8_t(l_read_format));
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs03_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs03_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs03;
fapi2::ReturnCode (*mrs03_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs03_decode;
} // ns ddr4
} // ns mss
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/shared/mss_generic_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_consts.H
/// @brief Common constants to be shared
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CONSTS_H_
#define _MSS_GENERIC_CONSTS_H_
#include <cstdint>
namespace mss
{
///
/// @brief Common constants
///
enum common_consts
{
DEFAULT_POLL_LIMIT = 50, ///< the number of poll attempts in the event we can't calculate another
MEMCMP_EQUAL = 0, ///< Equal comparison value for memcmp
BAD_BITS_RANKS = 4, ///< Bad bit attribute's number of ranks
BAD_DQ_BYTE_COUNT = 10, ///< Bad bit attribute's number of byte
ATTR_RANK0 = 0, ///< Attribute index for rank0
ATTR_RANK1 = 1, ///< Attribute index for rank1
ATTR_RANK2 = 2, ///< Attribute index for rank2
ATTR_RANK3 = 3, ///< Attribute index for rank3
};
///
/// @brief Common mcbist constants
///
enum mcbist_common_consts
{
CYCLES_PER_CMD = 4, ///< Best case cycles per MCBIST command
MAX_RANK_PER_DIMM = 4,
BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B
T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s
// Number of double words in...
NUM_DW_IN_128B = 16,
NUM_DW_IN_64B = 8,
BG_SCRUB_IN_HOURS = 12,
CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap
MAX_CMD_GAP = 4095, ///< Represents the maximum (non-multplied) time for MCBIST inter cmd gap
// MCBIST polling constant for actual HW
// The specific value here is not important, only that it is very large to avoid polling timeouts,
// but not to avoid any actual hardware timeouts
// Note: ~0 is not used as that would cause MCBIST to never timeout even if the hardware is in an infinite loop
// You can't get greater than ~0, so you'd never timeout
// TODO RTC:166340 - Clean up MCBIST polling
OVERLY_LARGE_NUMBER_OF_POLLS = 5000000000000,
};
///
/// @brief Common timings
///
enum common_timings
{
DELAY_1NS = 1,
DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode
DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode
DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode
DELAY_10US = 10000, ///< general purpose 1 usec delay for HW mode
DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode
DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode
};
///
/// @brief Common conversions
///
enum conversions
{
CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano
CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro
MHZ_TO_KHZ = 1000,
SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times
NIBBLES_PER_BYTE = 2,
BITS_PER_NIBBLE = 4,
BITS_PER_BYTE = 8,
// Used by exp_decoder.C for dA to cA
DECI_TO_CENTI = 10,
};
enum generic_sizes
{
NUM_MAX_FREQS = 5, ///< Used for ATTR_MAX_ALLOWED_DIMM_FREQ
MARK_STORE_COUNT = 8, ///< Elements in a VPD mark/store array
};
///
/// @brief FFDC generic codes
///
enum generic_ffdc_codes
{
// Starting at 0x1%%% to avoid
// any collisions with values
// from controller specific ffdc codes
SET_ATTR_DIMM_TYPE = 0x1000,
SET_ATTR_DRAM_GEN = 0x1001,
SET_ATTR_HYBRID = 0x1002,
SET_ATTR_HYBRID_MEDIA = 0x1003,
SET_ATTR_MASTER_RANKS = 0x1004,
SET_ATTR_RANKS_CONFIGED = 0x1005,
GET_FIELD = 0x1006,
READ_SPD_FIELD = 0x1007,
BASE_CFG_PARAM_SELECT = 0x1008,
DIMM_MODULE_PARAM_SELECT = 0x1009,
BASE_CFG_FACTORY = 0x100A,
DIMM_MODULE_FACTORY = 0x100B,
GET_TAAMIN = 0x100C,
GET_TCKMIN = 0x100D,
GET_TCKMAX = 0x100E,
GET_TIMEBASES_FTB = 0x100F,
GET_TIMEBASES_MTB = 0x1010,
GET_SUPPORTED_REV = 0x1011,
TRASMIN = 0x1012,
TRCMIN = 0x1013,
TRFC1MIN = 0x1014,
TRFC2MIN = 0x1015,
TRFC4MIN = 0x1016,
TFAWMIN = 0x1017,
TWTR_S_MIN = 0x1018,
TWRMIN = 0x1019,
TWTR_L_MIN = 0x101A,
DEVICE_TYPE = 0x101B,
BASE_MODULE_TYPE = 0x101C,
BAD_SPD_DATA = 0x101D,
SET_FIELD = 0x101E,
SELECT_SUPPORTED_FREQ = 0x101F,
FREQ_SCOREBOARD_REMOVE_FREQS_ABOVE_LIMIT = 0x1020,
FREQ_SCOREBOARD_REMOVE_FREQS_ABOVE_LIMIT_VECTOR = 0x1021,
FREQ_SCOREBOARD_REMOVE_FREQS_NOT_ON_LIST = 0x1022,
FREQ_SCOREBOARD_MAX_SUPPORTED_FREQ = 0x1023,
FREQ_SCOREBOARD_SUPPORTED_FREQS = 0x1024,
LIMIT_FREQ_BY_VPD = 0x1025,
SET_DIMM_TYPE = 0x1026,
SET_DRAM_GEN = 0x1027,
SET_HYBRID = 0x1028,
SET_HYBRID_MEDIA = 0x1029,
SET_MRANKS = 0x102A,
SET_HOST_TO_DDR_SPEED_RATIO = 0x102B,
SET_ATTR_HOST_TO_DDR_SPEED_RATIO = 0x102C,
SET_DIMM_RANKS_CNFG = 0x1039,
DDIMM_RAWCARD_DECODE = 0x103a,
INIT_RANK_INFO = 0x103B,
BIAS_PMIC_FROM_SPD = 0x103C,
SET_DRAM_WIDTH = 0x1040,
SET_SI_VREF_DRAM_WR = 0x1041,
SET_SI_MC_RCV_IMP_DQ_DQS = 0x1042,
SET_SI_MC_DRV_IMP_DQ_DQS_PULL_UP = 0x1043,
SET_SI_MC_DRV_IMP_DQ_DQS_PULL_DOWN = 0x1044,
SET_SI_MC_DRV_SLEW_RATE_DQ_DQS = 0x1045,
SET_SI_MC_DRV_IMP_CMD_ADDR = 0x10466,
SET_SI_MC_DRV_SLEW_RATE_CMD_ADDR = 0x1047,
SET_SI_MC_DRV_IMP_CLK = 0x1048,
SET_SI_MC_DRV_SLEW_RATE_CLK = 0x1049,
SET_SI_MC_RCV_IMP_ALERT_N = 0x1050,
SET_SI_DRAM_RTT_NOM = 0x1051,
SET_SI_DRAM_RTT_WR = 0x1052,
SET_SI_DRAM_RTT_PARK = 0x1053,
SET_SI_DRAM_PREAMBLE = 0x1054,
SET_SI_MC_DRV_EQ_DQ_DQS = 0x1055,
SET_SI_DRAM_DRV_IMP_DQ_DQS = 0x1056,
SET_SI_VREF_DQ_TRAIN_RANGE = 0x1057,
SET_SI_VREF_DQ_TRAIN_VALUE = 0x1058,
SET_SI_ODT_WR = 0x1059,
SET_SI_ODT_RD = 0x1060,
SET_SI_GEARDOWN_MODE = 0x1061,
PRE_DATA_ENGINE_CTOR = 0x1062,
SET_DRAM_GEN_METADATA = 0x1063,
SET_DIMM_TYPE_METADATA = 0x1064,
SET_DIMM_POS_METADATA = 0x1065,
SET_LOGICAL_RANKS = 0x1066,
SET_PRIM_STACK_TYPE = 0x1067,
SET_DIMM_SIZE = 0x1068,
SET_PRIM_BUS_WIDTH = 0x1069,
SET_PRIM_DIE_COUNT = 0x1070,
SET_DRAM_DENSITY = 0x1071,
// Power thermal functions
POWER_LIMIT = 0x1072,
SLOPE = 1073,
INTERCEPT = 1074,
};
///
/// @brief Supported proc types
/// @note Processor types by system generation and sub numbering
///
enum class proc_type
{
NIMBUS = 0x0900,
CUMULUS = 0x0901,
AXONE = 0x0902,
};
///
/// @brief Supported memory controller types
///
enum class mc_type
{
NIMBUS = 0,
CENTAUR = 1,
EXPLORER = 2,
};
///
/// @brief JEDEC supported DDR speeds
/// @note Includes DDR4 and DDR5 only
///
enum ddr_dimm_speeds
{
// Supported frequencies
DIMM_SPEED_1600 = 1600,
DIMM_SPEED_1866 = 1866,
DIMM_SPEED_2133 = 2133,
DIMM_SPEED_2400 = 2400,
DIMM_SPEED_2666 = 2666,
DIMM_SPEED_2933 = 2933,
DIMM_SPEED_3200 = 3200,
DIMM_SPEED_3600 = 3600,
DIMM_SPEED_4000 = 4000,
DIMM_SPEED_4400 = 4400,
DIMM_SPEED_4800 = 4800,
// Max/Mins for specific generations here
DDR4_MIN_SPEED = 1600,
DDR4_MAX_SPEED = 3200,
DDR5_MIN_SPEED = 3200,
DDR5_MAX_SPEED = 4800,
};
enum states
{
LOW = 0,
HIGH = 1,
START = 1,
STOP = 0,
START_N = 0,
STOP_N = 1,
ON = 1,
OFF = 0,
ON_N = 0,
OFF_N = 1,
YES = 1,
NO = 0,
YES_N = 0,
NO_N = 1,
// Uses "_" in the name for INVALID as INVALID is defined as a macro in the
// FSP code. If we just use INVALID as an enum name, then the preprocessor
// compile phase changes it to be the macro.
_INVALID_ = 0xFF,
NO_CHIP_SELECT_ACTIVE = 0xFF,
};
enum port_select
{
// Port selects for MCBIST and CCS
// Select for 1 port
PORT0 = 0b1000,
PORT1 = 0b0100,
PORT2 = 0b0010,
PORT3 = 0b0001,
// Selects for 2 port combinations
PORT01 = PORT0 | PORT1,
PORT02 = PORT0 | PORT2,
PORT03 = PORT0 | PORT3,
PORT12 = PORT1 | PORT2,
PORT13 = PORT1 | PORT3,
PORT23 = PORT2 | PORT3,
// Selects for 3 port combinations
PORT012 = PORT0 | PORT1 | PORT2,
PORT013 = PORT0 | PORT1 | PORT3,
PORT023 = PORT0 | PORT2 | PORT3,
PORT123 = PORT1 | PORT2 | PORT3,
// Select all
PORT0123 = PORT0 | PORT1 | PORT2 | PORT3,
// Maybe a better name for disabling all
PORT_NONE = 0b0000,
};
enum dimm_select
{
// Dimm selects for MCBIST and CCS
// Select for 1 dimm
DIMM0 = 0b10,
DIMM1 = 0b01,
// Selects for 2 dimm combinations
DIMM01 = DIMM0 | DIMM1,
// Maybe a better name for disabling all
DIMM_NONE = 0b00,
};
namespace mcbist
{
enum broadcast_timebase
{
// Number of 1024 2:1 cycle timebases to wait starting MCBIST
// for SRQs to get synced for broadcast mode
TB_COUNT_2 = 0b0000001,
TB_COUNT_4 = 0b0000011,
TB_COUNT_8 = 0b0000111,
TB_COUNT_16 = 0b0001111,
TB_COUNT_32 = 0b0011111,
TB_COUNT_64 = 0b0111111,
TB_COUNT_128 = 0b1111111,
};
enum rmw_address
{
// 32B block addresses into the maint portion of the rmw buffer
DW0 = 0b111110000,
DW1 = 0b111110001,
DW2 = 0b111110010,
DW3 = 0b111110011,
DW4 = 0b111110100,
DW5 = 0b111110101,
DW6 = 0b111110110,
DW7 = 0b111110111,
DW8 = 0b111111000,
DW9 = 0b111111001,
DWA = 0b111111010,
DWB = 0b111111011,
DWC = 0b111111100,
DWD = 0b111111101,
DWE = 0b111111110,
DWF = 0b111111111,
};
enum data_rotate_mode
{
// MCBIST data rotate modes refer to register MCBDRCR bits 0:3
ROTATE_0_BITS = 0b0000,
ROTATE_1_BITS = 0b0001,
ROTATE_2_BITS = 0b0010,
ROTATE_3_BITS = 0b0011,
ROTATE_4_BITS = 0b0100,
ROTATE_5_BITS = 0b0101,
ROTATE_6_BITS = 0b0110,
ROTATE_7_BITS = 0b0111,
ROTATE_8_BITS = 0b1000,
ROTATE_9_BITS = 0b1001,
ROTATE_10_BITS = 0b1010,
ROTATE_11_BITS = 0b1011,
ROTATE_12_BITS = 0b1100,
ROTATE_13_BITS = 0b1101,
ROTATE_14_BITS = 0b1110,
ROTATE_15_BITS = 0b1111,
};
enum data_seed_mode
{
// MCBIST data seed modes refer to register MCBDRCR bits 21:22
ALL_UNIQUE = 0b00,
REPEAT_SEED_0 = 0b01,
REPEAT_SEED_1 = 0b10,
REPEAT_SEED_2 = 0b11,
};
enum data_mode
{
// MCBIST test data modes
FIXED_DATA_MODE = 0b000,
RAND_FWD_MODE = 0b001,
RAND_REV_MODE = 0b010,
RAND_FWD_MAINT = 0b011,
RAND_REV_MAINT = 0b100,
DATA_EQ_ADDR = 0b101,
ROTATE_LEFT_MODE = 0b110,
ROTATE_RIGHT_MODE = 0b111,
};
// 0:3 Operation Type
enum op_type
{
WRITE = 0b0000, // fast, with no concurrent traffic
READ = 0b0001, // fast, with no concurrent traffic
READ_WRITE = 0b0010,
WRITE_READ = 0b0011,
READ_WRITE_READ = 0b0100,
READ_WRITE_WRITE = 0b0101,
RAND_SEQ = 0b0110,
READ_READ_WRITE = 0b1000,
SCRUB_RRWR = 0b1001,
STEER_RW = 0b1010,
ALTER = 0b1011, // (W)
DISPLAY = 0b1100, // (R, slow)
CCS_EXECUTE = 0b1111,
// if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to)
// Refresh only cmd if bits 9:11 (Data Mode bits) /= 000
GOTO_SUBTEST_N = 0b0111,
};
enum test_type
{
USER_MODE = 0,
CENSHMOO = 1,
SUREFAIL = 2,
MEMWRITE = 3,
MEMREAD = 4,
CBR_REFRESH = 5,
MCBIST_SHORT = 6,
SHORT_SEQ = 7,
DELTA_I = 8,
DELTA_I_LOOP = 9,
SHORT_RAND = 10,
LONG1 = 11,
BUS_TAT = 12,
SIMPLE_FIX = 13,
SIMPLE_RAND = 14,
SIMPLE_RAND_2W = 15,
SIMPLE_RAND_FIXD = 16,
SIMPLE_RA_RD_WR = 17,
SIMPLE_RA_RD_R = 18,
SIMPLE_RA_FD_R = 19,
SIMPLE_RA_FD_R_INF = 20,
SIMPLE_SA_FD_R = 21,
SIMPLE_RA_FD_W = 22,
INFINITE = 23,
WR_ONLY = 24,
W_ONLY = 25,
R_ONLY = 26,
W_ONLY_RAND = 27,
R_ONLY_RAND = 28,
R_ONLY_MULTI = 29,
SHORT = 30,
SIMPLE_RAND_BARI = 31,
W_R_INFINITE = 32,
W_R_RAND_INFINITE = 33,
R_INFINITE1 = 34,
R_INFINITE_RF = 35,
MARCH = 36,
SIMPLE_FIX_RF = 37,
SHMOO_STRESS = 38,
SIMPLE_RAND_RA = 39,
SIMPLE_FIX_RA = 40,
SIMPLE_FIX_RF_RA = 41,
TEST_RR = 42,
TEST_RF = 43,
W_ONLY_INFINITE_RAND = 44,
MCB_2D_CUP_SEQ = 45,
MCB_2D_CUP_RAND = 46,
SHMOO_STRESS_INFINITE = 47,
HYNIX_1_COL = 48,
RMWFIX = 49,
RMWFIX_I = 50,
W_INFINITE = 51,
R_INFINITE = 52,
};
} // namespace mcbist
///
/// @brief Supported DIMM speed equality deliberations
///
enum class speed_equality : uint8_t
{
NOT_EQUAL_DIMM_SPEEDS = 0, ///< denotes all DIMMs don't have the same speed
EQUAL_DIMM_SPEEDS = 1, ///< denotes all DIMMs have the same speed
};
namespace spd
{
///
/// @brief SPD revisions - not tied any particular module
///
enum rev : uint8_t
{
V0_0 = 0x00, ///< represents Rev 0.0
V1_0 = 0x10, ///< represents Rev 1.0
V1_1 = 0x11, ///< represents Rev 1.1
V1_2 = 0x12, ///< represents Rev 1.2
// These module revisions can vary independently
// so we track the largest decoded revision here.
GEN_SEC_MAX = V1_1,
RDIMM_MAX = V1_1,
LRDIMM_MAX = V1_2,
DDIMM_MAX = V0_0,
};
///
/// @brief SPD module parameters
/// @note helps distinguish SPD decoder sections
///
enum parameters
{
UNINITIALIZED,
BASE_CNFG,
RDIMM_MODULE,
LRDIMM_MODULE,
NVDIMM_MODULE,
DDIMM_MODULE,
};
///
/// @brief DRAM generation selector
/// @note values set to SPD settings
///
enum device_type
{
DDR4 = 0x0c,
};
///
/// @brief DIMM type selector
/// @note values set to SPD settings
///
enum dimm_type
{
RDIMM = 0b0001,
LRDIMM = 0b0100,
DDIMM = 0b1010,
SORDIMM = 0b1000,
MINIRDIMM = 0b0101,
};
enum guard_band : uint16_t
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR4_CORRECTION_FACTOR = 974, ///< DDR4 correction factor
};
}// spd
namespace efd
{
///
/// @brief EFD Module identifier
/// @note helps distinguish the EFD identifier
///
enum id
{
DDR4_CUSTOM_MICROCHIP = 0x11,
};
}//efd
///
/// @brief DIMM nibble mask
/// @note nibble0: 4 high bits, nibble1: 4 low bits
///
enum nibble_mask
{
MASK_NIBBLE0 = 0xf0,
MASK_NIBBLE1 = 0x0f,
};
///
/// @brief throttle_type used to set bulk_pwr_throttls to run POWER or THERMAL throttling
/// @note OCC will be using the POWER option
///
enum class throttle_type
{
POWER = 0,
THERMAL = 1,
};
///
/// @brief Trait classes for mc_type
/// @tparam MC the mc_type
///
template< mc_type MC >
class mcTypeTraits;
///
/// @brief Trait classes for mc_type - NIMBUS specialization
///
template< >
struct mcTypeTraits<mc_type::NIMBUS>
{
enum
{
MC_PER_MODULE = 2,
MCS_PER_MC = 2,
MCS_PER_PROC = MC_PER_MODULE * MCS_PER_MC,
PORTS_PER_MCBIST = 4,
PORTS_PER_MCS = 2,
DIMMS_PER_PORT = 2,
DIMMS_PER_MCS = PORTS_PER_MCS * DIMMS_PER_PORT,
DIMMS_PER_MCBIST = PORTS_PER_MCBIST * DIMMS_PER_PORT,
};
};
///
/// @brief Trait classes for mc_type - EXPLORER specialization
///
template< >
struct mcTypeTraits<mc_type::EXPLORER>
{
enum
{
MC_PER_PROC = 2,
MI_PER_MC = 2,
MCC_PER_MI = 2,
OMI_PER_MCC = 2,
OCMB_PER_OMI = 1,
PORTS_PER_OCMB = 1,
DIMMS_PER_PORT = 2,
};
};
}// mss
#endif
Add snapshot of ocmb/explorer for master-p10 branch
Had to fix mss incorrect use of p9 attribute enums
used in generic. Made a list of fixes to fix in
ekb/master.
Sets #5-7: Fix Jenkins build failure.
Change-Id: Ie76ab15d9ba8c7108249a746ed39526c155dcbce
Original-Change-Id: I556a2e117d4dab2276ecd122650d253782c52e52
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/78083
Tested-by: Jenkins Server <8e3f934e4c44875bc48d33da3ea13d93ba9a233f@us.ibm.com>
Reviewed-by: Louis Stermole <a2bef96d502debd02962600aef4d81d949c35039@us.ibm.com>
Reviewed-by: STEPHEN GLANCY <7301c4b00f53e5772c2576cd0c5f485155c2ece1@us.ibm.com>
Tested-by: PPE CI <dc75934ba5befb9221434e67a247b93aec46b36b@us.ibm.com>
Reviewed-by: Joseph J. McGill <4a85c6614f9f065f63d8fd57cde15e48af07ea2a@us.ibm.com>
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/shared/mss_generic_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_consts.H
/// @brief Common constants to be shared
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CONSTS_H_
#define _MSS_GENERIC_CONSTS_H_
#include <cstdint>
namespace mss
{
///
/// @brief Common constants
///
enum common_consts
{
DEFAULT_POLL_LIMIT = 50, ///< the number of poll attempts in the event we can't calculate another
MEMCMP_EQUAL = 0, ///< Equal comparison value for memcmp
BAD_BITS_RANKS = 4, ///< Bad bit attribute's number of ranks
BAD_DQ_BYTE_COUNT = 10, ///< Bad bit attribute's number of byte
ATTR_RANK0 = 0, ///< Attribute index for rank0
ATTR_RANK1 = 1, ///< Attribute index for rank1
ATTR_RANK2 = 2, ///< Attribute index for rank2
ATTR_RANK3 = 3, ///< Attribute index for rank3
};
///
/// @brief Common mcbist constants
///
enum mcbist_common_consts
{
CYCLES_PER_CMD = 4, ///< Best case cycles per MCBIST command
MAX_RANK_PER_DIMM = 4,
BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B
T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s
// Number of double words in...
NUM_DW_IN_128B = 16,
NUM_DW_IN_64B = 8,
BG_SCRUB_IN_HOURS = 12,
CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap
MAX_CMD_GAP = 4095, ///< Represents the maximum (non-multplied) time for MCBIST inter cmd gap
// MCBIST polling constant for actual HW
// The specific value here is not important, only that it is very large to avoid polling timeouts,
// but not to avoid any actual hardware timeouts
// Note: ~0 is not used as that would cause MCBIST to never timeout even if the hardware is in an infinite loop
// You can't get greater than ~0, so you'd never timeout
// TODO RTC:166340 - Clean up MCBIST polling
OVERLY_LARGE_NUMBER_OF_POLLS = 5000000000000,
};
///
/// @brief Common timings
///
enum common_timings
{
DELAY_1NS = 1,
DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode
DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode
DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode
DELAY_10US = 10000, ///< general purpose 1 usec delay for HW mode
DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode
DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode
};
///
/// @brief Common conversions
///
enum conversions
{
CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano
CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro
MHZ_TO_KHZ = 1000,
SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times
NIBBLES_PER_BYTE = 2,
BITS_PER_NIBBLE = 4,
BITS_PER_BYTE = 8,
// Used by exp_decoder.C for dA to cA
DECI_TO_CENTI = 10,
};
enum generic_sizes
{
NUM_MAX_FREQS = 5, ///< Used for ATTR_MAX_ALLOWED_DIMM_FREQ
MARK_STORE_COUNT = 8, ///< Elements in a VPD mark/store array
};
///
/// @brief FFDC generic codes
///
enum generic_ffdc_codes
{
// Starting at 0x1%%% to avoid
// any collisions with values
// from controller specific ffdc codes
SET_ATTR_DIMM_TYPE = 0x1000,
SET_ATTR_DRAM_GEN = 0x1001,
SET_ATTR_HYBRID = 0x1002,
SET_ATTR_HYBRID_MEDIA = 0x1003,
SET_ATTR_MASTER_RANKS = 0x1004,
SET_ATTR_RANKS_CONFIGED = 0x1005,
GET_FIELD = 0x1006,
READ_SPD_FIELD = 0x1007,
BASE_CFG_PARAM_SELECT = 0x1008,
DIMM_MODULE_PARAM_SELECT = 0x1009,
BASE_CFG_FACTORY = 0x100A,
DIMM_MODULE_FACTORY = 0x100B,
GET_TAAMIN = 0x100C,
GET_TCKMIN = 0x100D,
GET_TCKMAX = 0x100E,
GET_TIMEBASES_FTB = 0x100F,
GET_TIMEBASES_MTB = 0x1010,
GET_SUPPORTED_REV = 0x1011,
TRASMIN = 0x1012,
TRCMIN = 0x1013,
TRFC1MIN = 0x1014,
TRFC2MIN = 0x1015,
TRFC4MIN = 0x1016,
TFAWMIN = 0x1017,
TWTR_S_MIN = 0x1018,
TWRMIN = 0x1019,
TWTR_L_MIN = 0x101A,
DEVICE_TYPE = 0x101B,
BASE_MODULE_TYPE = 0x101C,
BAD_SPD_DATA = 0x101D,
SET_FIELD = 0x101E,
SELECT_SUPPORTED_FREQ = 0x101F,
FREQ_SCOREBOARD_REMOVE_FREQS_ABOVE_LIMIT = 0x1020,
FREQ_SCOREBOARD_REMOVE_FREQS_ABOVE_LIMIT_VECTOR = 0x1021,
FREQ_SCOREBOARD_REMOVE_FREQS_NOT_ON_LIST = 0x1022,
FREQ_SCOREBOARD_MAX_SUPPORTED_FREQ = 0x1023,
FREQ_SCOREBOARD_SUPPORTED_FREQS = 0x1024,
LIMIT_FREQ_BY_VPD = 0x1025,
SET_DIMM_TYPE = 0x1026,
SET_DRAM_GEN = 0x1027,
SET_HYBRID = 0x1028,
SET_HYBRID_MEDIA = 0x1029,
SET_MRANKS = 0x102A,
SET_HOST_TO_DDR_SPEED_RATIO = 0x102B,
SET_ATTR_HOST_TO_DDR_SPEED_RATIO = 0x102C,
CCS_INST_CONFIGURE_RANK = 0x102D,
SET_DIMM_RANKS_CNFG = 0x1039,
DDIMM_RAWCARD_DECODE = 0x103a,
INIT_RANK_INFO = 0x103B,
BIAS_PMIC_FROM_SPD = 0x103C,
SET_DRAM_WIDTH = 0x1040,
SET_SI_VREF_DRAM_WR = 0x1041,
SET_SI_MC_RCV_IMP_DQ_DQS = 0x1042,
SET_SI_MC_DRV_IMP_DQ_DQS_PULL_UP = 0x1043,
SET_SI_MC_DRV_IMP_DQ_DQS_PULL_DOWN = 0x1044,
SET_SI_MC_DRV_SLEW_RATE_DQ_DQS = 0x1045,
SET_SI_MC_DRV_IMP_CMD_ADDR = 0x10466,
SET_SI_MC_DRV_SLEW_RATE_CMD_ADDR = 0x1047,
SET_SI_MC_DRV_IMP_CLK = 0x1048,
SET_SI_MC_DRV_SLEW_RATE_CLK = 0x1049,
SET_SI_MC_RCV_IMP_ALERT_N = 0x1050,
SET_SI_DRAM_RTT_NOM = 0x1051,
SET_SI_DRAM_RTT_WR = 0x1052,
SET_SI_DRAM_RTT_PARK = 0x1053,
SET_SI_DRAM_PREAMBLE = 0x1054,
SET_SI_MC_DRV_EQ_DQ_DQS = 0x1055,
SET_SI_DRAM_DRV_IMP_DQ_DQS = 0x1056,
SET_SI_VREF_DQ_TRAIN_RANGE = 0x1057,
SET_SI_VREF_DQ_TRAIN_VALUE = 0x1058,
SET_SI_ODT_WR = 0x1059,
SET_SI_ODT_RD = 0x1060,
SET_SI_GEARDOWN_MODE = 0x1061,
PRE_DATA_ENGINE_CTOR = 0x1062,
SET_DRAM_GEN_METADATA = 0x1063,
SET_DIMM_TYPE_METADATA = 0x1064,
SET_DIMM_POS_METADATA = 0x1065,
SET_LOGICAL_RANKS = 0x1066,
SET_PRIM_STACK_TYPE = 0x1067,
SET_DIMM_SIZE = 0x1068,
SET_PRIM_BUS_WIDTH = 0x1069,
SET_PRIM_DIE_COUNT = 0x1070,
SET_DRAM_DENSITY = 0x1071,
SET_SI_RD_VREF_DQ = 0x1075,
SET_CAC_DELAY_A = 0x1076,
SET_CAC_DELAY_B = 0x1077,
EFD_CA_LATENCY_MODE = 0x1080,
EFD_CA_PL_MODE = 0x1081,
// Power thermal functions
POWER_LIMIT = 0x1072,
SLOPE = 0x1073,
INTERCEPT = 0x1074,
};
///
/// @brief Supported proc types
/// @note Processor types by system generation and sub numbering
///
enum class proc_type
{
NIMBUS = 0x0900,
CUMULUS = 0x0901,
AXONE = 0x0902,
};
///
/// @brief Supported memory controller types
///
enum class mc_type
{
NIMBUS = 0,
CENTAUR = 1,
EXPLORER = 2,
};
///
/// @brief JEDEC supported DDR speeds
/// @note Includes DDR4 and DDR5 only
///
enum ddr_dimm_speeds
{
// Supported frequencies
DIMM_SPEED_1600 = 1600,
DIMM_SPEED_1866 = 1866,
DIMM_SPEED_2133 = 2133,
DIMM_SPEED_2400 = 2400,
DIMM_SPEED_2666 = 2666,
DIMM_SPEED_2933 = 2933,
DIMM_SPEED_3200 = 3200,
DIMM_SPEED_3600 = 3600,
DIMM_SPEED_4000 = 4000,
DIMM_SPEED_4400 = 4400,
DIMM_SPEED_4800 = 4800,
// Max/Mins for specific generations here
DDR4_MIN_SPEED = 1600,
DDR4_MAX_SPEED = 3200,
DDR5_MIN_SPEED = 3200,
DDR5_MAX_SPEED = 4800,
};
enum states
{
LOW = 0,
HIGH = 1,
START = 1,
STOP = 0,
START_N = 0,
STOP_N = 1,
ON = 1,
OFF = 0,
ON_N = 0,
OFF_N = 1,
YES = 1,
NO = 0,
YES_N = 0,
NO_N = 1,
// Uses "_" in the name for INVALID as INVALID is defined as a macro in the
// FSP code. If we just use INVALID as an enum name, then the preprocessor
// compile phase changes it to be the macro.
_INVALID_ = 0xFF,
NO_CHIP_SELECT_ACTIVE = 0xFF,
};
enum port_select
{
// Port selects for MCBIST and CCS
// Select for 1 port
PORT0 = 0b1000,
PORT1 = 0b0100,
PORT2 = 0b0010,
PORT3 = 0b0001,
// Selects for 2 port combinations
PORT01 = PORT0 | PORT1,
PORT02 = PORT0 | PORT2,
PORT03 = PORT0 | PORT3,
PORT12 = PORT1 | PORT2,
PORT13 = PORT1 | PORT3,
PORT23 = PORT2 | PORT3,
// Selects for 3 port combinations
PORT012 = PORT0 | PORT1 | PORT2,
PORT013 = PORT0 | PORT1 | PORT3,
PORT023 = PORT0 | PORT2 | PORT3,
PORT123 = PORT1 | PORT2 | PORT3,
// Select all
PORT0123 = PORT0 | PORT1 | PORT2 | PORT3,
// Maybe a better name for disabling all
PORT_NONE = 0b0000,
};
enum dimm_select
{
// Dimm selects for MCBIST and CCS
// Select for 1 dimm
DIMM0 = 0b10,
DIMM1 = 0b01,
// Selects for 2 dimm combinations
DIMM01 = DIMM0 | DIMM1,
// Maybe a better name for disabling all
DIMM_NONE = 0b00,
};
namespace mcbist
{
enum broadcast_timebase
{
// Number of 1024 2:1 cycle timebases to wait starting MCBIST
// for SRQs to get synced for broadcast mode
TB_COUNT_2 = 0b0000001,
TB_COUNT_4 = 0b0000011,
TB_COUNT_8 = 0b0000111,
TB_COUNT_16 = 0b0001111,
TB_COUNT_32 = 0b0011111,
TB_COUNT_64 = 0b0111111,
TB_COUNT_128 = 0b1111111,
};
enum rmw_address
{
// 32B block addresses into the maint portion of the rmw buffer
DW0 = 0b111110000,
DW1 = 0b111110001,
DW2 = 0b111110010,
DW3 = 0b111110011,
DW4 = 0b111110100,
DW5 = 0b111110101,
DW6 = 0b111110110,
DW7 = 0b111110111,
DW8 = 0b111111000,
DW9 = 0b111111001,
DWA = 0b111111010,
DWB = 0b111111011,
DWC = 0b111111100,
DWD = 0b111111101,
DWE = 0b111111110,
DWF = 0b111111111,
};
enum data_rotate_mode
{
// MCBIST data rotate modes refer to register MCBDRCR bits 0:3
ROTATE_0_BITS = 0b0000,
ROTATE_1_BITS = 0b0001,
ROTATE_2_BITS = 0b0010,
ROTATE_3_BITS = 0b0011,
ROTATE_4_BITS = 0b0100,
ROTATE_5_BITS = 0b0101,
ROTATE_6_BITS = 0b0110,
ROTATE_7_BITS = 0b0111,
ROTATE_8_BITS = 0b1000,
ROTATE_9_BITS = 0b1001,
ROTATE_10_BITS = 0b1010,
ROTATE_11_BITS = 0b1011,
ROTATE_12_BITS = 0b1100,
ROTATE_13_BITS = 0b1101,
ROTATE_14_BITS = 0b1110,
ROTATE_15_BITS = 0b1111,
};
enum data_seed_mode
{
// MCBIST data seed modes refer to register MCBDRCR bits 21:22
ALL_UNIQUE = 0b00,
REPEAT_SEED_0 = 0b01,
REPEAT_SEED_1 = 0b10,
REPEAT_SEED_2 = 0b11,
};
enum data_mode
{
// MCBIST test data modes
FIXED_DATA_MODE = 0b000,
RAND_FWD_MODE = 0b001,
RAND_REV_MODE = 0b010,
RAND_FWD_MAINT = 0b011,
RAND_REV_MAINT = 0b100,
DATA_EQ_ADDR = 0b101,
ROTATE_LEFT_MODE = 0b110,
ROTATE_RIGHT_MODE = 0b111,
};
// 0:3 Operation Type
enum op_type
{
WRITE = 0b0000, // fast, with no concurrent traffic
READ = 0b0001, // fast, with no concurrent traffic
READ_WRITE = 0b0010,
WRITE_READ = 0b0011,
READ_WRITE_READ = 0b0100,
READ_WRITE_WRITE = 0b0101,
RAND_SEQ = 0b0110,
READ_READ_WRITE = 0b1000,
SCRUB_RRWR = 0b1001,
STEER_RW = 0b1010,
ALTER = 0b1011, // (W)
DISPLAY = 0b1100, // (R, slow)
CCS_EXECUTE = 0b1111,
// if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to)
// Refresh only cmd if bits 9:11 (Data Mode bits) /= 000
GOTO_SUBTEST_N = 0b0111,
};
enum test_type
{
USER_MODE = 0,
CENSHMOO = 1,
SUREFAIL = 2,
MEMWRITE = 3,
MEMREAD = 4,
CBR_REFRESH = 5,
MCBIST_SHORT = 6,
SHORT_SEQ = 7,
DELTA_I = 8,
DELTA_I_LOOP = 9,
SHORT_RAND = 10,
LONG1 = 11,
BUS_TAT = 12,
SIMPLE_FIX = 13,
SIMPLE_RAND = 14,
SIMPLE_RAND_2W = 15,
SIMPLE_RAND_FIXD = 16,
SIMPLE_RA_RD_WR = 17,
SIMPLE_RA_RD_R = 18,
SIMPLE_RA_FD_R = 19,
SIMPLE_RA_FD_R_INF = 20,
SIMPLE_SA_FD_R = 21,
SIMPLE_RA_FD_W = 22,
INFINITE = 23,
WR_ONLY = 24,
W_ONLY = 25,
R_ONLY = 26,
W_ONLY_RAND = 27,
R_ONLY_RAND = 28,
R_ONLY_MULTI = 29,
SHORT = 30,
SIMPLE_RAND_BARI = 31,
W_R_INFINITE = 32,
W_R_RAND_INFINITE = 33,
R_INFINITE1 = 34,
R_INFINITE_RF = 35,
MARCH = 36,
SIMPLE_FIX_RF = 37,
SHMOO_STRESS = 38,
SIMPLE_RAND_RA = 39,
SIMPLE_FIX_RA = 40,
SIMPLE_FIX_RF_RA = 41,
TEST_RR = 42,
TEST_RF = 43,
W_ONLY_INFINITE_RAND = 44,
MCB_2D_CUP_SEQ = 45,
MCB_2D_CUP_RAND = 46,
SHMOO_STRESS_INFINITE = 47,
HYNIX_1_COL = 48,
RMWFIX = 49,
RMWFIX_I = 50,
W_INFINITE = 51,
R_INFINITE = 52,
};
} // namespace mcbist
///
/// @brief Supported DIMM speed equality deliberations
///
enum class speed_equality : uint8_t
{
NOT_EQUAL_DIMM_SPEEDS = 0, ///< denotes all DIMMs don't have the same speed
EQUAL_DIMM_SPEEDS = 1, ///< denotes all DIMMs have the same speed
};
namespace spd
{
///
/// @brief SPD revisions - not tied any particular module
///
enum rev : uint8_t
{
V0_0 = 0x00, ///< represents Rev 0.0
V1_0 = 0x10, ///< represents Rev 1.0
V1_1 = 0x11, ///< represents Rev 1.1
V1_2 = 0x12, ///< represents Rev 1.2
// These module revisions can vary independently
// so we track the largest decoded revision here.
GEN_SEC_MAX = V1_1,
RDIMM_MAX = V1_1,
LRDIMM_MAX = V1_2,
DDIMM_MAX = V0_0,
};
///
/// @brief SPD module parameters
/// @note helps distinguish SPD decoder sections
///
enum parameters
{
UNINITIALIZED,
BASE_CNFG,
RDIMM_MODULE,
LRDIMM_MODULE,
NVDIMM_MODULE,
DDIMM_MODULE,
};
///
/// @brief DRAM generation selector
/// @note values set to SPD settings
///
enum device_type
{
DDR4 = 0x0c,
};
///
/// @brief DIMM type selector
/// @note values set to SPD settings
///
enum dimm_type
{
RDIMM = 0b0001,
LRDIMM = 0b0100,
DDIMM = 0b1010,
SORDIMM = 0b1000,
MINIRDIMM = 0b0101,
};
enum guard_band : uint16_t
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR4_CORRECTION_FACTOR = 974, ///< DDR4 correction factor
};
}// spd
namespace efd
{
///
/// @brief EFD Module identifier
/// @note helps distinguish the EFD identifier
///
enum id
{
DDR4_CUSTOM_MICROCHIP = 0x11,
};
}//efd
///
/// @brief DIMM nibble mask
/// @note nibble0: 4 high bits, nibble1: 4 low bits
///
enum nibble_mask
{
MASK_NIBBLE0 = 0xf0,
MASK_NIBBLE1 = 0x0f,
};
///
/// @brief throttle_type used to set bulk_pwr_throttls to run POWER or THERMAL throttling
/// @note OCC will be using the POWER option
///
enum class throttle_type
{
POWER = 0,
THERMAL = 1,
};
///
/// @brief Trait classes for mc_type
/// @tparam MC the mc_type
///
template< mc_type MC >
class mcTypeTraits;
///
/// @brief Trait classes for mc_type - NIMBUS specialization
///
template< >
struct mcTypeTraits<mc_type::NIMBUS>
{
enum
{
MC_PER_MODULE = 2,
MCS_PER_MC = 2,
MCS_PER_PROC = MC_PER_MODULE * MCS_PER_MC,
PORTS_PER_MCBIST = 4,
PORTS_PER_MCS = 2,
DIMMS_PER_PORT = 2,
DIMMS_PER_MCS = PORTS_PER_MCS * DIMMS_PER_PORT,
DIMMS_PER_MCBIST = PORTS_PER_MCBIST * DIMMS_PER_PORT,
};
};
///
/// @brief Trait classes for mc_type - EXPLORER specialization
///
template< >
struct mcTypeTraits<mc_type::EXPLORER>
{
enum
{
MC_PER_PROC = 2,
MI_PER_MC = 2,
MCC_PER_MI = 2,
OMI_PER_MCC = 2,
OCMB_PER_OMI = 1,
PORTS_PER_OCMB = 1,
DIMMS_PER_PORT = 2,
};
};
}// mss
#endif
|
// -------------------------------------------------------------------------
// @FileName NFCNet.cpp
// @Author LvSheng.Huang
// @Date 2013-12-15
// @Module NFIPacket
// @Desc : CNet
// -------------------------------------------------------------------------
#include "NFCNet.h"
#include "NFCPacket.h"
#include <WS2tcpip.h>
#include <winsock2.h>
#include <string.h>
#include "event2\bufferevent_struct.h"
void NFCNet::time_cb(evutil_socket_t fd, short _event, void *argc)
{
NetObject* pObject = (NetObject*)argc;
if (pObject)
{
pObject->GetNet()->HeartPack();
evtimer_add(pObject->GetNet()->ev, &(pObject->GetNet()->tv));
}
}
void NFCNet::conn_writecb(struct bufferevent *bev, void *user_data)
{
//ÿյϢʱ¼
// struct evbuffer *output = bufferevent_get_output(bev);
printf("Ϣ!!!\n");
}
void NFCNet::conn_eventcb(struct bufferevent *bev, short events, void *user_data)
{
NetObject* pObject = (NetObject*)user_data;
NFCNet* pNet = pObject->GetNet();
if(!pNet->mEventCB._Empty())
{
pNet->mEventCB(pObject->GetFd(), NF_NET_EVENT(events));
}
if (events & BEV_EVENT_EOF)
{
printf("%d Connection closed.\n", pObject->GetFd());
pNet->CloseSocket(pObject->GetFd());
if (pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_ERROR)
{
printf("%d Got an error on the connection: %d\n", pObject->GetFd(), errno);/*XXX win32*/
pNet->CloseSocket(pObject->GetFd());
if (!pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_TIMEOUT)
{
printf("%d read timeout: %d\n", pObject->GetFd(), errno);/*XXX win32*/
pNet->CloseSocket(pObject->GetFd());
if (pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_CONNECTED)
{
pNet->mbRuning = true;
printf("%d Connection successed\n", pObject->GetFd());/*XXX win32*/
}
}
void NFCNet::signal_cb(evutil_socket_t sig, short events, void *user_data)
{
NFCNet *base = (NFCNet *)user_data;
struct timeval delay = { 2, 0 };
printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
event_base_loopexit(base->base, &delay);
}
void NFCNet::listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data)
{
//
NFCNet* pNet = (NFCNet*)user_data;
bool bClose = pNet->CloseSocket(fd);
if (bClose)
{
//error
return;
}
if (pNet->mmObject.size() >= pNet->mnMaxConnect)
{
//ӦTܾ
return;
}
struct event_base *base = pNet->base;
//һsocketbufferevent
struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev)
{
//ӦTܾ
fprintf(stderr, "Error constructing bufferevent!");
//event_base_loopbreak(base);
return;
}
//һһӡΪ䴴һbufferevent--FDҪ
struct sockaddr_in* pSin = (sockaddr_in*)sa;
printf("µ¼ fd:%d IP: %s\n", fd, inet_ntoa(pSin->sin_addr));
NetObject* pObject = new NetObject(pNet, fd, *pSin, bev);
pObject->GetNet()->AddSocket(fd, pObject);
//Ϊbuffereventøֻص
bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, (void*)pObject);
//buffereventĶд
bufferevent_enable(bev, EV_READ|EV_WRITE);
//ģͻ¼
conn_eventcb(bev, BEV_EVENT_CONNECTED, (void*)pObject);
//////////////////////////////////////////////////////////////////////////
struct timeval tv;
/* öʱ120, Ϊ, 120ûյϢT */
tv.tv_sec = 120;
tv.tv_usec = 0;
bufferevent_set_timeouts(bev, &tv, NULL);
}
void NFCNet::conn_readcb(struct bufferevent *bev, void *user_data)
{
//ܵϢ
NetObject* pObject = (NetObject*)user_data;
if (!pObject)
{
return;
}
NFCNet* pNet = pObject->GetNet();
if (!pNet)
{
return;
}
struct evbuffer *input = bufferevent_get_input(bev);
if (!input)
{
return;
}
size_t len = evbuffer_get_length(input);
//ظͻ
// struct evbuffer *output = bufferevent_get_output(bev);
// evbuffer_add_buffer(output, input);
// SendMsg(1, strData,len, pObject->GetFd());
//////////////////////////////////////////////////////////////////////////
char* strData = new char[len];
//char strData[NF_MAX_SERVER_PACKET_SIZE] = {0};
if(evbuffer_remove(input, strData, len) > 0)
{
pObject->AddBuff(strData, len);
pNet->Dismantle(pObject);
}
delete[] strData;
}
//////////////////////////////////////////////////////////////////////////
bool NFCNet::Execute(const float fLasFrametime, const float fStartedTime)
{
//std::cout << "Running:" << mbRuning << std::endl;
if (mbRuning && base)
{
event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);
}
return mbRuning;
}
int NFCNet::Initialization( const char* strIP, const unsigned short nPort)
{
mstrIP = strIP;
mnPort = nPort;
return InitClientNet();
}
int NFCNet::Initialization( const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount)
{
mnMaxConnect = nMaxClient;
mnPort = nPort;
mnCpuCount = nCpuCount;
return InitServerNet();
}
bool NFCNet::Final()
{
if (mbServer)
{
CloseSocketAll();
}
if (listener)
{
evconnlistener_free(listener);
listener = NULL;
}
if (signal_event)
{
event_free(signal_event);
signal_event = NULL;
}
// bufferevent_socket_newòƹرsocketԼͷ
//if (base)
//{
// event_base_free(base);
// base = NULL;
//}
return true;
}
bool NFCNet::SendMsg( const NFIPacket& msg, const uint32_t nSockIndex, bool bBroadcast )
{
if (!mbRuning)
{
return false;
}
return SendMsg(msg.GetPacketData(), msg.GetPacketLen(), nSockIndex, bBroadcast );
}
bool NFCNet::SendMsg(const char* msg, const uint32_t nLen, const uint32_t nSockIndex, bool bBroadcast /*= false*/ )
{
std::map<int, NetObject*>::iterator it = mmObject.find(nSockIndex);
if (it != mmObject.end())
{
NetObject* pNetObject = (NetObject*)it->second;
if (pNetObject)
{
bufferevent* bev = pNetObject->GetBuffEvent();
if (NULL != bev && nLen > 0)
{
bufferevent_write(bev, msg, nLen);
return true;
}
}
}
return false;
}
bool NFCNet::CloseSocket( const uint32_t nSockIndex )
{
std::map<int, NetObject*>::iterator it = mmObject.find(nSockIndex);
if (it != mmObject.end())
{
NetObject* pObject = it->second;
struct bufferevent* bev = pObject->GetBuffEvent();
//bev->cbarg = NULL;
bufferevent_free(bev);
evutil_closesocket(nSockIndex);
mmObject.erase(it);
delete pObject;
pObject = NULL;
return true;
}
return false;
}
bool NFCNet::Dismantle(NetObject* pObject )
{
bool bRet = true;
NFCPacket packet(mnHeadLength);
int len = pObject->GetBuffLen();
if (len > packet.GetHeadSize())
{
int nUsedLen = packet.DeCode(pObject->GetBuff(), len);
if (nUsedLen > 0)
{
packet.SetFd(pObject->GetFd());
int nRet = 0;
if (!mRecvCB._Empty())
{
nRet = mRecvCB(packet);
bRet = bRet && nRet;
}
else
{
nRet = OnRecivePacket(pObject->GetFd(), packet.GetPacketData(), packet.GetPacketLen());
bRet = bRet && nRet;
}
//ӵ
pObject->RemoveBuff(0, nUsedLen);
//
bRet = bRet && Dismantle(pObject);
}
else if (0 == nUsedLen)
{
//Ȳ(ȴ´ν)
}
else
{
//ۼƴ̫--ʵո
pObject->IncreaseError();
}
if (pObject->GetErrorCount() > 5)
{
CloseSocket(pObject->GetFd());
}
}
return bRet;
}
bool NFCNet::AddSocket( const uint32_t nSockIndex, NetObject* pObject )
{
return mmObject.insert(std::map<int, NetObject*>::value_type(nSockIndex, pObject)).second;
}
int NFCNet::InitClientNet()
{
std::string strIP = mstrIP;
int nPort = mnPort;
struct sockaddr_in addr;
struct bufferevent *bev = NULL;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(nPort);
if (inet_pton(AF_INET, strIP.c_str(), &addr.sin_addr) <= 0)
{
printf("inet_pton");
return -1;
}
base = event_base_new();
if (base == NULL)
{
printf("event_base_new ");
return -1;
}
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (bev == NULL)
{
printf("bufferevent_socket_new ");
return -1;
}
int sockfd = bufferevent_socket_connect(bev, (struct sockaddr *)&addr, sizeof(addr));
if (0 != sockfd)
{
int nError = GetLastError();
printf("bufferevent_socket_connect error");
return -1;
}
NetObject* pObject = new NetObject(this, sockfd, addr, bev);
if (!AddSocket(sockfd, pObject))
{
assert(0);
return -1;
}
mbServer = false;
mbRuning = true;
bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, (void*)pObject);
bufferevent_enable(bev, EV_READ|EV_WRITE);
ev = evtimer_new(base, time_cb, (void*)pObject);
evutil_timerclear(&tv);
tv.tv_sec = 10; //
tv.tv_usec = 0;
evtimer_add(ev, &tv);
//event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);
return sockfd;
}
int NFCNet::InitServerNet()
{
int nMaxClient = mnMaxConnect;
int nCpuCount = mnCpuCount;
int nPort = mnPort;
struct sockaddr_in sin;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
//////////////////////////////////////////////////////////////////////////
struct event_config *cfg = event_config_new();
#if NF_PLATFORM == NF_PLATFORM_WIN
//event_config_avoid_method(cfg, "iocp");
//event_config_require_features(cfg, event_method_feature.EV_FEATURE_ET);//ʽ
evthread_use_windows_threads();
if(event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP) < 0)
{
//ʹIOCP
return -1;
}
if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
{
return -1;
}
base = event_base_new_with_config(cfg);
#else
//event_config_avoid_method(cfg, "epoll");
if(event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) < 0)
{
//ʹEPOLL
return -1;
}
if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
{
return -1;
}
base = event_base_new_with_config(cfg);//event_base_new()
#endif
event_config_free(cfg);
//////////////////////////////////////////////////////////////////////////
if (!base)
{
fprintf(stderr, "Could not initialize libevent!\n");
Final();
return -1;
}
//ʼʱ
//gettime(base, &base->event_tv);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(nPort);
printf("server started with %d\n", nPort);
listener = evconnlistener_new_bind(base, listener_cb, (void *)this,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr*)&sin,
sizeof(sin));
if (!listener)
{
fprintf(stderr, "Could not create a listener!\n");
Final();
return -1;
}
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)this);
if (!signal_event || event_add(signal_event, NULL)<0)
{
fprintf(stderr, "Could not create/add a signal event!\n");
Final();
return -1;
}
mbServer = true;
mbRuning = true;
return mnMaxConnect;
}
bool NFCNet::Reset()
{
if (!mbServer)
{
Final();
InitClientNet();
}
return true;
}
void NFCNet::HeartPack()
{
//NFCPacket msg(mnHeadLength);
//msg.EnCode(0, "", 0);
// SendMsg(msg, 0);
}
bool NFCNet::CloseSocketAll()
{
std::map<int, NetObject*>::iterator it = mmObject.begin();
for (it; it != mmObject.end(); it++)
{
NetObject* pObject = it->second;
struct bufferevent* bev = pObject->GetBuffEvent();
bev->cbarg = NULL;
bufferevent_free(bev);
evutil_closesocket(pObject->GetFd());
mmObject.erase(it);
delete pObject;
pObject = NULL;
}
mmObject.clear();
return true;
}
reset net module when time out
// -------------------------------------------------------------------------
// @FileName NFCNet.cpp
// @Author LvSheng.Huang
// @Date 2013-12-15
// @Module NFIPacket
// @Desc : CNet
// -------------------------------------------------------------------------
#include "NFCNet.h"
#include "NFCPacket.h"
#include <WS2tcpip.h>
#include <winsock2.h>
#include <string.h>
#include "event2\bufferevent_struct.h"
void NFCNet::time_cb(evutil_socket_t fd, short _event, void *argc)
{
NetObject* pObject = (NetObject*)argc;
if (pObject)
{
pObject->GetNet()->HeartPack();
evtimer_add(pObject->GetNet()->ev, &(pObject->GetNet()->tv));
}
}
void NFCNet::conn_writecb(struct bufferevent *bev, void *user_data)
{
//ÿյϢʱ¼
// struct evbuffer *output = bufferevent_get_output(bev);
printf("Ϣ!!!\n");
}
void NFCNet::conn_eventcb(struct bufferevent *bev, short events, void *user_data)
{
NetObject* pObject = (NetObject*)user_data;
NFCNet* pNet = pObject->GetNet();
if(!pNet->mEventCB._Empty())
{
pNet->mEventCB(pObject->GetFd(), NF_NET_EVENT(events));
}
if (events & BEV_EVENT_EOF)
{
printf("%d Connection closed.\n", pObject->GetFd());
pNet->CloseSocket(pObject->GetFd());
if (!pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_ERROR)
{
printf("%d Got an error on the connection: %d\n", pObject->GetFd(), errno);/*XXX win32*/
pNet->CloseSocket(pObject->GetFd());
if (!pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_TIMEOUT)
{
printf("%d read timeout: %d\n", pObject->GetFd(), errno);/*XXX win32*/
pNet->CloseSocket(pObject->GetFd());
if (!pNet->mbServer)
{
//ͻ˶
pNet->mbRuning = false;
pNet->Reset();
}
}
else if (events & BEV_EVENT_CONNECTED)
{
pNet->mbRuning = true;
printf("%d Connection successed\n", pObject->GetFd());/*XXX win32*/
}
}
void NFCNet::signal_cb(evutil_socket_t sig, short events, void *user_data)
{
NFCNet *base = (NFCNet *)user_data;
struct timeval delay = { 2, 0 };
printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
event_base_loopexit(base->base, &delay);
}
void NFCNet::listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data)
{
//
NFCNet* pNet = (NFCNet*)user_data;
bool bClose = pNet->CloseSocket(fd);
if (bClose)
{
//error
return;
}
if (pNet->mmObject.size() >= pNet->mnMaxConnect)
{
//ӦTܾ
return;
}
struct event_base *base = pNet->base;
//һsocketbufferevent
struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev)
{
//ӦTܾ
fprintf(stderr, "Error constructing bufferevent!");
//event_base_loopbreak(base);
return;
}
//һһӡΪ䴴һbufferevent--FDҪ
struct sockaddr_in* pSin = (sockaddr_in*)sa;
printf("µ¼ fd:%d IP: %s\n", fd, inet_ntoa(pSin->sin_addr));
NetObject* pObject = new NetObject(pNet, fd, *pSin, bev);
pObject->GetNet()->AddSocket(fd, pObject);
//Ϊbuffereventøֻص
bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, (void*)pObject);
//buffereventĶд
bufferevent_enable(bev, EV_READ|EV_WRITE);
//ģͻ¼
conn_eventcb(bev, BEV_EVENT_CONNECTED, (void*)pObject);
//////////////////////////////////////////////////////////////////////////
struct timeval tv;
/* öʱ120, Ϊ, 120ûյϢT */
tv.tv_sec = 120;
tv.tv_usec = 0;
bufferevent_set_timeouts(bev, &tv, NULL);
}
void NFCNet::conn_readcb(struct bufferevent *bev, void *user_data)
{
//ܵϢ
NetObject* pObject = (NetObject*)user_data;
if (!pObject)
{
return;
}
NFCNet* pNet = pObject->GetNet();
if (!pNet)
{
return;
}
struct evbuffer *input = bufferevent_get_input(bev);
if (!input)
{
return;
}
size_t len = evbuffer_get_length(input);
//ظͻ
// struct evbuffer *output = bufferevent_get_output(bev);
// evbuffer_add_buffer(output, input);
// SendMsg(1, strData,len, pObject->GetFd());
//////////////////////////////////////////////////////////////////////////
char* strData = new char[len];
//char strData[NF_MAX_SERVER_PACKET_SIZE] = {0};
if(evbuffer_remove(input, strData, len) > 0)
{
pObject->AddBuff(strData, len);
pNet->Dismantle(pObject);
}
delete[] strData;
}
//////////////////////////////////////////////////////////////////////////
bool NFCNet::Execute(const float fLasFrametime, const float fStartedTime)
{
//std::cout << "Running:" << mbRuning << std::endl;
if (mbRuning && base)
{
event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);
}
return mbRuning;
}
int NFCNet::Initialization( const char* strIP, const unsigned short nPort)
{
mstrIP = strIP;
mnPort = nPort;
return InitClientNet();
}
int NFCNet::Initialization( const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount)
{
mnMaxConnect = nMaxClient;
mnPort = nPort;
mnCpuCount = nCpuCount;
return InitServerNet();
}
bool NFCNet::Final()
{
if (mbServer)
{
CloseSocketAll();
}
if (listener)
{
evconnlistener_free(listener);
listener = NULL;
}
if (signal_event)
{
event_free(signal_event);
signal_event = NULL;
}
// bufferevent_socket_newòƹرsocketԼͷ
//if (base)
//{
// event_base_free(base);
// base = NULL;
//}
return true;
}
bool NFCNet::SendMsg( const NFIPacket& msg, const uint32_t nSockIndex, bool bBroadcast )
{
if (!mbRuning)
{
return false;
}
return SendMsg(msg.GetPacketData(), msg.GetPacketLen(), nSockIndex, bBroadcast );
}
bool NFCNet::SendMsg(const char* msg, const uint32_t nLen, const uint32_t nSockIndex, bool bBroadcast /*= false*/ )
{
std::map<int, NetObject*>::iterator it = mmObject.find(nSockIndex);
if (it != mmObject.end())
{
NetObject* pNetObject = (NetObject*)it->second;
if (pNetObject)
{
bufferevent* bev = pNetObject->GetBuffEvent();
if (NULL != bev && nLen > 0)
{
bufferevent_write(bev, msg, nLen);
return true;
}
}
}
return false;
}
bool NFCNet::CloseSocket( const uint32_t nSockIndex )
{
std::map<int, NetObject*>::iterator it = mmObject.find(nSockIndex);
if (it != mmObject.end())
{
NetObject* pObject = it->second;
struct bufferevent* bev = pObject->GetBuffEvent();
//bev->cbarg = NULL;
bufferevent_free(bev);
evutil_closesocket(nSockIndex);
mmObject.erase(it);
delete pObject;
pObject = NULL;
return true;
}
return false;
}
bool NFCNet::Dismantle(NetObject* pObject )
{
bool bRet = true;
NFCPacket packet(mnHeadLength);
int len = pObject->GetBuffLen();
if (len > packet.GetHeadSize())
{
int nUsedLen = packet.DeCode(pObject->GetBuff(), len);
if (nUsedLen > 0)
{
packet.SetFd(pObject->GetFd());
int nRet = 0;
if (!mRecvCB._Empty())
{
nRet = mRecvCB(packet);
bRet = bRet && nRet;
}
else
{
nRet = OnRecivePacket(pObject->GetFd(), packet.GetPacketData(), packet.GetPacketLen());
bRet = bRet && nRet;
}
//ӵ
pObject->RemoveBuff(0, nUsedLen);
//
bRet = bRet && Dismantle(pObject);
}
else if (0 == nUsedLen)
{
//Ȳ(ȴ´ν)
}
else
{
//ۼƴ̫--ʵո
pObject->IncreaseError();
}
if (pObject->GetErrorCount() > 5)
{
CloseSocket(pObject->GetFd());
}
}
return bRet;
}
bool NFCNet::AddSocket( const uint32_t nSockIndex, NetObject* pObject )
{
return mmObject.insert(std::map<int, NetObject*>::value_type(nSockIndex, pObject)).second;
}
int NFCNet::InitClientNet()
{
std::string strIP = mstrIP;
int nPort = mnPort;
struct sockaddr_in addr;
struct bufferevent *bev = NULL;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(nPort);
if (inet_pton(AF_INET, strIP.c_str(), &addr.sin_addr) <= 0)
{
printf("inet_pton");
return -1;
}
base = event_base_new();
if (base == NULL)
{
printf("event_base_new ");
return -1;
}
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (bev == NULL)
{
printf("bufferevent_socket_new ");
return -1;
}
int sockfd = bufferevent_socket_connect(bev, (struct sockaddr *)&addr, sizeof(addr));
if (0 != sockfd)
{
int nError = GetLastError();
printf("bufferevent_socket_connect error");
return -1;
}
NetObject* pObject = new NetObject(this, sockfd, addr, bev);
if (!AddSocket(sockfd, pObject))
{
assert(0);
return -1;
}
mbServer = false;
mbRuning = true;
bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, (void*)pObject);
bufferevent_enable(bev, EV_READ|EV_WRITE);
ev = evtimer_new(base, time_cb, (void*)pObject);
evutil_timerclear(&tv);
tv.tv_sec = 10; //
tv.tv_usec = 0;
evtimer_add(ev, &tv);
//event_base_loop(base, EVLOOP_ONCE|EVLOOP_NONBLOCK);
return sockfd;
}
int NFCNet::InitServerNet()
{
int nMaxClient = mnMaxConnect;
int nCpuCount = mnCpuCount;
int nPort = mnPort;
struct sockaddr_in sin;
#if NF_PLATFORM == NF_PLATFORM_WIN
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
//////////////////////////////////////////////////////////////////////////
struct event_config *cfg = event_config_new();
#if NF_PLATFORM == NF_PLATFORM_WIN
//event_config_avoid_method(cfg, "iocp");
//event_config_require_features(cfg, event_method_feature.EV_FEATURE_ET);//ʽ
evthread_use_windows_threads();
if(event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP) < 0)
{
//ʹIOCP
return -1;
}
if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
{
return -1;
}
base = event_base_new_with_config(cfg);
#else
//event_config_avoid_method(cfg, "epoll");
if(event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) < 0)
{
//ʹEPOLL
return -1;
}
if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
{
return -1;
}
base = event_base_new_with_config(cfg);//event_base_new()
#endif
event_config_free(cfg);
//////////////////////////////////////////////////////////////////////////
if (!base)
{
fprintf(stderr, "Could not initialize libevent!\n");
Final();
return -1;
}
//ʼʱ
//gettime(base, &base->event_tv);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(nPort);
printf("server started with %d\n", nPort);
listener = evconnlistener_new_bind(base, listener_cb, (void *)this,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr*)&sin,
sizeof(sin));
if (!listener)
{
fprintf(stderr, "Could not create a listener!\n");
Final();
return -1;
}
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)this);
if (!signal_event || event_add(signal_event, NULL)<0)
{
fprintf(stderr, "Could not create/add a signal event!\n");
Final();
return -1;
}
mbServer = true;
mbRuning = true;
return mnMaxConnect;
}
bool NFCNet::Reset()
{
if (!mbServer)
{
Final();
InitClientNet();
}
return true;
}
void NFCNet::HeartPack()
{
//NFCPacket msg(mnHeadLength);
//msg.EnCode(0, "", 0);
// SendMsg(msg, 0);
}
bool NFCNet::CloseSocketAll()
{
std::map<int, NetObject*>::iterator it = mmObject.begin();
for (it; it != mmObject.end(); it++)
{
NetObject* pObject = it->second;
struct bufferevent* bev = pObject->GetBuffEvent();
bev->cbarg = NULL;
bufferevent_free(bev);
evutil_closesocket(pObject->GetFd());
mmObject.erase(it);
delete pObject;
pObject = NULL;
}
mmObject.clear();
return true;
}
|
// Copyright (c) 2009 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "libmv/correspondence/feature.h"
#include "libmv/descriptor/descriptor.h"
#include "libmv/descriptor/vector_descriptor.h"
#include "libmv/image/convolve.h"
#include "libmv/image/image.h"
#include "libmv/image/integral_image.h"
#include "libmv/logging/logging.h"
#include "libmv/numeric/numeric.h"
namespace libmv {
namespace descriptor {
template<typename TImage>
float HarrX(const TImage &integral_image, int row, int col, int scale) {
// Ignore the center strip for odd scales.
int HW = scale / 2, W = scale;
int C = W % 2;
return float(BoxIntegral(integral_image, row - HW, col + C, W, HW))
- float(BoxIntegral(integral_image, row - HW, col - HW, W, HW));
}
template<typename TImage>
float HarrY(const TImage &integral_image, int row, int col, int scale) {
// Ignore the center strip for odd scales.
int HW = scale / 2, W = scale;
int C = W % 2;
return float(BoxIntegral(integral_image, row + C, col - HW, W, HW))
- float(BoxIntegral(integral_image, row - HW, col - HW, W, HW));
}
// TODO(keir): Concievably, these template parameters could be exposed to
// experiment with SURF parameters. Try that!
// descriptor must be sized to 4 * blocks *blocks
template<int blocks, int samples_per_block,
typename TImage, typename TPointFeature>
void USURFDescriptor(const TImage &integral_image,
const TPointFeature &feature,
Vecf *descriptor) {
float x = feature.x();
float y = feature.y();
float scale = feature.scale;
const int int_scale = lround(2*scale);
const int half_region = blocks*samples_per_block/2;
// Since the Gaussian is a separable filter, precompute it.
Matrix<float, 2*half_region, 1> gaussian;
for (int i = -half_region; i < half_region; ++i) {
gaussian(i + half_region) = Gaussian(i, 3.3*scale);
}
int done_dims = 0;
for (int row = -half_region; row < half_region; row += samples_per_block) {
for (int col = -half_region; col < half_region; col += samples_per_block) {
Vec4f components(0,0,0,0);
for (int r = row; r < row + samples_per_block; ++r) {
for (int c = col; c < col + samples_per_block; ++c) {
int sample_row = lround(y + scale*r);
int sample_col = lround(x + scale*c);
float weight = gaussian(r + half_region) * gaussian(c + half_region);
Vec2f dxy;
dxy << HarrX(integral_image, sample_row, sample_col, int_scale),
HarrY(integral_image, sample_row, sample_col, int_scale);
dxy *= weight;
components.start<2>() += dxy;
components.end<2>() += dxy.cwise().abs();
}
}
(*descriptor).segment<4>(done_dims) = components;
done_dims += 4;
}
}
descriptor->normalize();
}
class SurfDescriber : public Describer {
public:
virtual void Describe(const vector<Feature *> &features,
const Image &image,
const detector::DetectorData *detector_data,
vector<Descriptor *> *descriptors) {
// TODO(keir): Make the descriptor data the SURF detector integral image.
(void) detector_data;
Matu integral_image;
IntegralImage(*(image.AsArray3Du()), &integral_image);
descriptors->resize(features.size());
for (int i = 0; i < features.size(); ++i) {
PointFeature *point = dynamic_cast<PointFeature *>(features[i]);
VecfDescriptor *descriptor = NULL;
if (point) {
descriptor = new VecfDescriptor(64);
USURFDescriptor<4, 5>(integral_image, *point, &descriptor->coords);
}
(*descriptors)[i] = descriptor;
}
}
};
Describer *CreateSurfDescriber() {
return new SurfDescriber;
}
} // namespace descriptor
} // namespace libmv
Add the MSURFDescriptor. A Surf descriptor with overlapping of sampling boxes and two pass weighting scheme.
This descriptor support rotation.
// Copyright (c) 2009 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "libmv/correspondence/feature.h"
#include "libmv/descriptor/descriptor.h"
#include "libmv/descriptor/vector_descriptor.h"
#include "libmv/image/convolve.h"
#include "libmv/image/image.h"
#include "libmv/image/integral_image.h"
#include "libmv/logging/logging.h"
#include "libmv/numeric/numeric.h"
namespace libmv {
namespace descriptor {
template<typename TImage>
float HarrX(const TImage &integral_image, int row, int col, int scale) {
// Ignore the center strip for odd scales.
int HW = scale / 2, W = scale;
int C = W % 2;
return float(BoxIntegral(integral_image, row - HW, col + C, W, HW))
- float(BoxIntegral(integral_image, row - HW, col - HW, W, HW));
}
template<typename TImage>
float HarrY(const TImage &integral_image, int row, int col, int scale) {
// Ignore the center strip for odd scales.
int HW = scale / 2, W = scale;
int C = W % 2;
return float(BoxIntegral(integral_image, row + C, col - HW, W, HW))
- float(BoxIntegral(integral_image, row - HW, col - HW, W, HW));
}
// TODO(keir): Concievably, these template parameters could be exposed to
// experiment with SURF parameters. Try that!
// descriptor must be sized to 4 * blocks *blocks
template<int blocks, int samples_per_block,
typename TImage, typename TPointFeature>
void USURFDescriptor(const TImage &integral_image,
const TPointFeature &feature,
Vecf *descriptor) {
float x = feature.x();
float y = feature.y();
float scale = feature.scale;
const int int_scale = lround(2*scale);
const int half_region = blocks*samples_per_block/2;
// Since the Gaussian is a separable filter, precompute it.
Matrix<float, 2*half_region, 1> gaussian;
for (int i = -half_region; i < half_region; ++i) {
gaussian(i + half_region) = Gaussian(i, 3.3*scale);
}
int done_dims = 0;
for (int row = -half_region; row < half_region; row += samples_per_block) {
for (int col = -half_region; col < half_region; col += samples_per_block) {
Vec4f components(0,0,0,0);
for (int r = row; r < row + samples_per_block; ++r) {
for (int c = col; c < col + samples_per_block; ++c) {
int sample_row = lround(y + scale*r);
int sample_col = lround(x + scale*c);
float weight = gaussian(r + half_region) * gaussian(c + half_region);
Vec2f dxy;
dxy << HarrX(integral_image, sample_row, sample_col, int_scale),
HarrY(integral_image, sample_row, sample_col, int_scale);
dxy *= weight;
components.start<2>() += dxy;
components.end<2>() += dxy.cwise().abs();
}
}
(*descriptor).segment<4>(done_dims) = components;
done_dims += 4;
}
}
descriptor->normalize();
}
// descriptor must be sized to 4 * blocks *blocks
template<int blocks, int samples_per_block,
typename TImage, typename TPointFeature>
void MSURFDescriptor(const TImage &integral_image,
const TPointFeature &feature,
Vecf *descriptor) {
float x = feature.x();
float y = feature.y();
float scale = feature.scale;
const int int_scale = lround(2*scale);
// Allow overlap between blocks
const int half_region = blocks* (samples_per_block-(blocks-1))/2;
// Since the Gaussian is a separable filter, precompute it.
Matrix<float, 2*half_region, 1> gaussian;
for (int i = -half_region; i < half_region; ++i) {
gaussian(i + half_region) = Gaussian(i, 2*scale);
}
float co = 1.0f, si = 0.0f; // Suppose Upright descriptor
bool bUpright = false; //Todo(pmoulon) set this variable as parameter
if (!bUpright)
{
co = cos(feature.orientation);
si = sin(feature.orientation);
}
int done_dims = 0;
for (int row = -half_region; row < half_region - blocks;
row += (samples_per_block - blocks)) {
for (int col = -half_region; col < half_region - blocks;
col += (samples_per_block - blocks)) {
Vec4f components(0.0f,0.0f,0.0f,0.0f);
for (int r = row; r < row + samples_per_block; ++r) {
for (int c = col; c < col + samples_per_block; ++c) {
//Get coords of sample point on the rotated axis
int sample_col = lround(x + (-r*scale*si + c*scale*co));
int sample_row = lround(y + ( r*scale*co + c*scale*si));
float weight = gaussian(r + half_region) * gaussian(c + half_region);
//Compute Harr response on rotated axis
float rrx = HarrX(integral_image, sample_row, sample_col, int_scale);
float rry = HarrY(integral_image, sample_row, sample_col, int_scale);
Vec2f dxy;
dxy << (co*rry - si*rrx),
(si*rry + co*rrx);
dxy *= weight;
components.start<2>() += dxy;
components.end<2>() += dxy.cwise().abs();
}
}
float gauss_BigBox = Gaussian2D(row/half_region,col/half_region,1.0f);
(*descriptor).segment<4>(done_dims) = components*gauss_BigBox;
done_dims += 4;
}
}
descriptor->normalize();
}
class SurfDescriber : public Describer {
public:
virtual void Describe(const vector<Feature *> &features,
const Image &image,
const detector::DetectorData *detector_data,
vector<Descriptor *> *descriptors) {
// TODO(keir): Make the descriptor data the SURF detector integral image.
(void) detector_data;
Matu integral_image;
IntegralImage(*(image.AsArray3Du()), &integral_image);
descriptors->resize(features.size());
for (int i = 0; i < features.size(); ++i) {
PointFeature *point = dynamic_cast<PointFeature *>(features[i]);
VecfDescriptor *descriptor = NULL;
if (point) {
descriptor = new VecfDescriptor(64);
MSURFDescriptor<4, 9>(integral_image, *point, &descriptor->coords);
}
(*descriptors)[i] = descriptor;
}
}
};
Describer *CreateSurfDescriber() {
return new SurfDescriber;
}
} // namespace descriptor
} // namespace libmv
|
//===--- SwiftDtoa.c ---------------------------------------------*- c -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===---------------------------------------------------------------------===//
//
// Note: This is really a C file, but Swift's build system for Linux is
// partially allergic to C, so it's being compiled as ".cpp" for now. Please
// don't infect it with C++-isms.
//
///
/// The core algorithm here (see `swift_decompose_double` below) is a
/// modified form of the Grisu2 algorithm from Florian Loitsch;
/// "Printing Floating-Point Numbers Quickly and Accurately with
/// Integers", 2010. https://dl.acm.org/citation.cfm?id=1806623
///
/// This includes some improvements suggested by the "Errol paper":
/// Marc Andrysco, Ranjit Jhala, Sorin Lerner; "Printing
/// Floating-Point Numbers: A Faster, Always Correct Method", 2016.
/// https://dl.acm.org/citation.cfm?id=2837654
///
/// The following summary assumes you're familiar with Grisu-style
/// algorithms in general:
///
/// Loitsch' original Grisu2 implementation guarantees round-trip
/// accuracy but only generates the shortest decimal expansion about 99%
/// of the time. Grisu3 addresses this by essentially running two
/// copies of Grisu2 in parallel: one copy biased to avoid inaccuracy,
/// the other biased to avoid generating excess digits. If they agree,
/// then the result must be both accurate and short. But if they
/// disagree, then Grisu3 gives up and must defer to another algorithm.
///
/// The Errol paper provides a deeper analysis of the cases where
/// Grisu2 fails to find the shortest decimal expansion. There
/// are two root causes of such failures:
///
/// * Insufficient precision leads to scattered failures across the
/// entire range. Theorem 7 in the Errol paper shows a way to
/// construct a superset of the numbers subject to such failures.
/// With this list, we can simply test whether we have sufficient
/// precision.
///
/// For Double, the Errol3 algorithm uses double-double arithmetic
/// with about 106 bits precision. This turns out to be not quite
/// sufficient, requiring Errol3 to pre-screen the input against a
/// list of exceptions culled from the larger list of possible
/// failures. Using high-precision integers, we've discovered that
/// 110 bit precision is sufficient to satisfy the Errol test cases
/// without requiring any pre-screening.
///
/// For Float and Float80, the same approach shows that we need 53
/// and 135 bits, respectively. It is an interesting coincidence
/// that for all three cases, an n-bit significand can be formatted
/// optimally with no more than 2n+7 bits of intermediate precision.
///
/// * For numbers with even significands and a specific range of
/// exponents, the shortest value might occur exactly at the midpoint
/// between two adjacent binary floating-point values. Theorem 6 of
/// the Errol paper characterizes this sufficiently to allow us to
/// vary our strategy. Errol3 uses a separate formatter for this
/// case. This implementation instead widens the interval (as in
/// Grisu3), which allows us to use the same fast digit generation in
/// all cases, providing uniform performance across the entire range.
///
/// In addition to addressing the shortness failures characterized in
/// the Errol paper, the implementation here also incorporates
/// final-digit corrections from Grisu3, allowing it to produce the
/// optimal decimal decomposition in all cases.
///
/// In summary, this implementation is:
///
/// * Fast. It uses only fixed-width integer arithmetic and has
/// constant memory requirements.
///
/// * Simple. It is only a little more complex than Loitsch' original
/// implementation of Grisu2. The full digit decomposition for double
/// is less than 300 lines of standard C.
///
/// * Always Accurate. Converting the decimal form back to binary
/// will always yield exactly the same value. For the IEEE 754
/// formats, the round-trip will produce exactly the same bit
/// pattern in memory.
///
/// * Always Short. This always selects an accurate result with the
/// minimum number of decimal digits.
///
/// * Always Close. Among all accurate, short results, this always
/// chooses the result that is closest to the exact floating-point
/// value. (In case of an exact tie, it rounds the last digit even.)
///
/// For single-precision Float, these claims have been exhaustively
/// tested -- all 2^32 values can be checked in under an hour on a
/// mid-range modern laptop. The Double and Float80 formatters rely on
/// results from the Errol paper to ensure correctness. In addition,
/// we have verified more than 10^13 randomly-chosen values by comparing
/// the results to the output of Errol4.
///
// ----------------------------------------------------------------------------
#include <float.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "swift/Runtime/SwiftDtoa.h"
#if defined(__SIZEOF_INT128__)
// We get a significant speed boost if we can use the __uint128_t
// type that's present in GCC and Clang on 64-bit architectures. In
// particular, we can do 128-bit arithmetic directly and can
// represent 192-bit integers as a collection of 64-bit elements.
#define HAVE_UINT128_T 1
#else
// On 32-bit, we have to use slower code that manipulates 128-bit
// and 192-bit integers as collections of 32-bit elements.
#define HAVE_UINT128_T 0
#endif
// Try to verify that the system floating-point types really are what we
// expect. Note that the code below is specific to these exact
// floating-point representations.
#if (FLT_RADIX != 2)
// Either you're using hexadecimal float format on S390, or you have a
// really broken C environment.
#error "This platform claims to not use binary floating point."
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
#if (FLT_MANT_DIG != 24) || (FLT_MIN_EXP != -125) || (FLT_MAX_EXP != 128)
#error "Are you certain `float` on this platform is really IEEE 754 single-precision binary32 format?"
#endif
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
#if (DBL_MANT_DIG != 53) || (DBL_MIN_EXP != -1021) || (DBL_MAX_EXP != 1024)
#error "Are you certain `double` on this platform is really IEEE 754 double-precision binary64 format?"
#endif
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
#if (LDBL_MANT_DIG != 64) || (LDBL_MIN_EXP != -16381) || (LDBL_MAX_EXP != 16384)
#error "Are you certain `long double` on this platform is really Intel 80-bit extended precision?"
#endif
#endif
// See the implementations at the bottom of this file for detailed explanations
// of the purpose of each function.
//
// Helper functions used by float, double, and float80 machinery.
//
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
#if HAVE_UINT128_T
typedef __uint128_t swift_uint128_t;
#define initialize128WithHighLow64(dest, high64, low64) ((dest) = ((__uint128_t)(high64) << 64) | (low64))
#else
typedef struct {
uint32_t low, b, c, high;
} swift_uint128_t;
#define initialize128WithHighLow64(dest, high64, low64) \
((dest).low = (uint32_t)(low64), \
(dest).b = (uint32_t)((low64) >> 32), \
(dest).c = (uint32_t)(high64), \
(dest).high = (uint32_t)((high64) >> 32))
#endif
static int binaryExponentFor10ToThe(int p);
static int decimalExponentFor2ToThe(int e);
#endif
//
// Helper functions used only by the single-precision float formatter
//
#if SWIFT_DTOA_FLOAT_SUPPORT
static uint64_t multiply64x32RoundingDown(uint64_t lhs, uint32_t rhs);
static uint64_t multiply64x32RoundingUp(uint64_t lhs, uint32_t rhs);
static uint64_t multiply64x64RoundingDown(uint64_t lhs, uint64_t rhs);
static uint64_t multiply64x64RoundingUp(uint64_t lhs, uint64_t rhs);
static uint64_t shiftRightRoundingUp64(uint64_t lhs, int shift);
static void intervalContainingPowerOf10_Float(int p, uint64_t *lower, uint64_t *upper, int *exponent);
#endif
//
// Helper functions used only by the double-precision formatter
//
#if SWIFT_DTOA_DOUBLE_SUPPORT
#if HAVE_UINT128_T
#define increment128(dest) ((dest) += 1)
#define isLessThan128x128(lhs, rhs) ((lhs) < (rhs))
#define subtract128x128(lhs, rhs) (*(lhs) -= (rhs))
#define multiply128xi32(lhs, rhs) (*(lhs) *= (rhs))
#define initialize128WithHigh64(dest, value) ((dest) = (__uint128_t)(value) << 64)
#define extractHigh64From128(arg) ((uint64_t)((arg) >> 64))
static int extractIntegerPart128(__uint128_t *fixed128, int fractionBits) {
return (int)(*fixed128 >> fractionBits);
}
static void clearIntegerPart128(__uint128_t *fixed128, int fractionBits) {
const swift_uint128_t fixedPointMask = (((__uint128_t)1 << fractionBits) - 1);
*fixed128 &= fixedPointMask;
}
#else
#define increment128(dest) \
do { \
uint64_t t = (dest).low + 1; \
(dest).low = (uint32_t)t; \
t >>= 32; \
t += (dest).b; \
(dest).b = (uint32_t)t; \
t >>= 32; \
t += (dest).c; \
(dest).c = (uint32_t)t; \
t >>= 32; \
(dest).high += (uint32_t)t; \
} while (0)
static int isLessThan128x128(swift_uint128_t lhs, swift_uint128_t rhs);
static void subtract128x128(swift_uint128_t *lhs, swift_uint128_t rhs);
static void multiply128xi32(swift_uint128_t *lhs, uint32_t rhs);
#define initialize128WithHigh64(dest, value) \
((dest).low = (dest).b = 0, \
(dest).c = (uint32_t)(value), \
(dest).high = (uint32_t)((value) >> 32))
#define extractHigh64From128(arg) (((uint64_t)(arg).high << 32)|((arg).c))
static int extractIntegerPart128(swift_uint128_t *fixed128, int fractionBits) {
const int highFractionBits = fractionBits % 32;
return (int)(fixed128->high >> highFractionBits);
}
static void clearIntegerPart128(swift_uint128_t *fixed128, int fractionBits) {
const int highFractionBits = fractionBits % 32;
fixed128->high &= ((uint32_t)1 << highFractionBits) - 1;
}
#endif
static swift_uint128_t multiply128x64RoundingDown(swift_uint128_t lhs, uint64_t rhs);
static swift_uint128_t multiply128x64RoundingUp(swift_uint128_t lhs, uint64_t rhs);
static swift_uint128_t shiftRightRoundingDown128(swift_uint128_t lhs, int shift);
static swift_uint128_t shiftRightRoundingUp128(swift_uint128_t lhs, int shift);
static void intervalContainingPowerOf10_Double(int p, swift_uint128_t *lower, swift_uint128_t *upper, int *exponent);
#endif
//
// Helper functions used only by the extended-precision long double formatter
//
#if SWIFT_DTOA_FLOAT80_SUPPORT
#if HAVE_UINT128_T
// A 192-bit unsigned integer type stored as 3 64-bit words
typedef struct {uint64_t low, mid, high;} swift_uint192_t;
#define initialize192WithHighMidLow64(dest, high64, mid64, low64) \
((dest).low = (low64), \
(dest).mid = (mid64), \
(dest).high = (high64))
#else
// A 192-bit unsigned integer type stored as 6 32-bit words
typedef struct {uint32_t low, b, c, d, e, high;} swift_uint192_t;
#define initialize192WithHighMidLow64(dest, high64, mid64, low64) \
((dest).low = (uint64_t)(low64), \
(dest).b = (uint64_t)(low64) >> 32, \
(dest).c = (uint64_t)(mid64), \
(dest).d = (uint64_t)(mid64) >> 32, \
(dest).e = (uint64_t)(high64), \
(dest).high = (uint64_t)(high64) >> 32)
#endif
static void multiply192x64RoundingDown(swift_uint192_t *lhs, uint64_t rhs);
static void multiply192x64RoundingUp(swift_uint192_t *lhs, uint64_t rhs);
static void multiply192xi32(swift_uint192_t *lhs, uint32_t rhs);
static void multiply192x128RoundingDown(swift_uint192_t *lhs, swift_uint128_t rhs);
static void multiply192x128RoundingUp(swift_uint192_t *lhs, swift_uint128_t rhs);
static void subtract192x192(swift_uint192_t *lhs, swift_uint192_t rhs);
static int isLessThan192x192(swift_uint192_t lhs, swift_uint192_t rhs);
static void shiftRightRoundingDown192(swift_uint192_t *lhs, int shift);
static void shiftRightRoundingUp192(swift_uint192_t *lhs, int shift);
static void intervalContainingPowerOf10_Float80(int p, swift_uint192_t *lower, swift_uint192_t *upper, int *exponent);
#endif
//
// --------------- Digit generation ---------------------
//
// This is the interesting part.
// These routines take a floating-point value and efficiently compute
// everything necessary to write an optimal base-10 representation of
// that value. In particular, they compute the base-10 exponent and
// corresponding digits.
// swift_decompose_double is thoroughly commented; swift_decompose_float
// and swift_decompose_float80 are fundamentally the same algorithm, but
// adjusted to perform optimally for those types.
#if SWIFT_DTOA_DOUBLE_SUPPORT
// Return raw bits encoding the double
static uint64_t bitPatternForDouble(double d) {
union { double d; uint64_t u; } converter;
converter.d = d;
return converter.u;
}
int swift_decompose_double(double d,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
// Bits in raw significand (not including hidden bit, if present)
static const int significandBitCount = DBL_MANT_DIG - 1;
static const uint64_t significandMask
= ((uint64_t)1 << significandBitCount) - 1;
// Bits in raw exponent
static const int exponentBitCount = 11;
static const int exponentMask = (1 << exponentBitCount) - 1;
// Note: IEEE 754 conventionally uses 1023 as the exponent
// bias. That's because they treat the significand as a
// fixed-point number with one bit (the hidden bit) integer
// portion. The logic here reconstructs the significand as a
// pure fraction, so we need to accomodate that when
// reconstructing the binary exponent.
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 1022
// Step 0: Deconstruct the target number
// Note: this strongly assumes IEEE 754 binary64 format
uint64_t raw = bitPatternForDouble(d);
int exponentBitPattern = (raw >> significandBitCount) & exponentMask;
uint64_t significandBitPattern = raw & significandMask;
// Step 1: Handle the various input cases:
int binaryExponent;
uint64_t significand;
if (digits_length < 17) {
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern
<< (64 - significandBitCount - 1);
}
} else { // normal
binaryExponent = exponentBitPattern - exponentBias;
uint64_t hiddenBit = (uint64_t)1 << significandBitCount;
uint64_t fullSignificand = significandBitPattern + hiddenBit;
significand = fullSignificand << (64 - significandBitCount - 1);
}
// Step 2: Determine the exact unscaled target interval
// Grisu-style algorithms construct the shortest decimal digit
// sequence within a specific interval. To build the appropriate
// interval, we start by computing the exact midpoints between
// this floating-point value and the adjacent ones.
uint64_t halfUlp = (uint64_t)1 << (64 - significandBitCount - 2);
uint64_t quarterUlp = halfUlp >> 1;
uint64_t upperMidpointExact = significand + halfUlp;
int isBoundary = significandBitPattern == 0;
uint64_t lowerMidpointExact
= significand - (isBoundary ? quarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
// Grisu algorithms are based in part on a simple technique for
// generating a base-10 form for a binary floating-point number.
// Start with a binary floating-point number `f * 2^e` and then
// estimate the decimal exponent `p`. You can then rewrite your
// original number as:
//
// ```
// f * 2^e * 10^-p * 10^p
// ```
//
// The last term is part of our output, and a good estimate for
// `p` will ensure that `2^e * 10^-p` is going to be close to 1.
// So multiplying the first three terms yields a fraction suitable
// for producing the decimal digits. So we need to estimate `p`:
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
// Compute `10^-p` to 128-bit precision. We generate
// both over- and under-estimates to ensure we can exactly
// bound the later use of these values.
swift_uint128_t powerOfTenRoundedDown;
swift_uint128_t powerOfTenRoundedUp;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Double(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
// As mentioned above, the final digit generation works
// with an interval, so we actually apply the scaling
// to the upper and lower midpoint values separately.
// As part of the scaling here, we'll switch from a pure
// fraction to a fixed-point form. Using 14 bit integer portion
// will allow us to compute four decimal digits at a time.
static const int integerBits = 14;
static const int fractionBits = 128 - integerBits;
// We scale the interval in one of two different ways...
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 131;
swift_uint128_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Case A: Narrow the interval
// Loitsch' original Grisu2 always narrows the interval.
// Since our digit generation will select a value within
// the scaled interval, narrowing the interval guarantees
// that we will find a digit sequence that converts back
// to the original value.
// This ensures accuracy but, as explained in Loitsch' paper,
// this carries a risk that there will be a shorter digit
// sequence outside of our narrowed interval that we will
// miss. This risk obviously gets lower with increased
// precision, but it wasn't until the Errol paper that anyone
// had a good way to test whether a particular implementation
// had sufficient precision. Using Errol Theorem 7 and tinkering
// with the `fractionBits` parameter above, you can show that
// 110 fraction bits is sufficient for Double.
// Multiply out the upper midpoint, rounding down...
swift_uint128_t u1 = multiply128x64RoundingDown(powerOfTenRoundedDown,
upperMidpointExact);
// Account for residual binary exponent and adjust
// to the fixed-point format
u = shiftRightRoundingDown128(u1, integerBits - extraBits);
// Conversely for the lower midpoint...
swift_uint128_t l1 = multiply128x64RoundingUp(powerOfTenRoundedUp,
lowerMidpointExact);
l = shiftRightRoundingUp128(l1, integerBits - extraBits);
} else {
// Case B: Widen the interval
// As explained in Errol Theorem 6, in certain cases the true
// shortest decimal result is at one of the exact scaled
// midpoints. Any narrowing will exclude the exact midpoints,
// so we must widen here to ensure we consider those cases.
// Errol Theorem 6 explains that this can only happen if the
// exact midpoints are integers with even significands and
// exponents less than a particular bound. (See the `if`
// condition above.)
// Widening the interval in this case ensures that we find a
// short result but carries a risk of selecting a result
// outside of the exact scaled interval (which would be
// inaccurate). For Float and Float80, it's easy to see this
// never happens: they use more fraction bits here than the
// maximum exponent for this case so any number outside the
// exact interval will not be an integer. Since any
// non-integer will always have more digits than the adjacent
// integers, the digit generation will never select it. For
// double, we've cut things a bit finer (114 bit fraction here
// is not higher than the exponent limit of 131 above), so
// we've had to rely on Errol Theorem 7 to enumerate possible
// failures to test those cases.
// Note: Grisu3 converts every number twice: once with the
// narrowed interval to ensure accuracy and once with the
// wider interval to ensure shortness. If both agree, the
// result must meet both conditions. In essence, the Errol
// paper provides a way to select narrowing or widening
// appropriately so we can avoid Grisu3's double conversion.
swift_uint128_t u1 = multiply128x64RoundingUp(powerOfTenRoundedUp,
upperMidpointExact);
u = shiftRightRoundingUp128(u1, integerBits - extraBits);
swift_uint128_t l1 = multiply128x64RoundingDown(powerOfTenRoundedDown,
lowerMidpointExact);
l = shiftRightRoundingDown128(l1, integerBits - extraBits);
}
// Step 6: Align first digit, adjust exponent
// This preps for digit generation. It just multiplies repeatedly
// by 10 until we have exactly one decimal digit in the integer
// part, adjusting the exponent as we go.
// In particular, this prunes leading zeros from subnormals.
// Generate digits for `t` with interval width `delta`
swift_uint128_t t = u;
swift_uint128_t delta = u;
subtract128x128(&delta, l); // Explained below.
int exponent = base10Exponent + 1;
// Except for subnormals, this loop should never run more than once.
#if HAVE_UINT128_T
static const swift_uint128_t fixedPointOne = (__uint128_t)1 << fractionBits;
while (t < fixedPointOne)
#else
// Because 1.0 in fixed point has a lot of zeros, it suffices
// to only compare the high-order word here. This is a minor
// performance win.
while (t.high < ((uint32_t)1 << (fractionBits % 32)))
#endif
{
exponent -= 1;
multiply128xi32(&delta, 10);
multiply128xi32(&t, 10);
}
// Step 7: Generate digits
// This is a common part of Grisu-style algorithms. The
// underlying idea is to generate digits for the scaled upper and
// lower boundaries, and stop when we hit the first different
// digit (at which point, the digit for the upper midpoint is the
// candidate final digit). To understand this, just note that
// 0.1234 is the shortest decimal between u = 0.123456 and l =
// 0.123345.
// Grisu uses a slightly optimized technique: it generates digits
// for the upper bound (multiplying by 10 to isolate each digit)
// and multiplies the interval width `delta` at the same time.
// The `different digit` criteria above translates to a test for
// `delta` being larger than the remainder.
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = extractIntegerPart128(&t, fractionBits);
clearIntegerPart128(&t, fractionBits);
// Further optimization: Generating four digits at a time reduces
// the total arithmetic required per digit. Note: The following
// block can be entirely removed with no effect on the result.
// If you're trying to understand this algorithm, just skip this
// block on first reading.
swift_uint128_t d0 = delta;
multiply128xi32(&d0, 10000);
swift_uint128_t t0 = t;
multiply128xi32(&t0, 10000);
int fourDigits = extractIntegerPart128(&t0, fractionBits); // 4 digits
clearIntegerPart128(&t0, fractionBits);
while (isLessThan128x128(d0, t0)) {
*digit_p++ = nextDigit;
int d = fourDigits / 100; // top 2 digits
*digit_p++ = d / 10;
*digit_p++ = d % 10;
d = fourDigits % 100; // bottom 2 digits
*digit_p++ = d / 10;
nextDigit = d % 10;
t = t0;
delta = d0;
multiply128xi32(&d0, 10000);
multiply128xi32(&t0, 10000);
fourDigits = extractIntegerPart128(&t0, fractionBits);
clearIntegerPart128(&t0, fractionBits);
}
// Finish by generating one digit at a time.
while (isLessThan128x128(delta, t)) {
*digit_p++ = nextDigit;
multiply128xi32(&delta, 10);
multiply128xi32(&t, 10);
nextDigit = extractIntegerPart128(&t, fractionBits);
clearIntegerPart128(&t, fractionBits);
}
// Adjust the final digit to be closer to the original value.
// This is basically the same as Grisu3. It accounts for the
// fact that sometimes there is more than one shortest digit
// sequence.
// For example, consider how the above would work if you had the
// value 0.1234 and computed u = 0.1257, l = 0.1211. The above
// digit generation works with `u`, so produces 0.125. But the
// values 0.122, 0.123, and 0.124 are just as short and 0.123 is
// the best choice, since it's closest to the original value.
// If `delta <= t + 1.0`, then the interval is narrower than
// one decimal digit, so there is no other option.
// Note: We've already consumed most of our available precision,
// so it's okay to just work in 64 bits here...
uint64_t deltaHigh64 = extractHigh64From128(delta);
uint64_t tHigh64 = extractHigh64From128(t);
if (deltaHigh64 > tHigh64 + ((uint64_t)1 << (fractionBits % 64))) {
// Note: 64-bit arithmetic is okay here
uint64_t skew;
if (isBoundary) {
// If we're at the boundary where the exponent shifts,
// then the original value is 1/3 of the way from
// the bottom of the interval ...
skew = deltaHigh64 - deltaHigh64 / 3 - tHigh64;
} else {
// ... otherwise it's exactly in the middle.
skew = deltaHigh64 / 2 - tHigh64;
}
// The `skew` above is the difference between our
// computed digits and the original exact value.
// Use that to offset the final digit:
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is exactly integer + 1/2, round the
// last digit even after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit; // Store the final digit.
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
// Return raw bits encoding the float
static uint64_t bitPatternForFloat(float f) {
union { float f; uint32_t u; } converter;
converter.f = f;
return converter.u;
}
// Decompose an IEEE 754 binary32 single-precision float
// into decimal digits and a corresponding decimal exponent.
// See swift_decompose_double for detailed comments on the algorithm here
int swift_decompose_float(float f,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
static const int significandBitCount = FLT_MANT_DIG - 1;
static const uint32_t significandMask
= ((uint32_t)1 << significandBitCount) - 1;
static const int exponentBitCount = 8;
static const int exponentMask = (1 << exponentBitCount) - 1;
// See comments in swift_decompose_double
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 125
// Step 0: Deconstruct the target number
// Note: this strongly assumes IEEE 754 binary32 format
uint32_t raw = bitPatternForFloat(f);
int exponentBitPattern = (raw >> significandBitCount) & exponentMask;
uint32_t significandBitPattern = raw & significandMask;
// Step 1: Handle the various input cases:
int binaryExponent;
uint32_t significand;
if (digits_length < 9) {
// Ensure we have space for 9 digits
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
// Return one zero digit and decimalExponent = 0.
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // Subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern << (32 - significandBitCount - 1);
}
} else { // normal
binaryExponent = exponentBitPattern - exponentBias;
uint32_t hiddenBit = (uint32_t)1 << (uint32_t)significandBitCount;
uint32_t fullSignificand = significandBitPattern + hiddenBit;
significand = fullSignificand << (32 - significandBitCount - 1);
}
// Step 2: Determine the exact unscaled target interval
uint32_t halfUlp = (uint32_t)1 << (32 - significandBitCount - 2);
uint32_t quarterUlp = halfUlp >> 1;
uint32_t upperMidpointExact = significand + halfUlp;
int isBoundary = significandBitPattern == 0;
uint32_t lowerMidpointExact
= significand - (isBoundary ? quarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
uint64_t powerOfTenRoundedDown = 0;
uint64_t powerOfTenRoundedUp = 0;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Float(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
static const int integerBits = 5;
static const int fractionBits = 64 - integerBits;
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 57;
uint64_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Narrow the interval
uint64_t u1 = multiply64x32RoundingDown(powerOfTenRoundedDown,
upperMidpointExact);
u = u1 >> (integerBits - extraBits); // Rounding down
uint64_t l1 = multiply64x32RoundingUp(powerOfTenRoundedUp,
lowerMidpointExact);
l = shiftRightRoundingUp64(l1, integerBits - extraBits);
} else {
// Widen the interval
uint64_t u1 = multiply64x32RoundingUp(powerOfTenRoundedUp,
upperMidpointExact);
u = shiftRightRoundingUp64(u1, integerBits - extraBits);
uint64_t l1 = multiply64x32RoundingDown(powerOfTenRoundedDown,
lowerMidpointExact);
l = l1 >> (integerBits - extraBits); // Rounding down
}
// Step 6: Align first digit, adjust exponent
// In particular, this prunes leading zeros from subnormals
static const uint64_t fixedPointOne = (uint64_t)1 << fractionBits;
static const uint64_t fixedPointMask = fixedPointOne - 1;
uint64_t t = u;
uint64_t delta = u - l;
int exponent = base10Exponent + 1;
while (t < fixedPointOne) {
exponent -= 1;
delta *= 10;
t *= 10;
}
// Step 7: Generate digits
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = (int)(t >> fractionBits);
t &= fixedPointMask;
// Generate one digit at a time...
while (t > delta) {
*digit_p++ = nextDigit;
delta *= 10;
t *= 10;
nextDigit = (int)(t >> fractionBits);
t &= fixedPointMask;
}
// Adjust the final digit to be closer to the original value
if (delta > t + fixedPointOne) {
uint64_t skew;
if (isBoundary) {
skew = delta - delta / 3 - t;
} else {
skew = delta / 2 - t;
}
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is integer + 1/2, round the last digit even
// after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit;
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// See `swift_decompose_double` for detailed comments on this implementatoin.
int swift_decompose_float80(long double d,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
// Omit leading bit, as if we were an IEEE 754 format
static const int significandBitCount = LDBL_MANT_DIG - 1;
static const int exponentBitCount = 15;
static const int exponentMask = (1 << exponentBitCount) - 1;
// See comments in swift_decompose_double to understand
// why we use 16,382 instead of 16,383 here.
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 16,382
// Step 0: Deconstruct the target number
// Note: this strongly assumes Intel 80-bit extended format in LSB
// byte order
const uint64_t *raw_p = (const uint64_t *)&d;
int exponentBitPattern = raw_p[1] & exponentMask;
uint64_t significandBitPattern = raw_p[0];
// Step 1: Handle the various input cases:
int64_t binaryExponent;
uint64_t significand;
if (digits_length < 21) {
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern;
}
} else if (significandBitPattern >> 63) { // Normal
binaryExponent = exponentBitPattern - exponentBias;
significand = significandBitPattern;
} else {
// "Unnormal" values are rejected as invalid by 80387 and later.
// Treat them the same as NaNs here.
return 0;
}
// Step 2: Determine the exact unscaled target interval
uint64_t halfUlp = (uint64_t)1 << 63;
uint64_t quarterUlp = halfUlp >> 1;
uint64_t threeQuarterUlp = halfUlp + quarterUlp;
swift_uint128_t upperMidpointExact, lowerMidpointExact;
initialize128WithHighLow64(upperMidpointExact, significand, halfUlp);
int isBoundary = (significandBitPattern & 0x7fffffffffffffff) == 0;
// Subtract 1/4 or 1/2 ULP by first subtracting 1 full ULP, then adding some back
initialize128WithHighLow64(lowerMidpointExact, significand - 1, isBoundary ? threeQuarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
swift_uint192_t powerOfTenRoundedDown;
swift_uint192_t powerOfTenRoundedUp;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Float80(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
static const int integerBits = 14;
static const int fractionBits = 192 - integerBits;
#if HAVE_UINT128_T
static const int highFractionBits = fractionBits % 64;
#else
static const int highFractionBits = fractionBits % 32;
#endif
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 153;
swift_uint192_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Narrow the interval
u = powerOfTenRoundedDown;
multiply192x128RoundingDown(&u, upperMidpointExact);
shiftRightRoundingDown192(&u, integerBits - extraBits);
l = powerOfTenRoundedUp;
multiply192x128RoundingUp(&l, lowerMidpointExact);
shiftRightRoundingUp192(&l, integerBits - extraBits);
} else {
// Widen the interval
u = powerOfTenRoundedUp;
multiply192x128RoundingUp(&u, upperMidpointExact);
shiftRightRoundingUp192(&u, integerBits - extraBits);
l = powerOfTenRoundedDown;
multiply192x128RoundingDown(&l, lowerMidpointExact);
shiftRightRoundingDown192(&l, integerBits - extraBits);
}
// Step 6: Align first digit, adjust exponent
// In particular, this prunes leading zeros from subnormals
static const uint64_t fixedPointOneHigh = (uint64_t)1 << highFractionBits;
static const uint64_t fixedPointMaskHigh = fixedPointOneHigh - 1;
swift_uint192_t t = u;
swift_uint192_t delta = u;
subtract192x192(&delta, l);
int exponent = base10Exponent + 1;
while (t.high < fixedPointOneHigh) {
exponent -= 1;
multiply192xi32(&delta, 10);
multiply192xi32(&t, 10);
}
// Step 7: Generate digits
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = (int)(t.high >> highFractionBits);
t.high &= fixedPointMaskHigh;
// Generate four digits at a time ...
swift_uint192_t d0 = delta;
swift_uint192_t t0 = t;
multiply192xi32(&d0, 10000);
multiply192xi32(&t0, 10000);
int fourDigits = (int)(t0.high >> highFractionBits);
t0.high &= fixedPointMaskHigh;
while (isLessThan192x192(d0, t0)) {
*digit_p++ = nextDigit;
int d = fourDigits / 100;
*digit_p++ = d / 10;
*digit_p++ = d % 10;
d = fourDigits % 100;
*digit_p++ = d / 10;
nextDigit = d % 10;
t = t0;
delta = d0;
multiply192xi32(&d0, 10000);
multiply192xi32(&t0, 10000);
fourDigits = (int)(t0.high >> highFractionBits);
t0.high &= fixedPointMaskHigh;
}
// Generate one digit at a time...
while (isLessThan192x192(delta, t)) {
*digit_p++ = nextDigit;
multiply192xi32(&delta, 10);
multiply192xi32(&t, 10);
nextDigit = (int)(t.high >> highFractionBits);
t.high &= fixedPointMaskHigh;
}
// Adjust the final digit to be closer to the original value
// We've already consumed most of our available precision, so it's
// okay to just work in 64 bits here...
#if HAVE_UINT128_T
uint64_t deltaHigh64 = delta.high;
uint64_t tHigh64 = t.high;
#else
uint64_t deltaHigh64 = ((uint64_t)delta.high << 32) + delta.e;
uint64_t tHigh64 = ((uint64_t)t.high << 32) + t.e;
#endif
if (deltaHigh64 > tHigh64 + ((uint64_t)1 << (fractionBits % 64))) {
uint64_t skew;
if (isBoundary) {
skew = deltaHigh64 - deltaHigh64 / 3 - tHigh64;
} else {
skew = deltaHigh64 / 2 - tHigh64;
}
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is integer + 1/2, round the last digit even
// after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit;
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
//
// ---------------- High-level API -----------------
//
// Functions that format a Float/Double/Float80
// directly into a buffer.
//
// These handle various exception cases (infinity, Nan, zero)
// before invoking the general base-10 conversion.
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
static size_t swift_format_constant(char *dest, size_t length, const char *s) {
const size_t l = strlen(s);
if (length <= l) {
return 0;
}
strcpy(dest, s);
return l;
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
size_t swift_format_float(float d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
static const int significandBitCount = 23;
uint32_t raw = bitPatternForFloat(d);
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((raw >> (significandBitCount - 1)) & 1) ? "" : "s";
uint32_t payload = raw & ((1L << (significandBitCount - 2)) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%x)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
int decimalExponent;
int8_t digits[9];
int digitCount =
swift_decompose_float(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 6) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
size_t swift_format_double(double d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
static const int significandBitCount = 52;
uint64_t raw = bitPatternForDouble(d);
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((raw >> (significandBitCount - 1)) & 1) ? "" : "s";
uint64_t payload = raw & ((1L << (significandBitCount - 2)) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%llx)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
int decimalExponent;
int8_t digits[17];
int digitCount =
swift_decompose_double(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 15) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
size_t swift_format_float80(long double d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
// Assumes Intel 80-bit extended format in LSB byte order:
uint64_t significandBitPattern = *(const uint64_t *)&d;
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((significandBitPattern >> 62) & 1) ? "" : "s";
uint64_t payload = significandBitPattern & (((uint64_t)1 << 61) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%llx)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
// Decimal numeric formatting
int decimalExponent;
int8_t digits[21];
int digitCount =
swift_decompose_float80(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 18) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
/**
* Routines to format a decomposed value into a standard string form.
*/
// Format into exponential format: "1.234e+56"
// Returns number of characters actually written to `dest`.
// Returns zero if buffer is too small.
size_t swift_format_exponential(char *dest, size_t length,
bool negative, const int8_t *digits, int digit_count, int exponent)
{
// Largest buffer we could possibly need:
size_t maximum_size = digit_count + 9;
if (length < maximum_size) {
// We only do the detailed check if the size is borderline.
size_t actual_size =
+ (negative ? 1 : 0) // Leading minus
+ digit_count // digits
+ (digit_count > 1 ? 1 : 0) // decimal
+ 1 // 'e'
+ 1 // sign
+ (exponent > 99 ? (exponent > 999 ? 4 : 3) : 2) // exponent
+ 1; // trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
}
char *p = dest;
if (negative) {
*p++ = '-';
}
*p++ = digits[0] + '0';
exponent -= 1;
if (digit_count > 1) {
*p++ = '.';
for (int i = 1; i < digit_count; i++) {
*p++ = digits[i] + '0';
}
}
*p++ = 'e';
if (exponent < 0) {
*p++ = '-';
exponent = -exponent;
} else {
*p++ = '+';
}
if (exponent > 99) {
if (exponent > 999) {
*p++ = (exponent / 1000 % 10) + '0';
}
*p++ = (exponent / 100 % 10) + '0';
exponent %= 100;
}
*p++ = (exponent / 10) + '0';
*p++ = (exponent % 10) + '0';
*p = '\0';
return p - dest;
}
// Format into decimal form: "123456789000.0", "1234.5678", "0.0000001234"
// Returns number of bytes of `dest` actually used, or zero if
// provided buffer is too small.
size_t swift_format_decimal(char *dest, size_t length,
bool negative, const int8_t *digits, int digit_count, int exponent)
{
// Largest buffer we could possibly need:
size_t maximum_size =
digit_count // All the digits
+ (exponent > 0 ? exponent : -exponent) // Max # of extra zeros
+ 4; // Max # of other items
if (length < maximum_size) {
// We only do the detailed check if the size is borderline.
if (exponent <= 0) { // "0.0000001234"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ 2 // Leading "0."
+ (-exponent) // Leading zeros after decimal point
+ digit_count
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
} else if (exponent < digit_count) { // "123.45"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ digit_count
+ 1 // embedded decimal point
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
} else { // "12345000.0"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ digit_count
+ (exponent - digit_count) // trailing zeros
+ 2 // ".0" to mark this as floating point
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
}
}
char *p = dest;
if (negative) {
*p++ = '-';
}
if (exponent <= 0) {
*p++ = '0';
*p++ = '.';
while (exponent < 0) {
*p++ = '0';
exponent += 1;
}
for (int i = 0; i < digit_count; ++i) {
*p++ = digits[i] + '0';
}
} else if (exponent < digit_count) {
for (int i = 0; i < digit_count; i++) {
if (exponent == 0) {
*p++ = '.';
}
*p++ = digits[i] + '0';
exponent -= 1;
}
} else {
for (int i = 0; i < digit_count; i++) {
*p++ = digits[i] + '0';
exponent -= 1;
}
while (exponent > 0) {
*p++ = '0';
exponent -= 1;
}
*p++ = '.';
*p++ = '0';
}
*p = '\0';
return p - dest;
}
//
// ------------ Arithmetic helpers ----------------
//
// The core algorithm relies heavily on fraction and fixed-point
// arithmetic with 64-bit, 128-bit, and 192-bit integer values. (For
// float, double, and float80, respectively.) They also need precise
// control over all rounding.
//
// Note that most arithmetic operations are the same for integers and
// fractions, so we can just use the normal integer operations in most
// places. Multiplication however, is different for fixed-size
// fractions. Integer multiplication preserves the low-order part and
// discards the high-order part (ignoring overflow). Fraction
// multiplication preserves the high-order part and discards the
// low-order part (rounding). So most of the arithmetic helpers here
// are for multiplication.
// Note: With 64-bit GCC and Clang, we get a lot of performance gain
// and code simplification by using `__uint128_t`. Otherwise, we have
// to break things down into 32-bit chunks so we don't overflow 64-bit
// temporaries.
#if SWIFT_DTOA_FLOAT_SUPPORT
// Multiply a 64-bit fraction by a 32-bit fraction, rounding down.
static uint64_t multiply64x32RoundingDown(uint64_t lhs, uint32_t rhs) {
#if HAVE_UINT128_T
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)(full >> 32);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = ((lhs & mask32) * rhs) >> 32;
return t + (lhs >> 32) * rhs;
#endif
}
// Multiply a 64-bit fraction by a 32-bit fraction, rounding up.
static uint64_t multiply64x32RoundingUp(uint64_t lhs, uint32_t rhs) {
#if HAVE_UINT128_T
static const __uint128_t roundingFactor = UINT32_MAX;
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)((full + roundingFactor) >> 32);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (((lhs & mask32) * rhs) + mask32) >> 32;
return t + (lhs >> 32) * rhs;
#endif
}
// Multiply a 64-bit fraction by a 64-bit fraction, rounding down.
static uint64_t multiply64x64RoundingDown(uint64_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)(full >> 64);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (lhs & mask32) * (rhs & mask32);
t >>= 32;
uint64_t a = (lhs >> 32) * (rhs & mask32);
uint64_t b = (lhs & mask32) * (rhs >> 32);
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
return t + (lhs >> 32) * (rhs >> 32);
#endif
}
// Multiply a 64-bit fraction by a 64-bit fraction, rounding up.
static uint64_t multiply64x64RoundingUp(uint64_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
static const __uint128_t roundingFactor = ((__uint128_t)1 << 64) - 1;
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)((full + roundingFactor) >> 64);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (lhs & mask32) * (rhs & mask32);
t = (t + mask32) >> 32;
uint64_t a = (lhs >> 32) * (rhs & mask32);
uint64_t b = (lhs & mask32) * (rhs >> 32);
t += (a & mask32) + (b & mask32);
t = (t + mask32) >> 32;
t += (a >> 32) + (b >> 32);
return t + (lhs >> 32) * (rhs >> 32);
#endif
}
// Shift a 64-bit integer right, rounding up.
static uint64_t shiftRightRoundingUp64(uint64_t lhs, int shift) {
uint64_t mask = ((uint64_t)1 << shift) - 1;
uint64_t round = ((lhs & mask) == 0) ? 0 : 1;
return (lhs >> shift) + round;
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// Multiply a 128-bit fraction by a 64-bit fraction, rounding down.
static swift_uint128_t multiply128x64RoundingDown(swift_uint128_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
uint64_t lhsl = (uint64_t)lhs;
uint64_t lhsh = (uint64_t)(lhs >> 64);
swift_uint128_t h = (swift_uint128_t)lhsh * rhs;
swift_uint128_t l = (swift_uint128_t)lhsl * rhs;
return h + (l >> 64);
#else
swift_uint128_t result;
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = (lhs.low) * rhs0;
t >>= 32;
uint64_t a = (lhs.b) * rhs0;
uint64_t b = (lhs.low) * rhs1;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.c * rhs0;
b = lhs.b * rhs1;
t += (a & mask32) + (b & mask32);
result.low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.high * rhs0;
b = lhs.c * rhs1;
t += (a & mask32) + (b & mask32);
result.b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs.high * rhs1;
result.c = t;
result.high = t >> 32;
return result;
#endif
}
// Multiply a 128-bit fraction by a 64-bit fraction, rounding up.
static swift_uint128_t multiply128x64RoundingUp(swift_uint128_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
uint64_t lhsl = (uint64_t)lhs;
uint64_t lhsh = (uint64_t)(lhs >> 64);
swift_uint128_t h = (swift_uint128_t)lhsh * rhs;
swift_uint128_t l = (swift_uint128_t)lhsl * rhs;
uint64_t remainder = (uint64_t)l;
uint64_t round = (remainder != 0) ? 1 : 0;
return h + (l >> 64) + round;
#else
swift_uint128_t result;
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = (lhs.low) * rhs0 + mask32;
t >>= 32;
uint64_t a = (lhs.b) * rhs0;
uint64_t b = (lhs.low) * rhs1;
t += (a & mask32) + (b & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.c * rhs0;
b = lhs.b * rhs1;
t += (a & mask32) + (b & mask32);
result.low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.high * rhs0;
b = lhs.c * rhs1;
t += (a & mask32) + (b & mask32);
result.b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs.high * rhs1;
result.c = t;
result.high = t >> 32;
return result;
#endif
}
#if !HAVE_UINT128_T
// Multiply a 128-bit fraction by a 32-bit integer in a 32-bit environment.
// (On 64-bit, we use a fast inline macro.)
static void multiply128xi32(swift_uint128_t *lhs, uint32_t rhs) {
uint64_t t = (uint64_t)(lhs->low) * rhs;
lhs->low = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->b) * rhs;
lhs->b = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->c) * rhs;
lhs->c = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->high) * rhs;
lhs->high = (uint32_t)t;
}
// Compare two 128-bit integers in a 32-bit environment
// (On 64-bit, we use a fast inline macro.)
static int isLessThan128x128(swift_uint128_t lhs, swift_uint128_t rhs) {
return ((lhs.high < rhs.high)
|| ((lhs.high == rhs.high)
&& ((lhs.c < rhs.c)
|| ((lhs.c == rhs.c)
&& ((lhs.b < rhs.b)
|| ((lhs.b == rhs.b)
&& (lhs.low < rhs.low)))))));
}
// Subtract 128-bit values in a 32-bit environment
static void subtract128x128(swift_uint128_t *lhs, swift_uint128_t rhs) {
uint64_t t = (uint64_t)lhs->low + (~rhs.low) + 1;
lhs->low = (uint32_t)t;
t = (t >> 32) + lhs->b + (~rhs.b);
lhs->b = (uint32_t)t;
t = (t >> 32) + lhs->c + (~rhs.c);
lhs->c = (uint32_t)t;
t = (t >> 32) + lhs->high + (~rhs.high);
lhs->high = (uint32_t)t;
}
#endif
// Shift a 128-bit integer right, rounding down.
static swift_uint128_t shiftRightRoundingDown128(swift_uint128_t lhs, int shift) {
#if HAVE_UINT128_T
return lhs >> shift;
#else
// Note: Shift is always less than 32
swift_uint128_t result;
uint64_t t = (uint64_t)lhs.low >> shift;
t += ((uint64_t)lhs.b << (32 - shift));
result.low = t;
t >>= 32;
t += ((uint64_t)lhs.c << (32 - shift));
result.b = t;
t >>= 32;
t += ((uint64_t)lhs.high << (32 - shift));
result.c = t;
t >>= 32;
result.high = t;
return result;
#endif
}
// Shift a 128-bit integer right, rounding up.
static swift_uint128_t shiftRightRoundingUp128(swift_uint128_t lhs, int shift) {
#if HAVE_UINT128_T
uint64_t bias = ((uint64_t)1 << shift) - 1;
return ((lhs + bias) >> shift);
#else
swift_uint128_t result;
const uint64_t bias = (1 << shift) - 1;
uint64_t t = ((uint64_t)lhs.low + bias) >> shift;
t += ((uint64_t)lhs.b << (32 - shift));
result.low = t;
t >>= 32;
t += ((uint64_t)lhs.c << (32 - shift));
result.b = t;
t >>= 32;
t += ((uint64_t)lhs.high << (32 - shift));
result.c = t;
t >>= 32;
result.high = t;
return result;
#endif
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// Multiply a 192-bit fraction by a 64-bit fraction, rounding down.
static void multiply192x64RoundingDown(swift_uint192_t *lhs, uint64_t rhs) {
#if HAVE_UINT128_T
// Compute the three 128-bit cross-products
__uint128_t cd = (__uint128_t)lhs->low * rhs;
__uint128_t bc = (__uint128_t)lhs->mid * rhs;
__uint128_t ab = (__uint128_t)lhs->high * rhs;
// Add up the three 64-bit outputs (including carries)
__uint128_t c = (cd >> 64) + (uint64_t)bc;
__uint128_t b = (bc >> 64) + (uint64_t)ab + (c >> 64);
__uint128_t a = (ab >> 64) + (b >> 64);
lhs->high = a;
lhs->mid = b;
lhs->low = c;
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = lhs->low * rhs0;
t >>= 32;
uint64_t a = lhs->low * rhs1;
uint64_t b = lhs->b * rhs0;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->b * rhs1;
b = lhs->c * rhs0;
t += (a & mask32) + (b & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->c * rhs1;
b = lhs->d * rhs0;
t += (a & mask32) + (b & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->d * rhs1;
b = lhs->e * rhs0;
t += (a & mask32) + (b & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->e * rhs1;
b = lhs->high * rhs0;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs->high * rhs1;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 64-bit fraction, rounding up.
static void multiply192x64RoundingUp(swift_uint192_t *lhs, uint64_t rhs) {
#if HAVE_UINT128_T
// Compute the three 128-bit cross-products
__uint128_t cd = (__uint128_t)lhs->low * rhs + UINT64_MAX;
__uint128_t bc = (__uint128_t)lhs->mid * rhs;
__uint128_t ab = (__uint128_t)lhs->high * rhs;
// Add up the three 64-bit outputs (including carries)
__uint128_t c = (cd >> 64) + (uint64_t)bc;
__uint128_t b = (bc >> 64) + (uint64_t)ab + (c >> 64);
__uint128_t a = (ab >> 64) + (b >> 64);
lhs->high = a;
lhs->mid = b;
lhs->low = c;
#else
static const uint64_t mask32 = UINT32_MAX;
static const uint64_t bias = mask32;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = lhs->low * rhs0 + bias;
t >>= 32;
uint64_t a = lhs->low * rhs1;
uint64_t b = lhs->b * rhs0;
t += (a & mask32) + (b & mask32) + bias;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->b * rhs1;
b = lhs->c * rhs0;
t += (a & mask32) + (b & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->c * rhs1;
b = lhs->d * rhs0;
t += (a & mask32) + (b & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->d * rhs1;
b = lhs->e * rhs0;
t += (a & mask32) + (b & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->e * rhs1;
b = lhs->high * rhs0;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs->high * rhs1;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 64-bit integer.
// This is used in the digit generation to multiply by ten or
// 10,000. Note that rounding never appliles here.
// As used below, this will never overflow.
static void multiply192xi32(swift_uint192_t *lhs, uint32_t rhs) {
#if HAVE_UINT128_T
__uint128_t t = (__uint128_t)lhs->low * rhs;
lhs->low = (uint64_t)t;
t = (t >> 64) + (__uint128_t)lhs->mid * rhs;
lhs->mid = (uint64_t)t;
t = (t >> 64) + (__uint128_t)lhs->high * rhs;
lhs->high = (uint64_t)t;
#else
uint64_t t = (uint64_t)lhs->low * rhs;
lhs->low = t;
t = (t >> 32) + (uint64_t)lhs->b * rhs;
lhs->b = t;
t = (t >> 32) + (uint64_t)lhs->c * rhs;
lhs->c = t;
t = (t >> 32) + (uint64_t)lhs->d * rhs;
lhs->d = t;
t = (t >> 32) + (uint64_t)lhs->e * rhs;
lhs->e = t;
t = (t >> 32) + (uint64_t)lhs->high * rhs;
lhs->high = t;
#endif
}
// Multiply a 192-bit fraction by a 128-bit fraction, rounding down.
static void multiply192x128RoundingDown(swift_uint192_t *lhs, swift_uint128_t rhs) {
#if HAVE_UINT128_T
// A full multiply of three 64-bit values by two 64-bit values
// yields five such components. We discard the bottom two (except
// for carries) to get a rounded-down three-element result.
__uint128_t current = (__uint128_t)lhs->low * (uint64_t)rhs;
current = (current >> 64);
__uint128_t t = (__uint128_t)lhs->low * (rhs >> 64);
current += (uint64_t)t;
__uint128_t next = t >> 64;
t = (__uint128_t)lhs->mid * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
current = next + (current >> 64);
t = (__uint128_t)lhs->mid * (rhs >> 64);
current += (uint64_t)t;
next = t >> 64;
t = (__uint128_t)lhs->high * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
lhs->low = (uint64_t)current;
current = next + (current >> 64);
t = (__uint128_t)lhs->high * (rhs >> 64);
current += t;
lhs->mid = (uint64_t)current;
lhs->high = (uint64_t)(current >> 64);
#else
uint64_t a, b, c, d; // temporaries
// Six 32-bit values multiplied by 4 32-bit values. Oh my.
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = lhs->low * rhs.low;
t >>= 32;
a = (uint64_t)lhs->low * rhs.b;
b = (uint64_t)lhs->b * rhs.low;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = (uint64_t)lhs->low * rhs.c;
b = (uint64_t)lhs->b * rhs.b;
c = (uint64_t)lhs->c * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->low * rhs.high;
b = (uint64_t)lhs->b * rhs.c;
c = (uint64_t)lhs->c * rhs.b;
d = (uint64_t)lhs->d * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->b * rhs.high;
b = (uint64_t)lhs->c * rhs.c;
c = (uint64_t)lhs->d * rhs.b;
d = (uint64_t)lhs->e * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->c * rhs.high;
b = (uint64_t)lhs->d * rhs.c;
c = (uint64_t)lhs->e * rhs.b;
d = (uint64_t)lhs->high * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->d * rhs.high;
b = (uint64_t)lhs->e * rhs.c;
c = (uint64_t)lhs->high * rhs.b;
t += (a & mask32) + (b & mask32) + (c & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->e * rhs.high;
b = (uint64_t)lhs->high * rhs.c;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += (uint64_t)lhs->high * rhs.high;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 128-bit fraction, rounding up.
static void multiply192x128RoundingUp(swift_uint192_t *lhs, swift_uint128_t rhs) {
#if HAVE_UINT128_T
// Same as the rounding-down version, but we add
// UINT128_MAX to the bottom two to force an extra
// carry if they are non-zero.
swift_uint128_t current = (swift_uint128_t)lhs->low * (uint64_t)rhs;
current += UINT64_MAX;
current = (current >> 64);
swift_uint128_t t = (swift_uint128_t)lhs->low * (rhs >> 64);
current += (uint64_t)t;
swift_uint128_t next = t >> 64;
t = (swift_uint128_t)lhs->mid * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
// Round up by adding UINT128_MAX (upper half)
current += UINT64_MAX;
current = next + (current >> 64);
t = (swift_uint128_t)lhs->mid * (rhs >> 64);
current += (uint64_t)t;
next = t >> 64;
t = (swift_uint128_t)lhs->high * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
lhs->low = (uint64_t)current;
current = next + (current >> 64);
t = (swift_uint128_t)lhs->high * (rhs >> 64);
current += t;
lhs->mid = (uint64_t)current;
lhs->high = (uint64_t)(current >> 64);
#else
uint64_t a, b, c, d; // temporaries
// Six 32-bit values multiplied by 4 32-bit values. Oh my.
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (uint64_t)lhs->low * rhs.low + mask32;
t >>= 32;
a = (uint64_t)lhs->low * rhs.b;
b = (uint64_t)lhs->b * rhs.low;
t += (a & mask32) + (b & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = (uint64_t)lhs->low * rhs.c;
b = (uint64_t)lhs->b * rhs.b;
c = (uint64_t)lhs->c * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->low * rhs.high;
b = (uint64_t)lhs->b * rhs.c;
c = (uint64_t)lhs->c * rhs.b;
d = (uint64_t)lhs->d * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->b * rhs.high;
b = (uint64_t)lhs->c * rhs.c;
c = (uint64_t)lhs->d * rhs.b;
d = (uint64_t)lhs->e * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->c * rhs.high;
b = (uint64_t)lhs->d * rhs.c;
c = (uint64_t)lhs->e * rhs.b;
d = (uint64_t)lhs->high * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->d * rhs.high;
b = (uint64_t)lhs->e * rhs.c;
c = (uint64_t)lhs->high * rhs.b;
t += (a & mask32) + (b & mask32) + (c & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->e * rhs.high;
b = (uint64_t)lhs->high * rhs.c;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += (uint64_t)lhs->high * rhs.high;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Subtract two 192-bit integers or fractions.
static void subtract192x192(swift_uint192_t *lhs, swift_uint192_t rhs) {
#if HAVE_UINT128_T
swift_uint128_t t = (swift_uint128_t)lhs->low + (~rhs.low) + 1;
lhs->low = t;
t = (t >> 64) + lhs->mid + (~rhs.mid);
lhs->mid = t;
lhs->high += (t >> 64) + (~rhs.high);
#else
uint64_t t = (uint64_t)lhs->low + (~rhs.low) + 1;
lhs->low = t;
t = (t >> 32) + lhs->b + (~rhs.b);
lhs->b = t;
t = (t >> 32) + lhs->c + (~rhs.c);
lhs->c = t;
t = (t >> 32) + lhs->d + (~rhs.d);
lhs->d = t;
t = (t >> 32) + lhs->e + (~rhs.e);
lhs->e = t;
lhs->high += (t >> 32) + (~rhs.high);
#endif
}
// Compare two 192-bit integers or fractions.
static int isLessThan192x192(swift_uint192_t lhs, swift_uint192_t rhs) {
#if HAVE_UINT128_T
return (lhs.high < rhs.high)
|| (lhs.high == rhs.high
&& (lhs.mid < rhs.mid
|| (lhs.mid == rhs.mid
&& lhs.low < rhs.low)));
#else
return (lhs.high < rhs.high
|| (lhs.high == rhs.high
&& (lhs.e < rhs.e
|| (lhs.e == rhs.e
&& (lhs.d < rhs.d
|| (lhs.d == rhs.d
&& (lhs.c < rhs.c
|| (lhs.c == rhs.c
&& (lhs.b < rhs.b
|| (lhs.b == rhs.b
&& (lhs.low < rhs.low)))))))))));
#endif
}
// Shift a 192-bit integer right, rounding down.
static void shiftRightRoundingDown192(swift_uint192_t *lhs, int shift) {
#if HAVE_UINT128_T
__uint128_t t = (__uint128_t)lhs->low >> shift;
t += ((__uint128_t)lhs->mid << (64 - shift));
lhs->low = t;
t >>= 64;
t += ((__uint128_t)lhs->high << (64 - shift));
lhs->mid = t;
t >>= 64;
lhs->high = t;
#else
uint64_t t = (uint64_t)lhs->low >> shift;
t += ((uint64_t)lhs->b << (32 - shift));
lhs->low = t;
t >>= 32;
t += ((uint64_t)lhs->c << (32 - shift));
lhs->b = t;
t >>= 32;
t += ((uint64_t)lhs->d << (32 - shift));
lhs->c = t;
t >>= 32;
t += ((uint64_t)lhs->e << (32 - shift));
lhs->d = t;
t >>= 32;
t += ((uint64_t)lhs->high << (32 - shift));
lhs->e = t;
t >>= 32;
lhs->high = t;
#endif
}
// Shift a 192-bit integer right, rounding up.
// Note: The shift will always be less than 20. Someday, that
// might suggest a way to further optimize this.
static void shiftRightRoundingUp192(swift_uint192_t *lhs, int shift) {
#if HAVE_UINT128_T
const uint64_t bias = (1 << shift) - 1;
__uint128_t t = ((__uint128_t)lhs->low + bias) >> shift;
t += ((__uint128_t)lhs->mid << (64 - shift));
lhs->low = t;
t >>= 64;
t += ((__uint128_t)lhs->high << (64 - shift));
lhs->mid = t;
t >>= 64;
lhs->high = t;
#else
const uint64_t bias = (1 << shift) - 1;
uint64_t t = ((uint64_t)lhs->low + bias) >> shift;
t += ((uint64_t)lhs->b << (32 - shift));
lhs->low = t;
t >>= 32;
t += ((uint64_t)lhs->c << (32 - shift));
lhs->b = t;
t >>= 32;
t += ((uint64_t)lhs->d << (32 - shift));
lhs->c = t;
t >>= 32;
t += ((uint64_t)lhs->e << (32 - shift));
lhs->d = t;
t >>= 32;
t += ((uint64_t)lhs->high << (32 - shift));
lhs->e = t;
t >>= 32;
lhs->high = t;
#endif
}
#endif
//
// ------------ Power of 10 calculation ----------------
//
//
// ------------ Power-of-10 tables. --------------------------
//
// Grisu-style algorithms rely on being able to rapidly
// find a high-precision approximation of any power of 10.
// These values were computed by a simple script that
// relied on Python's excellent variable-length
// integer support.
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
// Float table
//
// The constant powers of 10 here represent pure fractions
// with a binary point at the far left. (Each number in
// this first table is implicitly divided by 2^64.)
//
// Table size: 320 bytes
//
// A 64-bit significand allows us to exactly represent
// powers of 10 up to 10^27. For larger powers, the
// value here is rounded DOWN from the exact value.
// For those powers, the value here is less than the
// exact power of 10; adding one gives a value greater
// than the exact power of 10.
//
// For single-precision Float, we use these directly
// for positive powers of 10. For negative powers of
// ten, we multiply a value here by 10^-40.
//
// For Double and Float80, we use the 28 exact values
// here to help reduce the size of those tables.
static const uint64_t powersOf10_Float[40] = {
0x8000000000000000, // x 2^1 == 10^0 exactly
0xa000000000000000, // x 2^4 == 10^1 exactly
0xc800000000000000, // x 2^7 == 10^2 exactly
0xfa00000000000000, // x 2^10 == 10^3 exactly
0x9c40000000000000, // x 2^14 == 10^4 exactly
0xc350000000000000, // x 2^17 == 10^5 exactly
0xf424000000000000, // x 2^20 == 10^6 exactly
0x9896800000000000, // x 2^24 == 10^7 exactly
0xbebc200000000000, // x 2^27 == 10^8 exactly
0xee6b280000000000, // x 2^30 == 10^9 exactly
0x9502f90000000000, // x 2^34 == 10^10 exactly
0xba43b74000000000, // x 2^37 == 10^11 exactly
0xe8d4a51000000000, // x 2^40 == 10^12 exactly
0x9184e72a00000000, // x 2^44 == 10^13 exactly
0xb5e620f480000000, // x 2^47 == 10^14 exactly
0xe35fa931a0000000, // x 2^50 == 10^15 exactly
0x8e1bc9bf04000000, // x 2^54 == 10^16 exactly
0xb1a2bc2ec5000000, // x 2^57 == 10^17 exactly
0xde0b6b3a76400000, // x 2^60 == 10^18 exactly
0x8ac7230489e80000, // x 2^64 == 10^19 exactly
0xad78ebc5ac620000, // x 2^67 == 10^20 exactly
0xd8d726b7177a8000, // x 2^70 == 10^21 exactly
0x878678326eac9000, // x 2^74 == 10^22 exactly
0xa968163f0a57b400, // x 2^77 == 10^23 exactly
0xd3c21bcecceda100, // x 2^80 == 10^24 exactly
0x84595161401484a0, // x 2^84 == 10^25 exactly
0xa56fa5b99019a5c8, // x 2^87 == 10^26 exactly
0xcecb8f27f4200f3a, // x 2^90 == 10^27 exactly
0x813f3978f8940984, // x 2^94 ~= 10^28
0xa18f07d736b90be5, // x 2^97 ~= 10^29
0xc9f2c9cd04674ede, // x 2^100 ~= 10^30
0xfc6f7c4045812296, // x 2^103 ~= 10^31
0x9dc5ada82b70b59d, // x 2^107 ~= 10^32
0xc5371912364ce305, // x 2^110 ~= 10^33
0xf684df56c3e01bc6, // x 2^113 ~= 10^34
0x9a130b963a6c115c, // x 2^117 ~= 10^35
0xc097ce7bc90715b3, // x 2^120 ~= 10^36
0xf0bdc21abb48db20, // x 2^123 ~= 10^37
0x96769950b50d88f4, // x 2^127 ~= 10^38
0xbc143fa4e250eb31, // x 2^130 ~= 10^39
};
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// As above, but with 128-bit fractions.
//
// Table size: 464 bytes
//
// We only store every 28th power of ten here.
// We can multiply by an exact 64-bit power of
// ten from the table above to reconstruct the
// significand for any power of 10.
static const uint64_t powersOf10_Double[] = {
// low-order half, high-order half
0x3931b850df08e738, 0x95fe7e07c91efafa, // x 2^-1328 ~= 10^-400
0xba954f8e758fecb3, 0x9774919ef68662a3, // x 2^-1235 ~= 10^-372
0x9028bed2939a635c, 0x98ee4a22ecf3188b, // x 2^-1142 ~= 10^-344
0x47b233c92125366e, 0x9a6bb0aa55653b2d, // x 2^-1049 ~= 10^-316
0x4ee367f9430aec32, 0x9becce62836ac577, // x 2^-956 ~= 10^-288
0x6f773fc3603db4a9, 0x9d71ac8fada6c9b5, // x 2^-863 ~= 10^-260
0xc47bc5014a1a6daf, 0x9efa548d26e5a6e1, // x 2^-770 ~= 10^-232
0x80e8a40eccd228a4, 0xa086cfcd97bf97f3, // x 2^-677 ~= 10^-204
0xb8ada00e5a506a7c, 0xa21727db38cb002f, // x 2^-584 ~= 10^-176
0xc13e60d0d2e0ebba, 0xa3ab66580d5fdaf5, // x 2^-491 ~= 10^-148
0xc2974eb4ee658828, 0xa54394fe1eedb8fe, // x 2^-398 ~= 10^-120
0xcb4ccd500f6bb952, 0xa6dfbd9fb8e5b88e, // x 2^-305 ~= 10^-92
0x3f2398d747b36224, 0xa87fea27a539e9a5, // x 2^-212 ~= 10^-64
0xdde50bd1d5d0b9e9, 0xaa242499697392d2, // x 2^-119 ~= 10^-36
0xfdc20d2b36ba7c3d, 0xabcc77118461cefc, // x 2^-26 ~= 10^-8
0x0000000000000000, 0xad78ebc5ac620000, // x 2^67 == 10^20 exactly
0x9670b12b7f410000, 0xaf298d050e4395d6, // x 2^160 == 10^48 exactly
0x3b25a55f43294bcb, 0xb0de65388cc8ada8, // x 2^253 ~= 10^76
0x58edec91ec2cb657, 0xb2977ee300c50fe7, // x 2^346 ~= 10^104
0x29babe4598c311fb, 0xb454e4a179dd1877, // x 2^439 ~= 10^132
0x577b986b314d6009, 0xb616a12b7fe617aa, // x 2^532 ~= 10^160
0x0c11ed6d538aeb2f, 0xb7dcbf5354e9bece, // x 2^625 ~= 10^188
0x6d953e2bd7173692, 0xb9a74a0637ce2ee1, // x 2^718 ~= 10^216
0x9d6d1ad41abe37f1, 0xbb764c4ca7a4440f, // x 2^811 ~= 10^244
0x4b2d8644d8a74e18, 0xbd49d14aa79dbc82, // x 2^904 ~= 10^272
0xe0470a63e6bd56c3, 0xbf21e44003acdd2c, // x 2^997 ~= 10^300
0x505f522e53053ff2, 0xc0fe908895cf3b44, // x 2^1090 ~= 10^328
0xcca845ab2beafa9a, 0xc2dfe19c8c055535, // x 2^1183 ~= 10^356
0x1027fff56784f444, 0xc4c5e310aef8aa17, // x 2^1276 ~= 10^384
};
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// Every 83rd power of 10 across the range of Float80
//
// Table size: 2,928 bytes
//
// Note: We could cut this in half at the cost of one additional
// 192-bit multiply by only storing the positive values and
// multiplying by 10^-5063 to obtain the negative ones, similar
// to how we handle Float above.
static const uint64_t powersOf10_Float80[] = {
// low 64 bits, middle 64 bits, high 64 bits
0x56825ada98468526, 0x0abc23fcfda07e29, 0x871db786569ca2dd, // x 2^-16818 ~= 10^-5063
0xe3885beff5ee930d, 0xd1e638f68c97f0e5, 0xde90d1b113564507, // x 2^-16543 ~= 10^-4980
0x5a7d22b5236bcad4, 0xbab3a28a6f0a489c, 0xb74ea21ab2946479, // x 2^-16267 ~= 10^-4897
0x7d1f78bf0f4e2878, 0xcf4aea39615ffe6e, 0x96f9351fcfdd2686, // x 2^-15991 ~= 10^-4814
0xad725c0d6c214314, 0x5bd5c19f18bd2857, 0xf8afafd6ef185238, // x 2^-15716 ~= 10^-4731
0xe418e9217ce83755, 0x801e38463183fc88, 0xccd1ffc6bba63e21, // x 2^-15440 ~= 10^-4648
0x4dcd52747e029d0c, 0x867b3096b1619df8, 0xa8b11ff4721d92fb, // x 2^-15164 ~= 10^-4565
0xed2903f7e1df2b78, 0xc846664fe1364ee8, 0x8aefaaae9060380f, // x 2^-14888 ~= 10^-4482
0xed7a7f4e1e171498, 0x7da1a627b88527f1, 0xe4dbb751faa311b0, // x 2^-14613 ~= 10^-4399
0x320796dc9b1a158c, 0x2a11a871597b8012, 0xbc7d620092481a7e, // x 2^-14337 ~= 10^-4316
0x796014ec6f4c0dcb, 0xcfa99f62903708d7, 0x9b3dee433c1311e9, // x 2^-14061 ~= 10^-4233
0x08920ae76bdb8282, 0x952b06c385a08ff6, 0xffb7a402531fd4c9, // x 2^-13786 ~= 10^-4150
0x18faa162f2c4d6b9, 0x050be8c5d21c6db6, 0xd29c7528965ae5bd, // x 2^-13510 ~= 10^-4067
0x576a6c1abab7f7e7, 0xc05fb0b5c550f28d, 0xad7617610634129e, // x 2^-13234 ~= 10^-3984
0x6cc3b2fb9cae4875, 0xe1bd5b09b7202157, 0x8edd4417ae3dc210, // x 2^-12958 ~= 10^-3901
0xfafc1dc8fd12a6f8, 0xc3f29d230036529b, 0xeb542860da9bc7d8, // x 2^-12683 ~= 10^-3818
0x9d198c56bc799f35, 0x42960adf9591f02a, 0xc1d1a4b6bc2eafc8, // x 2^-12407 ~= 10^-3735
0x1803d096e43ff4bc, 0xdef9759d6432dab7, 0x9fa18c5de65a16fb, // x 2^-12131 ~= 10^-3652
0x74872779576a577c, 0x9150140eb5101a96, 0x83793dfc83fd2f9b, // x 2^-11855 ~= 10^-3569
0x415d0667f0f88262, 0x4898d98d1314d99f, 0xd890d45a257f4644, // x 2^-11580 ~= 10^-3486
0x30a5256a610c1c72, 0x6ebca4d0365d504d, 0xb25d93f98145bdab, // x 2^-11304 ~= 10^-3403
0xfb149b1f86a46376, 0xb5143323a7f8e16c, 0x92e74be10524c389, // x 2^-11028 ~= 10^-3320
0x7b7532e25fead4c8, 0x0df6ab8ac6a0ec2f, 0xf1fb6e82e4df4a77, // x 2^-10753 ~= 10^-3237
0x3b738d6a3caae67a, 0x346b2dd31826cfed, 0xc74c79bce7fe949f, // x 2^-10477 ~= 10^-3154
0x22d3a12777cee527, 0xe185ac46f6ef1993, 0xa424ef0bb5ad3129, // x 2^-10201 ~= 10^-3071
0xb7b6bccb9f60adec, 0x30ad7df78fe30cc8, 0x8730d40821cd89f3, // x 2^-9925 ~= 10^-2988
0x21049149d72d44d5, 0x1e86debc54dd290d, 0xdeb04cb82aec22cb, // x 2^-9650 ~= 10^-2905
0xeb69d287f5e7f920, 0x8d7e84a13801d034, 0xb7688f9800d26b3a, // x 2^-9374 ~= 10^-2822
0x47b3da9aeff7df71, 0x82678774d6c0ac59, 0x970e8fd25ead01e3, // x 2^-9098 ~= 10^-2739
0x50d3e92e2e4f8210, 0x9492db3d978aaca8, 0xf8d2dcaf37504b51, // x 2^-8823 ~= 10^-2656
0xf4ce72058f777a4c, 0xb9eb2c585e924efe, 0xcceef83fdedcc506, // x 2^-8547 ~= 10^-2573
0xb0e624a35b791884, 0x7104a98dbbb38b94, 0xa8c8fc3b03c3d1ed, // x 2^-8271 ~= 10^-2490
0x6c94ecd8291e2ac9, 0x978b03821014b68c, 0x8b03518396007c08, // x 2^-7995 ~= 10^-2407
0x96475208daa03ee3, 0x10eaa1481b149e5a, 0xe4fc163319551441, // x 2^-7720 ~= 10^-2324
0xd709a820ff4ac847, 0x75aab7cb5cb15414, 0xbc980b270680156a, // x 2^-7444 ~= 10^-2241
0xf273bca6b4de9e24, 0xb5025d88d4b252e1, 0x9b53e384eccabcf7, // x 2^-7168 ~= 10^-2158
0x6c55a0603a928f40, 0x9e20db16dfb6b461, 0xffdbcf7251089796, // x 2^-6893 ~= 10^-2075
0x9006db4d43cffe42, 0x9b4bca4cd6cec2db, 0xd2ba3f510a3aa638, // x 2^-6617 ~= 10^-1992
0xa6b3c457fd0cd4d6, 0x28a4de91ba868fbf, 0xad8ea05a5f27642a, // x 2^-6341 ~= 10^-1909
0xe7b14ed140f8d98e, 0x7b2f7d61ce5d426c, 0x8ef179291b6f5424, // x 2^-6065 ~= 10^-1826
0x4a964d052fd03e10, 0x06897060bf491e6e, 0xeb75718d285cd8bf, // x 2^-5790 ~= 10^-1743
0x22b2270f0e8dd87c, 0xa8510fa2f5a9e4de, 0xc1ed0ed498f7c54c, // x 2^-5514 ~= 10^-1660
0x09102915726a9905, 0x5a0eb896edc89b54, 0x9fb8208d65ea5eda, // x 2^-5238 ~= 10^-1577
0xb80d5f481d01deb9, 0x673f2aa50486f5ba, 0x838bd699b7c539e6, // x 2^-4962 ~= 10^-1494
0x668b62b20ec2633b, 0x8682604c7123f859, 0xd8af761f94d2db2c, // x 2^-4687 ~= 10^-1411
0xb2adaed8559cc199, 0x712339ba54f12372, 0xb276ce87987995d5, // x 2^-4411 ~= 10^-1328
0x6beb873308685711, 0xac1ce34246ed56ad, 0x92fc133455668c02, // x 2^-4135 ~= 10^-1245
0x593293d68a2261bc, 0x3c368f9497ca075d, 0xf21da89a29fa1c61, // x 2^-3860 ~= 10^-1162
0x854051f9f0e4ca66, 0x8c5d5a234eda57f7, 0xc768aa46d6d1b675, // x 2^-3584 ~= 10^-1079
0x333d09b2299c5e6b, 0xcf1f49c33399c5ac, 0xa43c26a751d4f7e7, // x 2^-3308 ~= 10^-996
0x25a440d8b1620532, 0x274ebc67c3e21943, 0x8743f33df0feed29, // x 2^-3032 ~= 10^-913
0x3ca95e3deb5be648, 0x52d18ccca1c558c2, 0xdecfcc3329238dd8, // x 2^-2757 ~= 10^-830
0x59d1a7704af3acd7, 0xfae7722c6af19467, 0xb78280c024488353, // x 2^-2481 ~= 10^-747
0x78813f3e80148049, 0x73b2baf13aa1c233, 0x9723ed8a28baf5ac, // x 2^-2205 ~= 10^-664
0xf296a8198aa40fb8, 0x235532b08487fe6a, 0xf8f60e812de0cd7d, // x 2^-1930 ~= 10^-581
0xa7fbdcb40b4f648f, 0x4f20ba9a64a7f6e7, 0xcd0bf4d206072167, // x 2^-1654 ~= 10^-498
0x8dbf63ea468c724f, 0xa0e25c08b5c189d6, 0xa8e0dbe18ffb82cf, // x 2^-1378 ~= 10^-415
0x765995c6cfd406ce, 0x4c3bcb5021afcc31, 0x8b16fb203055ac76, // x 2^-1102 ~= 10^-332
0xe1d09ab6fb409872, 0x82b7e12780e7401a, 0xe51c79a85916f484, // x 2^-827 ~= 10^-249
0x89cbe2422f9e1df9, 0x7415d448f6b6f0e7, 0xbcb2b812db11a5de, // x 2^-551 ~= 10^-166
0x605fe83842e4d290, 0xc986afbe3ee11aba, 0x9b69dbe1b548ce7c, // x 2^-275 ~= 10^-83
0x0000000000000000, 0x0000000000000000, 0x8000000000000000, // x 2^1 == 10^0 exactly
0x0d6953169e1c7a1e, 0xf50a3fa490c30190, 0xd2d80db02aabd62b, // x 2^276 ~= 10^83
0x3720b80c7d8ee39d, 0xaf561aa79a10ae6a, 0xada72ccc20054ae9, // x 2^552 ~= 10^166
0x7cb3f026a212df74, 0x29cb4d87f2a7400e, 0x8f05b1163ba6832d, // x 2^828 ~= 10^249
0x7dda22f9451d28a4, 0xe41c5bd18c57e88f, 0xeb96bf6ebadf77d8, // x 2^1103 ~= 10^332
0xd5da00e6e2d05e5d, 0x5e510c5a752f0f8e, 0xc2087cd3215a16ad, // x 2^1379 ~= 10^415
0x5603ba353e0b2fac, 0x48bbddc4d7359e49, 0x9fceb7ee780436f0, // x 2^1655 ~= 10^498
0x15ceea8df15e47c7, 0x6a83c85cf158c652, 0x839e71d847c1779e, // x 2^1931 ~= 10^581
0x514478d1fcd48eea, 0x3a4181cdda0d6e24, 0xd8ce1c3a2fffaea7, // x 2^2206 ~= 10^664
0xe8b634620f1062be, 0x7304c7fb8a2f8a8a, 0xb2900ca735bdf121, // x 2^2482 ~= 10^747
0xc3ec2fd9302c9bda, 0x729a6a7e830e1cf2, 0x9310dd78089bd66f, // x 2^2758 ~= 10^830
0x1750ef5f751be079, 0x52ccabc96fc88a23, 0xf23fe788c763dffa, // x 2^3033 ~= 10^913
0xaa80925ec1c80b65, 0x97681c548ff6c12f, 0xc784decd820a6180, // x 2^3309 ~= 10^996
0xb4212d4b435a2317, 0x8df0a55abbb2c99a, 0xa453618b9dfd92db, // x 2^3585 ~= 10^1079
0x939c2fedd434642a, 0x7d7de34bf5aa96b4, 0x875715282612729b, // x 2^3861 ~= 10^1162
0xb7d9a0e46bbebb36, 0x3b2057dea52d686b, 0xdeef5022af37f1f6, // x 2^4136 ~= 10^1245
0x931a74148ea64e59, 0xfe7fe67bd1074d0c, 0xb79c7593a1c17df0, // x 2^4412 ~= 10^1328
0xabd20df0f1f1ad54, 0x0fff83cc7fa6b77b, 0x97394e479b6573b1, // x 2^4688 ~= 10^1411
0x25f2467421674b7a, 0x828ff55a248bc026, 0xf919454d86f16685, // x 2^4963 ~= 10^1494
0xe32dbd7131e6ab7d, 0xf674dd4821982084, 0xcd28f57dc585d094, // x 2^5239 ~= 10^1577
0x866ab816a532b07d, 0xdc567471f9639b4e, 0xa8f8bee890f905c7, // x 2^5515 ~= 10^1660
0xaca3a975993a2626, 0xc41cf207a71d87e4, 0x8b2aa784c405e2f1, // x 2^5791 ~= 10^1743
0x731f0b7d820918bd, 0x355fde18e8448607, 0xe53ce1b25fb31788, // x 2^6066 ~= 10^1826
0x0be7c29568db3f20, 0xc1328a3f1bf4d2b8, 0xbccd68c49888be61, // x 2^6342 ~= 10^1909
0x9c6e0b1b927b7d3f, 0xffc9b96619da642a, 0x9b7fd75a060350cd, // x 2^6618 ~= 10^1992
0x2a84c8fb4bd2edc9, 0xa679df45d339389b, 0x80121ad60ca2c518, // x 2^6894 ~= 10^2075
0x0d4648d0876cf1c3, 0x48c67661c087fb5a, 0xd2f5e0469040e0eb, // x 2^7169 ~= 10^2158
0xfe2d99a281a011ac, 0x65c13361e6b2c078, 0xadbfbcb6c676a69b, // x 2^7445 ~= 10^2241
0xf4ec157aa4147562, 0xac89bfa5e79484a6, 0x8f19ebdf7661e3e9, // x 2^7721 ~= 10^2324
0xe945f8c80090be1f, 0x9b8672e64aadbed2, 0xebb812063c9e01db, // x 2^7996 ~= 10^2407
0xca12d8ad3b36d2e4, 0xd252322ea50ad274, 0xc223eeb2e1bde452, // x 2^8272 ~= 10^2490
0xf554fb41e5b3e384, 0x977acb4d4af624fc, 0x9fe55281904ba38b, // x 2^8548 ~= 10^2573
0xf3f69093398e2573, 0x111ae5735ec0e878, 0x83b10fb893300cde, // x 2^8824 ~= 10^2656
0x30f65a8da0d10429, 0x1eecf4cf8a0b25f5, 0xd8ecc6aa93e876fc, // x 2^9099 ~= 10^2739
0xa577f5f0c9f1e5a7, 0x91a5430ed623abf0, 0xb2a94e58da4930c3, // x 2^9375 ~= 10^2822
0x202d2f87585ec0d7, 0x7a63589863efd480, 0x9325aaac89304b57, // x 2^9651 ~= 10^2905
0x049544fbba3c01a1, 0x53accb0f60ac6095, 0xf2622b4f6c68d6ce, // x 2^9926 ~= 10^2988
0x268a0d5f9d5ce861, 0xfe40703e1a91de57, 0xc7a117517a09153b, // x 2^10202 ~= 10^3071
0xb6cd470a2a3b1d63, 0x5f963916b20ea587, 0xa46a9fb9111003bc, // x 2^10478 ~= 10^3154
0xa3101c09fd8e6e96, 0xa2c6328011db5211, 0x876a39c722f798a7, // x 2^10754 ~= 10^3237
0x8507e5fdb0ec5d83, 0x7ce93cc7f8feeed4, 0xdf0ed8875e7b8914, // x 2^11029 ~= 10^3320
0xe19b7ebe4c7bfbca, 0x40930d1129943838, 0xb7b66e12fe1af499, // x 2^11305 ~= 10^3403
0xc90c4ec15c21a357, 0xd91c86512d147305, 0x974eb20b241a65f6, // x 2^11581 ~= 10^3486
0xb90341199c02a4eb, 0x69e684f53db6e8ce, 0xf93c8114f6c31f8a, // x 2^11856 ~= 10^3569
0xa873f1318cef91cb, 0xbf8718466b31a7ca, 0xcd45fa43b1ce4c8e, // x 2^12132 ~= 10^3652
0xacfe0dcc5262e273, 0x6e1bbb68662fd27a, 0xa910a550810203f8, // x 2^12408 ~= 10^3735
0x59e7c8921bbe3758, 0x834743c5eab7dcea, 0x8b3e56b1b5c57589, // x 2^12684 ~= 10^3818
0x145eed64fda2e6af, 0x1c605bdcc764238f, 0xe55d4e51d30b5592, // x 2^12959 ~= 10^3901
0xb747164b17268ea2, 0xd8aa19f1d85da07d, 0xbce81d3cc784a1ca, // x 2^13235 ~= 10^3984
0x3666af1cb2f0356b, 0xc8dd55687a68bb70, 0x9b95d5ee4f80366d, // x 2^13511 ~= 10^4067
0x70d67261b5bde1e9, 0x1d76f2d15166ec20, 0x8024383bab19730d, // x 2^13787 ~= 10^4150
0x084a3ba0b748546a, 0xc67f9026f83dca47, 0xd313b714d3a1c65e, // x 2^14062 ~= 10^4233
0x4411a8127eea085e, 0x441eb397ffcdab0d, 0xadd8501ad0361d15, // x 2^14338 ~= 10^4316
0x7b62a54ed6233032, 0x75458a1c8300e014, 0x8f2e2985332eae98, // x 2^14614 ~= 10^4399
0x162d5b51a1dd9594, 0x655bb1b7aa4e8196, 0xebd96954582af06f, // x 2^14889 ~= 10^4482
0x55e6c62f920d3682, 0x79fd57cf7c37941c, 0xc23f6474669f4abe, // x 2^15165 ~= 10^4565
0x19482fa0ac45669c, 0x803c1cd864033781, 0x9ffbf04722750449, // x 2^15441 ~= 10^4648
0xa412d1f95f4624cd, 0xc95abe9ce589e048, 0x83c3b03af95c9674, // x 2^15717 ~= 10^4731
0xc1207e487c57b4e1, 0xf93dd2c7669a8ed1, 0xd90b75715d861b38, // x 2^15992 ~= 10^4814
0xeb20d9a25e0372bd, 0xb5073df6adc221b4, 0xb2c2939d0763fcac, // x 2^16268 ~= 10^4897
0x1a648c339e28cc45, 0xbd14f0fa3e24b6ae, 0x933a7ad2419ea0b5, // x 2^16544 ~= 10^4980
};
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
// The power-of-10 tables do not directly store the associated binary
// exponent. That's because the binary exponent is a simple linear
// function of the decimal power (and vice versa), so it's just as
// fast (and uses much less memory) to compute it:
// The binary exponent corresponding to a particular power of 10.
// This matches the power-of-10 tables across the full range of Float80.
static int binaryExponentFor10ToThe(int p) {
return (int)(((((int64_t)p) * 55732705) >> 24) + 1);
}
// A decimal exponent that approximates a particular binary power.
static int decimalExponentFor2ToThe(int e) {
return (int)(((int64_t)e * 20201781) >> 26);
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
// Given a power `p`, this returns three values:
// * 64-bit fractions `lower` and `upper`
// * integer `exponent`
//
// The returned values satisty the following:
// ```
// lower * 2^exponent <= 10^p <= upper * 2^exponent
// ```
//
// In particular, if `10^p` can be exactly represented, this routine
// may return the same value for `lower` and `upper`.
//
static void intervalContainingPowerOf10_Float(int p, uint64_t *lower, uint64_t *upper, int *exponent) {
if (p < 0) {
uint64_t base = powersOf10_Float[p + 40];
int baseExponent = binaryExponentFor10ToThe(p + 40);
uint64_t tenToTheMinus40 = 0x8b61313bbabce2c6; // x 2^-132 ~= 10^-40
*lower = multiply64x64RoundingDown(base, tenToTheMinus40);
*upper = multiply64x64RoundingUp(base + 1, tenToTheMinus40 + 1);
*exponent = baseExponent - 132;
} else if (p <= 27) {
uint64_t exact = powersOf10_Float[p];
*upper = exact;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
} else {
uint64_t exact = powersOf10_Float[p];
*upper = exact + 1;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
}
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// As above, but returning 128-bit fractions suitable for
// converting doubles.
static void intervalContainingPowerOf10_Double(int p, swift_uint128_t *lower, swift_uint128_t *upper, int *exponent) {
if (p >= 0 && p <= 54) {
if (p <= 27) {
// Use one 64-bit exact value
swift_uint128_t exact;
initialize128WithHigh64(exact, powersOf10_Float[p]);
*upper = exact;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
return;
} else {
// Multiply two 64-bit exact values to get a 128-bit exact value
swift_uint128_t base;
initialize128WithHigh64(base, powersOf10_Float[p - 27]);
int baseExponent = binaryExponentFor10ToThe(p - 27);
uint64_t extra = powersOf10_Float[27];
int extraExponent = binaryExponentFor10ToThe(27);
swift_uint128_t exact = multiply128x64RoundingDown(base, extra);
*upper = exact;
*lower = exact;
*exponent = baseExponent + extraExponent;
return;
}
}
// Multiply a 128-bit approximate value with a 64-bit exact value
int index = p + 400;
// Copy a pair of uint64_t into a swift_uint128_t
const uint64_t *base_p = powersOf10_Double + (index / 28) * 2;
swift_uint128_t base;
initialize128WithHighLow64(base, base_p[1], base_p[0]);
int extraPower = index % 28;
int baseExponent = binaryExponentFor10ToThe(p - extraPower);
int e = baseExponent;
if (extraPower > 0) {
int64_t extra = powersOf10_Float[extraPower];
e += binaryExponentFor10ToThe(extraPower);
*lower = multiply128x64RoundingDown(base, extra);
increment128(base);
*upper = multiply128x64RoundingUp(base, extra);
} else {
*lower = base;
increment128(base);
*upper = base;
}
*exponent = e;
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// As above, but returning 192-bit fractions suitable for
// converting float80.
static void intervalContainingPowerOf10_Float80(int p, swift_uint192_t *lower, swift_uint192_t *upper, int *exponent) {
if (p >= 0 && p <= 27) {
// We have an exact form, return a zero-width interval.
uint64_t exact = powersOf10_Float[p];
initialize192WithHighMidLow64(*upper, exact, 0, 0);
initialize192WithHighMidLow64(*lower, exact, 0, 0);
*exponent = binaryExponentFor10ToThe(p);
return;
}
int index = p + 5063;
const uint64_t *base_p = powersOf10_Float80 + (index / 83) * 3;
// Note: The low-order value in the Float80 table above
// is never UINT64_MAX, so there's never a carry from
// the increment here.
initialize192WithHighMidLow64(*upper, base_p[2], base_p[1], base_p[0] + 1);
initialize192WithHighMidLow64(*lower, base_p[2], base_p[1], base_p[0]);
int extraPower = index % 83;
int e = binaryExponentFor10ToThe(p - extraPower);
while (extraPower > 27) {
uint64_t power27 = powersOf10_Float[27];
multiply192x64RoundingDown(lower, power27);
multiply192x64RoundingUp(upper, power27);
e += binaryExponentFor10ToThe(27);
extraPower -= 27;
}
if (extraPower > 0) {
uint64_t extra = powersOf10_Float[extraPower];
multiply192x64RoundingDown(lower, extra);
multiply192x64RoundingUp(upper, extra);
e += binaryExponentFor10ToThe(extraPower);
}
*exponent = e;
}
#endif
runtime: avoid UB on Windows x86_64 builds
Use the `ull` extension rather than `l` for LLP64 environment support.
Fixes UB on the Windows x86_64 port.
//===--- SwiftDtoa.c ---------------------------------------------*- c -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===---------------------------------------------------------------------===//
//
// Note: This is really a C file, but Swift's build system for Linux is
// partially allergic to C, so it's being compiled as ".cpp" for now. Please
// don't infect it with C++-isms.
//
///
/// The core algorithm here (see `swift_decompose_double` below) is a
/// modified form of the Grisu2 algorithm from Florian Loitsch;
/// "Printing Floating-Point Numbers Quickly and Accurately with
/// Integers", 2010. https://dl.acm.org/citation.cfm?id=1806623
///
/// This includes some improvements suggested by the "Errol paper":
/// Marc Andrysco, Ranjit Jhala, Sorin Lerner; "Printing
/// Floating-Point Numbers: A Faster, Always Correct Method", 2016.
/// https://dl.acm.org/citation.cfm?id=2837654
///
/// The following summary assumes you're familiar with Grisu-style
/// algorithms in general:
///
/// Loitsch' original Grisu2 implementation guarantees round-trip
/// accuracy but only generates the shortest decimal expansion about 99%
/// of the time. Grisu3 addresses this by essentially running two
/// copies of Grisu2 in parallel: one copy biased to avoid inaccuracy,
/// the other biased to avoid generating excess digits. If they agree,
/// then the result must be both accurate and short. But if they
/// disagree, then Grisu3 gives up and must defer to another algorithm.
///
/// The Errol paper provides a deeper analysis of the cases where
/// Grisu2 fails to find the shortest decimal expansion. There
/// are two root causes of such failures:
///
/// * Insufficient precision leads to scattered failures across the
/// entire range. Theorem 7 in the Errol paper shows a way to
/// construct a superset of the numbers subject to such failures.
/// With this list, we can simply test whether we have sufficient
/// precision.
///
/// For Double, the Errol3 algorithm uses double-double arithmetic
/// with about 106 bits precision. This turns out to be not quite
/// sufficient, requiring Errol3 to pre-screen the input against a
/// list of exceptions culled from the larger list of possible
/// failures. Using high-precision integers, we've discovered that
/// 110 bit precision is sufficient to satisfy the Errol test cases
/// without requiring any pre-screening.
///
/// For Float and Float80, the same approach shows that we need 53
/// and 135 bits, respectively. It is an interesting coincidence
/// that for all three cases, an n-bit significand can be formatted
/// optimally with no more than 2n+7 bits of intermediate precision.
///
/// * For numbers with even significands and a specific range of
/// exponents, the shortest value might occur exactly at the midpoint
/// between two adjacent binary floating-point values. Theorem 6 of
/// the Errol paper characterizes this sufficiently to allow us to
/// vary our strategy. Errol3 uses a separate formatter for this
/// case. This implementation instead widens the interval (as in
/// Grisu3), which allows us to use the same fast digit generation in
/// all cases, providing uniform performance across the entire range.
///
/// In addition to addressing the shortness failures characterized in
/// the Errol paper, the implementation here also incorporates
/// final-digit corrections from Grisu3, allowing it to produce the
/// optimal decimal decomposition in all cases.
///
/// In summary, this implementation is:
///
/// * Fast. It uses only fixed-width integer arithmetic and has
/// constant memory requirements.
///
/// * Simple. It is only a little more complex than Loitsch' original
/// implementation of Grisu2. The full digit decomposition for double
/// is less than 300 lines of standard C.
///
/// * Always Accurate. Converting the decimal form back to binary
/// will always yield exactly the same value. For the IEEE 754
/// formats, the round-trip will produce exactly the same bit
/// pattern in memory.
///
/// * Always Short. This always selects an accurate result with the
/// minimum number of decimal digits.
///
/// * Always Close. Among all accurate, short results, this always
/// chooses the result that is closest to the exact floating-point
/// value. (In case of an exact tie, it rounds the last digit even.)
///
/// For single-precision Float, these claims have been exhaustively
/// tested -- all 2^32 values can be checked in under an hour on a
/// mid-range modern laptop. The Double and Float80 formatters rely on
/// results from the Errol paper to ensure correctness. In addition,
/// we have verified more than 10^13 randomly-chosen values by comparing
/// the results to the output of Errol4.
///
// ----------------------------------------------------------------------------
#include <float.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "swift/Runtime/SwiftDtoa.h"
#if defined(__SIZEOF_INT128__)
// We get a significant speed boost if we can use the __uint128_t
// type that's present in GCC and Clang on 64-bit architectures. In
// particular, we can do 128-bit arithmetic directly and can
// represent 192-bit integers as a collection of 64-bit elements.
#define HAVE_UINT128_T 1
#else
// On 32-bit, we have to use slower code that manipulates 128-bit
// and 192-bit integers as collections of 32-bit elements.
#define HAVE_UINT128_T 0
#endif
// Try to verify that the system floating-point types really are what we
// expect. Note that the code below is specific to these exact
// floating-point representations.
#if (FLT_RADIX != 2)
// Either you're using hexadecimal float format on S390, or you have a
// really broken C environment.
#error "This platform claims to not use binary floating point."
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
#if (FLT_MANT_DIG != 24) || (FLT_MIN_EXP != -125) || (FLT_MAX_EXP != 128)
#error "Are you certain `float` on this platform is really IEEE 754 single-precision binary32 format?"
#endif
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
#if (DBL_MANT_DIG != 53) || (DBL_MIN_EXP != -1021) || (DBL_MAX_EXP != 1024)
#error "Are you certain `double` on this platform is really IEEE 754 double-precision binary64 format?"
#endif
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
#if (LDBL_MANT_DIG != 64) || (LDBL_MIN_EXP != -16381) || (LDBL_MAX_EXP != 16384)
#error "Are you certain `long double` on this platform is really Intel 80-bit extended precision?"
#endif
#endif
// See the implementations at the bottom of this file for detailed explanations
// of the purpose of each function.
//
// Helper functions used by float, double, and float80 machinery.
//
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
#if HAVE_UINT128_T
typedef __uint128_t swift_uint128_t;
#define initialize128WithHighLow64(dest, high64, low64) ((dest) = ((__uint128_t)(high64) << 64) | (low64))
#else
typedef struct {
uint32_t low, b, c, high;
} swift_uint128_t;
#define initialize128WithHighLow64(dest, high64, low64) \
((dest).low = (uint32_t)(low64), \
(dest).b = (uint32_t)((low64) >> 32), \
(dest).c = (uint32_t)(high64), \
(dest).high = (uint32_t)((high64) >> 32))
#endif
static int binaryExponentFor10ToThe(int p);
static int decimalExponentFor2ToThe(int e);
#endif
//
// Helper functions used only by the single-precision float formatter
//
#if SWIFT_DTOA_FLOAT_SUPPORT
static uint64_t multiply64x32RoundingDown(uint64_t lhs, uint32_t rhs);
static uint64_t multiply64x32RoundingUp(uint64_t lhs, uint32_t rhs);
static uint64_t multiply64x64RoundingDown(uint64_t lhs, uint64_t rhs);
static uint64_t multiply64x64RoundingUp(uint64_t lhs, uint64_t rhs);
static uint64_t shiftRightRoundingUp64(uint64_t lhs, int shift);
static void intervalContainingPowerOf10_Float(int p, uint64_t *lower, uint64_t *upper, int *exponent);
#endif
//
// Helper functions used only by the double-precision formatter
//
#if SWIFT_DTOA_DOUBLE_SUPPORT
#if HAVE_UINT128_T
#define increment128(dest) ((dest) += 1)
#define isLessThan128x128(lhs, rhs) ((lhs) < (rhs))
#define subtract128x128(lhs, rhs) (*(lhs) -= (rhs))
#define multiply128xi32(lhs, rhs) (*(lhs) *= (rhs))
#define initialize128WithHigh64(dest, value) ((dest) = (__uint128_t)(value) << 64)
#define extractHigh64From128(arg) ((uint64_t)((arg) >> 64))
static int extractIntegerPart128(__uint128_t *fixed128, int fractionBits) {
return (int)(*fixed128 >> fractionBits);
}
static void clearIntegerPart128(__uint128_t *fixed128, int fractionBits) {
const swift_uint128_t fixedPointMask = (((__uint128_t)1 << fractionBits) - 1);
*fixed128 &= fixedPointMask;
}
#else
#define increment128(dest) \
do { \
uint64_t t = (dest).low + 1; \
(dest).low = (uint32_t)t; \
t >>= 32; \
t += (dest).b; \
(dest).b = (uint32_t)t; \
t >>= 32; \
t += (dest).c; \
(dest).c = (uint32_t)t; \
t >>= 32; \
(dest).high += (uint32_t)t; \
} while (0)
static int isLessThan128x128(swift_uint128_t lhs, swift_uint128_t rhs);
static void subtract128x128(swift_uint128_t *lhs, swift_uint128_t rhs);
static void multiply128xi32(swift_uint128_t *lhs, uint32_t rhs);
#define initialize128WithHigh64(dest, value) \
((dest).low = (dest).b = 0, \
(dest).c = (uint32_t)(value), \
(dest).high = (uint32_t)((value) >> 32))
#define extractHigh64From128(arg) (((uint64_t)(arg).high << 32)|((arg).c))
static int extractIntegerPart128(swift_uint128_t *fixed128, int fractionBits) {
const int highFractionBits = fractionBits % 32;
return (int)(fixed128->high >> highFractionBits);
}
static void clearIntegerPart128(swift_uint128_t *fixed128, int fractionBits) {
const int highFractionBits = fractionBits % 32;
fixed128->high &= ((uint32_t)1 << highFractionBits) - 1;
}
#endif
static swift_uint128_t multiply128x64RoundingDown(swift_uint128_t lhs, uint64_t rhs);
static swift_uint128_t multiply128x64RoundingUp(swift_uint128_t lhs, uint64_t rhs);
static swift_uint128_t shiftRightRoundingDown128(swift_uint128_t lhs, int shift);
static swift_uint128_t shiftRightRoundingUp128(swift_uint128_t lhs, int shift);
static void intervalContainingPowerOf10_Double(int p, swift_uint128_t *lower, swift_uint128_t *upper, int *exponent);
#endif
//
// Helper functions used only by the extended-precision long double formatter
//
#if SWIFT_DTOA_FLOAT80_SUPPORT
#if HAVE_UINT128_T
// A 192-bit unsigned integer type stored as 3 64-bit words
typedef struct {uint64_t low, mid, high;} swift_uint192_t;
#define initialize192WithHighMidLow64(dest, high64, mid64, low64) \
((dest).low = (low64), \
(dest).mid = (mid64), \
(dest).high = (high64))
#else
// A 192-bit unsigned integer type stored as 6 32-bit words
typedef struct {uint32_t low, b, c, d, e, high;} swift_uint192_t;
#define initialize192WithHighMidLow64(dest, high64, mid64, low64) \
((dest).low = (uint64_t)(low64), \
(dest).b = (uint64_t)(low64) >> 32, \
(dest).c = (uint64_t)(mid64), \
(dest).d = (uint64_t)(mid64) >> 32, \
(dest).e = (uint64_t)(high64), \
(dest).high = (uint64_t)(high64) >> 32)
#endif
static void multiply192x64RoundingDown(swift_uint192_t *lhs, uint64_t rhs);
static void multiply192x64RoundingUp(swift_uint192_t *lhs, uint64_t rhs);
static void multiply192xi32(swift_uint192_t *lhs, uint32_t rhs);
static void multiply192x128RoundingDown(swift_uint192_t *lhs, swift_uint128_t rhs);
static void multiply192x128RoundingUp(swift_uint192_t *lhs, swift_uint128_t rhs);
static void subtract192x192(swift_uint192_t *lhs, swift_uint192_t rhs);
static int isLessThan192x192(swift_uint192_t lhs, swift_uint192_t rhs);
static void shiftRightRoundingDown192(swift_uint192_t *lhs, int shift);
static void shiftRightRoundingUp192(swift_uint192_t *lhs, int shift);
static void intervalContainingPowerOf10_Float80(int p, swift_uint192_t *lower, swift_uint192_t *upper, int *exponent);
#endif
//
// --------------- Digit generation ---------------------
//
// This is the interesting part.
// These routines take a floating-point value and efficiently compute
// everything necessary to write an optimal base-10 representation of
// that value. In particular, they compute the base-10 exponent and
// corresponding digits.
// swift_decompose_double is thoroughly commented; swift_decompose_float
// and swift_decompose_float80 are fundamentally the same algorithm, but
// adjusted to perform optimally for those types.
#if SWIFT_DTOA_DOUBLE_SUPPORT
// Return raw bits encoding the double
static uint64_t bitPatternForDouble(double d) {
union { double d; uint64_t u; } converter;
converter.d = d;
return converter.u;
}
int swift_decompose_double(double d,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
// Bits in raw significand (not including hidden bit, if present)
static const int significandBitCount = DBL_MANT_DIG - 1;
static const uint64_t significandMask
= ((uint64_t)1 << significandBitCount) - 1;
// Bits in raw exponent
static const int exponentBitCount = 11;
static const int exponentMask = (1 << exponentBitCount) - 1;
// Note: IEEE 754 conventionally uses 1023 as the exponent
// bias. That's because they treat the significand as a
// fixed-point number with one bit (the hidden bit) integer
// portion. The logic here reconstructs the significand as a
// pure fraction, so we need to accomodate that when
// reconstructing the binary exponent.
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 1022
// Step 0: Deconstruct the target number
// Note: this strongly assumes IEEE 754 binary64 format
uint64_t raw = bitPatternForDouble(d);
int exponentBitPattern = (raw >> significandBitCount) & exponentMask;
uint64_t significandBitPattern = raw & significandMask;
// Step 1: Handle the various input cases:
int binaryExponent;
uint64_t significand;
if (digits_length < 17) {
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern
<< (64 - significandBitCount - 1);
}
} else { // normal
binaryExponent = exponentBitPattern - exponentBias;
uint64_t hiddenBit = (uint64_t)1 << significandBitCount;
uint64_t fullSignificand = significandBitPattern + hiddenBit;
significand = fullSignificand << (64 - significandBitCount - 1);
}
// Step 2: Determine the exact unscaled target interval
// Grisu-style algorithms construct the shortest decimal digit
// sequence within a specific interval. To build the appropriate
// interval, we start by computing the exact midpoints between
// this floating-point value and the adjacent ones.
uint64_t halfUlp = (uint64_t)1 << (64 - significandBitCount - 2);
uint64_t quarterUlp = halfUlp >> 1;
uint64_t upperMidpointExact = significand + halfUlp;
int isBoundary = significandBitPattern == 0;
uint64_t lowerMidpointExact
= significand - (isBoundary ? quarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
// Grisu algorithms are based in part on a simple technique for
// generating a base-10 form for a binary floating-point number.
// Start with a binary floating-point number `f * 2^e` and then
// estimate the decimal exponent `p`. You can then rewrite your
// original number as:
//
// ```
// f * 2^e * 10^-p * 10^p
// ```
//
// The last term is part of our output, and a good estimate for
// `p` will ensure that `2^e * 10^-p` is going to be close to 1.
// So multiplying the first three terms yields a fraction suitable
// for producing the decimal digits. So we need to estimate `p`:
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
// Compute `10^-p` to 128-bit precision. We generate
// both over- and under-estimates to ensure we can exactly
// bound the later use of these values.
swift_uint128_t powerOfTenRoundedDown;
swift_uint128_t powerOfTenRoundedUp;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Double(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
// As mentioned above, the final digit generation works
// with an interval, so we actually apply the scaling
// to the upper and lower midpoint values separately.
// As part of the scaling here, we'll switch from a pure
// fraction to a fixed-point form. Using 14 bit integer portion
// will allow us to compute four decimal digits at a time.
static const int integerBits = 14;
static const int fractionBits = 128 - integerBits;
// We scale the interval in one of two different ways...
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 131;
swift_uint128_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Case A: Narrow the interval
// Loitsch' original Grisu2 always narrows the interval.
// Since our digit generation will select a value within
// the scaled interval, narrowing the interval guarantees
// that we will find a digit sequence that converts back
// to the original value.
// This ensures accuracy but, as explained in Loitsch' paper,
// this carries a risk that there will be a shorter digit
// sequence outside of our narrowed interval that we will
// miss. This risk obviously gets lower with increased
// precision, but it wasn't until the Errol paper that anyone
// had a good way to test whether a particular implementation
// had sufficient precision. Using Errol Theorem 7 and tinkering
// with the `fractionBits` parameter above, you can show that
// 110 fraction bits is sufficient for Double.
// Multiply out the upper midpoint, rounding down...
swift_uint128_t u1 = multiply128x64RoundingDown(powerOfTenRoundedDown,
upperMidpointExact);
// Account for residual binary exponent and adjust
// to the fixed-point format
u = shiftRightRoundingDown128(u1, integerBits - extraBits);
// Conversely for the lower midpoint...
swift_uint128_t l1 = multiply128x64RoundingUp(powerOfTenRoundedUp,
lowerMidpointExact);
l = shiftRightRoundingUp128(l1, integerBits - extraBits);
} else {
// Case B: Widen the interval
// As explained in Errol Theorem 6, in certain cases the true
// shortest decimal result is at one of the exact scaled
// midpoints. Any narrowing will exclude the exact midpoints,
// so we must widen here to ensure we consider those cases.
// Errol Theorem 6 explains that this can only happen if the
// exact midpoints are integers with even significands and
// exponents less than a particular bound. (See the `if`
// condition above.)
// Widening the interval in this case ensures that we find a
// short result but carries a risk of selecting a result
// outside of the exact scaled interval (which would be
// inaccurate). For Float and Float80, it's easy to see this
// never happens: they use more fraction bits here than the
// maximum exponent for this case so any number outside the
// exact interval will not be an integer. Since any
// non-integer will always have more digits than the adjacent
// integers, the digit generation will never select it. For
// double, we've cut things a bit finer (114 bit fraction here
// is not higher than the exponent limit of 131 above), so
// we've had to rely on Errol Theorem 7 to enumerate possible
// failures to test those cases.
// Note: Grisu3 converts every number twice: once with the
// narrowed interval to ensure accuracy and once with the
// wider interval to ensure shortness. If both agree, the
// result must meet both conditions. In essence, the Errol
// paper provides a way to select narrowing or widening
// appropriately so we can avoid Grisu3's double conversion.
swift_uint128_t u1 = multiply128x64RoundingUp(powerOfTenRoundedUp,
upperMidpointExact);
u = shiftRightRoundingUp128(u1, integerBits - extraBits);
swift_uint128_t l1 = multiply128x64RoundingDown(powerOfTenRoundedDown,
lowerMidpointExact);
l = shiftRightRoundingDown128(l1, integerBits - extraBits);
}
// Step 6: Align first digit, adjust exponent
// This preps for digit generation. It just multiplies repeatedly
// by 10 until we have exactly one decimal digit in the integer
// part, adjusting the exponent as we go.
// In particular, this prunes leading zeros from subnormals.
// Generate digits for `t` with interval width `delta`
swift_uint128_t t = u;
swift_uint128_t delta = u;
subtract128x128(&delta, l); // Explained below.
int exponent = base10Exponent + 1;
// Except for subnormals, this loop should never run more than once.
#if HAVE_UINT128_T
static const swift_uint128_t fixedPointOne = (__uint128_t)1 << fractionBits;
while (t < fixedPointOne)
#else
// Because 1.0 in fixed point has a lot of zeros, it suffices
// to only compare the high-order word here. This is a minor
// performance win.
while (t.high < ((uint32_t)1 << (fractionBits % 32)))
#endif
{
exponent -= 1;
multiply128xi32(&delta, 10);
multiply128xi32(&t, 10);
}
// Step 7: Generate digits
// This is a common part of Grisu-style algorithms. The
// underlying idea is to generate digits for the scaled upper and
// lower boundaries, and stop when we hit the first different
// digit (at which point, the digit for the upper midpoint is the
// candidate final digit). To understand this, just note that
// 0.1234 is the shortest decimal between u = 0.123456 and l =
// 0.123345.
// Grisu uses a slightly optimized technique: it generates digits
// for the upper bound (multiplying by 10 to isolate each digit)
// and multiplies the interval width `delta` at the same time.
// The `different digit` criteria above translates to a test for
// `delta` being larger than the remainder.
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = extractIntegerPart128(&t, fractionBits);
clearIntegerPart128(&t, fractionBits);
// Further optimization: Generating four digits at a time reduces
// the total arithmetic required per digit. Note: The following
// block can be entirely removed with no effect on the result.
// If you're trying to understand this algorithm, just skip this
// block on first reading.
swift_uint128_t d0 = delta;
multiply128xi32(&d0, 10000);
swift_uint128_t t0 = t;
multiply128xi32(&t0, 10000);
int fourDigits = extractIntegerPart128(&t0, fractionBits); // 4 digits
clearIntegerPart128(&t0, fractionBits);
while (isLessThan128x128(d0, t0)) {
*digit_p++ = nextDigit;
int d = fourDigits / 100; // top 2 digits
*digit_p++ = d / 10;
*digit_p++ = d % 10;
d = fourDigits % 100; // bottom 2 digits
*digit_p++ = d / 10;
nextDigit = d % 10;
t = t0;
delta = d0;
multiply128xi32(&d0, 10000);
multiply128xi32(&t0, 10000);
fourDigits = extractIntegerPart128(&t0, fractionBits);
clearIntegerPart128(&t0, fractionBits);
}
// Finish by generating one digit at a time.
while (isLessThan128x128(delta, t)) {
*digit_p++ = nextDigit;
multiply128xi32(&delta, 10);
multiply128xi32(&t, 10);
nextDigit = extractIntegerPart128(&t, fractionBits);
clearIntegerPart128(&t, fractionBits);
}
// Adjust the final digit to be closer to the original value.
// This is basically the same as Grisu3. It accounts for the
// fact that sometimes there is more than one shortest digit
// sequence.
// For example, consider how the above would work if you had the
// value 0.1234 and computed u = 0.1257, l = 0.1211. The above
// digit generation works with `u`, so produces 0.125. But the
// values 0.122, 0.123, and 0.124 are just as short and 0.123 is
// the best choice, since it's closest to the original value.
// If `delta <= t + 1.0`, then the interval is narrower than
// one decimal digit, so there is no other option.
// Note: We've already consumed most of our available precision,
// so it's okay to just work in 64 bits here...
uint64_t deltaHigh64 = extractHigh64From128(delta);
uint64_t tHigh64 = extractHigh64From128(t);
if (deltaHigh64 > tHigh64 + ((uint64_t)1 << (fractionBits % 64))) {
// Note: 64-bit arithmetic is okay here
uint64_t skew;
if (isBoundary) {
// If we're at the boundary where the exponent shifts,
// then the original value is 1/3 of the way from
// the bottom of the interval ...
skew = deltaHigh64 - deltaHigh64 / 3 - tHigh64;
} else {
// ... otherwise it's exactly in the middle.
skew = deltaHigh64 / 2 - tHigh64;
}
// The `skew` above is the difference between our
// computed digits and the original exact value.
// Use that to offset the final digit:
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is exactly integer + 1/2, round the
// last digit even after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit; // Store the final digit.
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
// Return raw bits encoding the float
static uint64_t bitPatternForFloat(float f) {
union { float f; uint32_t u; } converter;
converter.f = f;
return converter.u;
}
// Decompose an IEEE 754 binary32 single-precision float
// into decimal digits and a corresponding decimal exponent.
// See swift_decompose_double for detailed comments on the algorithm here
int swift_decompose_float(float f,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
static const int significandBitCount = FLT_MANT_DIG - 1;
static const uint32_t significandMask
= ((uint32_t)1 << significandBitCount) - 1;
static const int exponentBitCount = 8;
static const int exponentMask = (1 << exponentBitCount) - 1;
// See comments in swift_decompose_double
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 125
// Step 0: Deconstruct the target number
// Note: this strongly assumes IEEE 754 binary32 format
uint32_t raw = bitPatternForFloat(f);
int exponentBitPattern = (raw >> significandBitCount) & exponentMask;
uint32_t significandBitPattern = raw & significandMask;
// Step 1: Handle the various input cases:
int binaryExponent;
uint32_t significand;
if (digits_length < 9) {
// Ensure we have space for 9 digits
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
// Return one zero digit and decimalExponent = 0.
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // Subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern << (32 - significandBitCount - 1);
}
} else { // normal
binaryExponent = exponentBitPattern - exponentBias;
uint32_t hiddenBit = (uint32_t)1 << (uint32_t)significandBitCount;
uint32_t fullSignificand = significandBitPattern + hiddenBit;
significand = fullSignificand << (32 - significandBitCount - 1);
}
// Step 2: Determine the exact unscaled target interval
uint32_t halfUlp = (uint32_t)1 << (32 - significandBitCount - 2);
uint32_t quarterUlp = halfUlp >> 1;
uint32_t upperMidpointExact = significand + halfUlp;
int isBoundary = significandBitPattern == 0;
uint32_t lowerMidpointExact
= significand - (isBoundary ? quarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
uint64_t powerOfTenRoundedDown = 0;
uint64_t powerOfTenRoundedUp = 0;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Float(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
static const int integerBits = 5;
static const int fractionBits = 64 - integerBits;
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 57;
uint64_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Narrow the interval
uint64_t u1 = multiply64x32RoundingDown(powerOfTenRoundedDown,
upperMidpointExact);
u = u1 >> (integerBits - extraBits); // Rounding down
uint64_t l1 = multiply64x32RoundingUp(powerOfTenRoundedUp,
lowerMidpointExact);
l = shiftRightRoundingUp64(l1, integerBits - extraBits);
} else {
// Widen the interval
uint64_t u1 = multiply64x32RoundingUp(powerOfTenRoundedUp,
upperMidpointExact);
u = shiftRightRoundingUp64(u1, integerBits - extraBits);
uint64_t l1 = multiply64x32RoundingDown(powerOfTenRoundedDown,
lowerMidpointExact);
l = l1 >> (integerBits - extraBits); // Rounding down
}
// Step 6: Align first digit, adjust exponent
// In particular, this prunes leading zeros from subnormals
static const uint64_t fixedPointOne = (uint64_t)1 << fractionBits;
static const uint64_t fixedPointMask = fixedPointOne - 1;
uint64_t t = u;
uint64_t delta = u - l;
int exponent = base10Exponent + 1;
while (t < fixedPointOne) {
exponent -= 1;
delta *= 10;
t *= 10;
}
// Step 7: Generate digits
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = (int)(t >> fractionBits);
t &= fixedPointMask;
// Generate one digit at a time...
while (t > delta) {
*digit_p++ = nextDigit;
delta *= 10;
t *= 10;
nextDigit = (int)(t >> fractionBits);
t &= fixedPointMask;
}
// Adjust the final digit to be closer to the original value
if (delta > t + fixedPointOne) {
uint64_t skew;
if (isBoundary) {
skew = delta - delta / 3 - t;
} else {
skew = delta / 2 - t;
}
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is integer + 1/2, round the last digit even
// after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit;
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// See `swift_decompose_double` for detailed comments on this implementatoin.
int swift_decompose_float80(long double d,
int8_t *digits, size_t digits_length, int *decimalExponent)
{
// Omit leading bit, as if we were an IEEE 754 format
static const int significandBitCount = LDBL_MANT_DIG - 1;
static const int exponentBitCount = 15;
static const int exponentMask = (1 << exponentBitCount) - 1;
// See comments in swift_decompose_double to understand
// why we use 16,382 instead of 16,383 here.
static const int64_t exponentBias = (1 << (exponentBitCount - 1)) - 2; // 16,382
// Step 0: Deconstruct the target number
// Note: this strongly assumes Intel 80-bit extended format in LSB
// byte order
const uint64_t *raw_p = (const uint64_t *)&d;
int exponentBitPattern = raw_p[1] & exponentMask;
uint64_t significandBitPattern = raw_p[0];
// Step 1: Handle the various input cases:
int64_t binaryExponent;
uint64_t significand;
if (digits_length < 21) {
return 0;
} else if (exponentBitPattern == exponentMask) { // NaN or Infinity
// Return no digits
return 0;
} else if (exponentBitPattern == 0) {
if (significandBitPattern == 0) { // Zero
digits[0] = 0;
*decimalExponent = 0;
return 1;
} else { // subnormal
binaryExponent = 1 - exponentBias;
significand = significandBitPattern;
}
} else if (significandBitPattern >> 63) { // Normal
binaryExponent = exponentBitPattern - exponentBias;
significand = significandBitPattern;
} else {
// "Unnormal" values are rejected as invalid by 80387 and later.
// Treat them the same as NaNs here.
return 0;
}
// Step 2: Determine the exact unscaled target interval
uint64_t halfUlp = (uint64_t)1 << 63;
uint64_t quarterUlp = halfUlp >> 1;
uint64_t threeQuarterUlp = halfUlp + quarterUlp;
swift_uint128_t upperMidpointExact, lowerMidpointExact;
initialize128WithHighLow64(upperMidpointExact, significand, halfUlp);
int isBoundary = (significandBitPattern & 0x7fffffffffffffff) == 0;
// Subtract 1/4 or 1/2 ULP by first subtracting 1 full ULP, then adding some back
initialize128WithHighLow64(lowerMidpointExact, significand - 1, isBoundary ? threeQuarterUlp : halfUlp);
// Step 3: Estimate the base 10 exponent
int base10Exponent = decimalExponentFor2ToThe(binaryExponent);
// Step 4: Compute a power-of-10 scale factor
swift_uint192_t powerOfTenRoundedDown;
swift_uint192_t powerOfTenRoundedUp;
int powerOfTenExponent = 0;
intervalContainingPowerOf10_Float80(-base10Exponent,
&powerOfTenRoundedDown,
&powerOfTenRoundedUp,
&powerOfTenExponent);
const int extraBits = binaryExponent + powerOfTenExponent;
// Step 5: Scale the interval (with rounding)
static const int integerBits = 14;
static const int fractionBits = 192 - integerBits;
#if HAVE_UINT128_T
static const int highFractionBits = fractionBits % 64;
#else
static const int highFractionBits = fractionBits % 32;
#endif
// This value comes from the Errol paper, Theorem 6
static const int maxIntegerMidpointExponent = 153;
swift_uint192_t u, l;
if (((significandBitPattern & 1) != 0)
|| (binaryExponent < significandBitCount + 3)
|| (binaryExponent > maxIntegerMidpointExponent)) {
// Narrow the interval
u = powerOfTenRoundedDown;
multiply192x128RoundingDown(&u, upperMidpointExact);
shiftRightRoundingDown192(&u, integerBits - extraBits);
l = powerOfTenRoundedUp;
multiply192x128RoundingUp(&l, lowerMidpointExact);
shiftRightRoundingUp192(&l, integerBits - extraBits);
} else {
// Widen the interval
u = powerOfTenRoundedUp;
multiply192x128RoundingUp(&u, upperMidpointExact);
shiftRightRoundingUp192(&u, integerBits - extraBits);
l = powerOfTenRoundedDown;
multiply192x128RoundingDown(&l, lowerMidpointExact);
shiftRightRoundingDown192(&l, integerBits - extraBits);
}
// Step 6: Align first digit, adjust exponent
// In particular, this prunes leading zeros from subnormals
static const uint64_t fixedPointOneHigh = (uint64_t)1 << highFractionBits;
static const uint64_t fixedPointMaskHigh = fixedPointOneHigh - 1;
swift_uint192_t t = u;
swift_uint192_t delta = u;
subtract192x192(&delta, l);
int exponent = base10Exponent + 1;
while (t.high < fixedPointOneHigh) {
exponent -= 1;
multiply192xi32(&delta, 10);
multiply192xi32(&t, 10);
}
// Step 7: Generate digits
int8_t *digit_p = digits;
// Adjustment above already set up the first digit:
int nextDigit = (int)(t.high >> highFractionBits);
t.high &= fixedPointMaskHigh;
// Generate four digits at a time ...
swift_uint192_t d0 = delta;
swift_uint192_t t0 = t;
multiply192xi32(&d0, 10000);
multiply192xi32(&t0, 10000);
int fourDigits = (int)(t0.high >> highFractionBits);
t0.high &= fixedPointMaskHigh;
while (isLessThan192x192(d0, t0)) {
*digit_p++ = nextDigit;
int d = fourDigits / 100;
*digit_p++ = d / 10;
*digit_p++ = d % 10;
d = fourDigits % 100;
*digit_p++ = d / 10;
nextDigit = d % 10;
t = t0;
delta = d0;
multiply192xi32(&d0, 10000);
multiply192xi32(&t0, 10000);
fourDigits = (int)(t0.high >> highFractionBits);
t0.high &= fixedPointMaskHigh;
}
// Generate one digit at a time...
while (isLessThan192x192(delta, t)) {
*digit_p++ = nextDigit;
multiply192xi32(&delta, 10);
multiply192xi32(&t, 10);
nextDigit = (int)(t.high >> highFractionBits);
t.high &= fixedPointMaskHigh;
}
// Adjust the final digit to be closer to the original value
// We've already consumed most of our available precision, so it's
// okay to just work in 64 bits here...
#if HAVE_UINT128_T
uint64_t deltaHigh64 = delta.high;
uint64_t tHigh64 = t.high;
#else
uint64_t deltaHigh64 = ((uint64_t)delta.high << 32) + delta.e;
uint64_t tHigh64 = ((uint64_t)t.high << 32) + t.e;
#endif
if (deltaHigh64 > tHigh64 + ((uint64_t)1 << (fractionBits % 64))) {
uint64_t skew;
if (isBoundary) {
skew = deltaHigh64 - deltaHigh64 / 3 - tHigh64;
} else {
skew = deltaHigh64 / 2 - tHigh64;
}
uint64_t one = (uint64_t)(1) << (64 - integerBits);
uint64_t fractionMask = one - 1;
uint64_t oneHalf = one >> 1;
if ((skew & fractionMask) == oneHalf) {
int adjust = (int)(skew >> (64 - integerBits));
// If the skew is integer + 1/2, round the last digit even
// after adjustment
nextDigit = (nextDigit - adjust) & ~1;
} else {
// Else round to nearest...
int adjust = (int)((skew + oneHalf) >> (64 - integerBits));
nextDigit = (nextDigit - adjust);
}
}
*digit_p++ = nextDigit;
*decimalExponent = exponent;
return digit_p - digits;
}
#endif
//
// ---------------- High-level API -----------------
//
// Functions that format a Float/Double/Float80
// directly into a buffer.
//
// These handle various exception cases (infinity, Nan, zero)
// before invoking the general base-10 conversion.
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
static size_t swift_format_constant(char *dest, size_t length, const char *s) {
const size_t l = strlen(s);
if (length <= l) {
return 0;
}
strcpy(dest, s);
return l;
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
size_t swift_format_float(float d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
static const int significandBitCount = 23;
uint32_t raw = bitPatternForFloat(d);
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((raw >> (significandBitCount - 1)) & 1) ? "" : "s";
uint32_t payload = raw & ((1L << (significandBitCount - 2)) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%x)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
int decimalExponent;
int8_t digits[9];
int digitCount =
swift_decompose_float(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 6) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
size_t swift_format_double(double d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
static const int significandBitCount = 52;
uint64_t raw = bitPatternForDouble(d);
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((raw >> (significandBitCount - 1)) & 1) ? "" : "s";
uint64_t payload = raw & ((1ull << (significandBitCount - 2)) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%llx)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
int decimalExponent;
int8_t digits[17];
int digitCount =
swift_decompose_double(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 15) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
size_t swift_format_float80(long double d, char *dest, size_t length)
{
if (!isfinite(d)) {
if (isinf(d)) {
// Infinity
if (signbit(d)) {
return swift_format_constant(dest, length, "-inf");
} else {
return swift_format_constant(dest, length, "inf");
}
} else {
// NaN
// Assumes Intel 80-bit extended format in LSB byte order:
uint64_t significandBitPattern = *(const uint64_t *)&d;
const char *sign = signbit(d) ? "-" : "";
const char *signaling = ((significandBitPattern >> 62) & 1) ? "" : "s";
uint64_t payload = significandBitPattern & (((uint64_t)1 << 61) - 1);
char buff[32];
if (payload != 0) {
snprintf(buff, sizeof(buff), "%s%snan(0x%llx)",
sign, signaling, payload);
} else {
snprintf(buff, sizeof(buff), "%s%snan",
sign, signaling);
}
return swift_format_constant(dest, length, buff);
}
}
// zero
if (d == 0.0) {
if (signbit(d)) {
return swift_format_constant(dest, length, "-0.0");
} else {
return swift_format_constant(dest, length, "0.0");
}
}
// Decimal numeric formatting
// Decimal numeric formatting
int decimalExponent;
int8_t digits[21];
int digitCount =
swift_decompose_float80(d, digits, sizeof(digits), &decimalExponent);
if (decimalExponent < -3 || decimalExponent > 18) {
return swift_format_exponential(dest, length, signbit(d),
digits, digitCount, decimalExponent);
} else {
return swift_format_decimal(dest, length, signbit(d),
digits, digitCount, decimalExponent);
}
}
#endif
/**
* Routines to format a decomposed value into a standard string form.
*/
// Format into exponential format: "1.234e+56"
// Returns number of characters actually written to `dest`.
// Returns zero if buffer is too small.
size_t swift_format_exponential(char *dest, size_t length,
bool negative, const int8_t *digits, int digit_count, int exponent)
{
// Largest buffer we could possibly need:
size_t maximum_size = digit_count + 9;
if (length < maximum_size) {
// We only do the detailed check if the size is borderline.
size_t actual_size =
+ (negative ? 1 : 0) // Leading minus
+ digit_count // digits
+ (digit_count > 1 ? 1 : 0) // decimal
+ 1 // 'e'
+ 1 // sign
+ (exponent > 99 ? (exponent > 999 ? 4 : 3) : 2) // exponent
+ 1; // trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
}
char *p = dest;
if (negative) {
*p++ = '-';
}
*p++ = digits[0] + '0';
exponent -= 1;
if (digit_count > 1) {
*p++ = '.';
for (int i = 1; i < digit_count; i++) {
*p++ = digits[i] + '0';
}
}
*p++ = 'e';
if (exponent < 0) {
*p++ = '-';
exponent = -exponent;
} else {
*p++ = '+';
}
if (exponent > 99) {
if (exponent > 999) {
*p++ = (exponent / 1000 % 10) + '0';
}
*p++ = (exponent / 100 % 10) + '0';
exponent %= 100;
}
*p++ = (exponent / 10) + '0';
*p++ = (exponent % 10) + '0';
*p = '\0';
return p - dest;
}
// Format into decimal form: "123456789000.0", "1234.5678", "0.0000001234"
// Returns number of bytes of `dest` actually used, or zero if
// provided buffer is too small.
size_t swift_format_decimal(char *dest, size_t length,
bool negative, const int8_t *digits, int digit_count, int exponent)
{
// Largest buffer we could possibly need:
size_t maximum_size =
digit_count // All the digits
+ (exponent > 0 ? exponent : -exponent) // Max # of extra zeros
+ 4; // Max # of other items
if (length < maximum_size) {
// We only do the detailed check if the size is borderline.
if (exponent <= 0) { // "0.0000001234"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ 2 // Leading "0."
+ (-exponent) // Leading zeros after decimal point
+ digit_count
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
} else if (exponent < digit_count) { // "123.45"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ digit_count
+ 1 // embedded decimal point
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
} else { // "12345000.0"
size_t actual_size =
(negative ? 1 : 0) // Leading minus
+ digit_count
+ (exponent - digit_count) // trailing zeros
+ 2 // ".0" to mark this as floating point
+ 1; // Trailing zero byte
if (length < actual_size) {
if (length > 0) {
dest[0] = 0;
}
return 0;
}
}
}
char *p = dest;
if (negative) {
*p++ = '-';
}
if (exponent <= 0) {
*p++ = '0';
*p++ = '.';
while (exponent < 0) {
*p++ = '0';
exponent += 1;
}
for (int i = 0; i < digit_count; ++i) {
*p++ = digits[i] + '0';
}
} else if (exponent < digit_count) {
for (int i = 0; i < digit_count; i++) {
if (exponent == 0) {
*p++ = '.';
}
*p++ = digits[i] + '0';
exponent -= 1;
}
} else {
for (int i = 0; i < digit_count; i++) {
*p++ = digits[i] + '0';
exponent -= 1;
}
while (exponent > 0) {
*p++ = '0';
exponent -= 1;
}
*p++ = '.';
*p++ = '0';
}
*p = '\0';
return p - dest;
}
//
// ------------ Arithmetic helpers ----------------
//
// The core algorithm relies heavily on fraction and fixed-point
// arithmetic with 64-bit, 128-bit, and 192-bit integer values. (For
// float, double, and float80, respectively.) They also need precise
// control over all rounding.
//
// Note that most arithmetic operations are the same for integers and
// fractions, so we can just use the normal integer operations in most
// places. Multiplication however, is different for fixed-size
// fractions. Integer multiplication preserves the low-order part and
// discards the high-order part (ignoring overflow). Fraction
// multiplication preserves the high-order part and discards the
// low-order part (rounding). So most of the arithmetic helpers here
// are for multiplication.
// Note: With 64-bit GCC and Clang, we get a lot of performance gain
// and code simplification by using `__uint128_t`. Otherwise, we have
// to break things down into 32-bit chunks so we don't overflow 64-bit
// temporaries.
#if SWIFT_DTOA_FLOAT_SUPPORT
// Multiply a 64-bit fraction by a 32-bit fraction, rounding down.
static uint64_t multiply64x32RoundingDown(uint64_t lhs, uint32_t rhs) {
#if HAVE_UINT128_T
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)(full >> 32);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = ((lhs & mask32) * rhs) >> 32;
return t + (lhs >> 32) * rhs;
#endif
}
// Multiply a 64-bit fraction by a 32-bit fraction, rounding up.
static uint64_t multiply64x32RoundingUp(uint64_t lhs, uint32_t rhs) {
#if HAVE_UINT128_T
static const __uint128_t roundingFactor = UINT32_MAX;
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)((full + roundingFactor) >> 32);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (((lhs & mask32) * rhs) + mask32) >> 32;
return t + (lhs >> 32) * rhs;
#endif
}
// Multiply a 64-bit fraction by a 64-bit fraction, rounding down.
static uint64_t multiply64x64RoundingDown(uint64_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)(full >> 64);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (lhs & mask32) * (rhs & mask32);
t >>= 32;
uint64_t a = (lhs >> 32) * (rhs & mask32);
uint64_t b = (lhs & mask32) * (rhs >> 32);
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
return t + (lhs >> 32) * (rhs >> 32);
#endif
}
// Multiply a 64-bit fraction by a 64-bit fraction, rounding up.
static uint64_t multiply64x64RoundingUp(uint64_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
static const __uint128_t roundingFactor = ((__uint128_t)1 << 64) - 1;
__uint128_t full = (__uint128_t)lhs * rhs;
return (uint64_t)((full + roundingFactor) >> 64);
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (lhs & mask32) * (rhs & mask32);
t = (t + mask32) >> 32;
uint64_t a = (lhs >> 32) * (rhs & mask32);
uint64_t b = (lhs & mask32) * (rhs >> 32);
t += (a & mask32) + (b & mask32);
t = (t + mask32) >> 32;
t += (a >> 32) + (b >> 32);
return t + (lhs >> 32) * (rhs >> 32);
#endif
}
// Shift a 64-bit integer right, rounding up.
static uint64_t shiftRightRoundingUp64(uint64_t lhs, int shift) {
uint64_t mask = ((uint64_t)1 << shift) - 1;
uint64_t round = ((lhs & mask) == 0) ? 0 : 1;
return (lhs >> shift) + round;
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// Multiply a 128-bit fraction by a 64-bit fraction, rounding down.
static swift_uint128_t multiply128x64RoundingDown(swift_uint128_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
uint64_t lhsl = (uint64_t)lhs;
uint64_t lhsh = (uint64_t)(lhs >> 64);
swift_uint128_t h = (swift_uint128_t)lhsh * rhs;
swift_uint128_t l = (swift_uint128_t)lhsl * rhs;
return h + (l >> 64);
#else
swift_uint128_t result;
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = (lhs.low) * rhs0;
t >>= 32;
uint64_t a = (lhs.b) * rhs0;
uint64_t b = (lhs.low) * rhs1;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.c * rhs0;
b = lhs.b * rhs1;
t += (a & mask32) + (b & mask32);
result.low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.high * rhs0;
b = lhs.c * rhs1;
t += (a & mask32) + (b & mask32);
result.b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs.high * rhs1;
result.c = t;
result.high = t >> 32;
return result;
#endif
}
// Multiply a 128-bit fraction by a 64-bit fraction, rounding up.
static swift_uint128_t multiply128x64RoundingUp(swift_uint128_t lhs, uint64_t rhs) {
#if HAVE_UINT128_T
uint64_t lhsl = (uint64_t)lhs;
uint64_t lhsh = (uint64_t)(lhs >> 64);
swift_uint128_t h = (swift_uint128_t)lhsh * rhs;
swift_uint128_t l = (swift_uint128_t)lhsl * rhs;
uint64_t remainder = (uint64_t)l;
uint64_t round = (remainder != 0) ? 1 : 0;
return h + (l >> 64) + round;
#else
swift_uint128_t result;
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = (lhs.low) * rhs0 + mask32;
t >>= 32;
uint64_t a = (lhs.b) * rhs0;
uint64_t b = (lhs.low) * rhs1;
t += (a & mask32) + (b & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.c * rhs0;
b = lhs.b * rhs1;
t += (a & mask32) + (b & mask32);
result.low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs.high * rhs0;
b = lhs.c * rhs1;
t += (a & mask32) + (b & mask32);
result.b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs.high * rhs1;
result.c = t;
result.high = t >> 32;
return result;
#endif
}
#if !HAVE_UINT128_T
// Multiply a 128-bit fraction by a 32-bit integer in a 32-bit environment.
// (On 64-bit, we use a fast inline macro.)
static void multiply128xi32(swift_uint128_t *lhs, uint32_t rhs) {
uint64_t t = (uint64_t)(lhs->low) * rhs;
lhs->low = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->b) * rhs;
lhs->b = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->c) * rhs;
lhs->c = (uint32_t)t;
t = (t >> 32) + (uint64_t)(lhs->high) * rhs;
lhs->high = (uint32_t)t;
}
// Compare two 128-bit integers in a 32-bit environment
// (On 64-bit, we use a fast inline macro.)
static int isLessThan128x128(swift_uint128_t lhs, swift_uint128_t rhs) {
return ((lhs.high < rhs.high)
|| ((lhs.high == rhs.high)
&& ((lhs.c < rhs.c)
|| ((lhs.c == rhs.c)
&& ((lhs.b < rhs.b)
|| ((lhs.b == rhs.b)
&& (lhs.low < rhs.low)))))));
}
// Subtract 128-bit values in a 32-bit environment
static void subtract128x128(swift_uint128_t *lhs, swift_uint128_t rhs) {
uint64_t t = (uint64_t)lhs->low + (~rhs.low) + 1;
lhs->low = (uint32_t)t;
t = (t >> 32) + lhs->b + (~rhs.b);
lhs->b = (uint32_t)t;
t = (t >> 32) + lhs->c + (~rhs.c);
lhs->c = (uint32_t)t;
t = (t >> 32) + lhs->high + (~rhs.high);
lhs->high = (uint32_t)t;
}
#endif
// Shift a 128-bit integer right, rounding down.
static swift_uint128_t shiftRightRoundingDown128(swift_uint128_t lhs, int shift) {
#if HAVE_UINT128_T
return lhs >> shift;
#else
// Note: Shift is always less than 32
swift_uint128_t result;
uint64_t t = (uint64_t)lhs.low >> shift;
t += ((uint64_t)lhs.b << (32 - shift));
result.low = t;
t >>= 32;
t += ((uint64_t)lhs.c << (32 - shift));
result.b = t;
t >>= 32;
t += ((uint64_t)lhs.high << (32 - shift));
result.c = t;
t >>= 32;
result.high = t;
return result;
#endif
}
// Shift a 128-bit integer right, rounding up.
static swift_uint128_t shiftRightRoundingUp128(swift_uint128_t lhs, int shift) {
#if HAVE_UINT128_T
uint64_t bias = ((uint64_t)1 << shift) - 1;
return ((lhs + bias) >> shift);
#else
swift_uint128_t result;
const uint64_t bias = (1 << shift) - 1;
uint64_t t = ((uint64_t)lhs.low + bias) >> shift;
t += ((uint64_t)lhs.b << (32 - shift));
result.low = t;
t >>= 32;
t += ((uint64_t)lhs.c << (32 - shift));
result.b = t;
t >>= 32;
t += ((uint64_t)lhs.high << (32 - shift));
result.c = t;
t >>= 32;
result.high = t;
return result;
#endif
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// Multiply a 192-bit fraction by a 64-bit fraction, rounding down.
static void multiply192x64RoundingDown(swift_uint192_t *lhs, uint64_t rhs) {
#if HAVE_UINT128_T
// Compute the three 128-bit cross-products
__uint128_t cd = (__uint128_t)lhs->low * rhs;
__uint128_t bc = (__uint128_t)lhs->mid * rhs;
__uint128_t ab = (__uint128_t)lhs->high * rhs;
// Add up the three 64-bit outputs (including carries)
__uint128_t c = (cd >> 64) + (uint64_t)bc;
__uint128_t b = (bc >> 64) + (uint64_t)ab + (c >> 64);
__uint128_t a = (ab >> 64) + (b >> 64);
lhs->high = a;
lhs->mid = b;
lhs->low = c;
#else
static const uint64_t mask32 = UINT32_MAX;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = lhs->low * rhs0;
t >>= 32;
uint64_t a = lhs->low * rhs1;
uint64_t b = lhs->b * rhs0;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->b * rhs1;
b = lhs->c * rhs0;
t += (a & mask32) + (b & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->c * rhs1;
b = lhs->d * rhs0;
t += (a & mask32) + (b & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->d * rhs1;
b = lhs->e * rhs0;
t += (a & mask32) + (b & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->e * rhs1;
b = lhs->high * rhs0;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs->high * rhs1;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 64-bit fraction, rounding up.
static void multiply192x64RoundingUp(swift_uint192_t *lhs, uint64_t rhs) {
#if HAVE_UINT128_T
// Compute the three 128-bit cross-products
__uint128_t cd = (__uint128_t)lhs->low * rhs + UINT64_MAX;
__uint128_t bc = (__uint128_t)lhs->mid * rhs;
__uint128_t ab = (__uint128_t)lhs->high * rhs;
// Add up the three 64-bit outputs (including carries)
__uint128_t c = (cd >> 64) + (uint64_t)bc;
__uint128_t b = (bc >> 64) + (uint64_t)ab + (c >> 64);
__uint128_t a = (ab >> 64) + (b >> 64);
lhs->high = a;
lhs->mid = b;
lhs->low = c;
#else
static const uint64_t mask32 = UINT32_MAX;
static const uint64_t bias = mask32;
uint64_t rhs0 = rhs & mask32;
uint64_t rhs1 = rhs >> 32;
uint64_t t = lhs->low * rhs0 + bias;
t >>= 32;
uint64_t a = lhs->low * rhs1;
uint64_t b = lhs->b * rhs0;
t += (a & mask32) + (b & mask32) + bias;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->b * rhs1;
b = lhs->c * rhs0;
t += (a & mask32) + (b & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->c * rhs1;
b = lhs->d * rhs0;
t += (a & mask32) + (b & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->d * rhs1;
b = lhs->e * rhs0;
t += (a & mask32) + (b & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = lhs->e * rhs1;
b = lhs->high * rhs0;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += lhs->high * rhs1;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 64-bit integer.
// This is used in the digit generation to multiply by ten or
// 10,000. Note that rounding never appliles here.
// As used below, this will never overflow.
static void multiply192xi32(swift_uint192_t *lhs, uint32_t rhs) {
#if HAVE_UINT128_T
__uint128_t t = (__uint128_t)lhs->low * rhs;
lhs->low = (uint64_t)t;
t = (t >> 64) + (__uint128_t)lhs->mid * rhs;
lhs->mid = (uint64_t)t;
t = (t >> 64) + (__uint128_t)lhs->high * rhs;
lhs->high = (uint64_t)t;
#else
uint64_t t = (uint64_t)lhs->low * rhs;
lhs->low = t;
t = (t >> 32) + (uint64_t)lhs->b * rhs;
lhs->b = t;
t = (t >> 32) + (uint64_t)lhs->c * rhs;
lhs->c = t;
t = (t >> 32) + (uint64_t)lhs->d * rhs;
lhs->d = t;
t = (t >> 32) + (uint64_t)lhs->e * rhs;
lhs->e = t;
t = (t >> 32) + (uint64_t)lhs->high * rhs;
lhs->high = t;
#endif
}
// Multiply a 192-bit fraction by a 128-bit fraction, rounding down.
static void multiply192x128RoundingDown(swift_uint192_t *lhs, swift_uint128_t rhs) {
#if HAVE_UINT128_T
// A full multiply of three 64-bit values by two 64-bit values
// yields five such components. We discard the bottom two (except
// for carries) to get a rounded-down three-element result.
__uint128_t current = (__uint128_t)lhs->low * (uint64_t)rhs;
current = (current >> 64);
__uint128_t t = (__uint128_t)lhs->low * (rhs >> 64);
current += (uint64_t)t;
__uint128_t next = t >> 64;
t = (__uint128_t)lhs->mid * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
current = next + (current >> 64);
t = (__uint128_t)lhs->mid * (rhs >> 64);
current += (uint64_t)t;
next = t >> 64;
t = (__uint128_t)lhs->high * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
lhs->low = (uint64_t)current;
current = next + (current >> 64);
t = (__uint128_t)lhs->high * (rhs >> 64);
current += t;
lhs->mid = (uint64_t)current;
lhs->high = (uint64_t)(current >> 64);
#else
uint64_t a, b, c, d; // temporaries
// Six 32-bit values multiplied by 4 32-bit values. Oh my.
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = lhs->low * rhs.low;
t >>= 32;
a = (uint64_t)lhs->low * rhs.b;
b = (uint64_t)lhs->b * rhs.low;
t += (a & mask32) + (b & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32);
a = (uint64_t)lhs->low * rhs.c;
b = (uint64_t)lhs->b * rhs.b;
c = (uint64_t)lhs->c * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->low * rhs.high;
b = (uint64_t)lhs->b * rhs.c;
c = (uint64_t)lhs->c * rhs.b;
d = (uint64_t)lhs->d * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->b * rhs.high;
b = (uint64_t)lhs->c * rhs.c;
c = (uint64_t)lhs->d * rhs.b;
d = (uint64_t)lhs->e * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->c * rhs.high;
b = (uint64_t)lhs->d * rhs.c;
c = (uint64_t)lhs->e * rhs.b;
d = (uint64_t)lhs->high * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->d * rhs.high;
b = (uint64_t)lhs->e * rhs.c;
c = (uint64_t)lhs->high * rhs.b;
t += (a & mask32) + (b & mask32) + (c & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->e * rhs.high;
b = (uint64_t)lhs->high * rhs.c;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += (uint64_t)lhs->high * rhs.high;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Multiply a 192-bit fraction by a 128-bit fraction, rounding up.
static void multiply192x128RoundingUp(swift_uint192_t *lhs, swift_uint128_t rhs) {
#if HAVE_UINT128_T
// Same as the rounding-down version, but we add
// UINT128_MAX to the bottom two to force an extra
// carry if they are non-zero.
swift_uint128_t current = (swift_uint128_t)lhs->low * (uint64_t)rhs;
current += UINT64_MAX;
current = (current >> 64);
swift_uint128_t t = (swift_uint128_t)lhs->low * (rhs >> 64);
current += (uint64_t)t;
swift_uint128_t next = t >> 64;
t = (swift_uint128_t)lhs->mid * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
// Round up by adding UINT128_MAX (upper half)
current += UINT64_MAX;
current = next + (current >> 64);
t = (swift_uint128_t)lhs->mid * (rhs >> 64);
current += (uint64_t)t;
next = t >> 64;
t = (swift_uint128_t)lhs->high * (uint64_t)rhs;
current += (uint64_t)t;
next += t >> 64;
lhs->low = (uint64_t)current;
current = next + (current >> 64);
t = (swift_uint128_t)lhs->high * (rhs >> 64);
current += t;
lhs->mid = (uint64_t)current;
lhs->high = (uint64_t)(current >> 64);
#else
uint64_t a, b, c, d; // temporaries
// Six 32-bit values multiplied by 4 32-bit values. Oh my.
static const uint64_t mask32 = UINT32_MAX;
uint64_t t = (uint64_t)lhs->low * rhs.low + mask32;
t >>= 32;
a = (uint64_t)lhs->low * rhs.b;
b = (uint64_t)lhs->b * rhs.low;
t += (a & mask32) + (b & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32);
a = (uint64_t)lhs->low * rhs.c;
b = (uint64_t)lhs->b * rhs.b;
c = (uint64_t)lhs->c * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->low * rhs.high;
b = (uint64_t)lhs->b * rhs.c;
c = (uint64_t)lhs->c * rhs.b;
d = (uint64_t)lhs->d * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32) + mask32;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->b * rhs.high;
b = (uint64_t)lhs->c * rhs.c;
c = (uint64_t)lhs->d * rhs.b;
d = (uint64_t)lhs->e * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->low = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->c * rhs.high;
b = (uint64_t)lhs->d * rhs.c;
c = (uint64_t)lhs->e * rhs.b;
d = (uint64_t)lhs->high * rhs.low;
t += (a & mask32) + (b & mask32) + (c & mask32) + (d & mask32);
lhs->b = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32) + (d >> 32);
a = (uint64_t)lhs->d * rhs.high;
b = (uint64_t)lhs->e * rhs.c;
c = (uint64_t)lhs->high * rhs.b;
t += (a & mask32) + (b & mask32) + (c & mask32);
lhs->c = t;
t >>= 32;
t += (a >> 32) + (b >> 32) + (c >> 32);
a = (uint64_t)lhs->e * rhs.high;
b = (uint64_t)lhs->high * rhs.c;
t += (a & mask32) + (b & mask32);
lhs->d = t;
t >>= 32;
t += (a >> 32) + (b >> 32);
t += (uint64_t)lhs->high * rhs.high;
lhs->e = t;
lhs->high = t >> 32;
#endif
}
// Subtract two 192-bit integers or fractions.
static void subtract192x192(swift_uint192_t *lhs, swift_uint192_t rhs) {
#if HAVE_UINT128_T
swift_uint128_t t = (swift_uint128_t)lhs->low + (~rhs.low) + 1;
lhs->low = t;
t = (t >> 64) + lhs->mid + (~rhs.mid);
lhs->mid = t;
lhs->high += (t >> 64) + (~rhs.high);
#else
uint64_t t = (uint64_t)lhs->low + (~rhs.low) + 1;
lhs->low = t;
t = (t >> 32) + lhs->b + (~rhs.b);
lhs->b = t;
t = (t >> 32) + lhs->c + (~rhs.c);
lhs->c = t;
t = (t >> 32) + lhs->d + (~rhs.d);
lhs->d = t;
t = (t >> 32) + lhs->e + (~rhs.e);
lhs->e = t;
lhs->high += (t >> 32) + (~rhs.high);
#endif
}
// Compare two 192-bit integers or fractions.
static int isLessThan192x192(swift_uint192_t lhs, swift_uint192_t rhs) {
#if HAVE_UINT128_T
return (lhs.high < rhs.high)
|| (lhs.high == rhs.high
&& (lhs.mid < rhs.mid
|| (lhs.mid == rhs.mid
&& lhs.low < rhs.low)));
#else
return (lhs.high < rhs.high
|| (lhs.high == rhs.high
&& (lhs.e < rhs.e
|| (lhs.e == rhs.e
&& (lhs.d < rhs.d
|| (lhs.d == rhs.d
&& (lhs.c < rhs.c
|| (lhs.c == rhs.c
&& (lhs.b < rhs.b
|| (lhs.b == rhs.b
&& (lhs.low < rhs.low)))))))))));
#endif
}
// Shift a 192-bit integer right, rounding down.
static void shiftRightRoundingDown192(swift_uint192_t *lhs, int shift) {
#if HAVE_UINT128_T
__uint128_t t = (__uint128_t)lhs->low >> shift;
t += ((__uint128_t)lhs->mid << (64 - shift));
lhs->low = t;
t >>= 64;
t += ((__uint128_t)lhs->high << (64 - shift));
lhs->mid = t;
t >>= 64;
lhs->high = t;
#else
uint64_t t = (uint64_t)lhs->low >> shift;
t += ((uint64_t)lhs->b << (32 - shift));
lhs->low = t;
t >>= 32;
t += ((uint64_t)lhs->c << (32 - shift));
lhs->b = t;
t >>= 32;
t += ((uint64_t)lhs->d << (32 - shift));
lhs->c = t;
t >>= 32;
t += ((uint64_t)lhs->e << (32 - shift));
lhs->d = t;
t >>= 32;
t += ((uint64_t)lhs->high << (32 - shift));
lhs->e = t;
t >>= 32;
lhs->high = t;
#endif
}
// Shift a 192-bit integer right, rounding up.
// Note: The shift will always be less than 20. Someday, that
// might suggest a way to further optimize this.
static void shiftRightRoundingUp192(swift_uint192_t *lhs, int shift) {
#if HAVE_UINT128_T
const uint64_t bias = (1 << shift) - 1;
__uint128_t t = ((__uint128_t)lhs->low + bias) >> shift;
t += ((__uint128_t)lhs->mid << (64 - shift));
lhs->low = t;
t >>= 64;
t += ((__uint128_t)lhs->high << (64 - shift));
lhs->mid = t;
t >>= 64;
lhs->high = t;
#else
const uint64_t bias = (1 << shift) - 1;
uint64_t t = ((uint64_t)lhs->low + bias) >> shift;
t += ((uint64_t)lhs->b << (32 - shift));
lhs->low = t;
t >>= 32;
t += ((uint64_t)lhs->c << (32 - shift));
lhs->b = t;
t >>= 32;
t += ((uint64_t)lhs->d << (32 - shift));
lhs->c = t;
t >>= 32;
t += ((uint64_t)lhs->e << (32 - shift));
lhs->d = t;
t >>= 32;
t += ((uint64_t)lhs->high << (32 - shift));
lhs->e = t;
t >>= 32;
lhs->high = t;
#endif
}
#endif
//
// ------------ Power of 10 calculation ----------------
//
//
// ------------ Power-of-10 tables. --------------------------
//
// Grisu-style algorithms rely on being able to rapidly
// find a high-precision approximation of any power of 10.
// These values were computed by a simple script that
// relied on Python's excellent variable-length
// integer support.
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
// Float table
//
// The constant powers of 10 here represent pure fractions
// with a binary point at the far left. (Each number in
// this first table is implicitly divided by 2^64.)
//
// Table size: 320 bytes
//
// A 64-bit significand allows us to exactly represent
// powers of 10 up to 10^27. For larger powers, the
// value here is rounded DOWN from the exact value.
// For those powers, the value here is less than the
// exact power of 10; adding one gives a value greater
// than the exact power of 10.
//
// For single-precision Float, we use these directly
// for positive powers of 10. For negative powers of
// ten, we multiply a value here by 10^-40.
//
// For Double and Float80, we use the 28 exact values
// here to help reduce the size of those tables.
static const uint64_t powersOf10_Float[40] = {
0x8000000000000000, // x 2^1 == 10^0 exactly
0xa000000000000000, // x 2^4 == 10^1 exactly
0xc800000000000000, // x 2^7 == 10^2 exactly
0xfa00000000000000, // x 2^10 == 10^3 exactly
0x9c40000000000000, // x 2^14 == 10^4 exactly
0xc350000000000000, // x 2^17 == 10^5 exactly
0xf424000000000000, // x 2^20 == 10^6 exactly
0x9896800000000000, // x 2^24 == 10^7 exactly
0xbebc200000000000, // x 2^27 == 10^8 exactly
0xee6b280000000000, // x 2^30 == 10^9 exactly
0x9502f90000000000, // x 2^34 == 10^10 exactly
0xba43b74000000000, // x 2^37 == 10^11 exactly
0xe8d4a51000000000, // x 2^40 == 10^12 exactly
0x9184e72a00000000, // x 2^44 == 10^13 exactly
0xb5e620f480000000, // x 2^47 == 10^14 exactly
0xe35fa931a0000000, // x 2^50 == 10^15 exactly
0x8e1bc9bf04000000, // x 2^54 == 10^16 exactly
0xb1a2bc2ec5000000, // x 2^57 == 10^17 exactly
0xde0b6b3a76400000, // x 2^60 == 10^18 exactly
0x8ac7230489e80000, // x 2^64 == 10^19 exactly
0xad78ebc5ac620000, // x 2^67 == 10^20 exactly
0xd8d726b7177a8000, // x 2^70 == 10^21 exactly
0x878678326eac9000, // x 2^74 == 10^22 exactly
0xa968163f0a57b400, // x 2^77 == 10^23 exactly
0xd3c21bcecceda100, // x 2^80 == 10^24 exactly
0x84595161401484a0, // x 2^84 == 10^25 exactly
0xa56fa5b99019a5c8, // x 2^87 == 10^26 exactly
0xcecb8f27f4200f3a, // x 2^90 == 10^27 exactly
0x813f3978f8940984, // x 2^94 ~= 10^28
0xa18f07d736b90be5, // x 2^97 ~= 10^29
0xc9f2c9cd04674ede, // x 2^100 ~= 10^30
0xfc6f7c4045812296, // x 2^103 ~= 10^31
0x9dc5ada82b70b59d, // x 2^107 ~= 10^32
0xc5371912364ce305, // x 2^110 ~= 10^33
0xf684df56c3e01bc6, // x 2^113 ~= 10^34
0x9a130b963a6c115c, // x 2^117 ~= 10^35
0xc097ce7bc90715b3, // x 2^120 ~= 10^36
0xf0bdc21abb48db20, // x 2^123 ~= 10^37
0x96769950b50d88f4, // x 2^127 ~= 10^38
0xbc143fa4e250eb31, // x 2^130 ~= 10^39
};
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// As above, but with 128-bit fractions.
//
// Table size: 464 bytes
//
// We only store every 28th power of ten here.
// We can multiply by an exact 64-bit power of
// ten from the table above to reconstruct the
// significand for any power of 10.
static const uint64_t powersOf10_Double[] = {
// low-order half, high-order half
0x3931b850df08e738, 0x95fe7e07c91efafa, // x 2^-1328 ~= 10^-400
0xba954f8e758fecb3, 0x9774919ef68662a3, // x 2^-1235 ~= 10^-372
0x9028bed2939a635c, 0x98ee4a22ecf3188b, // x 2^-1142 ~= 10^-344
0x47b233c92125366e, 0x9a6bb0aa55653b2d, // x 2^-1049 ~= 10^-316
0x4ee367f9430aec32, 0x9becce62836ac577, // x 2^-956 ~= 10^-288
0x6f773fc3603db4a9, 0x9d71ac8fada6c9b5, // x 2^-863 ~= 10^-260
0xc47bc5014a1a6daf, 0x9efa548d26e5a6e1, // x 2^-770 ~= 10^-232
0x80e8a40eccd228a4, 0xa086cfcd97bf97f3, // x 2^-677 ~= 10^-204
0xb8ada00e5a506a7c, 0xa21727db38cb002f, // x 2^-584 ~= 10^-176
0xc13e60d0d2e0ebba, 0xa3ab66580d5fdaf5, // x 2^-491 ~= 10^-148
0xc2974eb4ee658828, 0xa54394fe1eedb8fe, // x 2^-398 ~= 10^-120
0xcb4ccd500f6bb952, 0xa6dfbd9fb8e5b88e, // x 2^-305 ~= 10^-92
0x3f2398d747b36224, 0xa87fea27a539e9a5, // x 2^-212 ~= 10^-64
0xdde50bd1d5d0b9e9, 0xaa242499697392d2, // x 2^-119 ~= 10^-36
0xfdc20d2b36ba7c3d, 0xabcc77118461cefc, // x 2^-26 ~= 10^-8
0x0000000000000000, 0xad78ebc5ac620000, // x 2^67 == 10^20 exactly
0x9670b12b7f410000, 0xaf298d050e4395d6, // x 2^160 == 10^48 exactly
0x3b25a55f43294bcb, 0xb0de65388cc8ada8, // x 2^253 ~= 10^76
0x58edec91ec2cb657, 0xb2977ee300c50fe7, // x 2^346 ~= 10^104
0x29babe4598c311fb, 0xb454e4a179dd1877, // x 2^439 ~= 10^132
0x577b986b314d6009, 0xb616a12b7fe617aa, // x 2^532 ~= 10^160
0x0c11ed6d538aeb2f, 0xb7dcbf5354e9bece, // x 2^625 ~= 10^188
0x6d953e2bd7173692, 0xb9a74a0637ce2ee1, // x 2^718 ~= 10^216
0x9d6d1ad41abe37f1, 0xbb764c4ca7a4440f, // x 2^811 ~= 10^244
0x4b2d8644d8a74e18, 0xbd49d14aa79dbc82, // x 2^904 ~= 10^272
0xe0470a63e6bd56c3, 0xbf21e44003acdd2c, // x 2^997 ~= 10^300
0x505f522e53053ff2, 0xc0fe908895cf3b44, // x 2^1090 ~= 10^328
0xcca845ab2beafa9a, 0xc2dfe19c8c055535, // x 2^1183 ~= 10^356
0x1027fff56784f444, 0xc4c5e310aef8aa17, // x 2^1276 ~= 10^384
};
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// Every 83rd power of 10 across the range of Float80
//
// Table size: 2,928 bytes
//
// Note: We could cut this in half at the cost of one additional
// 192-bit multiply by only storing the positive values and
// multiplying by 10^-5063 to obtain the negative ones, similar
// to how we handle Float above.
static const uint64_t powersOf10_Float80[] = {
// low 64 bits, middle 64 bits, high 64 bits
0x56825ada98468526, 0x0abc23fcfda07e29, 0x871db786569ca2dd, // x 2^-16818 ~= 10^-5063
0xe3885beff5ee930d, 0xd1e638f68c97f0e5, 0xde90d1b113564507, // x 2^-16543 ~= 10^-4980
0x5a7d22b5236bcad4, 0xbab3a28a6f0a489c, 0xb74ea21ab2946479, // x 2^-16267 ~= 10^-4897
0x7d1f78bf0f4e2878, 0xcf4aea39615ffe6e, 0x96f9351fcfdd2686, // x 2^-15991 ~= 10^-4814
0xad725c0d6c214314, 0x5bd5c19f18bd2857, 0xf8afafd6ef185238, // x 2^-15716 ~= 10^-4731
0xe418e9217ce83755, 0x801e38463183fc88, 0xccd1ffc6bba63e21, // x 2^-15440 ~= 10^-4648
0x4dcd52747e029d0c, 0x867b3096b1619df8, 0xa8b11ff4721d92fb, // x 2^-15164 ~= 10^-4565
0xed2903f7e1df2b78, 0xc846664fe1364ee8, 0x8aefaaae9060380f, // x 2^-14888 ~= 10^-4482
0xed7a7f4e1e171498, 0x7da1a627b88527f1, 0xe4dbb751faa311b0, // x 2^-14613 ~= 10^-4399
0x320796dc9b1a158c, 0x2a11a871597b8012, 0xbc7d620092481a7e, // x 2^-14337 ~= 10^-4316
0x796014ec6f4c0dcb, 0xcfa99f62903708d7, 0x9b3dee433c1311e9, // x 2^-14061 ~= 10^-4233
0x08920ae76bdb8282, 0x952b06c385a08ff6, 0xffb7a402531fd4c9, // x 2^-13786 ~= 10^-4150
0x18faa162f2c4d6b9, 0x050be8c5d21c6db6, 0xd29c7528965ae5bd, // x 2^-13510 ~= 10^-4067
0x576a6c1abab7f7e7, 0xc05fb0b5c550f28d, 0xad7617610634129e, // x 2^-13234 ~= 10^-3984
0x6cc3b2fb9cae4875, 0xe1bd5b09b7202157, 0x8edd4417ae3dc210, // x 2^-12958 ~= 10^-3901
0xfafc1dc8fd12a6f8, 0xc3f29d230036529b, 0xeb542860da9bc7d8, // x 2^-12683 ~= 10^-3818
0x9d198c56bc799f35, 0x42960adf9591f02a, 0xc1d1a4b6bc2eafc8, // x 2^-12407 ~= 10^-3735
0x1803d096e43ff4bc, 0xdef9759d6432dab7, 0x9fa18c5de65a16fb, // x 2^-12131 ~= 10^-3652
0x74872779576a577c, 0x9150140eb5101a96, 0x83793dfc83fd2f9b, // x 2^-11855 ~= 10^-3569
0x415d0667f0f88262, 0x4898d98d1314d99f, 0xd890d45a257f4644, // x 2^-11580 ~= 10^-3486
0x30a5256a610c1c72, 0x6ebca4d0365d504d, 0xb25d93f98145bdab, // x 2^-11304 ~= 10^-3403
0xfb149b1f86a46376, 0xb5143323a7f8e16c, 0x92e74be10524c389, // x 2^-11028 ~= 10^-3320
0x7b7532e25fead4c8, 0x0df6ab8ac6a0ec2f, 0xf1fb6e82e4df4a77, // x 2^-10753 ~= 10^-3237
0x3b738d6a3caae67a, 0x346b2dd31826cfed, 0xc74c79bce7fe949f, // x 2^-10477 ~= 10^-3154
0x22d3a12777cee527, 0xe185ac46f6ef1993, 0xa424ef0bb5ad3129, // x 2^-10201 ~= 10^-3071
0xb7b6bccb9f60adec, 0x30ad7df78fe30cc8, 0x8730d40821cd89f3, // x 2^-9925 ~= 10^-2988
0x21049149d72d44d5, 0x1e86debc54dd290d, 0xdeb04cb82aec22cb, // x 2^-9650 ~= 10^-2905
0xeb69d287f5e7f920, 0x8d7e84a13801d034, 0xb7688f9800d26b3a, // x 2^-9374 ~= 10^-2822
0x47b3da9aeff7df71, 0x82678774d6c0ac59, 0x970e8fd25ead01e3, // x 2^-9098 ~= 10^-2739
0x50d3e92e2e4f8210, 0x9492db3d978aaca8, 0xf8d2dcaf37504b51, // x 2^-8823 ~= 10^-2656
0xf4ce72058f777a4c, 0xb9eb2c585e924efe, 0xcceef83fdedcc506, // x 2^-8547 ~= 10^-2573
0xb0e624a35b791884, 0x7104a98dbbb38b94, 0xa8c8fc3b03c3d1ed, // x 2^-8271 ~= 10^-2490
0x6c94ecd8291e2ac9, 0x978b03821014b68c, 0x8b03518396007c08, // x 2^-7995 ~= 10^-2407
0x96475208daa03ee3, 0x10eaa1481b149e5a, 0xe4fc163319551441, // x 2^-7720 ~= 10^-2324
0xd709a820ff4ac847, 0x75aab7cb5cb15414, 0xbc980b270680156a, // x 2^-7444 ~= 10^-2241
0xf273bca6b4de9e24, 0xb5025d88d4b252e1, 0x9b53e384eccabcf7, // x 2^-7168 ~= 10^-2158
0x6c55a0603a928f40, 0x9e20db16dfb6b461, 0xffdbcf7251089796, // x 2^-6893 ~= 10^-2075
0x9006db4d43cffe42, 0x9b4bca4cd6cec2db, 0xd2ba3f510a3aa638, // x 2^-6617 ~= 10^-1992
0xa6b3c457fd0cd4d6, 0x28a4de91ba868fbf, 0xad8ea05a5f27642a, // x 2^-6341 ~= 10^-1909
0xe7b14ed140f8d98e, 0x7b2f7d61ce5d426c, 0x8ef179291b6f5424, // x 2^-6065 ~= 10^-1826
0x4a964d052fd03e10, 0x06897060bf491e6e, 0xeb75718d285cd8bf, // x 2^-5790 ~= 10^-1743
0x22b2270f0e8dd87c, 0xa8510fa2f5a9e4de, 0xc1ed0ed498f7c54c, // x 2^-5514 ~= 10^-1660
0x09102915726a9905, 0x5a0eb896edc89b54, 0x9fb8208d65ea5eda, // x 2^-5238 ~= 10^-1577
0xb80d5f481d01deb9, 0x673f2aa50486f5ba, 0x838bd699b7c539e6, // x 2^-4962 ~= 10^-1494
0x668b62b20ec2633b, 0x8682604c7123f859, 0xd8af761f94d2db2c, // x 2^-4687 ~= 10^-1411
0xb2adaed8559cc199, 0x712339ba54f12372, 0xb276ce87987995d5, // x 2^-4411 ~= 10^-1328
0x6beb873308685711, 0xac1ce34246ed56ad, 0x92fc133455668c02, // x 2^-4135 ~= 10^-1245
0x593293d68a2261bc, 0x3c368f9497ca075d, 0xf21da89a29fa1c61, // x 2^-3860 ~= 10^-1162
0x854051f9f0e4ca66, 0x8c5d5a234eda57f7, 0xc768aa46d6d1b675, // x 2^-3584 ~= 10^-1079
0x333d09b2299c5e6b, 0xcf1f49c33399c5ac, 0xa43c26a751d4f7e7, // x 2^-3308 ~= 10^-996
0x25a440d8b1620532, 0x274ebc67c3e21943, 0x8743f33df0feed29, // x 2^-3032 ~= 10^-913
0x3ca95e3deb5be648, 0x52d18ccca1c558c2, 0xdecfcc3329238dd8, // x 2^-2757 ~= 10^-830
0x59d1a7704af3acd7, 0xfae7722c6af19467, 0xb78280c024488353, // x 2^-2481 ~= 10^-747
0x78813f3e80148049, 0x73b2baf13aa1c233, 0x9723ed8a28baf5ac, // x 2^-2205 ~= 10^-664
0xf296a8198aa40fb8, 0x235532b08487fe6a, 0xf8f60e812de0cd7d, // x 2^-1930 ~= 10^-581
0xa7fbdcb40b4f648f, 0x4f20ba9a64a7f6e7, 0xcd0bf4d206072167, // x 2^-1654 ~= 10^-498
0x8dbf63ea468c724f, 0xa0e25c08b5c189d6, 0xa8e0dbe18ffb82cf, // x 2^-1378 ~= 10^-415
0x765995c6cfd406ce, 0x4c3bcb5021afcc31, 0x8b16fb203055ac76, // x 2^-1102 ~= 10^-332
0xe1d09ab6fb409872, 0x82b7e12780e7401a, 0xe51c79a85916f484, // x 2^-827 ~= 10^-249
0x89cbe2422f9e1df9, 0x7415d448f6b6f0e7, 0xbcb2b812db11a5de, // x 2^-551 ~= 10^-166
0x605fe83842e4d290, 0xc986afbe3ee11aba, 0x9b69dbe1b548ce7c, // x 2^-275 ~= 10^-83
0x0000000000000000, 0x0000000000000000, 0x8000000000000000, // x 2^1 == 10^0 exactly
0x0d6953169e1c7a1e, 0xf50a3fa490c30190, 0xd2d80db02aabd62b, // x 2^276 ~= 10^83
0x3720b80c7d8ee39d, 0xaf561aa79a10ae6a, 0xada72ccc20054ae9, // x 2^552 ~= 10^166
0x7cb3f026a212df74, 0x29cb4d87f2a7400e, 0x8f05b1163ba6832d, // x 2^828 ~= 10^249
0x7dda22f9451d28a4, 0xe41c5bd18c57e88f, 0xeb96bf6ebadf77d8, // x 2^1103 ~= 10^332
0xd5da00e6e2d05e5d, 0x5e510c5a752f0f8e, 0xc2087cd3215a16ad, // x 2^1379 ~= 10^415
0x5603ba353e0b2fac, 0x48bbddc4d7359e49, 0x9fceb7ee780436f0, // x 2^1655 ~= 10^498
0x15ceea8df15e47c7, 0x6a83c85cf158c652, 0x839e71d847c1779e, // x 2^1931 ~= 10^581
0x514478d1fcd48eea, 0x3a4181cdda0d6e24, 0xd8ce1c3a2fffaea7, // x 2^2206 ~= 10^664
0xe8b634620f1062be, 0x7304c7fb8a2f8a8a, 0xb2900ca735bdf121, // x 2^2482 ~= 10^747
0xc3ec2fd9302c9bda, 0x729a6a7e830e1cf2, 0x9310dd78089bd66f, // x 2^2758 ~= 10^830
0x1750ef5f751be079, 0x52ccabc96fc88a23, 0xf23fe788c763dffa, // x 2^3033 ~= 10^913
0xaa80925ec1c80b65, 0x97681c548ff6c12f, 0xc784decd820a6180, // x 2^3309 ~= 10^996
0xb4212d4b435a2317, 0x8df0a55abbb2c99a, 0xa453618b9dfd92db, // x 2^3585 ~= 10^1079
0x939c2fedd434642a, 0x7d7de34bf5aa96b4, 0x875715282612729b, // x 2^3861 ~= 10^1162
0xb7d9a0e46bbebb36, 0x3b2057dea52d686b, 0xdeef5022af37f1f6, // x 2^4136 ~= 10^1245
0x931a74148ea64e59, 0xfe7fe67bd1074d0c, 0xb79c7593a1c17df0, // x 2^4412 ~= 10^1328
0xabd20df0f1f1ad54, 0x0fff83cc7fa6b77b, 0x97394e479b6573b1, // x 2^4688 ~= 10^1411
0x25f2467421674b7a, 0x828ff55a248bc026, 0xf919454d86f16685, // x 2^4963 ~= 10^1494
0xe32dbd7131e6ab7d, 0xf674dd4821982084, 0xcd28f57dc585d094, // x 2^5239 ~= 10^1577
0x866ab816a532b07d, 0xdc567471f9639b4e, 0xa8f8bee890f905c7, // x 2^5515 ~= 10^1660
0xaca3a975993a2626, 0xc41cf207a71d87e4, 0x8b2aa784c405e2f1, // x 2^5791 ~= 10^1743
0x731f0b7d820918bd, 0x355fde18e8448607, 0xe53ce1b25fb31788, // x 2^6066 ~= 10^1826
0x0be7c29568db3f20, 0xc1328a3f1bf4d2b8, 0xbccd68c49888be61, // x 2^6342 ~= 10^1909
0x9c6e0b1b927b7d3f, 0xffc9b96619da642a, 0x9b7fd75a060350cd, // x 2^6618 ~= 10^1992
0x2a84c8fb4bd2edc9, 0xa679df45d339389b, 0x80121ad60ca2c518, // x 2^6894 ~= 10^2075
0x0d4648d0876cf1c3, 0x48c67661c087fb5a, 0xd2f5e0469040e0eb, // x 2^7169 ~= 10^2158
0xfe2d99a281a011ac, 0x65c13361e6b2c078, 0xadbfbcb6c676a69b, // x 2^7445 ~= 10^2241
0xf4ec157aa4147562, 0xac89bfa5e79484a6, 0x8f19ebdf7661e3e9, // x 2^7721 ~= 10^2324
0xe945f8c80090be1f, 0x9b8672e64aadbed2, 0xebb812063c9e01db, // x 2^7996 ~= 10^2407
0xca12d8ad3b36d2e4, 0xd252322ea50ad274, 0xc223eeb2e1bde452, // x 2^8272 ~= 10^2490
0xf554fb41e5b3e384, 0x977acb4d4af624fc, 0x9fe55281904ba38b, // x 2^8548 ~= 10^2573
0xf3f69093398e2573, 0x111ae5735ec0e878, 0x83b10fb893300cde, // x 2^8824 ~= 10^2656
0x30f65a8da0d10429, 0x1eecf4cf8a0b25f5, 0xd8ecc6aa93e876fc, // x 2^9099 ~= 10^2739
0xa577f5f0c9f1e5a7, 0x91a5430ed623abf0, 0xb2a94e58da4930c3, // x 2^9375 ~= 10^2822
0x202d2f87585ec0d7, 0x7a63589863efd480, 0x9325aaac89304b57, // x 2^9651 ~= 10^2905
0x049544fbba3c01a1, 0x53accb0f60ac6095, 0xf2622b4f6c68d6ce, // x 2^9926 ~= 10^2988
0x268a0d5f9d5ce861, 0xfe40703e1a91de57, 0xc7a117517a09153b, // x 2^10202 ~= 10^3071
0xb6cd470a2a3b1d63, 0x5f963916b20ea587, 0xa46a9fb9111003bc, // x 2^10478 ~= 10^3154
0xa3101c09fd8e6e96, 0xa2c6328011db5211, 0x876a39c722f798a7, // x 2^10754 ~= 10^3237
0x8507e5fdb0ec5d83, 0x7ce93cc7f8feeed4, 0xdf0ed8875e7b8914, // x 2^11029 ~= 10^3320
0xe19b7ebe4c7bfbca, 0x40930d1129943838, 0xb7b66e12fe1af499, // x 2^11305 ~= 10^3403
0xc90c4ec15c21a357, 0xd91c86512d147305, 0x974eb20b241a65f6, // x 2^11581 ~= 10^3486
0xb90341199c02a4eb, 0x69e684f53db6e8ce, 0xf93c8114f6c31f8a, // x 2^11856 ~= 10^3569
0xa873f1318cef91cb, 0xbf8718466b31a7ca, 0xcd45fa43b1ce4c8e, // x 2^12132 ~= 10^3652
0xacfe0dcc5262e273, 0x6e1bbb68662fd27a, 0xa910a550810203f8, // x 2^12408 ~= 10^3735
0x59e7c8921bbe3758, 0x834743c5eab7dcea, 0x8b3e56b1b5c57589, // x 2^12684 ~= 10^3818
0x145eed64fda2e6af, 0x1c605bdcc764238f, 0xe55d4e51d30b5592, // x 2^12959 ~= 10^3901
0xb747164b17268ea2, 0xd8aa19f1d85da07d, 0xbce81d3cc784a1ca, // x 2^13235 ~= 10^3984
0x3666af1cb2f0356b, 0xc8dd55687a68bb70, 0x9b95d5ee4f80366d, // x 2^13511 ~= 10^4067
0x70d67261b5bde1e9, 0x1d76f2d15166ec20, 0x8024383bab19730d, // x 2^13787 ~= 10^4150
0x084a3ba0b748546a, 0xc67f9026f83dca47, 0xd313b714d3a1c65e, // x 2^14062 ~= 10^4233
0x4411a8127eea085e, 0x441eb397ffcdab0d, 0xadd8501ad0361d15, // x 2^14338 ~= 10^4316
0x7b62a54ed6233032, 0x75458a1c8300e014, 0x8f2e2985332eae98, // x 2^14614 ~= 10^4399
0x162d5b51a1dd9594, 0x655bb1b7aa4e8196, 0xebd96954582af06f, // x 2^14889 ~= 10^4482
0x55e6c62f920d3682, 0x79fd57cf7c37941c, 0xc23f6474669f4abe, // x 2^15165 ~= 10^4565
0x19482fa0ac45669c, 0x803c1cd864033781, 0x9ffbf04722750449, // x 2^15441 ~= 10^4648
0xa412d1f95f4624cd, 0xc95abe9ce589e048, 0x83c3b03af95c9674, // x 2^15717 ~= 10^4731
0xc1207e487c57b4e1, 0xf93dd2c7669a8ed1, 0xd90b75715d861b38, // x 2^15992 ~= 10^4814
0xeb20d9a25e0372bd, 0xb5073df6adc221b4, 0xb2c2939d0763fcac, // x 2^16268 ~= 10^4897
0x1a648c339e28cc45, 0xbd14f0fa3e24b6ae, 0x933a7ad2419ea0b5, // x 2^16544 ~= 10^4980
};
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT || SWIFT_DTOA_DOUBLE_SUPPORT || SWIFT_DTOA_FLOAT80_SUPPORT
// The power-of-10 tables do not directly store the associated binary
// exponent. That's because the binary exponent is a simple linear
// function of the decimal power (and vice versa), so it's just as
// fast (and uses much less memory) to compute it:
// The binary exponent corresponding to a particular power of 10.
// This matches the power-of-10 tables across the full range of Float80.
static int binaryExponentFor10ToThe(int p) {
return (int)(((((int64_t)p) * 55732705) >> 24) + 1);
}
// A decimal exponent that approximates a particular binary power.
static int decimalExponentFor2ToThe(int e) {
return (int)(((int64_t)e * 20201781) >> 26);
}
#endif
#if SWIFT_DTOA_FLOAT_SUPPORT
// Given a power `p`, this returns three values:
// * 64-bit fractions `lower` and `upper`
// * integer `exponent`
//
// The returned values satisty the following:
// ```
// lower * 2^exponent <= 10^p <= upper * 2^exponent
// ```
//
// In particular, if `10^p` can be exactly represented, this routine
// may return the same value for `lower` and `upper`.
//
static void intervalContainingPowerOf10_Float(int p, uint64_t *lower, uint64_t *upper, int *exponent) {
if (p < 0) {
uint64_t base = powersOf10_Float[p + 40];
int baseExponent = binaryExponentFor10ToThe(p + 40);
uint64_t tenToTheMinus40 = 0x8b61313bbabce2c6; // x 2^-132 ~= 10^-40
*lower = multiply64x64RoundingDown(base, tenToTheMinus40);
*upper = multiply64x64RoundingUp(base + 1, tenToTheMinus40 + 1);
*exponent = baseExponent - 132;
} else if (p <= 27) {
uint64_t exact = powersOf10_Float[p];
*upper = exact;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
} else {
uint64_t exact = powersOf10_Float[p];
*upper = exact + 1;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
}
}
#endif
#if SWIFT_DTOA_DOUBLE_SUPPORT
// As above, but returning 128-bit fractions suitable for
// converting doubles.
static void intervalContainingPowerOf10_Double(int p, swift_uint128_t *lower, swift_uint128_t *upper, int *exponent) {
if (p >= 0 && p <= 54) {
if (p <= 27) {
// Use one 64-bit exact value
swift_uint128_t exact;
initialize128WithHigh64(exact, powersOf10_Float[p]);
*upper = exact;
*lower = exact;
*exponent = binaryExponentFor10ToThe(p);
return;
} else {
// Multiply two 64-bit exact values to get a 128-bit exact value
swift_uint128_t base;
initialize128WithHigh64(base, powersOf10_Float[p - 27]);
int baseExponent = binaryExponentFor10ToThe(p - 27);
uint64_t extra = powersOf10_Float[27];
int extraExponent = binaryExponentFor10ToThe(27);
swift_uint128_t exact = multiply128x64RoundingDown(base, extra);
*upper = exact;
*lower = exact;
*exponent = baseExponent + extraExponent;
return;
}
}
// Multiply a 128-bit approximate value with a 64-bit exact value
int index = p + 400;
// Copy a pair of uint64_t into a swift_uint128_t
const uint64_t *base_p = powersOf10_Double + (index / 28) * 2;
swift_uint128_t base;
initialize128WithHighLow64(base, base_p[1], base_p[0]);
int extraPower = index % 28;
int baseExponent = binaryExponentFor10ToThe(p - extraPower);
int e = baseExponent;
if (extraPower > 0) {
int64_t extra = powersOf10_Float[extraPower];
e += binaryExponentFor10ToThe(extraPower);
*lower = multiply128x64RoundingDown(base, extra);
increment128(base);
*upper = multiply128x64RoundingUp(base, extra);
} else {
*lower = base;
increment128(base);
*upper = base;
}
*exponent = e;
}
#endif
#if SWIFT_DTOA_FLOAT80_SUPPORT
// As above, but returning 192-bit fractions suitable for
// converting float80.
static void intervalContainingPowerOf10_Float80(int p, swift_uint192_t *lower, swift_uint192_t *upper, int *exponent) {
if (p >= 0 && p <= 27) {
// We have an exact form, return a zero-width interval.
uint64_t exact = powersOf10_Float[p];
initialize192WithHighMidLow64(*upper, exact, 0, 0);
initialize192WithHighMidLow64(*lower, exact, 0, 0);
*exponent = binaryExponentFor10ToThe(p);
return;
}
int index = p + 5063;
const uint64_t *base_p = powersOf10_Float80 + (index / 83) * 3;
// Note: The low-order value in the Float80 table above
// is never UINT64_MAX, so there's never a carry from
// the increment here.
initialize192WithHighMidLow64(*upper, base_p[2], base_p[1], base_p[0] + 1);
initialize192WithHighMidLow64(*lower, base_p[2], base_p[1], base_p[0]);
int extraPower = index % 83;
int e = binaryExponentFor10ToThe(p - extraPower);
while (extraPower > 27) {
uint64_t power27 = powersOf10_Float[27];
multiply192x64RoundingDown(lower, power27);
multiply192x64RoundingUp(upper, power27);
e += binaryExponentFor10ToThe(27);
extraPower -= 27;
}
if (extraPower > 0) {
uint64_t extra = powersOf10_Float[extraPower];
multiply192x64RoundingDown(lower, extra);
multiply192x64RoundingUp(upper, extra);
e += binaryExponentFor10ToThe(extraPower);
}
*exponent = e;
}
#endif
|
/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/sstream.h"
#include "util/sexpr/option_declarations.h"
#include "library/expr_lt.h"
#include "kernel/find_fn.h"
#include "kernel/replace_fn.h"
#include "kernel/instantiate.h"
#include "library/util.h"
#include "library/trace.h"
#include "library/normalize.h"
#include "library/idx_metavar.h"
#include "library/type_context.h"
#include "library/annotation.h"
#include "library/exception.h"
#include "library/replace_visitor.h"
#include "library/attribute_manager.h"
#include "library/tactic/tactic_state.h"
#include "library/tactic/smt/hinst_lemmas.h"
#ifndef LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS
#define LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS 1024
#endif
namespace lean {
/*
Step 1: Selecting which variables we should track.
Given (H : Pi (a_1 : A_1) ... (a_n : A_n), B) where B is not a Pi,
we use the following procedure to decide which a_i's must be in
patterns used by heuristic instantiation.
- We say an a_i that must occur in a pattern is "trackable".
- The set of "trackable" a_i's is the least fix point of
a) If there is j > i, a_j is trackable, type(a_j) depends on a_i,
and type(a_i) is not higher-order, then
a_i is NOT trackable.
Reason: we can infer a_i from a_j using type inference.
b) a_i is a proposition -> a_i is NOT trackable.
Reason: we leave a_i as hypothesis whenever we instantiate H.
c) a_i is instance implicit -> a_i is NOT trackable.
We should use type class resolution to infer a_i.
Remark: we say a (multi-)pattern for H is valid iff it contains all
trackable a_i's.
We define the set of "residue" hypotheses a_i as the least fix point of
a) a_i is a proposition
b) a_i is not inst_implicit
c) a_i is not trackable
d) a_i is not a proposition and there is no j > i s.t. a_j is not residue
and type(a_j) depends on a_i, and type(a_i) is not higher-order
That is, if a_i is a "residue" hypothesis, we cannot infer it
by using type inference or type class resolution.
Residue hypotheses are the hypotheses for any instance of H produced by
the heuristic instantiation module.
Step 2a: H contains user-provided pattern hints
The user may provide pattern hints by annotating subterms of H using
the notation (:t:).
Example: The term (g x y) is a pattern hint at (H : forall x y, f (:g x y:) = x).
Let S be the set of patterns hints contained in H.
Then, a multi-pattern P is any subset of S s.t.
a) P contains all trackable a_i's in H
b) There is no strict subset of P that contains all trackable a_i's in H
If S is not empty, Lean will generate an error if there is no multi-pattern P for S.
The option pattern.max_steps is a threshold on the number of steps performed
Lean will generate an error if more than pattern.max_steps are performed while processing the set S.
Step 2b: H does NOT contain user-provided pattern hints.
When pattern hints are not provided, Lean uses a heuristic for selecting patterns.
- Lean will only consider terms that do NOT contain constants marked with the hint attribute
[no_pattern]. In the standard library, we use this attribute to mark constants such as
'and', 'or', 'not', 'iff', 'eq', 'heq', etc.
- Lean will look for candidate patterns in B and residue hypotheses.
Actually, it uses the following approach (TODO(Leo): should we provide options to control it?)
1) Lean tries to find multi-patterns in B (only). If it finds at least one, then it is done, otherwise
2) Lean tries to find multi-patterns in residue hypotheses only.
If it finds at leat one, then it is done, otherwise
3) Lean tries to find multi-patterns using residue hypotheses and B.
If it can't find at least one, it signs an error.
- So, from now on, we will assume T is the set of terms where we will look for patterns.
We use trackable(p) to denote the set of trackable variables in p.
Lean will try to find "minimal" patterns and rank candidates in the following way
Given terms p and q where both do not contain [no_pattern] constants, we say
term p is "better" than q
IFF
1) trackable(p) is a strict superset of trackable(q) OR
2) trackable(p) == trackable(q), but p is as subterm of q.
Given T, we collect a set of candidates C s.t., for each c_1 in C, there is no c_2 in C s.t. c_2 is better than c_1.
If there is c in C s.t. c contains all trackable a_i's, then all such c in C is our set of patterns (done).
To mimize the number of multi-patterns to be considered, we delete from C
any candidate c_1 in C if there is a c_2 in C s.t.
trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
We say a subset M of C is a multi-pattern if M contains all trackable variables.
We say a multi-pattern M is minimal if no strict subset of M is a multi-pattern.
If the set of minimal multi-patterns for C is bigger than `pattern.max`, then we generate an error.
That is, the user should provide pattern-hints.
*/
static name * g_no_inst_pattern_attr = nullptr;
static basic_attribute const & get_no_inst_pattern_attribute() {
return static_cast<basic_attribute const &>(get_system_attribute(*g_no_inst_pattern_attr));
}
bool has_no_inst_pattern_attribute(environment const & env, name const & d) {
return has_attribute(env, *g_no_inst_pattern_attr, d);
}
environment add_no_inst_pattern_attribute(environment const & env, name const & n) {
return get_no_inst_pattern_attribute().set(env, get_dummy_ios(), n, LEAN_DEFAULT_PRIORITY, true);
}
name_set get_no_inst_patterns(environment const & env) {
buffer<name> ds;
get_no_inst_pattern_attribute().get_instances(env, ds);
return to_name_set(ds);
}
static name * g_pattern_hint = nullptr;
bool is_pattern_hint(expr const & e) { return is_annotation(e, *g_pattern_hint); }
expr const & get_pattern_hint_arg(expr const & e) { lean_assert(is_pattern_hint(e)); return get_annotation_arg(e); }
bool has_pattern_hints(expr const & e) {
return static_cast<bool>(find(e, [](expr const & e, unsigned) { return is_pattern_hint(e); }));
}
expr mk_pattern_hint(expr const & e) {
if (has_pattern_hints(e))
throw exception("invalid pattern hint, nested patterns hints are not allowed");
if (!is_app(e))
throw generic_exception(e, "invalid pattern hint, pattern hints must be applications");
return mk_annotation(*g_pattern_hint, e);
}
typedef rb_tree<unsigned, unsigned_cmp> idx_metavar_set;
static bool is_higher_order(type_context & ctx, expr const & e) {
/* Remark: is it too expensive to use ctx.relaxed_whnf here? */
return is_pi(ctx.whnf(ctx.infer(e)));
}
/** \brief Given type of the form (Pi (a_1 : A_1) ... (a_n : A_n), B) (or reducible to something of this form),
create n idx_metavars (one for each a_i), store the meta-variables in mvars,
and store in trackable and residue the subsets of these meta-variables as
described in the beginning of this file. Then returns B (instantiated with the new meta-variables) */
expr extract_trackable(type_context & ctx, expr const & type,
buffer<expr> & mvars,
buffer<bool> & inst_implicit_flags,
idx_metavar_set & trackable, idx_metavar_set & residue) {
// 1. Create mvars and initialize trackable and residue sets
expr it = type;
while (true) {
if (!is_pi(it)) {
expr new_it = ctx.relaxed_whnf(it);
if (!is_pi(new_it))
break; // consumed all arguments
it = new_it;
}
lean_assert(is_pi(it));
expr new_mvar = ctx.mk_tmp_mvar(binding_domain(it));
lean_assert(is_idx_metavar(new_mvar));
mvars.push_back(new_mvar);
bool is_inst_implicit = binding_info(it).is_inst_implicit();
inst_implicit_flags.push_back(is_inst_implicit);
bool is_prop = ctx.is_prop(binding_domain(it));
if (!is_inst_implicit) {
unsigned midx = to_meta_idx(new_mvar);
if (is_prop)
residue.insert(midx);
else
trackable.insert(midx);
}
it = instantiate(binding_body(it), new_mvar);
}
expr B = it;
unsigned n = mvars.size();
// 2. Compute trackable fixpoint
bool modified;
do {
modified = false;
for (unsigned i = 0; i < n; i++) {
unsigned midx = to_meta_idx(mvars[i]);
if (!trackable.contains(midx))
continue; // variable is not in the trackable set
// There is no j > i, mvars[j] is trackable, type(mvars[j]) depends on mvars[i],
// and type(mvars[i]) is not higher-order.
if (is_higher_order(ctx, mvars[i]))
continue;
unsigned j = i+1;
for (; j < n; j++) {
if (trackable.contains(to_meta_idx(mvars[j])) &&
occurs(mvars[i], ctx.infer(mvars[j]))) {
// we can infer mvars[i] using type inference
break;
}
}
if (j == n)
continue;
trackable.erase(midx);
modified = true;
}
} while (modified);
// 3. Compute residue fixpoint
do {
modified = false;
for (unsigned i = 0; i < n; i++) {
unsigned midx = to_meta_idx(mvars[i]);
if (!residue.contains(midx))
continue; // variable is not in the residue set
// There is no j > i s.t. mvars[j] is not residue
// and type(mvars[j]) depends on mvars[i], and type(mvars[i]) is not higher-order
if (is_higher_order(ctx, mvars[i]))
continue;
unsigned j = i+1;
for (; j < n; j++) {
if (!residue.contains(to_meta_idx(mvars[j])) &&
occurs(mvars[i], ctx.infer(mvars[j]))) {
// we can infer mvars[i] using type inference
break;
}
}
if (j == n)
continue;
residue.erase(midx);
modified = true;
}
} while (modified);
return B;
}
struct mk_hinst_lemma_fn {
type_context & m_ctx;
transparency_mode m_md_norm;
name_set m_no_inst_patterns;
expr m_H;
unsigned m_num_uvars;
unsigned m_max_steps;
/* If m_simp is true, the pattern inference procedure assumes the given lemma is a [simp] lemma.
That is, the conclusion is of the form (t ~ s), and it will try to use t as a pattern. */
bool m_simp;
buffer<expr> m_mvars;
idx_metavar_set m_trackable;
idx_metavar_set m_residue;
unsigned m_num_steps;
name m_id;
mk_hinst_lemma_fn(type_context & ctx, transparency_mode md_norm, expr const & H,
unsigned num_uvars, unsigned max_steps, bool simp,
name const & id):
m_ctx(ctx), m_md_norm(md_norm), m_no_inst_patterns(get_no_inst_patterns(ctx.env())),
m_H(H), m_num_uvars(num_uvars), m_max_steps(max_steps),
m_simp(simp), m_id(id) {}
struct candidate {
expr m_expr;
idx_metavar_set m_mvars;
candidate() {}
candidate(expr const & e):
m_expr(e) {
for_each(e, [&](expr const & e, unsigned) {
if (is_idx_metavar(e))
m_mvars.insert(to_meta_idx(e));
return true;
});
}
candidate(expr const & e, idx_metavar_set const & mvars):m_expr(e), m_mvars(mvars) {}
};
struct candidate_lt {
int operator()(candidate const & c1, candidate const & c2) const { return expr_quick_cmp()(c1.m_expr, c2.m_expr); }
};
typedef rb_tree<candidate, candidate_lt> candidate_set;
expr normalize(expr const & e) {
type_context::transparency_scope _(m_ctx, m_md_norm);
return ::lean::normalize(m_ctx, e);
}
void collect_pattern_hints(expr const & e, candidate_set & s) {
for_each(e, [&](expr const & e, unsigned) {
if (is_pattern_hint(e)) {
expr hint = get_pattern_hint_arg(e);
// TODO(Leo): if hint was unfolded and is not an application anymore, we should
// report to user this fact.
if (is_app(hint)) {
s.insert(candidate(normalize(hint)));
}
return false;
}
return true;
});
}
candidate_set collect_pattern_hints(buffer<expr> const & mvars, buffer<expr> const & residue, expr const & B) {
candidate_set s;
for (expr const & mvar : mvars)
collect_pattern_hints(m_ctx.infer(mvar), s);
for (expr const & r : residue)
collect_pattern_hints(m_ctx.infer(r), s);
collect_pattern_hints(B, s);
return s;
}
candidate_set m_candidates;
void save_candidates(candidate_set const & s) {
m_candidates.merge(s);
}
candidate_set collect_core(expr const & a) {
switch (a.kind()) {
case expr_kind::Var:
lean_unreachable();
case expr_kind::Sort: case expr_kind::Constant:
case expr_kind::Meta: case expr_kind::Local:
case expr_kind::Pi:
return candidate_set();
case expr_kind::Let:
/* TODO(Leo): Decide whether we should support let-expressions or not.
IF we don't, then we should report this occurrence users. */
return candidate_set();
case expr_kind::Lambda:
if (has_idx_metavar(a))
return candidate_set(candidate(a));
else
return candidate_set();
case expr_kind::Macro:
for (unsigned i = 0; i < macro_num_args(a); i++) {
candidate_set s = collect_core(macro_arg(a, i));
save_candidates(s);
}
return candidate_set();
case expr_kind::App: {
buffer<expr> args;
expr const & fn = get_app_args(a, args);
buffer<candidate_set> arg_candidates;
bool forbidden = !is_local(fn) && (!is_constant(fn) || m_no_inst_patterns.contains(const_name(fn)));
if (forbidden) {
for (expr const & arg : args) {
candidate_set s = collect_core(arg);
save_candidates(s);
}
return candidate_set();
} else {
candidate_set ss;
idx_metavar_set mvars;
for (expr const & arg : args) {
if (is_idx_metavar(arg)) {
if (m_trackable.contains(to_meta_idx(arg))) {
mvars.insert(to_meta_idx(arg));
}
} else {
candidate_set s = collect_core(arg);
s.for_each([&](candidate const & c) {
ss.insert(c);
mvars.merge(c.m_mvars);
});
}
}
if (ss.find_if([&](candidate const & c) { return mvars == c.m_mvars; })) {
return ss;
} else if (!mvars.empty()) {
// a subsumes all children candidates
return candidate_set(candidate(a, mvars));
} else {
return candidate_set();
}
}
}}
lean_unreachable();
}
candidate_set collect(expr const & a) {
m_candidates = candidate_set();
if (m_simp) {
expr lhs, rhs;
if (is_eq(a, lhs, rhs) || is_heq(a, lhs, rhs)) {
m_candidates.insert(candidate(normalize(lhs)));
}
} else {
save_candidates(collect_core(normalize(a)));
}
return m_candidates;
}
void mk_multi_patterns_core(unsigned i, buffer<candidate> const & s, buffer<expr> & mp, idx_metavar_set const & mvars, buffer<multi_pattern> & mps) {
m_num_steps++;
if (m_num_steps > m_max_steps)
throw exception(sstream() << "pattern inference failed for '" << m_id << "', the maximum number (" << m_max_steps << ") of steps has been reached "
"(possible solutions: provide pattern hints using the notation '(: t :)' for marking subterms; increase threshold using option pattern.max_steps)");
if (i == s.size())
return;
candidate const & c = s[i];
if (!mvars.is_strict_superset(c.m_mvars)) {
// candidate s[i] contributes with new variables
unsigned sz = mp.size();
mp.push_back(c.m_expr);
idx_metavar_set new_mvars = mvars;
new_mvars.merge(c.m_mvars);
if (new_mvars.is_superset(m_trackable)) {
// found multi-pattern
mps.push_back(to_list(mp));
} else {
// include s[i]
mk_multi_patterns_core(i+1, s, mp, new_mvars, mps);
}
mp.shrink(sz);
}
// do not include s[i];
mk_multi_patterns_core(i+1, s, mp, mvars, mps);
}
/* If heuristic is true, then
1. Give preference to unary patterns
2. If there are no unary patterns, then
a) delete any candidate c_1 if there is a c_2 s.t.
trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
b) delete any candidate c_1 if there is a c_2 s.t.
c_1 is a subterm of c_2, and c_2.m_vars is a strict superset of c_1.m_vars */
list<multi_pattern> mk_multi_patterns_using(candidate_set s, bool heuristic) {
if (heuristic) {
buffer<multi_pattern> unit_patterns;
s.for_each([&](candidate const & c) {
if (c.m_mvars.is_superset(m_trackable))
unit_patterns.push_back(to_list(c.m_expr));
});
if (!unit_patterns.empty()) {
return to_list(unit_patterns);
}
buffer<candidate> to_delete;
s.for_each([&](candidate const & c_1) {
if (s.find_if([&](candidate const & c_2) {
return
// a) delete any candidate c_1 if there is a c_2 s.t.
// trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
(c_1.m_mvars == c_2.m_mvars && get_weight(c_1.m_expr) > get_weight(c_2.m_expr)) ||
// b) delete any candidate c_1 if there is a c_2 s.t.
// c_1 is a subterm of c_2, and c_2.m_vars is a strict superset of c_1.m_vars
(occurs(c_1.m_expr, c_2.m_expr) && c_2.m_mvars.is_strict_superset(c_1.m_mvars));
})) {
to_delete.push_back(c_1);
}
});
for (candidate const & c : to_delete) {
s.erase(c);
}
}
buffer<candidate> s_buffer;
s.to_buffer(s_buffer);
buffer<multi_pattern> mps;
buffer<expr> mp;
m_num_steps = 0;
mk_multi_patterns_core(0, s_buffer, mp, idx_metavar_set(), mps);
return to_list(mps);
}
expr replace_mvars(expr const & e, buffer<expr> const & subst) {
return replace(e,
[&](expr const & e) {
if (!has_expr_metavar(e))
return some_expr(e);
if (is_idx_metavar(e))
return some_expr(subst[to_meta_idx(e)]);
else
return none_expr();
});
}
/* Create proof by pushing all residue hypotheses to the "end".
Residue hypotheses are converted into local constants.
Remaining metavariables are "renamed" (i.e., renumbered to avoid gaps due to residue hypotheses moved to the end).
Trackable set is updated.
subst will contain the mvars renaming */
expr mk_proof(type_context::tmp_locals & locals, buffer<expr> & new_residue, buffer<expr> & subst) {
unsigned j = 0;
bool found_residue = false;
bool only_tail_residue = true;
for (unsigned i = 0; i < m_mvars.size(); i++) {
expr new_type = m_ctx.infer(m_mvars[i]);
if (i != j)
new_type = replace_mvars(new_type, subst);
if (m_residue.contains(to_meta_idx(m_mvars[i]))) {
found_residue = true;
expr res = locals.push_local("_x", new_type);
new_residue.push_back(res);
subst.push_back(res);
} else {
if (found_residue)
only_tail_residue = false;
expr new_mvar;
if (j == i) {
new_mvar = m_mvars[i];
} else {
new_mvar = mk_idx_metavar(j, new_type);
if (m_trackable.contains(i)) {
m_trackable.erase(i);
m_trackable.insert(j);
}
m_mvars[j] = new_mvar;
}
j++;
subst.push_back(new_mvar);
}
}
m_mvars.shrink(j);
if (only_tail_residue) {
return mk_app(m_H, m_mvars);
} else {
return locals.mk_lambda(mk_app(m_H, subst));
}
}
struct try_again_without_hints {};
struct erase_hints_fn : public replace_visitor {
virtual expr visit_macro(expr const & e) override {
if (is_pattern_hint(e)) {
return visit(get_annotation_arg(e));
} else {
return replace_visitor::visit_macro(e);
}
}
};
hinst_lemma operator()(bool erase_hints) {
expr H_type = m_ctx.infer(m_H);
if (erase_hints) {
H_type = erase_hints_fn()(H_type);
}
buffer<bool> inst_implicit_flags;
expr B = extract_trackable(m_ctx, H_type, m_mvars, inst_implicit_flags, m_trackable, m_residue);
lean_assert(m_mvars.size() == inst_implicit_flags.size());
buffer<expr> subst;
buffer<expr> residue_locals;
type_context::tmp_locals locals(m_ctx);
expr proof = mk_proof(locals, residue_locals, subst);
B = replace_mvars(B, subst);
candidate_set hints = collect_pattern_hints(m_mvars, residue_locals, B);
list<multi_pattern> mps;
if (!hints.empty()) {
mps = mk_multi_patterns_using(hints, false);
} else {
if (has_pattern_hints(H_type)) {
throw try_again_without_hints();
}
buffer<expr> places;
candidate_set B_candidates = collect(B);
if (auto r1 = mk_multi_patterns_using(B_candidates, true)) {
mps = r1;
} else if (!m_simp) {
candidate_set residue_candidates;
for (expr const & r : residue_locals) {
residue_candidates.merge(collect(m_ctx.infer(r)));
}
if (auto r2 = mk_multi_patterns_using(residue_candidates, true)) {
mps = r2;
} else if (!residue_candidates.empty() && !B_candidates.empty()) {
candidate_set all_candidates = B_candidates;
all_candidates.merge(residue_candidates);
mps = mk_multi_patterns_using(all_candidates, true);
}
}
}
if (!mps) {
throw exception(sstream() << "pattern inference failed for '" << m_id << "', "
"(solution: provide pattern hints using the notation '(: t :)' )");
}
hinst_lemma r;
r.m_id = m_id;
r.m_num_uvars = m_num_uvars;
r.m_num_mvars = m_mvars.size();
r.m_multi_patterns = mps;
r.m_mvars = to_list(m_mvars);
r.m_is_inst_implicit = to_list(inst_implicit_flags);
r.m_prop = m_ctx.infer(proof);
r.m_proof = proof;
r.m_expr = m_H;
return r;
}
};
hinst_lemma mk_hinst_lemma_core(type_context & ctx, transparency_mode md_norm, expr const & H, unsigned num_uvars,
unsigned max_steps, bool simp, name const & id) {
try {
type_context::tmp_mode_scope tscope(ctx, num_uvars, 0);
bool erase_hints = false;
return mk_hinst_lemma_fn(ctx, md_norm, H, num_uvars, max_steps, simp, id)(erase_hints);
} catch (mk_hinst_lemma_fn::try_again_without_hints &) {
type_context::tmp_mode_scope tscope(ctx, num_uvars, 0);
try {
bool erase_hints = true;
return mk_hinst_lemma_fn(ctx, md_norm, H, num_uvars, max_steps, simp, id)(erase_hints);
} catch (mk_hinst_lemma_fn::try_again_without_hints &) {
lean_unreachable();
}
}
}
static name * g_hinst_lemma_max_steps = nullptr;
unsigned get_hinst_lemma_max_steps(options const & o) {
return o.get_unsigned(*g_hinst_lemma_max_steps, LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS);
}
hinst_lemma mk_hinst_lemma(type_context & ctx, transparency_mode md_norm, expr const & H, bool simp) {
unsigned max_steps = get_hinst_lemma_max_steps(ctx.get_options());
name id;
if (is_local(H))
id = local_pp_name(H);
return mk_hinst_lemma_core(ctx, md_norm, H, 0, max_steps, simp, id);
}
hinst_lemma mk_hinst_lemma(type_context & ctx, transparency_mode md_norm, name const & c, bool simp) {
unsigned max_steps = get_hinst_lemma_max_steps(ctx.get_options());
declaration const & d = ctx.env().get(c);
buffer<level> us;
unsigned num_us = d.get_num_univ_params();
for (unsigned i = 0; i < num_us; i++)
us.push_back(mk_idx_metauniv(i));
expr H = mk_constant(c, to_list(us));
name id = c;
return mk_hinst_lemma_core(ctx, md_norm, H, num_us, max_steps, simp, id);
}
format pp_hinst_lemma(formatter const & fmt, hinst_lemma const & h) {
format r;
r += format(h.m_id) + comma() + line();
bool first1 = true;
format pats;
for (multi_pattern const & mp : h.m_multi_patterns) {
if (first1) first1 = false; else pats += comma() + line();
format pat;
bool first2 = true;
for (expr const & p : mp) {
if (first2) first2 = false; else pat += comma() + line();
pat += fmt(p);
}
pats += group(bracket("{", pat, "}"));
}
char const * n = "patterns:";
r += nest(strlen(n), format(n) + line() + group(bracket("{", pats, "}")));
return group(bracket("[", r, "]"));
}
void initialize_hinst_lemmas() {
g_pattern_hint = new name("pattern_hint");
register_annotation(*g_pattern_hint);
g_no_inst_pattern_attr = new name({"no_inst_pattern"});
/* Add validation */
register_system_attribute(basic_attribute(*g_no_inst_pattern_attr, "do not consider terms containing this declaration in the pattern inference procedure"));
g_hinst_lemma_max_steps = new name{"hinst_lemma", "pattern", "max_steps"};
register_unsigned_option(*g_hinst_lemma_max_steps, LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS,
"(hinst_lemma) max number of steps performed by pattern inference procedure for heuristic instantiation lemmas, "
"we have this threshold because in the worst case this procedure may take "
"an exponetial number of steps");
}
void finalize_hinst_lemmas() {
delete g_no_inst_pattern_attr;
delete g_hinst_lemma_max_steps;
}
}
chore(library/tactic/smt/hinst_lemmas): style
/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/sstream.h"
#include "util/sexpr/option_declarations.h"
#include "library/expr_lt.h"
#include "kernel/find_fn.h"
#include "kernel/replace_fn.h"
#include "kernel/instantiate.h"
#include "library/util.h"
#include "library/trace.h"
#include "library/normalize.h"
#include "library/idx_metavar.h"
#include "library/type_context.h"
#include "library/annotation.h"
#include "library/exception.h"
#include "library/replace_visitor.h"
#include "library/attribute_manager.h"
#include "library/tactic/tactic_state.h"
#include "library/tactic/smt/hinst_lemmas.h"
#ifndef LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS
#define LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS 1024
#endif
namespace lean {
/*
Step 1: Selecting which variables we should track.
Given (H : Pi (a_1 : A_1) ... (a_n : A_n), B) where B is not a Pi,
we use the following procedure to decide which a_i's must be in
patterns used by heuristic instantiation.
- We say an a_i that must occur in a pattern is "trackable".
- The set of "trackable" a_i's is the least fix point of
a) If there is j > i, a_j is trackable, type(a_j) depends on a_i,
and type(a_i) is not higher-order, then
a_i is NOT trackable.
Reason: we can infer a_i from a_j using type inference.
b) a_i is a proposition -> a_i is NOT trackable.
Reason: we leave a_i as hypothesis whenever we instantiate H.
c) a_i is instance implicit -> a_i is NOT trackable.
We should use type class resolution to infer a_i.
Remark: we say a (multi-)pattern for H is valid iff it contains all
trackable a_i's.
We define the set of "residue" hypotheses a_i as the least fix point of
a) a_i is a proposition
b) a_i is not inst_implicit
c) a_i is not trackable
d) a_i is not a proposition and there is no j > i s.t. a_j is not residue
and type(a_j) depends on a_i, and type(a_i) is not higher-order
That is, if a_i is a "residue" hypothesis, we cannot infer it
by using type inference or type class resolution.
Residue hypotheses are the hypotheses for any instance of H produced by
the heuristic instantiation module.
Step 2a: H contains user-provided pattern hints
The user may provide pattern hints by annotating subterms of H using
the notation (:t:).
Example: The term (g x y) is a pattern hint at (H : forall x y, f (:g x y:) = x).
Let S be the set of patterns hints contained in H.
Then, a multi-pattern P is any subset of S s.t.
a) P contains all trackable a_i's in H
b) There is no strict subset of P that contains all trackable a_i's in H
If S is not empty, Lean will generate an error if there is no multi-pattern P for S.
The option pattern.max_steps is a threshold on the number of steps performed
Lean will generate an error if more than pattern.max_steps are performed while processing the set S.
Step 2b: H does NOT contain user-provided pattern hints.
When pattern hints are not provided, Lean uses a heuristic for selecting patterns.
- Lean will only consider terms that do NOT contain constants marked with the hint attribute
[no_pattern]. In the standard library, we use this attribute to mark constants such as
'and', 'or', 'not', 'iff', 'eq', 'heq', etc.
- Lean will look for candidate patterns in B and residue hypotheses.
Actually, it uses the following approach (TODO(Leo): should we provide options to control it?)
1) Lean tries to find multi-patterns in B (only). If it finds at least one, then it is done, otherwise
2) Lean tries to find multi-patterns in residue hypotheses only.
If it finds at leat one, then it is done, otherwise
3) Lean tries to find multi-patterns using residue hypotheses and B.
If it can't find at least one, it signs an error.
- So, from now on, we will assume T is the set of terms where we will look for patterns.
We use trackable(p) to denote the set of trackable variables in p.
Lean will try to find "minimal" patterns and rank candidates in the following way
Given terms p and q where both do not contain [no_pattern] constants, we say
term p is "better" than q
IFF
1) trackable(p) is a strict superset of trackable(q) OR
2) trackable(p) == trackable(q), but p is as subterm of q.
Given T, we collect a set of candidates C s.t., for each c_1 in C, there is no c_2 in C s.t. c_2 is better than c_1.
If there is c in C s.t. c contains all trackable a_i's, then all such c in C is our set of patterns (done).
To mimize the number of multi-patterns to be considered, we delete from C
any candidate c_1 in C if there is a c_2 in C s.t.
trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
We say a subset M of C is a multi-pattern if M contains all trackable variables.
We say a multi-pattern M is minimal if no strict subset of M is a multi-pattern.
If the set of minimal multi-patterns for C is bigger than `pattern.max`, then we generate an error.
That is, the user should provide pattern-hints.
*/
static name * g_no_inst_pattern_attr = nullptr;
static basic_attribute const & get_no_inst_pattern_attribute() {
return static_cast<basic_attribute const &>(get_system_attribute(*g_no_inst_pattern_attr));
}
bool has_no_inst_pattern_attribute(environment const & env, name const & d) {
return has_attribute(env, *g_no_inst_pattern_attr, d);
}
environment add_no_inst_pattern_attribute(environment const & env, name const & n) {
return get_no_inst_pattern_attribute().set(env, get_dummy_ios(), n, LEAN_DEFAULT_PRIORITY, true);
}
name_set get_no_inst_patterns(environment const & env) {
buffer<name> ds;
get_no_inst_pattern_attribute().get_instances(env, ds);
return to_name_set(ds);
}
static name * g_pattern_hint = nullptr;
bool is_pattern_hint(expr const & e) { return is_annotation(e, *g_pattern_hint); }
expr const & get_pattern_hint_arg(expr const & e) { lean_assert(is_pattern_hint(e)); return get_annotation_arg(e); }
bool has_pattern_hints(expr const & e) {
return static_cast<bool>(find(e, [](expr const & e, unsigned) { return is_pattern_hint(e); }));
}
expr mk_pattern_hint(expr const & e) {
if (has_pattern_hints(e))
throw exception("invalid pattern hint, nested patterns hints are not allowed");
if (!is_app(e))
throw generic_exception(e, "invalid pattern hint, pattern hints must be applications");
return mk_annotation(*g_pattern_hint, e);
}
typedef rb_tree<unsigned, unsigned_cmp> idx_metavar_set;
static bool is_higher_order(type_context & ctx, expr const & e) {
/* Remark: is it too expensive to use ctx.relaxed_whnf here? */
return is_pi(ctx.whnf(ctx.infer(e)));
}
/** \brief Given type of the form (Pi (a_1 : A_1) ... (a_n : A_n), B) (or reducible to something of this form),
create n idx_metavars (one for each a_i), store the meta-variables in mvars,
and store in trackable and residue the subsets of these meta-variables as
described in the beginning of this file. Then returns B (instantiated with the new meta-variables) */
expr extract_trackable(type_context & ctx, expr const & type,
buffer<expr> & mvars,
buffer<bool> & inst_implicit_flags,
idx_metavar_set & trackable, idx_metavar_set & residue) {
// 1. Create mvars and initialize trackable and residue sets
expr it = type;
while (true) {
if (!is_pi(it)) {
expr new_it = ctx.relaxed_whnf(it);
if (!is_pi(new_it))
break; // consumed all arguments
it = new_it;
}
lean_assert(is_pi(it));
expr new_mvar = ctx.mk_tmp_mvar(binding_domain(it));
lean_assert(is_idx_metavar(new_mvar));
mvars.push_back(new_mvar);
bool is_inst_implicit = binding_info(it).is_inst_implicit();
inst_implicit_flags.push_back(is_inst_implicit);
bool is_prop = ctx.is_prop(binding_domain(it));
if (!is_inst_implicit) {
unsigned midx = to_meta_idx(new_mvar);
if (is_prop)
residue.insert(midx);
else
trackable.insert(midx);
}
it = instantiate(binding_body(it), new_mvar);
}
expr B = it;
unsigned n = mvars.size();
// 2. Compute trackable fixpoint
bool modified;
do {
modified = false;
for (unsigned i = 0; i < n; i++) {
unsigned midx = to_meta_idx(mvars[i]);
if (!trackable.contains(midx))
continue; // variable is not in the trackable set
// There is no j > i, mvars[j] is trackable, type(mvars[j]) depends on mvars[i],
// and type(mvars[i]) is not higher-order.
if (is_higher_order(ctx, mvars[i]))
continue;
unsigned j = i+1;
for (; j < n; j++) {
if (trackable.contains(to_meta_idx(mvars[j])) &&
occurs(mvars[i], ctx.infer(mvars[j]))) {
// we can infer mvars[i] using type inference
break;
}
}
if (j == n)
continue;
trackable.erase(midx);
modified = true;
}
} while (modified);
// 3. Compute residue fixpoint
do {
modified = false;
for (unsigned i = 0; i < n; i++) {
unsigned midx = to_meta_idx(mvars[i]);
if (!residue.contains(midx))
continue; // variable is not in the residue set
// There is no j > i s.t. mvars[j] is not residue
// and type(mvars[j]) depends on mvars[i], and type(mvars[i]) is not higher-order
if (is_higher_order(ctx, mvars[i]))
continue;
unsigned j = i+1;
for (; j < n; j++) {
if (!residue.contains(to_meta_idx(mvars[j])) &&
occurs(mvars[i], ctx.infer(mvars[j]))) {
// we can infer mvars[i] using type inference
break;
}
}
if (j == n)
continue;
residue.erase(midx);
modified = true;
}
} while (modified);
return B;
}
struct mk_hinst_lemma_fn {
type_context & m_ctx;
transparency_mode m_md_norm;
name_set m_no_inst_patterns;
expr m_H;
unsigned m_num_uvars;
unsigned m_max_steps;
/* If m_simp is true, the pattern inference procedure assumes the given lemma is a [simp] lemma.
That is, the conclusion is of the form (t ~ s), and it will try to use t as a pattern. */
bool m_simp;
buffer<expr> m_mvars;
idx_metavar_set m_trackable;
idx_metavar_set m_residue;
unsigned m_num_steps;
name m_id;
mk_hinst_lemma_fn(type_context & ctx, transparency_mode md_norm, expr const & H,
unsigned num_uvars, unsigned max_steps, bool simp,
name const & id):
m_ctx(ctx), m_md_norm(md_norm), m_no_inst_patterns(get_no_inst_patterns(ctx.env())),
m_H(H), m_num_uvars(num_uvars), m_max_steps(max_steps),
m_simp(simp), m_id(id) {}
struct candidate {
expr m_expr;
idx_metavar_set m_mvars;
candidate() {}
candidate(expr const & e):
m_expr(e) {
for_each(e, [&](expr const & e, unsigned) {
if (is_idx_metavar(e))
m_mvars.insert(to_meta_idx(e));
return true;
});
}
candidate(expr const & e, idx_metavar_set const & mvars):m_expr(e), m_mvars(mvars) {}
};
struct candidate_lt {
int operator()(candidate const & c1, candidate const & c2) const { return expr_quick_cmp()(c1.m_expr, c2.m_expr); }
};
typedef rb_tree<candidate, candidate_lt> candidate_set;
expr normalize(expr const & e) {
type_context::transparency_scope _(m_ctx, m_md_norm);
return ::lean::normalize(m_ctx, e);
}
void collect_pattern_hints(expr const & e, candidate_set & s) {
for_each(e, [&](expr const & e, unsigned) {
if (is_pattern_hint(e)) {
expr hint = get_pattern_hint_arg(e);
// TODO(Leo): if hint was unfolded and is not an application anymore, we should
// report to user this fact.
if (is_app(hint)) {
s.insert(candidate(normalize(hint)));
}
return false;
}
return true;
});
}
candidate_set collect_pattern_hints(buffer<expr> const & mvars, buffer<expr> const & residue, expr const & B) {
candidate_set s;
for (expr const & mvar : mvars)
collect_pattern_hints(m_ctx.infer(mvar), s);
for (expr const & r : residue)
collect_pattern_hints(m_ctx.infer(r), s);
collect_pattern_hints(B, s);
return s;
}
candidate_set m_candidates;
void save_candidates(candidate_set const & s) {
m_candidates.merge(s);
}
candidate_set collect_core(expr const & a) {
switch (a.kind()) {
case expr_kind::Var:
lean_unreachable();
case expr_kind::Sort: case expr_kind::Constant:
case expr_kind::Meta: case expr_kind::Local:
case expr_kind::Pi:
return candidate_set();
case expr_kind::Let:
/* TODO(Leo): Decide whether we should support let-expressions or not.
IF we don't, then we should report this occurrence users. */
return candidate_set();
case expr_kind::Lambda:
if (has_idx_metavar(a))
return candidate_set(candidate(a));
else
return candidate_set();
case expr_kind::Macro:
for (unsigned i = 0; i < macro_num_args(a); i++) {
candidate_set s = collect_core(macro_arg(a, i));
save_candidates(s);
}
return candidate_set();
case expr_kind::App: {
buffer<expr> args;
expr const & fn = get_app_args(a, args);
buffer<candidate_set> arg_candidates;
bool forbidden = !is_local(fn) && (!is_constant(fn) || m_no_inst_patterns.contains(const_name(fn)));
if (forbidden) {
for (expr const & arg : args) {
candidate_set s = collect_core(arg);
save_candidates(s);
}
return candidate_set();
} else {
candidate_set ss;
idx_metavar_set mvars;
for (expr const & arg : args) {
if (is_idx_metavar(arg)) {
if (m_trackable.contains(to_meta_idx(arg))) {
mvars.insert(to_meta_idx(arg));
}
} else {
candidate_set s = collect_core(arg);
s.for_each([&](candidate const & c) {
ss.insert(c);
mvars.merge(c.m_mvars);
});
}
}
if (ss.find_if([&](candidate const & c) { return mvars == c.m_mvars; })) {
return ss;
} else if (!mvars.empty()) {
// a subsumes all children candidates
return candidate_set(candidate(a, mvars));
} else {
return candidate_set();
}
}
}}
lean_unreachable();
}
candidate_set collect(expr const & a) {
m_candidates = candidate_set();
if (m_simp) {
expr lhs, rhs;
if (is_eq(a, lhs, rhs) || is_heq(a, lhs, rhs)) {
m_candidates.insert(candidate(normalize(lhs)));
}
} else {
save_candidates(collect_core(normalize(a)));
}
return m_candidates;
}
void mk_multi_patterns_core(unsigned i, buffer<candidate> const & s, buffer<expr> & mp, idx_metavar_set const & mvars, buffer<multi_pattern> & mps) {
m_num_steps++;
if (m_num_steps > m_max_steps)
throw exception(sstream() << "pattern inference failed for '" << m_id << "', the maximum number (" << m_max_steps << ") of steps has been reached "
"(possible solutions: provide pattern hints using the notation '(: t :)' for marking subterms; increase threshold using option pattern.max_steps)");
if (i == s.size())
return;
candidate const & c = s[i];
if (!mvars.is_strict_superset(c.m_mvars)) {
// candidate s[i] contributes with new variables
unsigned sz = mp.size();
mp.push_back(c.m_expr);
idx_metavar_set new_mvars = mvars;
new_mvars.merge(c.m_mvars);
if (new_mvars.is_superset(m_trackable)) {
// found multi-pattern
mps.push_back(to_list(mp));
} else {
// include s[i]
mk_multi_patterns_core(i+1, s, mp, new_mvars, mps);
}
mp.shrink(sz);
}
// do not include s[i];
mk_multi_patterns_core(i+1, s, mp, mvars, mps);
}
/* If heuristic is true, then
1. Give preference to unary patterns
2. If there are no unary patterns, then
a) delete any candidate c_1 if there is a c_2 s.t.
trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
b) delete any candidate c_1 if there is a c_2 s.t.
c_1 is a subterm of c_2, and c_2.m_vars is a strict superset of c_1.m_vars */
list<multi_pattern> mk_multi_patterns_using(candidate_set s, bool heuristic) {
if (heuristic) {
buffer<multi_pattern> unit_patterns;
s.for_each([&](candidate const & c) {
if (c.m_mvars.is_superset(m_trackable))
unit_patterns.push_back(to_list(c.m_expr));
});
if (!unit_patterns.empty()) {
return to_list(unit_patterns);
}
buffer<candidate> to_delete;
s.for_each([&](candidate const & c_1) {
if (s.find_if([&](candidate const & c_2) {
return
// a) delete any candidate c_1 if there is a c_2 s.t.
// trackable(c_1) == trackable(c_2) and weight(c_1) > weight(c_2).
(c_1.m_mvars == c_2.m_mvars && get_weight(c_1.m_expr) > get_weight(c_2.m_expr)) ||
// b) delete any candidate c_1 if there is a c_2 s.t.
// c_1 is a subterm of c_2, and c_2.m_vars is a strict superset of c_1.m_vars
(occurs(c_1.m_expr, c_2.m_expr) && c_2.m_mvars.is_strict_superset(c_1.m_mvars));
})) {
to_delete.push_back(c_1);
}
});
for (candidate const & c : to_delete) {
s.erase(c);
}
}
buffer<candidate> s_buffer;
s.to_buffer(s_buffer);
buffer<multi_pattern> mps;
buffer<expr> mp;
m_num_steps = 0;
mk_multi_patterns_core(0, s_buffer, mp, idx_metavar_set(), mps);
return to_list(mps);
}
expr replace_mvars(expr const & e, buffer<expr> const & subst) {
return replace(e,
[&](expr const & e) {
if (!has_expr_metavar(e))
return some_expr(e);
if (is_idx_metavar(e))
return some_expr(subst[to_meta_idx(e)]);
else
return none_expr();
});
}
/* Create proof by pushing all residue hypotheses to the "end".
Residue hypotheses are converted into local constants.
Remaining metavariables are "renamed" (i.e., renumbered to avoid gaps due to residue hypotheses moved to the end).
Trackable set is updated.
subst will contain the mvars renaming */
expr mk_proof(type_context::tmp_locals & locals, buffer<expr> & new_residue, buffer<expr> & subst) {
unsigned j = 0;
bool found_residue = false;
bool only_tail_residue = true;
for (unsigned i = 0; i < m_mvars.size(); i++) {
expr new_type = m_ctx.infer(m_mvars[i]);
if (i != j)
new_type = replace_mvars(new_type, subst);
if (m_residue.contains(to_meta_idx(m_mvars[i]))) {
found_residue = true;
expr res = locals.push_local("_x", new_type);
new_residue.push_back(res);
subst.push_back(res);
} else {
if (found_residue)
only_tail_residue = false;
expr new_mvar;
if (j == i) {
new_mvar = m_mvars[i];
} else {
new_mvar = mk_idx_metavar(j, new_type);
if (m_trackable.contains(i)) {
m_trackable.erase(i);
m_trackable.insert(j);
}
m_mvars[j] = new_mvar;
}
j++;
subst.push_back(new_mvar);
}
}
m_mvars.shrink(j);
if (only_tail_residue) {
return mk_app(m_H, m_mvars);
} else {
return locals.mk_lambda(mk_app(m_H, subst));
}
}
struct try_again_without_hints {};
struct erase_hints_fn : public replace_visitor {
virtual expr visit_macro(expr const & e) override {
if (is_pattern_hint(e)) {
return visit(get_annotation_arg(e));
} else {
return replace_visitor::visit_macro(e);
}
}
};
hinst_lemma operator()(bool erase_hints) {
expr H_type = m_ctx.infer(m_H);
if (erase_hints) {
H_type = erase_hints_fn()(H_type);
}
buffer<bool> inst_implicit_flags;
expr B = extract_trackable(m_ctx, H_type, m_mvars, inst_implicit_flags, m_trackable, m_residue);
lean_assert(m_mvars.size() == inst_implicit_flags.size());
buffer<expr> subst;
buffer<expr> residue_locals;
type_context::tmp_locals locals(m_ctx);
expr proof = mk_proof(locals, residue_locals, subst);
B = replace_mvars(B, subst);
candidate_set hints = collect_pattern_hints(m_mvars, residue_locals, B);
list<multi_pattern> mps;
if (!hints.empty()) {
mps = mk_multi_patterns_using(hints, false);
} else {
if (has_pattern_hints(H_type)) {
throw try_again_without_hints();
}
buffer<expr> places;
candidate_set B_candidates = collect(B);
if (auto r1 = mk_multi_patterns_using(B_candidates, true)) {
mps = r1;
} else if (!m_simp) {
candidate_set residue_candidates;
for (expr const & r : residue_locals) {
residue_candidates.merge(collect(m_ctx.infer(r)));
}
if (auto r2 = mk_multi_patterns_using(residue_candidates, true)) {
mps = r2;
} else if (!residue_candidates.empty() && !B_candidates.empty()) {
candidate_set all_candidates = B_candidates;
all_candidates.merge(residue_candidates);
mps = mk_multi_patterns_using(all_candidates, true);
}
}
}
if (!mps) {
throw exception(sstream() << "pattern inference failed for '" << m_id << "', "
"(solution: provide pattern hints using the notation '(: t :)' )");
}
hinst_lemma r;
r.m_id = m_id;
r.m_num_uvars = m_num_uvars;
r.m_num_mvars = m_mvars.size();
r.m_multi_patterns = mps;
r.m_mvars = to_list(m_mvars);
r.m_is_inst_implicit = to_list(inst_implicit_flags);
r.m_prop = m_ctx.infer(proof);
r.m_proof = proof;
r.m_expr = m_H;
return r;
}
};
hinst_lemma mk_hinst_lemma_core(type_context & ctx, transparency_mode md_norm, expr const & H, unsigned num_uvars,
unsigned max_steps, bool simp, name const & id) {
try {
type_context::tmp_mode_scope tscope(ctx, num_uvars, 0);
bool erase_hints = false;
return mk_hinst_lemma_fn(ctx, md_norm, H, num_uvars, max_steps, simp, id)(erase_hints);
} catch (mk_hinst_lemma_fn::try_again_without_hints &) {
type_context::tmp_mode_scope tscope(ctx, num_uvars, 0);
try {
bool erase_hints = true;
return mk_hinst_lemma_fn(ctx, md_norm, H, num_uvars, max_steps, simp, id)(erase_hints);
} catch (mk_hinst_lemma_fn::try_again_without_hints &) {
lean_unreachable();
}
}
}
static name * g_hinst_lemma_max_steps = nullptr;
unsigned get_hinst_lemma_max_steps(options const & o) {
return o.get_unsigned(*g_hinst_lemma_max_steps, LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS);
}
hinst_lemma mk_hinst_lemma(type_context & ctx, transparency_mode md_norm, expr const & H, bool simp) {
unsigned max_steps = get_hinst_lemma_max_steps(ctx.get_options());
name id;
if (is_local(H))
id = local_pp_name(H);
return mk_hinst_lemma_core(ctx, md_norm, H, 0, max_steps, simp, id);
}
hinst_lemma mk_hinst_lemma(type_context & ctx, transparency_mode md_norm, name const & c, bool simp) {
unsigned max_steps = get_hinst_lemma_max_steps(ctx.get_options());
declaration const & d = ctx.env().get(c);
buffer<level> us;
unsigned num_us = d.get_num_univ_params();
for (unsigned i = 0; i < num_us; i++)
us.push_back(mk_idx_metauniv(i));
expr H = mk_constant(c, to_list(us));
name id = c;
return mk_hinst_lemma_core(ctx, md_norm, H, num_us, max_steps, simp, id);
}
format pp_hinst_lemma(formatter const & fmt, hinst_lemma const & h) {
format r;
r += format(h.m_id) + comma() + line();
bool first1 = true;
format pats;
for (multi_pattern const & mp : h.m_multi_patterns) {
if (first1) first1 = false; else pats += comma() + line();
format pat;
bool first2 = true;
for (expr const & p : mp) {
if (first2) first2 = false; else pat += comma() + line();
pat += fmt(p);
}
pats += group(bracket("{", pat, "}"));
}
char const * n = "patterns:";
r += nest(strlen(n), format(n) + line() + group(bracket("{", pats, "}")));
return group(bracket("[", r, "]"));
}
void initialize_hinst_lemmas() {
g_pattern_hint = new name("pattern_hint");
register_annotation(*g_pattern_hint);
g_no_inst_pattern_attr = new name({"no_inst_pattern"});
/* Add validation */
register_system_attribute(basic_attribute(*g_no_inst_pattern_attr, "do not consider terms containing this declaration in the pattern inference procedure"));
g_hinst_lemma_max_steps = new name{"hinst_lemma", "pattern", "max_steps"};
register_unsigned_option(*g_hinst_lemma_max_steps, LEAN_DEFAULT_HINST_LEMMA_PATTERN_MAX_STEPS,
"(hinst_lemma) max number of steps performed by pattern inference procedure for heuristic instantiation lemmas, "
"we have this threshold because in the worst case this procedure may take "
"an exponetial number of steps");
}
void finalize_hinst_lemmas() {
delete g_no_inst_pattern_attr;
delete g_hinst_lemma_max_steps;
}
}
|
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
Copyright (C) 2015 Roman Lebedev
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 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/CrwDecoder.h"
#include "common/Common.h" // for uint32, ushort16, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/BitPumpJPEG.h" // for BitPumpJPEG, BitStream<>::...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "metadata/Camera.h" // for Hints
#include "metadata/ColorFilterArray.h" // for CFAColor::CFA_GREEN, CFACo...
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::C...
#include "tiff/CiffIFD.h" // for CiffIFD
#include "tiff/CiffTag.h" // for CiffTag, CiffTag::CIFF_MAK...
#include <algorithm> // for min
#include <array> // for array
#include <cmath> // for copysignf, expf, logf
#include <cstdio> // for fprintf, stderr
#include <cstdlib> // for abs
#include <cstring> // for memset
#include <exception> // for exception
#include <memory> // for unique_ptr
#include <string> // for string
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
class CameraMetaData;
CrwDecoder::CrwDecoder(std::unique_ptr<CiffIFD> rootIFD, Buffer* file)
: RawDecoder(file), mRootIFD(move(rootIFD)) {}
RawImage CrwDecoder::decodeRawInternal() {
CiffEntry *sensorInfo = mRootIFD->getEntryRecursive(CIFF_SENSORINFO);
if (!sensorInfo || sensorInfo->count < 6 || sensorInfo->type != CIFF_SHORT)
ThrowRDE("Couldn't find image sensor info");
uint32 width = sensorInfo->getU16(1);
uint32 height = sensorInfo->getU16(2);
CiffEntry *decTable = mRootIFD->getEntryRecursive(CIFF_DECODERTABLE);
if (!decTable || decTable->type != CIFF_LONG)
ThrowRDE("Couldn't find decoder table");
uint32 dec_table = decTable->getU32();
if (dec_table > 2)
ThrowRDE("Unknown decoder table %d", dec_table);
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
bool lowbits = ! hints.has("no_decompressed_lowbits");
decodeRaw(lowbits, dec_table, width, height);
return mRaw;
}
void CrwDecoder::checkSupportInternal(const CameraMetaData* meta) {
vector<CiffIFD*> data = mRootIFD->getIFDsWithTag(CIFF_MAKEMODEL);
if (data.empty())
ThrowRDE("Model name not found");
vector<string> makemodel = data[0]->getEntry(CIFF_MAKEMODEL)->getStrings();
if (makemodel.size() < 2)
ThrowRDE("wrong number of strings for make/model");
string make = makemodel[0];
string model = makemodel[1];
this->checkCameraSupported(meta, make, model, "");
}
// based on exiftool's Image::ExifTool::Canon::CanonEv
float __attribute__((const)) CrwDecoder::canonEv(const long in) {
// remove sign
long val = abs(in);
// remove fraction
auto frac = static_cast<float>(val & 0x1f);
val -= long(frac);
// convert 1/3 (0x0c) and 2/3 (0x14) codes
if (frac == 0x0c) {
frac = 32.0f / 3;
}
else if (frac == 0x14) {
frac = 64.0f / 3;
}
return copysignf((val + frac) / 32.0f, in);
}
void CrwDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN, CFA_BLUE);
vector<CiffIFD*> data = mRootIFD->getIFDsWithTag(CIFF_MAKEMODEL);
if (data.empty())
ThrowRDE("Model name not found");
vector<string> makemodel = data[0]->getEntry(CIFF_MAKEMODEL)->getStrings();
if (makemodel.size() < 2)
ThrowRDE("wrong number of strings for make/model");
string make = makemodel[0];
string model = makemodel[1];
string mode;
if (mRootIFD->hasEntryRecursive(CIFF_SHOTINFO)) {
CiffEntry *shot_info = mRootIFD->getEntryRecursive(CIFF_SHOTINFO);
if (shot_info->type == CIFF_SHORT && shot_info->count >= 2) {
// os << exp(canonEv(value.toLong()) * log(2.0)) * 100.0 / 32.0;
ushort16 iso_index = shot_info->getU16(2);
iso = expf(canonEv((long)iso_index) * logf(2.0)) * 100.0f / 32.0f;
}
}
// Fetch the white balance
try{
if(mRootIFD->hasEntryRecursive((CiffTag)0x0032)) {
CiffEntry *wb = mRootIFD->getEntryRecursive((CiffTag)0x0032);
if (wb->type == CIFF_BYTE && wb->count == 768) {
// We're in a D30 file, values are RGGB
// This will probably not get used anyway as a 0x102c tag should exist
mRaw->metadata.wbCoeffs[0] = (float) (1024.0 /wb->getByte(72));
mRaw->metadata.wbCoeffs[1] = (float) ((1024.0/wb->getByte(73))+(1024.0/wb->getByte(74)))/2.0f;
mRaw->metadata.wbCoeffs[2] = (float) (1024.0 /wb->getByte(75));
} else if (wb->type == CIFF_BYTE && wb->count > 768) { // Other G series and S series cameras
// correct offset for most cameras
int offset = hints.get("wb_offset", 120);
ushort16 key[] = { 0x410, 0x45f3 };
if (! hints.has("wb_mangle"))
key[0] = key[1] = 0;
offset /= 2;
mRaw->metadata.wbCoeffs[0] = (float) (wb->getU16(offset+1) ^ key[1]);
mRaw->metadata.wbCoeffs[1] = (float) (wb->getU16(offset+0) ^ key[0]);
mRaw->metadata.wbCoeffs[2] = (float) (wb->getU16(offset+2) ^ key[0]);
}
}
if(mRootIFD->hasEntryRecursive((CiffTag)0x102c)) {
CiffEntry *entry = mRootIFD->getEntryRecursive((CiffTag)0x102c);
if (entry->type == CIFF_SHORT && entry->getU16() > 512) {
// G1/Pro90 CYGM pattern
mRaw->metadata.wbCoeffs[0] = (float) entry->getU16(62);
mRaw->metadata.wbCoeffs[1] = (float) entry->getU16(63);
mRaw->metadata.wbCoeffs[2] = (float) entry->getU16(60);
mRaw->metadata.wbCoeffs[3] = (float) entry->getU16(61);
} else if (entry->type == CIFF_SHORT) {
/* G2, S30, S40 */
mRaw->metadata.wbCoeffs[0] = (float) entry->getU16(51);
mRaw->metadata.wbCoeffs[1] = ((float) entry->getU16(50) + (float) entry->getU16(53))/ 2.0f;
mRaw->metadata.wbCoeffs[2] = (float) entry->getU16(52);
}
}
if (mRootIFD->hasEntryRecursive(CIFF_SHOTINFO) && mRootIFD->hasEntryRecursive(CIFF_WHITEBALANCE)) {
CiffEntry *shot_info = mRootIFD->getEntryRecursive(CIFF_SHOTINFO);
ushort16 wb_index = shot_info->getU16(7);
CiffEntry *wb_data = mRootIFD->getEntryRecursive(CIFF_WHITEBALANCE);
/* CANON EOS D60, CANON EOS 10D, CANON EOS 300D */
if (wb_index > 9)
ThrowRDE("Invalid white balance index");
int wb_offset = 1 + ("0134567028"[wb_index]-'0') * 4;
mRaw->metadata.wbCoeffs[0] = wb_data->getU16(wb_offset + 0);
mRaw->metadata.wbCoeffs[1] = wb_data->getU16(wb_offset + 1);
mRaw->metadata.wbCoeffs[2] = wb_data->getU16(wb_offset + 3);
}
} catch (const std::exception& e) {
fprintf(stderr, "Got exception: %s\n", e.what());
mRaw->setError(e.what());
// We caught an exception reading WB, just ignore it
}
setMetaData(meta, make, model, mode, iso);
}
// The rest of this file was ported as is from dcraw.c. I don't claim to
// understand it but have tried my best to make it work safely
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
HuffmanTable CrwDecoder::makeDecoder(int n, const uchar8* source) {
if (n > 1)
ThrowRDE("Invalid table number specified");
HuffmanTable ht;
auto count = ht.setNCodesPerLength(Buffer(source, 16));
ht.setCodeValues(Buffer(source + 16, count));
ht.setup(false, false);
return ht;
}
array<HuffmanTable, 2> CrwDecoder::initHuffTables(uint32 table) {
static const uchar8 first_tree[3][29] = {
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
{ 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff },
{ 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff },
};
static const uchar8 second_tree[3][180] = {
{ 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff },
{ 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff },
{ 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff }
};
array<HuffmanTable, 2> mHuff = {
{makeDecoder(0, first_tree[table]), makeDecoder(1, second_tree[table])}};
return mHuff;
}
void CrwDecoder::decodeRaw(bool lowbits, uint32 dec_table, uint32 width, uint32 height)
{
int nblocks;
int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
auto mHuff = initHuffTables(dec_table);
uint32 offset = 540 + lowbits*height*width/4;
ByteStream input(mFile, offset);
BitPumpJPEG pump(input);
for (uint32 row=0; row < height; row+=8) {
auto *dest = (ushort16 *)&mRaw->getData()[row * width * 2];
nblocks = min(8u, height - row) * width >> 6;
for (block=0; block < nblocks; block++) {
memset (diffbuf, 0, sizeof diffbuf);
for (uint32 i=0; i < 64; i++ ) {
leaf = mHuff[i > 0].decodeLength(pump);
if (leaf == 0 && i) break;
if (leaf == 0xff) continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0) continue;
diff = pump.getBits(len);
diff = HuffmanTable::signExtended(diff, len);
if (i < 64) diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (uint32 i=0; i < 64; i++ ) {
if (pnum++ % width == 0)
base[0] = base[1] = 512;
if ((dest[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
ThrowRDE("Error decompressing");
}
}
// Add the uncompressed 2 low bits to the decoded 8 high bits
if (lowbits) {
offset = 26 + row*width/4;
ByteStream lowbit_input(mFile, offset, height*width/4);
uint32 lines =
min(height - row, 8u); // Process 8 rows or however are left
for (uint32 i=0; i < width/4*lines; i++) {
uint32 c = ((uint32) lowbit_input.getByte());
for (uint32 r=0; r < 8; r+=2, dest++) { // Process 8 bits in pairs
ushort16 val = (*dest << 2) | ((c >> r) & 0x0003);
if (width == 2672 && val < 512) val += 2; // No idea why this is needed
*dest = val;
}
}
}
}
}
} // namespace RawSpeed
CrwDecoder::decodeRaw(): respect width / padding
FIXME: this function is absolutely horrible.
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
Copyright (C) 2015 Roman Lebedev
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 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/CrwDecoder.h"
#include "common/Common.h" // for uint32, ushort16, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for RawDecoderException (ptr o...
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/BitPumpJPEG.h" // for BitPumpJPEG, BitStream<>::...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "metadata/Camera.h" // for Hints
#include "metadata/ColorFilterArray.h" // for CFAColor::CFA_GREEN, CFACo...
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::C...
#include "tiff/CiffIFD.h" // for CiffIFD
#include "tiff/CiffTag.h" // for CiffTag, CiffTag::CIFF_MAK...
#include <algorithm> // for min
#include <array> // for array
#include <cassert> // for cassert
#include <cmath> // for copysignf, expf, logf
#include <cstdio> // for fprintf, stderr
#include <cstdlib> // for abs
#include <cstring> // for memset
#include <exception> // for exception
#include <memory> // for unique_ptr
#include <string> // for string
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
class CameraMetaData;
CrwDecoder::CrwDecoder(std::unique_ptr<CiffIFD> rootIFD, Buffer* file)
: RawDecoder(file), mRootIFD(move(rootIFD)) {}
RawImage CrwDecoder::decodeRawInternal() {
CiffEntry *sensorInfo = mRootIFD->getEntryRecursive(CIFF_SENSORINFO);
if (!sensorInfo || sensorInfo->count < 6 || sensorInfo->type != CIFF_SHORT)
ThrowRDE("Couldn't find image sensor info");
uint32 width = sensorInfo->getU16(1);
uint32 height = sensorInfo->getU16(2);
CiffEntry *decTable = mRootIFD->getEntryRecursive(CIFF_DECODERTABLE);
if (!decTable || decTable->type != CIFF_LONG)
ThrowRDE("Couldn't find decoder table");
uint32 dec_table = decTable->getU32();
if (dec_table > 2)
ThrowRDE("Unknown decoder table %d", dec_table);
mRaw->dim = iPoint2D(width, height);
mRaw->createData();
bool lowbits = ! hints.has("no_decompressed_lowbits");
decodeRaw(lowbits, dec_table, width, height);
return mRaw;
}
void CrwDecoder::checkSupportInternal(const CameraMetaData* meta) {
vector<CiffIFD*> data = mRootIFD->getIFDsWithTag(CIFF_MAKEMODEL);
if (data.empty())
ThrowRDE("Model name not found");
vector<string> makemodel = data[0]->getEntry(CIFF_MAKEMODEL)->getStrings();
if (makemodel.size() < 2)
ThrowRDE("wrong number of strings for make/model");
string make = makemodel[0];
string model = makemodel[1];
this->checkCameraSupported(meta, make, model, "");
}
// based on exiftool's Image::ExifTool::Canon::CanonEv
float __attribute__((const)) CrwDecoder::canonEv(const long in) {
// remove sign
long val = abs(in);
// remove fraction
auto frac = static_cast<float>(val & 0x1f);
val -= long(frac);
// convert 1/3 (0x0c) and 2/3 (0x14) codes
if (frac == 0x0c) {
frac = 32.0f / 3;
}
else if (frac == 0x14) {
frac = 64.0f / 3;
}
return copysignf((val + frac) / 32.0f, in);
}
void CrwDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN, CFA_BLUE);
vector<CiffIFD*> data = mRootIFD->getIFDsWithTag(CIFF_MAKEMODEL);
if (data.empty())
ThrowRDE("Model name not found");
vector<string> makemodel = data[0]->getEntry(CIFF_MAKEMODEL)->getStrings();
if (makemodel.size() < 2)
ThrowRDE("wrong number of strings for make/model");
string make = makemodel[0];
string model = makemodel[1];
string mode;
if (mRootIFD->hasEntryRecursive(CIFF_SHOTINFO)) {
CiffEntry *shot_info = mRootIFD->getEntryRecursive(CIFF_SHOTINFO);
if (shot_info->type == CIFF_SHORT && shot_info->count >= 2) {
// os << exp(canonEv(value.toLong()) * log(2.0)) * 100.0 / 32.0;
ushort16 iso_index = shot_info->getU16(2);
iso = expf(canonEv((long)iso_index) * logf(2.0)) * 100.0f / 32.0f;
}
}
// Fetch the white balance
try{
if(mRootIFD->hasEntryRecursive((CiffTag)0x0032)) {
CiffEntry *wb = mRootIFD->getEntryRecursive((CiffTag)0x0032);
if (wb->type == CIFF_BYTE && wb->count == 768) {
// We're in a D30 file, values are RGGB
// This will probably not get used anyway as a 0x102c tag should exist
mRaw->metadata.wbCoeffs[0] = (float) (1024.0 /wb->getByte(72));
mRaw->metadata.wbCoeffs[1] = (float) ((1024.0/wb->getByte(73))+(1024.0/wb->getByte(74)))/2.0f;
mRaw->metadata.wbCoeffs[2] = (float) (1024.0 /wb->getByte(75));
} else if (wb->type == CIFF_BYTE && wb->count > 768) { // Other G series and S series cameras
// correct offset for most cameras
int offset = hints.get("wb_offset", 120);
ushort16 key[] = { 0x410, 0x45f3 };
if (! hints.has("wb_mangle"))
key[0] = key[1] = 0;
offset /= 2;
mRaw->metadata.wbCoeffs[0] = (float) (wb->getU16(offset+1) ^ key[1]);
mRaw->metadata.wbCoeffs[1] = (float) (wb->getU16(offset+0) ^ key[0]);
mRaw->metadata.wbCoeffs[2] = (float) (wb->getU16(offset+2) ^ key[0]);
}
}
if(mRootIFD->hasEntryRecursive((CiffTag)0x102c)) {
CiffEntry *entry = mRootIFD->getEntryRecursive((CiffTag)0x102c);
if (entry->type == CIFF_SHORT && entry->getU16() > 512) {
// G1/Pro90 CYGM pattern
mRaw->metadata.wbCoeffs[0] = (float) entry->getU16(62);
mRaw->metadata.wbCoeffs[1] = (float) entry->getU16(63);
mRaw->metadata.wbCoeffs[2] = (float) entry->getU16(60);
mRaw->metadata.wbCoeffs[3] = (float) entry->getU16(61);
} else if (entry->type == CIFF_SHORT) {
/* G2, S30, S40 */
mRaw->metadata.wbCoeffs[0] = (float) entry->getU16(51);
mRaw->metadata.wbCoeffs[1] = ((float) entry->getU16(50) + (float) entry->getU16(53))/ 2.0f;
mRaw->metadata.wbCoeffs[2] = (float) entry->getU16(52);
}
}
if (mRootIFD->hasEntryRecursive(CIFF_SHOTINFO) && mRootIFD->hasEntryRecursive(CIFF_WHITEBALANCE)) {
CiffEntry *shot_info = mRootIFD->getEntryRecursive(CIFF_SHOTINFO);
ushort16 wb_index = shot_info->getU16(7);
CiffEntry *wb_data = mRootIFD->getEntryRecursive(CIFF_WHITEBALANCE);
/* CANON EOS D60, CANON EOS 10D, CANON EOS 300D */
if (wb_index > 9)
ThrowRDE("Invalid white balance index");
int wb_offset = 1 + ("0134567028"[wb_index]-'0') * 4;
mRaw->metadata.wbCoeffs[0] = wb_data->getU16(wb_offset + 0);
mRaw->metadata.wbCoeffs[1] = wb_data->getU16(wb_offset + 1);
mRaw->metadata.wbCoeffs[2] = wb_data->getU16(wb_offset + 3);
}
} catch (const std::exception& e) {
fprintf(stderr, "Got exception: %s\n", e.what());
mRaw->setError(e.what());
// We caught an exception reading WB, just ignore it
}
setMetaData(meta, make, model, mode, iso);
}
// The rest of this file was ported as is from dcraw.c. I don't claim to
// understand it but have tried my best to make it work safely
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
HuffmanTable CrwDecoder::makeDecoder(int n, const uchar8* source) {
if (n > 1)
ThrowRDE("Invalid table number specified");
HuffmanTable ht;
auto count = ht.setNCodesPerLength(Buffer(source, 16));
ht.setCodeValues(Buffer(source + 16, count));
ht.setup(false, false);
return ht;
}
array<HuffmanTable, 2> CrwDecoder::initHuffTables(uint32 table) {
static const uchar8 first_tree[3][29] = {
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
{ 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff },
{ 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff },
};
static const uchar8 second_tree[3][180] = {
{ 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff },
{ 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff },
{ 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff }
};
array<HuffmanTable, 2> mHuff = {
{makeDecoder(0, first_tree[table]), makeDecoder(1, second_tree[table])}};
return mHuff;
}
// FIXME: this function is absolutely horrible.
void CrwDecoder::decodeRaw(bool lowbits, uint32 dec_table, uint32 width, uint32 height)
{
int nblocks;
int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
auto mHuff = initHuffTables(dec_table);
uint32 offset = 540 + lowbits*height*width/4;
ByteStream input(mFile, offset);
BitPumpJPEG pump(input);
assert((int)width == mRaw->dim.x);
assert((int)height == mRaw->dim.y);
for (uint32 row=0; row < height; row+=8) {
nblocks = min(8u, height - row) * width >> 6;
for (block=0; block < nblocks; block++) {
memset (diffbuf, 0, sizeof diffbuf);
for (uint32 i=0; i < 64; i++ ) {
leaf = mHuff[i > 0].decodeLength(pump);
if (leaf == 0 && i) break;
if (leaf == 0xff) continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0) continue;
diff = pump.getBits(len);
diff = HuffmanTable::signExtended(diff, len);
if (i < 64) diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (uint32 i=0; i < 64; i++ ) {
if (pnum++ % width == 0)
base[0] = base[1] = 512;
base[i & 1] += diffbuf[i];
if (base[i & 1] >> 10)
ThrowRDE("Error decompressing");
const auto shift = (block << 6) + i;
const auto j = shift / width;
const auto k = shift % width;
auto* dest = (ushort16*)mRaw->getData(k, row + j);
*dest = base[i & 1];
}
}
}
// Add the uncompressed 2 low bits to the decoded 8 high bits
if (lowbits) {
size_t counter = 0;
for (uint32 row = 0; row < height; row += 8) {
offset = 26 + row*width/4;
ByteStream lowbit_input(mFile, offset, height*width/4);
uint32 lines =
min(height - row, 8u); // Process 8 rows or however are left
for (uint32 i=0; i < width/4*lines; i++) {
uint32 c = ((uint32) lowbit_input.getByte());
// Process 8 bits in pairs
for (uint32 r = 0; r < 8; r += 2, counter++) {
const auto j = counter / width;
const auto k = counter % width;
auto* dest = (ushort16*)mRaw->getData(k, j);
ushort16 val = (*dest << 2) | ((c >> r) & 0x0003);
if (width == 2672 && val < 512) val += 2; // No idea why this is needed
*dest = val;
}
}
}
}
}
} // namespace RawSpeed
|
/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
/**
@file storage/perfschema/ha_perfschema.cc
Performance schema storage engine (implementation).
*/
#include "my_global.h"
#include "my_pthread.h"
#include "sql_plugin.h"
#include "mysql/plugin.h"
#include "ha_perfschema.h"
#include "pfs_engine_table.h"
#include "pfs_column_values.h"
#include "pfs_instr_class.h"
#include "pfs_instr.h"
handlerton *pfs_hton= NULL;
static handler* pfs_create_handler(handlerton *hton,
TABLE_SHARE *table,
MEM_ROOT *mem_root)
{
return new (mem_root) ha_perfschema(hton, table);
}
static int compare_database_names(const char *name1, const char *name2)
{
if (lower_case_table_names)
return strcasecmp(name1, name2);
return strcmp(name1, name2);
}
static const PFS_engine_table_share*
find_table_share(const char *db, const char *name)
{
DBUG_ENTER("find_table_share");
if (compare_database_names(db, PERFORMANCE_SCHEMA_str.str) != 0)
DBUG_RETURN(NULL);
const PFS_engine_table_share* result;
result= PFS_engine_table::find_engine_table_share(name);
DBUG_RETURN(result);
}
static int pfs_init_func(void *p)
{
DBUG_ENTER("pfs_init_func");
pfs_hton= reinterpret_cast<handlerton *> (p);
pfs_hton->state= SHOW_OPTION_YES;
pfs_hton->create= pfs_create_handler;
pfs_hton->show_status= pfs_show_status;
pfs_hton->flags= HTON_ALTER_NOT_SUPPORTED |
HTON_TEMPORARY_NOT_SUPPORTED |
HTON_NO_PARTITION;
/*
As long as the server implementation keeps using legacy_db_type,
as for example in mysql_truncate(),
we can not rely on the fact that different mysqld process will assign
consistently the same legacy_db_type for a given storage engine name.
In particular, using different --loose-skip-xxx options between
./mysqld --bootstrap
./mysqld
creates bogus .frm forms when bootstrapping the performance schema,
if we rely on ha_initialize_handlerton to assign a really dynamic value.
To fix this, a dedicated DB_TYPE is officially assigned to
the performance schema. See Bug#43039.
*/
pfs_hton->db_type= DB_TYPE_PERFORMANCE_SCHEMA;
PFS_engine_table_share::init_all_locks();
DBUG_RETURN(0);
}
static int pfs_done_func(void *p)
{
DBUG_ENTER("pfs_done_func");
pfs_hton= NULL;
PFS_engine_table_share::delete_all_locks();
DBUG_RETURN(0);
}
static struct st_mysql_show_var pfs_status_vars[]=
{
{"Performance_schema_mutex_classes_lost",
(char*) &mutex_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_rwlock_classes_lost",
(char*) &rwlock_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_cond_classes_lost",
(char*) &cond_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_thread_classes_lost",
(char*) &thread_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_file_classes_lost",
(char*) &file_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_mutex_instances_lost",
(char*) &mutex_lost, SHOW_LONG},
{"Performance_schema_rwlock_instances_lost",
(char*) &rwlock_lost, SHOW_LONG},
{"Performance_schema_cond_instances_lost",
(char*) &cond_lost, SHOW_LONG},
{"Performance_schema_thread_instances_lost",
(char*) &thread_lost, SHOW_LONG},
{"Performance_schema_file_instances_lost",
(char*) &file_lost, SHOW_LONG},
{"Performance_schema_file_handles_lost",
(char*) &file_handle_lost, SHOW_LONG},
{"Performance_schema_locker_lost",
(char*) &locker_lost, SHOW_LONG},
/* table shares, can be flushed */
{"Performance_schema_table_instances_lost",
(char*) &table_share_lost, SHOW_LONG},
/* table handles, can be flushed */
{"Performance_schema_table_handles_lost",
(char*) &table_lost, SHOW_LONG},
{NullS, NullS, SHOW_LONG}
};
struct st_mysql_storage_engine pfs_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION };
const char* pfs_engine_name= "PERFORMANCE_SCHEMA";
mysql_declare_plugin(perfschema)
{
MYSQL_STORAGE_ENGINE_PLUGIN,
&pfs_storage_engine,
pfs_engine_name,
"Marc Alff, Oracle", /* Formerly Sun Microsystems, formerly MySQL */
"Performance Schema",
PLUGIN_LICENSE_GPL,
pfs_init_func, /* Plugin Init */
pfs_done_func, /* Plugin Deinit */
0x0001 /* 0.1 */,
pfs_status_vars, /* status variables */
NULL, /* system variables */
NULL /* config options */
}
mysql_declare_plugin_end;
ha_perfschema::ha_perfschema(handlerton *hton, TABLE_SHARE *share)
: handler(hton, share), m_table_share(NULL), m_table(NULL)
{}
ha_perfschema::~ha_perfschema()
{}
static const char *ha_pfs_exts[]= {
NullS
};
const char **ha_perfschema::bas_ext() const
{
return ha_pfs_exts;
}
int ha_perfschema::open(const char *name, int mode, uint test_if_locked)
{
DBUG_ENTER("ha_perfschema::open");
m_table_share= find_table_share(table_share->db.str,
table_share->table_name.str);
if (! m_table_share)
DBUG_RETURN(HA_ERR_NO_SUCH_TABLE);
thr_lock_data_init(m_table_share->m_thr_lock_ptr, &m_thr_lock, NULL);
ref_length= m_table_share->m_ref_length;
psi_open();
DBUG_RETURN(0);
}
int ha_perfschema::close(void)
{
DBUG_ENTER("ha_perfschema::close");
m_table_share= NULL;
delete m_table;
m_table= NULL;
psi_close();
DBUG_RETURN(0);
}
int ha_perfschema::write_row(uchar *buf)
{
int result;
DBUG_ENTER("ha_perfschema::write_row");
ha_statistic_increment(&SSV::ha_write_count);
DBUG_ASSERT(m_table_share);
if (m_table_share->m_write_row)
result= m_table_share->m_write_row(table, buf, table->field);
else
{
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
result= HA_ERR_WRONG_COMMAND;
}
DBUG_RETURN(result);
}
void ha_perfschema::use_hidden_primary_key(void)
{
/*
This is also called in case of row based replication,
see TABLE::mark_columns_needed_for_update().
Add all columns to the read set, but do not touch the write set,
as some columns in the SETUP_ tables are not writable.
*/
table->column_bitmaps_set_no_signal(&table->s->all_set, table->write_set);
}
int ha_perfschema::update_row(const uchar *old_data, uchar *new_data)
{
DBUG_ENTER("ha_perfschema::update_row");
DBUG_ASSERT(m_table);
int result= m_table->update_row(table, old_data, new_data, table->field);
DBUG_RETURN(result);
}
int ha_perfschema::rnd_init(bool scan)
{
int result;
DBUG_ENTER("ha_perfschema::rnd_init");
DBUG_ASSERT(m_table_share);
DBUG_ASSERT(m_table_share->m_open_table != NULL);
stats.records= 0;
if (m_table == NULL)
m_table= m_table_share->m_open_table();
else
m_table->reset_position();
result= m_table ? 0 : HA_ERR_OUT_OF_MEM;
DBUG_RETURN(result);
}
int ha_perfschema::rnd_end(void)
{
DBUG_ENTER("ha_perfschema::rnd_end");
DBUG_ASSERT(m_table);
delete m_table;
m_table= NULL;
DBUG_RETURN(0);
}
int ha_perfschema::rnd_next(uchar *buf)
{
DBUG_ENTER("ha_perfschema::rnd_next");
DBUG_ASSERT(m_table);
int result= m_table->rnd_next();
if (result == 0)
{
result= m_table->read_row(table, buf, table->field);
if (result == 0)
stats.records++;
}
DBUG_RETURN(result);
}
void ha_perfschema::position(const uchar *record)
{
DBUG_ENTER("ha_perfschema::position");
DBUG_ASSERT(m_table);
m_table->get_position(ref);
DBUG_VOID_RETURN;
}
int ha_perfschema::rnd_pos(uchar *buf, uchar *pos)
{
DBUG_ENTER("ha_perfschema::rnd_pos");
DBUG_ASSERT(m_table);
int result= m_table->rnd_pos(pos);
if (result == 0)
result= m_table->read_row(table, buf, table->field);
DBUG_RETURN(result);
}
int ha_perfschema::info(uint flag)
{
DBUG_ENTER("ha_perfschema::info");
DBUG_ASSERT(m_table_share);
if (flag & HA_STATUS_VARIABLE)
stats.records= m_table_share->m_records;
if (flag & HA_STATUS_CONST)
ref_length= m_table_share->m_ref_length;
DBUG_RETURN(0);
}
int ha_perfschema::delete_all_rows(void)
{
int result;
DBUG_ENTER("ha_perfschema::delete_all_rows");
DBUG_ASSERT(m_table_share);
if (m_table_share->m_delete_all_rows)
result= m_table_share->m_delete_all_rows();
else
{
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
result= HA_ERR_WRONG_COMMAND;
}
DBUG_RETURN(result);
}
THR_LOCK_DATA **ha_perfschema::store_lock(THD *thd,
THR_LOCK_DATA **to,
enum thr_lock_type lock_type)
{
if (lock_type != TL_IGNORE && m_thr_lock.type == TL_UNLOCK)
m_thr_lock.type= lock_type;
*to++= &m_thr_lock;
m_thr_lock.m_psi= m_psi;
return to;
}
int ha_perfschema::delete_table(const char *name)
{
DBUG_ENTER("ha_perfschema::delete_table");
DBUG_RETURN(0);
}
int ha_perfschema::rename_table(const char * from, const char * to)
{
DBUG_ENTER("ha_perfschema::rename_table ");
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
int ha_perfschema::create(const char *name, TABLE *table_arg,
HA_CREATE_INFO *create_info)
{
DBUG_ENTER("ha_perfschema::create");
DBUG_ASSERT(table_arg);
DBUG_ASSERT(table_arg->s);
if (find_table_share(table_arg->s->db.str,
table_arg->s->table_name.str))
{
/*
Attempting to create a known performance schema table.
Allowing the create, to create .FRM files,
for the initial database install, and mysql_upgrade.
This should fail once .FRM are removed.
*/
DBUG_RETURN(0);
}
/*
This is not a general purpose engine.
Failure to CREATE TABLE is the expected result.
*/
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
Selective transfer of a bugfix patch into 5.5.6-rc.
The first part is the functional change,
the second is needed as a compile fix on Windows
(header file order).
| committer: Marc Alff <marc.alff@oracle.com>
| branch nick: mysql-5.5-bugfixing-56521
| timestamp: Thu 2010-09-09 14:28:47 -0600
| message:
| Bug#56521 Assertion failed: (m_state == 2), function allocated_to_free, pfs_lock.h (138)
|
| Before this fix, it was possible to build the server:
| - with the performance schema
| - with a dummy implementation of my_atomic (MY_ATOMIC_MODE_DUMMY).
|
| In this case, the resulting binary will just crash,
| as this configuration is not supported.
|
| This fix enforces that the build will fail with a compilation error in this
| configuration, instead of resulting in a broken binary.
| committer: Tor Didriksen <tor.didriksen@oracle.com>
| branch nick: 5.5-bugfixing-56521
| timestamp: Fri 2010-09-10 11:10:38 +0200
| message:
| Header files should be self-contained
/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
/**
@file storage/perfschema/ha_perfschema.cc
Performance schema storage engine (implementation).
*/
#include "my_global.h"
#include "my_pthread.h"
#include "my_atomic.h"
#include "sql_plugin.h"
#include "mysql/plugin.h"
#include "ha_perfschema.h"
#include "pfs_engine_table.h"
#include "pfs_column_values.h"
#include "pfs_instr_class.h"
#include "pfs_instr.h"
#ifdef MY_ATOMIC_MODE_DUMMY
/*
The performance schema can can not function with MY_ATOMIC_MODE_DUMMY,
a fully functional implementation of MY_ATOMIC should be used instead.
If the build fails with this error message:
- either use a different ./configure --with-atomic-ops option
- or do not build with the performance schema.
*/
#error "The performance schema needs a functional MY_ATOMIC implementation."
#endif
handlerton *pfs_hton= NULL;
static handler* pfs_create_handler(handlerton *hton,
TABLE_SHARE *table,
MEM_ROOT *mem_root)
{
return new (mem_root) ha_perfschema(hton, table);
}
static int compare_database_names(const char *name1, const char *name2)
{
if (lower_case_table_names)
return strcasecmp(name1, name2);
return strcmp(name1, name2);
}
static const PFS_engine_table_share*
find_table_share(const char *db, const char *name)
{
DBUG_ENTER("find_table_share");
if (compare_database_names(db, PERFORMANCE_SCHEMA_str.str) != 0)
DBUG_RETURN(NULL);
const PFS_engine_table_share* result;
result= PFS_engine_table::find_engine_table_share(name);
DBUG_RETURN(result);
}
static int pfs_init_func(void *p)
{
DBUG_ENTER("pfs_init_func");
pfs_hton= reinterpret_cast<handlerton *> (p);
pfs_hton->state= SHOW_OPTION_YES;
pfs_hton->create= pfs_create_handler;
pfs_hton->show_status= pfs_show_status;
pfs_hton->flags= HTON_ALTER_NOT_SUPPORTED |
HTON_TEMPORARY_NOT_SUPPORTED |
HTON_NO_PARTITION;
/*
As long as the server implementation keeps using legacy_db_type,
as for example in mysql_truncate(),
we can not rely on the fact that different mysqld process will assign
consistently the same legacy_db_type for a given storage engine name.
In particular, using different --loose-skip-xxx options between
./mysqld --bootstrap
./mysqld
creates bogus .frm forms when bootstrapping the performance schema,
if we rely on ha_initialize_handlerton to assign a really dynamic value.
To fix this, a dedicated DB_TYPE is officially assigned to
the performance schema. See Bug#43039.
*/
pfs_hton->db_type= DB_TYPE_PERFORMANCE_SCHEMA;
PFS_engine_table_share::init_all_locks();
DBUG_RETURN(0);
}
static int pfs_done_func(void *p)
{
DBUG_ENTER("pfs_done_func");
pfs_hton= NULL;
PFS_engine_table_share::delete_all_locks();
DBUG_RETURN(0);
}
static struct st_mysql_show_var pfs_status_vars[]=
{
{"Performance_schema_mutex_classes_lost",
(char*) &mutex_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_rwlock_classes_lost",
(char*) &rwlock_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_cond_classes_lost",
(char*) &cond_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_thread_classes_lost",
(char*) &thread_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_file_classes_lost",
(char*) &file_class_lost, SHOW_LONG_NOFLUSH},
{"Performance_schema_mutex_instances_lost",
(char*) &mutex_lost, SHOW_LONG},
{"Performance_schema_rwlock_instances_lost",
(char*) &rwlock_lost, SHOW_LONG},
{"Performance_schema_cond_instances_lost",
(char*) &cond_lost, SHOW_LONG},
{"Performance_schema_thread_instances_lost",
(char*) &thread_lost, SHOW_LONG},
{"Performance_schema_file_instances_lost",
(char*) &file_lost, SHOW_LONG},
{"Performance_schema_file_handles_lost",
(char*) &file_handle_lost, SHOW_LONG},
{"Performance_schema_locker_lost",
(char*) &locker_lost, SHOW_LONG},
/* table shares, can be flushed */
{"Performance_schema_table_instances_lost",
(char*) &table_share_lost, SHOW_LONG},
/* table handles, can be flushed */
{"Performance_schema_table_handles_lost",
(char*) &table_lost, SHOW_LONG},
{NullS, NullS, SHOW_LONG}
};
struct st_mysql_storage_engine pfs_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION };
const char* pfs_engine_name= "PERFORMANCE_SCHEMA";
mysql_declare_plugin(perfschema)
{
MYSQL_STORAGE_ENGINE_PLUGIN,
&pfs_storage_engine,
pfs_engine_name,
"Marc Alff, Oracle", /* Formerly Sun Microsystems, formerly MySQL */
"Performance Schema",
PLUGIN_LICENSE_GPL,
pfs_init_func, /* Plugin Init */
pfs_done_func, /* Plugin Deinit */
0x0001 /* 0.1 */,
pfs_status_vars, /* status variables */
NULL, /* system variables */
NULL /* config options */
}
mysql_declare_plugin_end;
ha_perfschema::ha_perfschema(handlerton *hton, TABLE_SHARE *share)
: handler(hton, share), m_table_share(NULL), m_table(NULL)
{}
ha_perfschema::~ha_perfschema()
{}
static const char *ha_pfs_exts[]= {
NullS
};
const char **ha_perfschema::bas_ext() const
{
return ha_pfs_exts;
}
int ha_perfschema::open(const char *name, int mode, uint test_if_locked)
{
DBUG_ENTER("ha_perfschema::open");
m_table_share= find_table_share(table_share->db.str,
table_share->table_name.str);
if (! m_table_share)
DBUG_RETURN(HA_ERR_NO_SUCH_TABLE);
thr_lock_data_init(m_table_share->m_thr_lock_ptr, &m_thr_lock, NULL);
ref_length= m_table_share->m_ref_length;
psi_open();
DBUG_RETURN(0);
}
int ha_perfschema::close(void)
{
DBUG_ENTER("ha_perfschema::close");
m_table_share= NULL;
delete m_table;
m_table= NULL;
psi_close();
DBUG_RETURN(0);
}
int ha_perfschema::write_row(uchar *buf)
{
int result;
DBUG_ENTER("ha_perfschema::write_row");
ha_statistic_increment(&SSV::ha_write_count);
DBUG_ASSERT(m_table_share);
if (m_table_share->m_write_row)
result= m_table_share->m_write_row(table, buf, table->field);
else
{
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
result= HA_ERR_WRONG_COMMAND;
}
DBUG_RETURN(result);
}
void ha_perfschema::use_hidden_primary_key(void)
{
/*
This is also called in case of row based replication,
see TABLE::mark_columns_needed_for_update().
Add all columns to the read set, but do not touch the write set,
as some columns in the SETUP_ tables are not writable.
*/
table->column_bitmaps_set_no_signal(&table->s->all_set, table->write_set);
}
int ha_perfschema::update_row(const uchar *old_data, uchar *new_data)
{
DBUG_ENTER("ha_perfschema::update_row");
DBUG_ASSERT(m_table);
int result= m_table->update_row(table, old_data, new_data, table->field);
DBUG_RETURN(result);
}
int ha_perfschema::rnd_init(bool scan)
{
int result;
DBUG_ENTER("ha_perfschema::rnd_init");
DBUG_ASSERT(m_table_share);
DBUG_ASSERT(m_table_share->m_open_table != NULL);
stats.records= 0;
if (m_table == NULL)
m_table= m_table_share->m_open_table();
else
m_table->reset_position();
result= m_table ? 0 : HA_ERR_OUT_OF_MEM;
DBUG_RETURN(result);
}
int ha_perfschema::rnd_end(void)
{
DBUG_ENTER("ha_perfschema::rnd_end");
DBUG_ASSERT(m_table);
delete m_table;
m_table= NULL;
DBUG_RETURN(0);
}
int ha_perfschema::rnd_next(uchar *buf)
{
DBUG_ENTER("ha_perfschema::rnd_next");
DBUG_ASSERT(m_table);
int result= m_table->rnd_next();
if (result == 0)
{
result= m_table->read_row(table, buf, table->field);
if (result == 0)
stats.records++;
}
DBUG_RETURN(result);
}
void ha_perfschema::position(const uchar *record)
{
DBUG_ENTER("ha_perfschema::position");
DBUG_ASSERT(m_table);
m_table->get_position(ref);
DBUG_VOID_RETURN;
}
int ha_perfschema::rnd_pos(uchar *buf, uchar *pos)
{
DBUG_ENTER("ha_perfschema::rnd_pos");
DBUG_ASSERT(m_table);
int result= m_table->rnd_pos(pos);
if (result == 0)
result= m_table->read_row(table, buf, table->field);
DBUG_RETURN(result);
}
int ha_perfschema::info(uint flag)
{
DBUG_ENTER("ha_perfschema::info");
DBUG_ASSERT(m_table_share);
if (flag & HA_STATUS_VARIABLE)
stats.records= m_table_share->m_records;
if (flag & HA_STATUS_CONST)
ref_length= m_table_share->m_ref_length;
DBUG_RETURN(0);
}
int ha_perfschema::delete_all_rows(void)
{
int result;
DBUG_ENTER("ha_perfschema::delete_all_rows");
DBUG_ASSERT(m_table_share);
if (m_table_share->m_delete_all_rows)
result= m_table_share->m_delete_all_rows();
else
{
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
result= HA_ERR_WRONG_COMMAND;
}
DBUG_RETURN(result);
}
THR_LOCK_DATA **ha_perfschema::store_lock(THD *thd,
THR_LOCK_DATA **to,
enum thr_lock_type lock_type)
{
if (lock_type != TL_IGNORE && m_thr_lock.type == TL_UNLOCK)
m_thr_lock.type= lock_type;
*to++= &m_thr_lock;
m_thr_lock.m_psi= m_psi;
return to;
}
int ha_perfschema::delete_table(const char *name)
{
DBUG_ENTER("ha_perfschema::delete_table");
DBUG_RETURN(0);
}
int ha_perfschema::rename_table(const char * from, const char * to)
{
DBUG_ENTER("ha_perfschema::rename_table ");
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
int ha_perfschema::create(const char *name, TABLE *table_arg,
HA_CREATE_INFO *create_info)
{
DBUG_ENTER("ha_perfschema::create");
DBUG_ASSERT(table_arg);
DBUG_ASSERT(table_arg->s);
if (find_table_share(table_arg->s->db.str,
table_arg->s->table_name.str))
{
/*
Attempting to create a known performance schema table.
Allowing the create, to create .FRM files,
for the initial database install, and mysql_upgrade.
This should fail once .FRM are removed.
*/
DBUG_RETURN(0);
}
/*
This is not a general purpose engine.
Failure to CREATE TABLE is the expected result.
*/
my_error(ER_WRONG_PERFSCHEMA_USAGE, MYF(0));
DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestDelimitedTextReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include <vtkDelimitedTextReader.h>
#include <vtkStringArray.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkVariantArray.h>
#include <vtkTestUtilities.h>
#include <vtkIOStream.h>
int
TestDelimitedTextReader(int argc, char *argv[])
{
char *filename = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/delimited.txt");
cout << "Filename: " << filename << endl;
vtkDelimitedTextReader *reader = vtkDelimitedTextReader::New();
reader->SetFieldDelimiter(':');
reader->SetStringDelimiter('"');
reader->SetUseStringDelimiter(true);
reader->SetFileName(filename);
reader->SetHaveHeaders(false);
reader->Update();
cout << "Printing reader info..." << endl;
reader->Print(cout);
vtkTable *table = reader->GetOutput();
cout << "Delimited text file has " << table->GetNumberOfRows()
<< " rows" << endl;
cout << "Delimited text file has " << table->GetNumberOfColumns()
<< " columns" << endl;
cout << "Table contents:" << endl;
for (vtkIdType i = 0; i < table->GetNumberOfRows(); ++i)
{
vtkVariantArray *row = table->GetRow(i);
for (vtkIdType j = 0; j < row->GetNumberOfTuples(); ++j)
{
cout << "Row " << i << " column " << j << ": ";
vtkVariant value = row->GetValue(j);
if (! value.IsValid())
{
cout << "invalid value" << endl;
}
else
{
cout << "type " << value.GetTypeAsString() << " value "
<< value.ToString() << endl;
}
}
}
reader->Delete();
return 0;
}
BUG: Fix a memory leak. I didn't know that the vtkVariantArray returned by vtkTable::GetRow is allocated afresh every time you call the method.
/*=========================================================================
Program: Visualization Toolkit
Module: TestDelimitedTextReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include <vtkDelimitedTextReader.h>
#include <vtkStringArray.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkVariantArray.h>
#include <vtkTestUtilities.h>
#include <vtkIOStream.h>
int
TestDelimitedTextReader(int argc, char *argv[])
{
char *filename = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/delimited.txt");
cout << "Filename: " << filename << endl;
vtkDelimitedTextReader *reader = vtkDelimitedTextReader::New();
reader->SetFieldDelimiter(':');
reader->SetStringDelimiter('"');
reader->SetUseStringDelimiter(true);
reader->SetFileName(filename);
reader->SetHaveHeaders(false);
reader->Update();
cout << "Printing reader info..." << endl;
reader->Print(cout);
vtkTable *table = reader->GetOutput();
cout << "Delimited text file has " << table->GetNumberOfRows()
<< " rows" << endl;
cout << "Delimited text file has " << table->GetNumberOfColumns()
<< " columns" << endl;
cout << "Table contents:" << endl;
for (vtkIdType i = 0; i < table->GetNumberOfRows(); ++i)
{
vtkVariantArray *row = table->GetRow(i);
for (vtkIdType j = 0; j < row->GetNumberOfTuples(); ++j)
{
cout << "Row " << i << " column " << j << ": ";
vtkVariant value = row->GetValue(j);
if (! value.IsValid())
{
cout << "invalid value" << endl;
}
else
{
cout << "type " << value.GetTypeAsString() << " value "
<< value.ToString() << endl;
}
}
row->Delete();
}
reader->Delete();
return 0;
}
|
/*
* Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// file MainEdit.cpp
//
// Edit-related methods of DboxMain
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "corelib/pwsprefs.h"
#include "DDSupport.h"
// dialog boxen
#include "DboxMain.h"
#include "AddDlg.h"
#include "ConfirmDeleteDlg.h"
#include "QuerySetDef.h"
#include "EditDlg.h"
#include "KeySend.h"
#include "ClearQuestionDlg.h"
#include <vector>
#include <algorithm>
#include <Winable.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//Add an item
void
DboxMain::OnAdd()
{
CAddDlg dlg_add(this);
if (m_core.GetUseDefUser()) {
dlg_add.m_username = m_core.GetDefUsername();
}
// m_TreeViewGroup may be set by OnContextMenu, if not, try to grok it
if (m_TreeViewGroup.IsEmpty()) {
CItemData *itemData = NULL;
if (m_ctlItemTree.IsWindowVisible()) { // tree view
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) { // if anything selected
itemData = (CItemData *)m_ctlItemTree.GetItemData(ti);
if (itemData != NULL) { // leaf selected
m_TreeViewGroup = itemData->GetGroup();
} else { // node selected
m_TreeViewGroup = CMyString(m_ctlItemTree.GetGroup(ti));
}
}
} else { // list view
// XXX TBD - get group name of currently selected list entry
}
}
dlg_add.m_group = m_TreeViewGroup;
m_TreeViewGroup = _T(""); // for next time
app.DisableAccelerator();
INT_PTR rc = dlg_add.DoModal();
app.EnableAccelerator();
if (rc == IDOK) {
PWSprefs *prefs = PWSprefs::GetInstance();
//Check if they wish to set a default username
if (!m_core.GetUseDefUser()
&& (prefs->GetPref(PWSprefs::QuerySetDef))
&& (!dlg_add.m_username.IsEmpty())) {
CQuerySetDef defDlg(this);
defDlg.m_message.Format(IDS_SETUSERNAME, (const CString&)dlg_add.m_username);
INT_PTR rc2 = defDlg.DoModal();
if (rc2 == IDOK) {
prefs->SetPref(PWSprefs::UseDefaultUser, true);
prefs->SetPref(PWSprefs::DefaultUsername,
dlg_add.m_username);
m_core.SetUseDefUser(true);
m_core.SetDefUsername(dlg_add.m_username);
RefreshList();
}
}
//Finish Check (Does that make any geographical sense?)
CItemData temp;
CMyString user;
time_t t;
if (dlg_add.m_username.IsEmpty() && m_core.GetUseDefUser())
user = m_core.GetDefUsername();
else
user = dlg_add.m_username;
temp.CreateUUID();
temp.SetGroup(dlg_add.m_group);
temp.SetTitle(dlg_add.m_title);
temp.SetUser(user);
if (dlg_add.m_ibasedata > 0) {
// Password in alias format AND base entry exists
// No need to check if base is an alias as already done in
// call to PWScore::GetBaseEntry
uuid_array_t alias_uuid;
temp.GetUUID(alias_uuid);
m_core.AddAliasEntry(dlg_add.m_base_uuid, alias_uuid);
temp.SetPassword(CMyString(_T("[Alias]")));
temp.SetAlias();
ItemListIter iter = m_core.Find(dlg_add.m_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
} else {
temp.SetPassword(dlg_add.m_password);
temp.SetNormal();
}
temp.SetNotes(dlg_add.m_notes);
temp.SetURL(dlg_add.m_URL);
temp.SetAutoType(dlg_add.m_autotype);
time(&t);
temp.SetCTime(t);
if (temp.IsAlias())
temp.SetLTime((time_t)0);
else
temp.SetLTime(dlg_add.m_tttLTime);
if (dlg_add.m_SavePWHistory == TRUE) {
TCHAR buffer[6];
#if _MSC_VER >= 1400
_stprintf_s(buffer, 6, _T("1%02x00"), dlg_add.m_MaxPWHistory);
#else
_stprintf(buffer, _T("1%02x00"), dlg_add.m_MaxPWHistory);
#endif
temp.SetPWHistory(buffer);
}
AddEntry(temp);
if (m_core.GetNumEntries() == 1) {
// For some reason, when adding the first entry, it is not visible!
m_ctlItemTree.SetRedraw(TRUE);
}
m_ctlItemList.SetFocus();
if (prefs->GetPref(PWSprefs::SaveImmediately))
Save();
ChangeOkUpdate();
uuid_array_t uuid;
temp.GetUUID(uuid);
m_RUEList.AddRUEntry(uuid);
}
}
int
DboxMain::AddEntry(const CItemData &cinew)
{
// This routine is used by Add and also Drag & Drop
m_core.AddEntry(cinew);
// AddEntry copies the entry, and we want to work with the inserted copy
// Which we'll find by uuid
uuid_array_t uuid;
cinew.GetUUID(uuid);
int newpos = insertItem(m_core.GetEntry(m_core.Find(uuid)));
SelectEntry(newpos);
FixListIndexes();
return newpos;
}
//Add a group (tree view only)
void
DboxMain::OnAddGroup()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
if (m_ctlItemTree.IsWindowVisible()) {
// This can be reached by right clicking over an existing group node
// or by clicking over "whitespace".
// If the former, add a child node to the current one
// If the latter, add to root.
CMyString cmys_text(MAKEINTRESOURCE(IDS_NEWGROUP));
if (m_TreeViewGroup.IsEmpty())
m_TreeViewGroup = cmys_text;
else
m_TreeViewGroup += _T(".") + cmys_text;
HTREEITEM newGroup = m_ctlItemTree.AddGroup(m_TreeViewGroup);
m_ctlItemTree.SelectItem(newGroup);
m_TreeViewGroup = _T(""); // for next time
m_ctlItemTree.EditLabel(newGroup);
}
}
// Delete key was pressed (in list view or tree view) to delete an entry.
void
DboxMain::OnDelete()
{
if (m_core.GetNumEntries() == 0) // easiest way to avoid asking stupid questions...
return;
bool dontaskquestion = PWSprefs::GetInstance()->
GetPref(PWSprefs::DeleteQuestion);
bool dodelete = true;
int num_children = 0;
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM hStartItem = m_ctlItemTree.GetSelectedItem();
if (hStartItem != NULL) {
if (m_ctlItemTree.GetItemData(hStartItem) == NULL) { // group node
dontaskquestion = false; // ALWAYS ask if deleting a group
// Find number of child items
num_children = 0;
if (m_ctlItemTree.ItemHasChildren(hStartItem)) {
num_children = CountChildren(hStartItem);
} // if has children
}
}
}
//Confirm whether to delete the item
if (!dontaskquestion) {
CConfirmDeleteDlg deleteDlg(this, num_children);
INT_PTR rc = deleteDlg.DoModal();
if (rc == IDCANCEL) {
dodelete = false;
}
}
if (dodelete) {
Delete();
}
}
void
DboxMain::Delete(bool inRecursion)
{
CItemData *ci = getSelectedItem();
if (ci != NULL) {
uuid_array_t uuid;
ci->GetUUID(uuid);
UUIDList aliaslist;
int num_aliases;
m_core.GetAllAliasEntries(uuid, aliaslist);
num_aliases = aliaslist.size();
if (num_aliases > 0) {
CMyString csAliases;
SortAliasEntries(aliaslist, csAliases);
CString cs_msg;
const CString cs_title(MAKEINTRESOURCE(IDS_DELETEBASET));
cs_msg.Format(IDS_DELETEBASE, aliaslist.size(),
aliaslist.size() == 1 ? _T("") : _T("es"), csAliases);
if (MessageBox(cs_msg, cs_title, MB_ICONQUESTION | MB_YESNO) == IDNO) {
aliaslist.clear();
return;
}
}
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
int curSel = di->list_index;
// Find next in treeview, not always curSel after deletion
HTREEITEM curTree_item = di->tree_item;
HTREEITEM nextTree_item = m_ctlItemTree.GetNextItem(curTree_item,
TVGN_NEXT);
// Must Find before delete from m_ctlItemList:
ItemListIter listindex = m_core.Find(uuid);
ASSERT(listindex != m_core.GetEntryEndIter());
UnFindItem();
m_ctlItemList.DeleteItem(curSel);
m_ctlItemTree.DeleteWithParents(curTree_item);
delete di;
if (ci->NumberUnknownFields() > 0)
m_core.DecrementNumRecordsWithUnknownFields();
uuid_array_t base_uuid;
if (ci->IsAlias()) {
// I'm an alias entry
// Get corresponding base uuid
m_core.GetBaseUUID(uuid, base_uuid);
// Delete from both map and multimap
m_core.RemoveAliasEntry(base_uuid, uuid);
// Does my base now become a normal entry?
if (m_core.NumAliases(base_uuid) == 0) {
ItemListIter iter = m_core.Find(base_uuid);
CItemData &cibase = iter->second;
cibase.SetNormal();
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
}
if (num_aliases > 0) {
// I'm a base entry
m_core.ResetAllAliasPasswords(uuid);
m_core.RemoveAllAliasEntries(uuid);
// Now make all my aliases Normal
ItemListIter iter;
UUIDListIter UUIDiter;
for (UUIDiter = aliaslist.begin(); UUIDiter != aliaslist.end(); UUIDiter++) {
uuid_array_t auuid;
UUIDiter->GetUUID(auuid);
iter = m_core.Find(auuid);
CItemData &cialias = iter->second;
DisplayInfo *di = (DisplayInfo *)cialias.GetDisplayInfo();
HTREEITEM ati = di->tree_item;
SetEntryImage(cialias, ati, true);
}
aliaslist.clear();
}
m_core.RemoveEntryAt(listindex);
FixListIndexes();
if (m_ctlItemList.IsWindowVisible()) {
if (m_core.GetNumEntries() > 0) {
SelectEntry(curSel < (int)m_core.GetNumEntries() ?
curSel : (int)(m_core.GetNumEntries() - 1));
}
m_ctlItemList.SetFocus();
} else {// tree view visible
if (!inRecursion && nextTree_item != NULL) {
m_ctlItemTree.SelectItem(nextTree_item);
}
m_ctlItemTree.SetFocus();
}
ChangeOkUpdate();
m_RUEList.DeleteRUEntry(uuid);
} else { // !SelItemOk()
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) {
if (!m_ctlItemTree.IsLeaf(ti)) {
HTREEITEM cti = m_ctlItemTree.GetChildItem(ti);
m_ctlItemTree.SetRedraw( FALSE );
while (cti != NULL) {
m_ctlItemTree.SelectItem(cti);
Delete(true); // recursion - I'm so lazy!
cti = m_ctlItemTree.GetChildItem(ti);
}
m_ctlItemTree.SetRedraw( TRUE );
m_ctlItemTree.Invalidate();
// delete an empty group.
HTREEITEM parent = m_ctlItemTree.GetParentItem(ti);
m_ctlItemTree.DeleteItem(ti);
m_ctlItemTree.SelectItem(parent);
}
}
}
}
m_TreeViewGroup = _T("");
}
void
DboxMain::OnRename()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
// Renaming is only allowed while in Tree mode.
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM hItem = m_ctlItemTree.GetSelectedItem();
if (hItem != NULL)
m_ctlItemTree.EditLabel(hItem);
}
}
void
DboxMain::OnEdit()
{
// Note that Edit is also used for just viewing - don't want to disable
// viewing in read-only mode
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
EditItem(ci);
} else {
// entry item not selected - perhaps here on Enter on tree item?
// perhaps not the most elegant solution to improving non-mouse use,
// but it works. If anyone knows how Enter/Return gets mapped to OnEdit,
// let me know...
CItemData *itemData = NULL;
if (m_ctlItemTree.IsWindowVisible()) { // tree view
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) { // if anything selected
itemData = (CItemData *)m_ctlItemTree.GetItemData(ti);
if (itemData == NULL) { // node selected
m_ctlItemTree.Expand(ti, TVE_TOGGLE);
}
}
}
}
}
bool
DboxMain::EditItem(CItemData *ci, PWScore *pcore)
{
if (pcore == NULL)
pcore = &m_core;
// List might be cleared if db locked.
// Need to take care that we handle a rebuilt list.
CItemData editedItem(*ci);
CEditDlg dlg_edit(&editedItem, this);
if (pcore->GetUseDefUser())
dlg_edit.m_defusername = pcore->GetDefUsername();
dlg_edit.m_Edit_IsReadOnly = pcore->IsReadOnly();
uuid_array_t original_uuid, original_base_uuid, new_base_uuid;
ci->GetUUID(original_uuid); // Edit doesn't change this!
if (ci->IsBase()) {
// Base entry
UUIDList aliaslist;
CMyString csAliases(_T(""));
m_core.GetAllAliasEntries(original_uuid, aliaslist);
int num_aliases = aliaslist.size();
if (num_aliases > 0) {
SortAliasEntries(aliaslist, csAliases);
}
dlg_edit.m_numaliases = num_aliases;
dlg_edit.m_aliases = csAliases;
dlg_edit.m_original_entrytype = CItemData::Base;
aliaslist.clear();
}
if (ci->IsAlias()) {
// Alias entry
// Get corresponding base uuid
m_core.GetBaseUUID(original_uuid, original_base_uuid);
ItemListIter iter = m_core.Find(original_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
dlg_edit.m_base = _T("[") +
cibase.GetGroup() + _T(":") +
cibase.GetTitle() + _T(":") +
cibase.GetUser() + _T("]");
dlg_edit.m_original_entrytype = CItemData::Alias;
}
}
app.DisableAccelerator();
INT_PTR rc = dlg_edit.DoModal();
app.EnableAccelerator();
if (rc == IDOK) {
// Out with the old, in with the new
ItemListIter listpos = Find(original_uuid);
ASSERT(listpos != m_core.GetEntryEndIter());
CItemData oldElem = GetEntryAt(listpos);
DisplayInfo *di = (DisplayInfo *)oldElem.GetDisplayInfo();
ASSERT(di != NULL);
// editedItem's displayinfo will have been deleted if
// application "locked" (Cleared list)
DisplayInfo *ndi = new DisplayInfo;
ndi->list_index = -1; // so that insertItem will set new values
ndi->tree_item = 0;
editedItem.SetDisplayInfo(ndi);
CMyString newPassword = editedItem.GetPassword();
memcpy(new_base_uuid, dlg_edit.m_base_uuid, sizeof(uuid_array_t));
ItemListIter iter;
if (dlg_edit.m_original_entrytype == CItemData::Normal &&
ci->GetPassword() != newPassword) {
// Original was a 'normal' entry and the password has changed
if (dlg_edit.m_ibasedata > 0) {
// Now an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
} else {
// Still 'normal'
editedItem.SetPassword(newPassword);
editedItem.SetNormal();
}
}
if (dlg_edit.m_original_entrytype == CItemData::Alias) {
// Original was an alias - delete it from multimap
// RemoveAliasEntry also resets base to normal if the last alias is delete
pcore->RemoveAliasEntry(original_base_uuid, original_uuid);
if (newPassword == dlg_edit.m_base) {
// Password (i.e. base) unchanged - put it back
pcore->AddAliasEntry(original_base_uuid, original_uuid);
} else {
// Password changed so might be an alias of another entry!
// Could also be the same entry i.e. [:t:] == [t] !
if (dlg_edit.m_ibasedata > 0) {
// Still an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
} else {
// No longer an alias
editedItem.SetPassword(newPassword);
editedItem.SetNormal();
}
}
}
if (dlg_edit.m_original_entrytype == CItemData::Base &&
ci->GetPassword() != newPassword) {
// Original was a base but might now be an alias of another entry!
if (dlg_edit.m_ibasedata > 0) {
// Now an alias
// Make this one an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
// Move old aliases across
pcore->MoveAliases(original_uuid, new_base_uuid);
} else {
// Still a base entry but with a new password
editedItem.SetPassword(newPassword);
editedItem.SetBase();
}
}
// Reset all images!
// First the edited entry
iter = m_core.Find(original_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
// Next the original base entry
iter = m_core.Find(original_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
// Last the new base entry (only if different to the one we have done!
if (::memcmp(new_base_uuid, original_base_uuid, sizeof(uuid_array_t)) != 0) {
iter = m_core.Find(new_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
}
if (editedItem.IsAlias())
editedItem.SetLTime((time_t)0);
pcore->RemoveEntryAt(listpos);
pcore->AddEntry(editedItem);
m_ctlItemList.DeleteItem(di->list_index);
m_ctlItemTree.DeleteWithParents(di->tree_item);
// AddEntry copies the entry, and we want to work with the inserted copy
// Which we'll find by uuid
insertItem(pcore->GetEntry(m_core.Find(original_uuid)));
FixListIndexes();
// Now delete old entry's DisplayInfo
delete di;
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
}
rc = SelectEntry(ndi->list_index);
if (rc == LB_ERR) {
SelectEntry(m_ctlItemList.GetItemCount() - 1);
}
ChangeOkUpdate();
return true;
} // rc == IDOK
return false;
}
// Duplicate selected entry but make title unique
void
DboxMain::OnDuplicateEntry()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
// Get information from current selected entry
CMyString ci2_group = ci->GetGroup();
CMyString ci2_user = ci->GetUser();
CMyString ci2_title0 = ci->GetTitle();
CMyString ci2_title;
// Find a unique "Title"
ItemListConstIter listpos;
int i = 0;
CString s_copy;
do {
i++;
s_copy.Format(IDS_COPYNUMBER, i);
ci2_title = ci2_title0 + CMyString(s_copy);
listpos = m_core.Find(ci2_group, ci2_title, ci2_user);
} while (listpos != m_core.GetEntryEndIter());
// Set up new entry
CItemData ci2;
ci2.CreateUUID();
ci2.SetGroup(ci2_group);
ci2.SetTitle(ci2_title);
ci2.SetUser(ci2_user);
ci2.SetPassword(ci->GetPassword());
ci2.SetURL(ci->GetURL());
ci2.SetAutoType(ci->GetAutoType());
ci2.SetNotes(ci->GetNotes());
time_t t;
ci->GetCTime(t);
if ((long) t != 0)
ci2.SetCTime(t);
ci->GetATime(t);
if ((long) t != 0)
ci2.SetATime(t);
ci->GetLTime(t);
if ((long) t != 0)
ci2.SetLTime(t);
ci->GetPMTime(t);
if ((long) t != 0)
ci2.SetPMTime(t);
ci->GetRMTime(t);
if ((long) t != 0)
ci2.SetRMTime(t);
CMyString tmp = ci->GetPWHistory();
if (tmp.GetLength() >= 5)
ci2.SetPWHistory(tmp);
uuid_array_t base_uuid, alias_uuid;
if (ci->IsAlias()) {
ci2.SetAlias();
ci2.GetUUID(alias_uuid);
m_core.AddAliasEntry(alias_uuid, base_uuid);
ItemListIter iter;
iter = m_core.Find(base_uuid);
if (iter != m_core.GetEntryEndIter()) {
CMyString cs_tmp;
cs_tmp = _T("[") +
iter->second.GetGroup() + _T(":") +
iter->second.GetTitle() + _T(":") +
iter->second.GetUser() + _T("]");
ci2.SetPassword(cs_tmp);
}
}
// Add it to the end of the list
m_core.AddEntry(ci2);
di->list_index = -1; // so that insertItem will set new values
uuid_array_t uuid;
ci2.GetUUID(uuid);
insertItem(m_core.GetEntry(m_core.Find(uuid)));
FixListIndexes();
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
}
int rc = SelectEntry(di->list_index);
if (rc == LB_ERR) {
SelectEntry(m_ctlItemList.GetItemCount() - 1);
}
ChangeOkUpdate();
m_RUEList.AddRUEntry(uuid);
}
}
void
DboxMain::OnCopyPassword()
{
if (!SelItemOk())
return;
//Remind the user about clipboard security
CClearQuestionDlg clearDlg(this);
if (clearDlg.m_dontaskquestion == FALSE &&
clearDlg.DoModal() == IDCANCEL)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
uuid_array_t base_uuid, alias_uuid;
if (ci->IsAlias()) {
// This is an alias
ci->GetUUID(alias_uuid);
m_core.GetBaseUUID(alias_uuid, base_uuid);
ItemListIter iter = m_core.Find(base_uuid);
if (iter != End()) {
SetClipboardData(iter->second.GetPassword());
}
} else
SetClipboardData(ci->GetPassword());
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
void
DboxMain::OnCopyUsername()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString username = ci->GetUser();
if (!username.IsEmpty()) {
SetClipboardData(username);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnCopyNotes()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString notes = ci->GetNotes();
const CMyString url = ci->GetURL();
const CMyString autotype = ci->GetAutoType();
CMyString clipboard_data;
CString cs_text;
clipboard_data = notes;
if (!url.IsEmpty()) {
cs_text.LoadString(IDS_COPYURL);
clipboard_data += CMyString(cs_text);
clipboard_data += url;
}
if (!autotype.IsEmpty()) {
cs_text.LoadString(IDS_COPYAUTOTYPE);
clipboard_data += CMyString(cs_text);
clipboard_data += autotype;
}
if (!clipboard_data.IsEmpty()) {
SetClipboardData(clipboard_data);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnCopyURL()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString cs_URL = ci->GetURL();
if (!cs_URL.IsEmpty()) {
SetClipboardData(cs_URL);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnFind()
{
// Note that this "toggles" the Find Tool Bar so that the user can use Ctrl+F
// to show it and then hide it.
SetFindToolBar(!m_FindToolBar.IsVisible());
}
void
DboxMain::OnClearClipboard()
{
ClearClipboardData();
}
void
DboxMain::OnAutoType()
{
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
UpdateAccessTime(ci);
// All code using ci must be before this AutoType since the
// latter may trash *ci if lock-on-minimize
AutoType(*ci);
}
}
const CString DboxMain::DEFAULT_AUTOTYPE = _T("\\u\\t\\p\\n");
void
DboxMain::AutoType(const CItemData &ci)
{
CMyString AutoCmd = ci.GetAutoType();
const CMyString user(ci.GetUser());
CMyString pwd;
uuid_array_t base_uuid, alias_uuid;
if (ci.IsAlias()) {
// This is an alias
ci.GetUUID(alias_uuid);
m_core.GetBaseUUID(alias_uuid, base_uuid);
ItemListIter iter = m_core.Find(base_uuid);
if (iter != End()) {
pwd = iter->second.GetPassword();
}
} else {
pwd = ci.GetPassword();
}
// If empty, try the database default
if (AutoCmd.IsEmpty()) {
AutoCmd = PWSprefs::GetInstance()->
GetPref(PWSprefs::DefaultAutotypeString);
// If still empty, take this default
if (AutoCmd.IsEmpty()) {
// checking for user and password for default settings
if (!pwd.IsEmpty()){
if (!user.IsEmpty())
AutoCmd = CMyString(DEFAULT_AUTOTYPE);
else
AutoCmd = _T("\\p\\n");
}
}
}
CKeySend ks;
// Turn off CAPSLOCK
bool bCapsLock = false;
if (GetKeyState(VK_CAPITAL)) {
bCapsLock = true;
ks.SetCapsLock(false);
}
CMyString tmp;
TCHAR curChar;
const int N = AutoCmd.GetLength();
ks.ResetKeyboardState();
::BlockInput(true);
// Note that minimizing the window before calling ci.Get*()
// will cause garbage to be read if "lock on minimize" selected,
// since that will clear the data [Bugs item #1026630]
// (this is why we read user & pwd before actual use)
// Rules are ("Minimize on Autotype" takes precedence):
// 1. If "MinimizeOnAutotype" - minimize PWS during Autotype but do
// not restore it (previous default action - but a pain if locked
// in the system tray!)
// 2. If "Always on Top" - hide PWS during Autotype and then make it
// "AlwaysOnTop" again, unless minimized!
// 3. If not "Always on Top" - hide PWS during Autotype and show
// it again once finished - but behind other windows.
bool bMinOnAuto = PWSprefs::GetInstance()->
GetPref(PWSprefs::MinimizeOnAutotype) == TRUE;
if (bMinOnAuto)
ShowWindow(SW_MINIMIZE);
else
ShowWindow(SW_HIDE);
Sleep(1000); // Karl Student's suggestion, to ensure focus set correctly on minimize.
for(int n = 0; n < N; n++){
curChar = AutoCmd[n];
if(curChar == TCHAR('\\')) {
n++;
if(n < N)
curChar=AutoCmd[n];
switch(curChar){
case TCHAR('\\'):
tmp += TCHAR('\\');
break;
case TCHAR('n'):
case TCHAR('r'):
tmp += TCHAR('\r');
break;
case TCHAR('t'):
tmp += TCHAR('\t');
break;
case TCHAR('u'):
tmp += user;
break;
case TCHAR('p'):
tmp += pwd;
break;
case TCHAR('d'): {
// Delay is going to change - send what we have with old delay
ks.SendString(tmp);
// start collecting new delay
tmp = _T("");
int newdelay = 0;
int gNumIts = 0;
for(n++; n < N && (gNumIts < 3); ++gNumIts, n++)
if(isdigit(AutoCmd[n])){
newdelay *= 10;
newdelay += (AutoCmd[n] - TCHAR('0'));
} else
break; // for loop
n--;
ks.SetAndDelay(newdelay);
break; // case
}
default:
tmp += _T("\\") + curChar;
break;
}
} else
tmp += curChar;
}
ks.SendString(tmp);
// If we turned off CAPSLOCK, put it back
if (bCapsLock)
ks.SetCapsLock(true);
Sleep(100);
::BlockInput(false);
// If we hid it, now show it
if (bMinOnAuto)
return;
if (PWSprefs::GetInstance()->GetPref(PWSprefs::AlwaysOnTop)) {
SetWindowPos(&wndTopMost, 0, 0, 0, 0,
SWP_SHOWWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
} else {
SetWindowPos(&wndBottom, 0, 0, 0, 0,
SWP_SHOWWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
}
}
void
DboxMain::AddEntries(CDDObList &in_oblist, const CMyString &DropGroup)
{
CItemData tempitem;
UUIDList possible_aliases;
CMyString Group, Title, User;
POSITION pos;
TCHAR *dot;
for (pos = in_oblist.GetHeadPosition(); pos != NULL; in_oblist.GetNext(pos)) {
CDDObject *pDDObject = (CDDObject *)in_oblist.GetAt(pos);
tempitem.Clear();
pDDObject->ToItem(tempitem);
if (in_oblist.m_bDragNode) {
dot = (!DropGroup.IsEmpty() && !tempitem.GetGroup().IsEmpty()) ? _T(".") : _T("");
Group = DropGroup + dot + tempitem.GetGroup();
} else {
Group = DropGroup;
}
User = tempitem.GetUser();
Title = GetUniqueTitle(Group, tempitem.GetTitle(), User, IDS_DRAGNUMBER);
uuid_array_t entry_uuid;
tempitem.GetUUID(entry_uuid);
if (m_core.Find(entry_uuid) != End())
tempitem.CreateUUID();
tempitem.SetGroup(Group);
tempitem.SetTitle(Title);
uuid_array_t base_uuid, alias_uuid;
CMyString cs_tmp = tempitem.GetPassword();
CMyString csPwdGroup, csPwdTitle, csPwdUser;
bool bBase_was_Alias(false), bMultiple(false);
int ialias = m_core.GetBaseEntry(cs_tmp, base_uuid, bBase_was_Alias, bMultiple,
csPwdGroup, csPwdTitle, csPwdUser);
if (ialias > 0) {
// Password in alias format AND base entry exists
ItemListIter iter = m_core.Find(base_uuid);
ASSERT(iter != End());
if (bBase_was_Alias) {
// This base is in fact an alias. GetBaseEntry already found 'proper base'
// So dropped entry will point to the 'proper base' and tell the user.
CString cs_msg;
cs_msg.Format(IDS_DDBASEISALIAS, Group, Title, User);
AfxMessageBox(cs_msg, MB_OK);
}
tempitem.GetUUID(alias_uuid);
m_core.AddAliasEntry(base_uuid, alias_uuid);
tempitem.SetPassword(CMyString(_T("[Alias]")));
tempitem.SetAlias();
} else
if (ialias == 0) {
// Password NOT in alias format
tempitem.SetNormal();
} else
if (ialias < 0) {
// Password in alias format AND base entry does not exist or multiple possible
// base entries exit.
// Note: As more entries are added, what was "not exist" may become "no unique exists"
// or "multiple exist". Let the code that processes the possible aliases after all
// have been added sort this out.
tempitem.GetUUID(alias_uuid);
possible_aliases.push_back(alias_uuid);
}
AddEntry(tempitem);
} // iteration over in_oblist
// Now try to add aliases we couldn't add in previous processing
m_core.AddAliasesViaPassword(possible_aliases, NULL);
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
ChangeOkUpdate();
}
FixListIndexes();
RefreshList();
}
// Return whether first [g:t:u] is greater than the second [g:t:u]
// used in std::sort in SortAliasEntries below.
bool GTUCompare(CMyString elem1, CMyString elem2)
{
CMyString g1, t1, u1, g2, t2, u2, tmp1, tmp2;
g1 = elem1.SpanExcluding(_T(":"));
g2 = elem2.SpanExcluding(_T(":"));
if (g1 != g2)
return g1.Compare(g2) < 0;
tmp1 = elem1.Mid(g1.GetLength() + 1);
tmp2 = elem2.Mid(g2.GetLength() + 1);
t1 = tmp1.SpanExcluding(_T(":"));
t2 = tmp2.SpanExcluding(_T(":"));
if (t1 != t2)
return t1.Compare(t2) < 0;
tmp1 = tmp1.Mid(t1.GetLength() + 1);
tmp2 = tmp2.Mid(t2.GetLength() + 1);
u1 = tmp1.SpanExcluding(_T(":"));
u2 = tmp2.SpanExcluding(_T(":"));
return u1.Compare(u2) < 0;
}
void DboxMain::SortAliasEntries(UUIDList &aliaslist, CMyString &csAliases)
{
std::vector<CMyString> sorted_aliases;
std::vector<CMyString>::iterator sa_iter;
ItemListIter iter;
UUIDListIter aiter;
CMyString cs_alias;
for (aiter = aliaslist.begin(); aiter != aliaslist.end(); aiter++) {
uuid_array_t alias_uuid;
aiter->GetUUID(alias_uuid);
iter = m_core.Find(alias_uuid);
if (iter != m_core.GetEntryEndIter()) {
cs_alias = iter->second.GetGroup() + _T(":") +
iter->second.GetTitle() + _T(":") +
iter->second.GetUser();
sorted_aliases.push_back(cs_alias);
}
}
std::sort(sorted_aliases.begin(), sorted_aliases.end(), GTUCompare);
csAliases.Empty();
for (sa_iter = sorted_aliases.begin(); sa_iter != sorted_aliases.end(); sa_iter++) {
csAliases += _T("\t[") + *sa_iter + _T("]\r\n");
}
}
LRESULT
DboxMain::OnToolBarFindMessage(WPARAM /* wParam */, LPARAM /* lParam */)
{
// Called when user types into the Find search edit control on the Find Toolbar
// and presses enter.
OnToolBarFind();
return 0L;
}
void DboxMain::OnToolBarFind()
{
// Called when the user presses the Find button on the Find Toolbar
m_FindToolBar.Find();
}
bool
DboxMain::CheckNewPassword(const CMyString &group, const CMyString &title,
const CMyString &user, const CMyString &password,
const bool bIsEdit, uuid_array_t &base_uuid, int &ibasedata)
{
// Called from Add and Edit dialog
CMyString csPwdGroup, csPwdTitle, csPwdUser;
bool bBase_was_Alias(false), bMultiple(false);
ibasedata = m_core.GetBaseEntry(password, base_uuid, bBase_was_Alias, bMultiple,
csPwdGroup, csPwdTitle, csPwdUser);
if (bIsEdit && (csPwdGroup == group && csPwdTitle == title && csPwdUser == user)) {
// In Edit, check user isn't changing entry to point to itself (circular/self reference)
// Can't happen during Add as already checked entry does not exist so if accepted the
// password would be treated as an unusal "normal" password
AfxMessageBox(IDS_ALIASCANTREFERTOITSELF);
return false;
}
// ibasedata:
// +n: password contains (n-1) colons and base entry found (n = 1, 2 or 3)
// 0: password not in alias format
// -n: password contains (n-1) colons but base entry NOT found (n = 1, 2 or 3)
// "bBase_was_Alias" is set if the user specified a base entry that is an alias. The real base is returned
// "bMultiple" is set if no "unique" base entry could be found and is only valid if n = -1 or -2.
if (ibasedata < 0) {
CString cs_msg;
const CString cs_msgA(MAKEINTRESOURCE(IDS_ALIASNOTFOUNDA));
const CString cs_msgZ(MAKEINTRESOURCE(IDS_ALIASNOTFOUNDZ));
int rc(IDNO);
switch (ibasedata) {
case -1: // [x]
if (bMultiple)
cs_msg.Format(IDS_ALIASNOTFOUND0A, csPwdTitle); // multiple entries exist with title=x
else
cs_msg.Format(IDS_ALIASNOTFOUND0B, csPwdTitle); // no entry exists with title=x
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
break;
case -2: // [g,t], [t:u]
// In this case the 2 fields from the password are in Group & Title
if (bMultiple)
cs_msg.Format(IDS_ALIASNOTFOUND1A, csPwdGroup, csPwdTitle, csPwdGroup, csPwdTitle);
else
cs_msg.Format(IDS_ALIASNOTFOUND1B, csPwdGroup, csPwdTitle, csPwdGroup, csPwdTitle);
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
break;
case -3: // [x:y:z], [x:y:], [:y:z], [:y:] (title cannot be empty)
{
const bool bGE = csPwdGroup.IsEmpty() == TRUE;
const bool bTE = csPwdTitle.IsEmpty() == TRUE;
const bool bUE = csPwdUser.IsEmpty() == TRUE;
if (bTE) {
// Title is mandatory for all entries!
AfxMessageBox(IDS_BASEHASNOTITLE, MB_OK);
rc = IDNO;
break;
} else if (!bGE && !bUE) // [x:y:z]
cs_msg.Format(IDS_ALIASNOTFOUND2A, csPwdGroup, csPwdTitle, csPwdUser);
else if (!bGE && bUE) // [x:y:]
cs_msg.Format(IDS_ALIASNOTFOUND2B, csPwdGroup, csPwdTitle);
else if (bGE && !bUE) // [:y:z]
cs_msg.Format(IDS_ALIASNOTFOUND2C, csPwdTitle, csPwdUser);
else if (bGE && bUE) // [:y:]
cs_msg.Format(IDS_ALIASNOTFOUND0B, csPwdTitle);
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
}
break;
default:
// Never happens
ASSERT(0);
}
if (rc == IDNO) {
return false;
}
}
if (ibasedata > 0 && bBase_was_Alias) {
CString cs_msg;
cs_msg.Format(IDS_BASEISALIAS, csPwdGroup, csPwdTitle, csPwdUser);
if (AfxMessageBox(cs_msg, MB_YESNO | MB_DEFBUTTON2) == IDNO) {
return false;
}
}
// All OK
return true;
}
Fix duplicating aliases
git-svn-id: 7e36d3665aeca4d4e1f6df8911a80efc6ef565e7@1773 1f79f812-37fb-46fe-a122-30589dd2bf55
/*
* Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// file MainEdit.cpp
//
// Edit-related methods of DboxMain
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "corelib/pwsprefs.h"
#include "DDSupport.h"
// dialog boxen
#include "DboxMain.h"
#include "AddDlg.h"
#include "ConfirmDeleteDlg.h"
#include "QuerySetDef.h"
#include "EditDlg.h"
#include "KeySend.h"
#include "ClearQuestionDlg.h"
#include <vector>
#include <algorithm>
#include <Winable.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//Add an item
void
DboxMain::OnAdd()
{
CAddDlg dlg_add(this);
if (m_core.GetUseDefUser()) {
dlg_add.m_username = m_core.GetDefUsername();
}
// m_TreeViewGroup may be set by OnContextMenu, if not, try to grok it
if (m_TreeViewGroup.IsEmpty()) {
CItemData *itemData = NULL;
if (m_ctlItemTree.IsWindowVisible()) { // tree view
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) { // if anything selected
itemData = (CItemData *)m_ctlItemTree.GetItemData(ti);
if (itemData != NULL) { // leaf selected
m_TreeViewGroup = itemData->GetGroup();
} else { // node selected
m_TreeViewGroup = CMyString(m_ctlItemTree.GetGroup(ti));
}
}
} else { // list view
// XXX TBD - get group name of currently selected list entry
}
}
dlg_add.m_group = m_TreeViewGroup;
m_TreeViewGroup = _T(""); // for next time
app.DisableAccelerator();
INT_PTR rc = dlg_add.DoModal();
app.EnableAccelerator();
if (rc == IDOK) {
PWSprefs *prefs = PWSprefs::GetInstance();
//Check if they wish to set a default username
if (!m_core.GetUseDefUser()
&& (prefs->GetPref(PWSprefs::QuerySetDef))
&& (!dlg_add.m_username.IsEmpty())) {
CQuerySetDef defDlg(this);
defDlg.m_message.Format(IDS_SETUSERNAME, (const CString&)dlg_add.m_username);
INT_PTR rc2 = defDlg.DoModal();
if (rc2 == IDOK) {
prefs->SetPref(PWSprefs::UseDefaultUser, true);
prefs->SetPref(PWSprefs::DefaultUsername,
dlg_add.m_username);
m_core.SetUseDefUser(true);
m_core.SetDefUsername(dlg_add.m_username);
RefreshList();
}
}
//Finish Check (Does that make any geographical sense?)
CItemData temp;
CMyString user;
time_t t;
if (dlg_add.m_username.IsEmpty() && m_core.GetUseDefUser())
user = m_core.GetDefUsername();
else
user = dlg_add.m_username;
temp.CreateUUID();
temp.SetGroup(dlg_add.m_group);
temp.SetTitle(dlg_add.m_title);
temp.SetUser(user);
if (dlg_add.m_ibasedata > 0) {
// Password in alias format AND base entry exists
// No need to check if base is an alias as already done in
// call to PWScore::GetBaseEntry
uuid_array_t alias_uuid;
temp.GetUUID(alias_uuid);
m_core.AddAliasEntry(dlg_add.m_base_uuid, alias_uuid);
temp.SetPassword(CMyString(_T("[Alias]")));
temp.SetAlias();
ItemListIter iter = m_core.Find(dlg_add.m_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
} else {
temp.SetPassword(dlg_add.m_password);
temp.SetNormal();
}
temp.SetNotes(dlg_add.m_notes);
temp.SetURL(dlg_add.m_URL);
temp.SetAutoType(dlg_add.m_autotype);
time(&t);
temp.SetCTime(t);
if (temp.IsAlias())
temp.SetLTime((time_t)0);
else
temp.SetLTime(dlg_add.m_tttLTime);
if (dlg_add.m_SavePWHistory == TRUE) {
TCHAR buffer[6];
#if _MSC_VER >= 1400
_stprintf_s(buffer, 6, _T("1%02x00"), dlg_add.m_MaxPWHistory);
#else
_stprintf(buffer, _T("1%02x00"), dlg_add.m_MaxPWHistory);
#endif
temp.SetPWHistory(buffer);
}
AddEntry(temp);
if (m_core.GetNumEntries() == 1) {
// For some reason, when adding the first entry, it is not visible!
m_ctlItemTree.SetRedraw(TRUE);
}
m_ctlItemList.SetFocus();
if (prefs->GetPref(PWSprefs::SaveImmediately))
Save();
ChangeOkUpdate();
uuid_array_t uuid;
temp.GetUUID(uuid);
m_RUEList.AddRUEntry(uuid);
}
}
int
DboxMain::AddEntry(const CItemData &cinew)
{
// This routine is used by Add and also Drag & Drop
m_core.AddEntry(cinew);
// AddEntry copies the entry, and we want to work with the inserted copy
// Which we'll find by uuid
uuid_array_t uuid;
cinew.GetUUID(uuid);
int newpos = insertItem(m_core.GetEntry(m_core.Find(uuid)));
SelectEntry(newpos);
FixListIndexes();
return newpos;
}
//Add a group (tree view only)
void
DboxMain::OnAddGroup()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
if (m_ctlItemTree.IsWindowVisible()) {
// This can be reached by right clicking over an existing group node
// or by clicking over "whitespace".
// If the former, add a child node to the current one
// If the latter, add to root.
CMyString cmys_text(MAKEINTRESOURCE(IDS_NEWGROUP));
if (m_TreeViewGroup.IsEmpty())
m_TreeViewGroup = cmys_text;
else
m_TreeViewGroup += _T(".") + cmys_text;
HTREEITEM newGroup = m_ctlItemTree.AddGroup(m_TreeViewGroup);
m_ctlItemTree.SelectItem(newGroup);
m_TreeViewGroup = _T(""); // for next time
m_ctlItemTree.EditLabel(newGroup);
}
}
// Delete key was pressed (in list view or tree view) to delete an entry.
void
DboxMain::OnDelete()
{
if (m_core.GetNumEntries() == 0) // easiest way to avoid asking stupid questions...
return;
bool dontaskquestion = PWSprefs::GetInstance()->
GetPref(PWSprefs::DeleteQuestion);
bool dodelete = true;
int num_children = 0;
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM hStartItem = m_ctlItemTree.GetSelectedItem();
if (hStartItem != NULL) {
if (m_ctlItemTree.GetItemData(hStartItem) == NULL) { // group node
dontaskquestion = false; // ALWAYS ask if deleting a group
// Find number of child items
num_children = 0;
if (m_ctlItemTree.ItemHasChildren(hStartItem)) {
num_children = CountChildren(hStartItem);
} // if has children
}
}
}
//Confirm whether to delete the item
if (!dontaskquestion) {
CConfirmDeleteDlg deleteDlg(this, num_children);
INT_PTR rc = deleteDlg.DoModal();
if (rc == IDCANCEL) {
dodelete = false;
}
}
if (dodelete) {
Delete();
}
}
void
DboxMain::Delete(bool inRecursion)
{
CItemData *ci = getSelectedItem();
if (ci != NULL) {
uuid_array_t uuid;
ci->GetUUID(uuid);
UUIDList aliaslist;
int num_aliases;
m_core.GetAllAliasEntries(uuid, aliaslist);
num_aliases = aliaslist.size();
if (num_aliases > 0) {
CMyString csAliases;
SortAliasEntries(aliaslist, csAliases);
CString cs_msg;
const CString cs_title(MAKEINTRESOURCE(IDS_DELETEBASET));
cs_msg.Format(IDS_DELETEBASE, aliaslist.size(),
aliaslist.size() == 1 ? _T("") : _T("es"), csAliases);
if (MessageBox(cs_msg, cs_title, MB_ICONQUESTION | MB_YESNO) == IDNO) {
aliaslist.clear();
return;
}
}
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
int curSel = di->list_index;
// Find next in treeview, not always curSel after deletion
HTREEITEM curTree_item = di->tree_item;
HTREEITEM nextTree_item = m_ctlItemTree.GetNextItem(curTree_item,
TVGN_NEXT);
// Must Find before delete from m_ctlItemList:
ItemListIter listindex = m_core.Find(uuid);
ASSERT(listindex != m_core.GetEntryEndIter());
UnFindItem();
m_ctlItemList.DeleteItem(curSel);
m_ctlItemTree.DeleteWithParents(curTree_item);
delete di;
if (ci->NumberUnknownFields() > 0)
m_core.DecrementNumRecordsWithUnknownFields();
uuid_array_t base_uuid;
if (ci->IsAlias()) {
// I'm an alias entry
// Get corresponding base uuid
m_core.GetBaseUUID(uuid, base_uuid);
// Delete from both map and multimap
m_core.RemoveAliasEntry(base_uuid, uuid);
// Does my base now become a normal entry?
if (m_core.NumAliases(base_uuid) == 0) {
ItemListIter iter = m_core.Find(base_uuid);
CItemData &cibase = iter->second;
cibase.SetNormal();
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
}
if (num_aliases > 0) {
// I'm a base entry
m_core.ResetAllAliasPasswords(uuid);
m_core.RemoveAllAliasEntries(uuid);
// Now make all my aliases Normal
ItemListIter iter;
UUIDListIter UUIDiter;
for (UUIDiter = aliaslist.begin(); UUIDiter != aliaslist.end(); UUIDiter++) {
uuid_array_t auuid;
UUIDiter->GetUUID(auuid);
iter = m_core.Find(auuid);
CItemData &cialias = iter->second;
DisplayInfo *di = (DisplayInfo *)cialias.GetDisplayInfo();
HTREEITEM ati = di->tree_item;
SetEntryImage(cialias, ati, true);
}
aliaslist.clear();
}
m_core.RemoveEntryAt(listindex);
FixListIndexes();
if (m_ctlItemList.IsWindowVisible()) {
if (m_core.GetNumEntries() > 0) {
SelectEntry(curSel < (int)m_core.GetNumEntries() ?
curSel : (int)(m_core.GetNumEntries() - 1));
}
m_ctlItemList.SetFocus();
} else {// tree view visible
if (!inRecursion && nextTree_item != NULL) {
m_ctlItemTree.SelectItem(nextTree_item);
}
m_ctlItemTree.SetFocus();
}
ChangeOkUpdate();
m_RUEList.DeleteRUEntry(uuid);
} else { // !SelItemOk()
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) {
if (!m_ctlItemTree.IsLeaf(ti)) {
HTREEITEM cti = m_ctlItemTree.GetChildItem(ti);
m_ctlItemTree.SetRedraw( FALSE );
while (cti != NULL) {
m_ctlItemTree.SelectItem(cti);
Delete(true); // recursion - I'm so lazy!
cti = m_ctlItemTree.GetChildItem(ti);
}
m_ctlItemTree.SetRedraw( TRUE );
m_ctlItemTree.Invalidate();
// delete an empty group.
HTREEITEM parent = m_ctlItemTree.GetParentItem(ti);
m_ctlItemTree.DeleteItem(ti);
m_ctlItemTree.SelectItem(parent);
}
}
}
}
m_TreeViewGroup = _T("");
}
void
DboxMain::OnRename()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
// Renaming is only allowed while in Tree mode.
if (m_ctlItemTree.IsWindowVisible()) {
HTREEITEM hItem = m_ctlItemTree.GetSelectedItem();
if (hItem != NULL)
m_ctlItemTree.EditLabel(hItem);
}
}
void
DboxMain::OnEdit()
{
// Note that Edit is also used for just viewing - don't want to disable
// viewing in read-only mode
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
EditItem(ci);
} else {
// entry item not selected - perhaps here on Enter on tree item?
// perhaps not the most elegant solution to improving non-mouse use,
// but it works. If anyone knows how Enter/Return gets mapped to OnEdit,
// let me know...
CItemData *itemData = NULL;
if (m_ctlItemTree.IsWindowVisible()) { // tree view
HTREEITEM ti = m_ctlItemTree.GetSelectedItem();
if (ti != NULL) { // if anything selected
itemData = (CItemData *)m_ctlItemTree.GetItemData(ti);
if (itemData == NULL) { // node selected
m_ctlItemTree.Expand(ti, TVE_TOGGLE);
}
}
}
}
}
bool
DboxMain::EditItem(CItemData *ci, PWScore *pcore)
{
if (pcore == NULL)
pcore = &m_core;
// List might be cleared if db locked.
// Need to take care that we handle a rebuilt list.
CItemData editedItem(*ci);
CEditDlg dlg_edit(&editedItem, this);
if (pcore->GetUseDefUser())
dlg_edit.m_defusername = pcore->GetDefUsername();
dlg_edit.m_Edit_IsReadOnly = pcore->IsReadOnly();
uuid_array_t original_uuid, original_base_uuid, new_base_uuid;
ci->GetUUID(original_uuid); // Edit doesn't change this!
if (ci->IsBase()) {
// Base entry
UUIDList aliaslist;
CMyString csAliases(_T(""));
m_core.GetAllAliasEntries(original_uuid, aliaslist);
int num_aliases = aliaslist.size();
if (num_aliases > 0) {
SortAliasEntries(aliaslist, csAliases);
}
dlg_edit.m_numaliases = num_aliases;
dlg_edit.m_aliases = csAliases;
dlg_edit.m_original_entrytype = CItemData::Base;
aliaslist.clear();
}
if (ci->IsAlias()) {
// Alias entry
// Get corresponding base uuid
m_core.GetBaseUUID(original_uuid, original_base_uuid);
ItemListIter iter = m_core.Find(original_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
dlg_edit.m_base = _T("[") +
cibase.GetGroup() + _T(":") +
cibase.GetTitle() + _T(":") +
cibase.GetUser() + _T("]");
dlg_edit.m_original_entrytype = CItemData::Alias;
}
}
app.DisableAccelerator();
INT_PTR rc = dlg_edit.DoModal();
app.EnableAccelerator();
if (rc == IDOK) {
// Out with the old, in with the new
ItemListIter listpos = Find(original_uuid);
ASSERT(listpos != m_core.GetEntryEndIter());
CItemData oldElem = GetEntryAt(listpos);
DisplayInfo *di = (DisplayInfo *)oldElem.GetDisplayInfo();
ASSERT(di != NULL);
// editedItem's displayinfo will have been deleted if
// application "locked" (Cleared list)
DisplayInfo *ndi = new DisplayInfo;
ndi->list_index = -1; // so that insertItem will set new values
ndi->tree_item = 0;
editedItem.SetDisplayInfo(ndi);
CMyString newPassword = editedItem.GetPassword();
memcpy(new_base_uuid, dlg_edit.m_base_uuid, sizeof(uuid_array_t));
ItemListIter iter;
if (dlg_edit.m_original_entrytype == CItemData::Normal &&
ci->GetPassword() != newPassword) {
// Original was a 'normal' entry and the password has changed
if (dlg_edit.m_ibasedata > 0) {
// Now an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
} else {
// Still 'normal'
editedItem.SetPassword(newPassword);
editedItem.SetNormal();
}
}
if (dlg_edit.m_original_entrytype == CItemData::Alias) {
// Original was an alias - delete it from multimap
// RemoveAliasEntry also resets base to normal if the last alias is delete
pcore->RemoveAliasEntry(original_base_uuid, original_uuid);
if (newPassword == dlg_edit.m_base) {
// Password (i.e. base) unchanged - put it back
pcore->AddAliasEntry(original_base_uuid, original_uuid);
} else {
// Password changed so might be an alias of another entry!
// Could also be the same entry i.e. [:t:] == [t] !
if (dlg_edit.m_ibasedata > 0) {
// Still an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
} else {
// No longer an alias
editedItem.SetPassword(newPassword);
editedItem.SetNormal();
}
}
}
if (dlg_edit.m_original_entrytype == CItemData::Base &&
ci->GetPassword() != newPassword) {
// Original was a base but might now be an alias of another entry!
if (dlg_edit.m_ibasedata > 0) {
// Now an alias
// Make this one an alias
pcore->AddAliasEntry(new_base_uuid, original_uuid);
editedItem.SetPassword(CMyString(_T("[Alias]")));
editedItem.SetAlias();
// Move old aliases across
pcore->MoveAliases(original_uuid, new_base_uuid);
} else {
// Still a base entry but with a new password
editedItem.SetPassword(newPassword);
editedItem.SetBase();
}
}
// Reset all images!
// First the edited entry
iter = m_core.Find(original_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
// Next the original base entry
iter = m_core.Find(original_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
// Last the new base entry (only if different to the one we have done!
if (::memcmp(new_base_uuid, original_base_uuid, sizeof(uuid_array_t)) != 0) {
iter = m_core.Find(new_base_uuid);
if (iter != End()) {
const CItemData &cibase = iter->second;
DisplayInfo *di = (DisplayInfo *)cibase.GetDisplayInfo();
HTREEITEM bti = di->tree_item;
SetEntryImage(cibase, bti, true);
}
}
if (editedItem.IsAlias())
editedItem.SetLTime((time_t)0);
pcore->RemoveEntryAt(listpos);
pcore->AddEntry(editedItem);
m_ctlItemList.DeleteItem(di->list_index);
m_ctlItemTree.DeleteWithParents(di->tree_item);
// AddEntry copies the entry, and we want to work with the inserted copy
// Which we'll find by uuid
insertItem(pcore->GetEntry(m_core.Find(original_uuid)));
FixListIndexes();
// Now delete old entry's DisplayInfo
delete di;
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
}
rc = SelectEntry(ndi->list_index);
if (rc == LB_ERR) {
SelectEntry(m_ctlItemList.GetItemCount() - 1);
}
ChangeOkUpdate();
return true;
} // rc == IDOK
return false;
}
// Duplicate selected entry but make title unique
void
DboxMain::OnDuplicateEntry()
{
if (m_core.IsReadOnly()) // disable in read-only mode
return;
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
// Get information from current selected entry
CMyString ci2_group = ci->GetGroup();
CMyString ci2_user = ci->GetUser();
CMyString ci2_title0 = ci->GetTitle();
CMyString ci2_title;
// Find a unique "Title"
ItemListConstIter listpos;
int i = 0;
CString s_copy;
do {
i++;
s_copy.Format(IDS_COPYNUMBER, i);
ci2_title = ci2_title0 + CMyString(s_copy);
listpos = m_core.Find(ci2_group, ci2_title, ci2_user);
} while (listpos != m_core.GetEntryEndIter());
// Set up new entry
CItemData ci2;
ci2.CreateUUID();
ci2.SetGroup(ci2_group);
ci2.SetTitle(ci2_title);
ci2.SetUser(ci2_user);
ci2.SetPassword(ci->GetPassword());
ci2.SetURL(ci->GetURL());
ci2.SetAutoType(ci->GetAutoType());
ci2.SetNotes(ci->GetNotes());
time_t t;
ci->GetCTime(t);
if ((long) t != 0)
ci2.SetCTime(t);
ci->GetATime(t);
if ((long) t != 0)
ci2.SetATime(t);
ci->GetLTime(t);
if ((long) t != 0)
ci2.SetLTime(t);
ci->GetPMTime(t);
if ((long) t != 0)
ci2.SetPMTime(t);
ci->GetRMTime(t);
if ((long) t != 0)
ci2.SetRMTime(t);
CMyString tmp = ci->GetPWHistory();
if (tmp.GetLength() >= 5)
ci2.SetPWHistory(tmp);
uuid_array_t base_uuid, original_alias_uuid, new_alias_uuid;
if (ci->IsAlias()) {
ci->GetUUID(original_alias_uuid);
m_core.GetBaseUUID(original_alias_uuid, base_uuid);
ci2.SetAlias();
ci2.GetUUID(new_alias_uuid);
m_core.AddAliasEntry(base_uuid, new_alias_uuid);
ItemListIter iter;
iter = m_core.Find(base_uuid);
if (iter != m_core.GetEntryEndIter()) {
CMyString cs_tmp;
cs_tmp = _T("[") +
iter->second.GetGroup() + _T(":") +
iter->second.GetTitle() + _T(":") +
iter->second.GetUser() + _T("]");
ci2.SetPassword(cs_tmp);
}
}
// Add it to the end of the list
m_core.AddEntry(ci2);
di->list_index = -1; // so that insertItem will set new values
uuid_array_t uuid;
ci2.GetUUID(uuid);
insertItem(m_core.GetEntry(m_core.Find(uuid)));
FixListIndexes();
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
}
int rc = SelectEntry(di->list_index);
if (rc == LB_ERR) {
SelectEntry(m_ctlItemList.GetItemCount() - 1);
}
ChangeOkUpdate();
m_RUEList.AddRUEntry(uuid);
}
}
void
DboxMain::OnCopyPassword()
{
if (!SelItemOk())
return;
//Remind the user about clipboard security
CClearQuestionDlg clearDlg(this);
if (clearDlg.m_dontaskquestion == FALSE &&
clearDlg.DoModal() == IDCANCEL)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
uuid_array_t base_uuid, alias_uuid;
if (ci->IsAlias()) {
// This is an alias
ci->GetUUID(alias_uuid);
m_core.GetBaseUUID(alias_uuid, base_uuid);
ItemListIter iter = m_core.Find(base_uuid);
if (iter != End()) {
SetClipboardData(iter->second.GetPassword());
}
} else
SetClipboardData(ci->GetPassword());
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
void
DboxMain::OnCopyUsername()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString username = ci->GetUser();
if (!username.IsEmpty()) {
SetClipboardData(username);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnCopyNotes()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString notes = ci->GetNotes();
const CMyString url = ci->GetURL();
const CMyString autotype = ci->GetAutoType();
CMyString clipboard_data;
CString cs_text;
clipboard_data = notes;
if (!url.IsEmpty()) {
cs_text.LoadString(IDS_COPYURL);
clipboard_data += CMyString(cs_text);
clipboard_data += url;
}
if (!autotype.IsEmpty()) {
cs_text.LoadString(IDS_COPYAUTOTYPE);
clipboard_data += CMyString(cs_text);
clipboard_data += autotype;
}
if (!clipboard_data.IsEmpty()) {
SetClipboardData(clipboard_data);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnCopyURL()
{
if (SelItemOk() != TRUE)
return;
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
const CMyString cs_URL = ci->GetURL();
if (!cs_URL.IsEmpty()) {
SetClipboardData(cs_URL);
UpdateAccessTime(ci);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
}
}
void
DboxMain::OnFind()
{
// Note that this "toggles" the Find Tool Bar so that the user can use Ctrl+F
// to show it and then hide it.
SetFindToolBar(!m_FindToolBar.IsVisible());
}
void
DboxMain::OnClearClipboard()
{
ClearClipboardData();
}
void
DboxMain::OnAutoType()
{
if (SelItemOk() == TRUE) {
CItemData *ci = getSelectedItem();
ASSERT(ci != NULL);
uuid_array_t RUEuuid;
ci->GetUUID(RUEuuid);
m_RUEList.AddRUEntry(RUEuuid);
UpdateAccessTime(ci);
// All code using ci must be before this AutoType since the
// latter may trash *ci if lock-on-minimize
AutoType(*ci);
}
}
const CString DboxMain::DEFAULT_AUTOTYPE = _T("\\u\\t\\p\\n");
void
DboxMain::AutoType(const CItemData &ci)
{
CMyString AutoCmd = ci.GetAutoType();
const CMyString user(ci.GetUser());
CMyString pwd;
uuid_array_t base_uuid, alias_uuid;
if (ci.IsAlias()) {
// This is an alias
ci.GetUUID(alias_uuid);
m_core.GetBaseUUID(alias_uuid, base_uuid);
ItemListIter iter = m_core.Find(base_uuid);
if (iter != End()) {
pwd = iter->second.GetPassword();
}
} else {
pwd = ci.GetPassword();
}
// If empty, try the database default
if (AutoCmd.IsEmpty()) {
AutoCmd = PWSprefs::GetInstance()->
GetPref(PWSprefs::DefaultAutotypeString);
// If still empty, take this default
if (AutoCmd.IsEmpty()) {
// checking for user and password for default settings
if (!pwd.IsEmpty()){
if (!user.IsEmpty())
AutoCmd = CMyString(DEFAULT_AUTOTYPE);
else
AutoCmd = _T("\\p\\n");
}
}
}
CKeySend ks;
// Turn off CAPSLOCK
bool bCapsLock = false;
if (GetKeyState(VK_CAPITAL)) {
bCapsLock = true;
ks.SetCapsLock(false);
}
CMyString tmp;
TCHAR curChar;
const int N = AutoCmd.GetLength();
ks.ResetKeyboardState();
::BlockInput(true);
// Note that minimizing the window before calling ci.Get*()
// will cause garbage to be read if "lock on minimize" selected,
// since that will clear the data [Bugs item #1026630]
// (this is why we read user & pwd before actual use)
// Rules are ("Minimize on Autotype" takes precedence):
// 1. If "MinimizeOnAutotype" - minimize PWS during Autotype but do
// not restore it (previous default action - but a pain if locked
// in the system tray!)
// 2. If "Always on Top" - hide PWS during Autotype and then make it
// "AlwaysOnTop" again, unless minimized!
// 3. If not "Always on Top" - hide PWS during Autotype and show
// it again once finished - but behind other windows.
bool bMinOnAuto = PWSprefs::GetInstance()->
GetPref(PWSprefs::MinimizeOnAutotype) == TRUE;
if (bMinOnAuto)
ShowWindow(SW_MINIMIZE);
else
ShowWindow(SW_HIDE);
Sleep(1000); // Karl Student's suggestion, to ensure focus set correctly on minimize.
for(int n = 0; n < N; n++){
curChar = AutoCmd[n];
if(curChar == TCHAR('\\')) {
n++;
if(n < N)
curChar=AutoCmd[n];
switch(curChar){
case TCHAR('\\'):
tmp += TCHAR('\\');
break;
case TCHAR('n'):
case TCHAR('r'):
tmp += TCHAR('\r');
break;
case TCHAR('t'):
tmp += TCHAR('\t');
break;
case TCHAR('u'):
tmp += user;
break;
case TCHAR('p'):
tmp += pwd;
break;
case TCHAR('d'): {
// Delay is going to change - send what we have with old delay
ks.SendString(tmp);
// start collecting new delay
tmp = _T("");
int newdelay = 0;
int gNumIts = 0;
for(n++; n < N && (gNumIts < 3); ++gNumIts, n++)
if(isdigit(AutoCmd[n])){
newdelay *= 10;
newdelay += (AutoCmd[n] - TCHAR('0'));
} else
break; // for loop
n--;
ks.SetAndDelay(newdelay);
break; // case
}
default:
tmp += _T("\\") + curChar;
break;
}
} else
tmp += curChar;
}
ks.SendString(tmp);
// If we turned off CAPSLOCK, put it back
if (bCapsLock)
ks.SetCapsLock(true);
Sleep(100);
::BlockInput(false);
// If we hid it, now show it
if (bMinOnAuto)
return;
if (PWSprefs::GetInstance()->GetPref(PWSprefs::AlwaysOnTop)) {
SetWindowPos(&wndTopMost, 0, 0, 0, 0,
SWP_SHOWWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
} else {
SetWindowPos(&wndBottom, 0, 0, 0, 0,
SWP_SHOWWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
}
}
void
DboxMain::AddEntries(CDDObList &in_oblist, const CMyString &DropGroup)
{
CItemData tempitem;
UUIDList possible_aliases;
CMyString Group, Title, User;
POSITION pos;
TCHAR *dot;
for (pos = in_oblist.GetHeadPosition(); pos != NULL; in_oblist.GetNext(pos)) {
CDDObject *pDDObject = (CDDObject *)in_oblist.GetAt(pos);
tempitem.Clear();
pDDObject->ToItem(tempitem);
if (in_oblist.m_bDragNode) {
dot = (!DropGroup.IsEmpty() && !tempitem.GetGroup().IsEmpty()) ? _T(".") : _T("");
Group = DropGroup + dot + tempitem.GetGroup();
} else {
Group = DropGroup;
}
User = tempitem.GetUser();
Title = GetUniqueTitle(Group, tempitem.GetTitle(), User, IDS_DRAGNUMBER);
uuid_array_t entry_uuid;
tempitem.GetUUID(entry_uuid);
if (m_core.Find(entry_uuid) != End())
tempitem.CreateUUID();
tempitem.SetGroup(Group);
tempitem.SetTitle(Title);
uuid_array_t base_uuid, alias_uuid;
CMyString cs_tmp = tempitem.GetPassword();
CMyString csPwdGroup, csPwdTitle, csPwdUser;
bool bBase_was_Alias(false), bMultiple(false);
int ialias = m_core.GetBaseEntry(cs_tmp, base_uuid, bBase_was_Alias, bMultiple,
csPwdGroup, csPwdTitle, csPwdUser);
if (ialias > 0) {
// Password in alias format AND base entry exists
ItemListIter iter = m_core.Find(base_uuid);
ASSERT(iter != End());
if (bBase_was_Alias) {
// This base is in fact an alias. GetBaseEntry already found 'proper base'
// So dropped entry will point to the 'proper base' and tell the user.
CString cs_msg;
cs_msg.Format(IDS_DDBASEISALIAS, Group, Title, User);
AfxMessageBox(cs_msg, MB_OK);
}
tempitem.GetUUID(alias_uuid);
m_core.AddAliasEntry(base_uuid, alias_uuid);
tempitem.SetPassword(CMyString(_T("[Alias]")));
tempitem.SetAlias();
} else
if (ialias == 0) {
// Password NOT in alias format
tempitem.SetNormal();
} else
if (ialias < 0) {
// Password in alias format AND base entry does not exist or multiple possible
// base entries exit.
// Note: As more entries are added, what was "not exist" may become "no unique exists"
// or "multiple exist". Let the code that processes the possible aliases after all
// have been added sort this out.
tempitem.GetUUID(alias_uuid);
possible_aliases.push_back(alias_uuid);
}
AddEntry(tempitem);
} // iteration over in_oblist
// Now try to add aliases we couldn't add in previous processing
m_core.AddAliasesViaPassword(possible_aliases, NULL);
if (PWSprefs::GetInstance()->
GetPref(PWSprefs::SaveImmediately)) {
Save();
ChangeOkUpdate();
}
FixListIndexes();
RefreshList();
}
// Return whether first [g:t:u] is greater than the second [g:t:u]
// used in std::sort in SortAliasEntries below.
bool GTUCompare(CMyString elem1, CMyString elem2)
{
CMyString g1, t1, u1, g2, t2, u2, tmp1, tmp2;
g1 = elem1.SpanExcluding(_T(":"));
g2 = elem2.SpanExcluding(_T(":"));
if (g1 != g2)
return g1.Compare(g2) < 0;
tmp1 = elem1.Mid(g1.GetLength() + 1);
tmp2 = elem2.Mid(g2.GetLength() + 1);
t1 = tmp1.SpanExcluding(_T(":"));
t2 = tmp2.SpanExcluding(_T(":"));
if (t1 != t2)
return t1.Compare(t2) < 0;
tmp1 = tmp1.Mid(t1.GetLength() + 1);
tmp2 = tmp2.Mid(t2.GetLength() + 1);
u1 = tmp1.SpanExcluding(_T(":"));
u2 = tmp2.SpanExcluding(_T(":"));
return u1.Compare(u2) < 0;
}
void DboxMain::SortAliasEntries(UUIDList &aliaslist, CMyString &csAliases)
{
std::vector<CMyString> sorted_aliases;
std::vector<CMyString>::iterator sa_iter;
ItemListIter iter;
UUIDListIter aiter;
CMyString cs_alias;
for (aiter = aliaslist.begin(); aiter != aliaslist.end(); aiter++) {
uuid_array_t alias_uuid;
aiter->GetUUID(alias_uuid);
iter = m_core.Find(alias_uuid);
if (iter != m_core.GetEntryEndIter()) {
cs_alias = iter->second.GetGroup() + _T(":") +
iter->second.GetTitle() + _T(":") +
iter->second.GetUser();
sorted_aliases.push_back(cs_alias);
}
}
std::sort(sorted_aliases.begin(), sorted_aliases.end(), GTUCompare);
csAliases.Empty();
for (sa_iter = sorted_aliases.begin(); sa_iter != sorted_aliases.end(); sa_iter++) {
csAliases += _T("\t[") + *sa_iter + _T("]\r\n");
}
}
LRESULT
DboxMain::OnToolBarFindMessage(WPARAM /* wParam */, LPARAM /* lParam */)
{
// Called when user types into the Find search edit control on the Find Toolbar
// and presses enter.
OnToolBarFind();
return 0L;
}
void DboxMain::OnToolBarFind()
{
// Called when the user presses the Find button on the Find Toolbar
m_FindToolBar.Find();
}
bool
DboxMain::CheckNewPassword(const CMyString &group, const CMyString &title,
const CMyString &user, const CMyString &password,
const bool bIsEdit, uuid_array_t &base_uuid, int &ibasedata)
{
// Called from Add and Edit dialog
CMyString csPwdGroup, csPwdTitle, csPwdUser;
bool bBase_was_Alias(false), bMultiple(false);
ibasedata = m_core.GetBaseEntry(password, base_uuid, bBase_was_Alias, bMultiple,
csPwdGroup, csPwdTitle, csPwdUser);
if (bIsEdit && (csPwdGroup == group && csPwdTitle == title && csPwdUser == user)) {
// In Edit, check user isn't changing entry to point to itself (circular/self reference)
// Can't happen during Add as already checked entry does not exist so if accepted the
// password would be treated as an unusal "normal" password
AfxMessageBox(IDS_ALIASCANTREFERTOITSELF);
return false;
}
// ibasedata:
// +n: password contains (n-1) colons and base entry found (n = 1, 2 or 3)
// 0: password not in alias format
// -n: password contains (n-1) colons but base entry NOT found (n = 1, 2 or 3)
// "bBase_was_Alias" is set if the user specified a base entry that is an alias. The real base is returned
// "bMultiple" is set if no "unique" base entry could be found and is only valid if n = -1 or -2.
if (ibasedata < 0) {
CString cs_msg;
const CString cs_msgA(MAKEINTRESOURCE(IDS_ALIASNOTFOUNDA));
const CString cs_msgZ(MAKEINTRESOURCE(IDS_ALIASNOTFOUNDZ));
int rc(IDNO);
switch (ibasedata) {
case -1: // [x]
if (bMultiple)
cs_msg.Format(IDS_ALIASNOTFOUND0A, csPwdTitle); // multiple entries exist with title=x
else
cs_msg.Format(IDS_ALIASNOTFOUND0B, csPwdTitle); // no entry exists with title=x
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
break;
case -2: // [g,t], [t:u]
// In this case the 2 fields from the password are in Group & Title
if (bMultiple)
cs_msg.Format(IDS_ALIASNOTFOUND1A, csPwdGroup, csPwdTitle, csPwdGroup, csPwdTitle);
else
cs_msg.Format(IDS_ALIASNOTFOUND1B, csPwdGroup, csPwdTitle, csPwdGroup, csPwdTitle);
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
break;
case -3: // [x:y:z], [x:y:], [:y:z], [:y:] (title cannot be empty)
{
const bool bGE = csPwdGroup.IsEmpty() == TRUE;
const bool bTE = csPwdTitle.IsEmpty() == TRUE;
const bool bUE = csPwdUser.IsEmpty() == TRUE;
if (bTE) {
// Title is mandatory for all entries!
AfxMessageBox(IDS_BASEHASNOTITLE, MB_OK);
rc = IDNO;
break;
} else if (!bGE && !bUE) // [x:y:z]
cs_msg.Format(IDS_ALIASNOTFOUND2A, csPwdGroup, csPwdTitle, csPwdUser);
else if (!bGE && bUE) // [x:y:]
cs_msg.Format(IDS_ALIASNOTFOUND2B, csPwdGroup, csPwdTitle);
else if (bGE && !bUE) // [:y:z]
cs_msg.Format(IDS_ALIASNOTFOUND2C, csPwdTitle, csPwdUser);
else if (bGE && bUE) // [:y:]
cs_msg.Format(IDS_ALIASNOTFOUND0B, csPwdTitle);
rc = AfxMessageBox(cs_msgA + cs_msg + cs_msgZ, MB_YESNO | MB_DEFBUTTON2);
}
break;
default:
// Never happens
ASSERT(0);
}
if (rc == IDNO) {
return false;
}
}
if (ibasedata > 0 && bBase_was_Alias) {
CString cs_msg;
cs_msg.Format(IDS_BASEISALIAS, csPwdGroup, csPwdTitle, csPwdUser);
if (AfxMessageBox(cs_msg, MB_YESNO | MB_DEFBUTTON2) == IDNO) {
return false;
}
}
// All OK
return true;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
namespace
{
enum TableColum
{
COL_ENABLED,
COL_PATH,
COL_EXISTS
};
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_reader(HKEY_CURRENT_USER)
, m_config("QtPathEditor")
{
ui->setupUi(this);
getPaths();
const QIcon tick(":/icons/tick.png");
const QIcon cross(":/icons/cross.png");
ui->tableWidget->setRowCount(m_paths.size());
int itemIdxInTable = 0;
/// \todo use the indexes
for (int i = 0; i < m_paths.size(); ++i)
{
const QString & pathQt = m_paths[i];
QTableWidgetItem *itemEn = new QTableWidgetItem(); // enabled
QTableWidgetItem *itemPath = new QTableWidgetItem(pathQt);
QTableWidgetItem *itemEx = new QTableWidgetItem(); // exist
itemEn->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
itemEx->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
itemEn->setCheckState(m_statuses[i] ? Qt::Checked : Qt::Unchecked);
itemEn->setTextAlignment(Qt::AlignHCenter);
itemEx->setIcon(QFile::exists(pathQt) ? tick : cross);
ui->tableWidget->setItem(itemIdxInTable, COL_ENABLED, itemEn);
ui->tableWidget->setItem(itemIdxInTable, COL_PATH, itemPath);
ui->tableWidget->setItem(itemIdxInTable++, COL_EXISTS, itemEx);
}
setupVisualAspect();
makeConnections();
}
MainWindow::~MainWindow()
{
on_buttonSave_clicked();
delete ui;
}
void MainWindow::getPaths()
{
StringListT listFromRegistry;
m_reader.Read(listFromRegistry);
// Read from the registry (all must be enabled)
for (int i = 0; i < static_cast<int>(listFromRegistry.size()); ++i)
{
m_paths << QString::fromWCharArray(listFromRegistry[i].c_str());
m_statuses << true;
m_indexes << i;
}
// Read from the config file (it can override the status of the previous paths)
const QStringList paths = m_config.getPaths();
const QBitArray statuses = m_config.getStatus();
Q_ASSERT (paths.size() == statuses.size());
for (int i = 0; i < paths.size(); ++i)
{
const int idx = m_paths.indexOf(paths[i]);
if (idx != -1) // Already in the list -> update the status
{
m_statuses[i] = statuses[i];
}
else
{
m_paths << m_paths[i];
m_statuses << statuses[i];
m_indexes << (m_paths.size() - 1);
}
}
}
void MainWindow::on_buttonSave_clicked()
{
saveConfigFile();
saveRegistry();
}
void MainWindow::itemPressed(QTableWidgetItem *item)
{
switch (item->column())
{
case COL_ENABLED :
{
const int idx = m_indexes[item->row()];
const bool checked = item->checkState() == Qt::Checked;
m_statuses[idx] = checked;
qDebug() << "Path changed its status to: " << checked;
break;
}
default:
{
qDebug() << "itemPressed. Action not implemented with colum: " << item->column();
}
}
}
void MainWindow::saveRegistry()
{
StringListT listToRegistry;
for (int i = 0; i < m_paths.size(); ++i)
{
const int idx = m_indexes[i];
if (m_statuses[idx])
{
listToRegistry.push_back(m_paths[idx].toStdWString());
}
}
m_reader.Write(listToRegistry);
}
void MainWindow::saveConfigFile()
{
m_config.setPaths(m_paths);
m_config.setOrder(m_indexes);
QBitArray array (m_statuses.size());
for (int i = 0; i < m_statuses.size(); ++i)
{
array.setBit(i, m_statuses[i]);
}
m_config.setStatus(array);
}
void MainWindow::on_buttonBrowse_clicked()
{
const int idx = m_indexes[ui->tableWidget->currentRow()];
if (m_statuses[idx])
{
QDesktopServices::openUrl(m_paths[idx]);
}
else
{
qDebug() << "Non existing path will be not opened";
}
}
void MainWindow::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
qDebug() << "Section moved: " << logicalIndex << oldVisualIndex << newVisualIndex;
}
void MainWindow::setupVisualAspect()
{
ui->tableWidget->verticalHeader()->setMovable(true);
ui->tableWidget->verticalHeader()->setDragEnabled(true);
ui->tableWidget->verticalHeader()->setDragDropMode(QAbstractItemView::InternalMove);
ui->tableWidget->setColumnWidth(COL_ENABLED, 50);
ui->tableWidget->resizeColumnToContents(COL_PATH);
ui->tableWidget->setColumnWidth(COL_EXISTS, 50);
}
void MainWindow::makeConnections()
{
connect(ui->tableWidget, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(itemPressed(QTableWidgetItem *)));
connect(ui->tableWidget->verticalHeader(), SIGNAL(sectionMoved(int,int,int)),
this, SLOT(sectionMoved(int,int,int)));
}
void MainWindow::on_buttonAddPath_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Select path to add"),
QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
/// \todo check if the path exists?
const QIcon tick(":/icons/tick.png");
m_paths << dir;
m_statuses << true;
m_indexes << (m_paths.size() - 1);
const int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
QTableWidgetItem *itemEn = new QTableWidgetItem(); // enabled
QTableWidgetItem *itemPath = new QTableWidgetItem(dir);
QTableWidgetItem *itemEx = new QTableWidgetItem(); // exist
itemEn->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
itemEx->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
itemEn->setCheckState(Qt::Checked);
itemEn->setTextAlignment(Qt::AlignHCenter);
itemEx->setIcon(tick);
ui->tableWidget->setItem(row, COL_ENABLED, itemEn);
ui->tableWidget->setItem(row, COL_PATH, itemPath);
ui->tableWidget->setItem(row, COL_EXISTS, itemEx);
}
}
void MainWindow::on_buttonDeletePath_clicked()
{
}
Implement the delete function
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
namespace
{
enum TableColum
{
COL_ENABLED,
COL_PATH,
COL_EXISTS
};
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_reader(HKEY_CURRENT_USER)
, m_config("QtPathEditor")
{
ui->setupUi(this);
getPaths();
const QIcon tick(":/icons/tick.png");
const QIcon cross(":/icons/cross.png");
ui->tableWidget->setRowCount(m_paths.size());
int itemIdxInTable = 0;
/// \todo use the indexes
for (int i = 0; i < m_paths.size(); ++i)
{
const QString & pathQt = m_paths[i];
QTableWidgetItem *itemEn = new QTableWidgetItem(); // enabled
QTableWidgetItem *itemPath = new QTableWidgetItem(pathQt);
QTableWidgetItem *itemEx = new QTableWidgetItem(); // exist
itemEn->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
itemEx->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
itemEn->setCheckState(m_statuses[i] ? Qt::Checked : Qt::Unchecked);
itemEn->setTextAlignment(Qt::AlignHCenter);
itemEx->setIcon(QFile::exists(pathQt) ? tick : cross);
ui->tableWidget->setItem(itemIdxInTable, COL_ENABLED, itemEn);
ui->tableWidget->setItem(itemIdxInTable, COL_PATH, itemPath);
ui->tableWidget->setItem(itemIdxInTable++, COL_EXISTS, itemEx);
}
setupVisualAspect();
makeConnections();
}
MainWindow::~MainWindow()
{
on_buttonSave_clicked();
delete ui;
}
void MainWindow::getPaths()
{
StringListT listFromRegistry;
m_reader.Read(listFromRegistry);
// Read from the registry (all must be enabled)
for (int i = 0; i < static_cast<int>(listFromRegistry.size()); ++i)
{
m_paths << QString::fromWCharArray(listFromRegistry[i].c_str());
m_statuses << true;
m_indexes << i;
}
// Read from the config file (it can override the status of the previous paths)
const QStringList paths = m_config.getPaths();
const QBitArray statuses = m_config.getStatus();
Q_ASSERT (paths.size() == statuses.size());
for (int i = 0; i < paths.size(); ++i)
{
const int idx = m_paths.indexOf(paths[i]);
if (idx != -1) // Already in the list -> update the status
{
m_statuses[i] = statuses[i];
}
else
{
m_paths << m_paths[i];
m_statuses << statuses[i];
m_indexes << (m_paths.size() - 1);
}
}
}
void MainWindow::on_buttonSave_clicked()
{
saveConfigFile();
saveRegistry();
}
void MainWindow::itemPressed(QTableWidgetItem *item)
{
switch (item->column())
{
case COL_ENABLED :
{
const int idx = m_indexes[item->row()];
const bool checked = item->checkState() == Qt::Checked;
m_statuses[idx] = checked;
qDebug() << "Path changed its status to: " << checked;
break;
}
default:
{
qDebug() << "itemPressed. Action not implemented with colum: " << item->column();
}
}
}
void MainWindow::saveRegistry()
{
StringListT listToRegistry;
for (int i = 0; i < m_paths.size(); ++i)
{
const int idx = m_indexes[i];
if (m_statuses[idx])
{
listToRegistry.push_back(m_paths[idx].toStdWString());
}
}
m_reader.Write(listToRegistry);
}
void MainWindow::saveConfigFile()
{
m_config.setPaths(m_paths);
m_config.setOrder(m_indexes);
QBitArray array (m_statuses.size());
for (int i = 0; i < m_statuses.size(); ++i)
{
array.setBit(i, m_statuses[i]);
}
m_config.setStatus(array);
}
void MainWindow::on_buttonBrowse_clicked()
{
const int idx = m_indexes[ui->tableWidget->currentRow()];
if (m_statuses[idx])
{
QDesktopServices::openUrl(m_paths[idx]);
}
else
{
qDebug() << "Non existing path will be not opened";
}
}
void MainWindow::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
qDebug() << "Section moved: " << logicalIndex << oldVisualIndex << newVisualIndex;
}
void MainWindow::setupVisualAspect()
{
ui->tableWidget->verticalHeader()->setMovable(true);
ui->tableWidget->verticalHeader()->setDragEnabled(true);
ui->tableWidget->verticalHeader()->setDragDropMode(QAbstractItemView::InternalMove);
ui->tableWidget->setColumnWidth(COL_ENABLED, 50);
ui->tableWidget->resizeColumnToContents(COL_PATH);
ui->tableWidget->setColumnWidth(COL_EXISTS, 50);
}
void MainWindow::makeConnections()
{
connect(ui->tableWidget, SIGNAL(itemChanged(QTableWidgetItem *)),
this, SLOT(itemPressed(QTableWidgetItem *)));
connect(ui->tableWidget->verticalHeader(), SIGNAL(sectionMoved(int,int,int)),
this, SLOT(sectionMoved(int,int,int)));
}
void MainWindow::on_buttonAddPath_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Select path to add"),
QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
/// \todo check if the path exists?
const QIcon tick(":/icons/tick.png");
m_paths << dir;
m_statuses << true;
m_indexes << (m_paths.size() - 1);
const int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
QTableWidgetItem *itemEn = new QTableWidgetItem(); // enabled
QTableWidgetItem *itemPath = new QTableWidgetItem(dir);
QTableWidgetItem *itemEx = new QTableWidgetItem(); // exist
itemEn->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
itemEx->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
itemEn->setCheckState(Qt::Checked);
itemEn->setTextAlignment(Qt::AlignHCenter);
itemEx->setIcon(tick);
ui->tableWidget->setItem(row, COL_ENABLED, itemEn);
ui->tableWidget->setItem(row, COL_PATH, itemPath);
ui->tableWidget->setItem(row, COL_EXISTS, itemEx);
}
}
void MainWindow::on_buttonDeletePath_clicked()
{
const int dataIndex = m_indexes[ui->tableWidget->currentRow()];
m_paths.erase(m_paths.begin() + m_indexes[dataIndex]);
m_statuses.erase(m_statuses.begin() + m_indexes[dataIndex]);
m_indexes.erase(m_indexes.begin() + dataIndex);
ui->tableWidget->removeRow(ui->tableWidget->currentRow());
}
|
/*!
* Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* Copyright (C) 2014 Nomovok Ltd. All rights reserved.
* Contact: info@nomovok.com
*
* This file may be used under the terms of the GNU Lesser
* General Public License version 2.1 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 2.1 requirements
* will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
*
* In addition, as a special exception, Digia and other copyright holders
* give you certain additional rights. These rights are described in
* the Digia Qt LGPL Exception version 1.1, included in the file
* LGPL_EXCEPTION.txt in this package.
*/
#include <QQmlEngine>
#include <QDir>
#include <private/qv4engine_p.h>
#include <private/qqmltypeloader_p.h>
#include <private/qqmltypecompiler_p.h>
#include <private/qqmlimport_p.h>
#include <private/qqmlvmemetaobject_p.h>
#include "qmctypeunit.h"
#include "qmcunit.h"
#include "qmcunitpropertycachecreator.h"
#include "qmcloader.h"
#include "qmcscriptunit.h"
#include "qmctypeunitcomponentandaliasresolver.h"
QmcTypeUnit::QmcTypeUnit(QmcUnit *qmcUnit, QQmlTypeLoader *typeLoader)
: Blob(qmcUnit->loadedUrl, QQmlDataBlob::QmlFile, typeLoader),
unit(qmcUnit),
compiledData(new QQmlCompiledData(qmcUnit->engine)),
linked(false),
vmeMetaObjects(compiledData->metaObjects),
propertyCaches(compiledData->propertyCaches),
doneLinking(false)
{
compiledData->url = qmcUnit->loadedUrl;
}
QmcTypeUnit::~QmcTypeUnit()
{
foreach (const QQmlTypeData::ScriptReference &ref, scripts) {
ref.script->release();
}
scripts.clear();
foreach (QmcUnit *unit, dependencies) {
unit->blob->release();
}
compiledData->release();
delete unit;
}
QmcUnit *QmcTypeUnit::qmcUnit()
{
return unit;
}
void QmcTypeUnit::initializeFromCachedUnit(const QQmlPrivate::CachedQmlUnit *)
{
}
void QmcTypeUnit::dataReceived(const Data &)
{
}
void QmcTypeUnit::done()
{
}
QString QmcTypeUnit::stringAt(int idx) const
{
return unit->stringAt(idx);
}
bool QmcTypeUnit::link()
{
if (linked)
return true;
linked = true;
// create QV4::CompiledData::CompilationUnit and QQmlCompiledData
compiledData->compilationUnit = unit->compilationUnit;
compiledData->compilationUnit->ref();
compiledData->qmlUnit = unit->qmlUnit;
compiledData->name = unit->name;
setStatus(Complete);
// create imports
if (!addImports())
return false;
// resolve dependencies (TBD: recursively)
if (!initDependencies())
return false;
if (!initQml())
return false;
return true;
}
bool QmcTypeUnit::addImports()
{
QList<QString> fileImports;
if(unit->loadedUrl.toString().startsWith("file:///")){
// full, path this must be a plugin we are adding
m_importCache.setBaseUrl(QUrl(unit->loadedUrl), unit->loadedUrl.toString());
}else if (unit->url.toLocalFile().startsWith(":/") || unit->urlString.startsWith("qrc:/")){
m_importCache.setBaseUrl(unit->url, unit->urlString);
}else{
QDir dd;
QString newUrl = "file://" + dd.absolutePath() + "/" + unit->loadedUrl.toLocalFile();
m_importCache.setBaseUrl(QUrl(newUrl), newUrl);
}
compiledData->customParserData = qmcUnit()->customParsers;
compiledData->customParserBindings = qmcUnit()->customParserBindings;
compiledData->deferredBindingsPerObject = qmcUnit()->deferredBindings;
// qqmltypeloader.cpp:2271
// ->addImport qqmltypeloader.cpp:1311
for (uint i = 0; i < compiledData->qmlUnit->nImports; i++) {
const QV4::CompiledData::Import *p = compiledData->qmlUnit->importAt(i);
if (p->type == QV4::CompiledData::Import::ImportScript) {
// load it if it does not exist yet
QmcScriptUnit* scriptUnit = unit->loader->getScript(stringAt(p->uriIndex), unit->loadedUrl);
if (!scriptUnit) {
QQmlError error;
error.setColumn(p->location.column);
error.setLine(p->location.line);
error.setUrl(finalUrl());
error.setDescription("Could not find imported script");
return false;
}
QQmlTypeData::ScriptReference ref;
ref.location = p->location;
ref.qualifier = stringAt(p->qualifierIndex);
ref.script = scriptUnit;
scripts.append(ref);
} else if (p->type == QV4::CompiledData::Import::ImportLibrary) {
QString qmldirFilePath;
QString qmldirUrl;
const QString &importUri = stringAt(p->uriIndex);
const QString &importQualifier = stringAt(p->qualifierIndex);
if (QQmlMetaType::isLockedModule(importUri, p->majorVersion)) {
if (!addImport(p, &unit->errors))
return false;
} else if (m_importCache.locateQmldir(typeLoader()->importDatabase(), importUri, p->majorVersion, p->minorVersion,
&qmldirFilePath, &qmldirUrl)) {
if(QFile::exists(qmldirFilePath + "_loader")){
qmldirFilePath += "_loader";
qDebug() << "Using qmldir_loader file" << qmldirFilePath;
}
// This is a local library import
if (!m_importCache.addLibraryImport(typeLoader()->importDatabase(), importUri, importQualifier, p->majorVersion,
p->minorVersion, qmldirFilePath, qmldirUrl, false, &unit->errors)){
return false;
}
if (!importQualifier.isEmpty()) {
// Does this library contain any qualified scripts?
QUrl libraryUrl(qmldirUrl);
const QQmlTypeLoader::QmldirContent *qmldir = typeLoader()->qmldirContent(qmldirFilePath, qmldirUrl);
foreach (const QQmlDirParser::Script &script, qmldir->scripts()) {
QUrl scriptUrl = libraryUrl.resolved(QUrl(script.fileName));
QQmlScriptBlob *blob = typeLoader()->getScript(scriptUrl);
addDependency(blob);
scriptImported(blob, p->location, script.nameSpace, importQualifier);
}
}
} else {
if (!addImport(p, &unit->errors))
return false;
}
} else if (p->type == QV4::CompiledData::Import::ImportFile) {
// load file import
// qqmltypeloader.cpp:1384
const QString &importUri = stringAt(p->uriIndex);
const QString &importQualifier = stringAt(p->qualifierIndex);
QUrl qmldirUrl;
if (importQualifier.isEmpty()) {
qmldirUrl = finalUrl().resolved(QUrl(importUri + QLatin1String("/qmldir")));
if (!QQmlImports::isLocal(qmldirUrl)) {
// This is a remote file; the import is currently incomplete
QQmlError error;
error.setDescription("Remote dependencies not supported");
error.setUrl(qmldirUrl);
unit->errors.append(error);
return false;
}
}
if (!m_importCache.addFileImport(typeLoader()->importDatabase(), importUri, importQualifier, p->majorVersion,
p->minorVersion, false, &unit->errors))
return false;
fileImports.append(importUri);
} else {
QQmlError error;
error.setDescription("Unknown type import");
error.setColumn(p->location.column);
error.setLine(p->location.line);
error.setUrl(finalUrl());
unit->errors.append(error);
return false;
}
}
// resolve types
// type data creation
// qqmlirbuilder.cpp:285 create QV4::CompiledData::TypeReference = location
// qqmltypeloader.cpp:2402 QV4::CompiledData::TypeReference -> QQmlTypeData::TypeReference
// qqmltypecompiler.cpp:86 QQmlTypeData::TypeReference -> QQmlCompiledData::TypeReference
foreach (const QmcUnitTypeReference& typeRef, unit->typeReferences) {
int majorVersion = -1;
int minorVersion = -1;
QQmlImportNamespace *typeNamespace = 0;
if ((int)typeRef.index >= unit->strings.size())
return false;
const QString name = stringAt(typeRef.index);
if (typeRef.syntheticComponent)
continue;
QQmlCompiledData::TypeReference *ref = new QQmlCompiledData::TypeReference;
QQmlType *qmlType = NULL;
if (!m_importCache.resolveType(name, &qmlType, &majorVersion, &minorVersion, &typeNamespace, &unit->errors)) {
bool found = false;
// try to load it as implicit
QmcUnit *typeUnit = qmcUnit()->loader->getType(name, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
unit->errors.clear();
dependencies.append(typeUnit);
found = true;
}
if(!found){
// local file imports
foreach (const QString &path, fileImports){
QmcUnit *typeUnit = qmcUnit()->loader->getType(path + "/" + name, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
unit->errors.clear();
dependencies.append(typeUnit);
found = true;
break;
}
}
}
if(!found){
QQmlError error;
error.setDescription("Could not load implicit import");
unit->errors.append(error);
delete ref;
return false;
}
}
// component creation, see qqmltypecompiler.cpp:87
// and qqmltypeloader.cpp:2456
if (typeRef.composite && !ref->component) {
// extract name of the source url
Q_ASSERT(qmlType);
QString sourceName;
if (!sourceNameForUrl(qmlType->sourceUrl(), sourceName)) {
delete ref;
return false;
}
int lastDot = sourceName.lastIndexOf('.');
if (lastDot != -1)
sourceName = sourceName.left(lastDot);
QmcUnit *typeUnit = qmcUnit()->loader->getType(sourceName, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
dependencies.append(typeUnit);
} else {
QQmlError error;
error.setDescription("Could not load implicit import");
unit->errors.append(error);
delete ref;
return false;
}
} else if (qmlType) {
ref->type = qmlType;
if (ref->type->containsRevisionedAttributes()) {
// qqmltypecompiler.cpp:102
QQmlError cacheError;
ref->typePropertyCache = QQmlEnginePrivate::get(unit->engine)->cache(ref->type, minorVersion, cacheError);
if (!ref->typePropertyCache) {
delete ref;
unit->errors.append(cacheError);
return false;
}
ref->typePropertyCache->addref();
}
}
// TBD: qqmltypecompiler.cpp:86
ref->majorVersion = majorVersion;
ref->minorVersion = minorVersion;
// dynamic type check moved to init phase
compiledData->resolvedTypes.insert(typeRef.index, ref);
}
// from QQmlTypeCompiler::compile
compiledData->importCache = new QQmlTypeNameCache;
foreach (const QString &ns, unit->namespaces)
compiledData->importCache->add(ns);
#if 0
// Add any Composite Singletons that were used to the import cache
foreach (const QQmlTypeData::TypeReference &singleton, compositeSingletons)
compiledData->importCache->add(singleton.type->qmlTypeName(), singleton.type->sourceUrl(), singleton.prefix);
#endif
// TBD: is import cache required at all ? Cannot be null though.
m_importCache.populateCache(compiledData->importCache);
// qqmltypecompiler.cpp:1413
foreach (const QmcUnitTypeReference& typeRef, unit->typeReferences) {
static QQmlType *componentType = QQmlMetaType::qmlType(&QQmlComponent::staticMetaObject);
if (!typeRef.syntheticComponent)
continue;
QQmlCompiledData::TypeReference *ref = new QQmlCompiledData::TypeReference;
ref->type = componentType;
ref->majorVersion = componentType->majorVersion();
ref->minorVersion = componentType->minorVersion();
compiledData->resolvedTypes.insert(typeRef.index, ref);
}
// scripts resolved through file imports
// actual script loading is done in QQmlObjectCreator::create (qqmlobjectcreator.cpp:215)
foreach (const QQmlImports::ScriptReference &scriptRef, imports().resolvedScripts()) {
// script reference
QString locationName;
if (!sourceNameForUrl(scriptRef.location, locationName))
return false;
QmcScriptUnit *script = unit->loader->getScript(locationName, unit->loadedUrl);
if (!script) {
QQmlError error;
error.setDescription("Could not load script");
error.setUrl(scriptRef.location);
unit->errors.append(error);
return false;
}
//compiledData->scripts.append(script->scriptData());
QQmlTypeData::ScriptReference ref;
ref.script = script;
ref.qualifier = scriptRef.qualifier;
scripts.append(ref);
}
return true;
}
bool QmcTypeUnit::sourceNameForUrl(const QUrl &url, QString &name)
{
name = url.toString();
QString loadedBaseUrl = QmcLoader::getBaseUrl(unit->loadedUrl.toString());
if (name.startsWith("file://")) {
// keep name as is
} else if (name.startsWith(loadedBaseUrl)) {
if (name.size() > loadedBaseUrl.size())
name = name.mid(loadedBaseUrl.size());
else
name = "";
} else {
// use just name
qDebug() << "Reverting back to using just file name to resolve url, propably won't work";
int lastSlash = name.lastIndexOf('/');
if (lastSlash + 1 >= name.length()) {
QQmlError error;
error.setDescription("Illegal formatted url");
error.setUrl(url);
unit->errors.append(error);
return false;
} else if (lastSlash != -1)
name = name.mid(lastSlash + 1);
}
return true;
}
QQmlCompiledData *QmcTypeUnit::refCompiledData()
{
Q_ASSERT(compiledData);
compiledData->addref();
return compiledData;
}
bool QmcTypeUnit::initDependencies()
{
foreach (const QQmlTypeData::ScriptReference &scriptRef, scripts) {
QmcScriptUnit *script = (QmcScriptUnit *)scriptRef.script;
if (!script->initialize())
return false;
}
foreach (QmcUnit *unit, dependencies) {
if (unit->type == QMC_QML) {
QmcTypeUnit * blob = (QmcTypeUnit *)unit->blob;
if (!blob->link())
return false;
}
}
// TBD: initialize dependencies of script & types (recursion)
return true;
}
bool QmcTypeUnit::initQml()
{
// type references init
foreach (QQmlCompiledData::TypeReference *typeRef, compiledData->resolvedTypes) {
typeRef->doDynamicTypeCheck();
}
compiledData->initialize(unit->engine);
// create property caches
// qqmltypecompiler.cpp:143-150
QmcUnitPropertyCacheCreator cacheCreator(this);
if (!cacheCreator.buildMetaObjects())
return false;
// scripts
// qqmltypeloader.cpp:1315:
// create QQmlScriptBlob + QQmlScriptData
// add to QQmlTypeLoader::Blob->scripts
// qqmltypecompiler.cpp:180:
// add to import cache
// QQmlTypeData::ScriptReference->scriptData -> compiledData->scripts
foreach (const QQmlTypeData::ScriptReference &scriptRef, scripts) {
// create QQmlScriptData and link it to QmcScriptUnit
QQmlScriptData *scriptData = scriptRef.script->scriptData();
scriptData->addref();
compiledData->scripts.append(scriptData);
}
// add object mappings + aliases
// alias creation call chain
// QQmlTypeCompiler::compile
// ->QQmlComponentAndAliasResolver::resolve->resolveAliases
// -->QQmlPropertyCache::appendProperty
// TBD: add aliases to property cache
QmcTypeUnitComponentAndAliasResolver resolver(this);
if (!resolver.resolve())
return false;
// TBD: alias creation makes component composite type
if (compiledData->isCompositeType()) {
// TBD: does this work ?
QQmlEnginePrivate::get(unit->engine)->registerInternalCompositeType(compiledData);
//engine->registerInternalCompositeType(compiledData);
} else {
const QV4::CompiledData::Object *obj = compiledData->qmlUnit->objectAt(compiledData->qmlUnit->indexOfRootObject);
if (!obj)
return false;
QQmlCompiledData::TypeReference *typeRef = compiledData->resolvedTypes.value(obj->inheritedTypeNameIndex);
if (!typeRef)
return false;
if (typeRef->component) {
compiledData->metaTypeId = typeRef->component->metaTypeId;
compiledData->listMetaTypeId = typeRef->component->listMetaTypeId;
} else {
compiledData->metaTypeId = typeRef->type->typeId();
compiledData->listMetaTypeId = typeRef->type->qListTypeId();
}
}
// extra initiliazation of QQmlCompiledData qqmltypecompiler.cpp:263
#if 0
// TBD: function below seems to quite a lot
// Sanity check property bindings
QQmlPropertyValidator validator(this);
if (!validator.validate())
return false;
#endif
// add custom parsers, custom bindings and deferred bindings
// TBD:
// Collect some data for instantiation later.
int bindingCount = 0;
int parserStatusCount = 0;
int objectCount = 0;
for (quint32 i = 0; i < compiledData->qmlUnit->nObjects; ++i) {
const QV4::CompiledData::Object *obj = compiledData->qmlUnit->objectAt(i);
bindingCount += obj->nBindings;
if (QQmlCompiledData::TypeReference *typeRef = compiledData->resolvedTypes.value(obj->inheritedTypeNameIndex)) {
if (QQmlType *qmlType = typeRef->type) {
if (qmlType->parserStatusCast() != -1)
++parserStatusCount;
}
if (typeRef->component) {
bindingCount += typeRef->component->totalBindingsCount;
parserStatusCount += typeRef->component->totalParserStatusCount;
objectCount += typeRef->component->totalObjectCount;
} else
++objectCount;
}
}
compiledData->totalBindingsCount = bindingCount;
compiledData->totalParserStatusCount = parserStatusCount;
compiledData->totalObjectCount = objectCount;
if (compiledData->propertyCaches.count() != static_cast<int>(compiledData->qmlUnit->nObjects))
return false;
return true;
}
QQmlComponent* QmcTypeUnit::createComponent()
{
QQmlComponent* component = new QQmlComponent(unit->engine);
QQmlComponentPrivate* cPriv = QQmlComponentPrivate::get(component);
cPriv->cc = compiledData;
cPriv->cc->addref();
return component;
}
If importing a script fails, report the error in the linking.
/*!
* Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* Copyright (C) 2014 Nomovok Ltd. All rights reserved.
* Contact: info@nomovok.com
*
* This file may be used under the terms of the GNU Lesser
* General Public License version 2.1 as published by the Free Software
* Foundation and appearing in the file LICENSE.LGPL included in the
* packaging of this file. Please review the following information to
* ensure the GNU Lesser General Public License version 2.1 requirements
* will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
*
* In addition, as a special exception, Digia and other copyright holders
* give you certain additional rights. These rights are described in
* the Digia Qt LGPL Exception version 1.1, included in the file
* LGPL_EXCEPTION.txt in this package.
*/
#include <QQmlEngine>
#include <QDir>
#include <private/qv4engine_p.h>
#include <private/qqmltypeloader_p.h>
#include <private/qqmltypecompiler_p.h>
#include <private/qqmlimport_p.h>
#include <private/qqmlvmemetaobject_p.h>
#include "qmctypeunit.h"
#include "qmcunit.h"
#include "qmcunitpropertycachecreator.h"
#include "qmcloader.h"
#include "qmcscriptunit.h"
#include "qmctypeunitcomponentandaliasresolver.h"
QmcTypeUnit::QmcTypeUnit(QmcUnit *qmcUnit, QQmlTypeLoader *typeLoader)
: Blob(qmcUnit->loadedUrl, QQmlDataBlob::QmlFile, typeLoader),
unit(qmcUnit),
compiledData(new QQmlCompiledData(qmcUnit->engine)),
linked(false),
vmeMetaObjects(compiledData->metaObjects),
propertyCaches(compiledData->propertyCaches),
doneLinking(false)
{
compiledData->url = qmcUnit->loadedUrl;
}
QmcTypeUnit::~QmcTypeUnit()
{
foreach (const QQmlTypeData::ScriptReference &ref, scripts) {
ref.script->release();
}
scripts.clear();
foreach (QmcUnit *unit, dependencies) {
unit->blob->release();
}
compiledData->release();
delete unit;
}
QmcUnit *QmcTypeUnit::qmcUnit()
{
return unit;
}
void QmcTypeUnit::initializeFromCachedUnit(const QQmlPrivate::CachedQmlUnit *)
{
}
void QmcTypeUnit::dataReceived(const Data &)
{
}
void QmcTypeUnit::done()
{
}
QString QmcTypeUnit::stringAt(int idx) const
{
return unit->stringAt(idx);
}
bool QmcTypeUnit::link()
{
if (linked)
return true;
linked = true;
// create QV4::CompiledData::CompilationUnit and QQmlCompiledData
compiledData->compilationUnit = unit->compilationUnit;
compiledData->compilationUnit->ref();
compiledData->qmlUnit = unit->qmlUnit;
compiledData->name = unit->name;
setStatus(Complete);
// create imports
if (!addImports())
return false;
// resolve dependencies (TBD: recursively)
if (!initDependencies())
return false;
if (!initQml())
return false;
return true;
}
bool QmcTypeUnit::addImports()
{
QList<QString> fileImports;
if(unit->loadedUrl.toString().startsWith("file:///")){
// full, path this must be a plugin we are adding
m_importCache.setBaseUrl(QUrl(unit->loadedUrl), unit->loadedUrl.toString());
}else if (unit->url.toLocalFile().startsWith(":/") || unit->urlString.startsWith("qrc:/")){
m_importCache.setBaseUrl(unit->url, unit->urlString);
}else{
QDir dd;
QString newUrl = "file://" + dd.absolutePath() + "/" + unit->loadedUrl.toLocalFile();
m_importCache.setBaseUrl(QUrl(newUrl), newUrl);
}
compiledData->customParserData = qmcUnit()->customParsers;
compiledData->customParserBindings = qmcUnit()->customParserBindings;
compiledData->deferredBindingsPerObject = qmcUnit()->deferredBindings;
// qqmltypeloader.cpp:2271
// ->addImport qqmltypeloader.cpp:1311
for (uint i = 0; i < compiledData->qmlUnit->nImports; i++) {
const QV4::CompiledData::Import *p = compiledData->qmlUnit->importAt(i);
if (p->type == QV4::CompiledData::Import::ImportScript) {
// load it if it does not exist yet
QmcScriptUnit* scriptUnit = unit->loader->getScript(stringAt(p->uriIndex), unit->loadedUrl);
if (!scriptUnit) {
QQmlError error;
error.setColumn(p->location.column);
error.setLine(p->location.line);
error.setUrl(finalUrl());
error.setDescription("Could not find imported script");
unit->errors.append(error);
return false;
}
QQmlTypeData::ScriptReference ref;
ref.location = p->location;
ref.qualifier = stringAt(p->qualifierIndex);
ref.script = scriptUnit;
scripts.append(ref);
} else if (p->type == QV4::CompiledData::Import::ImportLibrary) {
QString qmldirFilePath;
QString qmldirUrl;
const QString &importUri = stringAt(p->uriIndex);
const QString &importQualifier = stringAt(p->qualifierIndex);
if (QQmlMetaType::isLockedModule(importUri, p->majorVersion)) {
if (!addImport(p, &unit->errors))
return false;
} else if (m_importCache.locateQmldir(typeLoader()->importDatabase(), importUri, p->majorVersion, p->minorVersion,
&qmldirFilePath, &qmldirUrl)) {
if(QFile::exists(qmldirFilePath + "_loader")){
qmldirFilePath += "_loader";
qDebug() << "Using qmldir_loader file" << qmldirFilePath;
}
// This is a local library import
if (!m_importCache.addLibraryImport(typeLoader()->importDatabase(), importUri, importQualifier, p->majorVersion,
p->minorVersion, qmldirFilePath, qmldirUrl, false, &unit->errors)){
return false;
}
if (!importQualifier.isEmpty()) {
// Does this library contain any qualified scripts?
QUrl libraryUrl(qmldirUrl);
const QQmlTypeLoader::QmldirContent *qmldir = typeLoader()->qmldirContent(qmldirFilePath, qmldirUrl);
foreach (const QQmlDirParser::Script &script, qmldir->scripts()) {
QUrl scriptUrl = libraryUrl.resolved(QUrl(script.fileName));
QQmlScriptBlob *blob = typeLoader()->getScript(scriptUrl);
addDependency(blob);
scriptImported(blob, p->location, script.nameSpace, importQualifier);
}
}
} else {
if (!addImport(p, &unit->errors))
return false;
}
} else if (p->type == QV4::CompiledData::Import::ImportFile) {
// load file import
// qqmltypeloader.cpp:1384
const QString &importUri = stringAt(p->uriIndex);
const QString &importQualifier = stringAt(p->qualifierIndex);
QUrl qmldirUrl;
if (importQualifier.isEmpty()) {
qmldirUrl = finalUrl().resolved(QUrl(importUri + QLatin1String("/qmldir")));
if (!QQmlImports::isLocal(qmldirUrl)) {
// This is a remote file; the import is currently incomplete
QQmlError error;
error.setDescription("Remote dependencies not supported");
error.setUrl(qmldirUrl);
unit->errors.append(error);
return false;
}
}
if (!m_importCache.addFileImport(typeLoader()->importDatabase(), importUri, importQualifier, p->majorVersion,
p->minorVersion, false, &unit->errors))
return false;
fileImports.append(importUri);
} else {
QQmlError error;
error.setDescription("Unknown type import");
error.setColumn(p->location.column);
error.setLine(p->location.line);
error.setUrl(finalUrl());
unit->errors.append(error);
return false;
}
}
// resolve types
// type data creation
// qqmlirbuilder.cpp:285 create QV4::CompiledData::TypeReference = location
// qqmltypeloader.cpp:2402 QV4::CompiledData::TypeReference -> QQmlTypeData::TypeReference
// qqmltypecompiler.cpp:86 QQmlTypeData::TypeReference -> QQmlCompiledData::TypeReference
foreach (const QmcUnitTypeReference& typeRef, unit->typeReferences) {
int majorVersion = -1;
int minorVersion = -1;
QQmlImportNamespace *typeNamespace = 0;
if ((int)typeRef.index >= unit->strings.size())
return false;
const QString name = stringAt(typeRef.index);
if (typeRef.syntheticComponent)
continue;
QQmlCompiledData::TypeReference *ref = new QQmlCompiledData::TypeReference;
QQmlType *qmlType = NULL;
if (!m_importCache.resolveType(name, &qmlType, &majorVersion, &minorVersion, &typeNamespace, &unit->errors)) {
bool found = false;
// try to load it as implicit
QmcUnit *typeUnit = qmcUnit()->loader->getType(name, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
unit->errors.clear();
dependencies.append(typeUnit);
found = true;
}
if(!found){
// local file imports
foreach (const QString &path, fileImports){
QmcUnit *typeUnit = qmcUnit()->loader->getType(path + "/" + name, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
unit->errors.clear();
dependencies.append(typeUnit);
found = true;
break;
}
}
}
if(!found){
QQmlError error;
error.setDescription("Could not load implicit import");
unit->errors.append(error);
delete ref;
return false;
}
}
// component creation, see qqmltypecompiler.cpp:87
// and qqmltypeloader.cpp:2456
if (typeRef.composite && !ref->component) {
// extract name of the source url
Q_ASSERT(qmlType);
QString sourceName;
if (!sourceNameForUrl(qmlType->sourceUrl(), sourceName)) {
delete ref;
return false;
}
int lastDot = sourceName.lastIndexOf('.');
if (lastDot != -1)
sourceName = sourceName.left(lastDot);
QmcUnit *typeUnit = qmcUnit()->loader->getType(sourceName, unit->loadedUrl);
if (typeUnit) {
ref->component = ((QmcTypeUnit *)typeUnit->blob)->refCompiledData(); // addref
dependencies.append(typeUnit);
} else {
QQmlError error;
error.setDescription("Could not load implicit import");
unit->errors.append(error);
delete ref;
return false;
}
} else if (qmlType) {
ref->type = qmlType;
if (ref->type->containsRevisionedAttributes()) {
// qqmltypecompiler.cpp:102
QQmlError cacheError;
ref->typePropertyCache = QQmlEnginePrivate::get(unit->engine)->cache(ref->type, minorVersion, cacheError);
if (!ref->typePropertyCache) {
delete ref;
unit->errors.append(cacheError);
return false;
}
ref->typePropertyCache->addref();
}
}
// TBD: qqmltypecompiler.cpp:86
ref->majorVersion = majorVersion;
ref->minorVersion = minorVersion;
// dynamic type check moved to init phase
compiledData->resolvedTypes.insert(typeRef.index, ref);
}
// from QQmlTypeCompiler::compile
compiledData->importCache = new QQmlTypeNameCache;
foreach (const QString &ns, unit->namespaces)
compiledData->importCache->add(ns);
#if 0
// Add any Composite Singletons that were used to the import cache
foreach (const QQmlTypeData::TypeReference &singleton, compositeSingletons)
compiledData->importCache->add(singleton.type->qmlTypeName(), singleton.type->sourceUrl(), singleton.prefix);
#endif
// TBD: is import cache required at all ? Cannot be null though.
m_importCache.populateCache(compiledData->importCache);
// qqmltypecompiler.cpp:1413
foreach (const QmcUnitTypeReference& typeRef, unit->typeReferences) {
static QQmlType *componentType = QQmlMetaType::qmlType(&QQmlComponent::staticMetaObject);
if (!typeRef.syntheticComponent)
continue;
QQmlCompiledData::TypeReference *ref = new QQmlCompiledData::TypeReference;
ref->type = componentType;
ref->majorVersion = componentType->majorVersion();
ref->minorVersion = componentType->minorVersion();
compiledData->resolvedTypes.insert(typeRef.index, ref);
}
// scripts resolved through file imports
// actual script loading is done in QQmlObjectCreator::create (qqmlobjectcreator.cpp:215)
foreach (const QQmlImports::ScriptReference &scriptRef, imports().resolvedScripts()) {
// script reference
QString locationName;
if (!sourceNameForUrl(scriptRef.location, locationName))
return false;
QmcScriptUnit *script = unit->loader->getScript(locationName, unit->loadedUrl);
if (!script) {
QQmlError error;
error.setDescription("Could not load script");
error.setUrl(scriptRef.location);
unit->errors.append(error);
return false;
}
//compiledData->scripts.append(script->scriptData());
QQmlTypeData::ScriptReference ref;
ref.script = script;
ref.qualifier = scriptRef.qualifier;
scripts.append(ref);
}
return true;
}
bool QmcTypeUnit::sourceNameForUrl(const QUrl &url, QString &name)
{
name = url.toString();
QString loadedBaseUrl = QmcLoader::getBaseUrl(unit->loadedUrl.toString());
if (name.startsWith("file://")) {
// keep name as is
} else if (name.startsWith(loadedBaseUrl)) {
if (name.size() > loadedBaseUrl.size())
name = name.mid(loadedBaseUrl.size());
else
name = "";
} else {
// use just name
qDebug() << "Reverting back to using just file name to resolve url, propably won't work";
int lastSlash = name.lastIndexOf('/');
if (lastSlash + 1 >= name.length()) {
QQmlError error;
error.setDescription("Illegal formatted url");
error.setUrl(url);
unit->errors.append(error);
return false;
} else if (lastSlash != -1)
name = name.mid(lastSlash + 1);
}
return true;
}
QQmlCompiledData *QmcTypeUnit::refCompiledData()
{
Q_ASSERT(compiledData);
compiledData->addref();
return compiledData;
}
bool QmcTypeUnit::initDependencies()
{
foreach (const QQmlTypeData::ScriptReference &scriptRef, scripts) {
QmcScriptUnit *script = (QmcScriptUnit *)scriptRef.script;
if (!script->initialize())
return false;
}
foreach (QmcUnit *unit, dependencies) {
if (unit->type == QMC_QML) {
QmcTypeUnit * blob = (QmcTypeUnit *)unit->blob;
if (!blob->link())
return false;
}
}
// TBD: initialize dependencies of script & types (recursion)
return true;
}
bool QmcTypeUnit::initQml()
{
// type references init
foreach (QQmlCompiledData::TypeReference *typeRef, compiledData->resolvedTypes) {
typeRef->doDynamicTypeCheck();
}
compiledData->initialize(unit->engine);
// create property caches
// qqmltypecompiler.cpp:143-150
QmcUnitPropertyCacheCreator cacheCreator(this);
if (!cacheCreator.buildMetaObjects())
return false;
// scripts
// qqmltypeloader.cpp:1315:
// create QQmlScriptBlob + QQmlScriptData
// add to QQmlTypeLoader::Blob->scripts
// qqmltypecompiler.cpp:180:
// add to import cache
// QQmlTypeData::ScriptReference->scriptData -> compiledData->scripts
foreach (const QQmlTypeData::ScriptReference &scriptRef, scripts) {
// create QQmlScriptData and link it to QmcScriptUnit
QQmlScriptData *scriptData = scriptRef.script->scriptData();
scriptData->addref();
compiledData->scripts.append(scriptData);
}
// add object mappings + aliases
// alias creation call chain
// QQmlTypeCompiler::compile
// ->QQmlComponentAndAliasResolver::resolve->resolveAliases
// -->QQmlPropertyCache::appendProperty
// TBD: add aliases to property cache
QmcTypeUnitComponentAndAliasResolver resolver(this);
if (!resolver.resolve())
return false;
// TBD: alias creation makes component composite type
if (compiledData->isCompositeType()) {
// TBD: does this work ?
QQmlEnginePrivate::get(unit->engine)->registerInternalCompositeType(compiledData);
//engine->registerInternalCompositeType(compiledData);
} else {
const QV4::CompiledData::Object *obj = compiledData->qmlUnit->objectAt(compiledData->qmlUnit->indexOfRootObject);
if (!obj)
return false;
QQmlCompiledData::TypeReference *typeRef = compiledData->resolvedTypes.value(obj->inheritedTypeNameIndex);
if (!typeRef)
return false;
if (typeRef->component) {
compiledData->metaTypeId = typeRef->component->metaTypeId;
compiledData->listMetaTypeId = typeRef->component->listMetaTypeId;
} else {
compiledData->metaTypeId = typeRef->type->typeId();
compiledData->listMetaTypeId = typeRef->type->qListTypeId();
}
}
// extra initiliazation of QQmlCompiledData qqmltypecompiler.cpp:263
#if 0
// TBD: function below seems to quite a lot
// Sanity check property bindings
QQmlPropertyValidator validator(this);
if (!validator.validate())
return false;
#endif
// add custom parsers, custom bindings and deferred bindings
// TBD:
// Collect some data for instantiation later.
int bindingCount = 0;
int parserStatusCount = 0;
int objectCount = 0;
for (quint32 i = 0; i < compiledData->qmlUnit->nObjects; ++i) {
const QV4::CompiledData::Object *obj = compiledData->qmlUnit->objectAt(i);
bindingCount += obj->nBindings;
if (QQmlCompiledData::TypeReference *typeRef = compiledData->resolvedTypes.value(obj->inheritedTypeNameIndex)) {
if (QQmlType *qmlType = typeRef->type) {
if (qmlType->parserStatusCast() != -1)
++parserStatusCount;
}
if (typeRef->component) {
bindingCount += typeRef->component->totalBindingsCount;
parserStatusCount += typeRef->component->totalParserStatusCount;
objectCount += typeRef->component->totalObjectCount;
} else
++objectCount;
}
}
compiledData->totalBindingsCount = bindingCount;
compiledData->totalParserStatusCount = parserStatusCount;
compiledData->totalObjectCount = objectCount;
if (compiledData->propertyCaches.count() != static_cast<int>(compiledData->qmlUnit->nObjects))
return false;
return true;
}
QQmlComponent* QmcTypeUnit::createComponent()
{
QQmlComponent* component = new QQmlComponent(unit->engine);
QQmlComponentPrivate* cPriv = QQmlComponentPrivate::get(component);
cPriv->cc = compiledData;
cPriv->cc->addref();
return component;
}
|
/*
* summit_xl_pad
* Copyright (c) 2012, Robotnik Automation, SLL
* 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 the Robotnik Automation, SLL. 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
* \author Robotnik Automation, SLL
* \brief Allows to use a pad with the roboy controller, sending the messages received from the joystick device
*/
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include <robotnik_msgs/ptz.h>
// Not yet catkinized 9/2013
// #include <sound_play/sound_play.h>
#include <unistd.h>
#include <robotnik_msgs/set_mode.h>
#include <robotnik_msgs/set_digital_output.h>
#include <robotnik_msgs/ptz.h>
#include <robotnik_msgs/home.h>
#include <diagnostic_updater/diagnostic_updater.h>
#include <diagnostic_updater/publisher.h>
#define DEFAULT_NUM_OF_BUTTONS 16
#define DEFAULT_AXIS_LINEAR_X 1
#define DEFAULT_AXIS_LINEAR_Y 0
#define DEFAULT_AXIS_ANGULAR 2
#define DEFAULT_AXIS_LINEAR_Z 3
#define DEFAULT_SCALE_LINEAR 1.0
#define DEFAULT_SCALE_ANGULAR 2.0
#define DEFAULT_SCALE_LINEAR_Z 1.0
//Used only with ps4
#define AXIS_PTZ_TILT_UP 0
#define AXIS_PTZ_TILT_DOWN 1
#define AXIS_PTZ_PAN_LEFT 2
#define AXIS_PTZ_PAN_RIGHT 3
////////////////////////////////////////////////////////////////////////
// NOTE: //
// This configuration is made for a THRUSTMASTER T-Wireless 3in1 Joy //
// please feel free to modify to adapt for your own joystick. //
// //
class SummitXLPad
{
public:
SummitXLPad();
void Update();
private:
void padCallback(const sensor_msgs::Joy::ConstPtr& joy);
ros::NodeHandle nh_;
int linear_x_, linear_y_, linear_z_, angular_;
double l_scale_, a_scale_, l_scale_z_;
//! It will publish into command velocity (for the robot) and the ptz_state (for the pantilt)
ros::Publisher vel_pub_, ptz_pub_;
//! It will be suscribed to the joystick
ros::Subscriber pad_sub_;
//! Name of the topic where it will be publishing the velocity
std::string cmd_topic_vel_;
//! Name of the service where it will be modifying the digital outputs
std::string cmd_service_io_;
//! Name of the topic where it will be publishing the pant-tilt values
std::string cmd_topic_ptz_;
double current_vel;
//! Pad type
std::string pad_type_;
//! Number of the DEADMAN button
int dead_man_button_;
//! Number of the button for increase or decrease the speed max of the joystick
int speed_up_button_, speed_down_button_;
int button_output_1_, button_output_2_;
int output_1_, output_2_;
bool bOutput1, bOutput2;
//! button to change kinematic mode
int button_kinematic_mode_;
//! kinematic mode
int kinematic_mode_;
//! Service to modify the kinematic mode
ros::ServiceClient setKinematicMode;
//! Name of the service to change the mode
std::string cmd_set_mode_;
//! button to start the homing service
int button_home_;
//! Service to start homing
ros::ServiceClient doHome;
//! Name of the service to do the homing
std::string cmd_home_;
//! buttons to the pan-tilt-zoom camera
int ptz_tilt_up_, ptz_tilt_down_, ptz_pan_right_, ptz_pan_left_;
int ptz_zoom_wide_, ptz_zoom_tele_;
//! Service to modify the digital outputs
ros::ServiceClient set_digital_outputs_client_;
//! Number of buttons of the joystick
int num_of_buttons_;
//! Pointer to a vector for controlling the event when pushing the buttons
bool bRegisteredButtonEvent[DEFAULT_NUM_OF_BUTTONS];
//! Pointer to a vector for controlling the event when pushing directional arrows (UNDER AXES ON PX4!)
bool bRegisteredDirectionalArrows[4];
// DIAGNOSTICS
//! Diagnostic to control the frequency of the published command velocity topic
diagnostic_updater::HeaderlessTopicDiagnostic *pub_command_freq;
//! Diagnostic to control the reception frequency of the subscribed joy topic
diagnostic_updater::HeaderlessTopicDiagnostic *sus_joy_freq;
//! General status diagnostic updater
diagnostic_updater::Updater updater_pad;
//! Diagnostics min freq
double min_freq_command, min_freq_joy; //
//! Diagnostics max freq
double max_freq_command, max_freq_joy; //
//! Flag to enable/disable the communication with the publishers topics
bool bEnable;
//! Flag to track the first reading without the deadman's button pressed.
bool last_command_;
//! Client of the sound play service
// sound_play::SoundClient sc;
//! Pan & tilt increment (degrees)
int pan_increment_, tilt_increment_;
//! Zoom increment (steps)
int zoom_increment_;
//! Add a dead zone to the joystick that controls scissor and robot rotation (only useful for xWam)
std::string joystick_dead_zone_;
};
SummitXLPad::SummitXLPad():
linear_x_(1),
linear_y_(0),
angular_(2),
linear_z_(3)
{
current_vel = 0.1;
//JOYSTICK PAD TYPE
nh_.param<std::string>("pad_type",pad_type_,"ps3");
//
nh_.param("num_of_buttons", num_of_buttons_, DEFAULT_NUM_OF_BUTTONS);
// MOTION CONF
nh_.param("axis_linear_x", linear_x_, DEFAULT_AXIS_LINEAR_X);
nh_.param("axis_linear_y", linear_y_, DEFAULT_AXIS_LINEAR_Y);
nh_.param("axis_linear_z", linear_z_, DEFAULT_AXIS_LINEAR_Z);
nh_.param("axis_angular", angular_, DEFAULT_AXIS_ANGULAR);
nh_.param("scale_angular", a_scale_, DEFAULT_SCALE_ANGULAR);
nh_.param("scale_linear", l_scale_, DEFAULT_SCALE_LINEAR);
nh_.param("scale_linear_z", l_scale_z_, DEFAULT_SCALE_LINEAR_Z);
nh_.param("cmd_topic_vel", cmd_topic_vel_, cmd_topic_vel_);
nh_.param("button_dead_man", dead_man_button_, dead_man_button_);
nh_.param("button_speed_up", speed_up_button_, speed_up_button_); //4 Thrustmaster
nh_.param("button_speed_down", speed_down_button_, speed_down_button_); //5 Thrustmaster
nh_.param<std::string>("joystick_dead_zone", joystick_dead_zone_, "true");
// DIGITAL OUTPUTS CONF
nh_.param("cmd_service_io", cmd_service_io_, cmd_service_io_);
nh_.param("button_output_1", button_output_1_, button_output_1_);
nh_.param("button_output_2", button_output_2_, button_output_2_);
nh_.param("output_1", output_1_, output_1_);
nh_.param("output_2", output_2_, output_2_);
// PANTILT-ZOOM CONF
nh_.param("cmd_topic_ptz", cmd_topic_ptz_, cmd_topic_ptz_);
nh_.param("button_ptz_tilt_up", ptz_tilt_up_, ptz_tilt_up_);
nh_.param("button_ptz_tilt_down", ptz_tilt_down_, ptz_tilt_down_);
nh_.param("button_ptz_pan_right", ptz_pan_right_, ptz_pan_right_);
nh_.param("button_ptz_pan_left", ptz_pan_left_, ptz_pan_left_);
nh_.param("button_ptz_zoom_wide", ptz_zoom_wide_, ptz_zoom_wide_);
nh_.param("button_ptz_zoom_tele", ptz_zoom_tele_, ptz_zoom_tele_);
nh_.param("button_home", button_home_, button_home_);
nh_.param("pan_increment", pan_increment_, 1);
nh_.param("tilt_increment",tilt_increment_, 1);
nh_.param("zoom_increment", zoom_increment_, 1);
// KINEMATIC MODE
nh_.param("button_kinematic_mode", button_kinematic_mode_, button_kinematic_mode_);
nh_.param("cmd_service_set_mode", cmd_set_mode_, cmd_set_mode_);
nh_.param("cmd_service_home", cmd_home_, cmd_home_);
kinematic_mode_ = 1;
ROS_INFO("SummitXLPad num_of_buttons_ = %d", num_of_buttons_);
for(int i = 0; i < num_of_buttons_; i++){
bRegisteredButtonEvent[i] = false;
ROS_INFO("bREG %d", i);
}
for(int i = 0; i < 3; i++){
bRegisteredDirectionalArrows[i] = false;
}
/*ROS_INFO("Service I/O = [%s]", cmd_service_io_.c_str());
ROS_INFO("Topic PTZ = [%s]", cmd_topic_ptz_.c_str());
ROS_INFO("Service I/O = [%s]", cmd_topic_vel_.c_str());
ROS_INFO("Axis linear = %d", linear_);
ROS_INFO("Axis angular = %d", angular_);
ROS_INFO("Scale angular = %d", a_scale_);
ROS_INFO("Deadman button = %d", dead_man_button_);
ROS_INFO("OUTPUT1 button %d", button_output_1_);
ROS_INFO("OUTPUT2 button %d", button_output_2_);
ROS_INFO("OUTPUT1 button %d", button_output_1_);
ROS_INFO("OUTPUT2 button %d", button_output_2_);*/
// Publish through the node handle Twist type messages to the guardian_controller/command topic
vel_pub_ = nh_.advertise<geometry_msgs::Twist>(cmd_topic_vel_, 1);
// Publishes msgs for the pant-tilt cam
ptz_pub_ = nh_.advertise<robotnik_msgs::ptz>(cmd_topic_ptz_, 1);
// Listen through the node handle sensor_msgs::Joy messages from joystick
// (these are the references that we will sent to summit_xl_controller/command)
pad_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &SummitXLPad::padCallback, this);
// Request service to activate / deactivate digital I/O
set_digital_outputs_client_ = nh_.serviceClient<robotnik_msgs::set_digital_output>(cmd_service_io_);
bOutput1 = bOutput2 = false;
// Request service to set kinematic mode
setKinematicMode = nh_.serviceClient<robotnik_msgs::set_mode>(cmd_set_mode_);
// Request service to start homing
doHome = nh_.serviceClient<robotnik_msgs::home>(cmd_home_);
// Diagnostics
updater_pad.setHardwareID("None");
// Topics freq control
min_freq_command = min_freq_joy = 5.0;
max_freq_command = max_freq_joy = 50.0;
sus_joy_freq = new diagnostic_updater::HeaderlessTopicDiagnostic("/joy", updater_pad,
diagnostic_updater::FrequencyStatusParam(&min_freq_joy, &max_freq_joy, 0.1, 10));
pub_command_freq = new diagnostic_updater::HeaderlessTopicDiagnostic(cmd_topic_vel_.c_str(), updater_pad,
diagnostic_updater::FrequencyStatusParam(&min_freq_command, &max_freq_command, 0.1, 10));
bEnable = false; // Communication flag disabled by default
last_command_ = true;
}
/*
* \brief Updates the diagnostic component. Diagnostics
*
*/
void SummitXLPad::Update(){
updater_pad.update();
}
void SummitXLPad::padCallback(const sensor_msgs::Joy::ConstPtr& joy)
{
geometry_msgs::Twist vel;
robotnik_msgs::ptz ptz;
bool ptzEvent = false;
vel.linear.x = 0.0;
vel.linear.y = 0.0;
vel.linear.z = 0.0;
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
bEnable = (joy->buttons[dead_man_button_] == 1);
// Actions dependant on dead-man button
if (joy->buttons[dead_man_button_] == 1) {
//ROS_ERROR("SummitXLPad::padCallback: DEADMAN button %d", dead_man_button_);
//Set the current velocity level
if ( joy->buttons[speed_down_button_] == 1 ){
if(!bRegisteredButtonEvent[speed_down_button_])
if(current_vel > 0.1){
current_vel = current_vel - 0.1;
bRegisteredButtonEvent[speed_down_button_] = true;
ROS_INFO("Velocity: %f%%", current_vel*100.0);
char buf[50]="\0";
int percent = (int) (current_vel*100.0);
sprintf(buf," %d percent", percent);
// sc.say(buf);
}
}else{
bRegisteredButtonEvent[speed_down_button_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPEED DOWN button %d", speed_down_button_);
if (joy->buttons[speed_up_button_] == 1){
if(!bRegisteredButtonEvent[speed_up_button_])
if(current_vel < 0.9){
current_vel = current_vel + 0.1;
bRegisteredButtonEvent[speed_up_button_] = true;
ROS_INFO("Velocity: %f%%", current_vel*100.0);
char buf[50]="\0";
int percent = (int) (current_vel*100.0);
sprintf(buf," %d percent", percent);
// sc.say(buf);
}
}else{
bRegisteredButtonEvent[speed_up_button_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPEED UP button %d", speed_up_button_);
vel.linear.x = current_vel*l_scale_*joy->axes[linear_x_];
vel.linear.y = current_vel*l_scale_*joy->axes[linear_y_];
//ROS_ERROR("SummitXLPad::padCallback: Passed linear axes");
if(joystick_dead_zone_=="true")
{
// limit scissor movement or robot turning (they are in the same joystick)
if(joy->axes[angular_] == 1.0 || joy->axes[angular_] == -1.0) // if robot turning
{
// Same angular velocity for the three axis
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = 0.0;
}
else if (joy->axes[linear_z_] == 1.0 || joy->axes[linear_z_] == -1.0) // if scissor moving
{
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement
// limit robot turn
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
}
else
{
// Same angular velocity for the three axis
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement
}
}
else // no dead zone
{
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_];
}
//ROS_ERROR("SummitXLPad::padCallback: Passed joystick deadzone ifelse");
// LIGHTS
if (joy->buttons[button_output_1_] == 1) {
if(!bRegisteredButtonEvent[button_output_1_]){
//ROS_INFO("SummitXLPad::padCallback: OUTPUT1 button %d", button_output_1_);
robotnik_msgs::set_digital_output write_do_srv;
write_do_srv.request.output = output_1_;
bOutput1=!bOutput1;
write_do_srv.request.value = bOutput1;
if(bEnable){
set_digital_outputs_client_.call( write_do_srv );
bRegisteredButtonEvent[button_output_1_] = true;
}
}
}else{
bRegisteredButtonEvent[button_output_1_] = false;
}
if (joy->buttons[button_output_2_] == 1) {
if(!bRegisteredButtonEvent[button_output_2_]){
//ROS_INFO("SummitXLPad::padCallback: OUTPUT2 button %d", button_output_2_);
robotnik_msgs::set_digital_output write_do_srv;
write_do_srv.request.output = output_2_;
bOutput2=!bOutput2;
write_do_srv.request.value = bOutput2;
if(bEnable){
set_digital_outputs_client_.call( write_do_srv );
bRegisteredButtonEvent[button_output_2_] = true;
}
}
}else{
bRegisteredButtonEvent[button_output_2_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed LIGHTS");
// HOMING SERVICE
if (joy->buttons[button_home_] == 1) {
if (!bRegisteredButtonEvent[button_home_]) {
robotnik_msgs::home home_srv;
home_srv.request.request = true;
if (bEnable) {
ROS_INFO("SummitXLPad::padCallback - Home");
doHome.call( home_srv );
bRegisteredButtonEvent[button_home_] = true;
}
}
// Use this button also to block robot motion while moving the scissor
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
vel.linear.x = 0.0;
vel.linear.y = 0.0;
}
else {
bRegisteredButtonEvent[button_home_]=false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed HOME BUTTON");
// SPHERECAM
ptz.pan = ptz.tilt = ptz.zoom = 0.0;
ptz.relative = true;
if(pad_type_=="ps4" || pad_type_=="logitechf710")
{
if (joy->axes[ptz_tilt_up_] == 1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP]){
ptz.tilt = tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT UP");
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = false;
}
if (joy->axes[ptz_tilt_down_] == -1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN]){
ptz.tilt = -tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT DOWN");
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = false;
}
if (joy->axes[ptz_pan_left_] == 1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT]){
ptz.pan = -pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN LEFT");
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = false;
}
if (joy->axes[ptz_pan_right_] == -1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT]){
ptz.pan = pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN RIGHT");
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = false;
}
}else{
//ROS_ERROR("SummitXLPad::padCallback: INSIDE ELSE PTZ PAD_TYPE");
// TILT-MOVEMENTS (RELATIVE POS)
if (joy->buttons[ptz_tilt_up_] == 1) {
if(!bRegisteredButtonEvent[ptz_tilt_up_]){
ptz.tilt = tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT UP");
bRegisteredButtonEvent[ptz_tilt_up_] = true;
ptzEvent = true;
}
}else {
bRegisteredButtonEvent[ptz_tilt_up_] = false;
}
if (joy->buttons[ptz_tilt_down_] == 1) {
if(!bRegisteredButtonEvent[ptz_tilt_down_]){
ptz.tilt = -tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT DOWN");
bRegisteredButtonEvent[ptz_tilt_down_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_tilt_down_] = false;
}
// PAN-MOVEMENTS (RELATIVE POS)
if (joy->buttons[ptz_pan_left_] == 1) {
if(!bRegisteredButtonEvent[ptz_pan_left_]){
ptz.pan = -pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN LEFT");
bRegisteredButtonEvent[ptz_pan_left_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_pan_left_] = false;
}
if (joy->buttons[ptz_pan_right_] == 1) {
if(!bRegisteredButtonEvent[ptz_pan_right_]){
ptz.pan = pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN RIGHT");
bRegisteredButtonEvent[ptz_pan_right_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_pan_right_] = false;
}
}
// ZOOM Settings (RELATIVE)
if (joy->buttons[ptz_zoom_wide_] == 1) {
if(!bRegisteredButtonEvent[ptz_zoom_wide_]){
ptz.zoom = -zoom_increment_;
//ROS_INFO("SummitXLPad::padCallback: ZOOM WIDe");
bRegisteredButtonEvent[ptz_zoom_wide_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_zoom_wide_] = false;
}
if (joy->buttons[ptz_zoom_tele_] == 1) {
if(!bRegisteredButtonEvent[ptz_zoom_tele_]){
ptz.zoom = zoom_increment_;
//ROS_INFO("SummitXLPad::padCallback: ZOOM TELE");
bRegisteredButtonEvent[ptz_zoom_tele_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_zoom_tele_] = false;
}
if (joy->buttons[button_kinematic_mode_] == 1) {
if(!bRegisteredButtonEvent[button_kinematic_mode_]){
// Define mode (inc) - still coupled
kinematic_mode_ += 1;
if (kinematic_mode_ > 2) kinematic_mode_ = 1;
ROS_INFO("SummitXLJoy::joyCallback: Kinematic Mode %d ", kinematic_mode_);
// Call service
robotnik_msgs::set_mode set_mode_srv;
set_mode_srv.request.mode = kinematic_mode_;
setKinematicMode.call( set_mode_srv );
bRegisteredButtonEvent[button_kinematic_mode_] = true;
}
}else{
bRegisteredButtonEvent[button_kinematic_mode_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPHERE CAM and KINEMATIC MODE");
}
else {
vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0;
vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0;
}
sus_joy_freq->tick(); // Ticks the reception of joy events
// Publish
// Only publishes if it's enabled
if(bEnable){
if (ptzEvent) ptz_pub_.publish(ptz);
vel_pub_.publish(vel);
pub_command_freq->tick();
last_command_ = true;
}
if(!bEnable && last_command_){
if (ptzEvent) ptz_pub_.publish(ptz);
vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0;
vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0;
vel_pub_.publish(vel);
pub_command_freq->tick();
last_command_ = false;
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "summit_xl_pad");
SummitXLPad summit_xl_pad;
ros::Rate r(50.0);
while( ros::ok() ){
// UPDATING DIAGNOSTICS
summit_xl_pad.Update();
ros::spinOnce();
r.sleep();
}
}
pad: working with private node handler for params. Few changes in ptz control
/*
* summit_xl_pad
* Copyright (c) 2012, Robotnik Automation, SLL
* 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 the Robotnik Automation, SLL. 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
*
* \author Robotnik Automation, SLL
* \brief Allows to use a pad with the roboy controller, sending the messages received from the joystick device
*/
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include <robotnik_msgs/ptz.h>
// Not yet catkinized 9/2013
// #include <sound_play/sound_play.h>
#include <unistd.h>
#include <robotnik_msgs/set_mode.h>
#include <robotnik_msgs/set_digital_output.h>
#include <robotnik_msgs/ptz.h>
#include <robotnik_msgs/home.h>
#include <diagnostic_updater/diagnostic_updater.h>
#include <diagnostic_updater/publisher.h>
#define DEFAULT_NUM_OF_BUTTONS 16
#define DEFAULT_AXIS_LINEAR_X 1
#define DEFAULT_AXIS_LINEAR_Y 0
#define DEFAULT_AXIS_ANGULAR 2
#define DEFAULT_AXIS_LINEAR_Z 3
#define DEFAULT_SCALE_LINEAR 1.0
#define DEFAULT_SCALE_ANGULAR 2.0
#define DEFAULT_SCALE_LINEAR_Z 1.0
//Used only with ps4
#define AXIS_PTZ_TILT_UP 0
#define AXIS_PTZ_TILT_DOWN 1
#define AXIS_PTZ_PAN_LEFT 2
#define AXIS_PTZ_PAN_RIGHT 3
////////////////////////////////////////////////////////////////////////
// NOTE: //
// This configuration is made for a THRUSTMASTER T-Wireless 3in1 Joy //
// please feel free to modify to adapt for your own joystick. //
// //
class SummitXLPad
{
public:
SummitXLPad();
void Update();
private:
void padCallback(const sensor_msgs::Joy::ConstPtr& joy);
ros::NodeHandle nh_;
ros::NodeHandle pnh_;
int linear_x_, linear_y_, linear_z_, angular_;
double l_scale_, a_scale_, l_scale_z_;
//! It will publish into command velocity (for the robot) and the ptz_state (for the pantilt)
ros::Publisher vel_pub_, ptz_pub_;
//! It will be suscribed to the joystick
ros::Subscriber pad_sub_;
//! Name of the topic where it will be publishing the velocity
std::string cmd_topic_vel_;
//! Name of the service where it will be modifying the digital outputs
std::string cmd_service_io_;
//! Name of the topic where it will be publishing the pant-tilt values
std::string cmd_topic_ptz_;
double current_vel;
//! Pad type
std::string pad_type_;
//! Number of the DEADMAN button
int dead_man_button_;
//! Number of the button for increase or decrease the speed max of the joystick
int speed_up_button_, speed_down_button_;
int button_output_1_, button_output_2_;
int output_1_, output_2_;
bool bOutput1, bOutput2;
//! button to change kinematic mode
int button_kinematic_mode_;
//! kinematic mode
int kinematic_mode_;
//! Service to modify the kinematic mode
ros::ServiceClient setKinematicMode;
//! Name of the service to change the mode
std::string cmd_set_mode_;
//! button to start the homing service
int button_home_;
//! Service to start homing
ros::ServiceClient doHome;
//! Name of the service to do the homing
std::string cmd_home_;
//! buttons to the pan-tilt-zoom camera
int ptz_tilt_up_, ptz_tilt_down_, ptz_pan_right_, ptz_pan_left_;
int ptz_zoom_wide_, ptz_zoom_tele_;
//! Service to modify the digital outputs
ros::ServiceClient set_digital_outputs_client_;
//! Number of buttons of the joystick
int num_of_buttons_;
//! Pointer to a vector for controlling the event when pushing the buttons
bool bRegisteredButtonEvent[DEFAULT_NUM_OF_BUTTONS];
//! Pointer to a vector for controlling the event when pushing directional arrows (UNDER AXES ON PX4!)
bool bRegisteredDirectionalArrows[4];
// DIAGNOSTICS
//! Diagnostic to control the frequency of the published command velocity topic
diagnostic_updater::HeaderlessTopicDiagnostic *pub_command_freq;
//! Diagnostic to control the reception frequency of the subscribed joy topic
diagnostic_updater::HeaderlessTopicDiagnostic *sus_joy_freq;
//! General status diagnostic updater
diagnostic_updater::Updater updater_pad;
//! Diagnostics min freq
double min_freq_command, min_freq_joy; //
//! Diagnostics max freq
double max_freq_command, max_freq_joy; //
//! Flag to enable/disable the communication with the publishers topics
bool bEnable;
//! Flag to track the first reading without the deadman's button pressed.
bool last_command_;
//! Client of the sound play service
// sound_play::SoundClient sc;
//! Pan & tilt increment (degrees)
double pan_increment_, tilt_increment_;
//! Zoom increment (steps)
int zoom_increment_;
//! Add a dead zone to the joystick that controls scissor and robot rotation (only useful for xWam)
std::string joystick_dead_zone_;
//! Flag to enable the ptz control via axes
bool ptz_control_by_axes_;
};
SummitXLPad::SummitXLPad():
linear_x_(1),
linear_y_(0),
angular_(2),
linear_z_(3),
pnh_("~")
{
current_vel = 0.1;
//JOYSTICK PAD TYPE
pnh_.param<std::string>("pad_type",pad_type_,"ps3");
//
pnh_.param("num_of_buttons", num_of_buttons_, DEFAULT_NUM_OF_BUTTONS);
// MOTION CONF
pnh_.param("axis_linear_x", linear_x_, DEFAULT_AXIS_LINEAR_X);
pnh_.param("axis_linear_y", linear_y_, DEFAULT_AXIS_LINEAR_Y);
pnh_.param("axis_linear_z", linear_z_, DEFAULT_AXIS_LINEAR_Z);
pnh_.param("axis_angular", angular_, DEFAULT_AXIS_ANGULAR);
pnh_.param("scale_angular", a_scale_, DEFAULT_SCALE_ANGULAR);
pnh_.param("scale_linear", l_scale_, DEFAULT_SCALE_LINEAR);
pnh_.param("scale_linear_z", l_scale_z_, DEFAULT_SCALE_LINEAR_Z);
pnh_.param("cmd_topic_vel", cmd_topic_vel_, cmd_topic_vel_);
pnh_.param("button_dead_man", dead_man_button_, dead_man_button_);
pnh_.param("button_speed_up", speed_up_button_, speed_up_button_); //4 Thrustmaster
pnh_.param("button_speed_down", speed_down_button_, speed_down_button_); //5 Thrustmaster
pnh_.param<std::string>("joystick_dead_zone", joystick_dead_zone_, "true");
// DIGITAL OUTPUTS CONF
pnh_.param("cmd_service_io", cmd_service_io_, cmd_service_io_);
pnh_.param("button_output_1", button_output_1_, button_output_1_);
pnh_.param("button_output_2", button_output_2_, button_output_2_);
pnh_.param("output_1", output_1_, output_1_);
pnh_.param("output_2", output_2_, output_2_);
// PANTILT-ZOOM CONF
pnh_.param("cmd_topic_ptz", cmd_topic_ptz_, cmd_topic_ptz_);
pnh_.param("button_ptz_tilt_up", ptz_tilt_up_, ptz_tilt_up_);
pnh_.param("button_ptz_tilt_down", ptz_tilt_down_, ptz_tilt_down_);
pnh_.param("button_ptz_pan_right", ptz_pan_right_, ptz_pan_right_);
pnh_.param("button_ptz_pan_left", ptz_pan_left_, ptz_pan_left_);
pnh_.param("button_ptz_zoom_wide", ptz_zoom_wide_, ptz_zoom_wide_);
pnh_.param("button_ptz_zoom_tele", ptz_zoom_tele_, ptz_zoom_tele_);
pnh_.param("button_home", button_home_, button_home_);
pnh_.param("pan_increment", pan_increment_, 0.09);
pnh_.param("tilt_increment", tilt_increment_, 0.09);
pnh_.param("zoom_increment", zoom_increment_, 200);
// KINEMATIC MODE
pnh_.param("button_kinematic_mode", button_kinematic_mode_, button_kinematic_mode_);
pnh_.param("cmd_service_set_mode", cmd_set_mode_, cmd_set_mode_);
pnh_.param("cmd_service_home", cmd_home_, std::string("home"));
kinematic_mode_ = 1;
ROS_INFO("SummitXLPad num_of_buttons_ = %d, zoom = %d, %d", num_of_buttons_, ptz_zoom_wide_, ptz_zoom_tele_);
for(int i = 0; i < num_of_buttons_; i++){
bRegisteredButtonEvent[i] = false;
ROS_INFO("bREG %d", i);
}
for(int i = 0; i < 3; i++){
bRegisteredDirectionalArrows[i] = false;
}
/*ROS_INFO("Service I/O = [%s]", cmd_service_io_.c_str());
ROS_INFO("Topic PTZ = [%s]", cmd_topic_ptz_.c_str());
ROS_INFO("Service I/O = [%s]", cmd_topic_vel_.c_str());
ROS_INFO("Axis linear = %d", linear_);
ROS_INFO("Axis angular = %d", angular_);
ROS_INFO("Scale angular = %d", a_scale_);
ROS_INFO("Deadman button = %d", dead_man_button_);
ROS_INFO("OUTPUT1 button %d", button_output_1_);
ROS_INFO("OUTPUT2 button %d", button_output_2_);
ROS_INFO("OUTPUT1 button %d", button_output_1_);
ROS_INFO("OUTPUT2 button %d", button_output_2_);*/
// Publish through the node handle Twist type messages to the guardian_controller/command topic
vel_pub_ = nh_.advertise<geometry_msgs::Twist>(cmd_topic_vel_, 1);
// Publishes msgs for the pant-tilt cam
ptz_pub_ = nh_.advertise<robotnik_msgs::ptz>(cmd_topic_ptz_, 1);
// Listen through the node handle sensor_msgs::Joy messages from joystick
// (these are the references that we will sent to summit_xl_controller/command)
pad_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &SummitXLPad::padCallback, this);
// Request service to activate / deactivate digital I/O
set_digital_outputs_client_ = nh_.serviceClient<robotnik_msgs::set_digital_output>(cmd_service_io_);
bOutput1 = bOutput2 = false;
// Request service to set kinematic mode
setKinematicMode = nh_.serviceClient<robotnik_msgs::set_mode>(cmd_set_mode_);
// Request service to start homing
doHome = nh_.serviceClient<robotnik_msgs::home>(cmd_home_);
// Diagnostics
updater_pad.setHardwareID("None");
// Topics freq control
min_freq_command = min_freq_joy = 5.0;
max_freq_command = max_freq_joy = 50.0;
sus_joy_freq = new diagnostic_updater::HeaderlessTopicDiagnostic("/joy", updater_pad,
diagnostic_updater::FrequencyStatusParam(&min_freq_joy, &max_freq_joy, 0.1, 10));
pub_command_freq = new diagnostic_updater::HeaderlessTopicDiagnostic(cmd_topic_vel_.c_str(), updater_pad,
diagnostic_updater::FrequencyStatusParam(&min_freq_command, &max_freq_command, 0.1, 10));
bEnable = false; // Communication flag disabled by default
last_command_ = true;
if(pad_type_=="ps4" || pad_type_=="logitechf710")
ptz_control_by_axes_ = true;
else
ptz_control_by_axes_ = false;
}
/*
* \brief Updates the diagnostic component. Diagnostics
*
*/
void SummitXLPad::Update(){
updater_pad.update();
}
void SummitXLPad::padCallback(const sensor_msgs::Joy::ConstPtr& joy)
{
geometry_msgs::Twist vel;
robotnik_msgs::ptz ptz;
bool ptzEvent = false;
vel.linear.x = 0.0;
vel.linear.y = 0.0;
vel.linear.z = 0.0;
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
bEnable = (joy->buttons[dead_man_button_] == 1);
// Actions dependant on dead-man button
if (joy->buttons[dead_man_button_] == 1) {
//ROS_ERROR("SummitXLPad::padCallback: DEADMAN button %d", dead_man_button_);
//Set the current velocity level
if ( joy->buttons[speed_down_button_] == 1 ){
if(!bRegisteredButtonEvent[speed_down_button_])
if(current_vel > 0.1){
current_vel = current_vel - 0.1;
bRegisteredButtonEvent[speed_down_button_] = true;
ROS_INFO("Velocity: %f%%", current_vel*100.0);
char buf[50]="\0";
int percent = (int) (current_vel*100.0);
sprintf(buf," %d percent", percent);
// sc.say(buf);
}
}else{
bRegisteredButtonEvent[speed_down_button_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPEED DOWN button %d", speed_down_button_);
if (joy->buttons[speed_up_button_] == 1){
if(!bRegisteredButtonEvent[speed_up_button_])
if(current_vel < 0.9){
current_vel = current_vel + 0.1;
bRegisteredButtonEvent[speed_up_button_] = true;
ROS_INFO("Velocity: %f%%", current_vel*100.0);
char buf[50]="\0";
int percent = (int) (current_vel*100.0);
sprintf(buf," %d percent", percent);
// sc.say(buf);
}
}else{
bRegisteredButtonEvent[speed_up_button_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPEED UP button %d", speed_up_button_);
vel.linear.x = current_vel*l_scale_*joy->axes[linear_x_];
vel.linear.y = current_vel*l_scale_*joy->axes[linear_y_];
//ROS_ERROR("SummitXLPad::padCallback: Passed linear axes");
if(joystick_dead_zone_=="true")
{
// limit scissor movement or robot turning (they are in the same joystick)
if(joy->axes[angular_] == 1.0 || joy->axes[angular_] == -1.0) // if robot turning
{
// Same angular velocity for the three axis
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = 0.0;
}
else if (joy->axes[linear_z_] == 1.0 || joy->axes[linear_z_] == -1.0) // if scissor moving
{
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement
// limit robot turn
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
}
else
{
// Same angular velocity for the three axis
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_]; // scissor movement
}
}
else // no dead zone
{
vel.angular.x = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.y = current_vel*(a_scale_*joy->axes[angular_]);
vel.angular.z = current_vel*(a_scale_*joy->axes[angular_]);
vel.linear.z = current_vel*l_scale_z_*joy->axes[linear_z_];
}
//ROS_ERROR("SummitXLPad::padCallback: Passed joystick deadzone ifelse");
// LIGHTS
if (joy->buttons[button_output_1_] == 1) {
if(!bRegisteredButtonEvent[button_output_1_]){
//ROS_INFO("SummitXLPad::padCallback: OUTPUT1 button %d", button_output_1_);
robotnik_msgs::set_digital_output write_do_srv;
write_do_srv.request.output = output_1_;
bOutput1=!bOutput1;
write_do_srv.request.value = bOutput1;
if(bEnable){
set_digital_outputs_client_.call( write_do_srv );
bRegisteredButtonEvent[button_output_1_] = true;
}
}
}else{
bRegisteredButtonEvent[button_output_1_] = false;
}
if (joy->buttons[button_output_2_] == 1) {
if(!bRegisteredButtonEvent[button_output_2_]){
//ROS_INFO("SummitXLPad::padCallback: OUTPUT2 button %d", button_output_2_);
robotnik_msgs::set_digital_output write_do_srv;
write_do_srv.request.output = output_2_;
bOutput2=!bOutput2;
write_do_srv.request.value = bOutput2;
if(bEnable){
set_digital_outputs_client_.call( write_do_srv );
bRegisteredButtonEvent[button_output_2_] = true;
}
}
}else{
bRegisteredButtonEvent[button_output_2_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed LIGHTS");
// HOMING SERVICE
if (joy->buttons[button_home_] == 1) {
if (!bRegisteredButtonEvent[button_home_]) {
robotnik_msgs::home home_srv;
home_srv.request.request = true;
if (bEnable) {
ROS_INFO("SummitXLPad::padCallback - Home");
doHome.call( home_srv );
bRegisteredButtonEvent[button_home_] = true;
}
}
// Use this button also to block robot motion while moving the scissor
vel.angular.x = 0.0;
vel.angular.y = 0.0;
vel.angular.z = 0.0;
vel.linear.x = 0.0;
vel.linear.y = 0.0;
}
else {
bRegisteredButtonEvent[button_home_]=false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed HOME BUTTON");
// PTZ
ptz.pan = ptz.tilt = ptz.zoom = 0.0;
ptz.relative = true;
if(ptz_control_by_axes_)
{
if (joy->axes[ptz_tilt_up_] == -1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP]){
ptz.tilt = tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT UP");
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_UP] = false;
}
if (joy->axes[ptz_tilt_down_] == 1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN]){
ptz.tilt = -tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT DOWN");
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_TILT_DOWN] = false;
}
if (joy->axes[ptz_pan_left_] == -1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT]){
ptz.pan = -pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN LEFT");
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_LEFT] = false;
}
if (joy->axes[ptz_pan_right_] == 1.0) {
if(!bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT]){
ptz.pan = pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN RIGHT");
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = true;
ptzEvent = true;
}
}else{
bRegisteredDirectionalArrows[AXIS_PTZ_PAN_RIGHT] = false;
}
}else{
//ROS_ERROR("SummitXLPad::padCallback: INSIDE ELSE PTZ PAD_TYPE");
// TILT-MOVEMENTS (RELATIVE POS)
if (joy->buttons[ptz_tilt_up_] == 1) {
if(!bRegisteredButtonEvent[ptz_tilt_up_]){
ptz.tilt = tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT UP");
bRegisteredButtonEvent[ptz_tilt_up_] = true;
ptzEvent = true;
}
}else {
bRegisteredButtonEvent[ptz_tilt_up_] = false;
}
if (joy->buttons[ptz_tilt_down_] == 1) {
if(!bRegisteredButtonEvent[ptz_tilt_down_]){
ptz.tilt = -tilt_increment_;
//ROS_INFO("SummitXLPad::padCallback: TILT DOWN");
bRegisteredButtonEvent[ptz_tilt_down_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_tilt_down_] = false;
}
// PAN-MOVEMENTS (RELATIVE POS)
if (joy->buttons[ptz_pan_left_] == 1) {
if(!bRegisteredButtonEvent[ptz_pan_left_]){
ptz.pan = -pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN LEFT");
bRegisteredButtonEvent[ptz_pan_left_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_pan_left_] = false;
}
if (joy->buttons[ptz_pan_right_] == 1) {
if(!bRegisteredButtonEvent[ptz_pan_right_]){
ptz.pan = pan_increment_;
//ROS_INFO("SummitXLPad::padCallback: PAN RIGHT");
bRegisteredButtonEvent[ptz_pan_right_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_pan_right_] = false;
}
}
// ZOOM Settings (RELATIVE)
if (joy->buttons[ptz_zoom_wide_] == 1) {
if(!bRegisteredButtonEvent[ptz_zoom_wide_]){
ptz.zoom = -zoom_increment_;
//ROS_INFO("SummitXLPad::padCallback: ZOOM WIDe");
bRegisteredButtonEvent[ptz_zoom_wide_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_zoom_wide_] = false;
}
if (joy->buttons[ptz_zoom_tele_] == 1) {
if(!bRegisteredButtonEvent[ptz_zoom_tele_]){
ptz.zoom = zoom_increment_;
//ROS_INFO("SummitXLPad::padCallback: ZOOM TELE");
bRegisteredButtonEvent[ptz_zoom_tele_] = true;
ptzEvent = true;
}
}else{
bRegisteredButtonEvent[ptz_zoom_tele_] = false;
}
if (joy->buttons[button_kinematic_mode_] == 1) {
if(!bRegisteredButtonEvent[button_kinematic_mode_]){
// Define mode (inc) - still coupled
kinematic_mode_ += 1;
if (kinematic_mode_ > 2) kinematic_mode_ = 1;
ROS_INFO("SummitXLJoy::joyCallback: Kinematic Mode %d ", kinematic_mode_);
// Call service
robotnik_msgs::set_mode set_mode_srv;
set_mode_srv.request.mode = kinematic_mode_;
setKinematicMode.call( set_mode_srv );
bRegisteredButtonEvent[button_kinematic_mode_] = true;
}
}else{
bRegisteredButtonEvent[button_kinematic_mode_] = false;
}
//ROS_ERROR("SummitXLPad::padCallback: Passed SPHERE CAM and KINEMATIC MODE");
}
else {
vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0;
vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0;
}
sus_joy_freq->tick(); // Ticks the reception of joy events
// Publish
// Only publishes if it's enabled
if(bEnable){
if (ptzEvent) ptz_pub_.publish(ptz);
vel_pub_.publish(vel);
pub_command_freq->tick();
last_command_ = true;
}
if(!bEnable && last_command_){
if (ptzEvent) ptz_pub_.publish(ptz);
vel.angular.x = 0.0; vel.angular.y = 0.0; vel.angular.z = 0.0;
vel.linear.x = 0.0; vel.linear.y = 0.0; vel.linear.z = 0.0;
vel_pub_.publish(vel);
pub_command_freq->tick();
last_command_ = false;
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "summit_xl_pad");
SummitXLPad summit_xl_pad;
ros::Rate r(50.0);
while( ros::ok() ){
// UPDATING DIAGNOSTICS
summit_xl_pad.Update();
ros::spinOnce();
r.sleep();
}
}
|
#include <string>
#include <sstream>
#include <vector>
#include "commands.h"
#include "RamCloud.h"
#include "ClientException.h"
std::string unsupportedCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
std::string res("+Unsupported command.\r\n");
return res;
}
std::string getCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
std::stringstream ss;
ss << "$" << buffer.size();
const char* data = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
ss.write(data, buffer.size());
ss << "\r\n";
return ss.str();
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
}
std::string incrCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
try {
uint64_t newValue = client->incrementInt64(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), 1);
std::stringstream ss;
ss << ":" << newValue;
ss << "\r\n";
return ss.str();
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
}
std::string setCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
client->write(tableId, (*argv)[1].c_str(),
(*argv)[1].length(),
(*argv)[2].c_str());
return std::string("+OK\r\n");
}
std::string lpushCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Arg validation.
if ((*argv)[2].length() >= (1 << (sizeof(uint16_t)*8))) {
std::string res("+List element must be less than 64KB in size.\r\n");
return res;
}
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
bool listExists = true;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
listExists = false;
}
// Append new element to list.
size_t newListSize;
uint16_t elementLength = (uint16_t)(*argv)[2].length();
if (listExists) {
newListSize = sizeof(uint16_t) + elementLength + buffer.size();
} else {
newListSize = sizeof(uint16_t) + elementLength;
}
char* newList = (char*)malloc(newListSize);
memcpy(newList, &elementLength, sizeof(uint16_t));
memcpy(newList + sizeof(uint16_t), (*argv)[2].c_str(), elementLength);
if (listExists) {
const char* oldList = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
memcpy(newList + sizeof(uint16_t) + elementLength, oldList, buffer.size());
}
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
// Count number of elements in the new list.
uint32_t pos = 0;
uint32_t count = 0;
while (pos < newListSize) {
count++;
uint16_t len = *(uint16_t*)(newList + pos);
pos += sizeof(uint16_t) + len;
}
std::ostringstream oss;
oss << ":" << count << "\r\n";
return oss.str();
}
std::string rpushCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Arg validation.
if ((*argv)[2].length() >= (1 << (sizeof(uint16_t)*8))) {
std::string res("+List element must be less than 64KB in size.\r\n");
return res;
}
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
bool listExists = true;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
listExists = false;
}
// Append new element to list.
size_t newListSize;
uint16_t elementLength = (uint16_t)(*argv)[2].length();
char* newList;
if (listExists) {
newListSize = sizeof(uint16_t) + elementLength + buffer.size();
newList = (char*)malloc(newListSize);
const char* oldList = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
memcpy(newList, oldList, buffer.size());
memcpy(newList + buffer.size(), &elementLength, sizeof(uint16_t));
memcpy(newList + buffer.size() + sizeof(uint16_t), (*argv)[2].c_str(),
elementLength);
} else {
newListSize = sizeof(uint16_t) + elementLength;
newList = (char*)malloc(newListSize);
memcpy(newList, &elementLength, sizeof(uint16_t));
memcpy(newList + sizeof(uint16_t), (*argv)[2].c_str(), elementLength);
}
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
// Count number of elements in the new list.
uint32_t pos = 0;
uint32_t count = 0;
printf("newListSize: %d\n", newListSize);
while (pos < newListSize) {
count++;
uint16_t len = *(uint16_t*)(newList + pos);
pos += sizeof(uint16_t) + len;
}
std::ostringstream oss;
oss << ":" << count << "\r\n";
return oss.str();
}
std::string lpopCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Read out list.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
return std::string("+Unknown key.");
}
if (buffer.size() == 0) {
return std::string("$-1\r\n");
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
uint16_t len = *(uint16_t*)(list);
std::string element(list + sizeof(uint16_t), len);
size_t newListSize = buffer.size() - sizeof(uint16_t) - len;
char* newList = (char*)malloc(newListSize);
memcpy(newList, list + sizeof(uint16_t) + len, newListSize);
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
std::ostringstream oss;
oss << "+" << element << "\r\n";
return oss.str();
}
std::string rpopCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Read out list.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
return std::string("+Unknown key.");
}
if (buffer.size() == 0) {
return std::string("$-1\r\n");
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
// Find last element of the list.
uint32_t pos = 0;
uint16_t len;
while (true) {
len = *(uint16_t*)(list + pos);
if (pos + sizeof(uint16_t) + len == buffer.size()) {
break;
}
pos += sizeof(uint16_t) + len;
}
std::string element(list + pos + sizeof(uint16_t), len);
size_t newListSize = buffer.size() - sizeof(uint16_t) - len;
char* newList = (char*)malloc(newListSize);
memcpy(newList, list, newListSize);
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
std::ostringstream oss;
oss << "+" << element << "\r\n";
return oss.str();
}
std::string lrangeCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
int start = atoi((*argv)[2].c_str());
int end = atoi((*argv)[3].c_str());
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
// Parse the elements.
uint32_t pos = 0;
std::vector<std::string> elements;
while (pos < buffer.size()) {
uint16_t len = *(uint16_t*)(list + pos);
pos += sizeof(uint16_t);
elements.emplace_back(list + pos, len);
pos += len;
}
uint32_t startIndex;
if (start < 0) {
startIndex = elements.size() + start;
} else {
startIndex = start;
}
uint32_t endIndex;
if (end < 0) {
endIndex = elements.size() + end;
} else {
if (end >= elements.size()) {
endIndex = elements.size() - 1;
}
}
// Generate return message.
std::ostringstream oss;
oss << "*" << elements.size() << "\r\n";
uint32_t count = 0;
for(auto const& e: elements) {
if (count >= start && count <= end) {
oss << "$" << e.length() << "\r\n" << e << "\r\n";
}
count++;
}
return oss.str();
}
Fix couple of bugs.
1) Freeing in the wrong place.
2) Incorrect calc. for num. elements in lrangeCommand.
#include <string>
#include <sstream>
#include <vector>
#include "commands.h"
#include "RamCloud.h"
#include "ClientException.h"
std::string unsupportedCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
std::string res("+Unsupported command.\r\n");
return res;
}
std::string getCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
std::stringstream ss;
ss << "$" << buffer.size();
const char* data = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
ss.write(data, buffer.size());
ss << "\r\n";
return ss.str();
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
}
std::string incrCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
try {
uint64_t newValue = client->incrementInt64(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), 1);
std::stringstream ss;
ss << ":" << newValue;
ss << "\r\n";
return ss.str();
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
}
std::string setCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
client->write(tableId, (*argv)[1].c_str(),
(*argv)[1].length(),
(*argv)[2].c_str());
return std::string("+OK\r\n");
}
std::string lpushCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Arg validation.
if ((*argv)[2].length() >= (1 << (sizeof(uint16_t)*8))) {
std::string res("+List element must be less than 64KB in size.\r\n");
return res;
}
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
bool listExists = true;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
listExists = false;
}
// Append new element to list.
size_t newListSize;
uint16_t elementLength = (uint16_t)(*argv)[2].length();
if (listExists) {
newListSize = sizeof(uint16_t) + elementLength + buffer.size();
} else {
newListSize = sizeof(uint16_t) + elementLength;
}
char* newList = (char*)malloc(newListSize);
memcpy(newList, &elementLength, sizeof(uint16_t));
memcpy(newList + sizeof(uint16_t), (*argv)[2].c_str(), elementLength);
if (listExists) {
const char* oldList = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
memcpy(newList + sizeof(uint16_t) + elementLength, oldList, buffer.size());
}
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
// Count number of elements in the new list.
uint32_t pos = 0;
uint32_t count = 0;
while (pos < newListSize) {
count++;
uint16_t len = *(uint16_t*)(newList + pos);
pos += sizeof(uint16_t) + len;
}
free(newList);
std::ostringstream oss;
oss << ":" << count << "\r\n";
return oss.str();
}
std::string rpushCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Arg validation.
if ((*argv)[2].length() >= (1 << (sizeof(uint16_t)*8))) {
std::string res("+List element must be less than 64KB in size.\r\n");
return res;
}
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
bool listExists = true;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
listExists = false;
}
// Append new element to list.
size_t newListSize;
uint16_t elementLength = (uint16_t)(*argv)[2].length();
char* newList;
if (listExists) {
newListSize = sizeof(uint16_t) + elementLength + buffer.size();
newList = (char*)malloc(newListSize);
const char* oldList = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
memcpy(newList, oldList, buffer.size());
memcpy(newList + buffer.size(), &elementLength, sizeof(uint16_t));
memcpy(newList + buffer.size() + sizeof(uint16_t), (*argv)[2].c_str(),
elementLength);
} else {
newListSize = sizeof(uint16_t) + elementLength;
newList = (char*)malloc(newListSize);
memcpy(newList, &elementLength, sizeof(uint16_t));
memcpy(newList + sizeof(uint16_t), (*argv)[2].c_str(), elementLength);
}
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
// Count number of elements in the new list.
uint32_t pos = 0;
uint32_t count = 0;
printf("newListSize: %d\n", newListSize);
while (pos < newListSize) {
count++;
uint16_t len = *(uint16_t*)(newList + pos);
pos += sizeof(uint16_t) + len;
}
free(newList);
std::ostringstream oss;
oss << ":" << count << "\r\n";
return oss.str();
}
std::string lpopCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Read out list.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
return std::string("+Unknown key.");
}
if (buffer.size() == 0) {
return std::string("$-1\r\n");
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
uint16_t len = *(uint16_t*)(list);
std::string element(list + sizeof(uint16_t), len);
size_t newListSize = buffer.size() - sizeof(uint16_t) - len;
char* newList = (char*)malloc(newListSize);
memcpy(newList, list + sizeof(uint16_t) + len, newListSize);
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
std::ostringstream oss;
oss << "+" << element << "\r\n";
return oss.str();
}
std::string rpopCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
// Read out list.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
return std::string("+Unknown key.");
}
if (buffer.size() == 0) {
return std::string("$-1\r\n");
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
// Find last element of the list.
uint32_t pos = 0;
uint16_t len;
while (true) {
len = *(uint16_t*)(list + pos);
if (pos + sizeof(uint16_t) + len == buffer.size()) {
break;
}
pos += sizeof(uint16_t) + len;
}
std::string element(list + pos + sizeof(uint16_t), len);
size_t newListSize = buffer.size() - sizeof(uint16_t) - len;
char* newList = (char*)malloc(newListSize);
memcpy(newList, list, newListSize);
// Write new list.
client->write(tableId,
(*argv)[1].c_str(),
(*argv)[1].length(),
newList,
newListSize);
free(newList);
std::ostringstream oss;
oss << "+" << element << "\r\n";
return oss.str();
}
std::string lrangeCommand(RAMCloud::RamCloud *client,
uint64_t tableId,
std::vector<std::string> *argv) {
int start = atoi((*argv)[2].c_str());
int end = atoi((*argv)[3].c_str());
// Read out old list, if it exists.
RAMCloud::Buffer buffer;
try {
client->read(tableId, (*argv)[1].c_str(),
(*argv)[1].length(), &buffer);
} catch (RAMCloud::ObjectDoesntExistException& e) {
std::string res("+Unknown key.\r\n");
return res;
}
const char* list = static_cast<const char*>(buffer.getRange(0,
buffer.size()));
// Parse the elements.
uint32_t pos = 0;
std::vector<std::string> elements;
while (pos < buffer.size()) {
uint16_t len = *(uint16_t*)(list + pos);
pos += sizeof(uint16_t);
elements.emplace_back(list + pos, len);
pos += len;
}
uint32_t startIndex;
if (start < 0) {
startIndex = elements.size() + start;
} else {
startIndex = start;
}
uint32_t endIndex;
if (end < 0) {
endIndex = elements.size() + end;
} else {
if (end >= elements.size()) {
endIndex = elements.size() - 1;
}
}
// Generate return message.
std::ostringstream oss;
oss << "*" << (endIndex - startIndex + 1) << "\r\n";
uint32_t count = 0;
for(auto const& e: elements) {
if (count >= start && count <= end) {
oss << "$" << e.length() << "\r\n" << e << "\r\n";
}
count++;
}
return oss.str();
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataReader.h"
#include "vtkBitArray.h"
#include "vtkByteSwap.h"
#include "vtkCellData.h"
#include "vtkCharArray.h"
#include "vtkDoubleArray.h"
#include "vtkErrorCode.h"
#include "vtkFieldData.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkLongArray.h"
#include "vtkLookupTable.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkRectilinearGrid.h"
#include "vtkShortArray.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkUnsignedShortArray.h"
#include <ctype.h>
#include <sys/stat.h>
vtkCxxRevisionMacro(vtkDataReader, "1.133");
vtkStandardNewMacro(vtkDataReader);
vtkCxxSetObjectMacro(vtkDataReader, InputArray, vtkCharArray);
// this undef is required on the hp. vtkMutexLock ends up including
// /usr/inclue/dce/cma_ux.h which has the gall to #define read as cma_read
#ifdef read
#undef read
#endif
// Construct object.
vtkDataReader::vtkDataReader()
{
this->FileType = VTK_ASCII;
this->FileName = NULL;
this->ScalarsName = NULL;
this->VectorsName = NULL;
this->TensorsName = NULL;
this->NormalsName = NULL;
this->TCoordsName = NULL;
this->LookupTableName = NULL;
this->FieldDataName = NULL;
this->ScalarLut = NULL;
this->InputString = NULL;
this->InputStringLength = 0;
this->InputStringPos = 0;
this->ReadFromInputString = 0;
this->IS = NULL;
this->Header = NULL;
this->InputArray = 0;
this->NumberOfScalarsInFile = 0;
this->ScalarsNameInFile = NULL;
this->ScalarsNameAllocSize = 0;
this->NumberOfVectorsInFile = 0;
this->VectorsNameInFile = NULL;
this->VectorsNameAllocSize = 0;
this->NumberOfTensorsInFile = 0;
this->TensorsNameInFile = NULL;
this->TensorsNameAllocSize = 0;
this->NumberOfTCoordsInFile = 0;
this->TCoordsNameInFile = NULL;
this->TCoordsNameAllocSize = 0;
this->NumberOfNormalsInFile = 0;
this->NormalsNameInFile = NULL;
this->NormalsNameAllocSize = 0;
this->NumberOfFieldDataInFile = 0;
this->FieldDataNameInFile = NULL;
this->FieldDataNameAllocSize = 0;
this->ReadAllScalars = 0;
this->ReadAllVectors = 0;
this->ReadAllNormals = 0;
this->ReadAllTensors = 0;
this->ReadAllColorScalars = 0;
this->ReadAllTCoords = 0;
this->ReadAllFields = 0;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
vtkDataReader::~vtkDataReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
if (this->ScalarsName)
{
delete [] this->ScalarsName;
}
if (this->VectorsName)
{
delete [] this->VectorsName;
}
if (this->TensorsName)
{
delete [] this->TensorsName;
}
if (this->NormalsName)
{
delete [] this->NormalsName;
}
if (this->TCoordsName)
{
delete [] this->TCoordsName;
}
if (this->LookupTableName)
{
delete [] this->LookupTableName;
}
if (this->FieldDataName)
{
delete [] this->FieldDataName;
}
if (this->ScalarLut)
{
delete [] this->ScalarLut;
}
if (this->InputString)
{
delete [] this->InputString;
}
if (this->Header)
{
delete [] this->Header;
}
this->SetInputArray(0);
this->InitializeCharacteristics();
if ( this->IS )
{
delete this->IS;
}
}
void vtkDataReader::SetInputString(const char *in)
{
if (in != NULL)
{
this->SetInputString(in, static_cast<int>(strlen(in)));
}
else
{
if (this->InputString)
{
delete [] this->InputString;
}
this->InputString = NULL;
}
}
void vtkDataReader::SetBinaryInputString(const char *in, int len)
{
this->SetInputString(in,len);
}
void vtkDataReader::SetInputString(const char *in, int len)
{
if (this->Debug)
{
vtkDebugMacro(<< "setting InputString to " << in );
}
if (this->InputString && in && strncmp(in, this->InputString, len) == 0)
{
return;
}
if (this->InputString)
{
delete [] this->InputString;
}
if (in)
{
this->InputString = new char[len];
memcpy(this->InputString,in,len);
this->InputStringLength = len;
}
else
{
this->InputString = NULL;
this->InputStringLength = 0;
}
this->Modified();
}
// Internal function to read in a line up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadLine(char result[256])
{
this->IS->getline(result,256);
if (this->IS->fail())
{
if (this->IS->eof())
{
return 0;
}
if (this->IS->gcount() == 255)
{
// Read 256 chars; ignoring the rest of the line.
this->IS->clear();
this->IS->ignore(VTK_INT_MAX, '\n');
}
}
return 1;
}
// Internal function to read in a string up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadString(char result[256])
{
this->IS->width(256);
*this->IS >> result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
// Internal function to read in an integer value.
// Returns zero if there was an error.
int vtkDataReader::Read(char *result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (char) intData;
return 1;
}
int vtkDataReader::Read(unsigned char *result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (unsigned char) intData;
return 1;
}
int vtkDataReader::Read(short *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned short *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(int *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned int *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(long *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned long *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(float *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(double *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
// Open a vtk data file. Returns zero if error.
int vtkDataReader::OpenVTKFile()
{
if (this->ReadFromInputString)
{
if (this->InputArray)
{
vtkDebugMacro(<< "Reading from InputArray");
this->IS = new istrstream(this->InputArray->GetPointer(0),
this->InputArray->GetNumberOfTuples()*
this->InputArray->GetNumberOfComponents());
return 1;
}
else if (this->InputString)
{
vtkDebugMacro(<< "Reading from InputString");
this->IS = new istrstream(this->InputString, this->InputStringLength);
return 1;
}
}
else
{
vtkDebugMacro(<< "Opening vtk file");
if ( !this->FileName || (strlen(this->FileName) == 0))
{
vtkErrorMacro(<< "No file specified!");
this->SetErrorCode( vtkErrorCode::NoFileNameError );
return 0;
}
// first make sure the file exists, this prevents an empty file from
// being created on older compilers
struct stat fs;
if (stat(this->FileName, &fs) != 0)
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
this->IS = new ifstream(this->FileName, ios::in);
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
delete this->IS;
this->IS = NULL;
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
return 1;
}
return 0;
}
// Read the header of a vtk data file. Returns 0 if error.
int vtkDataReader::ReadHeader()
{
char line[256];
vtkDebugMacro(<< "Reading vtk file header");
//
// read header
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<<"Premature EOF reading first line! " << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( strncmp ("# vtk DataFile Version", line, 20) )
{
vtkErrorMacro(<< "Unrecognized file type: "<< line << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::UnrecognizedFileTypeError );
return 0;
}
//
// read title
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<<"Premature EOF reading title! " << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if (this->Header)
{
delete [] this->Header;
}
this->Header = new char[strlen(line) + 1];
strcpy (this->Header, line);
vtkDebugMacro(<< "Reading vtk file entitled: " << line);
//
// read type
//
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Premature EOF reading file type!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( !strncmp(this->LowerCase(line), "ascii", 5) )
{
this->FileType = VTK_ASCII;
}
else if ( !strncmp(line, "binary", 6) )
{
this->FileType = VTK_BINARY;
}
else
{
vtkErrorMacro(<< "Unrecognized file type: "<< line << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->FileType = 0;
this->SetErrorCode( vtkErrorCode::UnrecognizedFileTypeError );
return 0;
}
// if this is a binary file we need to make sure that we opened it
// as a binary file.
if (this->FileType == VTK_BINARY && this->ReadFromInputString == 0)
{
vtkDebugMacro(<< "Opening vtk file as binary");
delete this->IS;
this->IS = 0;
#ifdef _WIN32
this->IS = new ifstream(this->FileName, ios::in | ios::binary);
#else
this->IS = new ifstream(this->FileName, ios::in);
#endif
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
delete this->IS;
this->IS = NULL;
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
// read up to the same point in the file
this->ReadLine(line);
this->ReadLine(line);
this->ReadString(line);
}
float progress=this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
int vtkDataReader::IsFileValid(const char *dstype)
{
char line[1024];
if (!dstype)
{
return 0;
}
if (!this->OpenVTKFile() || !this->ReadHeader())
{
return 0;
}
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( !strncmp(this->LowerCase(line),"dataset",(unsigned long)7) )
{
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if (strncmp(this->LowerCase(line),dstype,strlen(dstype)))
{
this->CloseVTKFile ();
return 0;
}
// everything looks good
this->CloseVTKFile();
return 1;
}
return 0;
}
// Read the cell data of a vtk data file. The number of cells (from the
// dataset) must match the number of cells defined in cell attributes (unless
// no geometry was defined).
int vtkDataReader::ReadCellData(vtkDataSet *ds, int numCells)
{
char line[256];
vtkDataSetAttributes *a=ds->GetCellData();
vtkDebugMacro(<< "Reading vtk cell data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if ( ! strncmp(this->LowerCase(line), "scalars", 7) )
{
if ( ! this->ReadScalarData(a, numCells) )
{
return 0;
}
}
//
// read vector data
//
else if ( ! strncmp(line, "vectors", 7) )
{
if ( ! this->ReadVectorData(a, numCells) )
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if ( ! strncmp(line, "tensors", 7) )
{
if ( ! this->ReadTensorData(a, numCells) )
{
return 0;
}
}
//
// read normals data
//
else if ( ! strncmp(line, "normals", 7) )
{
if ( ! this->ReadNormalData(a, numCells) )
{
return 0;
}
}
//
// read texture coordinates data
//
else if ( ! strncmp(line, "texture_coordinates", 19) )
{
if ( ! this->ReadTCoordsData(a, numCells) )
{
return 0;
}
}
//
// read color scalars data
//
else if ( ! strncmp(line, "color_scalars", 13) )
{
if ( ! this->ReadCoScalarData(a, numCells) )
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if ( ! strncmp(line, "lookup_table", 12) )
{
if ( ! this->ReadLutData(a) )
{
return 0;
}
}
//
// read field of data
//
else if ( ! strncmp(line, "field", 5) )
{
vtkFieldData *f;
if ( ! (f=this->ReadFieldData()) )
{
return 0;
}
for(int i=0; i<f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetArray(i));
}
f->Delete();
}
//
// maybe bumped into point data
//
else if ( ! strncmp(line, "point_data", 10) )
{
int npts;
if (!this->Read(&npts))
{
vtkErrorMacro(<<"Cannot read point data!");
return 0;
}
this->ReadPointData(ds, npts);
}
else
{
vtkErrorMacro(<< "Unsupported cell attribute type: " << line
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the point data of a vtk data file. The number of points (from the
// dataset) must match the number of points defined in point attributes (unless
// no geometry was defined).
int vtkDataReader::ReadPointData(vtkDataSet *ds, int numPts)
{
char line[256];
vtkDataSetAttributes *a=ds->GetPointData();
vtkDebugMacro(<< "Reading vtk point data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if ( ! strncmp(this->LowerCase(line), "scalars", 7) )
{
if ( ! this->ReadScalarData(a, numPts) )
{
return 0;
}
}
//
// read vector data
//
else if ( ! strncmp(line, "vectors", 7) )
{
if ( ! this->ReadVectorData(a, numPts) )
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if ( ! strncmp(line, "tensors", 7) )
{
if ( ! this->ReadTensorData(a, numPts) )
{
return 0;
}
}
//
// read normals data
//
else if ( ! strncmp(line, "normals", 7) )
{
if ( ! this->ReadNormalData(a, numPts) )
{
return 0;
}
}
//
// read texture coordinates data
//
else if ( ! strncmp(line, "texture_coordinates", 19) )
{
if ( ! this->ReadTCoordsData(a, numPts) )
{
return 0;
}
}
//
// read color scalars data
//
else if ( ! strncmp(line, "color_scalars", 13) )
{
if ( ! this->ReadCoScalarData(a, numPts) )
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if ( ! strncmp(line, "lookup_table", 12) )
{
if ( ! this->ReadLutData(a) )
{
return 0;
}
}
//
// read field of data
//
else if ( ! strncmp(line, "field", 5) )
{
vtkFieldData *f;
if ( ! (f=this->ReadFieldData()) )
{
return 0;
}
for(int i=0; i<f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetArray(i));
}
f->Delete();
}
//
// maybe bumped into cell data
//
else if ( ! strncmp(line, "cell_data", 9) )
{
int ncells;
if (!this->Read(&ncells))
{
vtkErrorMacro(<<"Cannot read cell data!");
return 0;
}
this->ReadCellData(ds, ncells);
}
else
{
vtkErrorMacro(<< "Unsupported point attribute type: " << line
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadBinaryData(istream *IS, T *data, int numTuples, int numComp)
{
char line[256];
// suck up newline
IS->getline(line,256);
IS->read((char *)data, sizeof(T)*numComp*numTuples);
if (IS->eof())
{
vtkGenericWarningMacro(<<"Error reading binary data!");
return 0;
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadASCIIData(vtkDataReader *self, T *data, int numTuples, int numComp)
{
int i, j;
for (i=0; i<numTuples; i++)
{
for (j=0; j<numComp; j++)
{
if ( !self->Read(data++) )
{
vtkGenericWarningMacro(<<"Error reading ascii data!");
return 0;
}
}
}
return 1;
}
// Decription:
// Read data array. Return pointer to array object if successful read;
// otherwise return NULL. Note: this method instantiates a reference counted
// object with initial count of one; proper protocol is for you to assign
// the data object and then invoke Delete() it to restore proper reference
// count.
vtkDataArray *vtkDataReader::ReadArray(const char *dataType, int numTuples, int numComp)
{
char *type=strdup(dataType);
type=this->LowerCase(type);
vtkDataArray *array;
if ( ! strncmp(type, "bit", 3) )
{
array = vtkBitArray::New();
array->SetNumberOfComponents(numComp);
unsigned char *ptr=((vtkBitArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
char line[256];
this->IS->getline(line,256);
this->IS->read((char *)ptr,sizeof(unsigned char)*(numTuples*numComp+7)/8);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary bit array!");
free(type);
return NULL;
}
}
else
{
int b;
for (int i=0; i<numTuples; i++)
{
for (int j=0; j<numComp; j++)
{
if ( !this->Read(&b) )
{
vtkErrorMacro(<<"Error reading ascii bit array! tuple: " << i << ", component: " << j);
free(type);
return NULL;
}
else
{
((vtkBitArray *)array)->SetValue(i*numComp+j,b);
}
}
}
}
}
else if ( ! strncmp(type, "char", 4) )
{
array = vtkCharArray::New();
array->SetNumberOfComponents(numComp);
char *ptr = ((vtkCharArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_char", 13) )
{
array = vtkUnsignedCharArray::New();
array->SetNumberOfComponents(numComp);
unsigned char *ptr = ((vtkUnsignedCharArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "short", 5) )
{
array = vtkShortArray::New();
array->SetNumberOfComponents(numComp);
short *ptr = ((vtkShortArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_short", 14) )
{
array = vtkUnsignedShortArray::New();
array->SetNumberOfComponents(numComp);
unsigned short *ptr = ((vtkUnsignedShortArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange((short *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "int", 3) )
{
array = vtkIntArray::New();
array->SetNumberOfComponents(numComp);
int *ptr = ((vtkIntArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_int", 12) )
{
array = vtkUnsignedIntArray::New();
array->SetNumberOfComponents(numComp);
unsigned int *ptr = ((vtkUnsignedIntArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "long", 4) )
{
array = vtkLongArray::New();
array->SetNumberOfComponents(numComp);
long *ptr = ((vtkLongArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_long", 13) )
{
array = vtkUnsignedLongArray::New();
array->SetNumberOfComponents(numComp);
unsigned long *ptr = ((vtkUnsignedLongArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "float", 5) )
{
array = vtkFloatArray::New();
array->SetNumberOfComponents(numComp);
float *ptr = ((vtkFloatArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "double", 6) )
{
array = vtkDoubleArray::New();
array->SetNumberOfComponents(numComp);
double *ptr = ((vtkDoubleArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap8BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else
{
vtkErrorMacro(<< "Unsupported data type: " << type);
free(type);
return NULL;
}
free(type);
return array;
}
// Read point coordinates. Return 0 if error.
int vtkDataReader::ReadPoints(vtkPointSet *ps, int numPts)
{
char line[256];
vtkDataArray *data;
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Cannot read points type!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
vtkPoints *points=vtkPoints::New();
points->SetData(data);
data->Delete();
ps->SetPoints(points);
points->Delete();
}
else
{
return 0;
}
vtkDebugMacro(<<"Read " << ps->GetNumberOfPoints() << " points");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read the coordinates for a rectilinear grid. The axes parameter specifies
// which coordinate axes (0,1,2) is being read.
int vtkDataReader::ReadCoordinates(vtkRectilinearGrid *rg, int axes,
int numCoords)
{
char line[256];
vtkDataArray *data;
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Cannot read coordinates type!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
data = this->ReadArray(line, numCoords, 1);
if ( !data )
{
return 0;
}
if ( axes == 0 )
{
rg->SetXCoordinates(data);
}
else if ( axes == 1 )
{
rg->SetYCoordinates(data);
}
else
{
rg->SetZCoordinates(data);
}
vtkDebugMacro(<<"Read " << data->GetNumberOfTuples() << " coordinates");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
data->Delete();
return 1;
}
// Read scalar point attributes. Return 0 if error.
int vtkDataReader::ReadScalarData(vtkDataSetAttributes *a, int numPts)
{
char line[256], name[256], key[256], tableName[256];
int skipScalar=0;
vtkDataArray *data;
int numComp = 1;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
if (!this->ReadString(key))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
// the next string could be an integer number of components or a lookup table
if (strcmp(this->LowerCase(key), "lookup_table"))
{
numComp = atoi(key);
if (numComp < 1 || !this->ReadString(key))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
if (strcmp(this->LowerCase(key), "lookup_table"))
{
vtkErrorMacro(<<"Lookup table must be specified with scalar.\n" <<
"Use \"LOOKUP_TABLE default\" to use default table.");
return 0;
}
if (!this->ReadString(tableName))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if ( a->GetScalars() != NULL || (this->ScalarsName && strcmp(name,this->ScalarsName)) )
{
skipScalar = 1;
}
else
{
this->SetScalarLut(tableName); //may be "default"
}
// Read the data
data = this->ReadArray(line, numPts, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipScalar )
{
a->SetScalars(data);
}
else if ( this->ReadAllScalars )
{
a->AddArray(data);
} data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read vector point attributes. Return 0 if error.
int vtkDataReader::ReadVectorData(vtkDataSetAttributes *a, int numPts)
{
int skipVector=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read vector data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether vector has been already read or vector name (if specified)
// matches name in file.
//
if ( a->GetVectors() != NULL || (this->VectorsName && strcmp(name,this->VectorsName)) )
{
skipVector = 1;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipVector )
{
a->SetVectors(data);
}
else if ( this->ReadAllVectors )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read normal point attributes. Return 0 if error.
int vtkDataReader::ReadNormalData(vtkDataSetAttributes *a, int numPts)
{
int skipNormal=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read normal data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether normal has been already read or normal name (if specified)
// matches name in file.
//
if ( a->GetNormals() != NULL || (this->NormalsName && strcmp(name,this->NormalsName)) )
{
skipNormal = 1;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipNormal )
{
a->SetNormals(data);
}
else if ( this->ReadAllNormals )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read tensor point attributes. Return 0 if error.
int vtkDataReader::ReadTensorData(vtkDataSetAttributes *a, int numPts)
{
int skipTensor=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read tensor data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether tensor has been already read or tensor name (if specified)
// matches name in file.
//
if ( a->GetTensors() != NULL || (this->TensorsName && strcmp(name,this->TensorsName)) )
{
skipTensor = 1;
}
data = this->ReadArray(line, numPts, 9);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipTensor )
{
a->SetTensors(data);
}
else if ( this->ReadAllTensors )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read color scalar point attributes. Return 0 if error.
int vtkDataReader::ReadCoScalarData(vtkDataSetAttributes *a, int numPts)
{
int i, j, idx, numComp, skipScalar=0;
char name[256];
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&numComp)))
{
vtkErrorMacro(<<"Cannot read color scalar data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if ( a->GetScalars() != NULL ||
(this->ScalarsName && strcmp(name,this->ScalarsName)) )
{
skipScalar = 1;
}
// handle binary different from ASCII since they are stored
// in a different format float versus uchar
if ( this->FileType == VTK_BINARY)
{
vtkUnsignedCharArray *data;
char type[14] = "unsigned_char";
data = (vtkUnsignedCharArray *)this->ReadArray(type, numPts, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipScalar )
{
a->SetScalars(data);
}
else if ( this->ReadAllColorScalars )
{
a->AddArray(data);
} data->Delete();
}
else
{
return 0;
}
}
else
{
vtkFloatArray *data;
char type[6] = "float";
data = (vtkFloatArray *)this->ReadArray(type, numPts, numComp);
if ( data != NULL )
{
if ( ! skipScalar || this->ReadAllColorScalars )
{
vtkUnsignedCharArray *scalars=vtkUnsignedCharArray::New();
scalars->SetNumberOfComponents(numComp);
scalars->SetNumberOfTuples(numPts);
scalars->SetName(name);
for (i=0; i<numPts; i++)
{
for (j=0; j<numComp; j++)
{
idx = i*numComp + j;
scalars->SetValue(idx,(unsigned char)(255.0*data->GetValue(idx)));
}
}
if ( ! skipScalar )
{
a->SetScalars(scalars);
}
else if ( this->ReadAllColorScalars )
{
a->AddArray(scalars);
} scalars->Delete();
}
data->Delete();
}
else
{
return 0;
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read texture coordinates point attributes. Return 0 if error.
int vtkDataReader::ReadTCoordsData(vtkDataSetAttributes *a, int numPts)
{
int dim;
int skipTCoord = 0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&dim) &&
this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read texture data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
if ( dim < 1 || dim > 3 )
{
vtkErrorMacro(<< "Unsupported texture coordinates dimension: " << dim
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
//
// See whether texture coords have been already read or texture coords name
// (if specified) matches name in file.
//
if ( a->GetTCoords() != NULL ||
(this->TCoordsName && strcmp(name,this->TCoordsName)) )
{
skipTCoord = 1;
}
data = this->ReadArray(line, numPts, dim);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipTCoord )
{
a->SetTCoords(data);
}
else if ( this->ReadAllTCoords )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadLutData(vtkDataSetAttributes *a)
{
int i;
int size, skipTable=0;
vtkLookupTable *lut;
unsigned char *ptr;
char line[256], name[256];
if (!(this->ReadString(name) && this->Read(&size)))
{
vtkErrorMacro(<<"Cannot read lookup table data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
if ( a->GetScalars() == NULL ||
(this->LookupTableName && strcmp(name,this->LookupTableName)) ||
(this->ScalarLut && strcmp(name,this->ScalarLut)) )
{
skipTable = 1;
}
lut = vtkLookupTable::New();
lut->Allocate(size);
ptr = lut->WritePointer(0,size);
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
this->IS->read((char *)ptr,sizeof(unsigned char)*4*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary lookup table!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
else // ascii
{
float rgba[4];
for (i=0; i<size; i++)
{
if (!(this->Read(rgba) && this->Read(rgba+1) &&
this->Read(rgba+2) && this->Read(rgba+3)))
{
vtkErrorMacro(<<"Error reading lookup table!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
lut->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]);
}
}
if ( ! skipTable )
{
a->GetScalars()->SetLookupTable(lut);
}
lut->Delete();
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadCells(int size, int *data)
{
char line[256];
int i;
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
this->IS->read((char *)data,sizeof(int)*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(data,size);
}
else // ascii
{
for (i=0; i<size; i++)
{
if (!this->Read(data+i))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
int vtkDataReader::ReadCells(int size, int *data,
int skip1, int read2, int skip3)
{
char line[256];
int i, numCellPts, junk, *tmp, *pTmp;
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
// first read all the cells as one chunk (each cell has different length).
if (skip1 == 0 && skip3 == 0)
{
tmp = data;
}
else
{
tmp = new int[size];
}
this->IS->read((char *)tmp,sizeof(int)*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(tmp,size);
if (tmp == data)
{
return 1;
}
// skip cells before the piece
pTmp = tmp;
while (skip1 > 0)
{
// the first value is the number of point ids
// skip these plus one for the number itself.
pTmp += *pTmp + 1;
--skip1;
}
// copy the cells in the piece
// (ok, I am getting criptic with the loops and increments ...)
while (read2 > 0)
{
// the first value is the number of point ids
*data++ = i = *pTmp++;
while (i-- > 0)
{
*data++ = *pTmp++;
}
--read2;
}
// delete the temporary array
delete [] tmp;
}
else // ascii
{
// skip cells before the piece
for (i=0; i<skip1; i++)
{
if (!this->Read(&numCellPts))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
// read the cells in the piece
for (i=0; i<read2; i++)
{
if (!this->Read(data))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
numCellPts = *data++;
while (numCellPts-- > 0)
{
this->Read(data++);
}
}
// skip cells after the piece
for (i=0; i<skip3; i++)
{
if (!this->Read(&numCellPts))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
vtkFieldData *vtkDataReader::ReadFieldData()
{
int i, numArrays, skipField=0;
vtkFieldData *f;
char name[256], type[256];
int numComp, numTuples;
vtkDataArray *data;
if ( !(this->ReadString(name) && this->Read(&numArrays)) )
{
vtkErrorMacro(<<"Cannot read field header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return NULL;
}
// See whether field data name (if specified)
if ( (this->FieldDataName && strcmp(name,this->FieldDataName)) )
{
skipField = 1;
}
f = vtkFieldData::New();
f->AllocateArrays(numArrays);
// Read the number of arrays specified
for (i=0; i<numArrays; i++)
{
char buffer[1024];
this->ReadString(buffer);
this->DecodeArrayName(name, buffer);
this->Read(&numComp);
this->Read(&numTuples);
this->ReadString(type);
data = this->ReadArray(type, numTuples, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipField || this->ReadAllFields )
{
f->AddArray(data);
}
data->Delete();
}
else
{
f->Delete();
return NULL;
}
}
if ( skipField && ! this->ReadAllFields )
{
f->Delete();
return NULL;
}
else
{
return f;
}
}
char *vtkDataReader::LowerCase(char *str, const size_t len)
{
size_t i;
char *s;
for ( i=0, s=str; *s != '\0' && i<len; s++,i++)
{
*s = tolower(*s);
}
return str;
}
// Close a vtk file.
void vtkDataReader::CloseVTKFile()
{
vtkDebugMacro(<<"Closing vtk file");
if ( this->IS != NULL )
{
delete this->IS;
}
this->IS = NULL;
}
void vtkDataReader::InitializeCharacteristics()
{
int i;
// Release any old stuff first
if ( this->ScalarsNameInFile )
{
for (i=0; i<this->NumberOfScalarsInFile; i++)
{
delete [] this->ScalarsNameInFile[i];
}
this->NumberOfScalarsInFile = 0;
delete [] this->ScalarsNameInFile;
this->ScalarsNameInFile = NULL;
}
if ( this->VectorsNameInFile )
{
for (i=0; i<this->NumberOfVectorsInFile; i++)
{
delete [] this->VectorsNameInFile[i];
}
this->NumberOfVectorsInFile = 0;
delete [] this->VectorsNameInFile;
this->VectorsNameInFile = NULL;
}
if ( this->TensorsNameInFile )
{
for (i=0; i<this->NumberOfTensorsInFile; i++)
{
delete [] this->TensorsNameInFile[i];
}
this->NumberOfTensorsInFile = 0;
delete [] this->TensorsNameInFile;
this->TensorsNameInFile = NULL;
}
if ( this->NormalsNameInFile )
{
for (i=0; i<this->NumberOfNormalsInFile; i++)
{
delete [] this->NormalsNameInFile[i];
}
this->NumberOfNormalsInFile = 0;
delete [] this->NormalsNameInFile;
this->NormalsNameInFile = NULL;
}
if ( this->TCoordsNameInFile )
{
for (i=0; i<this->NumberOfTCoordsInFile; i++)
{
delete [] this->TCoordsNameInFile[i];
}
this->NumberOfTCoordsInFile = 0;
delete [] this->TCoordsNameInFile;
this->TCoordsNameInFile = NULL;
}
if ( this->FieldDataNameInFile )
{
for (i=0; i<this->NumberOfFieldDataInFile; i++)
{
delete [] this->FieldDataNameInFile[i];
}
this->NumberOfFieldDataInFile = 0;
delete [] this->FieldDataNameInFile;
this->FieldDataNameInFile = NULL;
}
}
//read entire file, storing important characteristics
int vtkDataReader::CharacterizeFile()
{
if ( this->CharacteristicsTime > this->MTime )
{
return 1;
}
this->InitializeCharacteristics();
this->CharacteristicsTime.Modified();
// Open the file
if (!this->OpenVTKFile() || !this->ReadHeader())
{
return 0;
}
char line[256];
while (this->ReadLine(line))
{
this->CheckFor("scalars", line, this->NumberOfScalarsInFile,
this->ScalarsNameInFile, this->ScalarsNameAllocSize);
this->CheckFor("vectors", line, this->NumberOfVectorsInFile,
this->VectorsNameInFile, this->VectorsNameAllocSize);
this->CheckFor("tensors", line, this->NumberOfTensorsInFile,
this->TensorsNameInFile, this->TensorsNameAllocSize);
this->CheckFor("normals", line, this->NumberOfNormalsInFile,
this->NormalsNameInFile, this->NormalsNameAllocSize);
this->CheckFor("tcoords", line, this->NumberOfTCoordsInFile,
this->TCoordsNameInFile, this->TCoordsNameAllocSize);
this->CheckFor("field", line, this->NumberOfFieldDataInFile,
this->FieldDataNameInFile, this->FieldDataNameAllocSize);
}
this->CloseVTKFile ();
return 1;
}
void vtkDataReader::CheckFor(const char* name, char *line, int &num,
char** &array, int &allocSize)
{
if ( !strncmp(this->LowerCase(line, strlen(name)), name, strlen(name)) )
{
int i;
int newAllocSize;
char **newArray;
//update numbers
num++;
if ( !array )
{
allocSize = 25;
array = new char* [allocSize];
for (i=0; i<allocSize; i++)
{
array[i] = NULL;
}
}
else if ( num >= allocSize )
{
newAllocSize = 2*num;
newArray = new char* [newAllocSize];
for (i=0; i<allocSize; i++)
{
newArray[i] = array[i];
}
for (i=allocSize; i<newAllocSize; i++)
{
newArray[i] = NULL;
}
allocSize = newAllocSize;
delete [] array;
array = newArray;
}
// enter the name
char nameOfAttribute[256];
sscanf(line, "%*s %s", nameOfAttribute);
if ( nameOfAttribute )
{
array[num-1] = new char [strlen(nameOfAttribute)+1];
strcpy(array[num-1],nameOfAttribute);
}
}//found one
}
const char *vtkDataReader::GetScalarsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->ScalarsNameInFile ||
i < 0 || i >= this->NumberOfScalarsInFile )
{
return NULL;
}
else
{
return this->ScalarsNameInFile[i];
}
}
const char *vtkDataReader::GetVectorsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->VectorsNameInFile ||
i < 0 || i >= this->NumberOfVectorsInFile )
{
return NULL;
}
else
{
return this->VectorsNameInFile[i];
}
}
const char *vtkDataReader::GetTensorsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->TensorsNameInFile ||
i < 0 || i >= this->NumberOfTensorsInFile )
{
return NULL;
}
else
{
return this->TensorsNameInFile[i];
}
}
const char *vtkDataReader::GetNormalsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->NormalsNameInFile ||
i < 0 || i >= this->NumberOfNormalsInFile )
{
return NULL;
}
else
{
return this->NormalsNameInFile[i];
}
}
const char *vtkDataReader::GetTCoordsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->TCoordsNameInFile ||
i < 0 || i >= this->NumberOfTCoordsInFile )
{
return NULL;
}
else
{
return this->TCoordsNameInFile[i];
}
}
const char *vtkDataReader::GetFieldDataNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->FieldDataNameInFile ||
i < 0 || i >= this->NumberOfFieldDataInFile )
{
return NULL;
}
else
{
return this->FieldDataNameInFile[i];
}
}
int vtkDataReader::ProcessRequest(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// generate the data
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
return this->RequestData(request, inputVector, outputVector);
}
if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
{
return this->RequestUpdateExtent(request, inputVector, outputVector);
}
// execute information
if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
return this->RequestInformation(request, inputVector, outputVector);
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
void vtkDataReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
if ( this->FileType == VTK_BINARY )
{
os << indent << "File Type: BINARY\n";
}
else
{
os << indent << "File Type: ASCII\n";
}
if ( this->Header )
{
os << indent << "Header: " << this->Header << "\n";
}
else
{
os << indent << "Header: (None)\n";
}
os << indent << "ReadFromInputString: " << (this->ReadFromInputString ? "On\n" : "Off\n");
if ( this->InputString )
{
os << indent << "Input String: " << this->InputString << "\n";
}
else
{
os << indent << "Input String: (None)\n";
}
if ( this->InputArray )
{
os << indent << "Input Array: " << "\n";
this->InputArray->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Input String: (None)\n";
}
os << indent << "Input String Length: " << this->InputStringLength << endl;
if ( this->ScalarsName )
{
os << indent << "Scalars Name: " << this->ScalarsName << "\n";
}
else
{
os << indent << "Scalars Name: (None)\n";
}
os << indent << "ReadAllScalars: "
<< (this->ReadAllScalars ? "On" : "Off") << "\n";
if ( this->VectorsName )
{
os << indent << "Vectors Name: " << this->VectorsName << "\n";
}
else
{
os << indent << "Vectors Name: (None)\n";
}
os << indent << "ReadAllVectors: "
<< (this->ReadAllVectors ? "On" : "Off") << "\n";
if ( this->NormalsName )
{
os << indent << "Normals Name: " << this->NormalsName << "\n";
}
else
{
os << indent << "Normals Name: (None)\n";
}
os << indent << "ReadAllNormals: "
<< (this->ReadAllNormals ? "On" : "Off") << "\n";
if ( this->TensorsName )
{
os << indent << "Tensors Name: " << this->TensorsName << "\n";
}
else
{
os << indent << "Tensors Name: (None)\n";
}
os << indent << "ReadAllTensors: "
<< (this->ReadAllTensors ? "On" : "Off") << "\n";
if ( this->TCoordsName )
{
os << indent << "Texture Coords Name: " << this->TCoordsName << "\n";
}
else
{
os << indent << "Texture Coordinates Name: (None)\n";
}
os << indent << "ReadAllTCoords: "
<< (this->ReadAllTCoords ? "On" : "Off") << "\n";
if ( this->LookupTableName )
{
os << indent << "Lookup Table Name: " << this->LookupTableName << "\n";
}
else
{
os << indent << "Lookup Table Name: (None)\n";
}
os << indent << "ReadAllColorScalars: "
<< (this->ReadAllColorScalars ? "On" : "Off") << "\n";
if ( this->FieldDataName )
{
os << indent << "Field Data Name: " << this->FieldDataName << "\n";
}
else
{
os << indent << "Field Data Name: (None)\n";
}
os << indent << "ReadAllFields: "
<< (this->ReadAllFields ? "On" : "Off") << "\n";
os << indent << "InputStringLength: " << this->InputStringLength << endl;
}
int vtkDataReader::ReadDataSetData(vtkDataSet *vtkNotUsed(ds))
{
return 0;
}
void vtkDataReader::DecodeArrayName(char *resname, const char* name)
{
if ( !resname || !name )
{
return;
}
//strcpy(resname, name);
ostrstream str;
int cc = 0;
unsigned int ch;
int len = static_cast<int>(strlen(name));
char buffer[10] = "0x";
while(name[cc])
{
if ( name[cc] == '%' )
{
if ( cc < len - 3 )
{
buffer[2] = name[cc+1];
buffer[3] = name[cc+2];
buffer[4] = 0;
sscanf(buffer, "%x", &ch);
str << static_cast<char>(ch);
cc+=2;
}
}
else
{
str << name[cc];
}
cc ++;
}
str << ends;
strcpy(resname, str.str());
str.rdbuf()->freeze(0);
}
BUG: Fix Bug #1672 - Rounding error in vtkDataReader
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataReader.h"
#include "vtkBitArray.h"
#include "vtkByteSwap.h"
#include "vtkCellData.h"
#include "vtkCharArray.h"
#include "vtkDoubleArray.h"
#include "vtkErrorCode.h"
#include "vtkFieldData.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkLongArray.h"
#include "vtkLookupTable.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkRectilinearGrid.h"
#include "vtkShortArray.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkUnsignedShortArray.h"
#include <ctype.h>
#include <sys/stat.h>
vtkCxxRevisionMacro(vtkDataReader, "1.134");
vtkStandardNewMacro(vtkDataReader);
vtkCxxSetObjectMacro(vtkDataReader, InputArray, vtkCharArray);
// this undef is required on the hp. vtkMutexLock ends up including
// /usr/inclue/dce/cma_ux.h which has the gall to #define read as cma_read
#ifdef read
#undef read
#endif
// Construct object.
vtkDataReader::vtkDataReader()
{
this->FileType = VTK_ASCII;
this->FileName = NULL;
this->ScalarsName = NULL;
this->VectorsName = NULL;
this->TensorsName = NULL;
this->NormalsName = NULL;
this->TCoordsName = NULL;
this->LookupTableName = NULL;
this->FieldDataName = NULL;
this->ScalarLut = NULL;
this->InputString = NULL;
this->InputStringLength = 0;
this->InputStringPos = 0;
this->ReadFromInputString = 0;
this->IS = NULL;
this->Header = NULL;
this->InputArray = 0;
this->NumberOfScalarsInFile = 0;
this->ScalarsNameInFile = NULL;
this->ScalarsNameAllocSize = 0;
this->NumberOfVectorsInFile = 0;
this->VectorsNameInFile = NULL;
this->VectorsNameAllocSize = 0;
this->NumberOfTensorsInFile = 0;
this->TensorsNameInFile = NULL;
this->TensorsNameAllocSize = 0;
this->NumberOfTCoordsInFile = 0;
this->TCoordsNameInFile = NULL;
this->TCoordsNameAllocSize = 0;
this->NumberOfNormalsInFile = 0;
this->NormalsNameInFile = NULL;
this->NormalsNameAllocSize = 0;
this->NumberOfFieldDataInFile = 0;
this->FieldDataNameInFile = NULL;
this->FieldDataNameAllocSize = 0;
this->ReadAllScalars = 0;
this->ReadAllVectors = 0;
this->ReadAllNormals = 0;
this->ReadAllTensors = 0;
this->ReadAllColorScalars = 0;
this->ReadAllTCoords = 0;
this->ReadAllFields = 0;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
vtkDataReader::~vtkDataReader()
{
if (this->FileName)
{
delete [] this->FileName;
}
if (this->ScalarsName)
{
delete [] this->ScalarsName;
}
if (this->VectorsName)
{
delete [] this->VectorsName;
}
if (this->TensorsName)
{
delete [] this->TensorsName;
}
if (this->NormalsName)
{
delete [] this->NormalsName;
}
if (this->TCoordsName)
{
delete [] this->TCoordsName;
}
if (this->LookupTableName)
{
delete [] this->LookupTableName;
}
if (this->FieldDataName)
{
delete [] this->FieldDataName;
}
if (this->ScalarLut)
{
delete [] this->ScalarLut;
}
if (this->InputString)
{
delete [] this->InputString;
}
if (this->Header)
{
delete [] this->Header;
}
this->SetInputArray(0);
this->InitializeCharacteristics();
if ( this->IS )
{
delete this->IS;
}
}
void vtkDataReader::SetInputString(const char *in)
{
if (in != NULL)
{
this->SetInputString(in, static_cast<int>(strlen(in)));
}
else
{
if (this->InputString)
{
delete [] this->InputString;
}
this->InputString = NULL;
}
}
void vtkDataReader::SetBinaryInputString(const char *in, int len)
{
this->SetInputString(in,len);
}
void vtkDataReader::SetInputString(const char *in, int len)
{
if (this->Debug)
{
vtkDebugMacro(<< "setting InputString to " << in );
}
if (this->InputString && in && strncmp(in, this->InputString, len) == 0)
{
return;
}
if (this->InputString)
{
delete [] this->InputString;
}
if (in)
{
this->InputString = new char[len];
memcpy(this->InputString,in,len);
this->InputStringLength = len;
}
else
{
this->InputString = NULL;
this->InputStringLength = 0;
}
this->Modified();
}
// Internal function to read in a line up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadLine(char result[256])
{
this->IS->getline(result,256);
if (this->IS->fail())
{
if (this->IS->eof())
{
return 0;
}
if (this->IS->gcount() == 255)
{
// Read 256 chars; ignoring the rest of the line.
this->IS->clear();
this->IS->ignore(VTK_INT_MAX, '\n');
}
}
return 1;
}
// Internal function to read in a string up to 256 characters.
// Returns zero if there was an error.
int vtkDataReader::ReadString(char result[256])
{
this->IS->width(256);
*this->IS >> result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
// Internal function to read in an integer value.
// Returns zero if there was an error.
int vtkDataReader::Read(char *result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (char) intData;
return 1;
}
int vtkDataReader::Read(unsigned char *result)
{
int intData;
*this->IS >> intData;
if (this->IS->fail())
{
return 0;
}
*result = (unsigned char) intData;
return 1;
}
int vtkDataReader::Read(short *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned short *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(int *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned int *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(long *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(unsigned long *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(float *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
int vtkDataReader::Read(double *result)
{
*this->IS >> *result;
if (this->IS->fail())
{
return 0;
}
return 1;
}
// Open a vtk data file. Returns zero if error.
int vtkDataReader::OpenVTKFile()
{
if (this->ReadFromInputString)
{
if (this->InputArray)
{
vtkDebugMacro(<< "Reading from InputArray");
this->IS = new istrstream(this->InputArray->GetPointer(0),
this->InputArray->GetNumberOfTuples()*
this->InputArray->GetNumberOfComponents());
return 1;
}
else if (this->InputString)
{
vtkDebugMacro(<< "Reading from InputString");
this->IS = new istrstream(this->InputString, this->InputStringLength);
return 1;
}
}
else
{
vtkDebugMacro(<< "Opening vtk file");
if ( !this->FileName || (strlen(this->FileName) == 0))
{
vtkErrorMacro(<< "No file specified!");
this->SetErrorCode( vtkErrorCode::NoFileNameError );
return 0;
}
// first make sure the file exists, this prevents an empty file from
// being created on older compilers
struct stat fs;
if (stat(this->FileName, &fs) != 0)
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
this->IS = new ifstream(this->FileName, ios::in);
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
delete this->IS;
this->IS = NULL;
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
return 1;
}
return 0;
}
// Read the header of a vtk data file. Returns 0 if error.
int vtkDataReader::ReadHeader()
{
char line[256];
vtkDebugMacro(<< "Reading vtk file header");
//
// read header
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<<"Premature EOF reading first line! " << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( strncmp ("# vtk DataFile Version", line, 20) )
{
vtkErrorMacro(<< "Unrecognized file type: "<< line << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::UnrecognizedFileTypeError );
return 0;
}
//
// read title
//
if (!this->ReadLine(line))
{
vtkErrorMacro(<<"Premature EOF reading title! " << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if (this->Header)
{
delete [] this->Header;
}
this->Header = new char[strlen(line) + 1];
strcpy (this->Header, line);
vtkDebugMacro(<< "Reading vtk file entitled: " << line);
//
// read type
//
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Premature EOF reading file type!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( !strncmp(this->LowerCase(line), "ascii", 5) )
{
this->FileType = VTK_ASCII;
}
else if ( !strncmp(line, "binary", 6) )
{
this->FileType = VTK_BINARY;
}
else
{
vtkErrorMacro(<< "Unrecognized file type: "<< line << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
this->FileType = 0;
this->SetErrorCode( vtkErrorCode::UnrecognizedFileTypeError );
return 0;
}
// if this is a binary file we need to make sure that we opened it
// as a binary file.
if (this->FileType == VTK_BINARY && this->ReadFromInputString == 0)
{
vtkDebugMacro(<< "Opening vtk file as binary");
delete this->IS;
this->IS = 0;
#ifdef _WIN32
this->IS = new ifstream(this->FileName, ios::in | ios::binary);
#else
this->IS = new ifstream(this->FileName, ios::in);
#endif
if (this->IS->fail())
{
vtkErrorMacro(<< "Unable to open file: "<< this->FileName);
delete this->IS;
this->IS = NULL;
this->SetErrorCode( vtkErrorCode::CannotOpenFileError );
return 0;
}
// read up to the same point in the file
this->ReadLine(line);
this->ReadLine(line);
this->ReadString(line);
}
float progress=this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
int vtkDataReader::IsFileValid(const char *dstype)
{
char line[1024];
if (!dstype)
{
return 0;
}
if (!this->OpenVTKFile() || !this->ReadHeader())
{
return 0;
}
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if ( !strncmp(this->LowerCase(line),"dataset",(unsigned long)7) )
{
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
this->SetErrorCode( vtkErrorCode::PrematureEndOfFileError );
return 0;
}
if (strncmp(this->LowerCase(line),dstype,strlen(dstype)))
{
this->CloseVTKFile ();
return 0;
}
// everything looks good
this->CloseVTKFile();
return 1;
}
return 0;
}
// Read the cell data of a vtk data file. The number of cells (from the
// dataset) must match the number of cells defined in cell attributes (unless
// no geometry was defined).
int vtkDataReader::ReadCellData(vtkDataSet *ds, int numCells)
{
char line[256];
vtkDataSetAttributes *a=ds->GetCellData();
vtkDebugMacro(<< "Reading vtk cell data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if ( ! strncmp(this->LowerCase(line), "scalars", 7) )
{
if ( ! this->ReadScalarData(a, numCells) )
{
return 0;
}
}
//
// read vector data
//
else if ( ! strncmp(line, "vectors", 7) )
{
if ( ! this->ReadVectorData(a, numCells) )
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if ( ! strncmp(line, "tensors", 7) )
{
if ( ! this->ReadTensorData(a, numCells) )
{
return 0;
}
}
//
// read normals data
//
else if ( ! strncmp(line, "normals", 7) )
{
if ( ! this->ReadNormalData(a, numCells) )
{
return 0;
}
}
//
// read texture coordinates data
//
else if ( ! strncmp(line, "texture_coordinates", 19) )
{
if ( ! this->ReadTCoordsData(a, numCells) )
{
return 0;
}
}
//
// read color scalars data
//
else if ( ! strncmp(line, "color_scalars", 13) )
{
if ( ! this->ReadCoScalarData(a, numCells) )
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if ( ! strncmp(line, "lookup_table", 12) )
{
if ( ! this->ReadLutData(a) )
{
return 0;
}
}
//
// read field of data
//
else if ( ! strncmp(line, "field", 5) )
{
vtkFieldData *f;
if ( ! (f=this->ReadFieldData()) )
{
return 0;
}
for(int i=0; i<f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetArray(i));
}
f->Delete();
}
//
// maybe bumped into point data
//
else if ( ! strncmp(line, "point_data", 10) )
{
int npts;
if (!this->Read(&npts))
{
vtkErrorMacro(<<"Cannot read point data!");
return 0;
}
this->ReadPointData(ds, npts);
}
else
{
vtkErrorMacro(<< "Unsupported cell attribute type: " << line
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
return 1;
}
// Read the point data of a vtk data file. The number of points (from the
// dataset) must match the number of points defined in point attributes (unless
// no geometry was defined).
int vtkDataReader::ReadPointData(vtkDataSet *ds, int numPts)
{
char line[256];
vtkDataSetAttributes *a=ds->GetPointData();
vtkDebugMacro(<< "Reading vtk point data");
//
// Read keywords until end-of-file
//
while (this->ReadString(line))
{
//
// read scalar data
//
if ( ! strncmp(this->LowerCase(line), "scalars", 7) )
{
if ( ! this->ReadScalarData(a, numPts) )
{
return 0;
}
}
//
// read vector data
//
else if ( ! strncmp(line, "vectors", 7) )
{
if ( ! this->ReadVectorData(a, numPts) )
{
return 0;
}
}
//
// read 3x3 tensor data
//
else if ( ! strncmp(line, "tensors", 7) )
{
if ( ! this->ReadTensorData(a, numPts) )
{
return 0;
}
}
//
// read normals data
//
else if ( ! strncmp(line, "normals", 7) )
{
if ( ! this->ReadNormalData(a, numPts) )
{
return 0;
}
}
//
// read texture coordinates data
//
else if ( ! strncmp(line, "texture_coordinates", 19) )
{
if ( ! this->ReadTCoordsData(a, numPts) )
{
return 0;
}
}
//
// read color scalars data
//
else if ( ! strncmp(line, "color_scalars", 13) )
{
if ( ! this->ReadCoScalarData(a, numPts) )
{
return 0;
}
}
//
// read lookup table. Associate with scalar data.
//
else if ( ! strncmp(line, "lookup_table", 12) )
{
if ( ! this->ReadLutData(a) )
{
return 0;
}
}
//
// read field of data
//
else if ( ! strncmp(line, "field", 5) )
{
vtkFieldData *f;
if ( ! (f=this->ReadFieldData()) )
{
return 0;
}
for(int i=0; i<f->GetNumberOfArrays(); i++)
{
a->AddArray(f->GetArray(i));
}
f->Delete();
}
//
// maybe bumped into cell data
//
else if ( ! strncmp(line, "cell_data", 9) )
{
int ncells;
if (!this->Read(&ncells))
{
vtkErrorMacro(<<"Cannot read cell data!");
return 0;
}
this->ReadCellData(ds, ncells);
}
else
{
vtkErrorMacro(<< "Unsupported point attribute type: " << line
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadBinaryData(istream *IS, T *data, int numTuples, int numComp)
{
char line[256];
// suck up newline
IS->getline(line,256);
IS->read((char *)data, sizeof(T)*numComp*numTuples);
if (IS->eof())
{
vtkGenericWarningMacro(<<"Error reading binary data!");
return 0;
}
return 1;
}
// General templated function to read data of various types.
template <class T>
int vtkReadASCIIData(vtkDataReader *self, T *data, int numTuples, int numComp)
{
int i, j;
for (i=0; i<numTuples; i++)
{
for (j=0; j<numComp; j++)
{
if ( !self->Read(data++) )
{
vtkGenericWarningMacro(<<"Error reading ascii data!");
return 0;
}
}
}
return 1;
}
// Decription:
// Read data array. Return pointer to array object if successful read;
// otherwise return NULL. Note: this method instantiates a reference counted
// object with initial count of one; proper protocol is for you to assign
// the data object and then invoke Delete() it to restore proper reference
// count.
vtkDataArray *vtkDataReader::ReadArray(const char *dataType, int numTuples, int numComp)
{
char *type=strdup(dataType);
type=this->LowerCase(type);
vtkDataArray *array;
if ( ! strncmp(type, "bit", 3) )
{
array = vtkBitArray::New();
array->SetNumberOfComponents(numComp);
unsigned char *ptr=((vtkBitArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
char line[256];
this->IS->getline(line,256);
this->IS->read((char *)ptr,sizeof(unsigned char)*(numTuples*numComp+7)/8);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary bit array!");
free(type);
return NULL;
}
}
else
{
int b;
for (int i=0; i<numTuples; i++)
{
for (int j=0; j<numComp; j++)
{
if ( !this->Read(&b) )
{
vtkErrorMacro(<<"Error reading ascii bit array! tuple: " << i << ", component: " << j);
free(type);
return NULL;
}
else
{
((vtkBitArray *)array)->SetValue(i*numComp+j,b);
}
}
}
}
}
else if ( ! strncmp(type, "char", 4) )
{
array = vtkCharArray::New();
array->SetNumberOfComponents(numComp);
char *ptr = ((vtkCharArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_char", 13) )
{
array = vtkUnsignedCharArray::New();
array->SetNumberOfComponents(numComp);
unsigned char *ptr = ((vtkUnsignedCharArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "short", 5) )
{
array = vtkShortArray::New();
array->SetNumberOfComponents(numComp);
short *ptr = ((vtkShortArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_short", 14) )
{
array = vtkUnsignedShortArray::New();
array->SetNumberOfComponents(numComp);
unsigned short *ptr = ((vtkUnsignedShortArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap2BERange((short *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "int", 3) )
{
array = vtkIntArray::New();
array->SetNumberOfComponents(numComp);
int *ptr = ((vtkIntArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_int", 12) )
{
array = vtkUnsignedIntArray::New();
array->SetNumberOfComponents(numComp);
unsigned int *ptr = ((vtkUnsignedIntArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "long", 4) )
{
array = vtkLongArray::New();
array->SetNumberOfComponents(numComp);
long *ptr = ((vtkLongArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "unsigned_long", 13) )
{
array = vtkUnsignedLongArray::New();
array->SetNumberOfComponents(numComp);
unsigned long *ptr = ((vtkUnsignedLongArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange((int *)ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "float", 5) )
{
array = vtkFloatArray::New();
array->SetNumberOfComponents(numComp);
float *ptr = ((vtkFloatArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap4BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else if ( ! strncmp(type, "double", 6) )
{
array = vtkDoubleArray::New();
array->SetNumberOfComponents(numComp);
double *ptr = ((vtkDoubleArray *)array)->WritePointer(0,numTuples*numComp);
if ( this->FileType == VTK_BINARY )
{
vtkReadBinaryData(this->IS, ptr, numTuples, numComp);
vtkByteSwap::Swap8BERange(ptr,numTuples*numComp);
}
else
{
vtkReadASCIIData(this, ptr, numTuples, numComp);
}
}
else
{
vtkErrorMacro(<< "Unsupported data type: " << type);
free(type);
return NULL;
}
free(type);
return array;
}
// Read point coordinates. Return 0 if error.
int vtkDataReader::ReadPoints(vtkPointSet *ps, int numPts)
{
char line[256];
vtkDataArray *data;
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Cannot read points type!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
vtkPoints *points=vtkPoints::New();
points->SetData(data);
data->Delete();
ps->SetPoints(points);
points->Delete();
}
else
{
return 0;
}
vtkDebugMacro(<<"Read " << ps->GetNumberOfPoints() << " points");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read the coordinates for a rectilinear grid. The axes parameter specifies
// which coordinate axes (0,1,2) is being read.
int vtkDataReader::ReadCoordinates(vtkRectilinearGrid *rg, int axes,
int numCoords)
{
char line[256];
vtkDataArray *data;
if (!this->ReadString(line))
{
vtkErrorMacro(<<"Cannot read coordinates type!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
data = this->ReadArray(line, numCoords, 1);
if ( !data )
{
return 0;
}
if ( axes == 0 )
{
rg->SetXCoordinates(data);
}
else if ( axes == 1 )
{
rg->SetYCoordinates(data);
}
else
{
rg->SetZCoordinates(data);
}
vtkDebugMacro(<<"Read " << data->GetNumberOfTuples() << " coordinates");
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
data->Delete();
return 1;
}
// Read scalar point attributes. Return 0 if error.
int vtkDataReader::ReadScalarData(vtkDataSetAttributes *a, int numPts)
{
char line[256], name[256], key[256], tableName[256];
int skipScalar=0;
vtkDataArray *data;
int numComp = 1;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
if (!this->ReadString(key))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
// the next string could be an integer number of components or a lookup table
if (strcmp(this->LowerCase(key), "lookup_table"))
{
numComp = atoi(key);
if (numComp < 1 || !this->ReadString(key))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
if (strcmp(this->LowerCase(key), "lookup_table"))
{
vtkErrorMacro(<<"Lookup table must be specified with scalar.\n" <<
"Use \"LOOKUP_TABLE default\" to use default table.");
return 0;
}
if (!this->ReadString(tableName))
{
vtkErrorMacro(<<"Cannot read scalar header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if ( a->GetScalars() != NULL || (this->ScalarsName && strcmp(name,this->ScalarsName)) )
{
skipScalar = 1;
}
else
{
this->SetScalarLut(tableName); //may be "default"
}
// Read the data
data = this->ReadArray(line, numPts, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipScalar )
{
a->SetScalars(data);
}
else if ( this->ReadAllScalars )
{
a->AddArray(data);
} data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read vector point attributes. Return 0 if error.
int vtkDataReader::ReadVectorData(vtkDataSetAttributes *a, int numPts)
{
int skipVector=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read vector data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether vector has been already read or vector name (if specified)
// matches name in file.
//
if ( a->GetVectors() != NULL || (this->VectorsName && strcmp(name,this->VectorsName)) )
{
skipVector = 1;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipVector )
{
a->SetVectors(data);
}
else if ( this->ReadAllVectors )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read normal point attributes. Return 0 if error.
int vtkDataReader::ReadNormalData(vtkDataSetAttributes *a, int numPts)
{
int skipNormal=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read normal data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether normal has been already read or normal name (if specified)
// matches name in file.
//
if ( a->GetNormals() != NULL || (this->NormalsName && strcmp(name,this->NormalsName)) )
{
skipNormal = 1;
}
data = this->ReadArray(line, numPts, 3);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipNormal )
{
a->SetNormals(data);
}
else if ( this->ReadAllNormals )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read tensor point attributes. Return 0 if error.
int vtkDataReader::ReadTensorData(vtkDataSetAttributes *a, int numPts)
{
int skipTensor=0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read tensor data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether tensor has been already read or tensor name (if specified)
// matches name in file.
//
if ( a->GetTensors() != NULL || (this->TensorsName && strcmp(name,this->TensorsName)) )
{
skipTensor = 1;
}
data = this->ReadArray(line, numPts, 9);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipTensor )
{
a->SetTensors(data);
}
else if ( this->ReadAllTensors )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read color scalar point attributes. Return 0 if error.
int vtkDataReader::ReadCoScalarData(vtkDataSetAttributes *a, int numPts)
{
int i, j, idx, numComp, skipScalar=0;
char name[256];
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&numComp)))
{
vtkErrorMacro(<<"Cannot read color scalar data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
//
// See whether scalar has been already read or scalar name (if specified)
// matches name in file.
//
if ( a->GetScalars() != NULL ||
(this->ScalarsName && strcmp(name,this->ScalarsName)) )
{
skipScalar = 1;
}
// handle binary different from ASCII since they are stored
// in a different format float versus uchar
if ( this->FileType == VTK_BINARY)
{
vtkUnsignedCharArray *data;
char type[14] = "unsigned_char";
data = (vtkUnsignedCharArray *)this->ReadArray(type, numPts, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipScalar )
{
a->SetScalars(data);
}
else if ( this->ReadAllColorScalars )
{
a->AddArray(data);
} data->Delete();
}
else
{
return 0;
}
}
else
{
vtkFloatArray *data;
char type[6] = "float";
data = (vtkFloatArray *)this->ReadArray(type, numPts, numComp);
if ( data != NULL )
{
if ( ! skipScalar || this->ReadAllColorScalars )
{
vtkUnsignedCharArray *scalars=vtkUnsignedCharArray::New();
scalars->SetNumberOfComponents(numComp);
scalars->SetNumberOfTuples(numPts);
scalars->SetName(name);
for (i=0; i<numPts; i++)
{
for (j=0; j<numComp; j++)
{
idx = i*numComp + j;
scalars->SetValue(idx,(unsigned char)(255.0*data->GetValue(idx)+0.5));
}
}
if ( ! skipScalar )
{
a->SetScalars(scalars);
}
else if ( this->ReadAllColorScalars )
{
a->AddArray(scalars);
} scalars->Delete();
}
data->Delete();
}
else
{
return 0;
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read texture coordinates point attributes. Return 0 if error.
int vtkDataReader::ReadTCoordsData(vtkDataSetAttributes *a, int numPts)
{
int dim;
int skipTCoord = 0;
char line[256], name[256];
vtkDataArray *data;
char buffer[1024];
if (!(this->ReadString(buffer) && this->Read(&dim) &&
this->ReadString(line)))
{
vtkErrorMacro(<<"Cannot read texture data!" << " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
this->DecodeArrayName(name, buffer);
if ( dim < 1 || dim > 3 )
{
vtkErrorMacro(<< "Unsupported texture coordinates dimension: " << dim
<< " for file: " << (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
//
// See whether texture coords have been already read or texture coords name
// (if specified) matches name in file.
//
if ( a->GetTCoords() != NULL ||
(this->TCoordsName && strcmp(name,this->TCoordsName)) )
{
skipTCoord = 1;
}
data = this->ReadArray(line, numPts, dim);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipTCoord )
{
a->SetTCoords(data);
}
else if ( this->ReadAllTCoords )
{
a->AddArray(data);
}
data->Delete();
}
else
{
return 0;
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadLutData(vtkDataSetAttributes *a)
{
int i;
int size, skipTable=0;
vtkLookupTable *lut;
unsigned char *ptr;
char line[256], name[256];
if (!(this->ReadString(name) && this->Read(&size)))
{
vtkErrorMacro(<<"Cannot read lookup table data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
if ( a->GetScalars() == NULL ||
(this->LookupTableName && strcmp(name,this->LookupTableName)) ||
(this->ScalarLut && strcmp(name,this->ScalarLut)) )
{
skipTable = 1;
}
lut = vtkLookupTable::New();
lut->Allocate(size);
ptr = lut->WritePointer(0,size);
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
this->IS->read((char *)ptr,sizeof(unsigned char)*4*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary lookup table!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
else // ascii
{
float rgba[4];
for (i=0; i<size; i++)
{
if (!(this->Read(rgba) && this->Read(rgba+1) &&
this->Read(rgba+2) && this->Read(rgba+3)))
{
vtkErrorMacro(<<"Error reading lookup table!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
lut->SetTableValue(i, rgba[0], rgba[1], rgba[2], rgba[3]);
}
}
if ( ! skipTable )
{
a->GetScalars()->SetLookupTable(lut);
}
lut->Delete();
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
// Read lookup table. Return 0 if error.
int vtkDataReader::ReadCells(int size, int *data)
{
char line[256];
int i;
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
this->IS->read((char *)data,sizeof(int)*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(data,size);
}
else // ascii
{
for (i=0; i<size; i++)
{
if (!this->Read(data+i))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
int vtkDataReader::ReadCells(int size, int *data,
int skip1, int read2, int skip3)
{
char line[256];
int i, numCellPts, junk, *tmp, *pTmp;
if ( this->FileType == VTK_BINARY)
{
// suck up newline
this->IS->getline(line,256);
// first read all the cells as one chunk (each cell has different length).
if (skip1 == 0 && skip3 == 0)
{
tmp = data;
}
else
{
tmp = new int[size];
}
this->IS->read((char *)tmp,sizeof(int)*size);
if (this->IS->eof())
{
vtkErrorMacro(<<"Error reading binary cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
vtkByteSwap::Swap4BERange(tmp,size);
if (tmp == data)
{
return 1;
}
// skip cells before the piece
pTmp = tmp;
while (skip1 > 0)
{
// the first value is the number of point ids
// skip these plus one for the number itself.
pTmp += *pTmp + 1;
--skip1;
}
// copy the cells in the piece
// (ok, I am getting criptic with the loops and increments ...)
while (read2 > 0)
{
// the first value is the number of point ids
*data++ = i = *pTmp++;
while (i-- > 0)
{
*data++ = *pTmp++;
}
--read2;
}
// delete the temporary array
delete [] tmp;
}
else // ascii
{
// skip cells before the piece
for (i=0; i<skip1; i++)
{
if (!this->Read(&numCellPts))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
// read the cells in the piece
for (i=0; i<read2; i++)
{
if (!this->Read(data))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
numCellPts = *data++;
while (numCellPts-- > 0)
{
this->Read(data++);
}
}
// skip cells after the piece
for (i=0; i<skip3; i++)
{
if (!this->Read(&numCellPts))
{
vtkErrorMacro(<<"Error reading ascii cell data!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return 0;
}
while (numCellPts-- > 0)
{
this->Read(&junk);
}
}
}
float progress = this->GetProgress();
this->UpdateProgress(progress + 0.5*(1.0 - progress));
return 1;
}
vtkFieldData *vtkDataReader::ReadFieldData()
{
int i, numArrays, skipField=0;
vtkFieldData *f;
char name[256], type[256];
int numComp, numTuples;
vtkDataArray *data;
if ( !(this->ReadString(name) && this->Read(&numArrays)) )
{
vtkErrorMacro(<<"Cannot read field header!" << " for file: "
<< (this->FileName?this->FileName:"(Null FileName)"));
return NULL;
}
// See whether field data name (if specified)
if ( (this->FieldDataName && strcmp(name,this->FieldDataName)) )
{
skipField = 1;
}
f = vtkFieldData::New();
f->AllocateArrays(numArrays);
// Read the number of arrays specified
for (i=0; i<numArrays; i++)
{
char buffer[1024];
this->ReadString(buffer);
this->DecodeArrayName(name, buffer);
this->Read(&numComp);
this->Read(&numTuples);
this->ReadString(type);
data = this->ReadArray(type, numTuples, numComp);
if ( data != NULL )
{
data->SetName(name);
if ( ! skipField || this->ReadAllFields )
{
f->AddArray(data);
}
data->Delete();
}
else
{
f->Delete();
return NULL;
}
}
if ( skipField && ! this->ReadAllFields )
{
f->Delete();
return NULL;
}
else
{
return f;
}
}
char *vtkDataReader::LowerCase(char *str, const size_t len)
{
size_t i;
char *s;
for ( i=0, s=str; *s != '\0' && i<len; s++,i++)
{
*s = tolower(*s);
}
return str;
}
// Close a vtk file.
void vtkDataReader::CloseVTKFile()
{
vtkDebugMacro(<<"Closing vtk file");
if ( this->IS != NULL )
{
delete this->IS;
}
this->IS = NULL;
}
void vtkDataReader::InitializeCharacteristics()
{
int i;
// Release any old stuff first
if ( this->ScalarsNameInFile )
{
for (i=0; i<this->NumberOfScalarsInFile; i++)
{
delete [] this->ScalarsNameInFile[i];
}
this->NumberOfScalarsInFile = 0;
delete [] this->ScalarsNameInFile;
this->ScalarsNameInFile = NULL;
}
if ( this->VectorsNameInFile )
{
for (i=0; i<this->NumberOfVectorsInFile; i++)
{
delete [] this->VectorsNameInFile[i];
}
this->NumberOfVectorsInFile = 0;
delete [] this->VectorsNameInFile;
this->VectorsNameInFile = NULL;
}
if ( this->TensorsNameInFile )
{
for (i=0; i<this->NumberOfTensorsInFile; i++)
{
delete [] this->TensorsNameInFile[i];
}
this->NumberOfTensorsInFile = 0;
delete [] this->TensorsNameInFile;
this->TensorsNameInFile = NULL;
}
if ( this->NormalsNameInFile )
{
for (i=0; i<this->NumberOfNormalsInFile; i++)
{
delete [] this->NormalsNameInFile[i];
}
this->NumberOfNormalsInFile = 0;
delete [] this->NormalsNameInFile;
this->NormalsNameInFile = NULL;
}
if ( this->TCoordsNameInFile )
{
for (i=0; i<this->NumberOfTCoordsInFile; i++)
{
delete [] this->TCoordsNameInFile[i];
}
this->NumberOfTCoordsInFile = 0;
delete [] this->TCoordsNameInFile;
this->TCoordsNameInFile = NULL;
}
if ( this->FieldDataNameInFile )
{
for (i=0; i<this->NumberOfFieldDataInFile; i++)
{
delete [] this->FieldDataNameInFile[i];
}
this->NumberOfFieldDataInFile = 0;
delete [] this->FieldDataNameInFile;
this->FieldDataNameInFile = NULL;
}
}
//read entire file, storing important characteristics
int vtkDataReader::CharacterizeFile()
{
if ( this->CharacteristicsTime > this->MTime )
{
return 1;
}
this->InitializeCharacteristics();
this->CharacteristicsTime.Modified();
// Open the file
if (!this->OpenVTKFile() || !this->ReadHeader())
{
return 0;
}
char line[256];
while (this->ReadLine(line))
{
this->CheckFor("scalars", line, this->NumberOfScalarsInFile,
this->ScalarsNameInFile, this->ScalarsNameAllocSize);
this->CheckFor("vectors", line, this->NumberOfVectorsInFile,
this->VectorsNameInFile, this->VectorsNameAllocSize);
this->CheckFor("tensors", line, this->NumberOfTensorsInFile,
this->TensorsNameInFile, this->TensorsNameAllocSize);
this->CheckFor("normals", line, this->NumberOfNormalsInFile,
this->NormalsNameInFile, this->NormalsNameAllocSize);
this->CheckFor("tcoords", line, this->NumberOfTCoordsInFile,
this->TCoordsNameInFile, this->TCoordsNameAllocSize);
this->CheckFor("field", line, this->NumberOfFieldDataInFile,
this->FieldDataNameInFile, this->FieldDataNameAllocSize);
}
this->CloseVTKFile ();
return 1;
}
void vtkDataReader::CheckFor(const char* name, char *line, int &num,
char** &array, int &allocSize)
{
if ( !strncmp(this->LowerCase(line, strlen(name)), name, strlen(name)) )
{
int i;
int newAllocSize;
char **newArray;
//update numbers
num++;
if ( !array )
{
allocSize = 25;
array = new char* [allocSize];
for (i=0; i<allocSize; i++)
{
array[i] = NULL;
}
}
else if ( num >= allocSize )
{
newAllocSize = 2*num;
newArray = new char* [newAllocSize];
for (i=0; i<allocSize; i++)
{
newArray[i] = array[i];
}
for (i=allocSize; i<newAllocSize; i++)
{
newArray[i] = NULL;
}
allocSize = newAllocSize;
delete [] array;
array = newArray;
}
// enter the name
char nameOfAttribute[256];
sscanf(line, "%*s %s", nameOfAttribute);
if ( nameOfAttribute )
{
array[num-1] = new char [strlen(nameOfAttribute)+1];
strcpy(array[num-1],nameOfAttribute);
}
}//found one
}
const char *vtkDataReader::GetScalarsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->ScalarsNameInFile ||
i < 0 || i >= this->NumberOfScalarsInFile )
{
return NULL;
}
else
{
return this->ScalarsNameInFile[i];
}
}
const char *vtkDataReader::GetVectorsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->VectorsNameInFile ||
i < 0 || i >= this->NumberOfVectorsInFile )
{
return NULL;
}
else
{
return this->VectorsNameInFile[i];
}
}
const char *vtkDataReader::GetTensorsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->TensorsNameInFile ||
i < 0 || i >= this->NumberOfTensorsInFile )
{
return NULL;
}
else
{
return this->TensorsNameInFile[i];
}
}
const char *vtkDataReader::GetNormalsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->NormalsNameInFile ||
i < 0 || i >= this->NumberOfNormalsInFile )
{
return NULL;
}
else
{
return this->NormalsNameInFile[i];
}
}
const char *vtkDataReader::GetTCoordsNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->TCoordsNameInFile ||
i < 0 || i >= this->NumberOfTCoordsInFile )
{
return NULL;
}
else
{
return this->TCoordsNameInFile[i];
}
}
const char *vtkDataReader::GetFieldDataNameInFile(int i)
{
this->CharacterizeFile();
if ( !this->FieldDataNameInFile ||
i < 0 || i >= this->NumberOfFieldDataInFile )
{
return NULL;
}
else
{
return this->FieldDataNameInFile[i];
}
}
int vtkDataReader::ProcessRequest(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// generate the data
if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
{
return this->RequestData(request, inputVector, outputVector);
}
if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
{
return this->RequestUpdateExtent(request, inputVector, outputVector);
}
// execute information
if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
{
return this->RequestInformation(request, inputVector, outputVector);
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
void vtkDataReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
if ( this->FileType == VTK_BINARY )
{
os << indent << "File Type: BINARY\n";
}
else
{
os << indent << "File Type: ASCII\n";
}
if ( this->Header )
{
os << indent << "Header: " << this->Header << "\n";
}
else
{
os << indent << "Header: (None)\n";
}
os << indent << "ReadFromInputString: " << (this->ReadFromInputString ? "On\n" : "Off\n");
if ( this->InputString )
{
os << indent << "Input String: " << this->InputString << "\n";
}
else
{
os << indent << "Input String: (None)\n";
}
if ( this->InputArray )
{
os << indent << "Input Array: " << "\n";
this->InputArray->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Input String: (None)\n";
}
os << indent << "Input String Length: " << this->InputStringLength << endl;
if ( this->ScalarsName )
{
os << indent << "Scalars Name: " << this->ScalarsName << "\n";
}
else
{
os << indent << "Scalars Name: (None)\n";
}
os << indent << "ReadAllScalars: "
<< (this->ReadAllScalars ? "On" : "Off") << "\n";
if ( this->VectorsName )
{
os << indent << "Vectors Name: " << this->VectorsName << "\n";
}
else
{
os << indent << "Vectors Name: (None)\n";
}
os << indent << "ReadAllVectors: "
<< (this->ReadAllVectors ? "On" : "Off") << "\n";
if ( this->NormalsName )
{
os << indent << "Normals Name: " << this->NormalsName << "\n";
}
else
{
os << indent << "Normals Name: (None)\n";
}
os << indent << "ReadAllNormals: "
<< (this->ReadAllNormals ? "On" : "Off") << "\n";
if ( this->TensorsName )
{
os << indent << "Tensors Name: " << this->TensorsName << "\n";
}
else
{
os << indent << "Tensors Name: (None)\n";
}
os << indent << "ReadAllTensors: "
<< (this->ReadAllTensors ? "On" : "Off") << "\n";
if ( this->TCoordsName )
{
os << indent << "Texture Coords Name: " << this->TCoordsName << "\n";
}
else
{
os << indent << "Texture Coordinates Name: (None)\n";
}
os << indent << "ReadAllTCoords: "
<< (this->ReadAllTCoords ? "On" : "Off") << "\n";
if ( this->LookupTableName )
{
os << indent << "Lookup Table Name: " << this->LookupTableName << "\n";
}
else
{
os << indent << "Lookup Table Name: (None)\n";
}
os << indent << "ReadAllColorScalars: "
<< (this->ReadAllColorScalars ? "On" : "Off") << "\n";
if ( this->FieldDataName )
{
os << indent << "Field Data Name: " << this->FieldDataName << "\n";
}
else
{
os << indent << "Field Data Name: (None)\n";
}
os << indent << "ReadAllFields: "
<< (this->ReadAllFields ? "On" : "Off") << "\n";
os << indent << "InputStringLength: " << this->InputStringLength << endl;
}
int vtkDataReader::ReadDataSetData(vtkDataSet *vtkNotUsed(ds))
{
return 0;
}
void vtkDataReader::DecodeArrayName(char *resname, const char* name)
{
if ( !resname || !name )
{
return;
}
//strcpy(resname, name);
ostrstream str;
int cc = 0;
unsigned int ch;
int len = static_cast<int>(strlen(name));
char buffer[10] = "0x";
while(name[cc])
{
if ( name[cc] == '%' )
{
if ( cc < len - 3 )
{
buffer[2] = name[cc+1];
buffer[3] = name[cc+2];
buffer[4] = 0;
sscanf(buffer, "%x", &ch);
str << static_cast<char>(ch);
cc+=2;
}
}
else
{
str << name[cc];
}
cc ++;
}
str << ends;
strcpy(resname, str.str());
str.rdbuf()->freeze(0);
}
|
/*-------------------------------------------------------------------------
*
* FILE
* connection.cxx
*
* DESCRIPTION
* implementation of the pqxx::connection and sibling classes.
* Different ways of setting up a backend connection.
*
* Copyright (c) 2001-2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/connection"
using namespace PGSTD;
pqxx::connection::connection() :
connection_base(0)
{
do_startconnect();
}
pqxx::connection::connection(const string &ConnInfo) :
connection_base(ConnInfo)
{
do_startconnect();
}
pqxx::connection::connection(const char ConnInfo[]) :
connection_base(ConnInfo)
{
do_startconnect();
}
void pqxx::connection::do_startconnect()
{
if (!get_conn()) set_conn(PQconnectdb(options()));
}
void pqxx::lazyconnection::completeconnect()
{
if (!get_conn()) set_conn(PQconnectdb(options()));
}
pqxx::asyncconnection::asyncconnection() :
connection_base(0),
m_connecting(false)
{
do_startconnect();
}
pqxx::asyncconnection::asyncconnection(const string &ConnInfo) :
connection_base(ConnInfo),
m_connecting(false)
{
do_startconnect();
}
pqxx::asyncconnection::asyncconnection(const char ConnInfo[]) :
connection_base(ConnInfo),
m_connecting(false)
{
do_startconnect();
}
void pqxx::asyncconnection::do_startconnect()
{
if (get_conn()) return; // Already connecting or connected
m_connecting = false;
set_conn(PQconnectStart(options()));
if (!get_conn()) throw bad_alloc();
if (PQconnectPoll(get_conn()) == PGRES_POLLING_FAILED)
throw broken_connection();
m_connecting = true;
}
void pqxx::asyncconnection::completeconnect()
{
if (!get_conn()) startconnect();
if (!m_connecting) return;
// Our "attempt to connect" state ends here, for better or for worse
m_connecting = false;
if (!get_conn()) throw broken_connection();
PostgresPollingStatusType pollstatus;
do
{
pollstatus = PQconnectPoll(get_conn());
switch (pollstatus)
{
case PGRES_POLLING_FAILED:
throw broken_connection();
case PGRES_POLLING_READING:
wait_read();
break;
case PGRES_POLLING_WRITING:
wait_write();
break;
case PGRES_POLLING_ACTIVE:
case PGRES_POLLING_OK:
break;
}
} while (pollstatus != PGRES_POLLING_OK);
}
pqxx::nullconnection::~nullconnection() throw ()
{
}
// Conflicting workarounds for Windows and SUN CC 5.1; see header
#ifndef _WIN32
pqxx::connection::~connection() throw () { close(); }
pqxx::lazyconnection::~lazyconnection() throw () { close(); }
pqxx::asyncconnection::~asyncconnection() throw () {do_dropconnect(); close();}
#endif // _WIN32
Corrected copyright message
/*-------------------------------------------------------------------------
*
* FILE
* connection.cxx
*
* DESCRIPTION
* implementation of the pqxx::connection and sibling classes.
* Different ways of setting up a backend connection.
*
* Copyright (c) 2001-2005, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/connection"
using namespace PGSTD;
pqxx::connection::connection() :
connection_base(0)
{
do_startconnect();
}
pqxx::connection::connection(const string &ConnInfo) :
connection_base(ConnInfo)
{
do_startconnect();
}
pqxx::connection::connection(const char ConnInfo[]) :
connection_base(ConnInfo)
{
do_startconnect();
}
void pqxx::connection::do_startconnect()
{
if (!get_conn()) set_conn(PQconnectdb(options()));
}
void pqxx::lazyconnection::completeconnect()
{
if (!get_conn()) set_conn(PQconnectdb(options()));
}
pqxx::asyncconnection::asyncconnection() :
connection_base(0),
m_connecting(false)
{
do_startconnect();
}
pqxx::asyncconnection::asyncconnection(const string &ConnInfo) :
connection_base(ConnInfo),
m_connecting(false)
{
do_startconnect();
}
pqxx::asyncconnection::asyncconnection(const char ConnInfo[]) :
connection_base(ConnInfo),
m_connecting(false)
{
do_startconnect();
}
void pqxx::asyncconnection::do_startconnect()
{
if (get_conn()) return; // Already connecting or connected
m_connecting = false;
set_conn(PQconnectStart(options()));
if (!get_conn()) throw bad_alloc();
if (PQconnectPoll(get_conn()) == PGRES_POLLING_FAILED)
throw broken_connection();
m_connecting = true;
}
void pqxx::asyncconnection::completeconnect()
{
if (!get_conn()) startconnect();
if (!m_connecting) return;
// Our "attempt to connect" state ends here, for better or for worse
m_connecting = false;
if (!get_conn()) throw broken_connection();
PostgresPollingStatusType pollstatus;
do
{
pollstatus = PQconnectPoll(get_conn());
switch (pollstatus)
{
case PGRES_POLLING_FAILED:
throw broken_connection();
case PGRES_POLLING_READING:
wait_read();
break;
case PGRES_POLLING_WRITING:
wait_write();
break;
case PGRES_POLLING_ACTIVE:
case PGRES_POLLING_OK:
break;
}
} while (pollstatus != PGRES_POLLING_OK);
}
pqxx::nullconnection::~nullconnection() throw ()
{
}
// Conflicting workarounds for Windows and SUN CC 5.1; see header
#ifndef _WIN32
pqxx::connection::~connection() throw () { close(); }
pqxx::lazyconnection::~lazyconnection() throw () { close(); }
pqxx::asyncconnection::~asyncconnection() throw () {do_dropconnect(); close();}
#endif // _WIN32
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#if qPlatform_POXIX
#include <time.h>
#endif
#include "../Configuration/Common.h"
#include "../Characters/String.h"
#include "../Debug/Assertions.h"
#include "DateTime.h"
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
/*
********************************************************************************
********************************* Time::GetTimezone ****************************
********************************************************************************
*/
String Time::GetTimezone ()
{
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
return String::FromSDKString (tzInfo.StandardName);
#elif qPlatform_POXIX
// @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
return String::FromSDKString (IsDaylightSavingsTime () ? tzname[1] : tzname[0]);
#else
AssertNotImplemented ();
return String ();
#endif
}
/*
********************************************************************************
*********************** Time::IsDaylightSavingsTime ****************************
********************************************************************************
*/
bool Time::IsDaylightSavingsTime ()
{
static bool sCalledOnce_ = false;
if (not sCalledOnce_) {
DISABLE_COMPILER_MSC_WARNING_START(4996)// MSVC warns tzset() unsafe, but I think the way I use it will be safe
tzset ();
DISABLE_COMPILER_MSC_WARNING_END(4996)
sCalledOnce_ = true;
}
DISABLE_COMPILER_MSC_WARNING_START(4996)// MSVC warns tzset() unsafe, but I think the way I use it will be safe
return !!daylight;
DISABLE_COMPILER_MSC_WARNING_END(4996)
}
bool Time::IsDaylightSavingsTime (const DateTime& d)
{
struct tm asTM = d.As<struct tm> ();
asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
// THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
// So far it seems too however, --LGP 2011-10-15
time_t result = mktime (&asTM);
return asTM.tm_isdst >= 1;
}
/*
********************************************************************************
********************* Time::GetLocaltimeToGMTOffset ****************************
********************************************************************************
*/
time_t Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins);
#endif
#endif
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
tm.tm_isdst = applyDST;
time_t result = mktime (&tm);
return result;
}
fixed typo
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#if qPlatform_POSIX
#include <time.h>
#endif
#include "../Configuration/Common.h"
#include "../Characters/String.h"
#include "../Debug/Assertions.h"
#include "DateTime.h"
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
/*
********************************************************************************
********************************* Time::GetTimezone ****************************
********************************************************************************
*/
String Time::GetTimezone ()
{
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
return String::FromSDKString (tzInfo.StandardName);
#elif qPlatform_POSIX
// @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
return String::FromSDKString (IsDaylightSavingsTime () ? tzname[1] : tzname[0]);
#else
AssertNotImplemented ();
return String ();
#endif
}
/*
********************************************************************************
*********************** Time::IsDaylightSavingsTime ****************************
********************************************************************************
*/
bool Time::IsDaylightSavingsTime ()
{
static bool sCalledOnce_ = false;
if (not sCalledOnce_) {
DISABLE_COMPILER_MSC_WARNING_START(4996)// MSVC warns tzset() unsafe, but I think the way I use it will be safe
tzset ();
DISABLE_COMPILER_MSC_WARNING_END(4996)
sCalledOnce_ = true;
}
DISABLE_COMPILER_MSC_WARNING_START(4996)// MSVC warns tzset() unsafe, but I think the way I use it will be safe
return !!daylight;
DISABLE_COMPILER_MSC_WARNING_END(4996)
}
bool Time::IsDaylightSavingsTime (const DateTime& d)
{
struct tm asTM = d.As<struct tm> ();
asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
// THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
// So far it seems too however, --LGP 2011-10-15
time_t result = mktime (&asTM);
return asTM.tm_isdst >= 1;
}
/*
********************************************************************************
********************* Time::GetLocaltimeToGMTOffset ****************************
********************************************************************************
*/
time_t Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins);
#endif
#endif
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
tm.tm_isdst = applyDST;
time_t result = mktime (&tm);
return result;
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"
#include "mitkTestingMacros.h"
#include "mitkIGTTimeStamp.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
#include "mitkIGTConfig.h"
static void TestInstantiation()
{
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
// first test: did this work?
// using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
// it makes no sense to continue without an object.
MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");
}
static void TestSimpleDataPlay()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string fileName(MITK_IGT_DATA_DIR);
fileName.append("/NavigationDataTestData.xml");
player->SetFileName( fileName );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), fileName.c_str()) == 0, "Testing SetFileName and GetFileName");
//exception is thrown in StartPlaying method
player->StartPlaying();
player->Update();
player->StopPlaying();;
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( fileName );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::IGTTimeStamp::Pointer timer = mitk::IGTTimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
}
static void TestPauseAndResume()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string fileName(MITK_IGT_DATA_DIR);
fileName.append("/NavigationDataTestData.xml");
player->SetFileName( fileName );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), fileName.c_str()) == 0, "Testing SetFileName and GetFileName");
player->StartPlaying();
player->Update();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
MITK_TEST_OUTPUT(<<"Test double call of Pause() method!");
player->Pause(); //test pause method
player->Pause(); //call again to see if this causes an error
MITK_TEST_OUTPUT(<<"Test double call of Resume() method!");
player->Resume(); //test resume method
player->Resume(); //call again to see if this causes an error
player->Update();
player->StopPlaying();
player = mitk::NavigationDataPlayer::New();
player->SetFileName( fileName );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::IGTTimeStamp::Pointer timer = mitk::IGTTimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #0");
while( times.size()<3 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
MITK_TEST_OUTPUT(<<"Test pause method!");
player->Pause();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #1");
MITK_TEST_OUTPUT(<<"Test resume method!");
player->Resume();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
MITK_TEST_CONDITION_REQUIRED(player->IsAtEnd(), "Testing method IsAtEnd() #2");
}
static void TestInvalidStream()
{
MITK_TEST_OUTPUT(<<"#### Testing invalid input data: errors are expected. ####");
//declarate test variables
mitk::NavigationDataPlayer::Pointer player;
std::string file;
//case 0: stream not set
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException0 = false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException0=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#0: Tested stream not set. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException0, "Testing Invalid Stream method if exception (stream not set) was thrown.");
//case 1: non-existing file
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException1 = false;
player->SetFileName( "ffdsd" );
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException1=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#1: Tested non-existing file. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException1, "Testing Invalid Stream method if exception (non-existing file) was thrown.");
//case 2: wrong file format
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException2 = false;
file = MITK_IGT_DATA_DIR;
file.append("/SROMFile.rom");
player->SetFileName( file );
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException2=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#2: Tested wrong file format. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException2, "Testing Invalid Stream method if exception (wrong file format) was thrown.");
//case 3: wrong file version
player = mitk::NavigationDataPlayer::New();
file = MITK_IGT_DATA_DIR;
file.append("/InvalidVersionNavigationDataTestData.xml");
player->SetFileName( file );
bool InvalidStreamException3 = false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException3 = true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#3: Tested wrong file version. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException3, "Testing Invalid Stream method if exception (wrong file version) was thrown.");
//case 4: wrong file
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "cs:\fsd/$%ffdsd" );
bool InvalidStreamException4=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException4=true;
MITK_TEST_OUTPUT(<<"#4: Tested wrong file. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException4, "Testing Invalid Stream method if exception (wrong file) was thrown.");
//case 5: null stream
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException5=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException5=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#5: Tested null stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException5, "Testing Invalid Stream method if exception (null stream) was thrown.");
//case 6: empty stream, exception is thrown in setstream
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException6=false;
std::ifstream* myEmptyStream = NULL;
try
{
myEmptyStream = new std::ifstream("");
player->SetStream( myEmptyStream );
}
catch(mitk::IGTException)
{
InvalidStreamException6=true;
MITK_TEST_OUTPUT(<<"#6: Tested empty stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException6, "Testing Invalid Stream method if exception (empty stream) was thrown.");
//case 7: wrong stream
player = mitk::NavigationDataPlayer::New();
file = MITK_IGT_DATA_DIR;
file.append("/SROMFile.rom");
bool InvalidStreamException7=false;
std::ifstream* myWrongStream;
myWrongStream = new std::ifstream(file.c_str());
try
{
player->SetStream( myWrongStream );
}
catch(mitk::IGTIOException)
{
InvalidStreamException7=true;
MITK_TEST_OUTPUT(<<"#7: Tested wrong stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException7, "Testing Invalid Stream method if exception (wrong stream) was thrown.");
//case 8: invalid
player = mitk::NavigationDataPlayer::New();
file=MITK_IGT_DATA_DIR;
file.append("/InvalidDataNavigationDataTestData.xml");
player->SetFileName( file );
bool InvalidStreamException8=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTIOException)
{
InvalidStreamException8=true;
MITK_TEST_OUTPUT(<<"#8: Tested invalid file version. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException8, "Testing Invalid Stream method if exception (Invalid) was thrown.");
//clean up
delete myEmptyStream;
delete myWrongStream;
}
static void TestSetStreamExceptions()
{
mitk::NavigationDataPlayer::Pointer myTestPlayer = mitk::NavigationDataPlayer::New();
std::string file(MITK_IGT_DATA_DIR);
file.append("/NavigationDataTestData.xml");
myTestPlayer->SetFileName( file );
bool exceptionThrown=false;
try
{
std::istream* stream=NULL;
myTestPlayer->SetStream(stream);
}
catch(mitk::IGTException)
{
exceptionThrown = true;
MITK_TEST_OUTPUT(<<"#9: Tested exceptions in SetStream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown, "Testing SetStream method in exception was thrown.");
}
static void TestStartPlayingExceptions()
{
MITK_INFO <<"In the following, exceptions are tested. Errors will occur and are expected.";
//Case1 Testing if stream=NULL
mitk::NavigationDataPlayer::Pointer myTestPlayer1 = mitk::NavigationDataPlayer::New();
bool exceptionThrown1 = false;
try
{
myTestPlayer1->StartPlaying();
}
catch(mitk::IGTException)
{
exceptionThrown1 = true;
myTestPlayer1->StopPlaying();
MITK_TEST_OUTPUT(<<"#10: Tested exception for the case when stream=NULL in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown1, "Testing StartPlaying method if exception (stream=NULL) was thrown.");
//Case2 Testing if file does not exist
mitk::NavigationDataPlayer::Pointer myTestPlayer2 = mitk::NavigationDataPlayer::New();
myTestPlayer2->SetFileName("ffdsd");
bool exceptionThrown2 = false;
try{
myTestPlayer2->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown2 = true;
myTestPlayer2->StopPlaying();
MITK_TEST_OUTPUT(<<"#11: Tested exception for the case when file does not exist in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown2, "Testing StartPlaying method if exception is thrown when file does not exist.");
//Case3 Testing if wrong file format
mitk::NavigationDataPlayer::Pointer myTestPlayer3 = mitk::NavigationDataPlayer::New();
std::string file3(MITK_IGT_DATA_DIR);
file3.append("/SROMFile.rom");
myTestPlayer3->SetFileName( file3 );
bool exceptionThrown3 = false;
try{
myTestPlayer3->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown3 = true;
myTestPlayer3->StopPlaying();
MITK_TEST_OUTPUT(<<"#12: Tested exception for the case when file format is wrong in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown3, "Testing StartPlaying method if exception (file format is wrong) was thrown.");
//Case4 Testing if wrong file version
mitk::NavigationDataPlayer::Pointer myTestPlayer4 = mitk::NavigationDataPlayer::New();
std::string file4(MITK_IGT_DATA_DIR);
file4.append("/InvalidVersionNavigationDataTestData.xml");
myTestPlayer4->SetFileName( file3 );
bool exceptionThrown4 = false;
try{
myTestPlayer4->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown4 = true;
myTestPlayer4->StopPlaying();
MITK_TEST_OUTPUT(<<"#13: Tested exception for the case when file version is wrong in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown4, "Testing StartPlaying method if exception (file version is wrong) was thrown.");
//Case5 Testing if not existing file name
mitk::NavigationDataPlayer::Pointer myTestPlayer5 = mitk::NavigationDataPlayer::New();
myTestPlayer5->SetFileName("ffdsd");
bool exceptionThrown5 = false;
try{
myTestPlayer5->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown5 = true;
myTestPlayer5->StopPlaying();
MITK_TEST_OUTPUT(<<"#14: Tested exception for the case when non-existing file name in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown5, "Testing StartPlaying method if exception (non-existing file name) was thrown.");
}
/**Documentation
* test for the class "NavigationDataPlayer".
*/
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationDataPlayer");
std::string tmp = "";
TestInstantiation();
TestSimpleDataPlay();
TestSetStreamExceptions();
TestStartPlayingExceptions();
TestPauseAndResume();
TestInvalidStream();
// always end with this!
MITK_TEST_END();
}
Enable WARNINGS_AS_ERRORS for modules caused a error for character encoding
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"
#include "mitkTestingMacros.h"
#include "mitkIGTTimeStamp.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "mitkIGTException.h"
#include "mitkIGTIOException.h"
#include "mitkIGTConfig.h"
static void TestInstantiation()
{
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
// first test: did this work?
// using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
// it makes no sense to continue without an object.
MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");
}
static void TestSimpleDataPlay()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string fileName(MITK_IGT_DATA_DIR);
fileName.append("/NavigationDataTestData.xml");
player->SetFileName( fileName );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), fileName.c_str()) == 0, "Testing SetFileName and GetFileName");
//exception is thrown in StartPlaying method
player->StartPlaying();
player->Update();
player->StopPlaying();;
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( fileName );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::IGTTimeStamp::Pointer timer = mitk::IGTTimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
}
static void TestPauseAndResume()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string fileName(MITK_IGT_DATA_DIR);
fileName.append("/NavigationDataTestData.xml");
player->SetFileName( fileName );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), fileName.c_str()) == 0, "Testing SetFileName and GetFileName");
player->StartPlaying();
player->Update();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
MITK_TEST_OUTPUT(<<"Test double call of Pause() method!");
player->Pause(); //test pause method
player->Pause(); //call again to see if this causes an error
MITK_TEST_OUTPUT(<<"Test double call of Resume() method!");
player->Resume(); //test resume method
player->Resume(); //call again to see if this causes an error
player->Update();
player->StopPlaying();
player = mitk::NavigationDataPlayer::New();
player->SetFileName( fileName );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::IGTTimeStamp::Pointer timer = mitk::IGTTimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #0");
while( times.size()<3 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
MITK_TEST_OUTPUT(<<"Test pause method!");
player->Pause();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #1");
MITK_TEST_OUTPUT(<<"Test resume method!");
player->Resume();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
MITK_TEST_CONDITION_REQUIRED(player->IsAtEnd(), "Testing method IsAtEnd() #2");
}
static void TestInvalidStream()
{
MITK_TEST_OUTPUT(<<"#### Testing invalid input data: errors are expected. ####");
//declarate test variables
mitk::NavigationDataPlayer::Pointer player;
std::string file;
//case 0: stream not set
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException0 = false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException0=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#0: Tested stream not set. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException0, "Testing Invalid Stream method if exception (stream not set) was thrown.");
//case 1: non-existing file
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException1 = false;
player->SetFileName( "ffdsd" );
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException1=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#1: Tested non-existing file. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException1, "Testing Invalid Stream method if exception (non-existing file) was thrown.");
//case 2: wrong file format
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException2 = false;
file = MITK_IGT_DATA_DIR;
file.append("/SROMFile.rom");
player->SetFileName( file );
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException2=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#2: Tested wrong file format. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException2, "Testing Invalid Stream method if exception (wrong file format) was thrown.");
//case 3: wrong file version
player = mitk::NavigationDataPlayer::New();
file = MITK_IGT_DATA_DIR;
file.append("/InvalidVersionNavigationDataTestData.xml");
player->SetFileName( file );
bool InvalidStreamException3 = false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException3 = true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#3: Tested wrong file version. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException3, "Testing Invalid Stream method if exception (wrong file version) was thrown.");
//case 4: wrong file
/* remove test case caused by wrong string encoding
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "cs:\fsd/$%ffdsd" );
bool InvalidStreamException4=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException4=true;
MITK_TEST_OUTPUT(<<"#4: Tested wrong file. Application should not crash.");
}
*/
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException4, "Testing Invalid Stream method if exception (wrong file) was thrown.");
//case 5: null stream
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException5=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTException)
{
InvalidStreamException5=true;
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#5: Tested null stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException5, "Testing Invalid Stream method if exception (null stream) was thrown.");
//case 6: empty stream, exception is thrown in setstream
player = mitk::NavigationDataPlayer::New();
bool InvalidStreamException6=false;
std::ifstream* myEmptyStream = NULL;
try
{
myEmptyStream = new std::ifstream("");
player->SetStream( myEmptyStream );
}
catch(mitk::IGTException)
{
InvalidStreamException6=true;
MITK_TEST_OUTPUT(<<"#6: Tested empty stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException6, "Testing Invalid Stream method if exception (empty stream) was thrown.");
//case 7: wrong stream
player = mitk::NavigationDataPlayer::New();
file = MITK_IGT_DATA_DIR;
file.append("/SROMFile.rom");
bool InvalidStreamException7=false;
std::ifstream* myWrongStream;
myWrongStream = new std::ifstream(file.c_str());
try
{
player->SetStream( myWrongStream );
}
catch(mitk::IGTIOException)
{
InvalidStreamException7=true;
MITK_TEST_OUTPUT(<<"#7: Tested wrong stream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException7, "Testing Invalid Stream method if exception (wrong stream) was thrown.");
//case 8: invalid
player = mitk::NavigationDataPlayer::New();
file=MITK_IGT_DATA_DIR;
file.append("/InvalidDataNavigationDataTestData.xml");
player->SetFileName( file );
bool InvalidStreamException8=false;
try
{
player->StartPlaying();
}
catch(mitk::IGTIOException)
{
InvalidStreamException8=true;
MITK_TEST_OUTPUT(<<"#8: Tested invalid file version. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(InvalidStreamException8, "Testing Invalid Stream method if exception (Invalid) was thrown.");
//clean up
delete myEmptyStream;
delete myWrongStream;
}
static void TestSetStreamExceptions()
{
mitk::NavigationDataPlayer::Pointer myTestPlayer = mitk::NavigationDataPlayer::New();
std::string file(MITK_IGT_DATA_DIR);
file.append("/NavigationDataTestData.xml");
myTestPlayer->SetFileName( file );
bool exceptionThrown=false;
try
{
std::istream* stream=NULL;
myTestPlayer->SetStream(stream);
}
catch(mitk::IGTException)
{
exceptionThrown = true;
MITK_TEST_OUTPUT(<<"#9: Tested exceptions in SetStream. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown, "Testing SetStream method in exception was thrown.");
}
static void TestStartPlayingExceptions()
{
MITK_INFO <<"In the following, exceptions are tested. Errors will occur and are expected.";
//Case1 Testing if stream=NULL
mitk::NavigationDataPlayer::Pointer myTestPlayer1 = mitk::NavigationDataPlayer::New();
bool exceptionThrown1 = false;
try
{
myTestPlayer1->StartPlaying();
}
catch(mitk::IGTException)
{
exceptionThrown1 = true;
myTestPlayer1->StopPlaying();
MITK_TEST_OUTPUT(<<"#10: Tested exception for the case when stream=NULL in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown1, "Testing StartPlaying method if exception (stream=NULL) was thrown.");
//Case2 Testing if file does not exist
mitk::NavigationDataPlayer::Pointer myTestPlayer2 = mitk::NavigationDataPlayer::New();
myTestPlayer2->SetFileName("ffdsd");
bool exceptionThrown2 = false;
try{
myTestPlayer2->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown2 = true;
myTestPlayer2->StopPlaying();
MITK_TEST_OUTPUT(<<"#11: Tested exception for the case when file does not exist in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown2, "Testing StartPlaying method if exception is thrown when file does not exist.");
//Case3 Testing if wrong file format
mitk::NavigationDataPlayer::Pointer myTestPlayer3 = mitk::NavigationDataPlayer::New();
std::string file3(MITK_IGT_DATA_DIR);
file3.append("/SROMFile.rom");
myTestPlayer3->SetFileName( file3 );
bool exceptionThrown3 = false;
try{
myTestPlayer3->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown3 = true;
myTestPlayer3->StopPlaying();
MITK_TEST_OUTPUT(<<"#12: Tested exception for the case when file format is wrong in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown3, "Testing StartPlaying method if exception (file format is wrong) was thrown.");
//Case4 Testing if wrong file version
mitk::NavigationDataPlayer::Pointer myTestPlayer4 = mitk::NavigationDataPlayer::New();
std::string file4(MITK_IGT_DATA_DIR);
file4.append("/InvalidVersionNavigationDataTestData.xml");
myTestPlayer4->SetFileName( file3 );
bool exceptionThrown4 = false;
try{
myTestPlayer4->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown4 = true;
myTestPlayer4->StopPlaying();
MITK_TEST_OUTPUT(<<"#13: Tested exception for the case when file version is wrong in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown4, "Testing StartPlaying method if exception (file version is wrong) was thrown.");
//Case5 Testing if not existing file name
mitk::NavigationDataPlayer::Pointer myTestPlayer5 = mitk::NavigationDataPlayer::New();
myTestPlayer5->SetFileName("ffdsd");
bool exceptionThrown5 = false;
try{
myTestPlayer5->StartPlaying();
}
catch(mitk::IGTIOException)
{
exceptionThrown5 = true;
myTestPlayer5->StopPlaying();
MITK_TEST_OUTPUT(<<"#14: Tested exception for the case when non-existing file name in StartPlaying. Application should not crash.");
}
MITK_TEST_CONDITION_REQUIRED(exceptionThrown5, "Testing StartPlaying method if exception (non-existing file name) was thrown.");
}
/**Documentation
* test for the class "NavigationDataPlayer".
*/
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationDataPlayer");
std::string tmp = "";
TestInstantiation();
TestSimpleDataPlay();
TestSetStreamExceptions();
TestStartPlayingExceptions();
TestPauseAndResume();
TestInvalidStream();
// always end with this!
MITK_TEST_END();
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkPythonVariableStackTableView.h"
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
#include <mitkRenderingManager.h>
#include <mitkSurface.h>
QmitkPythonVariableStackTableView::QmitkPythonVariableStackTableView(QWidget *parent)
:QTableView(parent)
{
m_TableModel = new QmitkPythonVariableStackTableModel(parent);
m_TableModel->CommandExecuted("");
this->setSelectionBehavior( QAbstractItemView::SelectRows );
this->setAlternatingRowColors(true);
this->setDropIndicatorShown(true);
this->setAcceptDrops(true);
this->setModel( m_TableModel );
us::ModuleContext* context = us::GetModuleContext();
us::ServiceReference<mitk::IPythonService> serviceRef = context->GetServiceReference<mitk::IPythonService>();
m_PythonService = context->GetService<mitk::IPythonService>(serviceRef);
connect( this, SIGNAL(doubleClicked ( const QModelIndex& )), this, SLOT( OnVariableStackDoubleClicked(const QModelIndex&) ) );
}
QmitkPythonVariableStackTableView::~QmitkPythonVariableStackTableView()
{
}
void QmitkPythonVariableStackTableView::SetDataStorage(mitk::DataStorage *_DataStorage)
{
m_DataStorage = _DataStorage;
}
void QmitkPythonVariableStackTableView::OnVariableStackDoubleClicked(const QModelIndex &index)
{
if( m_DataStorage.IsNull() || m_PythonService == 0 )
{
MITK_ERROR << "QmitkPythonVariableStackTableView not configured correctly. Quit";
return;
}
int row = index.row();
std::vector<mitk::PythonVariable> variableStack = m_TableModel->GetVariableStack();
{
MITK_DEBUG("QmitkPythonVariableStackTableView") << "row " << row;
MITK_DEBUG("QmitkPythonVariableStackTableView") << "variableStack.size(): " << variableStack.size();
}
QString varName = QString::fromStdString( variableStack.at(row).m_Name );
QString type = QString::fromStdString( variableStack.at(row).m_Type );
QString value = QString::fromStdString( variableStack.at(row).m_Value );
{
MITK_DEBUG("QmitkPythonVariableStackTableView") << "varName: " << varName.toStdString();
MITK_DEBUG("QmitkPythonVariableStackTableView") << "type: " << type.toStdString();
}
mitk::Image::Pointer mitkImage;
mitk::Surface::Pointer mitkSurface;
if( type.startsWith("itkImage") )
{
mitkImage = m_PythonService->CopyItkImageFromPython(varName.toStdString());
}
else if( type.startsWith("numpy.ndarray") )
{
mitkImage = m_PythonService->CopyCvImageFromPython(varName.toStdString());
}
else if( value.startsWith("(vtkPolyData)") )
{
mitkSurface = m_PythonService->CopyVtkPolyDataFromPython(varName.toStdString());
}
std::string nodeName = varName.toStdString();
mitk::DataNode::Pointer node = mitk::DataNode::New();
node->SetName ( nodeName );
if( mitkImage.IsNotNull() )
{
node->SetData( mitkImage );
}
else if( mitkSurface.IsNotNull() )
{
node->SetData( mitkSurface );
}
m_DataStorage->Add(node);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
replacing data in nodes when node is already present, init view based on geometry on new objects
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkPythonVariableStackTableView.h"
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
#include <mitkRenderingManager.h>
#include <mitkSurface.h>
#include <vtkPolyData.h>
QmitkPythonVariableStackTableView::QmitkPythonVariableStackTableView(QWidget *parent)
:QTableView(parent)
{
m_TableModel = new QmitkPythonVariableStackTableModel(parent);
m_TableModel->CommandExecuted("");
this->setSelectionBehavior( QAbstractItemView::SelectRows );
this->setAlternatingRowColors(true);
this->setDropIndicatorShown(true);
this->setAcceptDrops(true);
this->setModel( m_TableModel );
us::ModuleContext* context = us::GetModuleContext();
us::ServiceReference<mitk::IPythonService> serviceRef = context->GetServiceReference<mitk::IPythonService>();
m_PythonService = context->GetService<mitk::IPythonService>(serviceRef);
connect( this, SIGNAL(doubleClicked ( const QModelIndex& )), this, SLOT( OnVariableStackDoubleClicked(const QModelIndex&) ) );
}
QmitkPythonVariableStackTableView::~QmitkPythonVariableStackTableView()
{
}
void QmitkPythonVariableStackTableView::SetDataStorage(mitk::DataStorage *_DataStorage)
{
m_DataStorage = _DataStorage;
}
void QmitkPythonVariableStackTableView::OnVariableStackDoubleClicked(const QModelIndex &index)
{
if( m_DataStorage.IsNull() || m_PythonService == 0 )
{
MITK_ERROR << "QmitkPythonVariableStackTableView not configured correctly. Quit";
return;
}
int row = index.row();
std::vector<mitk::PythonVariable> variableStack = m_TableModel->GetVariableStack();
{
MITK_DEBUG("QmitkPythonVariableStackTableView") << "row " << row;
MITK_DEBUG("QmitkPythonVariableStackTableView") << "variableStack.size(): " << variableStack.size();
}
QString varName = QString::fromStdString( variableStack.at(row).m_Name );
QString type = QString::fromStdString( variableStack.at(row).m_Type );
QString value = QString::fromStdString( variableStack.at(row).m_Value );
{
MITK_DEBUG("QmitkPythonVariableStackTableView") << "varName: " << varName.toStdString();
MITK_DEBUG("QmitkPythonVariableStackTableView") << "type: " << type.toStdString();
}
mitk::Image::Pointer mitkImage;
mitk::Surface::Pointer mitkSurface;
if( type.startsWith("itkImage") )
{
mitkImage = m_PythonService->CopyItkImageFromPython(varName.toStdString());
}
else if( type.startsWith("numpy.ndarray") )
{
mitkImage = m_PythonService->CopyCvImageFromPython(varName.toStdString());
}
else if( value.startsWith("(vtkPolyData)") )
{
mitkSurface = m_PythonService->CopyVtkPolyDataFromPython(varName.toStdString());
}
std::string nodeName = varName.toStdString();
mitk::DataNode::Pointer node = m_DataStorage->GetNamedNode(nodeName);
// only create data node if it does not exist
if ( node.IsNull() )
{
node = mitk::DataNode::New();
node->SetName ( nodeName );
m_DataStorage->Add(node);
}
if( mitkImage.IsNotNull() )
{
node->SetData( mitkImage );
}
else if( mitkSurface.IsNotNull() )
{
node->SetData( mitkSurface );
// init renderwindow geometry
mitk::RenderingManager::GetInstance()->InitializeViews(mitkSurface->GetGeometry());
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
|
/**
* Copyright (c) 2014, Facebook, Inc.
* Copyright (c) 2003-2014 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* This file is distributed under the University of Illinois Open Source License.
* See LLVM-LICENSE for details.
*
*/
/**
* Clang frontend plugin to export an AST of clang into Json and Yojson (and ultimately Biniou)
* while conforming to the inlined ATD specifications.
*
* /!\
* '\atd' block comments are meant to be extracted and processed to generate ATD specifications for the Json dumper.
* Do not modify ATD comments without modifying the Json emission accordingly (and conversely).
* See ATD_GUIDELINES.md for more guidelines on how to write and test ATD annotations.
*
* This file was obtained by modifying the file ASTdumper.cpp from the LLVM/clang project.
* The general layout should be maintained to make future merging easier.
*/
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Attr.h>
#include <clang/AST/CommentVisitor.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclLookups.h>
#include <clang/AST/DeclObjC.h>
#include <clang/AST/DeclVisitor.h>
#include <clang/AST/StmtVisitor.h>
#include <clang/Basic/Module.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendDiagnostic.h>
#include <llvm/Support/raw_ostream.h>
#include "atdlib/ATDWriter.h"
#include "SimplePluginASTAction.h"
#include "FileUtils.h"
using namespace clang;
using namespace clang::comments;
//===----------------------------------------------------------------------===//
// ASTExporter Visitor
//===----------------------------------------------------------------------===//
namespace {
typedef ATDWriter::JsonWriter<raw_ostream> JsonWriter;
typedef ATDWriter::YojsonWriter<raw_ostream> YojsonWriter;
template <class ATDWriter = YojsonWriter>
class ASTExporter :
public ConstDeclVisitor<ASTExporter<ATDWriter>>,
public ConstStmtVisitor<ASTExporter<ATDWriter>>,
public ConstCommentVisitor<ASTExporter<ATDWriter>>
{
typedef typename ATDWriter::ObjectScope ObjectScope;
typedef typename ATDWriter::ArrayScope ArrayScope;
typedef typename ATDWriter::TupleScope TupleScope;
typedef typename ATDWriter::VariantScope VariantScope;
ATDWriter OF;
const CommandTraits &Traits;
const SourceManager &SM;
// Optional currentWorkingDirectory to normalize relative paths.
StringRef BasePath;
// Optional service to avoid repeating the content of a same header file across a compilation.
FileUtils::DeduplicationService *DedupService;
// Encoding of NULL pointers into suitable empty nodes
// This is a hack but using option types in children lists would make the Json terribly verbose.
// Also these useless nodes could have occurred in the original AST anyway :)
//
// Note: We are not using OwningPtr because 'delete' appears to be protected (at least on Stmt).
const Stmt *const NullPtrStmt;
const Decl *const NullPtrDecl;
const Comment *const NullPtrComment;
/// Keep track of the last location we print out so that we can
/// print out deltas from then on out.
const char *LastLocFilename;
unsigned LastLocLine;
/// The \c FullComment parent of the comment being dumped.
const FullComment *FC;
public:
ASTExporter(raw_ostream &OS, ASTContext &Context, StringRef BasePath, FileUtils::DeduplicationService *DedupService)
: OF(OS),
Traits(Context.getCommentCommandTraits()),
SM(Context.getSourceManager()),
BasePath(BasePath),
DedupService(DedupService),
NullPtrStmt(new (Context) NullStmt(SourceLocation())),
NullPtrDecl(EmptyDecl::Create(Context, Context.getTranslationUnitDecl(), SourceLocation())),
NullPtrComment(new (Context) Comment(Comment::NoCommentKind, SourceLocation(), SourceLocation())),
LastLocFilename(""), LastLocLine(~0U), FC(0)
{
}
void dumpBareDecl(const Decl *D);
void dumpBareStmt(const Stmt *S);
void dumpFullComment(const FullComment *C);
// Utilities
void dumpBarePointer(const void *Ptr);
void dumpSourceRange(SourceRange R);
void dumpBareSourceLocation(SourceLocation Loc);
void dumpBareQualType(QualType T);
void dumpBareType(const Type *T);
void dumpQualType(QualType T);
void dumpBareDeclRef(const Decl &Node);
void dumpDeclRef(const Decl *Node, const char *Label = 0);
void dumpName(const NamedDecl *D);
bool hasNodes(const DeclContext *DC);
void dumpBareLookups(const DeclContext &DC);
void dumpBareAttr(const Attr &A);
void dumpBareSelector(const Selector sel);
// C++ Utilities
void dumpAccessSpecifier(AccessSpecifier AS);
void dumpBareCXXCtorInitializer(const CXXCtorInitializer &Init);
// void dumpTemplateParameters(const TemplateParameterList *TPL);
// void dumpTemplateArgumentListInfo(const TemplateArgumentListInfo &TALI);
// void dumpTemplateArgumentLoc(const TemplateArgumentLoc &A);
// void dumpTemplateArgumentList(const TemplateArgumentList &TAL);
// void dumpTemplateArgument(const TemplateArgument &A,
// SourceRange R = SourceRange());
void dumpBareCXXBaseSpecifier(const CXXBaseSpecifier &Base);
// Decls
void VisitDecl(const Decl *D);
void VisitDeclContext(const DeclContext *DC);
void VisitBlockDecl(const BlockDecl *D);
void VisitCapturedDecl(const CapturedDecl *D);
void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
void VisitNamespaceDecl(const NamespaceDecl *D);
void VisitObjCContainerDecl(const ObjCContainerDecl *D);
void VisitTagDecl(const TagDecl *D);
void VisitTypeDecl(const TypeDecl *D);
void VisitTranslationUnitDecl(const TranslationUnitDecl *D);
void VisitNamedDecl(const NamedDecl *D);
void VisitValueDecl(const ValueDecl *D);
void VisitTypedefDecl(const TypedefDecl *D);
void VisitEnumDecl(const EnumDecl *D);
void VisitRecordDecl(const RecordDecl *D);
void VisitEnumConstantDecl(const EnumConstantDecl *D);
void VisitIndirectFieldDecl(const IndirectFieldDecl *D);
void VisitFunctionDecl(const FunctionDecl *D);
void VisitFieldDecl(const FieldDecl *D);
void VisitVarDecl(const VarDecl *D);
void VisitFileScopeAsmDecl(const FileScopeAsmDecl *D);
void VisitImportDecl(const ImportDecl *D);
// // C++ Decls
// void VisitNamespaceDecl(const NamespaceDecl *D);
// void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D);
// void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
// void VisitTypeAliasDecl(const TypeAliasDecl *D);
// void VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D);
// void VisitCXXRecordDecl(const CXXRecordDecl *D);
// void VisitStaticAssertDecl(const StaticAssertDecl *D);
// void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
// void VisitClassTemplateDecl(const ClassTemplateDecl *D);
// void VisitClassTemplateSpecializationDecl(
// const ClassTemplateSpecializationDecl *D);
// void VisitClassTemplatePartialSpecializationDecl(
// const ClassTemplatePartialSpecializationDecl *D);
// void VisitClassScopeFunctionSpecializationDecl(
// const ClassScopeFunctionSpecializationDecl *D);
// void VisitVarTemplateDecl(const VarTemplateDecl *D);
// void VisitVarTemplateSpecializationDecl(
// const VarTemplateSpecializationDecl *D);
// void VisitVarTemplatePartialSpecializationDecl(
// const VarTemplatePartialSpecializationDecl *D);
// void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
// void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
// void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
// void VisitUsingDecl(const UsingDecl *D);
// void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
// void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
// void VisitUsingShadowDecl(const UsingShadowDecl *D);
// void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
// void VisitAccessSpecDecl(const AccessSpecDecl *D);
// void VisitFriendDecl(const FriendDecl *D);
//
// // ObjC Decls
void VisitObjCIvarDecl(const ObjCIvarDecl *D);
void VisitObjCMethodDecl(const ObjCMethodDecl *D);
void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
// Stmts.
void VisitStmt(const Stmt *Node);
void VisitDeclStmt(const DeclStmt *Node);
void VisitAttributedStmt(const AttributedStmt *Node);
void VisitLabelStmt(const LabelStmt *Node);
void VisitGotoStmt(const GotoStmt *Node);
void VisitCXXCatchStmt(const CXXCatchStmt *Node);
// Exprs
void VisitExpr(const Expr *Node);
void VisitCastExpr(const CastExpr *Node);
void VisitExplicitCastExpr(const ExplicitCastExpr *Node);
void VisitDeclRefExpr(const DeclRefExpr *Node);
void VisitPredefinedExpr(const PredefinedExpr *Node);
void VisitCharacterLiteral(const CharacterLiteral *Node);
void VisitIntegerLiteral(const IntegerLiteral *Node);
void VisitFloatingLiteral(const FloatingLiteral *Node);
void VisitStringLiteral(const StringLiteral *Str);
void VisitUnaryOperator(const UnaryOperator *Node);
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Node);
void VisitMemberExpr(const MemberExpr *Node);
void VisitExtVectorElementExpr(const ExtVectorElementExpr *Node);
void VisitBinaryOperator(const BinaryOperator *Node);
void VisitCompoundAssignOperator(const CompoundAssignOperator *Node);
void VisitAddrLabelExpr(const AddrLabelExpr *Node);
void VisitBlockExpr(const BlockExpr *Node);
void VisitOpaqueValueExpr(const OpaqueValueExpr *Node);
// C++
void VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node);
void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
void VisitCXXConstructExpr(const CXXConstructExpr *Node);
// void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
// void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node);
// void VisitExprWithCleanups(const ExprWithCleanups *Node);
// void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node);
// void dumpCXXTemporary(const CXXTemporary *Temporary);
// void VisitLambdaExpr(const LambdaExpr *Node) {
// VisitExpr(Node);
// dumpBareDecl(Node->getLambdaClass());
// }
// ObjC
void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node);
void VisitObjCEncodeExpr(const ObjCEncodeExpr *Node);
void VisitObjCMessageExpr(const ObjCMessageExpr *Node);
void VisitObjCBoxedExpr(const ObjCBoxedExpr *Node);
void VisitObjCSelectorExpr(const ObjCSelectorExpr *Node);
void VisitObjCProtocolExpr(const ObjCProtocolExpr *Node);
void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node);
void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node);
void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node);
void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node);
// Comments.
const char *getCommandName(unsigned CommandID);
void dumpBareComment(const Comment *C);
// Inline comments.
void visitComment(const Comment *C);
void visitTextComment(const TextComment *C);
// void visitInlineCommandComment(const InlineCommandComment *C);
// void visitHTMLStartTagComment(const HTMLStartTagComment *C);
// void visitHTMLEndTagComment(const HTMLEndTagComment *C);
//
// // Block comments.
// void visitBlockCommandComment(const BlockCommandComment *C);
// void visitParamCommandComment(const ParamCommandComment *C);
// void visitTParamCommandComment(const TParamCommandComment *C);
// void visitVerbatimBlockComment(const VerbatimBlockComment *C);
// void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
// void visitVerbatimLineComment(const VerbatimLineComment *C);
};
}
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// \atd
/// type pointer = string
template <class ATDWriter>
static void dumpBarePointer(ATDWriter &OF, const void *Ptr) {
char str[20];
snprintf(str, 20, "%p", Ptr);
OF.emitString(std::string(str));
}
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBarePointer(const void *Ptr) {
::dumpBarePointer(OF, Ptr);
}
/// \atd
/// type source_location = {
/// ?file : string option;
/// ?line : int option;
/// ?column : int option;
/// } <ocaml field_prefix="sl_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareSourceLocation(SourceLocation Loc) {
ObjectScope Scope(OF);
SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
// The general format we print out is filename:line:col, but we drop pieces
// that haven't changed since the last loc printed.
PresumedLoc PLoc = SM.getPresumedLoc(SpellingLoc);
if (PLoc.isInvalid()) {
return;
}
if (strcmp(PLoc.getFilename(), LastLocFilename) != 0) {
OF.emitTag("file");
// Normalizing filenames matters because the current directory may change during the compilation of large projects.
OF.emitString(FileUtils::normalizePath(BasePath, PLoc.getFilename()));
OF.emitTag("line");
OF.emitInteger(PLoc.getLine());
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
} else if (PLoc.getLine() != LastLocLine) {
OF.emitTag("line");
OF.emitInteger(PLoc.getLine());
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
} else {
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
}
LastLocFilename = PLoc.getFilename();
LastLocLine = PLoc.getLine();
// TODO: lastLocColumn
}
/// \atd
/// type _source_range = {
/// ?source_range : source_range option
/// }
/// type source_range = (source_location * source_location)
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpSourceRange(SourceRange R) {
OF.emitTag("source_range");
TupleScope Scope(OF);
dumpBareSourceLocation(R.getBegin());
dumpBareSourceLocation(R.getEnd());
}
// TODO: really dump types as trees
/// \atd
/// type opt_type = [Type of string | NoType]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareType(const Type *T) {
if (!T) {
OF.emitSimpleVariant("NoType");
} else {
VariantScope Scope(OF, "Type");
OF.emitString(QualType::getAsString(QualType(T, 0).getSplitDesugaredType()));
}
}
/// \atd
/// type qual_type = {
/// raw : string;
/// ?desugared : string option
/// } <ocaml field_prefix="qt_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareQualType(QualType T) {
ObjectScope Scope(OF);
SplitQualType T_split = T.split();
OF.emitTag("raw");
OF.emitString(QualType::getAsString(T_split));
if (!T.isNull()) {
// If the type is sugared, also dump a (shallow) desugared type.
SplitQualType D_split = T.getSplitDesugaredType();
if (T_split != D_split) {
OF.emitTag("desugared");
OF.emitString(QualType::getAsString(D_split));
}
}
}
/// \atd
/// type _qual_type = { qual_type : qual_type }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpQualType(QualType T) {
OF.emitTag("qual_type");
dumpBareQualType(T);
}
/// \atd
/// type _name = { ?name : string option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpName(const NamedDecl *ND) {
if (ND && ND->getDeclName()) {
OF.emitTag("name");
OF.emitString(ND->getNameAsString());
}
}
/// \atd
/// type decl_ref = {
/// kind : decl_kind;
/// inherit _name;
/// ~is_hidden : bool;
/// ?qual_type : qual_type option
/// } <ocaml field_prefix="dr_">
///
/// type decl_kind = [
#define DECL(DERIVED, BASE) /// | DERIVED
#define ABSTRACT_DECL(DECL) DECL
#include <clang/AST/DeclNodes.inc>
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareDeclRef(const Decl &D) {
ObjectScope Scope(OF);
OF.emitTag("kind");
OF.emitSimpleVariant(D.getDeclKindName());
const NamedDecl *ND = dyn_cast<NamedDecl>(&D);
if (ND) {
dumpName(ND);
OF.emitFlag("is_hidden", ND->isHidden());
}
if (const ValueDecl *VD = dyn_cast<ValueDecl>(&D)) {
dumpQualType(VD->getType());
}
}
/// \atd
/// type _decl_ref = { ?decl_ref : decl_ref option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpDeclRef(const Decl *D, const char *Label) {
if (!D)
return;
if (Label) {
// ATD TODO: not supported
OF.emitTag(Label);
} else {
OF.emitTag("decl_ref");
}
dumpBareDeclRef(*D);
}
/// \atd
/// #define decl_context_tuple decl list * decl_context_info
/// type decl_context_info = {
/// ~has_external_lexical_storage : bool;
/// ~has_external_visible_storage : bool
/// } <ocaml field_prefix="dci_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclContext(const DeclContext *DC) {
if (!DC) {
{ ArrayScope Scope(OF); }
{ ObjectScope Scope(OF); }
return;
}
{
ArrayScope Scope(OF);
for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
I != E; ++I) {
if (!DedupService || DedupService->verifyDeclFileLocation(**I)) {
dumpBareDecl(*I);
}
}
}
{
ObjectScope Scope(OF);
OF.emitFlag("has_external_lexical_storage", DC->hasExternalLexicalStorage());
OF.emitFlag("has_external_visible_storage", DC->hasExternalVisibleStorage());
}
}
/// \atd
/// type lookups = {
/// decl_ref : decl_ref;
/// ?primary_context_pointer : pointer option;
/// lookups : lookup list;
/// ~has_undeserialized_decls : bool;
/// } <ocaml field_prefix="lups_">
///
/// type lookup = {
/// decl_name : string;
/// decl_refs : decl_ref list;
/// } <ocaml field_prefix="lup_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareLookups(const DeclContext &DC) {
ObjectScope Scope(OF);
OF.emitTag("decl_ref");
dumpBareDeclRef(cast<Decl>(DC));
const DeclContext *Primary = DC.getPrimaryContext();
if (Primary != &DC) {
OF.emitTag("primary_context_pointer");
dumpBarePointer(cast<Decl>(Primary));
}
OF.emitTag("lookups");
{
ArrayScope Scope(OF);
DeclContext::all_lookups_iterator I = Primary->noload_lookups_begin(),
E = Primary->noload_lookups_end();
while (I != E) {
DeclarationName Name = I.getLookupName();
DeclContextLookupResult R = *I++;
ObjectScope Scope(OF);
OF.emitTag("decl_name");
OF.emitString(Name.getAsString());
OF.emitTag("decl_refs");
{
ArrayScope Scope(OF);
for (DeclContextLookupResult::iterator RI = R.begin(), RE = R.end();
RI != RE; ++RI) {
dumpBareDeclRef(**RI);
}
}
}
}
bool HasUndeserializedLookups = Primary->hasExternalVisibleStorage();
OF.emitFlag("has_undeserialized_decls", HasUndeserializedLookups);
}
//TODO: dump the content of the attributes
//static bool hasMoreChildren() { return false; }
//static void setMoreChildren(bool x) {}
//static void lastChild() {}
/// \atd
/// type attribute = [
#define ATTR(X) /// | X of attribute_info
#include <clang/Basic/AttrList.inc>
/// ]
/// type attribute_info = {
/// pointer : pointer;
/// inherit _source_range;
/// ~is_implicit : bool
/// } <ocaml field_prefix="ai_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareAttr(const Attr &A) {
std::string tag;
switch (A.getKind()) {
#define ATTR(X) case attr::X: tag = #X; break;
#include <clang/Basic/AttrList.inc>
default: llvm_unreachable("unexpected attribute kind");
}
VariantScope Scope(OF, tag);
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(&A);
dumpSourceRange(A.getRange());
// TODO
//#include <clang/AST/AttrDump.inc>
OF.emitFlag("is_implicit", A.isImplicit());
}
}
/// \atd
/// type previous_decl = [
/// | None
/// | First of pointer
/// | Previous of pointer
/// ]
template <class ATDWriter>
static void dumpPreviousDeclImpl(ATDWriter &OF, ...) {}
template <class ATDWriter, typename T>
static void dumpPreviousDeclImpl(ATDWriter &OF, const Mergeable<T> *D) {
const T *First = D->getFirstDecl();
if (First != D) {
OF.emitTag("previous_decl");
typename ATDWriter::VariantScope Scope(OF, "First");
dumpBarePointer(OF, First);
}
}
template <class ATDWriter, typename T>
static void dumpPreviousDeclImpl(ATDWriter &OF, const Redeclarable<T> *D) {
const T *Prev = D->getPreviousDecl();
if (Prev) {
OF.emitTag("previous_decl");
typename ATDWriter::VariantScope Scope(OF, "Previous");
dumpBarePointer(OF, Prev);
}
}
/// Dump the previous declaration in the redeclaration chain for a declaration,
/// if any.
///
/// \atd type _previous_decl = {
/// ~previous_decl <ocaml default="`None"> : previous_decl;
/// }
template <class ATDWriter>
static void dumpPreviousDecl(ATDWriter &OF, const Decl *D) {
switch (D->getKind()) {
#define DECL(DERIVED, BASE) \
case Decl::DERIVED: \
return dumpPreviousDeclImpl(OF, cast<DERIVED##Decl>(D));
#define ABSTRACT_DECL(DECL)
#include <clang/AST/DeclNodes.inc>
}
llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
}
//===----------------------------------------------------------------------===//
// C++ Utilities
//===----------------------------------------------------------------------===//
/// \atd
/// type _access_specifier = { ~access_specifier <ocaml default="`None"> : access_specifier }
/// type access_specifier = [ None | Public | Protected | Private ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpAccessSpecifier(AccessSpecifier AS) {
if (AS == AS_none) {
return;
}
OF.emitTag("access_specifier");
switch (AS) {
case AS_public:
OF.emitSimpleVariant("Public");
break;
case AS_protected:
OF.emitSimpleVariant("Protected");
break;
case AS_private:
OF.emitSimpleVariant("Private");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
/// \atd
/// type cxx_ctor_initializer = {
/// subject : cxx_ctor_initializer_subject;
/// ?init_expr : stmt option
/// } <ocaml field_prefix="xci_">
/// type cxx_ctor_initializer_subject = [
/// Member of decl_ref
/// | Delegating of qual_type
/// | BaseClass of (qual_type * bool)
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareCXXCtorInitializer(const CXXCtorInitializer &Init) {
ObjectScope Scope(OF);
OF.emitTag("subject");
const FieldDecl *FD = Init.getAnyMember();
if (FD) {
VariantScope Scope(OF, "Member");
dumpBareDeclRef(*FD);
} else if (Init.isDelegatingInitializer()) {
VariantScope Scope(OF, "Delegating");
dumpBareQualType(Init.getTypeSourceInfo()->getType());
} else {
VariantScope Scope(OF, "BaseClass");
{
TupleScope Scope(OF);
dumpBareQualType(Init.getTypeSourceInfo()->getType());
OF.emitBoolean(Init.isBaseVirtual());
}
}
const Expr *E = Init.getInit();
if (E) {
OF.emitTag("init_expr");
dumpBareStmt(E);
}
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateParameters(const TemplateParameterList *TPL) {
// if (!TPL)
// return;
//
// for (TemplateParameterList::const_iterator I = TPL->begin(), E = TPL->end();
// I != E; ++I)
// dumpBareDecl(*I);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentListInfo(
// const TemplateArgumentListInfo &TALI) {
// for (unsigned i = 0, e = TALI.size(); i < e; ++i) {
// dumpTemplateArgumentLoc(TALI[i]);
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentLoc(const TemplateArgumentLoc &A) {
// dumpTemplateArgument(A.getArgument(), A.getSourceRange());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentList(const TemplateArgumentList &TAL) {
// for (unsigned i = 0, e = TAL.size(); i < e; ++i)
// dumpTemplateArgument(TAL[i]);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgument(const TemplateArgument &A, SourceRange R) {
// ObjectScope Scope(OF);
// OS << "TemplateArgument";
// if (R.isValid())
// dumpSourceRange(R);
//
// switch (A.getKind()) {
// case TemplateArgument::Null:
// OS << " null";
// break;
// case TemplateArgument::Type:
// OS << " type";
// dumpQualType(A.getAsType());
// break;
// case TemplateArgument::Declaration:
// OS << " decl";
// dumpDeclRef(A.getAsDecl());
// break;
// case TemplateArgument::NullPtr:
// OS << " nullptr";
// break;
// case TemplateArgument::Integral:
// OS << " integral " << A.getAsIntegral();
// break;
// case TemplateArgument::Template:
// OS << " template ";
// // FIXME: do not use the local dump method
// A.getAsTemplate().dump(OS);
// break;
// case TemplateArgument::TemplateExpansion:
// OS << " template expansion";
// // FIXME: do not use the local dump method
// A.getAsTemplateOrTemplatePattern().dump(OS);
// break;
// case TemplateArgument::Expression:
// OS << " expr";
// dumpBareStmt(A.getAsExpr());
// break;
// case TemplateArgument::Pack:
// OS << " pack";
// for (TemplateArgument::pack_iterator I = A.pack_begin(), E = A.pack_end();
// I != E; ++I) {
// dumpTemplateArgument(*I);
// }
// break;
// }
//}
//===----------------------------------------------------------------------===//
// Decl dumping methods.
//===----------------------------------------------------------------------===//
/// \atd
#define DECL(DERIVED, BASE) /// #define @DERIVED@_decl_tuple @BASE@_tuple
#define ABSTRACT_DECL(DECL) DECL
#include <clang/AST/DeclNodes.inc>
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareDecl(const Decl *D) {
if (!D) {
// We use a fixed EmptyDecl node to represent null pointers
D = NullPtrDecl;
}
VariantScope Scope(OF, std::string(D->getDeclKindName()) + "Decl");
{
TupleScope Scope(OF);
ConstDeclVisitor<ASTExporter<ATDWriter>>::Visit(D);
}
}
/// \atd
/// #define decl_tuple decl_info
/// type decl_info = {
/// pointer : pointer;
/// ?parent_pointer : pointer option;
/// inherit _previous_decl;
/// inherit _source_range;
/// ?owning_module : string option;
/// ~is_hidden : bool;
/// attributes : attribute list;
/// inherit _full_comment;
/// ~is_invalid_decl : bool
/// } <ocaml field_prefix="di_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDecl(const Decl *D) {
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(D);
if (D->getLexicalDeclContext() != D->getDeclContext()) {
OF.emitTag("parent_pointer");
dumpBarePointer(cast<Decl>(D->getDeclContext()));
}
dumpPreviousDecl(OF, D);
dumpSourceRange(D->getSourceRange());
if (Module *M = D->getOwningModule()) {
OF.emitTag("owning_module");
OF.emitString(M->getFullModuleName());
}
if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
OF.emitFlag("is_hidden", ND->isHidden());
}
OF.emitTag("attributes");
{
ArrayScope ArrayAttr(OF);
for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
I != E; ++I) {
assert(*I);
dumpBareAttr(**I);
}
}
const FullComment *Comment = D->getASTContext().getLocalCommentForDeclUncached(D);
dumpFullComment(Comment);
OF.emitFlag("is_invalid_decl", D->isInvalidDecl());
}
}
/// \atd
/// #define captured_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCapturedDecl(const CapturedDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define linkage_spec_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define namespace_decl_tuple named_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitNamespaceDecl(const NamespaceDecl *D) {
VisitNamedDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define obj_c_container_decl_tuple named_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCContainerDecl(const ObjCContainerDecl *D) {
VisitNamedDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define tag_decl_tuple type_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTagDecl(const TagDecl *D) {
VisitTypeDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define type_decl_tuple named_decl_tuple * opt_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTypeDecl(const TypeDecl *D) {
VisitNamedDecl(D);
dumpBareType(D->getTypeForDecl());
}
/// \atd
/// #define value_decl_tuple named_decl_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitValueDecl(const ValueDecl *D) {
VisitNamedDecl(D);
dumpBareQualType(D->getType());
}
/// \atd
/// #define translation_unit_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTranslationUnitDecl(const TranslationUnitDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define named_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitNamedDecl(const NamedDecl *D) {
VisitDecl(D);
OF.emitString(D->getNameAsString());
}
/// \atd
/// #define typedef_decl_tuple typedef_name_decl_tuple * typedef_decl_info
/// type typedef_decl_info = {
/// ~is_module_private : bool
/// } <ocaml field_prefix="tdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTypedefDecl(const TypedefDecl *D) {
ASTExporter<ATDWriter>::VisitTypedefNameDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_module_private", D->isModulePrivate());
}
/// \atd
/// #define enum_decl_tuple tag_decl_tuple * enum_decl_info
/// type enum_decl_info = {
/// ?scope : enum_decl_scope option;
/// ~is_module_private : bool
/// } <ocaml field_prefix="edi_">
/// type enum_decl_scope = [Class | Struct]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitEnumDecl(const EnumDecl *D) {
VisitTagDecl(D);
ObjectScope Scope(OF);
if (D->isScoped()) {
OF.emitTag("scope");
if (D->isScopedUsingClassTag())
OF.emitSimpleVariant("Class");
else
OF.emitSimpleVariant("Struct");
}
OF.emitFlag("is_module_private", D->isModulePrivate());
}
/// \atd
/// #define record_decl_tuple tag_decl_tuple * record_decl_info
/// type record_decl_info = {
/// ~is_module_private : bool;
/// ~is_complete_definition : bool
/// } <ocaml field_prefix="rdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitRecordDecl(const RecordDecl *D) {
VisitTagDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_complete_definition", D->isCompleteDefinition());
}
/// \atd
/// #define enum_constant_decl_tuple value_decl_tuple * enum_constant_decl_info
/// type enum_constant_decl_info = {
/// ?init_expr : stmt option
/// } <ocaml field_prefix="ecdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitEnumConstantDecl(const EnumConstantDecl *D) {
VisitValueDecl(D);
ObjectScope Scope(OF);
if (const Expr *Init = D->getInitExpr()) {
OF.emitTag("init_expr");
dumpBareStmt(Init);
}
}
/// \atd
/// #define indirect_field_decl_tuple value_decl_tuple * decl_ref list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitIndirectFieldDecl(const IndirectFieldDecl *D) {
VisitValueDecl(D);
ArrayScope Scope(OF);
for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
E = D->chain_end();
I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
/// \atd
/// #define function_decl_tuple declarator_decl_tuple * function_decl_info
/// type function_decl_info = {
/// ?storage_class : string option;
/// ~is_inline : bool;
/// ~is_virtual : bool;
/// ~is_module_private : bool;
/// ~is_pure : bool;
/// ~is_delete_as_written : bool;
/// ~decls_in_prototype_scope : decl list;
/// ~parameters : decl list;
/// ~cxx_ctor_initializers : cxx_ctor_initializer list;
/// ?body : stmt option
/// } <ocaml field_prefix="fdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFunctionDecl(const FunctionDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
// We purposedly do not call VisitDeclContext(D).
ObjectScope Scope(OF);
StorageClass SC = D->getStorageClass();
if (SC != SC_None) {
OF.emitTag("storage_class");
OF.emitString(VarDecl::getStorageClassSpecifierString(SC));
}
OF.emitFlag("is_inline", D->isInlineSpecified());
OF.emitFlag("is_virtual", D->isVirtualAsWritten());
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_pure", D->isPure());
OF.emitFlag("is_delete_as_written", D->isDeletedAsWritten());
// if (const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>()) {
// FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
// switch (EPI.ExceptionSpecType) {
// default: break;
// case EST_Unevaluated:
// OS << " noexcept-unevaluated " << EPI.ExceptionSpecDecl;
// break;
// case EST_Uninstantiated:
// OS << " noexcept-uninstantiated " << EPI.ExceptionSpecTemplate;
// break;
// }
// }
//
// const FunctionTemplateSpecializationInfo *FTSI =
// D->getTemplateSpecializationInfo();
// bool HasTemplateSpecialization = FTSI;
//
//
// if (HasTemplateSpecialization) {
// dumpTemplateArgumentList(*FTSI->TemplateArguments);
// }
{
ArrayRef<NamedDecl *>::iterator
I = D->getDeclsInPrototypeScope().begin(),
E = D->getDeclsInPrototypeScope().end();
if (I != E) {
OF.emitTag("decls_in_prototype_scope");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
{
FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(D);
bool HasCtorInitializers = C && C->init_begin() != C->init_end();
if (HasCtorInitializers) {
OF.emitTag("cxx_ctor_initializers");
ArrayScope Scope(OF);
for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
E = C->init_end();
I != E; ++I) {
assert(*I);
dumpBareCXXCtorInitializer(**I);
}
}
bool HasDeclarationBody = D->doesThisDeclarationHaveABody();
if (HasDeclarationBody) {
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
}
/// \atd
/// #define field_decl_tuple declarator_decl_tuple * field_decl_info
/// type field_decl_info = {
/// ~is_mutable : bool;
/// ~is_module_private : bool;
/// ?init_expr : stmt option;
/// ?bit_width_expr : stmt option
/// } <ocaml field_prefix="fldi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFieldDecl(const FieldDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_mutable", D->isMutable());
OF.emitFlag("is_module_private", D->isModulePrivate());
bool IsBitField = D->isBitField();
if (IsBitField && D->getBitWidth()) {
OF.emitTag("bit_width_expr");
dumpBareStmt(D->getBitWidth());
}
Expr *Init = D->getInClassInitializer();
if (Init) {
OF.emitTag("init_expr");
dumpBareStmt(Init);
}
}
/// \atd
/// #define var_decl_tuple declarator_decl_tuple * var_decl_info
/// type var_decl_info = {
/// ?storage_class : string option;
/// ~tls_kind <ocaml default="`Tls_none">: tls_kind;
/// ~is_module_private : bool;
/// ~is_nrvo_variable : bool;
/// ?init_expr : stmt option;
/// } <ocaml field_prefix="vdi_">
///
/// type tls_kind = [ Tls_none | Tls_static | Tls_dynamic ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitVarDecl(const VarDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
ObjectScope Scope(OF);
StorageClass SC = D->getStorageClass();
if (SC != SC_None) {
OF.emitTag("storage_class");
OF.emitString(VarDecl::getStorageClassSpecifierString(SC));
}
switch (D->getTLSKind()) {
case VarDecl::TLS_None: break;
case VarDecl::TLS_Static: OF.emitTag("tls_kind"); OF.emitSimpleVariant("Tls_static"); break;
case VarDecl::TLS_Dynamic: OF.emitTag("tls_kind"); OF.emitSimpleVariant("Tls_dynamic"); break;
}
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_nrvo_variable", D->isNRVOVariable());
if (D->hasInit()) {
OF.emitTag("init_expr");
dumpBareStmt(D->getInit());
}
}
/// \atd
/// #define file_scope_asm_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFileScopeAsmDecl(const FileScopeAsmDecl *D) {
VisitDecl(D);
OF.emitString(D->getAsmString()->getBytes());
}
/// \atd
/// #define import_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitImportDecl(const ImportDecl *D) {
VisitDecl(D);
OF.emitString(D->getImportedModule()->getFullModuleName());
}
////===----------------------------------------------------------------------===//
//// C++ Declarations
////===----------------------------------------------------------------------===//
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNamespaceDecl(const NamespaceDecl *D) {
// dumpName(D);
// if (D->isInline())
// OS << " inline";
// if (!D->isOriginalNamespace())
// dumpDeclRef(D->getOriginalNamespace(), "original");
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
// OS << ' ';
// dumpBareDeclRef(D->getNominatedNamespace());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
// dumpName(D);
// dumpDeclRef(D->getAliasedNamespace());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTypeAliasDecl(const TypeAliasDecl *D) {
// dumpName(D);
// dumpQualType(D->getUnderlyingType());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// dumpBareDecl(D->getTemplatedDecl());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitCXXRecordDecl(const CXXRecordDecl *D) {
// VisitRecordDecl(D);
// if (!D->isCompleteDefinition())
// return;
//
// for (CXXRecordDecl::base_class_const_iterator I = D->bases_begin(),
// E = D->bases_end();
// I != E; ++I) {
// ObjectScope Scope(OF);
// if (I->isVirtual())
// OS << "virtual ";
// dumpAccessSpecifier(I->getAccessSpecifier());
// dumpQualType(I->getType());
// if (I->isPackExpansion())
// OS << "...";
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitStaticAssertDecl(const StaticAssertDecl *D) {
// dumpBareStmt(D->getAssertExpr());
// dumpBareStmt(D->getMessage());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// dumpBareDecl(D->getTemplatedDecl());
// for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(),
// E = D->spec_end();
// I != E; ++I) {
// FunctionTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
//
// ClassTemplateDecl::spec_iterator I = D->spec_begin();
// ClassTemplateDecl::spec_iterator E = D->spec_end();
// dumpBareDecl(D->getTemplatedDecl());
// for (; I != E; ++I) {
// ClassTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplateSpecializationDecl(
// const ClassTemplateSpecializationDecl *D) {
// VisitCXXRecordDecl(D);
// dumpTemplateArgumentList(D->getTemplateArgs());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplatePartialSpecializationDecl(
// const ClassTemplatePartialSpecializationDecl *D) {
// VisitClassTemplateSpecializationDecl(D);
// dumpTemplateParameters(D->getTemplateParameters());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassScopeFunctionSpecializationDecl(
// const ClassScopeFunctionSpecializationDecl *D) {
// dumpDeclRef(D->getSpecialization());
// if (D->hasExplicitTemplateArgs())
// dumpTemplateArgumentListInfo(D->templateArgs());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplateDecl(const VarTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
//
// VarTemplateDecl::spec_iterator I = D->spec_begin();
// VarTemplateDecl::spec_iterator E = D->spec_end();
// dumpBareDecl(D->getTemplatedDecl());
// for (; I != E; ++I) {
// VarTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplateSpecializationDecl(
// const VarTemplateSpecializationDecl *D) {
// dumpTemplateArgumentList(D->getTemplateArgs());
// VisitVarDecl(D);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplatePartialSpecializationDecl(
// const VarTemplatePartialSpecializationDecl *D) {
// dumpTemplateParameters(D->getTemplateParameters());
// VisitVarTemplateSpecializationDecl(D);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
// if (D->wasDeclaredWithTypename())
// OS << " typename";
// else
// OS << " class";
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// if (D->hasDefaultArgument())
// dumpQualType(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
// dumpQualType(D->getType());
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// if (D->hasDefaultArgument())
// dumpBareStmt(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTemplateTemplateParmDecl(
// const TemplateTemplateParmDecl *D) {
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// if (D->hasDefaultArgument())
// dumpTemplateArgumentLoc(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingDecl(const UsingDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedUsingTypenameDecl(
// const UnresolvedUsingTypenameDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
// dumpQualType(D->getType());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingShadowDecl(const UsingShadowDecl *D) {
// OS << ' ';
// dumpBareDeclRef(D->getTargetDecl());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
// switch (D->getLanguage()) {
// case LinkageSpecDecl::lang_c: OS << " C"; break;
// case LinkageSpecDecl::lang_cxx: OS << " C++"; break;
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitAccessSpecDecl(const AccessSpecDecl *D) {
// OS << ' ';
// dumpAccessSpecifier(D->getAccess());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitFriendDecl(const FriendDecl *D) {
// if (TypeSourceInfo *T = D->getFriendType())
// dumpQualType(T->getType());
// else
// dumpBareDecl(D->getFriendDecl());
//}
//
////===----------------------------------------------------------------------===//
//// Obj-C Declarations
////===----------------------------------------------------------------------===//
/// \atd
/// #define obj_c_ivar_decl_tuple field_decl_tuple * obj_c_ivar_decl_info
/// type obj_c_ivar_decl_info = {
/// ~is_synthesize : bool;
/// ~access_control <ocaml default="`None"> : obj_c_access_control;
/// } <ocaml field_prefix="ovdi_">
/// type obj_c_access_control = [ None | Private | Protected | Public | Package ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
VisitFieldDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_synthesize", D->getSynthesize());
ObjCIvarDecl::AccessControl AC = D->getAccessControl();
if (AC != ObjCIvarDecl::None) {
OF.emitTag("access_control");
switch (AC) {
case ObjCIvarDecl::Private:
OF.emitSimpleVariant("Private");
break;
case ObjCIvarDecl::Protected:
OF.emitSimpleVariant("Protected");
break;
case ObjCIvarDecl::Public:
OF.emitSimpleVariant("Public");
break;
case ObjCIvarDecl::Package:
OF.emitSimpleVariant("Package");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// #define obj_c_method_decl_tuple named_decl_tuple * obj_c_method_decl_info
/// type obj_c_method_decl_info = {
/// ~is_instance_method : bool;
/// result_type : qual_type;
/// ~parameters : decl list;
/// ~is_variadic : bool;
/// ?body : stmt option;
/// } <ocaml field_prefix="omdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
VisitNamedDecl(D);
// We purposedly do not call VisitDeclContext(D).
ObjectScope Scope(OF);
OF.emitFlag("is_instance_method", D->isInstanceMethod());
OF.emitTag("result_type");
dumpBareQualType(D->getReturnType());
{
ObjCMethodDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
OF.emitFlag("is_variadic", D->isVariadic());
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
/// \atd
/// #define obj_c_category_decl_tuple obj_c_container_decl_tuple * obj_c_category_decl_info
/// type obj_c_category_decl_info = {
/// ?class_interface : decl_ref option;
/// ?implementation : decl_ref option;
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="odi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
const ObjCCategoryImplDecl *Impl = D->getImplementation();
if (Impl) {
OF.emitTag("implementation");
dumpBareDeclRef(*Impl);
}
ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_category_impl_decl_tuple obj_c_impl_decl_tuple * obj_c_category_impl_decl_info
/// type obj_c_category_impl_decl_info = {
/// ?class_interface : decl_ref option;
/// ?category_decl : decl_ref option;
/// } <ocaml field_prefix="ocidi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
ASTExporter<ATDWriter>::VisitObjCImplDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
const ObjCCategoryDecl *CD = D->getCategoryDecl();
if (CD) {
OF.emitTag("category_decl");
dumpBareDeclRef(*CD);
}
}
/// \atd
/// #define obj_c_protocol_decl_tuple obj_c_container_decl_tuple * obj_c_protocol_decl_info
/// type obj_c_protocol_decl_info = {
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="opcdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
ASTExporter<ATDWriter>::VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_interface_decl_tuple obj_c_container_decl_tuple * obj_c_interface_decl_info
/// type obj_c_interface_decl_info = {
/// ?super : decl_ref option;
/// ?implementation : decl_ref option;
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="otdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *SC = D->getSuperClass();
if (SC) {
OF.emitTag("super");
dumpBareDeclRef(*SC);
}
const ObjCImplementationDecl *Impl = D->getImplementation();
if (Impl) {
OF.emitTag("implementation");
dumpBareDeclRef(*Impl);
}
ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_implementation_decl_tuple obj_c_impl_decl_tuple * obj_c_implementation_decl_info
/// type obj_c_implementation_decl_info = {
/// ?super : decl_ref option;
/// ?class_interface : decl_ref option;
/// ~ivar_initializers : cxx_ctor_initializer list;
/// } <ocaml field_prefix="oidi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
ASTExporter<ATDWriter>::VisitObjCImplDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *SC = D->getSuperClass();
if (SC) {
OF.emitTag("super");
dumpBareDeclRef(*SC);
}
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
ObjCImplementationDecl::init_const_iterator I = D->init_begin(),
E = D->init_end();
if (I != E) {
OF.emitTag("ivar_initializers");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareCXXCtorInitializer(**I);
}
}
}
/// \atd
/// #define obj_c_compatible_alias_decl_tuple named_decl_tuple * obj_c_compatible_alias_decl_info
/// type obj_c_compatible_alias_decl_info = {
/// ?class_interface : decl_ref option;
/// } <ocaml field_prefix="ocadi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D) {
VisitNamedDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
}
/// \atd
/// #define obj_c_property_decl_tuple named_decl_tuple * obj_c_property_decl_info
/// type obj_c_property_decl_info = {
/// ?class_interface : decl_ref option;
/// inherit _qual_type;
/// ~property_control <ocaml default="`None"> : obj_c_property_control;
/// ~property_attributes : property_attribute list
/// } <ocaml field_prefix="opdi_">
/// type obj_c_property_control = [ None | Required | Optional ]
/// type property_attribute = [
/// Readonly
/// | Assign
/// | Readwrite
/// | Retain
/// | Copy
/// | Nonatomic
/// | Atomic
/// | Weak
/// | Strong
/// | Unsafe_unretained
/// | Getter of decl_ref
/// | Setter of decl_ref
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
VisitNamedDecl(D);
ObjectScope Scope(OF);
dumpQualType(D->getType());
ObjCPropertyDecl::PropertyControl PC = D->getPropertyImplementation();
if (PC != ObjCPropertyDecl::None) {
OF.emitTag("property_control");
switch (PC) {
case ObjCPropertyDecl::Required: OF.emitSimpleVariant("Required"); break;
case ObjCPropertyDecl::Optional: OF.emitSimpleVariant("Optional"); break;
default:
llvm_unreachable("unknown case");
break;
}
}
ObjCPropertyDecl::PropertyAttributeKind Attrs = D->getPropertyAttributes();
if (Attrs != ObjCPropertyDecl::OBJC_PR_noattr) {
OF.emitTag("property_attributes");
ArrayScope Scope(OF);
if (Attrs & ObjCPropertyDecl::OBJC_PR_readonly)
OF.emitSimpleVariant("Readonly");
if (Attrs & ObjCPropertyDecl::OBJC_PR_assign)
OF.emitSimpleVariant("Assign");
if (Attrs & ObjCPropertyDecl::OBJC_PR_readwrite)
OF.emitSimpleVariant("Readwrite");
if (Attrs & ObjCPropertyDecl::OBJC_PR_retain)
OF.emitSimpleVariant("Retain");
if (Attrs & ObjCPropertyDecl::OBJC_PR_copy)
OF.emitSimpleVariant("Copy");
if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic)
OF.emitSimpleVariant("Nonatomic");
if (Attrs & ObjCPropertyDecl::OBJC_PR_atomic)
OF.emitSimpleVariant("Atomic");
if (Attrs & ObjCPropertyDecl::OBJC_PR_weak)
OF.emitSimpleVariant("Weak");
if (Attrs & ObjCPropertyDecl::OBJC_PR_strong)
OF.emitSimpleVariant("Strong");
if (Attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained)
OF.emitSimpleVariant("Unsafe_unretained");
if (Attrs & ObjCPropertyDecl::OBJC_PR_getter) {
VariantScope Scope(OF, "Getter");
dumpBareDeclRef(*D->getGetterMethodDecl());
}
if (Attrs & ObjCPropertyDecl::OBJC_PR_setter) {
VariantScope Scope(OF, "Setter");
dumpBareDeclRef(*D->getSetterMethodDecl());
}
}
}
/// \atd
/// #define obj_c_property_impl_decl_tuple decl_tuple * obj_c_property_impl_decl_info
/// type obj_c_property_impl_decl_info = {
/// inherit _name;
/// implementation : property_implementation;
/// ?property_decl : decl_ref option;
/// ?ivar_decl : decl_ref option;
/// } <ocaml field_prefix="opidi_">
/// type property_implementation = [ Synthesize | Dynamic ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
VisitDecl(D);
ObjectScope Scope(OF);
dumpName(D->getPropertyDecl());
OF.emitTag("implementation");
switch (D->getPropertyImplementation()) {
case ObjCPropertyImplDecl::Synthesize: OF.emitSimpleVariant("Synthesize"); break;
case ObjCPropertyImplDecl::Dynamic: OF.emitSimpleVariant("Dynamic"); break;
}
const ObjCPropertyDecl *PD = D->getPropertyDecl();
if (PD) {
OF.emitTag("property_decl");
dumpBareDeclRef(*PD);
}
const ObjCIvarDecl *ID = D->getPropertyIvarDecl();
if (ID) {
OF.emitTag("ivar_decl");
dumpBareDeclRef(*ID);
}
}
/// \atd
/// #define block_decl_tuple decl_tuple * decl_context_tuple * block_decl_info
/// type block_decl_info = {
/// ~parameters : decl list;
/// ~is_variadic : bool;
/// ~does_capture_cxx_this : bool;
/// ~captured_variables : block_captured_variable list;
/// ?body : stmt option;
/// } <ocaml field_prefix="bdi_">
///
/// type block_captured_variable = {
/// ~is_by_ref : bool;
/// ~is_nested : bool;
/// ?variable : decl_ref option;
/// ?copy_expr : stmt option
/// } <ocaml field_prefix="bcv_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBlockDecl(const BlockDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
ObjectScope Scope(OF);
{
ObjCMethodDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
OF.emitFlag("is_variadic", D->isVariadic());
OF.emitFlag("does_capture_cxx_this", D->capturesCXXThis());
{
BlockDecl::capture_iterator I = D->capture_begin(), E = D->capture_end();
if (I != E) {
OF.emitTag("captured_variables");
ArrayScope Scope(OF);
for (; I != E; ++I) {
ObjectScope Scope(OF);
OF.emitFlag("is_by_ref", I->isByRef());
OF.emitFlag("is_nested", I->isNested());
if (I->getVariable()) {
OF.emitTag("variable");
dumpBareDeclRef(*I->getVariable());
}
if (I->hasCopyExpr()) {
OF.emitTag("copy_expr");
dumpBareStmt(I->getCopyExpr());
}
}
}
}
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
// main variant for declarations
/// \atd
/// type decl = [
#define DECL(DERIVED, BASE) /// | DERIVED@@Decl of (@DERIVED@_decl_tuple)
#define ABSTRACT_DECL(DECL)
#include <clang/AST/DeclNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// Stmt dumping methods.
//===----------------------------------------------------------------------===//
// Default aliases for generating variant components
// The main variant is defined at the end of section.
/// \atd
#define STMT(CLASS, PARENT) /// #define @CLASS@_tuple @PARENT@_tuple
#define ABSTRACT_STMT(STMT) STMT
#include <clang/AST/StmtNodes.inc>
//
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareStmt(const Stmt *S) {
if (!S) {
// We use a fixed NullStmt node to represent null pointers
S = NullPtrStmt;
}
VariantScope Scope(OF, S->getStmtClassName());
{
TupleScope Scope(OF);
ConstStmtVisitor<ASTExporter<ATDWriter>>::Visit(S);
}
}
/// \atd
/// #define stmt_tuple stmt_info * stmt list
/// type stmt_info = {
/// pointer : pointer;
/// inherit _source_range;
/// } <ocaml field_prefix="si_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitStmt(const Stmt *S) {
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(S);
dumpSourceRange(S->getSourceRange());
}
{
ArrayScope Scope(OF);
for (Stmt::const_child_range CI = S->children(); CI; ++CI) {
dumpBareStmt(*CI);
}
}
}
/// \atd
/// #define decl_stmt_tuple stmt_tuple * decl list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclStmt(const DeclStmt *Node) {
VisitStmt(Node);
ArrayScope Scope(OF);
for (DeclStmt::const_decl_iterator I = Node->decl_begin(),
E = Node->decl_end();
I != E; ++I) {
dumpBareDecl(*I);
}
}
/// \atd
/// #define attributed_stmt_tuple stmt_tuple * attribute list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitAttributedStmt(const AttributedStmt *Node) {
VisitStmt(Node);
ArrayScope Scope(OF);
for (ArrayRef<const Attr *>::iterator I = Node->getAttrs().begin(),
E = Node->getAttrs().end();
I != E; ++I) {
assert(*I);
dumpBareAttr(**I);
}
}
/// \atd
/// #define label_stmt_tuple stmt_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitLabelStmt(const LabelStmt *Node) {
VisitStmt(Node);
OF.emitString(Node->getName());
}
/// \atd
/// #define goto_stmt_tuple stmt_tuple * goto_stmt_info
/// type goto_stmt_info = {
/// label : string;
/// pointer : pointer
/// } <ocaml field_prefix="gsi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitGotoStmt(const GotoStmt *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
OF.emitTag("label");
OF.emitString(Node->getLabel()->getName());
OF.emitTag("pointer");
dumpBarePointer(Node->getLabel());
}
/// \atd
/// #define cxx_catch_stmt_tuple stmt_tuple * cxx_catch_stmt_info
/// type cxx_catch_stmt_info = {
/// ?variable : decl option
/// } <ocaml field_prefix="xcsi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXCatchStmt(const CXXCatchStmt *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
const VarDecl *decl = Node->getExceptionDecl();
if (decl) {
OF.emitTag("variable");
dumpBareDecl(decl);
}
}
////===----------------------------------------------------------------------===//
//// Expr dumping methods.
////===----------------------------------------------------------------------===//
//
/// \atd
/// #define expr_tuple stmt_tuple * expr_info
/// type expr_info = {
/// inherit _qual_type;
/// ~value_kind <ocaml default="`RValue"> : value_kind;
/// ~object_kind <ocaml default="`Ordinary"> : object_kind;
/// } <ocaml field_prefix="ei_">
///
/// type value_kind = [ RValue | LValue | XValue ]
/// type object_kind = [ Ordinary | BitField | ObjCProperty | ObjCSubscript | VectorComponent ]
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExpr(const Expr *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
dumpQualType(Node->getType());
ExprValueKind VK = Node->getValueKind();
if (VK != VK_RValue) {
OF.emitTag("value_kind");
switch (VK) {
case VK_LValue:
OF.emitSimpleVariant("LValue");
break;
case VK_XValue:
OF.emitSimpleVariant("XValue");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
ExprObjectKind OK = Node->getObjectKind();
if (OK != OK_Ordinary) {
OF.emitTag("object_kind");
switch (Node->getObjectKind()) {
case OK_BitField:
OF.emitSimpleVariant("BitField");
break;
case OK_ObjCProperty:
OF.emitSimpleVariant("ObjCProperty");
break;
case OK_ObjCSubscript:
OF.emitSimpleVariant("ObjCSubscript");
break;
case OK_VectorComponent:
OF.emitSimpleVariant("VectorComponent");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// type cxx_base_specifier = {
/// name : string;
/// ~virtual : bool;
/// } <ocaml field_prefix="xbs_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
ObjectScope Scope(OF);
OF.emitTag("name");
const CXXRecordDecl *RD = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
OF.emitString(RD->getName());
OF.emitFlag("virtual", Base.isVirtual());
}
/// \atd
/// type cast_kind = [
/// | Dependent
/// | BitCast
/// | LValueBitCast
/// | LValueToRValue
/// | NoOp
/// | BaseToDerived
/// | DerivedToBase
/// | UncheckedDerivedToBase
/// | Dynamic
/// | ToUnion
/// | ArrayToPointerDecay
/// | FunctionToPointerDecay
/// | NullToPointer
/// | NullToMemberPointer
/// | BaseToDerivedMemberPointer
/// | DerivedToBaseMemberPointer
/// | MemberPointerToBoolean
/// | ReinterpretMemberPointer
/// | UserDefinedConversion
/// | ConstructorConversion
/// | IntegralToPointer
/// | PointerToIntegral
/// | PointerToBoolean
/// | ToVoid
/// | VectorSplat
/// | IntegralCast
/// | IntegralToBoolean
/// | IntegralToFloating
/// | FloatingToIntegral
/// | FloatingToBoolean
/// | FloatingCast
/// | CPointerToObjCPointerCast
/// | BlockPointerToObjCPointerCast
/// | AnyPointerToBlockPointerCast
/// | ObjCObjectLValueCast
/// | FloatingRealToComplex
/// | FloatingComplexToReal
/// | FloatingComplexToBoolean
/// | FloatingComplexCast
/// | FloatingComplexToIntegralComplex
/// | IntegralRealToComplex
/// | IntegralComplexToReal
/// | IntegralComplexToBoolean
/// | IntegralComplexCast
/// | IntegralComplexToFloatingComplex
/// | ARCProduceObject
/// | ARCConsumeObject
/// | ARCReclaimReturnedObject
/// | ARCExtendBlockObject
/// | AtomicToNonAtomic
/// | NonAtomicToAtomic
/// | CopyAndAutoreleaseBlockObject
/// | BuiltinFnToFnPtr
/// | ZeroToOCLEvent
/// ]
///
/// #define cast_expr_tuple expr_tuple * cast_expr_info
/// type cast_expr_info = {
/// cast_kind : cast_kind;
/// base_path : cxx_base_specifier list;
/// } <ocaml field_prefix="cei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCastExpr(const CastExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("cast_kind");
OF.emitSimpleVariant(Node->getCastKindName());
OF.emitTag("base_path");
{
ArrayScope Scope(OF);
for (CastExpr::path_const_iterator I = Node->path_begin(),
E = Node->path_end();
I != E; ++I) {
dumpBareCXXBaseSpecifier(**I);
}
}
}
/// \atd
/// #define explicit_cast_expr_tuple cast_expr_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExplicitCastExpr(const ExplicitCastExpr *Node) {
VisitCastExpr(Node);
dumpBareQualType(Node->getTypeAsWritten());
}
/// \atd
/// #define decl_ref_expr_tuple expr_tuple * decl_ref_expr_info
/// type decl_ref_expr_info = {
/// ?decl_ref : decl_ref option;
/// ?found_decl_ref : decl_ref option
/// } <ocaml field_prefix="drti_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclRefExpr(const DeclRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
const ValueDecl *D = Node->getDecl();
if (D) {
OF.emitTag("decl_ref");
dumpBareDeclRef(*D);
}
const NamedDecl *FD = Node->getFoundDecl();
if (FD && D != FD) {
OF.emitTag("found_decl_ref");
dumpBareDeclRef(*FD);
}
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node) {
// VisitExpr(Node);
// OS << " (";
// if (!Node->requiresADL())
// OS << "no ";
// OS << "ADL) = '" << Node->getName() << '\'';
//
// UnresolvedLookupExpr::decls_iterator
// I = Node->decls_begin(), E = Node->decls_end();
// if (I == E)
// OS << " empty";
// for (; I != E; ++I)
// dumpBarePointer(*I);
//}
/// \atd
/// #define obj_c_ivar_ref_expr_tuple expr_tuple * obj_c_ivar_ref_expr_info
/// type obj_c_ivar_ref_expr_info = {
/// decl_ref : decl_ref;
/// pointer : pointer;
/// ~is_free_ivar : bool
/// } <ocaml field_prefix="ovrei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("decl_ref");
dumpBareDeclRef(*Node->getDecl());
OF.emitTag("pointer");
dumpBarePointer(Node->getDecl());
OF.emitFlag("is_free_ivar", Node->isFreeIvar());
}
/// \atd
/// #define predefined_expr_tuple expr_tuple * predefined_expr_type
/// type predefined_expr_type = [
/// | Func
/// | Function
/// | FuncDName
/// | LFunction
/// | PrettyFunction
/// | PrettyFunctionNoVirtual
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitPredefinedExpr(const PredefinedExpr *Node) {
VisitExpr(Node);
switch (Node->getIdentType()) {
case PredefinedExpr::Func: OF.emitSimpleVariant("Func"); break;
case PredefinedExpr::Function: OF.emitSimpleVariant("Function"); break;
case PredefinedExpr::FuncDName: OF.emitSimpleVariant("FuncDName"); break;
case PredefinedExpr::LFunction: OF.emitSimpleVariant("LFunction"); break;
case PredefinedExpr::PrettyFunction: OF.emitSimpleVariant("PrettyFunction"); break;
case PredefinedExpr::PrettyFunctionNoVirtual: OF.emitSimpleVariant("PrettyFunctionNoVirtual"); break;
}
}
/// \atd
/// #define character_literal_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCharacterLiteral(const CharacterLiteral *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
/// \atd
/// #define integer_literal_tuple expr_tuple * integer_literal_info
/// type integer_literal_info = {
/// ~is_signed : bool;
/// bitwidth : int;
/// value : string;
/// } <ocaml field_prefix="ili_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitIntegerLiteral(const IntegerLiteral *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
bool isSigned = Node->getType()->isSignedIntegerType();
OF.emitFlag("is_signed", isSigned);
OF.emitTag("bitwidth");
OF.emitInteger(Node->getValue().getBitWidth());
OF.emitTag("value");
OF.emitString(Node->getValue().toString(10, isSigned));
}
/// \atd
/// #define floating_literal_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFloatingLiteral(const FloatingLiteral *Node) {
VisitExpr(Node);
llvm::SmallString<20> buf;
Node->getValue().toString(buf);
OF.emitString(buf.str());
}
/// \atd
/// #define string_literal_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitStringLiteral(const StringLiteral *Str) {
VisitExpr(Str);
OF.emitString(Str->getBytes());
}
/// \atd
/// #define unary_operator_tuple expr_tuple * unary_operator_info
/// type unary_operator_info = {
/// kind : unary_operator_kind;
/// ~is_postfix : bool;
/// } <ocaml field_prefix="uoi_">
/// type unary_operator_kind = [
/// PostInc
/// | PostDec
/// | PreInc
/// | PreDec
/// | AddrOf
/// | Deref
/// | Plus
/// | Minus
/// | Not
/// | LNot
/// | Real
/// | Imag
/// | Extension
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitUnaryOperator(const UnaryOperator *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch (Node->getOpcode()) {
case UO_PostInc: OF.emitSimpleVariant("PostInc"); break;
case UO_PostDec: OF.emitSimpleVariant("PostDec"); break;
case UO_PreInc: OF.emitSimpleVariant("PreInc"); break;
case UO_PreDec: OF.emitSimpleVariant("PreDec"); break;
case UO_AddrOf: OF.emitSimpleVariant("AddrOf"); break;
case UO_Deref: OF.emitSimpleVariant("Deref"); break;
case UO_Plus: OF.emitSimpleVariant("Plus"); break;
case UO_Minus: OF.emitSimpleVariant("Minus"); break;
case UO_Not: OF.emitSimpleVariant("Not"); break;
case UO_LNot: OF.emitSimpleVariant("LNot"); break;
case UO_Real: OF.emitSimpleVariant("Real"); break;
case UO_Imag: OF.emitSimpleVariant("Imag"); break;
case UO_Extension: OF.emitSimpleVariant("Extension"); break;
}
OF.emitFlag("is_postfix", Node->isPostfix());
}
/// \atd
/// #define unary_expr_or_type_trait_expr_tuple expr_tuple * unary_expr_or_type_trait_expr_info
/// type unary_expr_or_type_trait_expr_info = {
/// kind : unary_expr_or_type_trait_kind;
/// ?qual_type : qual_type option
/// } <ocaml field_prefix="uttei_">
///
/// type unary_expr_or_type_trait_kind = [ SizeOf | AlignOf | VecStep ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitUnaryExprOrTypeTraitExpr(
const UnaryExprOrTypeTraitExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch(Node->getKind()) {
case UETT_SizeOf:
OF.emitSimpleVariant("SizeOf");
break;
case UETT_AlignOf:
OF.emitSimpleVariant("AlignOf");
break;
case UETT_VecStep:
OF.emitSimpleVariant("VecStep");
break;
}
if (Node->isArgumentType()) {
dumpQualType(Node->getArgumentType());
}
}
/// \atd
/// #define member_expr_tuple expr_tuple * member_expr_info
/// type member_expr_info = {
/// ~is_arrow : bool;
/// name : string;
/// pointer : pointer
/// } <ocaml field_prefix="mei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitMemberExpr(const MemberExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitFlag("is_arrow", Node->isArrow());
OF.emitTag("name");
OF.emitString(Node->getMemberDecl()->getNameAsString());
OF.emitTag("pointer");
dumpBarePointer(Node->getMemberDecl());
}
/// \atd
/// #define ext_vector_element_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExtVectorElementExpr(const ExtVectorElementExpr *Node) {
VisitExpr(Node);
OF.emitString(Node->getAccessor().getNameStart());
}
/// \atd
/// #define binary_operator_tuple expr_tuple * binary_operator_info
/// type binary_operator_info = {
/// kind : binary_operator_kind
/// } <ocaml field_prefix="boi_">
///
/// type binary_operator_kind = [
/// PtrMemD |
/// PtrMemI |
/// Mul |
/// Div |
/// Rem |
/// Add |
/// Sub |
/// Shl |
/// Shr |
/// LT |
/// GT |
/// LE |
/// GE |
/// EQ |
/// NE |
/// And |
/// Xor |
/// Or |
/// LAnd |
/// LOr |
/// Assign |
/// MulAssign |
/// DivAssign |
/// RemAssign |
/// AddAssign |
/// SubAssign |
/// ShlAssign |
/// ShrAssign |
/// AndAssign |
/// XorAssign |
/// OrAssign |
/// Comma
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBinaryOperator(const BinaryOperator *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch (Node->getOpcode()) {
case BO_PtrMemD: OF.emitSimpleVariant("PtrMemD"); break;
case BO_PtrMemI: OF.emitSimpleVariant("PtrMemI"); break;
case BO_Mul: OF.emitSimpleVariant("Mul"); break;
case BO_Div: OF.emitSimpleVariant("Div"); break;
case BO_Rem: OF.emitSimpleVariant("Rem"); break;
case BO_Add: OF.emitSimpleVariant("Add"); break;
case BO_Sub: OF.emitSimpleVariant("Sub"); break;
case BO_Shl: OF.emitSimpleVariant("Shl"); break;
case BO_Shr: OF.emitSimpleVariant("Shr"); break;
case BO_LT: OF.emitSimpleVariant("LT"); break;
case BO_GT: OF.emitSimpleVariant("GT"); break;
case BO_LE: OF.emitSimpleVariant("LE"); break;
case BO_GE: OF.emitSimpleVariant("GE"); break;
case BO_EQ: OF.emitSimpleVariant("EQ"); break;
case BO_NE: OF.emitSimpleVariant("NE"); break;
case BO_And: OF.emitSimpleVariant("And"); break;
case BO_Xor: OF.emitSimpleVariant("Xor"); break;
case BO_Or: OF.emitSimpleVariant("Or"); break;
case BO_LAnd: OF.emitSimpleVariant("LAnd"); break;
case BO_LOr: OF.emitSimpleVariant("LOr"); break;
case BO_Assign: OF.emitSimpleVariant("Assign"); break;
case BO_MulAssign: OF.emitSimpleVariant("MulAssign"); break;
case BO_DivAssign: OF.emitSimpleVariant("DivAssign"); break;
case BO_RemAssign: OF.emitSimpleVariant("RemAssign"); break;
case BO_AddAssign: OF.emitSimpleVariant("AddAssign"); break;
case BO_SubAssign: OF.emitSimpleVariant("SubAssign"); break;
case BO_ShlAssign: OF.emitSimpleVariant("ShlAssign"); break;
case BO_ShrAssign: OF.emitSimpleVariant("ShrAssign"); break;
case BO_AndAssign: OF.emitSimpleVariant("AndAssign"); break;
case BO_XorAssign: OF.emitSimpleVariant("XorAssign"); break;
case BO_OrAssign: OF.emitSimpleVariant("OrAssign"); break;
case BO_Comma: OF.emitSimpleVariant("Comma"); break;
}
}
/// \atd
/// #define compound_assign_operator_tuple binary_operator_tuple * compound_assign_operator_info
/// type compound_assign_operator_info = {
/// lhs_type : qual_type;
/// result_type : qual_type;
/// } <ocaml field_prefix="caoi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCompoundAssignOperator(const CompoundAssignOperator *Node) {
VisitBinaryOperator(Node);
ObjectScope Scope(OF);
OF.emitTag("lhs_type");
dumpBareQualType(Node->getComputationLHSType());
OF.emitTag("result_type");
dumpBareQualType(Node->getComputationResultType());
}
/// \atd
/// #define block_expr_tuple expr_tuple * decl
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBlockExpr(const BlockExpr *Node) {
VisitExpr(Node);
dumpBareDecl(Node->getBlockDecl());
}
/// \atd
/// #define opaque_value_expr_tuple expr_tuple * opaque_value_expr_info
/// type opaque_value_expr_info = {
/// ?source_expr : stmt option;
/// } <ocaml field_prefix="ovei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitOpaqueValueExpr(const OpaqueValueExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
if (const Expr *Source = Node->getSourceExpr()) {
OF.emitTag("source_expr");
dumpBareStmt(Source);
}
}
// GNU extensions.
/// \atd
/// #define addr_label_expr_tuple expr_tuple * addr_label_expr_info
/// type addr_label_expr_info = {
/// label : string;
/// pointer : pointer;
/// } <ocaml field_prefix="alei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitAddrLabelExpr(const AddrLabelExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("label");
OF.emitString(Node->getLabel()->getName());
OF.emitTag("pointer");
dumpBarePointer(Node->getLabel());
}
////===----------------------------------------------------------------------===//
//// C++ Expressions
////===----------------------------------------------------------------------===//
/// \atd
/// #define cxx_named_cast_expr_tuple explicit_cast_expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node) {
VisitExplicitCastExpr(Node);
OF.emitString(Node->getCastName());
}
/// \atd
/// #define cxx_bool_literal_expr_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
/// \atd
/// #define cxx_construct_expr_tuple expr_tuple * cxx_construct_expr_info
/// type cxx_construct_expr_info = {
/// qual_type : qual_type;
/// ~is_elidable : bool;
/// ~requires_zero_initialization : bool;
/// } <ocaml field_prefix="xcei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXConstructExpr(const CXXConstructExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("qual_type");
CXXConstructorDecl *Ctor = Node->getConstructor();
dumpBareQualType(Ctor->getType());
OF.emitFlag("is_elidable", Node->isElidable());
OF.emitFlag("requires_zero_initialization", Node->requiresZeroInitialization());
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node) {
// VisitExpr(Node);
// OS << " ";
// dumpCXXTemporary(Node->getTemporary());
//}
//
//void
//ASTExporter<ATDWriter>::VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node) {
// VisitExpr(Node);
// if (const ValueDecl *VD = Node->getExtendingDecl()) {
// OS << " extended by ";
// dumpBareDeclRef(VD);
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitExprWithCleanups(const ExprWithCleanups *Node) {
// VisitExpr(Node);
// for (unsigned i = 0, e = Node->getNumObjects(); i != e; ++i)
// dumpDeclRef(Node->getObject(i), "cleanup");
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpCXXTemporary(const CXXTemporary *Temporary) {
// OS << "(CXXTemporary";
// dumpBarePointer(Temporary);
// OS << ")";
//}
//
////===----------------------------------------------------------------------===//
//// Obj-C Expressions
////===----------------------------------------------------------------------===//
/// \atd
/// #define obj_c_message_expr_tuple expr_tuple * obj_c_message_expr_info
/// type obj_c_message_expr_info = {
/// selector : string;
/// ~receiver_kind <ocaml default="`Instance"> : receiver_kind
/// } <ocaml field_prefix="omei_">
///
/// type receiver_kind = [ Instance | Class of qual_type | SuperInstance | SuperClass ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCMessageExpr(const ObjCMessageExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("selector");
OF.emitString(Node->getSelector().getAsString());
ObjCMessageExpr::ReceiverKind RK = Node->getReceiverKind();
if (RK != ObjCMessageExpr::Instance) {
OF.emitTag("receiver_kind");
switch (RK) {
case ObjCMessageExpr::Class:
{
VariantScope Scope(OF, "Class");
dumpBareQualType(Node->getClassReceiver());
}
break;
case ObjCMessageExpr::SuperInstance:
OF.emitSimpleVariant("SuperInstance");
break;
case ObjCMessageExpr::SuperClass:
OF.emitSimpleVariant("SuperClass");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// type selector = string
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareSelector(const Selector sel) {
OF.emitString(sel.getAsString());
}
/// \atd
/// #define obj_c_boxed_expr_tuple expr_tuple * selector
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *Node) {
VisitExpr(Node);
dumpBareSelector(Node->getBoxingMethod()->getSelector());
}
/// \atd
/// #define obj_c_at_catch_stmt_tuple stmt_tuple * obj_c_message_expr_kind
/// type obj_c_message_expr_kind = [
/// | CatchParam of decl
/// | CatchAll
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node) {
VisitStmt(Node);
if (const VarDecl *CatchParam = Node->getCatchParamDecl()) {
VariantScope Scope(OF, "CatchParam");
dumpBareDecl(CatchParam);
} else {
OF.emitSimpleVariant("CatchAll");
}
}
/// \atd
/// #define obj_c_encode_expr_tuple expr_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *Node) {
VisitExpr(Node);
dumpBareQualType(Node->getEncodedType());
}
/// \atd
/// #define obj_c_selector_expr_tuple expr_tuple * selector
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCSelectorExpr(const ObjCSelectorExpr *Node) {
VisitExpr(Node);
dumpBareSelector(Node->getSelector());
}
/// \atd
/// #define obj_c_protocol_expr_tuple expr_tuple * decl_ref
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCProtocolExpr(const ObjCProtocolExpr *Node) {
VisitExpr(Node);
dumpBareDeclRef(*Node->getProtocol());
}
/// \atd
/// #define obj_c_property_ref_expr_tuple expr_tuple * obj_c_property_ref_expr_info
///
/// type obj_c_property_ref_expr_info = {
/// kind : property_ref_kind;
/// ~is_super_receiver : bool;
/// ~is_messaging_getter : bool;
/// ~is_messaging_setter : bool;
/// } <ocaml field_prefix="oprei_">
///
/// type property_ref_kind = [
/// | MethodRef of obj_c_method_ref_info
/// | PropertyRef of decl_ref
/// ]
///
/// type obj_c_method_ref_info = {
/// ?getter : selector option;
/// ?setter : selector option
/// } <ocaml field_prefix="mri_">
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
if (Node->isImplicitProperty()) {
VariantScope Scope(OF, "MethodRef");
{
ObjectScope Scope(OF);
if (Node->getImplicitPropertyGetter()) {
OF.emitTag("getter");
dumpBareSelector(Node->getImplicitPropertyGetter()->getSelector());
}
if (Node->getImplicitPropertySetter()) {
OF.emitTag("setter");
dumpBareSelector(Node->getImplicitPropertySetter()->getSelector());
}
}
} else {
VariantScope Scope(OF, "PropertyRef");
dumpBareDeclRef(*Node->getExplicitProperty());
}
OF.emitFlag("is_super_receiver", Node->isSuperReceiver());
OF.emitFlag("is_messaging_getter", Node->isMessagingGetter());
OF.emitFlag("is_messaging_setter", Node->isMessagingSetter());
}
/// \atd
/// #define obj_c_subscript_ref_expr_tuple expr_tuple * obj_c_subscript_ref_expr_info
///
/// type obj_c_subscript_ref_expr_info = {
/// kind : obj_c_subscript_kind;
/// ?getter : selector option;
/// ?setter : selector option
/// } <ocaml field_prefix="osrei_">
///
/// type obj_c_subscript_kind = [ ArraySubscript | DictionarySubscript ]
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
if (Node->isArraySubscriptRefExpr()) {
OF.emitSimpleVariant("ArraySubscript");
} else {
OF.emitSimpleVariant("DictionarySubscript");
}
if (Node->getAtIndexMethodDecl()) {
OF.emitTag("getter");
dumpBareSelector(Node->getAtIndexMethodDecl()->getSelector());
}
if (Node->setAtIndexMethodDecl()) {
OF.emitTag("setter");
dumpBareSelector(Node->setAtIndexMethodDecl()->getSelector());
}
}
/// \atd
/// #define obj_c_bool_literal_expr_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
// Main variant for statements
/// \atd
/// type stmt = [
#define STMT(CLASS, PARENT) /// | CLASS of (@CLASS@_tuple)
#define ABSTRACT_STMT(STMT)
#include <clang/AST/StmtNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// Comments
//===----------------------------------------------------------------------===//
template <class ATDWriter>
const char *ASTExporter<ATDWriter>::getCommandName(unsigned CommandID) {
return Traits.getCommandInfo(CommandID)->Name;
}
/// \atd
/// type _full_comment = { ?full_comment : comment option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpFullComment(const FullComment *C) {
if (!C)
return;
OF.emitTag("full_comment");
FC = C;
dumpBareComment(C);
FC = 0;
}
/// \atd
#define COMMENT(CLASS, PARENT) /// #define @CLASS@_tuple @PARENT@_tuple
#define ABSTRACT_COMMENT(COMMENT) COMMENT
#include <clang/AST/CommentNodes.inc>
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareComment(const Comment *C) {
if (!C) {
// We use a fixed NoComment node to represent null pointers
C = NullPtrComment;
}
VariantScope Scope(OF, std::string(C->getCommentKindName()));
{
TupleScope Scope(OF);
ConstCommentVisitor<ASTExporter<ATDWriter>>::visit(C);
}
}
/// \atd
/// #define comment_tuple comment_info * comment list
/// type comment_info = {
/// parent_pointer : pointer;
/// inherit _source_range;
/// } <ocaml field_prefix="ci_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::visitComment(const Comment *C) {
{
ObjectScope ObjComment(OF);
OF.emitTag("parent_pointer");
dumpBarePointer(C);
dumpSourceRange(C->getSourceRange());
}
{
ArrayScope Scope(OF);
for (Comment::child_iterator I = C->child_begin(), E = C->child_end();
I != E; ++I) {
dumpBareComment(*I);
}
}
}
/// \atd
/// #define text_comment_tuple comment_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::visitTextComment(const TextComment *C) {
visitComment(C);
OF.emitString(C->getText());
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitInlineCommandComment(const InlineCommandComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
// switch (C->getRenderKind()) {
// case InlineCommandComment::RenderNormal:
// OS << " RenderNormal";
// break;
// case InlineCommandComment::RenderBold:
// OS << " RenderBold";
// break;
// case InlineCommandComment::RenderMonospaced:
// OS << " RenderMonospaced";
// break;
// case InlineCommandComment::RenderEmphasized:
// OS << " RenderEmphasized";
// break;
// }
//
// for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
// OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
// OS << " Name=\"" << C->getTagName() << "\"";
// if (C->getNumAttrs() != 0) {
// OS << " Attrs: ";
// for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
// const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
// OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
// }
// }
// if (C->isSelfClosing())
// OS << " SelfClosing";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
// OS << " Name=\"" << C->getTagName() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitBlockCommandComment(const BlockCommandComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
// for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
// OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitParamCommandComment(const ParamCommandComment *C) {
// OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
//
// if (C->isDirectionExplicit())
// OS << " explicitly";
// else
// OS << " implicitly";
//
// if (C->hasParamName()) {
// if (C->isParamIndexValid())
// OS << " Param=\"" << C->getParamName(FC) << "\"";
// else
// OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
// }
//
// if (C->isParamIndexValid())
// OS << " ParamIndex=" << C->getParamIndex();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitTParamCommandComment(const TParamCommandComment *C) {
// if (C->hasParamName()) {
// if (C->isPositionValid())
// OS << " Param=\"" << C->getParamName(FC) << "\"";
// else
// OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
// }
//
// if (C->isPositionValid()) {
// OS << " Position=<";
// for (unsigned i = 0, e = C->getDepth(); i != e; ++i) {
// OS << C->getIndex(i);
// if (i != e - 1)
// OS << ", ";
// }
// OS << ">";
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\""
// " CloseName=\"" << C->getCloseName() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimBlockLineComment(
// const VerbatimBlockLineComment *C) {
// OS << " Text=\"" << C->getText() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimLineComment(const VerbatimLineComment *C) {
// OS << " Text=\"" << C->getText() << "\"";
//}
/// \atd
/// type comment = [
#define COMMENT(CLASS, PARENT) /// | CLASS of (@CLASS@_tuple)
#define ABSTRACT_COMMENT(COMMENT)
#include <clang/AST/CommentNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// ASTExporter Plugin Main
//===----------------------------------------------------------------------===//
namespace {
template <class ATDWriter>
class ExporterASTConsumer : public ASTConsumer {
private:
std::string BasePath;
std::string DeduplicationServicePath;
raw_ostream &OS;
public:
ExporterASTConsumer(CompilerInstance &CI,
StringRef InputFile,
StringRef BasePath,
StringRef DeduplicationServicePath,
raw_ostream &OS)
: BasePath(BasePath),
DeduplicationServicePath(DeduplicationServicePath),
OS(OS)
{}
virtual void HandleTranslationUnit(ASTContext &Context) {
TranslationUnitDecl *D = Context.getTranslationUnitDecl();
FileUtils::DeduplicationService Dedup(DeduplicationServicePath, BasePath, Context.getSourceManager());
ASTExporter<ATDWriter> P(OS, Context, BasePath, DeduplicationServicePath != "" ? &Dedup : nullptr);
P.dumpBareDecl(D);
}
};
}
typedef SimplePluginASTAction<ExporterASTConsumer<JsonWriter>> JsonExporterASTAction;
typedef SimplePluginASTAction<ExporterASTConsumer<YojsonWriter>> YojsonExporterASTAction;
static FrontendPluginRegistry::Add<JsonExporterASTAction>
X("JsonASTExporter", "Export the AST of source files into ATD-specified Json data");
static FrontendPluginRegistry::Add<YojsonExporterASTAction>
Y("YojsonASTExporter", "Export the AST of source files into ATD-specified Yojson data");
[libtooling] Rename the only boolean flag starting with "does_"
Summary: [libtooling] Rename the only boolean flag starting with "does_"
Test Plan:
make -C libtooling test
make -C clang-ocaml test
Reviewers: irp
Reviewed By: irp
Differential Revision: https://phabricator.fb.com/D1438487
/**
* Copyright (c) 2014, Facebook, Inc.
* Copyright (c) 2003-2014 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* This file is distributed under the University of Illinois Open Source License.
* See LLVM-LICENSE for details.
*
*/
/**
* Clang frontend plugin to export an AST of clang into Json and Yojson (and ultimately Biniou)
* while conforming to the inlined ATD specifications.
*
* /!\
* '\atd' block comments are meant to be extracted and processed to generate ATD specifications for the Json dumper.
* Do not modify ATD comments without modifying the Json emission accordingly (and conversely).
* See ATD_GUIDELINES.md for more guidelines on how to write and test ATD annotations.
*
* This file was obtained by modifying the file ASTdumper.cpp from the LLVM/clang project.
* The general layout should be maintained to make future merging easier.
*/
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/Attr.h>
#include <clang/AST/CommentVisitor.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclLookups.h>
#include <clang/AST/DeclObjC.h>
#include <clang/AST/DeclVisitor.h>
#include <clang/AST/StmtVisitor.h>
#include <clang/Basic/Module.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendDiagnostic.h>
#include <llvm/Support/raw_ostream.h>
#include "atdlib/ATDWriter.h"
#include "SimplePluginASTAction.h"
#include "FileUtils.h"
using namespace clang;
using namespace clang::comments;
//===----------------------------------------------------------------------===//
// ASTExporter Visitor
//===----------------------------------------------------------------------===//
namespace {
typedef ATDWriter::JsonWriter<raw_ostream> JsonWriter;
typedef ATDWriter::YojsonWriter<raw_ostream> YojsonWriter;
template <class ATDWriter = YojsonWriter>
class ASTExporter :
public ConstDeclVisitor<ASTExporter<ATDWriter>>,
public ConstStmtVisitor<ASTExporter<ATDWriter>>,
public ConstCommentVisitor<ASTExporter<ATDWriter>>
{
typedef typename ATDWriter::ObjectScope ObjectScope;
typedef typename ATDWriter::ArrayScope ArrayScope;
typedef typename ATDWriter::TupleScope TupleScope;
typedef typename ATDWriter::VariantScope VariantScope;
ATDWriter OF;
const CommandTraits &Traits;
const SourceManager &SM;
// Optional currentWorkingDirectory to normalize relative paths.
StringRef BasePath;
// Optional service to avoid repeating the content of a same header file across a compilation.
FileUtils::DeduplicationService *DedupService;
// Encoding of NULL pointers into suitable empty nodes
// This is a hack but using option types in children lists would make the Json terribly verbose.
// Also these useless nodes could have occurred in the original AST anyway :)
//
// Note: We are not using OwningPtr because 'delete' appears to be protected (at least on Stmt).
const Stmt *const NullPtrStmt;
const Decl *const NullPtrDecl;
const Comment *const NullPtrComment;
/// Keep track of the last location we print out so that we can
/// print out deltas from then on out.
const char *LastLocFilename;
unsigned LastLocLine;
/// The \c FullComment parent of the comment being dumped.
const FullComment *FC;
public:
ASTExporter(raw_ostream &OS, ASTContext &Context, StringRef BasePath, FileUtils::DeduplicationService *DedupService)
: OF(OS),
Traits(Context.getCommentCommandTraits()),
SM(Context.getSourceManager()),
BasePath(BasePath),
DedupService(DedupService),
NullPtrStmt(new (Context) NullStmt(SourceLocation())),
NullPtrDecl(EmptyDecl::Create(Context, Context.getTranslationUnitDecl(), SourceLocation())),
NullPtrComment(new (Context) Comment(Comment::NoCommentKind, SourceLocation(), SourceLocation())),
LastLocFilename(""), LastLocLine(~0U), FC(0)
{
}
void dumpBareDecl(const Decl *D);
void dumpBareStmt(const Stmt *S);
void dumpFullComment(const FullComment *C);
// Utilities
void dumpBarePointer(const void *Ptr);
void dumpSourceRange(SourceRange R);
void dumpBareSourceLocation(SourceLocation Loc);
void dumpBareQualType(QualType T);
void dumpBareType(const Type *T);
void dumpQualType(QualType T);
void dumpBareDeclRef(const Decl &Node);
void dumpDeclRef(const Decl *Node, const char *Label = 0);
void dumpName(const NamedDecl *D);
bool hasNodes(const DeclContext *DC);
void dumpBareLookups(const DeclContext &DC);
void dumpBareAttr(const Attr &A);
void dumpBareSelector(const Selector sel);
// C++ Utilities
void dumpAccessSpecifier(AccessSpecifier AS);
void dumpBareCXXCtorInitializer(const CXXCtorInitializer &Init);
// void dumpTemplateParameters(const TemplateParameterList *TPL);
// void dumpTemplateArgumentListInfo(const TemplateArgumentListInfo &TALI);
// void dumpTemplateArgumentLoc(const TemplateArgumentLoc &A);
// void dumpTemplateArgumentList(const TemplateArgumentList &TAL);
// void dumpTemplateArgument(const TemplateArgument &A,
// SourceRange R = SourceRange());
void dumpBareCXXBaseSpecifier(const CXXBaseSpecifier &Base);
// Decls
void VisitDecl(const Decl *D);
void VisitDeclContext(const DeclContext *DC);
void VisitBlockDecl(const BlockDecl *D);
void VisitCapturedDecl(const CapturedDecl *D);
void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
void VisitNamespaceDecl(const NamespaceDecl *D);
void VisitObjCContainerDecl(const ObjCContainerDecl *D);
void VisitTagDecl(const TagDecl *D);
void VisitTypeDecl(const TypeDecl *D);
void VisitTranslationUnitDecl(const TranslationUnitDecl *D);
void VisitNamedDecl(const NamedDecl *D);
void VisitValueDecl(const ValueDecl *D);
void VisitTypedefDecl(const TypedefDecl *D);
void VisitEnumDecl(const EnumDecl *D);
void VisitRecordDecl(const RecordDecl *D);
void VisitEnumConstantDecl(const EnumConstantDecl *D);
void VisitIndirectFieldDecl(const IndirectFieldDecl *D);
void VisitFunctionDecl(const FunctionDecl *D);
void VisitFieldDecl(const FieldDecl *D);
void VisitVarDecl(const VarDecl *D);
void VisitFileScopeAsmDecl(const FileScopeAsmDecl *D);
void VisitImportDecl(const ImportDecl *D);
// // C++ Decls
// void VisitNamespaceDecl(const NamespaceDecl *D);
// void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D);
// void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
// void VisitTypeAliasDecl(const TypeAliasDecl *D);
// void VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D);
// void VisitCXXRecordDecl(const CXXRecordDecl *D);
// void VisitStaticAssertDecl(const StaticAssertDecl *D);
// void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
// void VisitClassTemplateDecl(const ClassTemplateDecl *D);
// void VisitClassTemplateSpecializationDecl(
// const ClassTemplateSpecializationDecl *D);
// void VisitClassTemplatePartialSpecializationDecl(
// const ClassTemplatePartialSpecializationDecl *D);
// void VisitClassScopeFunctionSpecializationDecl(
// const ClassScopeFunctionSpecializationDecl *D);
// void VisitVarTemplateDecl(const VarTemplateDecl *D);
// void VisitVarTemplateSpecializationDecl(
// const VarTemplateSpecializationDecl *D);
// void VisitVarTemplatePartialSpecializationDecl(
// const VarTemplatePartialSpecializationDecl *D);
// void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
// void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
// void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
// void VisitUsingDecl(const UsingDecl *D);
// void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
// void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
// void VisitUsingShadowDecl(const UsingShadowDecl *D);
// void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
// void VisitAccessSpecDecl(const AccessSpecDecl *D);
// void VisitFriendDecl(const FriendDecl *D);
//
// // ObjC Decls
void VisitObjCIvarDecl(const ObjCIvarDecl *D);
void VisitObjCMethodDecl(const ObjCMethodDecl *D);
void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
// Stmts.
void VisitStmt(const Stmt *Node);
void VisitDeclStmt(const DeclStmt *Node);
void VisitAttributedStmt(const AttributedStmt *Node);
void VisitLabelStmt(const LabelStmt *Node);
void VisitGotoStmt(const GotoStmt *Node);
void VisitCXXCatchStmt(const CXXCatchStmt *Node);
// Exprs
void VisitExpr(const Expr *Node);
void VisitCastExpr(const CastExpr *Node);
void VisitExplicitCastExpr(const ExplicitCastExpr *Node);
void VisitDeclRefExpr(const DeclRefExpr *Node);
void VisitPredefinedExpr(const PredefinedExpr *Node);
void VisitCharacterLiteral(const CharacterLiteral *Node);
void VisitIntegerLiteral(const IntegerLiteral *Node);
void VisitFloatingLiteral(const FloatingLiteral *Node);
void VisitStringLiteral(const StringLiteral *Str);
void VisitUnaryOperator(const UnaryOperator *Node);
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Node);
void VisitMemberExpr(const MemberExpr *Node);
void VisitExtVectorElementExpr(const ExtVectorElementExpr *Node);
void VisitBinaryOperator(const BinaryOperator *Node);
void VisitCompoundAssignOperator(const CompoundAssignOperator *Node);
void VisitAddrLabelExpr(const AddrLabelExpr *Node);
void VisitBlockExpr(const BlockExpr *Node);
void VisitOpaqueValueExpr(const OpaqueValueExpr *Node);
// C++
void VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node);
void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
void VisitCXXConstructExpr(const CXXConstructExpr *Node);
// void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
// void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node);
// void VisitExprWithCleanups(const ExprWithCleanups *Node);
// void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node);
// void dumpCXXTemporary(const CXXTemporary *Temporary);
// void VisitLambdaExpr(const LambdaExpr *Node) {
// VisitExpr(Node);
// dumpBareDecl(Node->getLambdaClass());
// }
// ObjC
void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node);
void VisitObjCEncodeExpr(const ObjCEncodeExpr *Node);
void VisitObjCMessageExpr(const ObjCMessageExpr *Node);
void VisitObjCBoxedExpr(const ObjCBoxedExpr *Node);
void VisitObjCSelectorExpr(const ObjCSelectorExpr *Node);
void VisitObjCProtocolExpr(const ObjCProtocolExpr *Node);
void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node);
void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node);
void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node);
void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node);
// Comments.
const char *getCommandName(unsigned CommandID);
void dumpBareComment(const Comment *C);
// Inline comments.
void visitComment(const Comment *C);
void visitTextComment(const TextComment *C);
// void visitInlineCommandComment(const InlineCommandComment *C);
// void visitHTMLStartTagComment(const HTMLStartTagComment *C);
// void visitHTMLEndTagComment(const HTMLEndTagComment *C);
//
// // Block comments.
// void visitBlockCommandComment(const BlockCommandComment *C);
// void visitParamCommandComment(const ParamCommandComment *C);
// void visitTParamCommandComment(const TParamCommandComment *C);
// void visitVerbatimBlockComment(const VerbatimBlockComment *C);
// void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
// void visitVerbatimLineComment(const VerbatimLineComment *C);
};
}
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// \atd
/// type pointer = string
template <class ATDWriter>
static void dumpBarePointer(ATDWriter &OF, const void *Ptr) {
char str[20];
snprintf(str, 20, "%p", Ptr);
OF.emitString(std::string(str));
}
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBarePointer(const void *Ptr) {
::dumpBarePointer(OF, Ptr);
}
/// \atd
/// type source_location = {
/// ?file : string option;
/// ?line : int option;
/// ?column : int option;
/// } <ocaml field_prefix="sl_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareSourceLocation(SourceLocation Loc) {
ObjectScope Scope(OF);
SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
// The general format we print out is filename:line:col, but we drop pieces
// that haven't changed since the last loc printed.
PresumedLoc PLoc = SM.getPresumedLoc(SpellingLoc);
if (PLoc.isInvalid()) {
return;
}
if (strcmp(PLoc.getFilename(), LastLocFilename) != 0) {
OF.emitTag("file");
// Normalizing filenames matters because the current directory may change during the compilation of large projects.
OF.emitString(FileUtils::normalizePath(BasePath, PLoc.getFilename()));
OF.emitTag("line");
OF.emitInteger(PLoc.getLine());
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
} else if (PLoc.getLine() != LastLocLine) {
OF.emitTag("line");
OF.emitInteger(PLoc.getLine());
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
} else {
OF.emitTag("column");
OF.emitInteger(PLoc.getColumn());
}
LastLocFilename = PLoc.getFilename();
LastLocLine = PLoc.getLine();
// TODO: lastLocColumn
}
/// \atd
/// type _source_range = {
/// ?source_range : source_range option
/// }
/// type source_range = (source_location * source_location)
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpSourceRange(SourceRange R) {
OF.emitTag("source_range");
TupleScope Scope(OF);
dumpBareSourceLocation(R.getBegin());
dumpBareSourceLocation(R.getEnd());
}
// TODO: really dump types as trees
/// \atd
/// type opt_type = [Type of string | NoType]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareType(const Type *T) {
if (!T) {
OF.emitSimpleVariant("NoType");
} else {
VariantScope Scope(OF, "Type");
OF.emitString(QualType::getAsString(QualType(T, 0).getSplitDesugaredType()));
}
}
/// \atd
/// type qual_type = {
/// raw : string;
/// ?desugared : string option
/// } <ocaml field_prefix="qt_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareQualType(QualType T) {
ObjectScope Scope(OF);
SplitQualType T_split = T.split();
OF.emitTag("raw");
OF.emitString(QualType::getAsString(T_split));
if (!T.isNull()) {
// If the type is sugared, also dump a (shallow) desugared type.
SplitQualType D_split = T.getSplitDesugaredType();
if (T_split != D_split) {
OF.emitTag("desugared");
OF.emitString(QualType::getAsString(D_split));
}
}
}
/// \atd
/// type _qual_type = { qual_type : qual_type }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpQualType(QualType T) {
OF.emitTag("qual_type");
dumpBareQualType(T);
}
/// \atd
/// type _name = { ?name : string option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpName(const NamedDecl *ND) {
if (ND && ND->getDeclName()) {
OF.emitTag("name");
OF.emitString(ND->getNameAsString());
}
}
/// \atd
/// type decl_ref = {
/// kind : decl_kind;
/// inherit _name;
/// ~is_hidden : bool;
/// ?qual_type : qual_type option
/// } <ocaml field_prefix="dr_">
///
/// type decl_kind = [
#define DECL(DERIVED, BASE) /// | DERIVED
#define ABSTRACT_DECL(DECL) DECL
#include <clang/AST/DeclNodes.inc>
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareDeclRef(const Decl &D) {
ObjectScope Scope(OF);
OF.emitTag("kind");
OF.emitSimpleVariant(D.getDeclKindName());
const NamedDecl *ND = dyn_cast<NamedDecl>(&D);
if (ND) {
dumpName(ND);
OF.emitFlag("is_hidden", ND->isHidden());
}
if (const ValueDecl *VD = dyn_cast<ValueDecl>(&D)) {
dumpQualType(VD->getType());
}
}
/// \atd
/// type _decl_ref = { ?decl_ref : decl_ref option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpDeclRef(const Decl *D, const char *Label) {
if (!D)
return;
if (Label) {
// ATD TODO: not supported
OF.emitTag(Label);
} else {
OF.emitTag("decl_ref");
}
dumpBareDeclRef(*D);
}
/// \atd
/// #define decl_context_tuple decl list * decl_context_info
/// type decl_context_info = {
/// ~has_external_lexical_storage : bool;
/// ~has_external_visible_storage : bool
/// } <ocaml field_prefix="dci_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclContext(const DeclContext *DC) {
if (!DC) {
{ ArrayScope Scope(OF); }
{ ObjectScope Scope(OF); }
return;
}
{
ArrayScope Scope(OF);
for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
I != E; ++I) {
if (!DedupService || DedupService->verifyDeclFileLocation(**I)) {
dumpBareDecl(*I);
}
}
}
{
ObjectScope Scope(OF);
OF.emitFlag("has_external_lexical_storage", DC->hasExternalLexicalStorage());
OF.emitFlag("has_external_visible_storage", DC->hasExternalVisibleStorage());
}
}
/// \atd
/// type lookups = {
/// decl_ref : decl_ref;
/// ?primary_context_pointer : pointer option;
/// lookups : lookup list;
/// ~has_undeserialized_decls : bool;
/// } <ocaml field_prefix="lups_">
///
/// type lookup = {
/// decl_name : string;
/// decl_refs : decl_ref list;
/// } <ocaml field_prefix="lup_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareLookups(const DeclContext &DC) {
ObjectScope Scope(OF);
OF.emitTag("decl_ref");
dumpBareDeclRef(cast<Decl>(DC));
const DeclContext *Primary = DC.getPrimaryContext();
if (Primary != &DC) {
OF.emitTag("primary_context_pointer");
dumpBarePointer(cast<Decl>(Primary));
}
OF.emitTag("lookups");
{
ArrayScope Scope(OF);
DeclContext::all_lookups_iterator I = Primary->noload_lookups_begin(),
E = Primary->noload_lookups_end();
while (I != E) {
DeclarationName Name = I.getLookupName();
DeclContextLookupResult R = *I++;
ObjectScope Scope(OF);
OF.emitTag("decl_name");
OF.emitString(Name.getAsString());
OF.emitTag("decl_refs");
{
ArrayScope Scope(OF);
for (DeclContextLookupResult::iterator RI = R.begin(), RE = R.end();
RI != RE; ++RI) {
dumpBareDeclRef(**RI);
}
}
}
}
bool HasUndeserializedLookups = Primary->hasExternalVisibleStorage();
OF.emitFlag("has_undeserialized_decls", HasUndeserializedLookups);
}
//TODO: dump the content of the attributes
//static bool hasMoreChildren() { return false; }
//static void setMoreChildren(bool x) {}
//static void lastChild() {}
/// \atd
/// type attribute = [
#define ATTR(X) /// | X of attribute_info
#include <clang/Basic/AttrList.inc>
/// ]
/// type attribute_info = {
/// pointer : pointer;
/// inherit _source_range;
/// ~is_implicit : bool
/// } <ocaml field_prefix="ai_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareAttr(const Attr &A) {
std::string tag;
switch (A.getKind()) {
#define ATTR(X) case attr::X: tag = #X; break;
#include <clang/Basic/AttrList.inc>
default: llvm_unreachable("unexpected attribute kind");
}
VariantScope Scope(OF, tag);
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(&A);
dumpSourceRange(A.getRange());
// TODO
//#include <clang/AST/AttrDump.inc>
OF.emitFlag("is_implicit", A.isImplicit());
}
}
/// \atd
/// type previous_decl = [
/// | None
/// | First of pointer
/// | Previous of pointer
/// ]
template <class ATDWriter>
static void dumpPreviousDeclImpl(ATDWriter &OF, ...) {}
template <class ATDWriter, typename T>
static void dumpPreviousDeclImpl(ATDWriter &OF, const Mergeable<T> *D) {
const T *First = D->getFirstDecl();
if (First != D) {
OF.emitTag("previous_decl");
typename ATDWriter::VariantScope Scope(OF, "First");
dumpBarePointer(OF, First);
}
}
template <class ATDWriter, typename T>
static void dumpPreviousDeclImpl(ATDWriter &OF, const Redeclarable<T> *D) {
const T *Prev = D->getPreviousDecl();
if (Prev) {
OF.emitTag("previous_decl");
typename ATDWriter::VariantScope Scope(OF, "Previous");
dumpBarePointer(OF, Prev);
}
}
/// Dump the previous declaration in the redeclaration chain for a declaration,
/// if any.
///
/// \atd type _previous_decl = {
/// ~previous_decl <ocaml default="`None"> : previous_decl;
/// }
template <class ATDWriter>
static void dumpPreviousDecl(ATDWriter &OF, const Decl *D) {
switch (D->getKind()) {
#define DECL(DERIVED, BASE) \
case Decl::DERIVED: \
return dumpPreviousDeclImpl(OF, cast<DERIVED##Decl>(D));
#define ABSTRACT_DECL(DECL)
#include <clang/AST/DeclNodes.inc>
}
llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
}
//===----------------------------------------------------------------------===//
// C++ Utilities
//===----------------------------------------------------------------------===//
/// \atd
/// type _access_specifier = { ~access_specifier <ocaml default="`None"> : access_specifier }
/// type access_specifier = [ None | Public | Protected | Private ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpAccessSpecifier(AccessSpecifier AS) {
if (AS == AS_none) {
return;
}
OF.emitTag("access_specifier");
switch (AS) {
case AS_public:
OF.emitSimpleVariant("Public");
break;
case AS_protected:
OF.emitSimpleVariant("Protected");
break;
case AS_private:
OF.emitSimpleVariant("Private");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
/// \atd
/// type cxx_ctor_initializer = {
/// subject : cxx_ctor_initializer_subject;
/// ?init_expr : stmt option
/// } <ocaml field_prefix="xci_">
/// type cxx_ctor_initializer_subject = [
/// Member of decl_ref
/// | Delegating of qual_type
/// | BaseClass of (qual_type * bool)
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareCXXCtorInitializer(const CXXCtorInitializer &Init) {
ObjectScope Scope(OF);
OF.emitTag("subject");
const FieldDecl *FD = Init.getAnyMember();
if (FD) {
VariantScope Scope(OF, "Member");
dumpBareDeclRef(*FD);
} else if (Init.isDelegatingInitializer()) {
VariantScope Scope(OF, "Delegating");
dumpBareQualType(Init.getTypeSourceInfo()->getType());
} else {
VariantScope Scope(OF, "BaseClass");
{
TupleScope Scope(OF);
dumpBareQualType(Init.getTypeSourceInfo()->getType());
OF.emitBoolean(Init.isBaseVirtual());
}
}
const Expr *E = Init.getInit();
if (E) {
OF.emitTag("init_expr");
dumpBareStmt(E);
}
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateParameters(const TemplateParameterList *TPL) {
// if (!TPL)
// return;
//
// for (TemplateParameterList::const_iterator I = TPL->begin(), E = TPL->end();
// I != E; ++I)
// dumpBareDecl(*I);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentListInfo(
// const TemplateArgumentListInfo &TALI) {
// for (unsigned i = 0, e = TALI.size(); i < e; ++i) {
// dumpTemplateArgumentLoc(TALI[i]);
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentLoc(const TemplateArgumentLoc &A) {
// dumpTemplateArgument(A.getArgument(), A.getSourceRange());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgumentList(const TemplateArgumentList &TAL) {
// for (unsigned i = 0, e = TAL.size(); i < e; ++i)
// dumpTemplateArgument(TAL[i]);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpTemplateArgument(const TemplateArgument &A, SourceRange R) {
// ObjectScope Scope(OF);
// OS << "TemplateArgument";
// if (R.isValid())
// dumpSourceRange(R);
//
// switch (A.getKind()) {
// case TemplateArgument::Null:
// OS << " null";
// break;
// case TemplateArgument::Type:
// OS << " type";
// dumpQualType(A.getAsType());
// break;
// case TemplateArgument::Declaration:
// OS << " decl";
// dumpDeclRef(A.getAsDecl());
// break;
// case TemplateArgument::NullPtr:
// OS << " nullptr";
// break;
// case TemplateArgument::Integral:
// OS << " integral " << A.getAsIntegral();
// break;
// case TemplateArgument::Template:
// OS << " template ";
// // FIXME: do not use the local dump method
// A.getAsTemplate().dump(OS);
// break;
// case TemplateArgument::TemplateExpansion:
// OS << " template expansion";
// // FIXME: do not use the local dump method
// A.getAsTemplateOrTemplatePattern().dump(OS);
// break;
// case TemplateArgument::Expression:
// OS << " expr";
// dumpBareStmt(A.getAsExpr());
// break;
// case TemplateArgument::Pack:
// OS << " pack";
// for (TemplateArgument::pack_iterator I = A.pack_begin(), E = A.pack_end();
// I != E; ++I) {
// dumpTemplateArgument(*I);
// }
// break;
// }
//}
//===----------------------------------------------------------------------===//
// Decl dumping methods.
//===----------------------------------------------------------------------===//
/// \atd
#define DECL(DERIVED, BASE) /// #define @DERIVED@_decl_tuple @BASE@_tuple
#define ABSTRACT_DECL(DECL) DECL
#include <clang/AST/DeclNodes.inc>
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareDecl(const Decl *D) {
if (!D) {
// We use a fixed EmptyDecl node to represent null pointers
D = NullPtrDecl;
}
VariantScope Scope(OF, std::string(D->getDeclKindName()) + "Decl");
{
TupleScope Scope(OF);
ConstDeclVisitor<ASTExporter<ATDWriter>>::Visit(D);
}
}
/// \atd
/// #define decl_tuple decl_info
/// type decl_info = {
/// pointer : pointer;
/// ?parent_pointer : pointer option;
/// inherit _previous_decl;
/// inherit _source_range;
/// ?owning_module : string option;
/// ~is_hidden : bool;
/// attributes : attribute list;
/// inherit _full_comment;
/// ~is_invalid_decl : bool
/// } <ocaml field_prefix="di_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDecl(const Decl *D) {
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(D);
if (D->getLexicalDeclContext() != D->getDeclContext()) {
OF.emitTag("parent_pointer");
dumpBarePointer(cast<Decl>(D->getDeclContext()));
}
dumpPreviousDecl(OF, D);
dumpSourceRange(D->getSourceRange());
if (Module *M = D->getOwningModule()) {
OF.emitTag("owning_module");
OF.emitString(M->getFullModuleName());
}
if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
OF.emitFlag("is_hidden", ND->isHidden());
}
OF.emitTag("attributes");
{
ArrayScope ArrayAttr(OF);
for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
I != E; ++I) {
assert(*I);
dumpBareAttr(**I);
}
}
const FullComment *Comment = D->getASTContext().getLocalCommentForDeclUncached(D);
dumpFullComment(Comment);
OF.emitFlag("is_invalid_decl", D->isInvalidDecl());
}
}
/// \atd
/// #define captured_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCapturedDecl(const CapturedDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define linkage_spec_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define namespace_decl_tuple named_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitNamespaceDecl(const NamespaceDecl *D) {
VisitNamedDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define obj_c_container_decl_tuple named_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCContainerDecl(const ObjCContainerDecl *D) {
VisitNamedDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define tag_decl_tuple type_decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTagDecl(const TagDecl *D) {
VisitTypeDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define type_decl_tuple named_decl_tuple * opt_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTypeDecl(const TypeDecl *D) {
VisitNamedDecl(D);
dumpBareType(D->getTypeForDecl());
}
/// \atd
/// #define value_decl_tuple named_decl_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitValueDecl(const ValueDecl *D) {
VisitNamedDecl(D);
dumpBareQualType(D->getType());
}
/// \atd
/// #define translation_unit_decl_tuple decl_tuple * decl_context_tuple
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTranslationUnitDecl(const TranslationUnitDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
}
/// \atd
/// #define named_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitNamedDecl(const NamedDecl *D) {
VisitDecl(D);
OF.emitString(D->getNameAsString());
}
/// \atd
/// #define typedef_decl_tuple typedef_name_decl_tuple * typedef_decl_info
/// type typedef_decl_info = {
/// ~is_module_private : bool
/// } <ocaml field_prefix="tdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitTypedefDecl(const TypedefDecl *D) {
ASTExporter<ATDWriter>::VisitTypedefNameDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_module_private", D->isModulePrivate());
}
/// \atd
/// #define enum_decl_tuple tag_decl_tuple * enum_decl_info
/// type enum_decl_info = {
/// ?scope : enum_decl_scope option;
/// ~is_module_private : bool
/// } <ocaml field_prefix="edi_">
/// type enum_decl_scope = [Class | Struct]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitEnumDecl(const EnumDecl *D) {
VisitTagDecl(D);
ObjectScope Scope(OF);
if (D->isScoped()) {
OF.emitTag("scope");
if (D->isScopedUsingClassTag())
OF.emitSimpleVariant("Class");
else
OF.emitSimpleVariant("Struct");
}
OF.emitFlag("is_module_private", D->isModulePrivate());
}
/// \atd
/// #define record_decl_tuple tag_decl_tuple * record_decl_info
/// type record_decl_info = {
/// ~is_module_private : bool;
/// ~is_complete_definition : bool
/// } <ocaml field_prefix="rdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitRecordDecl(const RecordDecl *D) {
VisitTagDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_complete_definition", D->isCompleteDefinition());
}
/// \atd
/// #define enum_constant_decl_tuple value_decl_tuple * enum_constant_decl_info
/// type enum_constant_decl_info = {
/// ?init_expr : stmt option
/// } <ocaml field_prefix="ecdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitEnumConstantDecl(const EnumConstantDecl *D) {
VisitValueDecl(D);
ObjectScope Scope(OF);
if (const Expr *Init = D->getInitExpr()) {
OF.emitTag("init_expr");
dumpBareStmt(Init);
}
}
/// \atd
/// #define indirect_field_decl_tuple value_decl_tuple * decl_ref list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitIndirectFieldDecl(const IndirectFieldDecl *D) {
VisitValueDecl(D);
ArrayScope Scope(OF);
for (IndirectFieldDecl::chain_iterator I = D->chain_begin(),
E = D->chain_end();
I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
/// \atd
/// #define function_decl_tuple declarator_decl_tuple * function_decl_info
/// type function_decl_info = {
/// ?storage_class : string option;
/// ~is_inline : bool;
/// ~is_virtual : bool;
/// ~is_module_private : bool;
/// ~is_pure : bool;
/// ~is_delete_as_written : bool;
/// ~decls_in_prototype_scope : decl list;
/// ~parameters : decl list;
/// ~cxx_ctor_initializers : cxx_ctor_initializer list;
/// ?body : stmt option
/// } <ocaml field_prefix="fdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFunctionDecl(const FunctionDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
// We purposedly do not call VisitDeclContext(D).
ObjectScope Scope(OF);
StorageClass SC = D->getStorageClass();
if (SC != SC_None) {
OF.emitTag("storage_class");
OF.emitString(VarDecl::getStorageClassSpecifierString(SC));
}
OF.emitFlag("is_inline", D->isInlineSpecified());
OF.emitFlag("is_virtual", D->isVirtualAsWritten());
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_pure", D->isPure());
OF.emitFlag("is_delete_as_written", D->isDeletedAsWritten());
// if (const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>()) {
// FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
// switch (EPI.ExceptionSpecType) {
// default: break;
// case EST_Unevaluated:
// OS << " noexcept-unevaluated " << EPI.ExceptionSpecDecl;
// break;
// case EST_Uninstantiated:
// OS << " noexcept-uninstantiated " << EPI.ExceptionSpecTemplate;
// break;
// }
// }
//
// const FunctionTemplateSpecializationInfo *FTSI =
// D->getTemplateSpecializationInfo();
// bool HasTemplateSpecialization = FTSI;
//
//
// if (HasTemplateSpecialization) {
// dumpTemplateArgumentList(*FTSI->TemplateArguments);
// }
{
ArrayRef<NamedDecl *>::iterator
I = D->getDeclsInPrototypeScope().begin(),
E = D->getDeclsInPrototypeScope().end();
if (I != E) {
OF.emitTag("decls_in_prototype_scope");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
{
FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(D);
bool HasCtorInitializers = C && C->init_begin() != C->init_end();
if (HasCtorInitializers) {
OF.emitTag("cxx_ctor_initializers");
ArrayScope Scope(OF);
for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
E = C->init_end();
I != E; ++I) {
assert(*I);
dumpBareCXXCtorInitializer(**I);
}
}
bool HasDeclarationBody = D->doesThisDeclarationHaveABody();
if (HasDeclarationBody) {
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
}
/// \atd
/// #define field_decl_tuple declarator_decl_tuple * field_decl_info
/// type field_decl_info = {
/// ~is_mutable : bool;
/// ~is_module_private : bool;
/// ?init_expr : stmt option;
/// ?bit_width_expr : stmt option
/// } <ocaml field_prefix="fldi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFieldDecl(const FieldDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_mutable", D->isMutable());
OF.emitFlag("is_module_private", D->isModulePrivate());
bool IsBitField = D->isBitField();
if (IsBitField && D->getBitWidth()) {
OF.emitTag("bit_width_expr");
dumpBareStmt(D->getBitWidth());
}
Expr *Init = D->getInClassInitializer();
if (Init) {
OF.emitTag("init_expr");
dumpBareStmt(Init);
}
}
/// \atd
/// #define var_decl_tuple declarator_decl_tuple * var_decl_info
/// type var_decl_info = {
/// ?storage_class : string option;
/// ~tls_kind <ocaml default="`Tls_none">: tls_kind;
/// ~is_module_private : bool;
/// ~is_nrvo_variable : bool;
/// ?init_expr : stmt option;
/// } <ocaml field_prefix="vdi_">
///
/// type tls_kind = [ Tls_none | Tls_static | Tls_dynamic ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitVarDecl(const VarDecl *D) {
ASTExporter<ATDWriter>::VisitDeclaratorDecl(D);
ObjectScope Scope(OF);
StorageClass SC = D->getStorageClass();
if (SC != SC_None) {
OF.emitTag("storage_class");
OF.emitString(VarDecl::getStorageClassSpecifierString(SC));
}
switch (D->getTLSKind()) {
case VarDecl::TLS_None: break;
case VarDecl::TLS_Static: OF.emitTag("tls_kind"); OF.emitSimpleVariant("Tls_static"); break;
case VarDecl::TLS_Dynamic: OF.emitTag("tls_kind"); OF.emitSimpleVariant("Tls_dynamic"); break;
}
OF.emitFlag("is_module_private", D->isModulePrivate());
OF.emitFlag("is_nrvo_variable", D->isNRVOVariable());
if (D->hasInit()) {
OF.emitTag("init_expr");
dumpBareStmt(D->getInit());
}
}
/// \atd
/// #define file_scope_asm_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFileScopeAsmDecl(const FileScopeAsmDecl *D) {
VisitDecl(D);
OF.emitString(D->getAsmString()->getBytes());
}
/// \atd
/// #define import_decl_tuple decl_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitImportDecl(const ImportDecl *D) {
VisitDecl(D);
OF.emitString(D->getImportedModule()->getFullModuleName());
}
////===----------------------------------------------------------------------===//
//// C++ Declarations
////===----------------------------------------------------------------------===//
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNamespaceDecl(const NamespaceDecl *D) {
// dumpName(D);
// if (D->isInline())
// OS << " inline";
// if (!D->isOriginalNamespace())
// dumpDeclRef(D->getOriginalNamespace(), "original");
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
// OS << ' ';
// dumpBareDeclRef(D->getNominatedNamespace());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
// dumpName(D);
// dumpDeclRef(D->getAliasedNamespace());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTypeAliasDecl(const TypeAliasDecl *D) {
// dumpName(D);
// dumpQualType(D->getUnderlyingType());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// dumpBareDecl(D->getTemplatedDecl());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitCXXRecordDecl(const CXXRecordDecl *D) {
// VisitRecordDecl(D);
// if (!D->isCompleteDefinition())
// return;
//
// for (CXXRecordDecl::base_class_const_iterator I = D->bases_begin(),
// E = D->bases_end();
// I != E; ++I) {
// ObjectScope Scope(OF);
// if (I->isVirtual())
// OS << "virtual ";
// dumpAccessSpecifier(I->getAccessSpecifier());
// dumpQualType(I->getType());
// if (I->isPackExpansion())
// OS << "...";
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitStaticAssertDecl(const StaticAssertDecl *D) {
// dumpBareStmt(D->getAssertExpr());
// dumpBareStmt(D->getMessage());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// dumpBareDecl(D->getTemplatedDecl());
// for (FunctionTemplateDecl::spec_iterator I = D->spec_begin(),
// E = D->spec_end();
// I != E; ++I) {
// FunctionTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
//
// ClassTemplateDecl::spec_iterator I = D->spec_begin();
// ClassTemplateDecl::spec_iterator E = D->spec_end();
// dumpBareDecl(D->getTemplatedDecl());
// for (; I != E; ++I) {
// ClassTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplateSpecializationDecl(
// const ClassTemplateSpecializationDecl *D) {
// VisitCXXRecordDecl(D);
// dumpTemplateArgumentList(D->getTemplateArgs());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassTemplatePartialSpecializationDecl(
// const ClassTemplatePartialSpecializationDecl *D) {
// VisitClassTemplateSpecializationDecl(D);
// dumpTemplateParameters(D->getTemplateParameters());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitClassScopeFunctionSpecializationDecl(
// const ClassScopeFunctionSpecializationDecl *D) {
// dumpDeclRef(D->getSpecialization());
// if (D->hasExplicitTemplateArgs())
// dumpTemplateArgumentListInfo(D->templateArgs());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplateDecl(const VarTemplateDecl *D) {
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
//
// VarTemplateDecl::spec_iterator I = D->spec_begin();
// VarTemplateDecl::spec_iterator E = D->spec_end();
// dumpBareDecl(D->getTemplatedDecl());
// for (; I != E; ++I) {
// VarTemplateDecl::spec_iterator Next = I;
// ++Next;
// switch (I->getTemplateSpecializationKind()) {
// case TSK_Undeclared:
// case TSK_ImplicitInstantiation:
// if (D == D->getCanonicalDecl())
// dumpBareDecl(*I);
// else
// dumpDeclRef(*I);
// break;
// case TSK_ExplicitSpecialization:
// case TSK_ExplicitInstantiationDeclaration:
// case TSK_ExplicitInstantiationDefinition:
// dumpDeclRef(*I);
// break;
// }
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplateSpecializationDecl(
// const VarTemplateSpecializationDecl *D) {
// dumpTemplateArgumentList(D->getTemplateArgs());
// VisitVarDecl(D);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitVarTemplatePartialSpecializationDecl(
// const VarTemplatePartialSpecializationDecl *D) {
// dumpTemplateParameters(D->getTemplateParameters());
// VisitVarTemplateSpecializationDecl(D);
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
// if (D->wasDeclaredWithTypename())
// OS << " typename";
// else
// OS << " class";
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// if (D->hasDefaultArgument())
// dumpQualType(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
// dumpQualType(D->getType());
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// if (D->hasDefaultArgument())
// dumpBareStmt(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitTemplateTemplateParmDecl(
// const TemplateTemplateParmDecl *D) {
// if (D->isParameterPack())
// OS << " ...";
// dumpName(D);
// dumpTemplateParameters(D->getTemplateParameters());
// if (D->hasDefaultArgument())
// dumpTemplateArgumentLoc(D->getDefaultArgument());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingDecl(const UsingDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedUsingTypenameDecl(
// const UnresolvedUsingTypenameDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
// OS << ' ';
// D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
// OS << D->getNameAsString();
// dumpQualType(D->getType());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUsingShadowDecl(const UsingShadowDecl *D) {
// OS << ' ';
// dumpBareDeclRef(D->getTargetDecl());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
// switch (D->getLanguage()) {
// case LinkageSpecDecl::lang_c: OS << " C"; break;
// case LinkageSpecDecl::lang_cxx: OS << " C++"; break;
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitAccessSpecDecl(const AccessSpecDecl *D) {
// OS << ' ';
// dumpAccessSpecifier(D->getAccess());
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitFriendDecl(const FriendDecl *D) {
// if (TypeSourceInfo *T = D->getFriendType())
// dumpQualType(T->getType());
// else
// dumpBareDecl(D->getFriendDecl());
//}
//
////===----------------------------------------------------------------------===//
//// Obj-C Declarations
////===----------------------------------------------------------------------===//
/// \atd
/// #define obj_c_ivar_decl_tuple field_decl_tuple * obj_c_ivar_decl_info
/// type obj_c_ivar_decl_info = {
/// ~is_synthesize : bool;
/// ~access_control <ocaml default="`None"> : obj_c_access_control;
/// } <ocaml field_prefix="ovdi_">
/// type obj_c_access_control = [ None | Private | Protected | Public | Package ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
VisitFieldDecl(D);
ObjectScope Scope(OF);
OF.emitFlag("is_synthesize", D->getSynthesize());
ObjCIvarDecl::AccessControl AC = D->getAccessControl();
if (AC != ObjCIvarDecl::None) {
OF.emitTag("access_control");
switch (AC) {
case ObjCIvarDecl::Private:
OF.emitSimpleVariant("Private");
break;
case ObjCIvarDecl::Protected:
OF.emitSimpleVariant("Protected");
break;
case ObjCIvarDecl::Public:
OF.emitSimpleVariant("Public");
break;
case ObjCIvarDecl::Package:
OF.emitSimpleVariant("Package");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// #define obj_c_method_decl_tuple named_decl_tuple * obj_c_method_decl_info
/// type obj_c_method_decl_info = {
/// ~is_instance_method : bool;
/// result_type : qual_type;
/// ~parameters : decl list;
/// ~is_variadic : bool;
/// ?body : stmt option;
/// } <ocaml field_prefix="omdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
VisitNamedDecl(D);
// We purposedly do not call VisitDeclContext(D).
ObjectScope Scope(OF);
OF.emitFlag("is_instance_method", D->isInstanceMethod());
OF.emitTag("result_type");
dumpBareQualType(D->getReturnType());
{
ObjCMethodDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
OF.emitFlag("is_variadic", D->isVariadic());
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
/// \atd
/// #define obj_c_category_decl_tuple obj_c_container_decl_tuple * obj_c_category_decl_info
/// type obj_c_category_decl_info = {
/// ?class_interface : decl_ref option;
/// ?implementation : decl_ref option;
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="odi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
const ObjCCategoryImplDecl *Impl = D->getImplementation();
if (Impl) {
OF.emitTag("implementation");
dumpBareDeclRef(*Impl);
}
ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_category_impl_decl_tuple obj_c_impl_decl_tuple * obj_c_category_impl_decl_info
/// type obj_c_category_impl_decl_info = {
/// ?class_interface : decl_ref option;
/// ?category_decl : decl_ref option;
/// } <ocaml field_prefix="ocidi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
ASTExporter<ATDWriter>::VisitObjCImplDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
const ObjCCategoryDecl *CD = D->getCategoryDecl();
if (CD) {
OF.emitTag("category_decl");
dumpBareDeclRef(*CD);
}
}
/// \atd
/// #define obj_c_protocol_decl_tuple obj_c_container_decl_tuple * obj_c_protocol_decl_info
/// type obj_c_protocol_decl_info = {
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="opcdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
ASTExporter<ATDWriter>::VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_interface_decl_tuple obj_c_container_decl_tuple * obj_c_interface_decl_info
/// type obj_c_interface_decl_info = {
/// ?super : decl_ref option;
/// ?implementation : decl_ref option;
/// ~protocols : decl_ref list;
/// } <ocaml field_prefix="otdi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
VisitObjCContainerDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *SC = D->getSuperClass();
if (SC) {
OF.emitTag("super");
dumpBareDeclRef(*SC);
}
const ObjCImplementationDecl *Impl = D->getImplementation();
if (Impl) {
OF.emitTag("implementation");
dumpBareDeclRef(*Impl);
}
ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
E = D->protocol_end();
if (I != E) {
OF.emitTag("protocols");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareDeclRef(**I);
}
}
}
/// \atd
/// #define obj_c_implementation_decl_tuple obj_c_impl_decl_tuple * obj_c_implementation_decl_info
/// type obj_c_implementation_decl_info = {
/// ?super : decl_ref option;
/// ?class_interface : decl_ref option;
/// ~ivar_initializers : cxx_ctor_initializer list;
/// } <ocaml field_prefix="oidi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
ASTExporter<ATDWriter>::VisitObjCImplDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *SC = D->getSuperClass();
if (SC) {
OF.emitTag("super");
dumpBareDeclRef(*SC);
}
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
ObjCImplementationDecl::init_const_iterator I = D->init_begin(),
E = D->init_end();
if (I != E) {
OF.emitTag("ivar_initializers");
ArrayScope Scope(OF);
for (; I != E; ++I) {
assert(*I);
dumpBareCXXCtorInitializer(**I);
}
}
}
/// \atd
/// #define obj_c_compatible_alias_decl_tuple named_decl_tuple * obj_c_compatible_alias_decl_info
/// type obj_c_compatible_alias_decl_info = {
/// ?class_interface : decl_ref option;
/// } <ocaml field_prefix="ocadi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D) {
VisitNamedDecl(D);
ObjectScope Scope(OF);
const ObjCInterfaceDecl *CI = D->getClassInterface();
if (CI) {
OF.emitTag("class_interface");
dumpBareDeclRef(*CI);
}
}
/// \atd
/// #define obj_c_property_decl_tuple named_decl_tuple * obj_c_property_decl_info
/// type obj_c_property_decl_info = {
/// ?class_interface : decl_ref option;
/// inherit _qual_type;
/// ~property_control <ocaml default="`None"> : obj_c_property_control;
/// ~property_attributes : property_attribute list
/// } <ocaml field_prefix="opdi_">
/// type obj_c_property_control = [ None | Required | Optional ]
/// type property_attribute = [
/// Readonly
/// | Assign
/// | Readwrite
/// | Retain
/// | Copy
/// | Nonatomic
/// | Atomic
/// | Weak
/// | Strong
/// | Unsafe_unretained
/// | Getter of decl_ref
/// | Setter of decl_ref
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
VisitNamedDecl(D);
ObjectScope Scope(OF);
dumpQualType(D->getType());
ObjCPropertyDecl::PropertyControl PC = D->getPropertyImplementation();
if (PC != ObjCPropertyDecl::None) {
OF.emitTag("property_control");
switch (PC) {
case ObjCPropertyDecl::Required: OF.emitSimpleVariant("Required"); break;
case ObjCPropertyDecl::Optional: OF.emitSimpleVariant("Optional"); break;
default:
llvm_unreachable("unknown case");
break;
}
}
ObjCPropertyDecl::PropertyAttributeKind Attrs = D->getPropertyAttributes();
if (Attrs != ObjCPropertyDecl::OBJC_PR_noattr) {
OF.emitTag("property_attributes");
ArrayScope Scope(OF);
if (Attrs & ObjCPropertyDecl::OBJC_PR_readonly)
OF.emitSimpleVariant("Readonly");
if (Attrs & ObjCPropertyDecl::OBJC_PR_assign)
OF.emitSimpleVariant("Assign");
if (Attrs & ObjCPropertyDecl::OBJC_PR_readwrite)
OF.emitSimpleVariant("Readwrite");
if (Attrs & ObjCPropertyDecl::OBJC_PR_retain)
OF.emitSimpleVariant("Retain");
if (Attrs & ObjCPropertyDecl::OBJC_PR_copy)
OF.emitSimpleVariant("Copy");
if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic)
OF.emitSimpleVariant("Nonatomic");
if (Attrs & ObjCPropertyDecl::OBJC_PR_atomic)
OF.emitSimpleVariant("Atomic");
if (Attrs & ObjCPropertyDecl::OBJC_PR_weak)
OF.emitSimpleVariant("Weak");
if (Attrs & ObjCPropertyDecl::OBJC_PR_strong)
OF.emitSimpleVariant("Strong");
if (Attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained)
OF.emitSimpleVariant("Unsafe_unretained");
if (Attrs & ObjCPropertyDecl::OBJC_PR_getter) {
VariantScope Scope(OF, "Getter");
dumpBareDeclRef(*D->getGetterMethodDecl());
}
if (Attrs & ObjCPropertyDecl::OBJC_PR_setter) {
VariantScope Scope(OF, "Setter");
dumpBareDeclRef(*D->getSetterMethodDecl());
}
}
}
/// \atd
/// #define obj_c_property_impl_decl_tuple decl_tuple * obj_c_property_impl_decl_info
/// type obj_c_property_impl_decl_info = {
/// inherit _name;
/// implementation : property_implementation;
/// ?property_decl : decl_ref option;
/// ?ivar_decl : decl_ref option;
/// } <ocaml field_prefix="opidi_">
/// type property_implementation = [ Synthesize | Dynamic ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
VisitDecl(D);
ObjectScope Scope(OF);
dumpName(D->getPropertyDecl());
OF.emitTag("implementation");
switch (D->getPropertyImplementation()) {
case ObjCPropertyImplDecl::Synthesize: OF.emitSimpleVariant("Synthesize"); break;
case ObjCPropertyImplDecl::Dynamic: OF.emitSimpleVariant("Dynamic"); break;
}
const ObjCPropertyDecl *PD = D->getPropertyDecl();
if (PD) {
OF.emitTag("property_decl");
dumpBareDeclRef(*PD);
}
const ObjCIvarDecl *ID = D->getPropertyIvarDecl();
if (ID) {
OF.emitTag("ivar_decl");
dumpBareDeclRef(*ID);
}
}
/// \atd
/// #define block_decl_tuple decl_tuple * decl_context_tuple * block_decl_info
/// type block_decl_info = {
/// ~parameters : decl list;
/// ~is_variadic : bool;
/// ~captures_cxx_this : bool;
/// ~captured_variables : block_captured_variable list;
/// ?body : stmt option;
/// } <ocaml field_prefix="bdi_">
///
/// type block_captured_variable = {
/// ~is_by_ref : bool;
/// ~is_nested : bool;
/// ?variable : decl_ref option;
/// ?copy_expr : stmt option
/// } <ocaml field_prefix="bcv_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBlockDecl(const BlockDecl *D) {
VisitDecl(D);
VisitDeclContext(D);
ObjectScope Scope(OF);
{
ObjCMethodDecl::param_const_iterator I = D->param_begin(), E = D->param_end();
if (I != E) {
OF.emitTag("parameters");
ArrayScope Scope(OF);
for (; I != E; ++I) {
dumpBareDecl(*I);
}
}
}
OF.emitFlag("is_variadic", D->isVariadic());
OF.emitFlag("captures_cxx_this", D->capturesCXXThis());
{
BlockDecl::capture_iterator I = D->capture_begin(), E = D->capture_end();
if (I != E) {
OF.emitTag("captured_variables");
ArrayScope Scope(OF);
for (; I != E; ++I) {
ObjectScope Scope(OF);
OF.emitFlag("is_by_ref", I->isByRef());
OF.emitFlag("is_nested", I->isNested());
if (I->getVariable()) {
OF.emitTag("variable");
dumpBareDeclRef(*I->getVariable());
}
if (I->hasCopyExpr()) {
OF.emitTag("copy_expr");
dumpBareStmt(I->getCopyExpr());
}
}
}
}
const Stmt *Body = D->getBody();
if (Body) {
OF.emitTag("body");
dumpBareStmt(Body);
}
}
// main variant for declarations
/// \atd
/// type decl = [
#define DECL(DERIVED, BASE) /// | DERIVED@@Decl of (@DERIVED@_decl_tuple)
#define ABSTRACT_DECL(DECL)
#include <clang/AST/DeclNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// Stmt dumping methods.
//===----------------------------------------------------------------------===//
// Default aliases for generating variant components
// The main variant is defined at the end of section.
/// \atd
#define STMT(CLASS, PARENT) /// #define @CLASS@_tuple @PARENT@_tuple
#define ABSTRACT_STMT(STMT) STMT
#include <clang/AST/StmtNodes.inc>
//
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareStmt(const Stmt *S) {
if (!S) {
// We use a fixed NullStmt node to represent null pointers
S = NullPtrStmt;
}
VariantScope Scope(OF, S->getStmtClassName());
{
TupleScope Scope(OF);
ConstStmtVisitor<ASTExporter<ATDWriter>>::Visit(S);
}
}
/// \atd
/// #define stmt_tuple stmt_info * stmt list
/// type stmt_info = {
/// pointer : pointer;
/// inherit _source_range;
/// } <ocaml field_prefix="si_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitStmt(const Stmt *S) {
{
ObjectScope Scope(OF);
OF.emitTag("pointer");
dumpBarePointer(S);
dumpSourceRange(S->getSourceRange());
}
{
ArrayScope Scope(OF);
for (Stmt::const_child_range CI = S->children(); CI; ++CI) {
dumpBareStmt(*CI);
}
}
}
/// \atd
/// #define decl_stmt_tuple stmt_tuple * decl list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclStmt(const DeclStmt *Node) {
VisitStmt(Node);
ArrayScope Scope(OF);
for (DeclStmt::const_decl_iterator I = Node->decl_begin(),
E = Node->decl_end();
I != E; ++I) {
dumpBareDecl(*I);
}
}
/// \atd
/// #define attributed_stmt_tuple stmt_tuple * attribute list
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitAttributedStmt(const AttributedStmt *Node) {
VisitStmt(Node);
ArrayScope Scope(OF);
for (ArrayRef<const Attr *>::iterator I = Node->getAttrs().begin(),
E = Node->getAttrs().end();
I != E; ++I) {
assert(*I);
dumpBareAttr(**I);
}
}
/// \atd
/// #define label_stmt_tuple stmt_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitLabelStmt(const LabelStmt *Node) {
VisitStmt(Node);
OF.emitString(Node->getName());
}
/// \atd
/// #define goto_stmt_tuple stmt_tuple * goto_stmt_info
/// type goto_stmt_info = {
/// label : string;
/// pointer : pointer
/// } <ocaml field_prefix="gsi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitGotoStmt(const GotoStmt *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
OF.emitTag("label");
OF.emitString(Node->getLabel()->getName());
OF.emitTag("pointer");
dumpBarePointer(Node->getLabel());
}
/// \atd
/// #define cxx_catch_stmt_tuple stmt_tuple * cxx_catch_stmt_info
/// type cxx_catch_stmt_info = {
/// ?variable : decl option
/// } <ocaml field_prefix="xcsi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXCatchStmt(const CXXCatchStmt *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
const VarDecl *decl = Node->getExceptionDecl();
if (decl) {
OF.emitTag("variable");
dumpBareDecl(decl);
}
}
////===----------------------------------------------------------------------===//
//// Expr dumping methods.
////===----------------------------------------------------------------------===//
//
/// \atd
/// #define expr_tuple stmt_tuple * expr_info
/// type expr_info = {
/// inherit _qual_type;
/// ~value_kind <ocaml default="`RValue"> : value_kind;
/// ~object_kind <ocaml default="`Ordinary"> : object_kind;
/// } <ocaml field_prefix="ei_">
///
/// type value_kind = [ RValue | LValue | XValue ]
/// type object_kind = [ Ordinary | BitField | ObjCProperty | ObjCSubscript | VectorComponent ]
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExpr(const Expr *Node) {
VisitStmt(Node);
ObjectScope Scope(OF);
dumpQualType(Node->getType());
ExprValueKind VK = Node->getValueKind();
if (VK != VK_RValue) {
OF.emitTag("value_kind");
switch (VK) {
case VK_LValue:
OF.emitSimpleVariant("LValue");
break;
case VK_XValue:
OF.emitSimpleVariant("XValue");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
ExprObjectKind OK = Node->getObjectKind();
if (OK != OK_Ordinary) {
OF.emitTag("object_kind");
switch (Node->getObjectKind()) {
case OK_BitField:
OF.emitSimpleVariant("BitField");
break;
case OK_ObjCProperty:
OF.emitSimpleVariant("ObjCProperty");
break;
case OK_ObjCSubscript:
OF.emitSimpleVariant("ObjCSubscript");
break;
case OK_VectorComponent:
OF.emitSimpleVariant("VectorComponent");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// type cxx_base_specifier = {
/// name : string;
/// ~virtual : bool;
/// } <ocaml field_prefix="xbs_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
ObjectScope Scope(OF);
OF.emitTag("name");
const CXXRecordDecl *RD = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
OF.emitString(RD->getName());
OF.emitFlag("virtual", Base.isVirtual());
}
/// \atd
/// type cast_kind = [
/// | Dependent
/// | BitCast
/// | LValueBitCast
/// | LValueToRValue
/// | NoOp
/// | BaseToDerived
/// | DerivedToBase
/// | UncheckedDerivedToBase
/// | Dynamic
/// | ToUnion
/// | ArrayToPointerDecay
/// | FunctionToPointerDecay
/// | NullToPointer
/// | NullToMemberPointer
/// | BaseToDerivedMemberPointer
/// | DerivedToBaseMemberPointer
/// | MemberPointerToBoolean
/// | ReinterpretMemberPointer
/// | UserDefinedConversion
/// | ConstructorConversion
/// | IntegralToPointer
/// | PointerToIntegral
/// | PointerToBoolean
/// | ToVoid
/// | VectorSplat
/// | IntegralCast
/// | IntegralToBoolean
/// | IntegralToFloating
/// | FloatingToIntegral
/// | FloatingToBoolean
/// | FloatingCast
/// | CPointerToObjCPointerCast
/// | BlockPointerToObjCPointerCast
/// | AnyPointerToBlockPointerCast
/// | ObjCObjectLValueCast
/// | FloatingRealToComplex
/// | FloatingComplexToReal
/// | FloatingComplexToBoolean
/// | FloatingComplexCast
/// | FloatingComplexToIntegralComplex
/// | IntegralRealToComplex
/// | IntegralComplexToReal
/// | IntegralComplexToBoolean
/// | IntegralComplexCast
/// | IntegralComplexToFloatingComplex
/// | ARCProduceObject
/// | ARCConsumeObject
/// | ARCReclaimReturnedObject
/// | ARCExtendBlockObject
/// | AtomicToNonAtomic
/// | NonAtomicToAtomic
/// | CopyAndAutoreleaseBlockObject
/// | BuiltinFnToFnPtr
/// | ZeroToOCLEvent
/// ]
///
/// #define cast_expr_tuple expr_tuple * cast_expr_info
/// type cast_expr_info = {
/// cast_kind : cast_kind;
/// base_path : cxx_base_specifier list;
/// } <ocaml field_prefix="cei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCastExpr(const CastExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("cast_kind");
OF.emitSimpleVariant(Node->getCastKindName());
OF.emitTag("base_path");
{
ArrayScope Scope(OF);
for (CastExpr::path_const_iterator I = Node->path_begin(),
E = Node->path_end();
I != E; ++I) {
dumpBareCXXBaseSpecifier(**I);
}
}
}
/// \atd
/// #define explicit_cast_expr_tuple cast_expr_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExplicitCastExpr(const ExplicitCastExpr *Node) {
VisitCastExpr(Node);
dumpBareQualType(Node->getTypeAsWritten());
}
/// \atd
/// #define decl_ref_expr_tuple expr_tuple * decl_ref_expr_info
/// type decl_ref_expr_info = {
/// ?decl_ref : decl_ref option;
/// ?found_decl_ref : decl_ref option
/// } <ocaml field_prefix="drti_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitDeclRefExpr(const DeclRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
const ValueDecl *D = Node->getDecl();
if (D) {
OF.emitTag("decl_ref");
dumpBareDeclRef(*D);
}
const NamedDecl *FD = Node->getFoundDecl();
if (FD && D != FD) {
OF.emitTag("found_decl_ref");
dumpBareDeclRef(*FD);
}
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node) {
// VisitExpr(Node);
// OS << " (";
// if (!Node->requiresADL())
// OS << "no ";
// OS << "ADL) = '" << Node->getName() << '\'';
//
// UnresolvedLookupExpr::decls_iterator
// I = Node->decls_begin(), E = Node->decls_end();
// if (I == E)
// OS << " empty";
// for (; I != E; ++I)
// dumpBarePointer(*I);
//}
/// \atd
/// #define obj_c_ivar_ref_expr_tuple expr_tuple * obj_c_ivar_ref_expr_info
/// type obj_c_ivar_ref_expr_info = {
/// decl_ref : decl_ref;
/// pointer : pointer;
/// ~is_free_ivar : bool
/// } <ocaml field_prefix="ovrei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("decl_ref");
dumpBareDeclRef(*Node->getDecl());
OF.emitTag("pointer");
dumpBarePointer(Node->getDecl());
OF.emitFlag("is_free_ivar", Node->isFreeIvar());
}
/// \atd
/// #define predefined_expr_tuple expr_tuple * predefined_expr_type
/// type predefined_expr_type = [
/// | Func
/// | Function
/// | FuncDName
/// | LFunction
/// | PrettyFunction
/// | PrettyFunctionNoVirtual
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitPredefinedExpr(const PredefinedExpr *Node) {
VisitExpr(Node);
switch (Node->getIdentType()) {
case PredefinedExpr::Func: OF.emitSimpleVariant("Func"); break;
case PredefinedExpr::Function: OF.emitSimpleVariant("Function"); break;
case PredefinedExpr::FuncDName: OF.emitSimpleVariant("FuncDName"); break;
case PredefinedExpr::LFunction: OF.emitSimpleVariant("LFunction"); break;
case PredefinedExpr::PrettyFunction: OF.emitSimpleVariant("PrettyFunction"); break;
case PredefinedExpr::PrettyFunctionNoVirtual: OF.emitSimpleVariant("PrettyFunctionNoVirtual"); break;
}
}
/// \atd
/// #define character_literal_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCharacterLiteral(const CharacterLiteral *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
/// \atd
/// #define integer_literal_tuple expr_tuple * integer_literal_info
/// type integer_literal_info = {
/// ~is_signed : bool;
/// bitwidth : int;
/// value : string;
/// } <ocaml field_prefix="ili_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitIntegerLiteral(const IntegerLiteral *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
bool isSigned = Node->getType()->isSignedIntegerType();
OF.emitFlag("is_signed", isSigned);
OF.emitTag("bitwidth");
OF.emitInteger(Node->getValue().getBitWidth());
OF.emitTag("value");
OF.emitString(Node->getValue().toString(10, isSigned));
}
/// \atd
/// #define floating_literal_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitFloatingLiteral(const FloatingLiteral *Node) {
VisitExpr(Node);
llvm::SmallString<20> buf;
Node->getValue().toString(buf);
OF.emitString(buf.str());
}
/// \atd
/// #define string_literal_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitStringLiteral(const StringLiteral *Str) {
VisitExpr(Str);
OF.emitString(Str->getBytes());
}
/// \atd
/// #define unary_operator_tuple expr_tuple * unary_operator_info
/// type unary_operator_info = {
/// kind : unary_operator_kind;
/// ~is_postfix : bool;
/// } <ocaml field_prefix="uoi_">
/// type unary_operator_kind = [
/// PostInc
/// | PostDec
/// | PreInc
/// | PreDec
/// | AddrOf
/// | Deref
/// | Plus
/// | Minus
/// | Not
/// | LNot
/// | Real
/// | Imag
/// | Extension
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitUnaryOperator(const UnaryOperator *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch (Node->getOpcode()) {
case UO_PostInc: OF.emitSimpleVariant("PostInc"); break;
case UO_PostDec: OF.emitSimpleVariant("PostDec"); break;
case UO_PreInc: OF.emitSimpleVariant("PreInc"); break;
case UO_PreDec: OF.emitSimpleVariant("PreDec"); break;
case UO_AddrOf: OF.emitSimpleVariant("AddrOf"); break;
case UO_Deref: OF.emitSimpleVariant("Deref"); break;
case UO_Plus: OF.emitSimpleVariant("Plus"); break;
case UO_Minus: OF.emitSimpleVariant("Minus"); break;
case UO_Not: OF.emitSimpleVariant("Not"); break;
case UO_LNot: OF.emitSimpleVariant("LNot"); break;
case UO_Real: OF.emitSimpleVariant("Real"); break;
case UO_Imag: OF.emitSimpleVariant("Imag"); break;
case UO_Extension: OF.emitSimpleVariant("Extension"); break;
}
OF.emitFlag("is_postfix", Node->isPostfix());
}
/// \atd
/// #define unary_expr_or_type_trait_expr_tuple expr_tuple * unary_expr_or_type_trait_expr_info
/// type unary_expr_or_type_trait_expr_info = {
/// kind : unary_expr_or_type_trait_kind;
/// ?qual_type : qual_type option
/// } <ocaml field_prefix="uttei_">
///
/// type unary_expr_or_type_trait_kind = [ SizeOf | AlignOf | VecStep ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitUnaryExprOrTypeTraitExpr(
const UnaryExprOrTypeTraitExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch(Node->getKind()) {
case UETT_SizeOf:
OF.emitSimpleVariant("SizeOf");
break;
case UETT_AlignOf:
OF.emitSimpleVariant("AlignOf");
break;
case UETT_VecStep:
OF.emitSimpleVariant("VecStep");
break;
}
if (Node->isArgumentType()) {
dumpQualType(Node->getArgumentType());
}
}
/// \atd
/// #define member_expr_tuple expr_tuple * member_expr_info
/// type member_expr_info = {
/// ~is_arrow : bool;
/// name : string;
/// pointer : pointer
/// } <ocaml field_prefix="mei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitMemberExpr(const MemberExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitFlag("is_arrow", Node->isArrow());
OF.emitTag("name");
OF.emitString(Node->getMemberDecl()->getNameAsString());
OF.emitTag("pointer");
dumpBarePointer(Node->getMemberDecl());
}
/// \atd
/// #define ext_vector_element_tuple expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitExtVectorElementExpr(const ExtVectorElementExpr *Node) {
VisitExpr(Node);
OF.emitString(Node->getAccessor().getNameStart());
}
/// \atd
/// #define binary_operator_tuple expr_tuple * binary_operator_info
/// type binary_operator_info = {
/// kind : binary_operator_kind
/// } <ocaml field_prefix="boi_">
///
/// type binary_operator_kind = [
/// PtrMemD |
/// PtrMemI |
/// Mul |
/// Div |
/// Rem |
/// Add |
/// Sub |
/// Shl |
/// Shr |
/// LT |
/// GT |
/// LE |
/// GE |
/// EQ |
/// NE |
/// And |
/// Xor |
/// Or |
/// LAnd |
/// LOr |
/// Assign |
/// MulAssign |
/// DivAssign |
/// RemAssign |
/// AddAssign |
/// SubAssign |
/// ShlAssign |
/// ShrAssign |
/// AndAssign |
/// XorAssign |
/// OrAssign |
/// Comma
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBinaryOperator(const BinaryOperator *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
switch (Node->getOpcode()) {
case BO_PtrMemD: OF.emitSimpleVariant("PtrMemD"); break;
case BO_PtrMemI: OF.emitSimpleVariant("PtrMemI"); break;
case BO_Mul: OF.emitSimpleVariant("Mul"); break;
case BO_Div: OF.emitSimpleVariant("Div"); break;
case BO_Rem: OF.emitSimpleVariant("Rem"); break;
case BO_Add: OF.emitSimpleVariant("Add"); break;
case BO_Sub: OF.emitSimpleVariant("Sub"); break;
case BO_Shl: OF.emitSimpleVariant("Shl"); break;
case BO_Shr: OF.emitSimpleVariant("Shr"); break;
case BO_LT: OF.emitSimpleVariant("LT"); break;
case BO_GT: OF.emitSimpleVariant("GT"); break;
case BO_LE: OF.emitSimpleVariant("LE"); break;
case BO_GE: OF.emitSimpleVariant("GE"); break;
case BO_EQ: OF.emitSimpleVariant("EQ"); break;
case BO_NE: OF.emitSimpleVariant("NE"); break;
case BO_And: OF.emitSimpleVariant("And"); break;
case BO_Xor: OF.emitSimpleVariant("Xor"); break;
case BO_Or: OF.emitSimpleVariant("Or"); break;
case BO_LAnd: OF.emitSimpleVariant("LAnd"); break;
case BO_LOr: OF.emitSimpleVariant("LOr"); break;
case BO_Assign: OF.emitSimpleVariant("Assign"); break;
case BO_MulAssign: OF.emitSimpleVariant("MulAssign"); break;
case BO_DivAssign: OF.emitSimpleVariant("DivAssign"); break;
case BO_RemAssign: OF.emitSimpleVariant("RemAssign"); break;
case BO_AddAssign: OF.emitSimpleVariant("AddAssign"); break;
case BO_SubAssign: OF.emitSimpleVariant("SubAssign"); break;
case BO_ShlAssign: OF.emitSimpleVariant("ShlAssign"); break;
case BO_ShrAssign: OF.emitSimpleVariant("ShrAssign"); break;
case BO_AndAssign: OF.emitSimpleVariant("AndAssign"); break;
case BO_XorAssign: OF.emitSimpleVariant("XorAssign"); break;
case BO_OrAssign: OF.emitSimpleVariant("OrAssign"); break;
case BO_Comma: OF.emitSimpleVariant("Comma"); break;
}
}
/// \atd
/// #define compound_assign_operator_tuple binary_operator_tuple * compound_assign_operator_info
/// type compound_assign_operator_info = {
/// lhs_type : qual_type;
/// result_type : qual_type;
/// } <ocaml field_prefix="caoi_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCompoundAssignOperator(const CompoundAssignOperator *Node) {
VisitBinaryOperator(Node);
ObjectScope Scope(OF);
OF.emitTag("lhs_type");
dumpBareQualType(Node->getComputationLHSType());
OF.emitTag("result_type");
dumpBareQualType(Node->getComputationResultType());
}
/// \atd
/// #define block_expr_tuple expr_tuple * decl
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitBlockExpr(const BlockExpr *Node) {
VisitExpr(Node);
dumpBareDecl(Node->getBlockDecl());
}
/// \atd
/// #define opaque_value_expr_tuple expr_tuple * opaque_value_expr_info
/// type opaque_value_expr_info = {
/// ?source_expr : stmt option;
/// } <ocaml field_prefix="ovei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitOpaqueValueExpr(const OpaqueValueExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
if (const Expr *Source = Node->getSourceExpr()) {
OF.emitTag("source_expr");
dumpBareStmt(Source);
}
}
// GNU extensions.
/// \atd
/// #define addr_label_expr_tuple expr_tuple * addr_label_expr_info
/// type addr_label_expr_info = {
/// label : string;
/// pointer : pointer;
/// } <ocaml field_prefix="alei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitAddrLabelExpr(const AddrLabelExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("label");
OF.emitString(Node->getLabel()->getName());
OF.emitTag("pointer");
dumpBarePointer(Node->getLabel());
}
////===----------------------------------------------------------------------===//
//// C++ Expressions
////===----------------------------------------------------------------------===//
/// \atd
/// #define cxx_named_cast_expr_tuple explicit_cast_expr_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node) {
VisitExplicitCastExpr(Node);
OF.emitString(Node->getCastName());
}
/// \atd
/// #define cxx_bool_literal_expr_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
/// \atd
/// #define cxx_construct_expr_tuple expr_tuple * cxx_construct_expr_info
/// type cxx_construct_expr_info = {
/// qual_type : qual_type;
/// ~is_elidable : bool;
/// ~requires_zero_initialization : bool;
/// } <ocaml field_prefix="xcei_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitCXXConstructExpr(const CXXConstructExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("qual_type");
CXXConstructorDecl *Ctor = Node->getConstructor();
dumpBareQualType(Ctor->getType());
OF.emitFlag("is_elidable", Node->isElidable());
OF.emitFlag("requires_zero_initialization", Node->requiresZeroInitialization());
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node) {
// VisitExpr(Node);
// OS << " ";
// dumpCXXTemporary(Node->getTemporary());
//}
//
//void
//ASTExporter<ATDWriter>::VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node) {
// VisitExpr(Node);
// if (const ValueDecl *VD = Node->getExtendingDecl()) {
// OS << " extended by ";
// dumpBareDeclRef(VD);
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::VisitExprWithCleanups(const ExprWithCleanups *Node) {
// VisitExpr(Node);
// for (unsigned i = 0, e = Node->getNumObjects(); i != e; ++i)
// dumpDeclRef(Node->getObject(i), "cleanup");
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::dumpCXXTemporary(const CXXTemporary *Temporary) {
// OS << "(CXXTemporary";
// dumpBarePointer(Temporary);
// OS << ")";
//}
//
////===----------------------------------------------------------------------===//
//// Obj-C Expressions
////===----------------------------------------------------------------------===//
/// \atd
/// #define obj_c_message_expr_tuple expr_tuple * obj_c_message_expr_info
/// type obj_c_message_expr_info = {
/// selector : string;
/// ~receiver_kind <ocaml default="`Instance"> : receiver_kind
/// } <ocaml field_prefix="omei_">
///
/// type receiver_kind = [ Instance | Class of qual_type | SuperInstance | SuperClass ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCMessageExpr(const ObjCMessageExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("selector");
OF.emitString(Node->getSelector().getAsString());
ObjCMessageExpr::ReceiverKind RK = Node->getReceiverKind();
if (RK != ObjCMessageExpr::Instance) {
OF.emitTag("receiver_kind");
switch (RK) {
case ObjCMessageExpr::Class:
{
VariantScope Scope(OF, "Class");
dumpBareQualType(Node->getClassReceiver());
}
break;
case ObjCMessageExpr::SuperInstance:
OF.emitSimpleVariant("SuperInstance");
break;
case ObjCMessageExpr::SuperClass:
OF.emitSimpleVariant("SuperClass");
break;
default:
llvm_unreachable("unknown case");
break;
}
}
}
/// \atd
/// type selector = string
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareSelector(const Selector sel) {
OF.emitString(sel.getAsString());
}
/// \atd
/// #define obj_c_boxed_expr_tuple expr_tuple * selector
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *Node) {
VisitExpr(Node);
dumpBareSelector(Node->getBoxingMethod()->getSelector());
}
/// \atd
/// #define obj_c_at_catch_stmt_tuple stmt_tuple * obj_c_message_expr_kind
/// type obj_c_message_expr_kind = [
/// | CatchParam of decl
/// | CatchAll
/// ]
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node) {
VisitStmt(Node);
if (const VarDecl *CatchParam = Node->getCatchParamDecl()) {
VariantScope Scope(OF, "CatchParam");
dumpBareDecl(CatchParam);
} else {
OF.emitSimpleVariant("CatchAll");
}
}
/// \atd
/// #define obj_c_encode_expr_tuple expr_tuple * qual_type
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *Node) {
VisitExpr(Node);
dumpBareQualType(Node->getEncodedType());
}
/// \atd
/// #define obj_c_selector_expr_tuple expr_tuple * selector
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCSelectorExpr(const ObjCSelectorExpr *Node) {
VisitExpr(Node);
dumpBareSelector(Node->getSelector());
}
/// \atd
/// #define obj_c_protocol_expr_tuple expr_tuple * decl_ref
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCProtocolExpr(const ObjCProtocolExpr *Node) {
VisitExpr(Node);
dumpBareDeclRef(*Node->getProtocol());
}
/// \atd
/// #define obj_c_property_ref_expr_tuple expr_tuple * obj_c_property_ref_expr_info
///
/// type obj_c_property_ref_expr_info = {
/// kind : property_ref_kind;
/// ~is_super_receiver : bool;
/// ~is_messaging_getter : bool;
/// ~is_messaging_setter : bool;
/// } <ocaml field_prefix="oprei_">
///
/// type property_ref_kind = [
/// | MethodRef of obj_c_method_ref_info
/// | PropertyRef of decl_ref
/// ]
///
/// type obj_c_method_ref_info = {
/// ?getter : selector option;
/// ?setter : selector option
/// } <ocaml field_prefix="mri_">
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
if (Node->isImplicitProperty()) {
VariantScope Scope(OF, "MethodRef");
{
ObjectScope Scope(OF);
if (Node->getImplicitPropertyGetter()) {
OF.emitTag("getter");
dumpBareSelector(Node->getImplicitPropertyGetter()->getSelector());
}
if (Node->getImplicitPropertySetter()) {
OF.emitTag("setter");
dumpBareSelector(Node->getImplicitPropertySetter()->getSelector());
}
}
} else {
VariantScope Scope(OF, "PropertyRef");
dumpBareDeclRef(*Node->getExplicitProperty());
}
OF.emitFlag("is_super_receiver", Node->isSuperReceiver());
OF.emitFlag("is_messaging_getter", Node->isMessagingGetter());
OF.emitFlag("is_messaging_setter", Node->isMessagingSetter());
}
/// \atd
/// #define obj_c_subscript_ref_expr_tuple expr_tuple * obj_c_subscript_ref_expr_info
///
/// type obj_c_subscript_ref_expr_info = {
/// kind : obj_c_subscript_kind;
/// ?getter : selector option;
/// ?setter : selector option
/// } <ocaml field_prefix="osrei_">
///
/// type obj_c_subscript_kind = [ ArraySubscript | DictionarySubscript ]
///
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node) {
VisitExpr(Node);
ObjectScope Scope(OF);
OF.emitTag("kind");
if (Node->isArraySubscriptRefExpr()) {
OF.emitSimpleVariant("ArraySubscript");
} else {
OF.emitSimpleVariant("DictionarySubscript");
}
if (Node->getAtIndexMethodDecl()) {
OF.emitTag("getter");
dumpBareSelector(Node->getAtIndexMethodDecl()->getSelector());
}
if (Node->setAtIndexMethodDecl()) {
OF.emitTag("setter");
dumpBareSelector(Node->setAtIndexMethodDecl()->getSelector());
}
}
/// \atd
/// #define obj_c_bool_literal_expr_tuple expr_tuple * int
template <class ATDWriter>
void ASTExporter<ATDWriter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node) {
VisitExpr(Node);
OF.emitInteger(Node->getValue());
}
// Main variant for statements
/// \atd
/// type stmt = [
#define STMT(CLASS, PARENT) /// | CLASS of (@CLASS@_tuple)
#define ABSTRACT_STMT(STMT)
#include <clang/AST/StmtNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// Comments
//===----------------------------------------------------------------------===//
template <class ATDWriter>
const char *ASTExporter<ATDWriter>::getCommandName(unsigned CommandID) {
return Traits.getCommandInfo(CommandID)->Name;
}
/// \atd
/// type _full_comment = { ?full_comment : comment option }
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpFullComment(const FullComment *C) {
if (!C)
return;
OF.emitTag("full_comment");
FC = C;
dumpBareComment(C);
FC = 0;
}
/// \atd
#define COMMENT(CLASS, PARENT) /// #define @CLASS@_tuple @PARENT@_tuple
#define ABSTRACT_COMMENT(COMMENT) COMMENT
#include <clang/AST/CommentNodes.inc>
template <class ATDWriter>
void ASTExporter<ATDWriter>::dumpBareComment(const Comment *C) {
if (!C) {
// We use a fixed NoComment node to represent null pointers
C = NullPtrComment;
}
VariantScope Scope(OF, std::string(C->getCommentKindName()));
{
TupleScope Scope(OF);
ConstCommentVisitor<ASTExporter<ATDWriter>>::visit(C);
}
}
/// \atd
/// #define comment_tuple comment_info * comment list
/// type comment_info = {
/// parent_pointer : pointer;
/// inherit _source_range;
/// } <ocaml field_prefix="ci_">
template <class ATDWriter>
void ASTExporter<ATDWriter>::visitComment(const Comment *C) {
{
ObjectScope ObjComment(OF);
OF.emitTag("parent_pointer");
dumpBarePointer(C);
dumpSourceRange(C->getSourceRange());
}
{
ArrayScope Scope(OF);
for (Comment::child_iterator I = C->child_begin(), E = C->child_end();
I != E; ++I) {
dumpBareComment(*I);
}
}
}
/// \atd
/// #define text_comment_tuple comment_tuple * string
template <class ATDWriter>
void ASTExporter<ATDWriter>::visitTextComment(const TextComment *C) {
visitComment(C);
OF.emitString(C->getText());
}
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitInlineCommandComment(const InlineCommandComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
// switch (C->getRenderKind()) {
// case InlineCommandComment::RenderNormal:
// OS << " RenderNormal";
// break;
// case InlineCommandComment::RenderBold:
// OS << " RenderBold";
// break;
// case InlineCommandComment::RenderMonospaced:
// OS << " RenderMonospaced";
// break;
// case InlineCommandComment::RenderEmphasized:
// OS << " RenderEmphasized";
// break;
// }
//
// for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
// OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
// OS << " Name=\"" << C->getTagName() << "\"";
// if (C->getNumAttrs() != 0) {
// OS << " Attrs: ";
// for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
// const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
// OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
// }
// }
// if (C->isSelfClosing())
// OS << " SelfClosing";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
// OS << " Name=\"" << C->getTagName() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitBlockCommandComment(const BlockCommandComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
// for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
// OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitParamCommandComment(const ParamCommandComment *C) {
// OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
//
// if (C->isDirectionExplicit())
// OS << " explicitly";
// else
// OS << " implicitly";
//
// if (C->hasParamName()) {
// if (C->isParamIndexValid())
// OS << " Param=\"" << C->getParamName(FC) << "\"";
// else
// OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
// }
//
// if (C->isParamIndexValid())
// OS << " ParamIndex=" << C->getParamIndex();
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitTParamCommandComment(const TParamCommandComment *C) {
// if (C->hasParamName()) {
// if (C->isPositionValid())
// OS << " Param=\"" << C->getParamName(FC) << "\"";
// else
// OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
// }
//
// if (C->isPositionValid()) {
// OS << " Position=<";
// for (unsigned i = 0, e = C->getDepth(); i != e; ++i) {
// OS << C->getIndex(i);
// if (i != e - 1)
// OS << ", ";
// }
// OS << ">";
// }
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
// OS << " Name=\"" << getCommandName(C->getCommandID()) << "\""
// " CloseName=\"" << C->getCloseName() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimBlockLineComment(
// const VerbatimBlockLineComment *C) {
// OS << " Text=\"" << C->getText() << "\"";
//}
//
//template <class ATDWriter>
//void ASTExporter<ATDWriter>::visitVerbatimLineComment(const VerbatimLineComment *C) {
// OS << " Text=\"" << C->getText() << "\"";
//}
/// \atd
/// type comment = [
#define COMMENT(CLASS, PARENT) /// | CLASS of (@CLASS@_tuple)
#define ABSTRACT_COMMENT(COMMENT)
#include <clang/AST/CommentNodes.inc>
/// ]
//===----------------------------------------------------------------------===//
// ASTExporter Plugin Main
//===----------------------------------------------------------------------===//
namespace {
template <class ATDWriter>
class ExporterASTConsumer : public ASTConsumer {
private:
std::string BasePath;
std::string DeduplicationServicePath;
raw_ostream &OS;
public:
ExporterASTConsumer(CompilerInstance &CI,
StringRef InputFile,
StringRef BasePath,
StringRef DeduplicationServicePath,
raw_ostream &OS)
: BasePath(BasePath),
DeduplicationServicePath(DeduplicationServicePath),
OS(OS)
{}
virtual void HandleTranslationUnit(ASTContext &Context) {
TranslationUnitDecl *D = Context.getTranslationUnitDecl();
FileUtils::DeduplicationService Dedup(DeduplicationServicePath, BasePath, Context.getSourceManager());
ASTExporter<ATDWriter> P(OS, Context, BasePath, DeduplicationServicePath != "" ? &Dedup : nullptr);
P.dumpBareDecl(D);
}
};
}
typedef SimplePluginASTAction<ExporterASTConsumer<JsonWriter>> JsonExporterASTAction;
typedef SimplePluginASTAction<ExporterASTConsumer<YojsonWriter>> YojsonExporterASTAction;
static FrontendPluginRegistry::Add<JsonExporterASTAction>
X("JsonASTExporter", "Export the AST of source files into ATD-specified Json data");
static FrontendPluginRegistry::Add<YojsonExporterASTAction>
Y("YojsonASTExporter", "Export the AST of source files into ATD-specified Yojson data");
|
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mirtk/FreeFormTransformation.h"
#include "mirtk/Math.h"
#include "mirtk/Memory.h"
#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
namespace mirtk {
// =============================================================================
// Construction/Destruction
// =============================================================================
// Auxiliary macro used to initialize references to often needed
// control point image attributes in initialization list of constructor
#define _References() \
_attr (_CPImage.Attributes()), \
_x (_CPImage.Attributes()._x), \
_y (_CPImage.Attributes()._y), \
_z (_CPImage.Attributes()._z), \
_t (_CPImage.Attributes()._t), \
_dx (_CPImage.Attributes()._dx), \
_dy (_CPImage.Attributes()._dy), \
_dz (_CPImage.Attributes()._dz), \
_dt (_CPImage.Attributes()._dt), \
_matW2L(_CPImage.GetWorldToImageMatrix()), \
_matL2W(_CPImage.GetImageToWorldMatrix())
// -----------------------------------------------------------------------------
FreeFormTransformation
::FreeFormTransformation(CPInterpolator &func, CPInterpolator *func2D)
:
_ExtrapolationMode(Extrapolation_Const),
_SpeedupFactor(1.0),
_CPValue (NULL),
_CPFunc (&func),
_CPFunc2D(func2D),
_CPStatus(NULL),
_References()
{
}
// -----------------------------------------------------------------------------
FreeFormTransformation
::FreeFormTransformation(const FreeFormTransformation &ffd,
CPInterpolator &func, CPInterpolator *func2D)
:
Transformation(ffd),
_ExtrapolationMode(ffd._ExtrapolationMode),
_SpeedupFactor(ffd._SpeedupFactor),
_CPValue (NULL),
_CPFunc (&func),
_CPFunc2D(func2D),
_CPStatus(NULL),
_References()
{
if (_NumberOfDOFs > 0) {
_CPImage.Initialize(ffd.Attributes(), reinterpret_cast<CPValue *>(_Param));
Allocate(_CPStatus, _x, _y, _z, _t, reinterpret_cast<CPStatus *>(_Status));
}
}
// -----------------------------------------------------------------------------
FreeFormTransformation::~FreeFormTransformation()
{
Deallocate(_CPStatus, _Status);
Delete(_CPValue);
}
#undef _References // only used/needed for constructors
// -----------------------------------------------------------------------------
ImageAttributes
FreeFormTransformation
::DefaultAttributes(const ImageAttributes &attr,
double dx, double dy, double dz, double dt)
{
// Set spacing equal to voxel size if not specified (i.e., negative)
if (dx < .0) dx = attr._dx;
if (dy < .0) dy = attr._dy;
if (dz < .0) dz = attr._dz;
if (dt < .0) dt = attr._dt;
// Orthogonalize image grid if necessary
const ImageAttributes grid = OrthogonalFieldOfView(attr);
// Set lattice attributes to image attributes
ImageAttributes lattice = grid;
// Adjust lattice dimensions
lattice._x = ((dx > .0 && grid._x > 1) ? iround((grid._x - 1) * grid._dx / dx) + 1 : 1);
lattice._y = ((dy > .0 && grid._y > 1) ? iround((grid._y - 1) * grid._dy / dy) + 1 : 1);
lattice._z = ((dz > .0 && grid._z > 1) ? iround((grid._z - 1) * grid._dz / dz) + 1 : 1);
lattice._t = ((dt > .0 && grid._t > 1) ? iround((grid._t - 1) * grid._dt / dt) + 1 : 1);
// Update lattice spacing
lattice._dx = ((lattice._x > 1) ? dx : .0);
lattice._dy = ((lattice._y > 1) ? dy : .0);
lattice._dz = ((lattice._z > 1) ? dz : .0);
lattice._dt = ((lattice._t > 1) ? dt : .0);
return lattice;
}
// -----------------------------------------------------------------------------
ImageAttributes
FreeFormTransformation
::DefaultAttributes(double x1, double y1, double z1, double t1,
double x2, double y2, double z2, double t2,
double dx, double dy, double dz, double dt,
const double *xaxis,
const double *yaxis,
const double *zaxis)
{
ImageAttributes attr;
// Lattice origin
attr._xorigin = (x2 + x1) / 2.0;
attr._yorigin = (y2 + y1) / 2.0;
attr._zorigin = (z2 + z1) / 2.0;
attr._torigin = t1;
// Lattice orientation
memcpy(attr._xaxis, xaxis, 3 * sizeof(double));
memcpy(attr._yaxis, yaxis, 3 * sizeof(double));
memcpy(attr._zaxis, zaxis, 3 * sizeof(double));
// FOV in lattice orientation
double a, b, c;
a = x1 * xaxis[0] + y1 * xaxis[1] + z1 * xaxis[2];
b = x1 * yaxis[0] + y1 * yaxis[1] + z1 * yaxis[2];
c = x1 * zaxis[0] + y1 * zaxis[1] + z1 * zaxis[2];
x1 = a, y1 = b, z1 = c;
a = x2 * xaxis[0] + y2 * xaxis[1] + z2 * xaxis[2];
b = x2 * yaxis[0] + y2 * yaxis[1] + z2 * yaxis[2];
c = x2 * zaxis[0] + y2 * zaxis[1] + z2 * zaxis[2];
x2 = a, y2 = b, z2 = c;
// Lattice dimensions
attr._x = ((dx > .0) ? iround((x2 - x1) / dx) + 1 : 1);
attr._y = ((dy > .0) ? iround((y2 - y1) / dy) + 1 : 1);
attr._z = ((dz > .0) ? iround((z2 - z1) / dz) + 1 : 1);
attr._t = ((dt > .0) ? iround((t2 - t1) / dt) + 1 : 1);
// Lattice spacing
attr._dx = ((attr._x > 1) ? dx : .0);
attr._dy = ((attr._y > 1) ? dy : .0);
attr._dz = ((attr._z > 1) ? dz : .0);
attr._dt = ((attr._t > 1) ? dt : .0);
return attr;
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeInterpolator()
{
// Attention: Returns NULL for _ExtrapolationMode == Extrapolation_None!
Delete(_CPValue);
_CPValue = CPExtrapolator::New(_ExtrapolationMode, &_CPImage);
_CPFunc->Input(&_CPImage);
_CPFunc->Extrapolator(_CPValue);
_CPFunc->Initialize(true); // also initializes _CPValue
if (_CPFunc2D) {
_CPFunc2D->Input(&_CPImage);
_CPFunc2D->Extrapolator(_CPValue);
_CPFunc2D->Initialize(true);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeCPs(const ImageAttributes &attr, bool dofs)
{
if (attr._x > 1000 || attr._y > 1000 || attr._z > 1000) {
// Otherwise we may not only run out of memory, but also encounter an
// integer overflow when computing the number of control points...
cerr << "FreeFormTransformation::InitializeCPs: Number of control points may not exceed 1000 in each dimension!" << endl;
exit(1);
}
Deallocate(_CPStatus, _Status);
const int ncps = attr.NumberOfPoints();
if (ncps > 0) {
// If NULL, allocate memory for control points which differs from
// the memory referenced by _Param and _Status of the base class
CPValue *param = NULL;
CPStatus *status = NULL;
// If control points are directly the parameters of the transformation...
if (dofs) {
// Assert size of types
if (sizeof(CPValue) != 3 * sizeof(DOFValue)) {
cerr << "FreeFormTransformation::InitializeCPs: Assertion \"sizeof(CPValue) == 3 * sizeof(DOFValue)\" failed!" << endl;
cerr << " Make sure that the vector type used fulfills this assertion such that FFDs can wrap the linear" << endl;
cerr << " memory used to store the transformation parameters in an image instance with 3D vector voxel type." << endl;
exit(1);
}
// ...allocate memory for parameters and their respective status
InitializeDOFs(3 * ncps);
// ...and reinterpret this memory as 3D(+t) images
param = reinterpret_cast<CPValue *>(_Param);
status = reinterpret_cast<CPStatus *>(_Status);
}
// Allocate 4D array for convenient access to parameters of each control point
_CPImage.Initialize(attr, param);
Allocate(_CPStatus, attr._x, attr._y, attr._z, attr._t, status);
InitializeInterpolator();
InitializeStatus();
} else {
Delete(_CPValue);
_CPImage.Clear();
InitializeDOFs(0);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeCPs(const FreeFormTransformation &ffd, bool dofs)
{
if (ffd.NumberOfCPs() > 0) {
// If NULL, allocate memory for control points which differs from
// the memory referenced by _Param and _Status of the base class
CPValue *param = NULL;
CPStatus *status = NULL;
// If control points are directly the parameters of the transformation...
if (dofs) {
// ...copy transformation parameters and their respective status
InitializeDOFs(ffd);
// ...and reinterpret this memory as 3D(+t) images
param = reinterpret_cast<CPValue *>(_Param);
status = reinterpret_cast<CPStatus *>(_Status);
}
// Allocate 4D array for convenient access to parameters of each control point
_CPImage.Initialize(ffd.Attributes(), param);
Allocate(_CPStatus, _x, _y, _z, _t, status);
InitializeInterpolator();
InitializeStatus();
} else {
Delete(_CPValue);
_CPImage.Clear();
Deallocate(_CPStatus, _Status);
InitializeDOFs(0);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeStatus()
{
// Set status of unused control point dimensions to Passive
// TODO: Consider removing this commented code or uncomment it again once
// the control point coefficients are in lattice units/orientation.
// A 2D FFD in a plane not parallel to the xy plane has non-zero
// (i.e., active) z coefficients in world space!
// const CPStatus status(((_x > 1) ? Active : Passive),
// ((_y > 1) ? Active : Passive),
// ((_z > 1) ? Active : Passive));
const CPStatus status = Active;
for (int cp = 0; cp < this->NumberOfCPs(); ++cp) PutStatus(cp, status);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const ImageAttributes &attr)
{
InitializeCPs(attr);
this->Changed(true);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const ImageAttributes &attr,
double dx, double dy, double dz, double dt)
{
this->Initialize(DefaultAttributes(attr, dx, dy, dz, dt));
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const CPImage &image, bool displacement)
{
// Initialize free-form transformation
this->Initialize(image.Attributes());
// Copy control point coefficients
_CPImage.CopyFrom(image);
// Convert control point deformation to displacement
if (!displacement) {
double x, y, z;
CPValue *data = _CPImage.Data();
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
data->_x -= x;
data->_y -= y;
data->_z -= z;
++data;
}
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation
::Initialize(const GenericImage<double> &image, bool displacement)
{
if (image.T() < 2 || image.T() > 3) {
cerr << "FreeFormTransformation::Initialize:"
" Input image must be 2D/3D vector field with _t == 2 or 3)" << endl;
exit(1);
}
// Initialize control points
ImageAttributes attr = image.Attributes();
attr._t = 1;
attr._dt = .0;
this->Initialize(attr);
// Copy vector field
CPValue *data = _CPImage.Data();
for (int k = 0; k < image.GetZ(); ++k)
for (int j = 0; j < image.GetY(); ++j)
for (int i = 0; i < image.GetX(); ++i) {
data->_x = image(i, j, k, 0);
data->_y = image(i, j, k, 1);
if (image.GetT() >= 3) data->_z = image(i, j, k, 2);
else data->_z = .0;
++data;
}
// Convert control point deformation to displacement
if (!displacement) {
double x, y, z;
CPValue *data = _CPImage.Data();
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
data->_x -= x;
data->_y -= y;
data->_z -= z;
++data;
}
}
}
// =============================================================================
// Parameters (non-DoFs)
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::ExtrapolationMode(enum ExtrapolationMode mode)
{
// Set extrapolation mode
_ExtrapolationMode = mode;
// Update control point function, if _CPValue == NULL the FFD is uninitialized yet
if (_CPValue && _CPValue->ExtrapolationMode() != _ExtrapolationMode) {
Delete(_CPValue);
_CPValue = CPExtrapolator::New(_ExtrapolationMode, &_CPImage);
if (_CPValue) {
_CPValue->Input(&_CPImage);
_CPValue->Initialize();
}
_CPFunc->Extrapolator(_CPValue);
if (_CPFunc2D) _CPFunc2D->Extrapolator(_CPValue);
// Note: No need to call _CPFunc(2D)->Initialize() again
}
}
// -----------------------------------------------------------------------------
bool FreeFormTransformation::Set(const char *name, const char *value)
{
// Extrapolation mode
if (strcmp(name, "Transformation extrapolation") == 0) {
enum ExtrapolationMode mode;
if (!FromString(value, mode)) return false;
this->ExtrapolationMode(mode);
this->Changed(true);
return true;
}
// Speedup factor for gradient computation
if (strcmp(name, "Speedup factor") == 0) {
double d;
if (!FromString(value, d) || d < 1.0) return false;
_SpeedupFactor = d;
this->Changed(true);
return true;
}
// Control point spacing
if (strncmp(name, "Control point spacing", 21) == 0) {
double dx, dy, dz, dt, ds;
if (!FromString(value, ds) || ds <= .0) return false;
if (strstr(name, "[m]") != NULL) ds *= 1.0e+3;
else if (strstr(name, "[mu]") != NULL) ds *= 1.0e-3;
_CPImage.GetPixelSize(dx, dy, dz, dt);
if (strncmp(name + 21, " in ", 4) == 0) {
if (name[25] == 'X') dx = ds;
else if (name[25] == 'Y') dy = ds;
else if (name[25] == 'Z') dz = ds;
else if (name[25] == 'T') dt = ds;
} else {
dx = dy = dz = dt = ds;
}
if (_x == 1) dx = .0;
if (_y == 1) dy = .0;
if (_z == 1) dz = .0;
if (_t == 1) dt = .0;
_CPImage.PutPixelSize(dx, dy, dz, dt);
this->Changed(true);
return true;
}
if (strcmp(name, "Control point xyz units") == 0) {
double s;
if (strcmp(value, "Meter") == 0 || strcmp(value, "m") == 0) s = 1.0e+3;
else if (strcmp(value, "Millimeter") == 0 || strcmp(value, "mm") == 0) s = 1.0;
else if (strcmp(value, "Micrometer") == 0 || strcmp(value, "mu") == 0) s = 1.0e-3;
else return false;
if (s != 1.0) {
double ox, oy, oz, dx, dy, dz;
_CPImage.GetOrigin (ox, oy, oz);
_CPImage.PutOrigin (ox * s, oy * s, oz * s);
_CPImage.GetPixelSize(dx, dy, dz);
_CPImage.PutPixelSize(dx * s, dy * s, dz * s);
_CPImage *= s;
}
this->Changed(true);
return true;
}
return Transformation::Set(name, value);
}
// -----------------------------------------------------------------------------
ParameterList FreeFormTransformation::Parameter() const
{
ParameterList params;
Insert(params, "Transformation extrapolation", ToString(_ExtrapolationMode));
Insert(params, "Speedup factor", ToString(_SpeedupFactor));
return params;
}
// =============================================================================
// Approximation/Interpolation
// =============================================================================
// -----------------------------------------------------------------------------
ImageAttributes FreeFormTransformation
::ApproximationDomain(const ImageAttributes &domain, const Transformation *)
{
return domain;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::EvaluateRMSError(const Transformation *dof) const
{
return EvaluateRMSError(_attr, dof);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::Approximate(const Transformation *t, int niter, double max_error)
{
return this->Approximate(_attr, t, niter, max_error);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const ImageAttributes &domain, double *dx, double *dy, double *dz,
int niter, double max_error)
{
const int no = domain.NumberOfPoints();
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Compute world coordinates of lattice points
double *x = Allocate<double>(no);
double *y = Allocate<double>(no);
double *z = Allocate<double>(no);
double *t = Allocate<double>(no);
domain.LatticeToWorld(x, y, z, t);
// Copy original displacements
double *tx = CAllocate<double>(no);
double *ty = CAllocate<double>(no);
double *tz = CAllocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
if (this->RequiresCachingOfDisplacements()) {
error = EvaluateRMSError(domain, dx, dy, dz);
} else {
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
if (this->RequiresCachingOfDisplacements()) {
error = EvaluateRMSError(domain, dx, dy, dz);
} else {
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
Deallocate(x);
Deallocate(y);
Deallocate(z);
Deallocate(t);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const double *x, const double *y, const double *z,
double *dx, double *dy, double *dz, int no,
int niter, double max_error)
{
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Compute (fixed) time coordinates
const double t0 = .0;
double *t = CAllocate<double>(no, &t0);
// Copy original displacements
double *tx = Allocate<double>(no);
double *ty = Allocate<double>(no);
double *tz = Allocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
error = EvaluateRMSError(x, y, z, t0, dx, dy, dz, no);
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
error = EvaluateRMSError(x, y, z, t0, dx, dy, dz, no);
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
Deallocate(t);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const double *x, const double *y, const double *z, const double *t,
double *dx, double *dy, double *dz, int no,
int niter, double max_error)
{
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Copy original displacements
double *tx = Allocate<double>(no);
double *ty = Allocate<double>(no);
double *tz = Allocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::ApproximateAsNew(const Transformation *t, int niter, double max_error)
{
return this->ApproximateAsNew(_attr, t, niter, max_error);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::ApproximateAsNew(const ImageAttributes &domain, double *dx, double *dy, double *dz, int niter, double max_error)
{
bool ignore_time = (AreEqual(domain._dt, 0.) || domain._t == 1) && (AreEqual(_dt, 0.) || _t == 1);
if ((!ignore_time && domain == _attr) || (ignore_time && domain.EqualInSpace(_attr))) {
this->Interpolate(dx, dy, dz);
return .0; // No approximation error at lattice/control points
}
return Transformation::ApproximateAsNew(domain, dx, dy, dz, niter, max_error);
}
// =============================================================================
// Lattice
// =============================================================================
// -----------------------------------------------------------------------------
bool FreeFormTransformation::CropPadPassiveCPs(int margin, bool reset)
{
return this->CropPadPassiveCPs(margin, margin, margin, margin, reset);
}
// -----------------------------------------------------------------------------
bool FreeFormTransformation::CropPadPassiveCPs(int mx, int my, int mz, int mt, bool reset)
{
ImageAttributes attr = _attr;
// Determine lower bound along x axis: i1
int i1 = _x;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
if (IsActive(i, j, k, l)) {
if (i < i1) i1 = i;
break;
}
}
// Determine upper bound along x axis: i2
int i2 = -1;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = _x - 1; i >= i1; --i) {
if (IsActive(i, j, k, l)) {
if (i > i2) i2 = i;
break;
}
}
// Determine lower bound along y axis: j1
int j1 = _y;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int i = i1; i <= i2; ++i)
for (int j = 0; j < _y; ++j) {
if (IsActive(i, j, k, l)) {
if (j < j1) j1 = j;
break;
}
}
// Determine upper bound along y axis: j2
int j2 = -1;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int i = i1; i <= i2; ++i)
for (int j = _y - 1; j >= j1; --j) {
if (IsActive(i, j, k, l)) {
if (j > j2) j2 = j;
break;
}
}
// Determine lower bound along z axis: k1
int k1 = _z;
for (int l = 0; l < _t; ++l)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int k = 0; k < _z; ++k) {
if (IsActive(i, j, k, l)) {
if (k < k1) k1 = k;
break;
}
}
// Determine upper bound along z axis: k2
int k2 = -1;
for (int l = 0; l < _t; ++l)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int k = _z - 1; k >= k1; --k) {
if (IsActive(i, j, k, l)) {
if (k > k2) k2 = k;
break;
}
}
// Determine lower bound along t axis: l1
int l1 = _t;
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int l = 0; l < _t; ++l) {
if (IsActive(i, j, k, l)) {
if (l < l1) l1 = l;
break;
}
}
// Determine upper bound along t axis: l2
int l2 = -1;
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int l = _t - 1; l >= l1; --l) {
if (IsActive(i, j, k, l)) {
if (l > l2) l2 = l;
break;
}
}
// Do nothing if all control points are passive, but report it
if (i1 > i2 || j1 > j2 || k1 > k2 || l1 > l2) return false;
// Convert upper index bounds to margin widths
i2 = (_x - 1) - i2;
j2 = (_y - 1) - j2;
k2 = (_z - 1) - k2;
l2 = (_t - 1) - l2;
// Leave a margin of passive control points with specified width
// Note: Negative value gives the number of control points to add.
if (_x > 1) i1 -= mx, i2 -= mx;
if (_y > 1) j1 -= my, j2 -= my;
if (_z > 1) k1 -= mz, k2 -= mz;
if (_t > 1) l1 -= mt, l2 -= mt;
// Do nothing, if nothing to be done
if (i1 == 0 && i2 == 0 && j1 == 0 && j2 == 0 &&
k1 == 0 && k2 == 0 && l1 == 0 && l2 == 0) return true;
// Adjust control point lattice
attr._x -= i1 + i2;
attr._y -= j1 + j2;
attr._z -= k1 + k2;
attr._t -= l1 + l2;
attr._xorigin = 0.5 * ((_x - 1) + (i1 - i2));
attr._yorigin = 0.5 * ((_y - 1) + (j1 - j2));
attr._zorigin = 0.5 * ((_z - 1) + (k1 - k2));
this->LatticeToWorld(attr._xorigin, attr._yorigin, attr._zorigin);
attr._torigin = this->LatticeToTime(l1);
// Convert upper margin widths to index bounds
i2 = (_x - 1) - i2;
j2 = (_y - 1) - j2;
k2 = (_z - 1) - k2;
l2 = (_t - 1) - l2;
// Copy remaining control points and pad lattice where needed
const int ncps = attr.NumberOfPoints();
CPValue *param = Allocate<CPValue >(ncps);
CPStatus *status = Allocate<CPStatus>(ncps);
CPValue *param_iter = param;
CPStatus *status_iter = status;
for (int l = l1; l <= l2; ++l)
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i, ++param_iter, ++status_iter) {
if (0 <= i && i < _x &&
0 <= j && j < _y &&
0 <= k && k < _z &&
0 <= l && l < _t) {
(*status_iter) = _CPStatus[l][k][j][i];
(*param_iter) = _CPImage(i, j, k, l);
} else {
// Padded control point to extend margin
(*status_iter) = CPStatus(Passive);
(*param_iter) = CPValue (.0);
}
}
// Initialize new control point lattice
this->Initialize(attr);
param_iter = param;
status_iter = status;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i, ++param_iter, ++status_iter) {
_CPStatus[l][k][j][i] = (*status_iter);
if (// Copy all control point values by default
!reset ||
// Always if control point status is not passive...
(status_iter->_x != Passive) ||
(status_iter->_y != Passive) ||
(status_iter->_z != Passive) ||
// ...or control point is not within the boundary margin
i >= mx || i < _x - mx ||
j >= my || j < _y - my ||
k >= mz || k < _z - mz ||
l >= mt || l < _t - mt) {
_CPImage(i, j, k, l) = (*param_iter);
}
}
// Free temporary allocated memory
Deallocate(param);
Deallocate(status);
return true;
}
// =============================================================================
// Bounding box
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double x1, double y1, double z1,
double x2, double y2, double z2)
{
const ImageAttributes &attr = Attributes();
double a, b, c;
// Update lattice origin
_CPImage.PutOrigin((x2 + x1) / 2.0, (y2 + y1) / 2.0, (z2 + z1) / 2.0);
// FOV in lattice orientation
a = x1 * attr._xaxis[0] + y1 * attr._xaxis[1] + z1 * attr._xaxis[2];
b = x1 * attr._yaxis[0] + y1 * attr._yaxis[1] + z1 * attr._yaxis[2];
c = x1 * attr._zaxis[0] + y1 * attr._zaxis[1] + z1 * attr._zaxis[2];
x1 = a, y1 = b, z1 = c;
a = x2 * attr._xaxis[0] + y2 * attr._xaxis[1] + z2 * attr._xaxis[2];
b = x2 * attr._yaxis[0] + y2 * attr._yaxis[1] + z2 * attr._yaxis[2];
c = x2 * attr._zaxis[0] + y2 * attr._zaxis[1] + z2 * attr._zaxis[2];
x2 = a, y2 = b, z2 = c;
// Update lattice spacing
_CPImage.PutPixelSize(((x2 > x1) ? ((x2 - x1) / (attr._x - 1)) : 1),
((y2 > y1) ? ((y2 - y1) / (attr._y - 1)) : 1),
((z2 > z1) ? ((z2 - z1) / (attr._z - 1)) : 1));
this->Changed(true);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(const Point &p1, const Point &p2)
{
PutBoundingBox(p1._x, p1._y, p1._z, p2._x, p2._y, p2._z);
}
// ---------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double t1, double t2)
{
_CPImage.PutTOrigin((t2 + t1) / 2.0);
_CPImage.PutTSize ((t2 > t2) ? ((t2 - t1) / (_t - 1)) : 1);
this->Changed(true);
}
// ---------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double x1, double y1, double z1, double t1,
double x2, double y2, double z2, double t2)
{
PutBoundingBox(x1, y1, z1, x2, y2, z2);
PutBoundingBox(t1, t2);
}
// =============================================================================
// Derivatives
// =============================================================================
// -----------------------------------------------------------------------------
/// (Multi-threaded) body of FreeFormTransformation::ParametricGradient
///
/// This default implementation uses the FreeFormTransformation::JacobianDOFs
/// overload which computes the derivatives of the transformation w.r.t. all
/// transformation parameters at once for a given spatial location (target voxel).
/// It provides better performance in particular for transformations which are
/// parameterized by non-stationary velocity fields (3D+t) in which case the
/// derivatives along each temporal trajectory are computed at once and therefore
/// this trajectory does not have to be re-computed for each and every control
/// point. For classic FFDs, which are parameterized by displacements, less
/// general but more efficient implementations of the ParametricGradient function
/// are provided by the FreeFormTransformation3D and
/// FreeFormTransformation4D subclasses, which therefore override this
/// FreeFormTransformation::ParametricGradient implementation. If a subclass
/// of either of these subclasses is parameterized by velocities, it must therefore
/// override the ParametericGradient function again, for example as follows,
/// unless a more specialized gradient computation is provided by this subclass.
///
/// \code
/// void BSplineFreeFormTransformationTD::ParametricGradient(...)
/// {
/// FreeFormTransformation::ParametricGradient(...);
/// }
/// \endcode
class FreeFormTransformationParametricGradientBody
{
public:
const FreeFormTransformation *_FFD;
const GenericImage<double> *_Input;
const WorldCoordsImage *_WorldCoords;
double *_Output;
double _Weight;
double _t; ///< Time corrresponding to input gradient image (in ms)
double _t0; ///< Second time argument for velocity-based transformations
private:
int _X; ///< Number of voxels along x axis
int _Y; ///< Number of voxels along y axis
public:
// ---------------------------------------------------------------------------
/// Default constructor
FreeFormTransformationParametricGradientBody()
:
_FFD (NULL),
_Input (NULL),
_WorldCoords(NULL),
_Output (NULL),
_Weight ( 1.0),
_t ( 0.0),
_t0 (-1.0),
_X (0),
_Y (0)
{}
// ---------------------------------------------------------------------------
/// Split constructor
FreeFormTransformationParametricGradientBody(const FreeFormTransformationParametricGradientBody &other, split)
:
_FFD (other._FFD),
_Input (other._Input),
_WorldCoords(other._WorldCoords),
_Output (NULL),
_Weight (other._Weight),
_t (other._t),
_t0 (other._t0),
_X (other._X),
_Y (other._Y)
{
const int ndofs = _FFD->NumberOfDOFs();
_Output = new double[ndofs];
memset(_Output, 0, ndofs * sizeof(double));
}
// ---------------------------------------------------------------------------
/// Destructor
~FreeFormTransformationParametricGradientBody() {}
// ---------------------------------------------------------------------------
/// Join results of right-hand body with this body
void join(FreeFormTransformationParametricGradientBody &rhs)
{
const int ndofs = _FFD->NumberOfDOFs();
for (int dof = 0; dof < ndofs; dof++) _Output[dof] += rhs._Output[dof];
delete[] rhs._Output;
rhs._Output = NULL;
}
// ---------------------------------------------------------------------------
/// Calculates the gradient of the similarity term w.r.t. the transformation
/// parameters for each voxel in the specified image region
void operator ()(const blocked_range3d<int> &re)
{
const int i1 = re.cols ().begin();
const int j1 = re.rows ().begin();
const int k1 = re.pages().begin();
const int i2 = re.cols ().end();
const int j2 = re.rows ().end();
const int k2 = re.pages().end();
TransformationJacobian jac;
TransformationJacobian::ConstColumnIterator it;
//s1=1
const int s2 = _X - (i2 - i1);
const int s3 = (_Y - (j2 - j1)) * _X;
// Non-parametric/voxelwise gradient
const double *gx = _Input->Data(i1, j1, k1, 0);
const double *gy = _Input->Data(i1, j1, k1, 1);
const double *gz = _Input->Data(i1, j1, k1, 2);
// With (transformed) pre-computed world coordinates
if (_WorldCoords) {
const double *wx = _WorldCoords->Data(i1, j1, k1, 0);
const double *wy = _WorldCoords->Data(i1, j1, k1, 1);
const double *wz = _WorldCoords->Data(i1, j1, k1, 2);
for (int k = k1; k < k2; ++k, wx += s3, wy += s3, wz += s3, gx += s3, gy += s3, gz += s3)
for (int j = j1; j < j2; ++j, wx += s2, wy += s2, wz += s2, gx += s2, gy += s2, gz += s2)
for (int i = i1; i < i2; ++i, wx += 1, wy += 1, wz += 1, gx += 1, gy += 1, gz += 1) {
if (*gx || *gy || *gz) {
// Calculate derivatives of transformation w.r.t. the parameters
_FFD->JacobianDOFs(jac, *wx, *wy, *wz, _t, _t0);
// Apply chain rule to obtain similarity gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * (*gx) +
it->second._y * (*gy) +
it->second._z * (*gz));
}
}
}
// Without pre-computed world coordinates
} else {
double x, y, z;
for (int k = k1; k < k2; ++k, gx += s3, gy += s3, gz += s3)
for (int j = j1; j < j2; ++j, gx += s2, gy += s2, gz += s2)
for (int i = i1; i < i2; ++i, gx += 1, gy += 1, gz += 1) {
if (*gx || *gy || *gz) {
// Convert voxel to world coordinates
x = i, y = j, z = k;
_Input->ImageToWorld(x, y, z);
// Calculate derivatives of transformation w.r.t. the parameters
_FFD->JacobianDOFs(jac, x, y, z, _t, _t0);
// Apply chain rule to obtain similarity gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * (*gx) +
it->second._y * (*gy) +
it->second._z * (*gz));
}
}
}
}
}
// ---------------------------------------------------------------------------
void operator ()()
{
// Initialize members to often accessed data
_X = _Input->GetX();
_Y = _Input->GetY();
const int _Z = _Input->GetZ();
// Check input
if (_WorldCoords && (_WorldCoords->X() != _X ||
_WorldCoords->Y() != _Y ||
_WorldCoords->Z() != _Z ||
_WorldCoords->T() != 3)) {
cerr << "FreeFormTransformation::ParametricGradient: Invalid world coordinates map" << endl;
exit(1);
}
if (_Input->GetXSize() > _FFD->GetXSpacing() ||
_Input->GetYSize() > _FFD->GetYSpacing() ||
(_FFD->Z() > 1 && _Input->GetZSize() > _FFD->GetZSpacing())) {
// FIXME: In this case, the non-parametric input gradient should be
// resampled using linear interpolation to obtain a value at
// each control point.
cerr << "Warning: FFD spacing smaller than image resolution!" << endl;
cerr << " This may lead to artifacts in the transformation because" << endl;
cerr << " not all control points are within the vicinity of a voxel center." << endl;
}
// Calculate parametric gradient
blocked_range3d<int> voxels(0, _Z, 0, _Y, 0, _X);
parallel_reduce(voxels, *this);
}
}; // FreeFormTransformationParametricGradientBody
// -----------------------------------------------------------------------------
class FreeFormTransformationPointWiseParametricGradientBody
{
public:
const FreeFormTransformation *_FFD;
const PointSet *_PointSet;
const Vector3D<double> *_Input;
double *_Output;
double _Weight;
double _t; ///< Time corrresponding to input gradient image (in ms)
double _t0; ///< Second time argument for velocity-based transformations
// ---------------------------------------------------------------------------
/// Default constructor
FreeFormTransformationPointWiseParametricGradientBody()
:
_FFD (NULL),
_PointSet(NULL),
_Input (NULL),
_Output (NULL),
_Weight ( 1.0),
_t ( 0.0),
_t0 (-1.0)
{}
// ---------------------------------------------------------------------------
/// Split constructor
FreeFormTransformationPointWiseParametricGradientBody(const FreeFormTransformationPointWiseParametricGradientBody &other, split)
:
_FFD (other._FFD),
_PointSet(other._PointSet),
_Input (other._Input),
_Output (NULL),
_Weight (other._Weight),
_t (other._t),
_t0 (other._t0)
{
const int ndofs = _FFD->NumberOfDOFs();
_Output = new double[ndofs];
memset(_Output, 0, ndofs * sizeof(double));
}
// ---------------------------------------------------------------------------
/// Destructor
~FreeFormTransformationPointWiseParametricGradientBody() {}
// ---------------------------------------------------------------------------
/// Join results of right-hand body with this body
void join(FreeFormTransformationPointWiseParametricGradientBody &rhs)
{
const int ndofs = _FFD->NumberOfDOFs();
for (int dof = 0; dof < ndofs; ++dof) _Output[dof] += rhs._Output[dof];
delete[] rhs._Output;
rhs._Output = NULL;
}
// ---------------------------------------------------------------------------
/// Calculates the gradient of the similarity term w.r.t. the transformation
/// parameters for the specified points in 3D.
void operator ()(const blocked_range<int> &re)
{
TransformationJacobian jac;
TransformationJacobian::ConstColumnIterator it;
Point p;
for (int i = re.begin(); i != re.end(); ++i) {
const Vector3D<double> &g = _Input[i];
// Check whether reference point is valid
if (g._x != .0 || g._y != .0 || g._z != .0) {
// Calculate derivatives of transformation w.r.t. the parameters
_PointSet->GetPoint(i, p);
_FFD->JacobianDOFs(jac, p._x, p._y, p._z, _t, _t0);
// Apply chain rule to obtain gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * g._x +
it->second._y * g._y +
it->second._z * g._z);
}
}
}
}
// ---------------------------------------------------------------------------
void operator ()()
{
blocked_range<int> pts(0, _PointSet->Size());
parallel_reduce(pts, *this);
}
}; // FreeFormTransformationPointWiseParametricGradientBody
// -----------------------------------------------------------------------------
void FreeFormTransformation
::ParametricGradient(const GenericImage<double> *in, double *out,
const WorldCoordsImage *i2w, const WorldCoordsImage *wc,
double t0, double w) const
{
MIRTK_START_TIMING();
FreeFormTransformationParametricGradientBody body;
body._FFD = this;
body._Input = in;
body._Output = out;
body._Weight = w;
body._WorldCoords = (wc ? wc : i2w);
body._t = in->GetTOrigin();
body._t0 = t0;
body();
MIRTK_DEBUG_TIMING(2, "parametric gradient computation (FFD)");
}
// -----------------------------------------------------------------------------
void FreeFormTransformation
::ParametricGradient(const PointSet &pos, const Vector3D<double> *in,
double *out, double t, double t0, double w) const
{
MIRTK_START_TIMING();
FreeFormTransformationPointWiseParametricGradientBody body;
body._FFD = this;
body._PointSet = &pos;
body._Input = in;
body._Output = out;
body._Weight = w;
body._t = t;
body._t0 = t0;
body();
MIRTK_DEBUG_TIMING(2, "point-wise parametric gradient computation (FFD)");
}
// =============================================================================
// Properties
// =============================================================================
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(double x, double y, double z, double t, double t0, bool wrt_world) const
{
if (!wrt_world) {
cerr << "FreeFormTransformation::BendingEnergy: Always uses derivatives w.r.t. world coordinates" << endl;
exit(1);
}
// Calculate 2nd order derivatives
Matrix hessian[3];
this->LocalHessian(hessian, x, y, z, t, t0);
// Calculate bending energy
return Bending3D(hessian);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(bool incl_passive, bool wrt_world) const
{
int nactive = 0;
double bending = .0;
double x, y, z, t;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
if (incl_passive || this->IsActive(i, j, k, l)) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
t = this->LatticeToTime(l);
bending += this->BendingEnergy(x, y, z, t, 1.0, wrt_world);
++nactive;
}
}
if (nactive > 0) bending /= nactive;
return bending;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(const ImageAttributes &attr, double t0, bool wrt_world) const
{
const int N = attr.NumberOfPoints();
const int L = attr._dt ? attr._t : 1;
if (N == 0) return .0;
double x, y, z, t, bending = .0;
for (int l = 0; l < L; ++l) {
t = attr.LatticeToTime(l);
for (int k = 0; k < attr._z; ++k)
for (int j = 0; j < attr._y; ++j)
for (int i = 0; i < attr._x; ++i) {
x = i, y = j, z = k;
attr.LatticeToWorld(x, y, z);
bending += this->BendingEnergy(x, y, z, t, t0, wrt_world);
}
}
return bending / N;
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::BendingEnergyGradient(double *, double, bool, bool) const
{
cerr << this->NameOfClass() << "::BendingEnergyGradient: Not implemented" << endl;
exit(1);
}
// =============================================================================
// I/O
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::Print(ostream &os, Indent indent) const
{
// Print no. of transformation parameters
os << indent << "Number of DOFs: " << this->NumberOfDOFs() << endl;
os << indent << "Number of CPs (active): " << this->NumberOfActiveCPs()<< endl;
os << indent << "Number of CPs (passive): " << this->NumberOfPassiveCPs()<< endl;
os << indent << "Extrapolation mode: " << ToString(_ExtrapolationMode) << endl;
// Print lattice attributes
os << indent << "Control point lattice:" << endl;
_attr.Print(os, indent + 1);
}
// -----------------------------------------------------------------------------
Cofstream &FreeFormTransformation::WriteCPs(Cofstream &to) const
{
// Note: this->NumberOfDOFs() may differ for specialized subclasses!
const int num = 3 * this->NumberOfCPs();
to.WriteAsDouble(reinterpret_cast<const double *>(_CPImage.Data()), num);
to.WriteAsInt (reinterpret_cast<const int *>(_CPStatus[0][0][0]), num);
return to;
}
} // namespace mirtk
fix: FreeFormTransformation::Parameter [Transformation]
/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mirtk/FreeFormTransformation.h"
#include "mirtk/Math.h"
#include "mirtk/Memory.h"
#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
namespace mirtk {
// =============================================================================
// Construction/Destruction
// =============================================================================
// Auxiliary macro used to initialize references to often needed
// control point image attributes in initialization list of constructor
#define _References() \
_attr (_CPImage.Attributes()), \
_x (_CPImage.Attributes()._x), \
_y (_CPImage.Attributes()._y), \
_z (_CPImage.Attributes()._z), \
_t (_CPImage.Attributes()._t), \
_dx (_CPImage.Attributes()._dx), \
_dy (_CPImage.Attributes()._dy), \
_dz (_CPImage.Attributes()._dz), \
_dt (_CPImage.Attributes()._dt), \
_matW2L(_CPImage.GetWorldToImageMatrix()), \
_matL2W(_CPImage.GetImageToWorldMatrix())
// -----------------------------------------------------------------------------
FreeFormTransformation
::FreeFormTransformation(CPInterpolator &func, CPInterpolator *func2D)
:
_ExtrapolationMode(Extrapolation_Const),
_SpeedupFactor(1.0),
_CPValue (NULL),
_CPFunc (&func),
_CPFunc2D(func2D),
_CPStatus(NULL),
_References()
{
}
// -----------------------------------------------------------------------------
FreeFormTransformation
::FreeFormTransformation(const FreeFormTransformation &ffd,
CPInterpolator &func, CPInterpolator *func2D)
:
Transformation(ffd),
_ExtrapolationMode(ffd._ExtrapolationMode),
_SpeedupFactor(ffd._SpeedupFactor),
_CPValue (NULL),
_CPFunc (&func),
_CPFunc2D(func2D),
_CPStatus(NULL),
_References()
{
if (_NumberOfDOFs > 0) {
_CPImage.Initialize(ffd.Attributes(), reinterpret_cast<CPValue *>(_Param));
Allocate(_CPStatus, _x, _y, _z, _t, reinterpret_cast<CPStatus *>(_Status));
}
}
// -----------------------------------------------------------------------------
FreeFormTransformation::~FreeFormTransformation()
{
Deallocate(_CPStatus, _Status);
Delete(_CPValue);
}
#undef _References // only used/needed for constructors
// -----------------------------------------------------------------------------
ImageAttributes
FreeFormTransformation
::DefaultAttributes(const ImageAttributes &attr,
double dx, double dy, double dz, double dt)
{
// Set spacing equal to voxel size if not specified (i.e., negative)
if (dx < .0) dx = attr._dx;
if (dy < .0) dy = attr._dy;
if (dz < .0) dz = attr._dz;
if (dt < .0) dt = attr._dt;
// Orthogonalize image grid if necessary
const ImageAttributes grid = OrthogonalFieldOfView(attr);
// Set lattice attributes to image attributes
ImageAttributes lattice = grid;
// Adjust lattice dimensions
lattice._x = ((dx > .0 && grid._x > 1) ? iround((grid._x - 1) * grid._dx / dx) + 1 : 1);
lattice._y = ((dy > .0 && grid._y > 1) ? iround((grid._y - 1) * grid._dy / dy) + 1 : 1);
lattice._z = ((dz > .0 && grid._z > 1) ? iround((grid._z - 1) * grid._dz / dz) + 1 : 1);
lattice._t = ((dt > .0 && grid._t > 1) ? iround((grid._t - 1) * grid._dt / dt) + 1 : 1);
// Update lattice spacing
lattice._dx = ((lattice._x > 1) ? dx : .0);
lattice._dy = ((lattice._y > 1) ? dy : .0);
lattice._dz = ((lattice._z > 1) ? dz : .0);
lattice._dt = ((lattice._t > 1) ? dt : .0);
return lattice;
}
// -----------------------------------------------------------------------------
ImageAttributes
FreeFormTransformation
::DefaultAttributes(double x1, double y1, double z1, double t1,
double x2, double y2, double z2, double t2,
double dx, double dy, double dz, double dt,
const double *xaxis,
const double *yaxis,
const double *zaxis)
{
ImageAttributes attr;
// Lattice origin
attr._xorigin = (x2 + x1) / 2.0;
attr._yorigin = (y2 + y1) / 2.0;
attr._zorigin = (z2 + z1) / 2.0;
attr._torigin = t1;
// Lattice orientation
memcpy(attr._xaxis, xaxis, 3 * sizeof(double));
memcpy(attr._yaxis, yaxis, 3 * sizeof(double));
memcpy(attr._zaxis, zaxis, 3 * sizeof(double));
// FOV in lattice orientation
double a, b, c;
a = x1 * xaxis[0] + y1 * xaxis[1] + z1 * xaxis[2];
b = x1 * yaxis[0] + y1 * yaxis[1] + z1 * yaxis[2];
c = x1 * zaxis[0] + y1 * zaxis[1] + z1 * zaxis[2];
x1 = a, y1 = b, z1 = c;
a = x2 * xaxis[0] + y2 * xaxis[1] + z2 * xaxis[2];
b = x2 * yaxis[0] + y2 * yaxis[1] + z2 * yaxis[2];
c = x2 * zaxis[0] + y2 * zaxis[1] + z2 * zaxis[2];
x2 = a, y2 = b, z2 = c;
// Lattice dimensions
attr._x = ((dx > .0) ? iround((x2 - x1) / dx) + 1 : 1);
attr._y = ((dy > .0) ? iround((y2 - y1) / dy) + 1 : 1);
attr._z = ((dz > .0) ? iround((z2 - z1) / dz) + 1 : 1);
attr._t = ((dt > .0) ? iround((t2 - t1) / dt) + 1 : 1);
// Lattice spacing
attr._dx = ((attr._x > 1) ? dx : .0);
attr._dy = ((attr._y > 1) ? dy : .0);
attr._dz = ((attr._z > 1) ? dz : .0);
attr._dt = ((attr._t > 1) ? dt : .0);
return attr;
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeInterpolator()
{
// Attention: Returns NULL for _ExtrapolationMode == Extrapolation_None!
Delete(_CPValue);
_CPValue = CPExtrapolator::New(_ExtrapolationMode, &_CPImage);
_CPFunc->Input(&_CPImage);
_CPFunc->Extrapolator(_CPValue);
_CPFunc->Initialize(true); // also initializes _CPValue
if (_CPFunc2D) {
_CPFunc2D->Input(&_CPImage);
_CPFunc2D->Extrapolator(_CPValue);
_CPFunc2D->Initialize(true);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeCPs(const ImageAttributes &attr, bool dofs)
{
if (attr._x > 1000 || attr._y > 1000 || attr._z > 1000) {
// Otherwise we may not only run out of memory, but also encounter an
// integer overflow when computing the number of control points...
cerr << "FreeFormTransformation::InitializeCPs: Number of control points may not exceed 1000 in each dimension!" << endl;
exit(1);
}
Deallocate(_CPStatus, _Status);
const int ncps = attr.NumberOfPoints();
if (ncps > 0) {
// If NULL, allocate memory for control points which differs from
// the memory referenced by _Param and _Status of the base class
CPValue *param = NULL;
CPStatus *status = NULL;
// If control points are directly the parameters of the transformation...
if (dofs) {
// Assert size of types
if (sizeof(CPValue) != 3 * sizeof(DOFValue)) {
cerr << "FreeFormTransformation::InitializeCPs: Assertion \"sizeof(CPValue) == 3 * sizeof(DOFValue)\" failed!" << endl;
cerr << " Make sure that the vector type used fulfills this assertion such that FFDs can wrap the linear" << endl;
cerr << " memory used to store the transformation parameters in an image instance with 3D vector voxel type." << endl;
exit(1);
}
// ...allocate memory for parameters and their respective status
InitializeDOFs(3 * ncps);
// ...and reinterpret this memory as 3D(+t) images
param = reinterpret_cast<CPValue *>(_Param);
status = reinterpret_cast<CPStatus *>(_Status);
}
// Allocate 4D array for convenient access to parameters of each control point
_CPImage.Initialize(attr, param);
Allocate(_CPStatus, attr._x, attr._y, attr._z, attr._t, status);
InitializeInterpolator();
InitializeStatus();
} else {
Delete(_CPValue);
_CPImage.Clear();
InitializeDOFs(0);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeCPs(const FreeFormTransformation &ffd, bool dofs)
{
if (ffd.NumberOfCPs() > 0) {
// If NULL, allocate memory for control points which differs from
// the memory referenced by _Param and _Status of the base class
CPValue *param = NULL;
CPStatus *status = NULL;
// If control points are directly the parameters of the transformation...
if (dofs) {
// ...copy transformation parameters and their respective status
InitializeDOFs(ffd);
// ...and reinterpret this memory as 3D(+t) images
param = reinterpret_cast<CPValue *>(_Param);
status = reinterpret_cast<CPStatus *>(_Status);
}
// Allocate 4D array for convenient access to parameters of each control point
_CPImage.Initialize(ffd.Attributes(), param);
Allocate(_CPStatus, _x, _y, _z, _t, status);
InitializeInterpolator();
InitializeStatus();
} else {
Delete(_CPValue);
_CPImage.Clear();
Deallocate(_CPStatus, _Status);
InitializeDOFs(0);
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::InitializeStatus()
{
// Set status of unused control point dimensions to Passive
// TODO: Consider removing this commented code or uncomment it again once
// the control point coefficients are in lattice units/orientation.
// A 2D FFD in a plane not parallel to the xy plane has non-zero
// (i.e., active) z coefficients in world space!
// const CPStatus status(((_x > 1) ? Active : Passive),
// ((_y > 1) ? Active : Passive),
// ((_z > 1) ? Active : Passive));
const CPStatus status = Active;
for (int cp = 0; cp < this->NumberOfCPs(); ++cp) PutStatus(cp, status);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const ImageAttributes &attr)
{
InitializeCPs(attr);
this->Changed(true);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const ImageAttributes &attr,
double dx, double dy, double dz, double dt)
{
this->Initialize(DefaultAttributes(attr, dx, dy, dz, dt));
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::Initialize(const CPImage &image, bool displacement)
{
// Initialize free-form transformation
this->Initialize(image.Attributes());
// Copy control point coefficients
_CPImage.CopyFrom(image);
// Convert control point deformation to displacement
if (!displacement) {
double x, y, z;
CPValue *data = _CPImage.Data();
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
data->_x -= x;
data->_y -= y;
data->_z -= z;
++data;
}
}
}
// -----------------------------------------------------------------------------
void FreeFormTransformation
::Initialize(const GenericImage<double> &image, bool displacement)
{
if (image.T() < 2 || image.T() > 3) {
cerr << "FreeFormTransformation::Initialize:"
" Input image must be 2D/3D vector field with _t == 2 or 3)" << endl;
exit(1);
}
// Initialize control points
ImageAttributes attr = image.Attributes();
attr._t = 1;
attr._dt = .0;
this->Initialize(attr);
// Copy vector field
CPValue *data = _CPImage.Data();
for (int k = 0; k < image.GetZ(); ++k)
for (int j = 0; j < image.GetY(); ++j)
for (int i = 0; i < image.GetX(); ++i) {
data->_x = image(i, j, k, 0);
data->_y = image(i, j, k, 1);
if (image.GetT() >= 3) data->_z = image(i, j, k, 2);
else data->_z = .0;
++data;
}
// Convert control point deformation to displacement
if (!displacement) {
double x, y, z;
CPValue *data = _CPImage.Data();
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
data->_x -= x;
data->_y -= y;
data->_z -= z;
++data;
}
}
}
// =============================================================================
// Parameters (non-DoFs)
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::ExtrapolationMode(enum ExtrapolationMode mode)
{
// Set extrapolation mode
_ExtrapolationMode = mode;
// Update control point function, if _CPValue == NULL the FFD is uninitialized yet
if (_CPValue && _CPValue->ExtrapolationMode() != _ExtrapolationMode) {
Delete(_CPValue);
_CPValue = CPExtrapolator::New(_ExtrapolationMode, &_CPImage);
if (_CPValue) {
_CPValue->Input(&_CPImage);
_CPValue->Initialize();
}
_CPFunc->Extrapolator(_CPValue);
if (_CPFunc2D) _CPFunc2D->Extrapolator(_CPValue);
// Note: No need to call _CPFunc(2D)->Initialize() again
}
}
// -----------------------------------------------------------------------------
bool FreeFormTransformation::Set(const char *name, const char *value)
{
// Extrapolation mode
if (strcmp(name, "Transformation extrapolation") == 0) {
enum ExtrapolationMode mode;
if (!FromString(value, mode)) return false;
this->ExtrapolationMode(mode);
this->Changed(true);
return true;
}
// Speedup factor for gradient computation
if (strcmp(name, "Speedup factor") == 0) {
double d;
if (!FromString(value, d) || d < 1.0) return false;
_SpeedupFactor = d;
this->Changed(true);
return true;
}
// Control point spacing
if (strncmp(name, "Control point spacing", 21) == 0) {
double dx, dy, dz, dt, ds;
if (!FromString(value, ds) || ds <= .0) return false;
if (strstr(name, "[m]") != NULL) ds *= 1.0e+3;
else if (strstr(name, "[mu]") != NULL) ds *= 1.0e-3;
_CPImage.GetPixelSize(dx, dy, dz, dt);
if (strncmp(name + 21, " in ", 4) == 0) {
if (name[25] == 'X') dx = ds;
else if (name[25] == 'Y') dy = ds;
else if (name[25] == 'Z') dz = ds;
else if (name[25] == 'T') dt = ds;
} else {
dx = dy = dz = dt = ds;
}
if (_x == 1) dx = .0;
if (_y == 1) dy = .0;
if (_z == 1) dz = .0;
if (_t == 1) dt = .0;
_CPImage.PutPixelSize(dx, dy, dz, dt);
this->Changed(true);
return true;
}
if (strcmp(name, "Control point xyz units") == 0) {
double s;
if (strcmp(value, "Meter") == 0 || strcmp(value, "m") == 0) s = 1.0e+3;
else if (strcmp(value, "Millimeter") == 0 || strcmp(value, "mm") == 0) s = 1.0;
else if (strcmp(value, "Micrometer") == 0 || strcmp(value, "mu") == 0) s = 1.0e-3;
else return false;
if (s != 1.0) {
double ox, oy, oz, dx, dy, dz;
_CPImage.GetOrigin (ox, oy, oz);
_CPImage.PutOrigin (ox * s, oy * s, oz * s);
_CPImage.GetPixelSize(dx, dy, dz);
_CPImage.PutPixelSize(dx * s, dy * s, dz * s);
_CPImage *= s;
}
this->Changed(true);
return true;
}
return Transformation::Set(name, value);
}
// -----------------------------------------------------------------------------
ParameterList FreeFormTransformation::Parameter() const
{
ParameterList params = Transformation::Parameter();
Insert(params, "Transformation extrapolation", ToString(_ExtrapolationMode));
Insert(params, "Speedup factor", ToString(_SpeedupFactor));
return params;
}
// =============================================================================
// Approximation/Interpolation
// =============================================================================
// -----------------------------------------------------------------------------
ImageAttributes FreeFormTransformation
::ApproximationDomain(const ImageAttributes &domain, const Transformation *)
{
return domain;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::EvaluateRMSError(const Transformation *dof) const
{
return EvaluateRMSError(_attr, dof);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::Approximate(const Transformation *t, int niter, double max_error)
{
return this->Approximate(_attr, t, niter, max_error);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const ImageAttributes &domain, double *dx, double *dy, double *dz,
int niter, double max_error)
{
const int no = domain.NumberOfPoints();
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Compute world coordinates of lattice points
double *x = Allocate<double>(no);
double *y = Allocate<double>(no);
double *z = Allocate<double>(no);
double *t = Allocate<double>(no);
domain.LatticeToWorld(x, y, z, t);
// Copy original displacements
double *tx = CAllocate<double>(no);
double *ty = CAllocate<double>(no);
double *tz = CAllocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
if (this->RequiresCachingOfDisplacements()) {
error = EvaluateRMSError(domain, dx, dy, dz);
} else {
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
if (this->RequiresCachingOfDisplacements()) {
error = EvaluateRMSError(domain, dx, dy, dz);
} else {
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
Deallocate(x);
Deallocate(y);
Deallocate(z);
Deallocate(t);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const double *x, const double *y, const double *z,
double *dx, double *dy, double *dz, int no,
int niter, double max_error)
{
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Compute (fixed) time coordinates
const double t0 = .0;
double *t = CAllocate<double>(no, &t0);
// Copy original displacements
double *tx = Allocate<double>(no);
double *ty = Allocate<double>(no);
double *tz = Allocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
error = EvaluateRMSError(x, y, z, t0, dx, dy, dz, no);
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
error = EvaluateRMSError(x, y, z, t0, dx, dy, dz, no);
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
Deallocate(t);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::Approximate(const double *x, const double *y, const double *z, const double *t,
double *dx, double *dy, double *dz, int no,
int niter, double max_error)
{
if (no <= 0) return .0;
double error = numeric_limits<double>::infinity();
if (niter < 1) return error;
// Copy original displacements
double *tx = Allocate<double>(no);
double *ty = Allocate<double>(no);
double *tz = Allocate<double>(no);
memcpy(tx, dx, no * sizeof(double));
memcpy(ty, dy, no * sizeof(double));
memcpy(tz, dz, no * sizeof(double));
// Evaluate error of approximation and residual displacements
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
// Repeat approximation n times or until error drops below a threshold
DOFValue *param = Allocate<DOFValue>(_NumberOfDOFs);
for (int iter = 0; iter < niter && error > max_error; ++iter) {
// Copy current parameters
this->Get(param);
// Approximate residual displacements by new parameters
this->ApproximateDOFs(x, y, z, t, dx, dy, dz, no);
// Add previous parameters
this->Add(param);
// Evaluate error of approximation and residual displacements
memcpy(dx, tx, no * sizeof(double));
memcpy(dy, ty, no * sizeof(double));
memcpy(dz, tz, no * sizeof(double));
error = EvaluateRMSError(x, y, z, t, dx, dy, dz, no);
}
// Free memory
Deallocate(param);
Deallocate(tx);
Deallocate(ty);
Deallocate(tz);
return error;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation::ApproximateAsNew(const Transformation *t, int niter, double max_error)
{
return this->ApproximateAsNew(_attr, t, niter, max_error);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::ApproximateAsNew(const ImageAttributes &domain, double *dx, double *dy, double *dz, int niter, double max_error)
{
bool ignore_time = (AreEqual(domain._dt, 0.) || domain._t == 1) && (AreEqual(_dt, 0.) || _t == 1);
if ((!ignore_time && domain == _attr) || (ignore_time && domain.EqualInSpace(_attr))) {
this->Interpolate(dx, dy, dz);
return .0; // No approximation error at lattice/control points
}
return Transformation::ApproximateAsNew(domain, dx, dy, dz, niter, max_error);
}
// =============================================================================
// Lattice
// =============================================================================
// -----------------------------------------------------------------------------
bool FreeFormTransformation::CropPadPassiveCPs(int margin, bool reset)
{
return this->CropPadPassiveCPs(margin, margin, margin, margin, reset);
}
// -----------------------------------------------------------------------------
bool FreeFormTransformation::CropPadPassiveCPs(int mx, int my, int mz, int mt, bool reset)
{
ImageAttributes attr = _attr;
// Determine lower bound along x axis: i1
int i1 = _x;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
if (IsActive(i, j, k, l)) {
if (i < i1) i1 = i;
break;
}
}
// Determine upper bound along x axis: i2
int i2 = -1;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = _x - 1; i >= i1; --i) {
if (IsActive(i, j, k, l)) {
if (i > i2) i2 = i;
break;
}
}
// Determine lower bound along y axis: j1
int j1 = _y;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int i = i1; i <= i2; ++i)
for (int j = 0; j < _y; ++j) {
if (IsActive(i, j, k, l)) {
if (j < j1) j1 = j;
break;
}
}
// Determine upper bound along y axis: j2
int j2 = -1;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int i = i1; i <= i2; ++i)
for (int j = _y - 1; j >= j1; --j) {
if (IsActive(i, j, k, l)) {
if (j > j2) j2 = j;
break;
}
}
// Determine lower bound along z axis: k1
int k1 = _z;
for (int l = 0; l < _t; ++l)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int k = 0; k < _z; ++k) {
if (IsActive(i, j, k, l)) {
if (k < k1) k1 = k;
break;
}
}
// Determine upper bound along z axis: k2
int k2 = -1;
for (int l = 0; l < _t; ++l)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int k = _z - 1; k >= k1; --k) {
if (IsActive(i, j, k, l)) {
if (k > k2) k2 = k;
break;
}
}
// Determine lower bound along t axis: l1
int l1 = _t;
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int l = 0; l < _t; ++l) {
if (IsActive(i, j, k, l)) {
if (l < l1) l1 = l;
break;
}
}
// Determine upper bound along t axis: l2
int l2 = -1;
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i)
for (int l = _t - 1; l >= l1; --l) {
if (IsActive(i, j, k, l)) {
if (l > l2) l2 = l;
break;
}
}
// Do nothing if all control points are passive, but report it
if (i1 > i2 || j1 > j2 || k1 > k2 || l1 > l2) return false;
// Convert upper index bounds to margin widths
i2 = (_x - 1) - i2;
j2 = (_y - 1) - j2;
k2 = (_z - 1) - k2;
l2 = (_t - 1) - l2;
// Leave a margin of passive control points with specified width
// Note: Negative value gives the number of control points to add.
if (_x > 1) i1 -= mx, i2 -= mx;
if (_y > 1) j1 -= my, j2 -= my;
if (_z > 1) k1 -= mz, k2 -= mz;
if (_t > 1) l1 -= mt, l2 -= mt;
// Do nothing, if nothing to be done
if (i1 == 0 && i2 == 0 && j1 == 0 && j2 == 0 &&
k1 == 0 && k2 == 0 && l1 == 0 && l2 == 0) return true;
// Adjust control point lattice
attr._x -= i1 + i2;
attr._y -= j1 + j2;
attr._z -= k1 + k2;
attr._t -= l1 + l2;
attr._xorigin = 0.5 * ((_x - 1) + (i1 - i2));
attr._yorigin = 0.5 * ((_y - 1) + (j1 - j2));
attr._zorigin = 0.5 * ((_z - 1) + (k1 - k2));
this->LatticeToWorld(attr._xorigin, attr._yorigin, attr._zorigin);
attr._torigin = this->LatticeToTime(l1);
// Convert upper margin widths to index bounds
i2 = (_x - 1) - i2;
j2 = (_y - 1) - j2;
k2 = (_z - 1) - k2;
l2 = (_t - 1) - l2;
// Copy remaining control points and pad lattice where needed
const int ncps = attr.NumberOfPoints();
CPValue *param = Allocate<CPValue >(ncps);
CPStatus *status = Allocate<CPStatus>(ncps);
CPValue *param_iter = param;
CPStatus *status_iter = status;
for (int l = l1; l <= l2; ++l)
for (int k = k1; k <= k2; ++k)
for (int j = j1; j <= j2; ++j)
for (int i = i1; i <= i2; ++i, ++param_iter, ++status_iter) {
if (0 <= i && i < _x &&
0 <= j && j < _y &&
0 <= k && k < _z &&
0 <= l && l < _t) {
(*status_iter) = _CPStatus[l][k][j][i];
(*param_iter) = _CPImage(i, j, k, l);
} else {
// Padded control point to extend margin
(*status_iter) = CPStatus(Passive);
(*param_iter) = CPValue (.0);
}
}
// Initialize new control point lattice
this->Initialize(attr);
param_iter = param;
status_iter = status;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i, ++param_iter, ++status_iter) {
_CPStatus[l][k][j][i] = (*status_iter);
if (// Copy all control point values by default
!reset ||
// Always if control point status is not passive...
(status_iter->_x != Passive) ||
(status_iter->_y != Passive) ||
(status_iter->_z != Passive) ||
// ...or control point is not within the boundary margin
i >= mx || i < _x - mx ||
j >= my || j < _y - my ||
k >= mz || k < _z - mz ||
l >= mt || l < _t - mt) {
_CPImage(i, j, k, l) = (*param_iter);
}
}
// Free temporary allocated memory
Deallocate(param);
Deallocate(status);
return true;
}
// =============================================================================
// Bounding box
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double x1, double y1, double z1,
double x2, double y2, double z2)
{
const ImageAttributes &attr = Attributes();
double a, b, c;
// Update lattice origin
_CPImage.PutOrigin((x2 + x1) / 2.0, (y2 + y1) / 2.0, (z2 + z1) / 2.0);
// FOV in lattice orientation
a = x1 * attr._xaxis[0] + y1 * attr._xaxis[1] + z1 * attr._xaxis[2];
b = x1 * attr._yaxis[0] + y1 * attr._yaxis[1] + z1 * attr._yaxis[2];
c = x1 * attr._zaxis[0] + y1 * attr._zaxis[1] + z1 * attr._zaxis[2];
x1 = a, y1 = b, z1 = c;
a = x2 * attr._xaxis[0] + y2 * attr._xaxis[1] + z2 * attr._xaxis[2];
b = x2 * attr._yaxis[0] + y2 * attr._yaxis[1] + z2 * attr._yaxis[2];
c = x2 * attr._zaxis[0] + y2 * attr._zaxis[1] + z2 * attr._zaxis[2];
x2 = a, y2 = b, z2 = c;
// Update lattice spacing
_CPImage.PutPixelSize(((x2 > x1) ? ((x2 - x1) / (attr._x - 1)) : 1),
((y2 > y1) ? ((y2 - y1) / (attr._y - 1)) : 1),
((z2 > z1) ? ((z2 - z1) / (attr._z - 1)) : 1));
this->Changed(true);
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(const Point &p1, const Point &p2)
{
PutBoundingBox(p1._x, p1._y, p1._z, p2._x, p2._y, p2._z);
}
// ---------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double t1, double t2)
{
_CPImage.PutTOrigin((t2 + t1) / 2.0);
_CPImage.PutTSize ((t2 > t2) ? ((t2 - t1) / (_t - 1)) : 1);
this->Changed(true);
}
// ---------------------------------------------------------------------------
void FreeFormTransformation::PutBoundingBox(double x1, double y1, double z1, double t1,
double x2, double y2, double z2, double t2)
{
PutBoundingBox(x1, y1, z1, x2, y2, z2);
PutBoundingBox(t1, t2);
}
// =============================================================================
// Derivatives
// =============================================================================
// -----------------------------------------------------------------------------
/// (Multi-threaded) body of FreeFormTransformation::ParametricGradient
///
/// This default implementation uses the FreeFormTransformation::JacobianDOFs
/// overload which computes the derivatives of the transformation w.r.t. all
/// transformation parameters at once for a given spatial location (target voxel).
/// It provides better performance in particular for transformations which are
/// parameterized by non-stationary velocity fields (3D+t) in which case the
/// derivatives along each temporal trajectory are computed at once and therefore
/// this trajectory does not have to be re-computed for each and every control
/// point. For classic FFDs, which are parameterized by displacements, less
/// general but more efficient implementations of the ParametricGradient function
/// are provided by the FreeFormTransformation3D and
/// FreeFormTransformation4D subclasses, which therefore override this
/// FreeFormTransformation::ParametricGradient implementation. If a subclass
/// of either of these subclasses is parameterized by velocities, it must therefore
/// override the ParametericGradient function again, for example as follows,
/// unless a more specialized gradient computation is provided by this subclass.
///
/// \code
/// void BSplineFreeFormTransformationTD::ParametricGradient(...)
/// {
/// FreeFormTransformation::ParametricGradient(...);
/// }
/// \endcode
class FreeFormTransformationParametricGradientBody
{
public:
const FreeFormTransformation *_FFD;
const GenericImage<double> *_Input;
const WorldCoordsImage *_WorldCoords;
double *_Output;
double _Weight;
double _t; ///< Time corrresponding to input gradient image (in ms)
double _t0; ///< Second time argument for velocity-based transformations
private:
int _X; ///< Number of voxels along x axis
int _Y; ///< Number of voxels along y axis
public:
// ---------------------------------------------------------------------------
/// Default constructor
FreeFormTransformationParametricGradientBody()
:
_FFD (NULL),
_Input (NULL),
_WorldCoords(NULL),
_Output (NULL),
_Weight ( 1.0),
_t ( 0.0),
_t0 (-1.0),
_X (0),
_Y (0)
{}
// ---------------------------------------------------------------------------
/// Split constructor
FreeFormTransformationParametricGradientBody(const FreeFormTransformationParametricGradientBody &other, split)
:
_FFD (other._FFD),
_Input (other._Input),
_WorldCoords(other._WorldCoords),
_Output (NULL),
_Weight (other._Weight),
_t (other._t),
_t0 (other._t0),
_X (other._X),
_Y (other._Y)
{
const int ndofs = _FFD->NumberOfDOFs();
_Output = new double[ndofs];
memset(_Output, 0, ndofs * sizeof(double));
}
// ---------------------------------------------------------------------------
/// Destructor
~FreeFormTransformationParametricGradientBody() {}
// ---------------------------------------------------------------------------
/// Join results of right-hand body with this body
void join(FreeFormTransformationParametricGradientBody &rhs)
{
const int ndofs = _FFD->NumberOfDOFs();
for (int dof = 0; dof < ndofs; dof++) _Output[dof] += rhs._Output[dof];
delete[] rhs._Output;
rhs._Output = NULL;
}
// ---------------------------------------------------------------------------
/// Calculates the gradient of the similarity term w.r.t. the transformation
/// parameters for each voxel in the specified image region
void operator ()(const blocked_range3d<int> &re)
{
const int i1 = re.cols ().begin();
const int j1 = re.rows ().begin();
const int k1 = re.pages().begin();
const int i2 = re.cols ().end();
const int j2 = re.rows ().end();
const int k2 = re.pages().end();
TransformationJacobian jac;
TransformationJacobian::ConstColumnIterator it;
//s1=1
const int s2 = _X - (i2 - i1);
const int s3 = (_Y - (j2 - j1)) * _X;
// Non-parametric/voxelwise gradient
const double *gx = _Input->Data(i1, j1, k1, 0);
const double *gy = _Input->Data(i1, j1, k1, 1);
const double *gz = _Input->Data(i1, j1, k1, 2);
// With (transformed) pre-computed world coordinates
if (_WorldCoords) {
const double *wx = _WorldCoords->Data(i1, j1, k1, 0);
const double *wy = _WorldCoords->Data(i1, j1, k1, 1);
const double *wz = _WorldCoords->Data(i1, j1, k1, 2);
for (int k = k1; k < k2; ++k, wx += s3, wy += s3, wz += s3, gx += s3, gy += s3, gz += s3)
for (int j = j1; j < j2; ++j, wx += s2, wy += s2, wz += s2, gx += s2, gy += s2, gz += s2)
for (int i = i1; i < i2; ++i, wx += 1, wy += 1, wz += 1, gx += 1, gy += 1, gz += 1) {
if (*gx || *gy || *gz) {
// Calculate derivatives of transformation w.r.t. the parameters
_FFD->JacobianDOFs(jac, *wx, *wy, *wz, _t, _t0);
// Apply chain rule to obtain similarity gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * (*gx) +
it->second._y * (*gy) +
it->second._z * (*gz));
}
}
}
// Without pre-computed world coordinates
} else {
double x, y, z;
for (int k = k1; k < k2; ++k, gx += s3, gy += s3, gz += s3)
for (int j = j1; j < j2; ++j, gx += s2, gy += s2, gz += s2)
for (int i = i1; i < i2; ++i, gx += 1, gy += 1, gz += 1) {
if (*gx || *gy || *gz) {
// Convert voxel to world coordinates
x = i, y = j, z = k;
_Input->ImageToWorld(x, y, z);
// Calculate derivatives of transformation w.r.t. the parameters
_FFD->JacobianDOFs(jac, x, y, z, _t, _t0);
// Apply chain rule to obtain similarity gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * (*gx) +
it->second._y * (*gy) +
it->second._z * (*gz));
}
}
}
}
}
// ---------------------------------------------------------------------------
void operator ()()
{
// Initialize members to often accessed data
_X = _Input->GetX();
_Y = _Input->GetY();
const int _Z = _Input->GetZ();
// Check input
if (_WorldCoords && (_WorldCoords->X() != _X ||
_WorldCoords->Y() != _Y ||
_WorldCoords->Z() != _Z ||
_WorldCoords->T() != 3)) {
cerr << "FreeFormTransformation::ParametricGradient: Invalid world coordinates map" << endl;
exit(1);
}
if (_Input->GetXSize() > _FFD->GetXSpacing() ||
_Input->GetYSize() > _FFD->GetYSpacing() ||
(_FFD->Z() > 1 && _Input->GetZSize() > _FFD->GetZSpacing())) {
// FIXME: In this case, the non-parametric input gradient should be
// resampled using linear interpolation to obtain a value at
// each control point.
cerr << "Warning: FFD spacing smaller than image resolution!" << endl;
cerr << " This may lead to artifacts in the transformation because" << endl;
cerr << " not all control points are within the vicinity of a voxel center." << endl;
}
// Calculate parametric gradient
blocked_range3d<int> voxels(0, _Z, 0, _Y, 0, _X);
parallel_reduce(voxels, *this);
}
}; // FreeFormTransformationParametricGradientBody
// -----------------------------------------------------------------------------
class FreeFormTransformationPointWiseParametricGradientBody
{
public:
const FreeFormTransformation *_FFD;
const PointSet *_PointSet;
const Vector3D<double> *_Input;
double *_Output;
double _Weight;
double _t; ///< Time corrresponding to input gradient image (in ms)
double _t0; ///< Second time argument for velocity-based transformations
// ---------------------------------------------------------------------------
/// Default constructor
FreeFormTransformationPointWiseParametricGradientBody()
:
_FFD (NULL),
_PointSet(NULL),
_Input (NULL),
_Output (NULL),
_Weight ( 1.0),
_t ( 0.0),
_t0 (-1.0)
{}
// ---------------------------------------------------------------------------
/// Split constructor
FreeFormTransformationPointWiseParametricGradientBody(const FreeFormTransformationPointWiseParametricGradientBody &other, split)
:
_FFD (other._FFD),
_PointSet(other._PointSet),
_Input (other._Input),
_Output (NULL),
_Weight (other._Weight),
_t (other._t),
_t0 (other._t0)
{
const int ndofs = _FFD->NumberOfDOFs();
_Output = new double[ndofs];
memset(_Output, 0, ndofs * sizeof(double));
}
// ---------------------------------------------------------------------------
/// Destructor
~FreeFormTransformationPointWiseParametricGradientBody() {}
// ---------------------------------------------------------------------------
/// Join results of right-hand body with this body
void join(FreeFormTransformationPointWiseParametricGradientBody &rhs)
{
const int ndofs = _FFD->NumberOfDOFs();
for (int dof = 0; dof < ndofs; ++dof) _Output[dof] += rhs._Output[dof];
delete[] rhs._Output;
rhs._Output = NULL;
}
// ---------------------------------------------------------------------------
/// Calculates the gradient of the similarity term w.r.t. the transformation
/// parameters for the specified points in 3D.
void operator ()(const blocked_range<int> &re)
{
TransformationJacobian jac;
TransformationJacobian::ConstColumnIterator it;
Point p;
for (int i = re.begin(); i != re.end(); ++i) {
const Vector3D<double> &g = _Input[i];
// Check whether reference point is valid
if (g._x != .0 || g._y != .0 || g._z != .0) {
// Calculate derivatives of transformation w.r.t. the parameters
_PointSet->GetPoint(i, p);
_FFD->JacobianDOFs(jac, p._x, p._y, p._z, _t, _t0);
// Apply chain rule to obtain gradient w.r.t. the transformation parameters
for (it = jac.Begin(); it != jac.End(); ++it) {
_Output[it->first] += _Weight * (it->second._x * g._x +
it->second._y * g._y +
it->second._z * g._z);
}
}
}
}
// ---------------------------------------------------------------------------
void operator ()()
{
blocked_range<int> pts(0, _PointSet->Size());
parallel_reduce(pts, *this);
}
}; // FreeFormTransformationPointWiseParametricGradientBody
// -----------------------------------------------------------------------------
void FreeFormTransformation
::ParametricGradient(const GenericImage<double> *in, double *out,
const WorldCoordsImage *i2w, const WorldCoordsImage *wc,
double t0, double w) const
{
MIRTK_START_TIMING();
FreeFormTransformationParametricGradientBody body;
body._FFD = this;
body._Input = in;
body._Output = out;
body._Weight = w;
body._WorldCoords = (wc ? wc : i2w);
body._t = in->GetTOrigin();
body._t0 = t0;
body();
MIRTK_DEBUG_TIMING(2, "parametric gradient computation (FFD)");
}
// -----------------------------------------------------------------------------
void FreeFormTransformation
::ParametricGradient(const PointSet &pos, const Vector3D<double> *in,
double *out, double t, double t0, double w) const
{
MIRTK_START_TIMING();
FreeFormTransformationPointWiseParametricGradientBody body;
body._FFD = this;
body._PointSet = &pos;
body._Input = in;
body._Output = out;
body._Weight = w;
body._t = t;
body._t0 = t0;
body();
MIRTK_DEBUG_TIMING(2, "point-wise parametric gradient computation (FFD)");
}
// =============================================================================
// Properties
// =============================================================================
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(double x, double y, double z, double t, double t0, bool wrt_world) const
{
if (!wrt_world) {
cerr << "FreeFormTransformation::BendingEnergy: Always uses derivatives w.r.t. world coordinates" << endl;
exit(1);
}
// Calculate 2nd order derivatives
Matrix hessian[3];
this->LocalHessian(hessian, x, y, z, t, t0);
// Calculate bending energy
return Bending3D(hessian);
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(bool incl_passive, bool wrt_world) const
{
int nactive = 0;
double bending = .0;
double x, y, z, t;
for (int l = 0; l < _t; ++l)
for (int k = 0; k < _z; ++k)
for (int j = 0; j < _y; ++j)
for (int i = 0; i < _x; ++i) {
if (incl_passive || this->IsActive(i, j, k, l)) {
x = i, y = j, z = k;
this->LatticeToWorld(x, y, z);
t = this->LatticeToTime(l);
bending += this->BendingEnergy(x, y, z, t, 1.0, wrt_world);
++nactive;
}
}
if (nactive > 0) bending /= nactive;
return bending;
}
// -----------------------------------------------------------------------------
double FreeFormTransformation
::BendingEnergy(const ImageAttributes &attr, double t0, bool wrt_world) const
{
const int N = attr.NumberOfPoints();
const int L = attr._dt ? attr._t : 1;
if (N == 0) return .0;
double x, y, z, t, bending = .0;
for (int l = 0; l < L; ++l) {
t = attr.LatticeToTime(l);
for (int k = 0; k < attr._z; ++k)
for (int j = 0; j < attr._y; ++j)
for (int i = 0; i < attr._x; ++i) {
x = i, y = j, z = k;
attr.LatticeToWorld(x, y, z);
bending += this->BendingEnergy(x, y, z, t, t0, wrt_world);
}
}
return bending / N;
}
// -----------------------------------------------------------------------------
void FreeFormTransformation::BendingEnergyGradient(double *, double, bool, bool) const
{
cerr << this->NameOfClass() << "::BendingEnergyGradient: Not implemented" << endl;
exit(1);
}
// =============================================================================
// I/O
// =============================================================================
// -----------------------------------------------------------------------------
void FreeFormTransformation::Print(ostream &os, Indent indent) const
{
// Print no. of transformation parameters
os << indent << "Number of DOFs: " << this->NumberOfDOFs() << endl;
os << indent << "Number of CPs (active): " << this->NumberOfActiveCPs()<< endl;
os << indent << "Number of CPs (passive): " << this->NumberOfPassiveCPs()<< endl;
os << indent << "Extrapolation mode: " << ToString(_ExtrapolationMode) << endl;
// Print lattice attributes
os << indent << "Control point lattice:" << endl;
_attr.Print(os, indent + 1);
}
// -----------------------------------------------------------------------------
Cofstream &FreeFormTransformation::WriteCPs(Cofstream &to) const
{
// Note: this->NumberOfDOFs() may differ for specialized subclasses!
const int num = 3 * this->NumberOfCPs();
to.WriteAsDouble(reinterpret_cast<const double *>(_CPImage.Data()), num);
to.WriteAsInt (reinterpret_cast<const int *>(_CPStatus[0][0][0]), num);
return to;
}
} // namespace mirtk
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// * Neither the name of DreamWorks Animation 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 THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY 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.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
//
/// @file SOP_OpenVDB_Combine.cc
///
/// @author FX R&D OpenVDB team
#include <houdini_utils/ParmFactory.h>
#include <openvdb_houdini/Utils.h>
#include <openvdb_houdini/SOP_NodeVDB.h>
#include <openvdb/math/Math.h> // for isFinite()
#include <openvdb/tools/ChangeBackground.h>
#include <openvdb/tools/Composite.h>
#include <openvdb/tools/GridTransformer.h> // for resampleToMatch()
#include <openvdb/tools/LevelSetRebuild.h> // for levelSetRebuild()
#include <openvdb/tools/Morphology.h> // for deactivate()
#include <openvdb/tools/Prune.h>
#include <openvdb/tools/SignedFloodFill.h>
#include <openvdb/util/NullInterrupter.h>
#include <PRM/PRM_Parm.h>
#include <UT/UT_Interrupt.h>
#include <UT/UT_Version.h>
#include <algorithm> // for std::min()
#include <cctype> // for isspace()
#include <iomanip>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace hvdb = openvdb_houdini;
namespace hutil = houdini_utils;
namespace {
//
// Operations
//
enum Operation {
OP_COPY_A, // A
OP_COPY_B, // B
OP_INVERT, // 1 - A
OP_ADD, // A + B
OP_SUBTRACT, // A - B
OP_MULTIPLY, // A * B
OP_DIVIDE, // A / B
OP_MAXIMUM, // max(A, B)
OP_MINIMUM, // min(A, B)
OP_BLEND1, // (1 - A) * B
OP_BLEND2, // A + (1 - A) * B
OP_UNION, // CSG A u B
OP_INTERSECTION, // CSG A n B
OP_DIFFERENCE, // CSG A / B
OP_REPLACE, // replace A with B
OP_TOPO_UNION, // A u active(B)
OP_TOPO_INTERSECTION, // A n active(B)
OP_TOPO_DIFFERENCE // A / active(B)
};
enum { OP_FIRST = OP_COPY_A, OP_LAST = OP_TOPO_DIFFERENCE };
//#define TIMES " \xd7 " // ISO-8859 multiplication symbol
#define TIMES " * "
const char* const sOpMenuItems[] = {
"copya", "Copy A",
"copyb", "Copy B",
"inverta", "Invert A",
"add", "Add",
"subtract", "Subtract",
"multiply", "Multiply",
"divide", "Divide",
"maximum", "Maximum",
"minimum", "Minimum",
"compatimesb", "(1 - A)" TIMES "B",
"apluscompatimesb", "A + (1 - A)" TIMES "B",
"sdfunion", "SDF Union",
"sdfintersect", "SDF Intersection",
"sdfdifference", "SDF Difference",
"replacewithactive", "Replace A with Active B",
"topounion", "Activity Union",
"topointersect", "Activity Intersection",
"topodifference", "Activity Difference",
nullptr
};
#undef TIMES
inline Operation
asOp(int i, Operation defaultOp = OP_COPY_A)
{
return (i >= OP_FIRST && i <= OP_LAST)
? static_cast<Operation>(i) : defaultOp;
}
inline bool needAGrid(Operation op) { return (op != OP_COPY_B); }
inline bool needBGrid(Operation op) { return (op != OP_COPY_A && op != OP_INVERT); }
inline bool needLevelSets(Operation op)
{
return (op == OP_UNION || op == OP_INTERSECTION || op == OP_DIFFERENCE);
}
//
// Resampling options
//
enum ResampleMode {
RESAMPLE_OFF, // don't auto-resample grids
RESAMPLE_B, // resample B to match A
RESAMPLE_A, // resample A to match B
RESAMPLE_HI_RES, // resample higher-res grid to match lower-res
RESAMPLE_LO_RES // resample lower-res grid to match higher-res
};
enum { RESAMPLE_MODE_FIRST = RESAMPLE_OFF, RESAMPLE_MODE_LAST = RESAMPLE_LO_RES };
const char* const sResampleModeMenuItems[] = {
"off", "Off",
"btoa", "B to Match A",
"atob", "A to Match B",
"hitolo", "Higher-res to Match Lower-res",
"lotohi", "Lower-res to Match Higher-res",
nullptr
};
inline ResampleMode
asResampleMode(exint i, ResampleMode defaultMode = RESAMPLE_B)
{
return (i >= RESAMPLE_MODE_FIRST && i <= RESAMPLE_MODE_LAST)
? static_cast<ResampleMode>(i) : defaultMode;
}
//
// Collation options
//
enum CollationMode {
COLL_PAIRS = 0,
COLL_A_WITH_1ST_B,
COLL_FLATTEN_A,
COLL_FLATTEN_B_TO_A,
COLL_FLATTEN_A_GROUPS
};
inline CollationMode
asCollation(const std::string& str)
{
if (str == "pairs") return COLL_PAIRS;
if (str == "awithfirstb") return COLL_A_WITH_1ST_B;
if (str == "flattena") return COLL_FLATTEN_A;
if (str == "flattenbtoa") return COLL_FLATTEN_B_TO_A;
if (str == "flattenagroups") return COLL_FLATTEN_A_GROUPS;
throw std::runtime_error{"invalid collation mode \"" + str + "\""};
}
} // anonymous namespace
/// @brief SOP to combine two VDB grids via various arithmetic operations
class SOP_OpenVDB_Combine: public hvdb::SOP_NodeVDB
{
public:
SOP_OpenVDB_Combine(OP_Network*, const char* name, OP_Operator*);
~SOP_OpenVDB_Combine() override {}
static OP_Node* factory(OP_Network*, const char*, OP_Operator*);
class Cache: public SOP_VDBCacheOptions
{
public:
fpreal getTime() const { return mTime; }
protected:
OP_ERROR cookVDBSop(OP_Context&) override;
private:
hvdb::GridPtr combineGrids(Operation,
hvdb::GridCPtr aGrid, hvdb::GridCPtr bGrid,
const UT_String& aGridName, const UT_String& bGridName,
ResampleMode resample);
fpreal mTime = 0.0;
}; // class Cache
protected:
bool updateParmsFlags() override;
void resolveObsoleteParms(PRM_ParmList*) override;
private:
template<typename> struct DispatchOp;
struct CombineOp;
};
////////////////////////////////////////
void
newSopOperator(OP_OperatorTable* table)
{
if (table == nullptr) return;
hutil::ParmList parms;
// Group A
parms.add(hutil::ParmFactory(PRM_STRING, "agroup", "Group A")
.setChoiceList(&hutil::PrimGroupMenuInput1)
.setTooltip("Use a subset of the first input as the A VDB(s).")
.setDocumentation(
"The VDBs to be used from the first input"
" (see [specifying volumes|/model/volumes#group])"));
// Group B
parms.add(hutil::ParmFactory(PRM_STRING, "bgroup", "Group B")
.setChoiceList(&hutil::PrimGroupMenuInput2)
.setTooltip("Use a subset of the second input as the B VDB(s).")
.setDocumentation(
"The VDBs to be used from the second input"
" (see [specifying volumes|/model/volumes#group])"));
parms.add(hutil::ParmFactory(PRM_STRING, "collation", "Collation")
.setChoiceListItems(PRM_CHOICELIST_SINGLE, {
"pairs", "Combine A/B Pairs",
"awithfirstb", "Combine Each A With First B",
"flattena", "Flatten All A",
"flattenbtoa", "Flatten All B Into First A",
"flattenagroups", "Flatten A Groups"
})
.setDefault("pairs")
.setTooltip("Specify the order in which to combine VDBs from the A and/or B groups.")
.setDocumentation("\
The order in which to combine VDBs from the _A_ and/or _B_ groups\n\
\n\
Combine _A_/_B_ Pairs:\n\
Combine pairs of _A_ and _B_ VDBs, in the order in which they appear\n\
in their respective groups.\n\
Combine Each _A_ With First _B_:\n\
Combine each _A_ VDB with the first _B_ VDB.\n\
Flatten All _A_:\n\
Collapse all of the _A_ VDBs into a single output VDB.\n\
Flatten All _B_ Into First _A_:\n\
Accumulate each _B_ VDB into the first _A_ VDB, producing a single output VDB.\n\
Flatten _A_ Groups:\n\
Collapse VDBs within each _A_ group, producing one output VDB for each group.\n\
\n\
Space-separated group patterns are treated as distinct groups in this mode.\n\
For example, \"`@name=x* @name=y*`\" results in two output VDBs\n\
(provided that there is at least one _A_ VDB whose name starts with `x`\n\
and at least one whose name starts with `y`).\n\
"));
// Menu of available operations
parms.add(hutil::ParmFactory(PRM_ORD, "operation", "Operation")
.setDefault(PRMzeroDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, sOpMenuItems)
.setDocumentation("\
Each voxel that is active in either of the input VDBs\n\
will be processed with this operation.\n\
\n\
Copy _A_:\n\
Use _A_, ignore _B_.\n\
\n\
Copy _B_:\n\
Use _B_, ignore _A_.\n\
\n\
Invert _A_:\n\
Use 0 − _A_.\n\
\n\
Add:\n\
Add the values of _A_ and _B_.\n\
\n\
NOTE:\n\
Using this for fog volumes, which have density values between 0 and 1,\n\
will push densities over 1 and cause a bright interface between the\n\
input volumes when rendered. To avoid this problem, try using the\n\
_A_ + (1 − _A_) × _B_\n\
operation.\n\
\n\
Subtract:\n\
Subtract the values of _B_ from the values of _A_.\n\
\n\
Multiply:\n\
Multiply the values of _A_ and _B_.\n\
\n\
Divide:\n\
Divide the values of _A_ by _B_.\n\
\n\
Maximum:\n\
Use the maximum of each corresponding value from _A_ and _B_.\n\
\n\
NOTE:\n\
Using this for fog volumes, which have density values between 0 and 1,\n\
can produce a dark interface between the inputs when rendered, due to\n\
the binary nature of choosing a value from either from _A_ or _B_.\n\
To avoid this problem, try using the\n\
(1 − _A_) × _B_ operation.\n\
\n\
Minimum:\n\
Use the minimum of each corresponding value from _A_ and _B_.\n\
\n\
(1 − _A_) × _B_:\n\
This is similar to SDF Difference, except for fog volumes,\n\
and can also be viewed as \"soft cutout\" operation.\n\
It is typically used to clear out an area around characters\n\
in a dust simulation or some other environmental volume.\n\
\n\
_A_ + (1 − _A_) × _B_:\n\
This is similar to SDF Union, except for fog volumes, and\n\
can also be viewed as a \"soft union\" or \"merge\" operation.\n\
Consider using this over the Maximum or Add operations\n\
for fog volumes.\n\
\n\
SDF Union:\n\
Generate the union of signed distance fields _A_ and _B_.\n\
\n\
SDF Intersection:\n\
Generate the intersection of signed distance fields _A_ and _B_.\n\
\n\
SDF Difference:\n\
Remove signed distance field _B_ from signed distance field _A_.\n\
\n\
Replace _A_ with Active _B_:\n\
Copy the active voxels of _B_ into _A_.\n\
\n\
Activity Union:\n\
Make voxels active if they are active in either _A_ or _B_.\n\
\n\
Activity Intersection:\n\
Make voxels active if they are active in both _A_ and _B_.\n\
\n\
It is recommended to enable pruning when using this operation.\n\
\n\
Activity Difference:\n\
Make voxels active if they are active in _A_ but not in _B_.\n\
\n\
It is recommended to enable pruning when using this operation.\n"));
// Scalar multiplier on the A grid
parms.add(hutil::ParmFactory(PRM_FLT_J, "amult", "A Multiplier")
.setDefault(PRMoneDefaults)
.setRange(PRM_RANGE_UI, -10, PRM_RANGE_UI, 10)
.setTooltip(
"Multiply voxel values in the A VDB by a scalar\n"
"before combining the A VDB with the B VDB."));
// Scalar multiplier on the B grid
parms.add(hutil::ParmFactory(PRM_FLT_J, "bmult", "B Multiplier")
.setDefault(PRMoneDefaults)
.setRange(PRM_RANGE_UI, -10, PRM_RANGE_UI, 10)
.setTooltip(
"Multiply voxel values in the B VDB by a scalar\n"
"before combining the A VDB with the B VDB."));
// Menu of resampling options
parms.add(hutil::ParmFactory(PRM_ORD, "resample", "Resample")
.setDefault(PRMoneDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, sResampleModeMenuItems)
.setTooltip(
"If the A and B VDBs have different transforms, one VDB should\n"
"be resampled to match the other before the two are combined.\n"
"Also, level set VDBs should have matching background values\n"
"(i.e., matching narrow band widths)."));
// Menu of resampling interpolation order options
parms.add(hutil::ParmFactory(PRM_ORD, "resampleinterp", "Interpolation")
.setDefault(PRMoneDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, {
"point", "Nearest",
"linear", "Linear",
"quadratic", "Quadratic"
})
.setTooltip(
"Specify the type of interpolation to be used when\n"
"resampling one VDB to match the other's transform.")
.setDocumentation(
"The type of interpolation to be used when resampling one VDB"
" to match the other's transform\n\n"
"Nearest neighbor interpolation is fast but can introduce noticeable"
" sampling artifacts. Quadratic interpolation is slow but high-quality."
" Linear interpolation is intermediate in speed and quality."));
// Deactivate background value toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "deactivate", "Deactivate Background Voxels")
.setDefault(PRMzeroDefaults)
.setTypeExtended(PRM_TYPE_TOGGLE_JOIN)
.setDocumentation(
"Deactivate active output voxels whose values equal"
" the output VDB's background value."));
// Deactivation tolerance slider
parms.add(hutil::ParmFactory(PRM_FLT_J, "bgtolerance", "Deactivate Tolerance")
.setDefault(PRMzeroDefaults)
.setRange(PRM_RANGE_RESTRICTED, 0, PRM_RANGE_UI, 1)
.setTooltip(
"Deactivate active output voxels whose values\n"
"equal the output VDB's background value.\n"
"Voxel values are considered equal if they differ\n"
"by less than the specified tolerance.")
.setDocumentation(
"When deactivation of background voxels is enabled,"
" voxel values are considered equal to the background"
" if they differ by less than this tolerance."));
// Prune toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "prune", "Prune")
.setDefault(PRMoneDefaults)
.setTypeExtended(PRM_TYPE_TOGGLE_JOIN)
.setDocumentation(
"Reduce the memory footprint of output VDBs that have"
" (sufficiently large) regions of voxels with the same value.\n\n"
"NOTE:\n"
" Pruning affects only the memory usage of a VDB.\n"
" It does not remove voxels, apart from inactive voxels\n"
" whose value is equal to the background."));
// Pruning tolerance slider
parms.add(hutil::ParmFactory(PRM_FLT_J, "tolerance", "Prune Tolerance")
.setDefault(PRMzeroDefaults)
.setRange(PRM_RANGE_RESTRICTED, 0, PRM_RANGE_UI, 1)
.setTooltip(
"Collapse regions of constant value in output VDBs.\n"
"Voxel values are considered equal if they differ\n"
"by less than the specified tolerance.")
.setDocumentation(
"When pruning is enabled, voxel values are considered equal"
" if they differ by less than the specified tolerance."));
// Flood fill toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "flood", "Signed-Flood-Fill Output SDFs")
.setDefault(PRMzeroDefaults)
.setTooltip(
"Reclassify inactive voxels of level set VDBs as either inside or outside.")
.setDocumentation(
"Test inactive voxels to determine if they are inside or outside of an SDF"
" and hence whether they should have negative or positive sign."));
// Obsolete parameters
hutil::ParmList obsoleteParms;
obsoleteParms.add(hutil::ParmFactory(PRM_ORD, "combination", "Operation")
.setDefault(-2));
obsoleteParms.add(hutil::ParmFactory(PRM_SEPARATOR, "sep1", ""));
obsoleteParms.add(hutil::ParmFactory(PRM_SEPARATOR, "sep2", ""));
obsoleteParms.add(hutil::ParmFactory(PRM_TOGGLE, "flatten", "Flatten All B into A")
.setDefault(PRMzeroDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_TOGGLE, "pairs", "Combine A/B Pairs")
.setDefault(PRMoneDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_STRING, "groupA", "Group A"));
obsoleteParms.add(hutil::ParmFactory(PRM_STRING, "groupB", "Group B"));
obsoleteParms.add(hutil::ParmFactory(PRM_FLT_J, "mult_a", "A Multiplier")
.setDefault(PRMoneDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_FLT_J, "mult_b", "B Multiplier")
.setDefault(PRMoneDefaults));
// Register SOP
hvdb::OpenVDBOpFactory("VDB Combine", SOP_OpenVDB_Combine::factory, parms, *table)
.addInput("A VDBs")
.addOptionalInput("B VDBs")
.setObsoleteParms(obsoleteParms)
.setVerb(SOP_NodeVerb::COOK_INPLACE, []() { return new SOP_OpenVDB_Combine::Cache; })
.setDocumentation("\
#icon: COMMON/openvdb\n\
#tags: vdb\n\
\n\
\"\"\"Combine the values of VDB volumes in various ways.\"\"\"\n\
\n\
@related\n\
\n\
- [Node:sop/vdbcombine]\n\
- [Node:sop/volumevop]\n\
- [Node:sop/volumemix]\n\
\n\
@examples\n\
\n\
See [openvdb.org|http://www.openvdb.org/download/] for source code\n\
and usage examples.\n");
}
////////////////////////////////////////
OP_Node*
SOP_OpenVDB_Combine::factory(OP_Network* net,
const char* name, OP_Operator* op)
{
return new SOP_OpenVDB_Combine(net, name, op);
}
SOP_OpenVDB_Combine::SOP_OpenVDB_Combine(OP_Network* net, const char* name, OP_Operator* op)
: SOP_NodeVDB(net, name, op)
{
}
////////////////////////////////////////
void
SOP_OpenVDB_Combine::resolveObsoleteParms(PRM_ParmList* obsoleteParms)
{
if (!obsoleteParms) return;
const fpreal time = 0.0;
if (PRM_Parm* parm = obsoleteParms->getParmPtr("combination")) {
if (!parm->isFactoryDefault()) {
// The "combination" choices (union, intersection, difference) from
// the old CSG SOP were appended to this SOP's "operation" list.
switch (obsoleteParms->evalInt("combination", 0, time)) {
case 0: setInt("operation", 0, 0.0, OP_UNION); break;
case 1: setInt("operation", 0, 0.0, OP_INTERSECTION); break;
case 2: setInt("operation", 0, 0.0, OP_DIFFERENCE); break;
}
}
}
{
PRM_Parm
*flatten = obsoleteParms->getParmPtr("flatten"),
*pairs = obsoleteParms->getParmPtr("pairs");
if (flatten && !flatten->isFactoryDefault()) { // factory default was Off
setString("flattenbtoa", CH_STRING_LITERAL, "collation", 0, time);
} else if (pairs && !pairs->isFactoryDefault()) { // factory default was On
setString("awithfirstb", CH_STRING_LITERAL, "collation", 0, time);
}
}
resolveRenamedParm(*obsoleteParms, "groupA", "agroup");
resolveRenamedParm(*obsoleteParms, "groupB", "bgroup");
resolveRenamedParm(*obsoleteParms, "mult_a", "amult");
resolveRenamedParm(*obsoleteParms, "mult_b", "bmult");
// Delegate to the base class.
hvdb::SOP_NodeVDB::resolveObsoleteParms(obsoleteParms);
}
// Enable or disable parameters in the UI.
bool
SOP_OpenVDB_Combine::updateParmsFlags()
{
bool changed = false;
changed |= enableParm("resampleinterp", evalInt("resample", 0, 0) != 0);
changed |= enableParm("bgtolerance", evalInt("deactivate", 0, 0) != 0);
changed |= enableParm("tolerance", evalInt("prune", 0, 0) != 0);
return changed;
}
////////////////////////////////////////
namespace {
using StringVec = std::vector<std::string>;
// Split a string into group patterns separated by whitespace.
// For example, given '@name=d* @id="1 2" {grp1 grp2}', return
// ['@name=d*', '@id="1 2"', '{grp1 grp2}'].
// (This is nonstandard. Normally, multiple patterns are unioned
// to define a single group.)
// Nesting of quotes and braces is not supported.
inline StringVec
splitPatterns(const std::string& str)
{
StringVec patterns;
bool quoted = false, braced = false;
std::string pattern;
for (const auto c: str) {
if (isspace(c)) {
if (pattern.empty()) continue; // skip whitespace between patterns
if (quoted || braced) {
pattern.push_back(c); // keep whitespace within quotes or braces
} else {
// At the end of a pattern. Start a new pattern.
patterns.push_back(pattern);
pattern.clear();
quoted = braced = false;
}
} else {
switch (c) {
case '"': quoted = !quoted; break;
case '{': braced = true; break;
case '}': braced = false; break;
default: break;
}
pattern.push_back(c);
}
}
if (!pattern.empty()) { patterns.push_back(pattern); } // add the final pattern
// If no patterns were found, add an empty pattern, which matches everything.
if (patterns.empty()) { patterns.push_back(""); }
return patterns;
}
inline UT_String
getGridName(const GU_PrimVDB* vdb, const UT_String& defaultName = "")
{
UT_String name{UT_String::ALWAYS_DEEP};
if (vdb != nullptr) {
name = vdb->getGridName();
if (!name.isstring()) name = defaultName;
}
return name;
}
} // anonymous namespace
OP_ERROR
SOP_OpenVDB_Combine::Cache::cookVDBSop(OP_Context& context)
{
try {
UT_AutoInterrupt progress{"Combining VDBs"};
mTime = context.getTime();
const Operation op = asOp(static_cast<int>(evalInt("operation", 0, getTime())));
const ResampleMode resample = asResampleMode(evalInt("resample", 0, getTime()));
const CollationMode collation = asCollation(evalStdString("collation", getTime()));
const bool
flattenA = ((collation == COLL_FLATTEN_A) || (collation == COLL_FLATTEN_A_GROUPS)),
flatten = (flattenA || (collation == COLL_FLATTEN_B_TO_A)),
needA = needAGrid(op),
needB = (needBGrid(op) && !flattenA);
GU_Detail* aGdp = gdp;
const GU_Detail* bGdp = inputGeo(1, context);
const auto aGroupStr = evalStdString("agroup", getTime());
const auto bGroupStr = evalStdString("bgroup", getTime());
const auto* bGroup = (!bGdp ? nullptr : matchGroup(*bGdp, bGroupStr));
// In Flatten A Groups mode, treat space-separated subpatterns
// as specifying distinct groups to be processed independently.
// (In all other modes, subpatterns are unioned into a single group.)
std::vector<const GA_PrimitiveGroup*> aGroupVec;
if (collation != COLL_FLATTEN_A_GROUPS) {
aGroupVec.push_back(matchGroup(*aGdp, aGroupStr));
} else {
for (const auto& pattern: splitPatterns(aGroupStr)) {
aGroupVec.push_back(matchGroup(*aGdp, pattern));
}
}
// For diagnostic purposes, keep track of whether any input grids are left unused.
bool unusedA = false, unusedB = false;
// Iterate over one or more A groups.
for (const auto* aGroup: aGroupVec) {
hvdb::VdbPrimIterator aIt{aGdp, GA_Range::safedeletions{}, aGroup};
hvdb::VdbPrimCIterator bIt{bGdp, bGroup};
// Populate two vectors of primitives, one comprising the A grids
// and the other the B grids. (In the case of flattening operations,
// these grids might be taken from the same input.)
// Note: the following relies on exhausted iterators returning nullptr
// and on incrementing an exhausted iterator being a no-op.
std::vector<GU_PrimVDB*> aVdbVec;
std::vector<const GU_PrimVDB*> bVdbVec;
switch (collation) {
case COLL_PAIRS:
for ( ; (!needA || aIt) && (!needB || bIt); ++aIt, ++bIt) {
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
}
unusedA = unusedA || (needA && bool(aIt));
unusedB = unusedB || (needB && bool(bIt));
break;
case COLL_A_WITH_1ST_B:
for ( ; aIt && (!needB || bIt); ++aIt) {
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
}
break;
case COLL_FLATTEN_B_TO_A:
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
for (++bIt; bIt; ++bIt) {
aVdbVec.push_back(nullptr);
bVdbVec.push_back(*bIt);
}
break;
case COLL_FLATTEN_A:
case COLL_FLATTEN_A_GROUPS:
aVdbVec.push_back(*aIt);
for (++aIt; aIt; ++aIt) { bVdbVec.push_back(*aIt); }
break;
}
if ((needA && aVdbVec.empty()) || (needB && bVdbVec.empty())) continue;
std::set<GU_PrimVDB*> vdbsToRemove;
// Combine grids.
if (!flatten) {
// Iterate over A and, optionally, B grids.
for (size_t i = 0, N = std::min(aVdbVec.size(), bVdbVec.size()); i < N; ++i) {
if (progress.wasInterrupted()) { throw std::runtime_error{"interrupted"}; }
// Note: even if needA is false, we still need to delete A grids.
GU_PrimVDB* aVdb = aVdbVec[i];
const GU_PrimVDB* bVdb = bVdbVec[i];
hvdb::GridPtr aGrid;
hvdb::GridCPtr bGrid;
if (aVdb) aGrid = aVdb->getGridPtr();
if (bVdb) bGrid = bVdb->getConstGridPtr();
// For error reporting, get the names of the A and B grids.
const UT_String
aGridName = getGridName(aVdb, /*default=*/"A"),
bGridName = getGridName(bVdb, /*default=*/"B");
if (hvdb::GridPtr outGrid =
combineGrids(op, aGrid, bGrid, aGridName, bGridName, resample))
{
// Name the output grid after the A grid if the A grid is used,
// or after the B grid otherwise.
UT_String outGridName = needA ? getGridName(aVdb) : getGridName(bVdb);
// Add a new VDB primitive for the output grid to the output gdp.
GU_PrimVDB::buildFromGrid(*gdp, outGrid,
/*copyAttrsFrom=*/needA ? aVdb : bVdb, outGridName);
vdbsToRemove.insert(aVdb);
}
}
// Flatten grids (i.e., combine all B grids into the first A grid).
} else {
GU_PrimVDB* aVdb = aVdbVec[0];
hvdb::GridPtr aGrid;
if (aVdb) aGrid = aVdb->getGridPtr();
hvdb::GridPtr outGrid;
UT_String outGridName;
// Iterate over B grids.
const GU_PrimVDB* bVdb = nullptr;
for (const GU_PrimVDB* theBVdb: bVdbVec) {
if (progress.wasInterrupted()) { throw std::runtime_error{"interrupted"}; }
bVdb = theBVdb;
hvdb::GridCPtr bGrid;
if (bVdb) {
bGrid = bVdb->getConstGridPtr();
if (flattenA) {
// When flattening within the A group, remove B grids,
// since they're actually copies of grids from input 0.
vdbsToRemove.insert(const_cast<GU_PrimVDB*>(bVdb));
}
}
const UT_String
aGridName = getGridName(aVdb, /*default=*/"A"),
bGridName = getGridName(bVdb, /*default=*/"B");
// Name the output grid after the A grid if the A grid is used,
// or after the B grid otherwise.
outGridName = (needA ? getGridName(aVdb) : getGridName(bVdb));
outGrid = combineGrids(op, aGrid, bGrid, aGridName, bGridName, resample);
aGrid = outGrid;
}
if (outGrid) {
// Add a new VDB primitive for the output grid to the output gdp.
GU_PrimVDB::buildFromGrid(*gdp, outGrid,
/*copyAttrsFrom=*/needA ? aVdb : bVdb, outGridName);
vdbsToRemove.insert(aVdb);
}
}
// Remove primitives that were copied from input 0.
for (GU_PrimVDB* vdb: vdbsToRemove) {
gdp->destroyPrimitive(*vdb, /*andPoints=*/true);
}
} // for each A group
if (unusedA || unusedB) {
std::ostringstream ostr;
ostr << "some grids were not processed because there were more "
<< (unusedA ? "A" : "B") << " grids than "
<< (unusedA ? "B" : "A") << " grids";
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} catch (std::exception& e) {
addError(SOP_MESSAGE, e.what());
}
return error();
}
////////////////////////////////////////
namespace {
/// Functor to compute scale * grid + offset, for scalars scale and offset
template<typename GridT>
struct MulAdd
{
using ValueT = typename GridT::ValueType;
using GridPtrT = typename GridT::Ptr;
float scale, offset;
explicit MulAdd(float s, float t = 0.0): scale(s), offset(t) {}
void operator()(const ValueT& a, const ValueT&, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT(a * scale + offset);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
/// @return true if the scale is 1 and the offset is 0
bool isIdentity() const
{
return (openvdb::math::isApproxEqual(scale, 1.f, 1.0e-6f)
&& openvdb::math::isApproxEqual(offset, 0.f, 1.0e-6f));
}
/// Compute dest = src * scale + offset
void process(const GridT& src, GridPtrT& dest) const
{
if (isIdentity()) {
dest = src.deepCopy();
} else {
if (!dest) dest = GridT::create(src); // same transform, new tree
ValueT bg;
(*this)(src.background(), ValueT(), bg);
openvdb::tools::changeBackground(dest->tree(), bg);
dest->tree().combine2(src.tree(), src.tree(), *this, /*prune=*/false);
}
}
};
////////////////////////////////////////
/// Functor to compute (1 - A) * B for grids A and B
template<typename ValueT>
struct Blend1
{
float aMult, bMult;
const ValueT ONE;
explicit Blend1(float a = 1.0, float b = 1.0):
aMult(a), bMult(b), ONE(openvdb::zeroVal<ValueT>() + 1) {}
void operator()(const ValueT& a, const ValueT& b, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT((ONE - aMult * a) * bMult * b);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
};
////////////////////////////////////////
/// Functor to compute A + (1 - A) * B for grids A and B
template<typename ValueT>
struct Blend2
{
float aMult, bMult;
const ValueT ONE;
explicit Blend2(float a = 1.0, float b = 1.0):
aMult(a), bMult(b), ONE(openvdb::zeroVal<ValueT>() + 1) {}
void operator()(const ValueT& a, const ValueT& b, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT(a*aMult); out = out + ValueT((ONE - out) * bMult*b);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
};
////////////////////////////////////////
// Helper class to compare both scalar and vector values
template<typename ValueT>
struct ApproxEq
{
const ValueT &a, &b;
ApproxEq(const ValueT& _a, const ValueT& _b): a(_a), b(_b) {}
operator bool() const {
return openvdb::math::isRelOrApproxEqual(
a, b, /*rel*/ValueT(1e-6f), /*abs*/ValueT(1e-8f));
}
};
// Specialization for Vec2
template<typename T>
struct ApproxEq<openvdb::math::Vec2<T> >
{
using VecT = openvdb::math::Vec2<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
// Specialization for Vec3
template<typename T>
struct ApproxEq<openvdb::math::Vec3<T> >
{
using VecT = openvdb::math::Vec3<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
// Specialization for Vec4
template<typename T>
struct ApproxEq<openvdb::math::Vec4<T> >
{
using VecT = openvdb::math::Vec4<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
} // unnamed namespace
////////////////////////////////////////
template<typename AGridT>
struct SOP_OpenVDB_Combine::DispatchOp
{
SOP_OpenVDB_Combine::CombineOp* combineOp;
DispatchOp(SOP_OpenVDB_Combine::CombineOp& op): combineOp(&op) {}
template<typename BGridT> void operator()(typename BGridT::ConstPtr);
}; // struct DispatchOp
// Helper class for use with UTvdbProcessTypedGrid()
struct SOP_OpenVDB_Combine::CombineOp
{
SOP_OpenVDB_Combine::Cache* self;
Operation op;
ResampleMode resample;
UT_String aGridName, bGridName;
hvdb::GridCPtr aBaseGrid, bBaseGrid;
hvdb::GridPtr outGrid;
hvdb::Interrupter interrupt;
CombineOp(): self(nullptr) {}
// Functor for use with UTvdbProcessTypedGridScalar() to return
// a scalar grid's background value as a floating-point quantity
struct BackgroundOp {
double value;
BackgroundOp(): value(0.0) {}
template<typename GridT> void operator()(const GridT& grid) {
value = static_cast<double>(grid.background());
}
};
static double getScalarBackgroundValue(const hvdb::Grid& baseGrid)
{
BackgroundOp bgOp;
UTvdbProcessTypedGridScalar(UTvdbGetGridType(baseGrid), baseGrid, bgOp);
return bgOp.value;
}
template<typename GridT>
typename GridT::Ptr resampleToMatch(const GridT& src, const hvdb::Grid& ref, int order)
{
using ValueT = typename GridT::ValueType;
const ValueT ZERO = openvdb::zeroVal<ValueT>();
const openvdb::math::Transform& refXform = ref.constTransform();
typename GridT::Ptr dest;
if (src.getGridClass() == openvdb::GRID_LEVEL_SET) {
// For level set grids, use the level set rebuild tool to both resample the
// source grid to match the reference grid and to rebuild the resulting level set.
const bool refIsLevelSet = ref.getGridClass() == openvdb::GRID_LEVEL_SET;
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT halfWidth = refIsLevelSet
? ValueT(ZERO + this->getScalarBackgroundValue(ref) * (1.0 / ref.voxelSize()[0]))
: ValueT(src.background() * (1.0 / src.voxelSize()[0]));
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
if (!openvdb::math::isFinite(halfWidth)) {
std::stringstream msg;
msg << "Resample to match: Illegal narrow band width = " << halfWidth
<< ", caused by grid '" << src.getName() << "' with background "
<< this->getScalarBackgroundValue(ref);
throw std::invalid_argument(msg.str());
}
try {
dest = openvdb::tools::doLevelSetRebuild(src, /*iso=*/ZERO,
/*exWidth=*/halfWidth, /*inWidth=*/halfWidth, &refXform, &interrupt);
} catch (openvdb::TypeError&) {
self->addWarning(SOP_MESSAGE, ("skipped rebuild of level set grid "
+ src.getName() + " of type " + src.type()).c_str());
dest.reset();
}
}
if (!dest && src.constTransform() != refXform) {
// For non-level set grids or if level set rebuild failed due to an unsupported
// grid type, use the grid transformer tool to resample the source grid to match
// the reference grid.
#if OPENVDB_ABI_VERSION_NUMBER <= 3
dest = src.copy(openvdb::CP_NEW);
#else
dest = src.copyWithNewTree();
#endif
dest->setTransform(refXform.copy());
using namespace openvdb;
switch (order) {
case 0: tools::resampleToMatch<tools::PointSampler>(src, *dest, interrupt); break;
case 1: tools::resampleToMatch<tools::BoxSampler>(src, *dest, interrupt); break;
case 2: tools::resampleToMatch<tools::QuadraticSampler>(src, *dest, interrupt); break;
}
}
return dest;
}
// If necessary, resample one grid so that its index space registers
// with the other grid's.
// Note that one of the grid pointers might change as a result.
template<typename AGridT, typename BGridT>
void resampleGrids(const AGridT*& aGrid, const BGridT*& bGrid)
{
if (!aGrid || !bGrid) return;
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needBoth = needA && needB;
const int samplingOrder = static_cast<int>(
self->evalInt("resampleinterp", 0, self->getTime()));
// One of RESAMPLE_A, RESAMPLE_B or RESAMPLE_OFF, specifying whether
// grid A, grid B or neither grid was resampled
int resampleWhich = RESAMPLE_OFF;
// Determine which of the two grids should be resampled.
if (resample == RESAMPLE_HI_RES || resample == RESAMPLE_LO_RES) {
const openvdb::Vec3d
aVoxSize = aGrid->voxelSize(),
bVoxSize = bGrid->voxelSize();
const double
aVoxVol = aVoxSize[0] * aVoxSize[1] * aVoxSize[2],
bVoxVol = bVoxSize[0] * bVoxSize[1] * bVoxSize[2];
resampleWhich = ((aVoxVol > bVoxVol && resample == RESAMPLE_LO_RES)
|| (aVoxVol < bVoxVol && resample == RESAMPLE_HI_RES))
? RESAMPLE_A : RESAMPLE_B;
} else {
resampleWhich = resample;
}
if (aGrid->constTransform() != bGrid->constTransform()) {
// If the A and B grid transforms don't match, one of the grids
// should be resampled into the other's index space.
if (resample == RESAMPLE_OFF) {
if (needBoth) {
// Resampling is disabled. Just log a warning.
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName << " transforms don't match";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} else {
if (needA && resampleWhich == RESAMPLE_A) {
// Resample grid A into grid B's index space.
aBaseGrid = this->resampleToMatch(*aGrid, *bGrid, samplingOrder);
aGrid = static_cast<const AGridT*>(aBaseGrid.get());
} else if (needB && resampleWhich == RESAMPLE_B) {
// Resample grid B into grid A's index space.
bBaseGrid = this->resampleToMatch(*bGrid, *aGrid, samplingOrder);
bGrid = static_cast<const BGridT*>(bBaseGrid.get());
}
}
}
if (aGrid->getGridClass() == openvdb::GRID_LEVEL_SET &&
bGrid->getGridClass() == openvdb::GRID_LEVEL_SET)
{
// If both grids are level sets, ensure that their background values match.
// (If one of the grids was resampled, then the background values should
// already match.)
const double
a = this->getScalarBackgroundValue(*aGrid),
b = this->getScalarBackgroundValue(*bGrid);
if (!ApproxEq<double>(a, b)) {
if (resample == RESAMPLE_OFF) {
if (needBoth) {
// Resampling/rebuilding is disabled. Just log a warning.
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName
<< " background values don't match ("
<< std::setprecision(3) << a << " vs. " << b << ");\n"
<< " the output grid will not be a valid level set";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} else {
// One of the two grids needs a level set rebuild.
if (needA && resampleWhich == RESAMPLE_A) {
// Rebuild A to match B's background value.
aBaseGrid = this->resampleToMatch(*aGrid, *bGrid, samplingOrder);
aGrid = static_cast<const AGridT*>(aBaseGrid.get());
} else if (needB && resampleWhich == RESAMPLE_B) {
// Rebuild B to match A's background value.
bBaseGrid = this->resampleToMatch(*bGrid, *aGrid, samplingOrder);
bGrid = static_cast<const BGridT*>(bBaseGrid.get());
}
}
}
}
}
void checkVectorTypes(const hvdb::Grid* aGrid, const hvdb::Grid* bGrid)
{
if (!aGrid || !bGrid || !needAGrid(op) || !needBGrid(op)) return;
switch (op) {
case OP_TOPO_UNION:
case OP_TOPO_INTERSECTION:
case OP_TOPO_DIFFERENCE:
// No need to warn about different vector types for topology-only operations.
break;
default:
{
const openvdb::VecType
aVecType = aGrid->getVectorType(),
bVecType = bGrid->getVectorType();
if (aVecType != bVecType) {
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName
<< " have different vector types\n"
<< " (" << hvdb::Grid::vecTypeToString(aVecType)
<< " vs. " << hvdb::Grid::vecTypeToString(bVecType) << ")";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
break;
}
}
}
// Combine two grids of the same type.
template<typename GridT>
void combineSameType()
{
using ValueT = typename GridT::ValueType;
const bool
needA = needAGrid(op),
needB = needBGrid(op);
const float
aMult = float(self->evalFloat("amult", 0, self->getTime())),
bMult = float(self->evalFloat("bmult", 0, self->getTime()));
const GridT *aGrid = nullptr, *bGrid = nullptr;
if (aBaseGrid) aGrid = UTvdbGridCast<GridT>(aBaseGrid).get();
if (bBaseGrid) bGrid = UTvdbGridCast<GridT>(bBaseGrid).get();
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
// Warn if combining vector grids with different vector types.
if (needA && needB && openvdb::VecTraits<ValueT>::IsVec) {
this->checkVectorTypes(aGrid, bGrid);
}
// If necessary, resample one grid so that its index space
// registers with the other grid's.
if (aGrid && bGrid) this->resampleGrids(aGrid, bGrid);
const ValueT ZERO = openvdb::zeroVal<ValueT>();
// A temporary grid is needed for binary operations, because they
// cannibalize the B grid.
typename GridT::Ptr resultGrid, tempGrid;
switch (op) {
case OP_COPY_A:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
break;
case OP_COPY_B:
MulAdd<GridT>(bMult).process(*bGrid, resultGrid);
break;
case OP_INVERT:
MulAdd<GridT>(-aMult, 1.0).process(*aGrid, resultGrid);
break;
case OP_ADD:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compSum(*resultGrid, *tempGrid);
break;
case OP_SUBTRACT:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(-bMult).process(*bGrid, tempGrid);
openvdb::tools::compSum(*resultGrid, *tempGrid);
break;
case OP_MULTIPLY:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMul(*resultGrid, *tempGrid);
break;
case OP_DIVIDE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compDiv(*resultGrid, *tempGrid);
break;
case OP_MAXIMUM:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMax(*resultGrid, *tempGrid);
break;
case OP_MINIMUM:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMin(*resultGrid, *tempGrid);
break;
case OP_BLEND1: // (1 - A) * B
{
const Blend1<ValueT> comp(aMult, bMult);
ValueT bg;
comp(aGrid->background(), ZERO, bg);
#if OPENVDB_ABI_VERSION_NUMBER <= 3
resultGrid = aGrid->copy(/*tree=*/openvdb::CP_NEW);
#else
resultGrid = aGrid->copyWithNewTree();
#endif
openvdb::tools::changeBackground(resultGrid->tree(), bg);
resultGrid->tree().combine2(aGrid->tree(), bGrid->tree(), comp, /*prune=*/false);
break;
}
case OP_BLEND2: // A + (1 - A) * B
{
const Blend2<ValueT> comp(aMult, bMult);
ValueT bg;
comp(aGrid->background(), ZERO, bg);
#if OPENVDB_ABI_VERSION_NUMBER <= 3
resultGrid = aGrid->copy(/*tree=*/openvdb::CP_NEW);
#else
resultGrid = aGrid->copyWithNewTree();
#endif
openvdb::tools::changeBackground(resultGrid->tree(), bg);
resultGrid->tree().combine2(aGrid->tree(), bGrid->tree(), comp, /*prune=*/false);
break;
}
case OP_UNION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgUnion(*resultGrid, *tempGrid);
break;
case OP_INTERSECTION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgIntersection(*resultGrid, *tempGrid);
break;
case OP_DIFFERENCE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgDifference(*resultGrid, *tempGrid);
break;
case OP_REPLACE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compReplace(*resultGrid, *tempGrid);
break;
case OP_TOPO_UNION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
// Note: no need to scale the B grid for topology-only operations.
resultGrid->topologyUnion(*bGrid);
break;
case OP_TOPO_INTERSECTION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyIntersection(*bGrid);
break;
case OP_TOPO_DIFFERENCE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyDifference(*bGrid);
break;
}
outGrid = this->postprocess<GridT>(resultGrid);
}
// Combine two grids of different types.
/// @todo Currently, only topology operations can be performed on grids of different types.
template<typename AGridT, typename BGridT>
void combineDifferentTypes()
{
const bool
needA = needAGrid(op),
needB = needBGrid(op);
const AGridT* aGrid = nullptr;
const BGridT* bGrid = nullptr;
if (aBaseGrid) aGrid = UTvdbGridCast<AGridT>(aBaseGrid).get();
if (bBaseGrid) bGrid = UTvdbGridCast<BGridT>(bBaseGrid).get();
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
// Warn if combining vector grids with different vector types.
if (needA && needB && openvdb::VecTraits<typename AGridT::ValueType>::IsVec
&& openvdb::VecTraits<typename BGridT::ValueType>::IsVec)
{
this->checkVectorTypes(aGrid, bGrid);
}
// If necessary, resample one grid so that its index space
// registers with the other grid's.
if (aGrid && bGrid) this->resampleGrids(aGrid, bGrid);
const float aMult = float(self->evalFloat("amult", 0, self->getTime()));
typename AGridT::Ptr resultGrid;
switch (op) {
case OP_TOPO_UNION:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
// Note: no need to scale the B grid for topology-only operations.
resultGrid->topologyUnion(*bGrid);
break;
case OP_TOPO_INTERSECTION:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyIntersection(*bGrid);
break;
case OP_TOPO_DIFFERENCE:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyDifference(*bGrid);
break;
default:
{
std::ostringstream ostr;
ostr << "can't combine grid " << aGridName << " of type " << aGrid->type()
<< "\n with grid " << bGridName
<< " of type " << bGrid->type();
throw std::runtime_error(ostr.str());
break;
}
}
outGrid = this->postprocess<AGridT>(resultGrid);
}
template<typename GridT>
typename GridT::Ptr postprocess(typename GridT::Ptr resultGrid)
{
using ValueT = typename GridT::ValueType;
const ValueT ZERO = openvdb::zeroVal<ValueT>();
const bool
prune = self->evalInt("prune", 0, self->getTime()),
flood = self->evalInt("flood", 0, self->getTime()),
deactivate = self->evalInt("deactivate", 0, self->getTime());
if (deactivate) {
const float deactivationTolerance =
float(self->evalFloat("bgtolerance", 0, self->getTime()));
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT tolerance(ZERO + deactivationTolerance);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
// Mark active output tiles and voxels as inactive if their
// values match the output grid's background value.
// Do this first to facilitate pruning.
openvdb::tools::deactivate(*resultGrid, resultGrid->background(), tolerance);
}
if (flood && resultGrid->getGridClass() == openvdb::GRID_LEVEL_SET) {
openvdb::tools::signedFloodFill(resultGrid->tree());
}
if (prune) {
const float pruneTolerance = float(self->evalFloat("tolerance", 0, self->getTime()));
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT tolerance(ZERO + pruneTolerance);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
openvdb::tools::prune(resultGrid->tree(), tolerance);
}
return resultGrid;
}
template<typename AGridT>
void operator()(typename AGridT::ConstPtr)
{
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needBoth = needA && needB;
if (!needBoth || !aBaseGrid || !bBaseGrid || aBaseGrid->type() == bBaseGrid->type()) {
this->combineSameType<AGridT>();
} else {
DispatchOp<AGridT> dispatcher(*this);
// Dispatch on the B grid's type.
int success = UTvdbProcessTypedGridTopology(
UTvdbGetGridType(*bBaseGrid), bBaseGrid, dispatcher);
if (!success) {
std::ostringstream ostr;
ostr << "grid " << bGridName << " has unsupported type " << bBaseGrid->type();
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
}
}
}; // struct CombineOp
template<typename AGridT>
template<typename BGridT>
void
SOP_OpenVDB_Combine::DispatchOp<AGridT>::operator()(typename BGridT::ConstPtr)
{
combineOp->combineDifferentTypes<AGridT, BGridT>();
}
////////////////////////////////////////
hvdb::GridPtr
SOP_OpenVDB_Combine::Cache::combineGrids(
Operation op,
hvdb::GridCPtr aGrid,
hvdb::GridCPtr bGrid,
const UT_String& aGridName,
const UT_String& bGridName,
ResampleMode resample)
{
hvdb::GridPtr outGrid;
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needLS = needLevelSets(op);
if (!needA && !needB) throw std::runtime_error("nothing to do");
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
if (needLS &&
((aGrid && aGrid->getGridClass() != openvdb::GRID_LEVEL_SET) ||
(bGrid && bGrid->getGridClass() != openvdb::GRID_LEVEL_SET)))
{
std::ostringstream ostr;
ostr << "expected level set grids for the " << sOpMenuItems[op*2+1]
<< " operation,\n found "
<< hvdb::Grid::gridClassToString(aGrid->getGridClass()) << " (" << aGridName << ") and "
<< hvdb::Grid::gridClassToString(bGrid->getGridClass()) << " (" << bGridName
<< ");\n the output grid will not be a valid level set";
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
if (needA && needB && aGrid->type() != bGrid->type()
&& op != OP_TOPO_UNION && op != OP_TOPO_INTERSECTION && op != OP_TOPO_DIFFERENCE)
{
std::ostringstream ostr;
ostr << "can't combine grid " << aGridName << " of type " << aGrid->type()
<< "\n with grid " << bGridName << " of type " << bGrid->type();
addWarning(SOP_MESSAGE, ostr.str().c_str());
return outGrid;
}
CombineOp compOp;
compOp.self = this;
compOp.op = op;
compOp.resample = resample;
compOp.aBaseGrid = aGrid;
compOp.bBaseGrid = bGrid;
compOp.aGridName = aGridName;
compOp.bGridName = bGridName;
compOp.interrupt = hvdb::Interrupter();
int success = UTvdbProcessTypedGridTopology(
UTvdbGetGridType(needA ? *aGrid : *bGrid), aGrid, compOp);
if (!success || !compOp.outGrid) {
std::ostringstream ostr;
if (aGrid->type() == bGrid->type()) {
ostr << "grids " << aGridName << " and " << bGridName
<< " have unsupported type " << aGrid->type();
} else {
ostr << "grid " << (needA ? aGridName : bGridName)
<< " has unsupported type " << (needA ? aGrid->type() : bGrid->type());
}
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
return compOp.outGrid;
}
// Copyright (c) DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
It is quite possible to end up with null vdbs in our vdbsToRemove
if needA or needB is false. In particular, Copy B will do this
if the destination is not a VDB and the source is. Since
dereferencing NULL is bad and will crash, do not try to destroy
primitives that are NULL.
Signed-off-by: jlait <81974a1ed0c0d66870f9fb02ff829ce3f8e53fdd@andorra.sidefx.com>
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// * Neither the name of DreamWorks Animation 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 THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY 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.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
//
/// @file SOP_OpenVDB_Combine.cc
///
/// @author FX R&D OpenVDB team
#include <houdini_utils/ParmFactory.h>
#include <openvdb_houdini/Utils.h>
#include <openvdb_houdini/SOP_NodeVDB.h>
#include <openvdb/math/Math.h> // for isFinite()
#include <openvdb/tools/ChangeBackground.h>
#include <openvdb/tools/Composite.h>
#include <openvdb/tools/GridTransformer.h> // for resampleToMatch()
#include <openvdb/tools/LevelSetRebuild.h> // for levelSetRebuild()
#include <openvdb/tools/Morphology.h> // for deactivate()
#include <openvdb/tools/Prune.h>
#include <openvdb/tools/SignedFloodFill.h>
#include <openvdb/util/NullInterrupter.h>
#include <PRM/PRM_Parm.h>
#include <UT/UT_Interrupt.h>
#include <UT/UT_Version.h>
#include <algorithm> // for std::min()
#include <cctype> // for isspace()
#include <iomanip>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace hvdb = openvdb_houdini;
namespace hutil = houdini_utils;
namespace {
//
// Operations
//
enum Operation {
OP_COPY_A, // A
OP_COPY_B, // B
OP_INVERT, // 1 - A
OP_ADD, // A + B
OP_SUBTRACT, // A - B
OP_MULTIPLY, // A * B
OP_DIVIDE, // A / B
OP_MAXIMUM, // max(A, B)
OP_MINIMUM, // min(A, B)
OP_BLEND1, // (1 - A) * B
OP_BLEND2, // A + (1 - A) * B
OP_UNION, // CSG A u B
OP_INTERSECTION, // CSG A n B
OP_DIFFERENCE, // CSG A / B
OP_REPLACE, // replace A with B
OP_TOPO_UNION, // A u active(B)
OP_TOPO_INTERSECTION, // A n active(B)
OP_TOPO_DIFFERENCE // A / active(B)
};
enum { OP_FIRST = OP_COPY_A, OP_LAST = OP_TOPO_DIFFERENCE };
//#define TIMES " \xd7 " // ISO-8859 multiplication symbol
#define TIMES " * "
const char* const sOpMenuItems[] = {
"copya", "Copy A",
"copyb", "Copy B",
"inverta", "Invert A",
"add", "Add",
"subtract", "Subtract",
"multiply", "Multiply",
"divide", "Divide",
"maximum", "Maximum",
"minimum", "Minimum",
"compatimesb", "(1 - A)" TIMES "B",
"apluscompatimesb", "A + (1 - A)" TIMES "B",
"sdfunion", "SDF Union",
"sdfintersect", "SDF Intersection",
"sdfdifference", "SDF Difference",
"replacewithactive", "Replace A with Active B",
"topounion", "Activity Union",
"topointersect", "Activity Intersection",
"topodifference", "Activity Difference",
nullptr
};
#undef TIMES
inline Operation
asOp(int i, Operation defaultOp = OP_COPY_A)
{
return (i >= OP_FIRST && i <= OP_LAST)
? static_cast<Operation>(i) : defaultOp;
}
inline bool needAGrid(Operation op) { return (op != OP_COPY_B); }
inline bool needBGrid(Operation op) { return (op != OP_COPY_A && op != OP_INVERT); }
inline bool needLevelSets(Operation op)
{
return (op == OP_UNION || op == OP_INTERSECTION || op == OP_DIFFERENCE);
}
//
// Resampling options
//
enum ResampleMode {
RESAMPLE_OFF, // don't auto-resample grids
RESAMPLE_B, // resample B to match A
RESAMPLE_A, // resample A to match B
RESAMPLE_HI_RES, // resample higher-res grid to match lower-res
RESAMPLE_LO_RES // resample lower-res grid to match higher-res
};
enum { RESAMPLE_MODE_FIRST = RESAMPLE_OFF, RESAMPLE_MODE_LAST = RESAMPLE_LO_RES };
const char* const sResampleModeMenuItems[] = {
"off", "Off",
"btoa", "B to Match A",
"atob", "A to Match B",
"hitolo", "Higher-res to Match Lower-res",
"lotohi", "Lower-res to Match Higher-res",
nullptr
};
inline ResampleMode
asResampleMode(exint i, ResampleMode defaultMode = RESAMPLE_B)
{
return (i >= RESAMPLE_MODE_FIRST && i <= RESAMPLE_MODE_LAST)
? static_cast<ResampleMode>(i) : defaultMode;
}
//
// Collation options
//
enum CollationMode {
COLL_PAIRS = 0,
COLL_A_WITH_1ST_B,
COLL_FLATTEN_A,
COLL_FLATTEN_B_TO_A,
COLL_FLATTEN_A_GROUPS
};
inline CollationMode
asCollation(const std::string& str)
{
if (str == "pairs") return COLL_PAIRS;
if (str == "awithfirstb") return COLL_A_WITH_1ST_B;
if (str == "flattena") return COLL_FLATTEN_A;
if (str == "flattenbtoa") return COLL_FLATTEN_B_TO_A;
if (str == "flattenagroups") return COLL_FLATTEN_A_GROUPS;
throw std::runtime_error{"invalid collation mode \"" + str + "\""};
}
} // anonymous namespace
/// @brief SOP to combine two VDB grids via various arithmetic operations
class SOP_OpenVDB_Combine: public hvdb::SOP_NodeVDB
{
public:
SOP_OpenVDB_Combine(OP_Network*, const char* name, OP_Operator*);
~SOP_OpenVDB_Combine() override {}
static OP_Node* factory(OP_Network*, const char*, OP_Operator*);
class Cache: public SOP_VDBCacheOptions
{
public:
fpreal getTime() const { return mTime; }
protected:
OP_ERROR cookVDBSop(OP_Context&) override;
private:
hvdb::GridPtr combineGrids(Operation,
hvdb::GridCPtr aGrid, hvdb::GridCPtr bGrid,
const UT_String& aGridName, const UT_String& bGridName,
ResampleMode resample);
fpreal mTime = 0.0;
}; // class Cache
protected:
bool updateParmsFlags() override;
void resolveObsoleteParms(PRM_ParmList*) override;
private:
template<typename> struct DispatchOp;
struct CombineOp;
};
////////////////////////////////////////
void
newSopOperator(OP_OperatorTable* table)
{
if (table == nullptr) return;
hutil::ParmList parms;
// Group A
parms.add(hutil::ParmFactory(PRM_STRING, "agroup", "Group A")
.setChoiceList(&hutil::PrimGroupMenuInput1)
.setTooltip("Use a subset of the first input as the A VDB(s).")
.setDocumentation(
"The VDBs to be used from the first input"
" (see [specifying volumes|/model/volumes#group])"));
// Group B
parms.add(hutil::ParmFactory(PRM_STRING, "bgroup", "Group B")
.setChoiceList(&hutil::PrimGroupMenuInput2)
.setTooltip("Use a subset of the second input as the B VDB(s).")
.setDocumentation(
"The VDBs to be used from the second input"
" (see [specifying volumes|/model/volumes#group])"));
parms.add(hutil::ParmFactory(PRM_STRING, "collation", "Collation")
.setChoiceListItems(PRM_CHOICELIST_SINGLE, {
"pairs", "Combine A/B Pairs",
"awithfirstb", "Combine Each A With First B",
"flattena", "Flatten All A",
"flattenbtoa", "Flatten All B Into First A",
"flattenagroups", "Flatten A Groups"
})
.setDefault("pairs")
.setTooltip("Specify the order in which to combine VDBs from the A and/or B groups.")
.setDocumentation("\
The order in which to combine VDBs from the _A_ and/or _B_ groups\n\
\n\
Combine _A_/_B_ Pairs:\n\
Combine pairs of _A_ and _B_ VDBs, in the order in which they appear\n\
in their respective groups.\n\
Combine Each _A_ With First _B_:\n\
Combine each _A_ VDB with the first _B_ VDB.\n\
Flatten All _A_:\n\
Collapse all of the _A_ VDBs into a single output VDB.\n\
Flatten All _B_ Into First _A_:\n\
Accumulate each _B_ VDB into the first _A_ VDB, producing a single output VDB.\n\
Flatten _A_ Groups:\n\
Collapse VDBs within each _A_ group, producing one output VDB for each group.\n\
\n\
Space-separated group patterns are treated as distinct groups in this mode.\n\
For example, \"`@name=x* @name=y*`\" results in two output VDBs\n\
(provided that there is at least one _A_ VDB whose name starts with `x`\n\
and at least one whose name starts with `y`).\n\
"));
// Menu of available operations
parms.add(hutil::ParmFactory(PRM_ORD, "operation", "Operation")
.setDefault(PRMzeroDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, sOpMenuItems)
.setDocumentation("\
Each voxel that is active in either of the input VDBs\n\
will be processed with this operation.\n\
\n\
Copy _A_:\n\
Use _A_, ignore _B_.\n\
\n\
Copy _B_:\n\
Use _B_, ignore _A_.\n\
\n\
Invert _A_:\n\
Use 0 − _A_.\n\
\n\
Add:\n\
Add the values of _A_ and _B_.\n\
\n\
NOTE:\n\
Using this for fog volumes, which have density values between 0 and 1,\n\
will push densities over 1 and cause a bright interface between the\n\
input volumes when rendered. To avoid this problem, try using the\n\
_A_ + (1 − _A_) × _B_\n\
operation.\n\
\n\
Subtract:\n\
Subtract the values of _B_ from the values of _A_.\n\
\n\
Multiply:\n\
Multiply the values of _A_ and _B_.\n\
\n\
Divide:\n\
Divide the values of _A_ by _B_.\n\
\n\
Maximum:\n\
Use the maximum of each corresponding value from _A_ and _B_.\n\
\n\
NOTE:\n\
Using this for fog volumes, which have density values between 0 and 1,\n\
can produce a dark interface between the inputs when rendered, due to\n\
the binary nature of choosing a value from either from _A_ or _B_.\n\
To avoid this problem, try using the\n\
(1 − _A_) × _B_ operation.\n\
\n\
Minimum:\n\
Use the minimum of each corresponding value from _A_ and _B_.\n\
\n\
(1 − _A_) × _B_:\n\
This is similar to SDF Difference, except for fog volumes,\n\
and can also be viewed as \"soft cutout\" operation.\n\
It is typically used to clear out an area around characters\n\
in a dust simulation or some other environmental volume.\n\
\n\
_A_ + (1 − _A_) × _B_:\n\
This is similar to SDF Union, except for fog volumes, and\n\
can also be viewed as a \"soft union\" or \"merge\" operation.\n\
Consider using this over the Maximum or Add operations\n\
for fog volumes.\n\
\n\
SDF Union:\n\
Generate the union of signed distance fields _A_ and _B_.\n\
\n\
SDF Intersection:\n\
Generate the intersection of signed distance fields _A_ and _B_.\n\
\n\
SDF Difference:\n\
Remove signed distance field _B_ from signed distance field _A_.\n\
\n\
Replace _A_ with Active _B_:\n\
Copy the active voxels of _B_ into _A_.\n\
\n\
Activity Union:\n\
Make voxels active if they are active in either _A_ or _B_.\n\
\n\
Activity Intersection:\n\
Make voxels active if they are active in both _A_ and _B_.\n\
\n\
It is recommended to enable pruning when using this operation.\n\
\n\
Activity Difference:\n\
Make voxels active if they are active in _A_ but not in _B_.\n\
\n\
It is recommended to enable pruning when using this operation.\n"));
// Scalar multiplier on the A grid
parms.add(hutil::ParmFactory(PRM_FLT_J, "amult", "A Multiplier")
.setDefault(PRMoneDefaults)
.setRange(PRM_RANGE_UI, -10, PRM_RANGE_UI, 10)
.setTooltip(
"Multiply voxel values in the A VDB by a scalar\n"
"before combining the A VDB with the B VDB."));
// Scalar multiplier on the B grid
parms.add(hutil::ParmFactory(PRM_FLT_J, "bmult", "B Multiplier")
.setDefault(PRMoneDefaults)
.setRange(PRM_RANGE_UI, -10, PRM_RANGE_UI, 10)
.setTooltip(
"Multiply voxel values in the B VDB by a scalar\n"
"before combining the A VDB with the B VDB."));
// Menu of resampling options
parms.add(hutil::ParmFactory(PRM_ORD, "resample", "Resample")
.setDefault(PRMoneDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, sResampleModeMenuItems)
.setTooltip(
"If the A and B VDBs have different transforms, one VDB should\n"
"be resampled to match the other before the two are combined.\n"
"Also, level set VDBs should have matching background values\n"
"(i.e., matching narrow band widths)."));
// Menu of resampling interpolation order options
parms.add(hutil::ParmFactory(PRM_ORD, "resampleinterp", "Interpolation")
.setDefault(PRMoneDefaults)
.setChoiceListItems(PRM_CHOICELIST_SINGLE, {
"point", "Nearest",
"linear", "Linear",
"quadratic", "Quadratic"
})
.setTooltip(
"Specify the type of interpolation to be used when\n"
"resampling one VDB to match the other's transform.")
.setDocumentation(
"The type of interpolation to be used when resampling one VDB"
" to match the other's transform\n\n"
"Nearest neighbor interpolation is fast but can introduce noticeable"
" sampling artifacts. Quadratic interpolation is slow but high-quality."
" Linear interpolation is intermediate in speed and quality."));
// Deactivate background value toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "deactivate", "Deactivate Background Voxels")
.setDefault(PRMzeroDefaults)
.setTypeExtended(PRM_TYPE_TOGGLE_JOIN)
.setDocumentation(
"Deactivate active output voxels whose values equal"
" the output VDB's background value."));
// Deactivation tolerance slider
parms.add(hutil::ParmFactory(PRM_FLT_J, "bgtolerance", "Deactivate Tolerance")
.setDefault(PRMzeroDefaults)
.setRange(PRM_RANGE_RESTRICTED, 0, PRM_RANGE_UI, 1)
.setTooltip(
"Deactivate active output voxels whose values\n"
"equal the output VDB's background value.\n"
"Voxel values are considered equal if they differ\n"
"by less than the specified tolerance.")
.setDocumentation(
"When deactivation of background voxels is enabled,"
" voxel values are considered equal to the background"
" if they differ by less than this tolerance."));
// Prune toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "prune", "Prune")
.setDefault(PRMoneDefaults)
.setTypeExtended(PRM_TYPE_TOGGLE_JOIN)
.setDocumentation(
"Reduce the memory footprint of output VDBs that have"
" (sufficiently large) regions of voxels with the same value.\n\n"
"NOTE:\n"
" Pruning affects only the memory usage of a VDB.\n"
" It does not remove voxels, apart from inactive voxels\n"
" whose value is equal to the background."));
// Pruning tolerance slider
parms.add(hutil::ParmFactory(PRM_FLT_J, "tolerance", "Prune Tolerance")
.setDefault(PRMzeroDefaults)
.setRange(PRM_RANGE_RESTRICTED, 0, PRM_RANGE_UI, 1)
.setTooltip(
"Collapse regions of constant value in output VDBs.\n"
"Voxel values are considered equal if they differ\n"
"by less than the specified tolerance.")
.setDocumentation(
"When pruning is enabled, voxel values are considered equal"
" if they differ by less than the specified tolerance."));
// Flood fill toggle
parms.add(hutil::ParmFactory(PRM_TOGGLE, "flood", "Signed-Flood-Fill Output SDFs")
.setDefault(PRMzeroDefaults)
.setTooltip(
"Reclassify inactive voxels of level set VDBs as either inside or outside.")
.setDocumentation(
"Test inactive voxels to determine if they are inside or outside of an SDF"
" and hence whether they should have negative or positive sign."));
// Obsolete parameters
hutil::ParmList obsoleteParms;
obsoleteParms.add(hutil::ParmFactory(PRM_ORD, "combination", "Operation")
.setDefault(-2));
obsoleteParms.add(hutil::ParmFactory(PRM_SEPARATOR, "sep1", ""));
obsoleteParms.add(hutil::ParmFactory(PRM_SEPARATOR, "sep2", ""));
obsoleteParms.add(hutil::ParmFactory(PRM_TOGGLE, "flatten", "Flatten All B into A")
.setDefault(PRMzeroDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_TOGGLE, "pairs", "Combine A/B Pairs")
.setDefault(PRMoneDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_STRING, "groupA", "Group A"));
obsoleteParms.add(hutil::ParmFactory(PRM_STRING, "groupB", "Group B"));
obsoleteParms.add(hutil::ParmFactory(PRM_FLT_J, "mult_a", "A Multiplier")
.setDefault(PRMoneDefaults));
obsoleteParms.add(hutil::ParmFactory(PRM_FLT_J, "mult_b", "B Multiplier")
.setDefault(PRMoneDefaults));
// Register SOP
hvdb::OpenVDBOpFactory("VDB Combine", SOP_OpenVDB_Combine::factory, parms, *table)
.addInput("A VDBs")
.addOptionalInput("B VDBs")
.setObsoleteParms(obsoleteParms)
.setVerb(SOP_NodeVerb::COOK_INPLACE, []() { return new SOP_OpenVDB_Combine::Cache; })
.setDocumentation("\
#icon: COMMON/openvdb\n\
#tags: vdb\n\
\n\
\"\"\"Combine the values of VDB volumes in various ways.\"\"\"\n\
\n\
@related\n\
\n\
- [Node:sop/vdbcombine]\n\
- [Node:sop/volumevop]\n\
- [Node:sop/volumemix]\n\
\n\
@examples\n\
\n\
See [openvdb.org|http://www.openvdb.org/download/] for source code\n\
and usage examples.\n");
}
////////////////////////////////////////
OP_Node*
SOP_OpenVDB_Combine::factory(OP_Network* net,
const char* name, OP_Operator* op)
{
return new SOP_OpenVDB_Combine(net, name, op);
}
SOP_OpenVDB_Combine::SOP_OpenVDB_Combine(OP_Network* net, const char* name, OP_Operator* op)
: SOP_NodeVDB(net, name, op)
{
}
////////////////////////////////////////
void
SOP_OpenVDB_Combine::resolveObsoleteParms(PRM_ParmList* obsoleteParms)
{
if (!obsoleteParms) return;
const fpreal time = 0.0;
if (PRM_Parm* parm = obsoleteParms->getParmPtr("combination")) {
if (!parm->isFactoryDefault()) {
// The "combination" choices (union, intersection, difference) from
// the old CSG SOP were appended to this SOP's "operation" list.
switch (obsoleteParms->evalInt("combination", 0, time)) {
case 0: setInt("operation", 0, 0.0, OP_UNION); break;
case 1: setInt("operation", 0, 0.0, OP_INTERSECTION); break;
case 2: setInt("operation", 0, 0.0, OP_DIFFERENCE); break;
}
}
}
{
PRM_Parm
*flatten = obsoleteParms->getParmPtr("flatten"),
*pairs = obsoleteParms->getParmPtr("pairs");
if (flatten && !flatten->isFactoryDefault()) { // factory default was Off
setString("flattenbtoa", CH_STRING_LITERAL, "collation", 0, time);
} else if (pairs && !pairs->isFactoryDefault()) { // factory default was On
setString("awithfirstb", CH_STRING_LITERAL, "collation", 0, time);
}
}
resolveRenamedParm(*obsoleteParms, "groupA", "agroup");
resolveRenamedParm(*obsoleteParms, "groupB", "bgroup");
resolveRenamedParm(*obsoleteParms, "mult_a", "amult");
resolveRenamedParm(*obsoleteParms, "mult_b", "bmult");
// Delegate to the base class.
hvdb::SOP_NodeVDB::resolveObsoleteParms(obsoleteParms);
}
// Enable or disable parameters in the UI.
bool
SOP_OpenVDB_Combine::updateParmsFlags()
{
bool changed = false;
changed |= enableParm("resampleinterp", evalInt("resample", 0, 0) != 0);
changed |= enableParm("bgtolerance", evalInt("deactivate", 0, 0) != 0);
changed |= enableParm("tolerance", evalInt("prune", 0, 0) != 0);
return changed;
}
////////////////////////////////////////
namespace {
using StringVec = std::vector<std::string>;
// Split a string into group patterns separated by whitespace.
// For example, given '@name=d* @id="1 2" {grp1 grp2}', return
// ['@name=d*', '@id="1 2"', '{grp1 grp2}'].
// (This is nonstandard. Normally, multiple patterns are unioned
// to define a single group.)
// Nesting of quotes and braces is not supported.
inline StringVec
splitPatterns(const std::string& str)
{
StringVec patterns;
bool quoted = false, braced = false;
std::string pattern;
for (const auto c: str) {
if (isspace(c)) {
if (pattern.empty()) continue; // skip whitespace between patterns
if (quoted || braced) {
pattern.push_back(c); // keep whitespace within quotes or braces
} else {
// At the end of a pattern. Start a new pattern.
patterns.push_back(pattern);
pattern.clear();
quoted = braced = false;
}
} else {
switch (c) {
case '"': quoted = !quoted; break;
case '{': braced = true; break;
case '}': braced = false; break;
default: break;
}
pattern.push_back(c);
}
}
if (!pattern.empty()) { patterns.push_back(pattern); } // add the final pattern
// If no patterns were found, add an empty pattern, which matches everything.
if (patterns.empty()) { patterns.push_back(""); }
return patterns;
}
inline UT_String
getGridName(const GU_PrimVDB* vdb, const UT_String& defaultName = "")
{
UT_String name{UT_String::ALWAYS_DEEP};
if (vdb != nullptr) {
name = vdb->getGridName();
if (!name.isstring()) name = defaultName;
}
return name;
}
} // anonymous namespace
OP_ERROR
SOP_OpenVDB_Combine::Cache::cookVDBSop(OP_Context& context)
{
try {
UT_AutoInterrupt progress{"Combining VDBs"};
mTime = context.getTime();
const Operation op = asOp(static_cast<int>(evalInt("operation", 0, getTime())));
const ResampleMode resample = asResampleMode(evalInt("resample", 0, getTime()));
const CollationMode collation = asCollation(evalStdString("collation", getTime()));
const bool
flattenA = ((collation == COLL_FLATTEN_A) || (collation == COLL_FLATTEN_A_GROUPS)),
flatten = (flattenA || (collation == COLL_FLATTEN_B_TO_A)),
needA = needAGrid(op),
needB = (needBGrid(op) && !flattenA);
GU_Detail* aGdp = gdp;
const GU_Detail* bGdp = inputGeo(1, context);
const auto aGroupStr = evalStdString("agroup", getTime());
const auto bGroupStr = evalStdString("bgroup", getTime());
const auto* bGroup = (!bGdp ? nullptr : matchGroup(*bGdp, bGroupStr));
// In Flatten A Groups mode, treat space-separated subpatterns
// as specifying distinct groups to be processed independently.
// (In all other modes, subpatterns are unioned into a single group.)
std::vector<const GA_PrimitiveGroup*> aGroupVec;
if (collation != COLL_FLATTEN_A_GROUPS) {
aGroupVec.push_back(matchGroup(*aGdp, aGroupStr));
} else {
for (const auto& pattern: splitPatterns(aGroupStr)) {
aGroupVec.push_back(matchGroup(*aGdp, pattern));
}
}
// For diagnostic purposes, keep track of whether any input grids are left unused.
bool unusedA = false, unusedB = false;
// Iterate over one or more A groups.
for (const auto* aGroup: aGroupVec) {
hvdb::VdbPrimIterator aIt{aGdp, GA_Range::safedeletions{}, aGroup};
hvdb::VdbPrimCIterator bIt{bGdp, bGroup};
// Populate two vectors of primitives, one comprising the A grids
// and the other the B grids. (In the case of flattening operations,
// these grids might be taken from the same input.)
// Note: the following relies on exhausted iterators returning nullptr
// and on incrementing an exhausted iterator being a no-op.
std::vector<GU_PrimVDB*> aVdbVec;
std::vector<const GU_PrimVDB*> bVdbVec;
switch (collation) {
case COLL_PAIRS:
for ( ; (!needA || aIt) && (!needB || bIt); ++aIt, ++bIt) {
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
}
unusedA = unusedA || (needA && bool(aIt));
unusedB = unusedB || (needB && bool(bIt));
break;
case COLL_A_WITH_1ST_B:
for ( ; aIt && (!needB || bIt); ++aIt) {
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
}
break;
case COLL_FLATTEN_B_TO_A:
aVdbVec.push_back(*aIt);
bVdbVec.push_back(*bIt);
for (++bIt; bIt; ++bIt) {
aVdbVec.push_back(nullptr);
bVdbVec.push_back(*bIt);
}
break;
case COLL_FLATTEN_A:
case COLL_FLATTEN_A_GROUPS:
aVdbVec.push_back(*aIt);
for (++aIt; aIt; ++aIt) { bVdbVec.push_back(*aIt); }
break;
}
if ((needA && aVdbVec.empty()) || (needB && bVdbVec.empty())) continue;
std::set<GU_PrimVDB*> vdbsToRemove;
// Combine grids.
if (!flatten) {
// Iterate over A and, optionally, B grids.
for (size_t i = 0, N = std::min(aVdbVec.size(), bVdbVec.size()); i < N; ++i) {
if (progress.wasInterrupted()) { throw std::runtime_error{"interrupted"}; }
// Note: even if needA is false, we still need to delete A grids.
GU_PrimVDB* aVdb = aVdbVec[i];
const GU_PrimVDB* bVdb = bVdbVec[i];
hvdb::GridPtr aGrid;
hvdb::GridCPtr bGrid;
if (aVdb) aGrid = aVdb->getGridPtr();
if (bVdb) bGrid = bVdb->getConstGridPtr();
// For error reporting, get the names of the A and B grids.
const UT_String
aGridName = getGridName(aVdb, /*default=*/"A"),
bGridName = getGridName(bVdb, /*default=*/"B");
if (hvdb::GridPtr outGrid =
combineGrids(op, aGrid, bGrid, aGridName, bGridName, resample))
{
// Name the output grid after the A grid if the A grid is used,
// or after the B grid otherwise.
UT_String outGridName = needA ? getGridName(aVdb) : getGridName(bVdb);
// Add a new VDB primitive for the output grid to the output gdp.
GU_PrimVDB::buildFromGrid(*gdp, outGrid,
/*copyAttrsFrom=*/needA ? aVdb : bVdb, outGridName);
vdbsToRemove.insert(aVdb);
}
}
// Flatten grids (i.e., combine all B grids into the first A grid).
} else {
GU_PrimVDB* aVdb = aVdbVec[0];
hvdb::GridPtr aGrid;
if (aVdb) aGrid = aVdb->getGridPtr();
hvdb::GridPtr outGrid;
UT_String outGridName;
// Iterate over B grids.
const GU_PrimVDB* bVdb = nullptr;
for (const GU_PrimVDB* theBVdb: bVdbVec) {
if (progress.wasInterrupted()) { throw std::runtime_error{"interrupted"}; }
bVdb = theBVdb;
hvdb::GridCPtr bGrid;
if (bVdb) {
bGrid = bVdb->getConstGridPtr();
if (flattenA) {
// When flattening within the A group, remove B grids,
// since they're actually copies of grids from input 0.
vdbsToRemove.insert(const_cast<GU_PrimVDB*>(bVdb));
}
}
const UT_String
aGridName = getGridName(aVdb, /*default=*/"A"),
bGridName = getGridName(bVdb, /*default=*/"B");
// Name the output grid after the A grid if the A grid is used,
// or after the B grid otherwise.
outGridName = (needA ? getGridName(aVdb) : getGridName(bVdb));
outGrid = combineGrids(op, aGrid, bGrid, aGridName, bGridName, resample);
aGrid = outGrid;
}
if (outGrid) {
// Add a new VDB primitive for the output grid to the output gdp.
GU_PrimVDB::buildFromGrid(*gdp, outGrid,
/*copyAttrsFrom=*/needA ? aVdb : bVdb, outGridName);
vdbsToRemove.insert(aVdb);
}
}
// Remove primitives that were copied from input 0.
for (GU_PrimVDB* vdb: vdbsToRemove) {
if (vdb)
gdp->destroyPrimitive(*vdb, /*andPoints=*/true);
}
} // for each A group
if (unusedA || unusedB) {
std::ostringstream ostr;
ostr << "some grids were not processed because there were more "
<< (unusedA ? "A" : "B") << " grids than "
<< (unusedA ? "B" : "A") << " grids";
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} catch (std::exception& e) {
addError(SOP_MESSAGE, e.what());
}
return error();
}
////////////////////////////////////////
namespace {
/// Functor to compute scale * grid + offset, for scalars scale and offset
template<typename GridT>
struct MulAdd
{
using ValueT = typename GridT::ValueType;
using GridPtrT = typename GridT::Ptr;
float scale, offset;
explicit MulAdd(float s, float t = 0.0): scale(s), offset(t) {}
void operator()(const ValueT& a, const ValueT&, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT(a * scale + offset);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
/// @return true if the scale is 1 and the offset is 0
bool isIdentity() const
{
return (openvdb::math::isApproxEqual(scale, 1.f, 1.0e-6f)
&& openvdb::math::isApproxEqual(offset, 0.f, 1.0e-6f));
}
/// Compute dest = src * scale + offset
void process(const GridT& src, GridPtrT& dest) const
{
if (isIdentity()) {
dest = src.deepCopy();
} else {
if (!dest) dest = GridT::create(src); // same transform, new tree
ValueT bg;
(*this)(src.background(), ValueT(), bg);
openvdb::tools::changeBackground(dest->tree(), bg);
dest->tree().combine2(src.tree(), src.tree(), *this, /*prune=*/false);
}
}
};
////////////////////////////////////////
/// Functor to compute (1 - A) * B for grids A and B
template<typename ValueT>
struct Blend1
{
float aMult, bMult;
const ValueT ONE;
explicit Blend1(float a = 1.0, float b = 1.0):
aMult(a), bMult(b), ONE(openvdb::zeroVal<ValueT>() + 1) {}
void operator()(const ValueT& a, const ValueT& b, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT((ONE - aMult * a) * bMult * b);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
};
////////////////////////////////////////
/// Functor to compute A + (1 - A) * B for grids A and B
template<typename ValueT>
struct Blend2
{
float aMult, bMult;
const ValueT ONE;
explicit Blend2(float a = 1.0, float b = 1.0):
aMult(a), bMult(b), ONE(openvdb::zeroVal<ValueT>() + 1) {}
void operator()(const ValueT& a, const ValueT& b, ValueT& out) const
{
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
out = ValueT(a*aMult); out = out + ValueT((ONE - out) * bMult*b);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
}
};
////////////////////////////////////////
// Helper class to compare both scalar and vector values
template<typename ValueT>
struct ApproxEq
{
const ValueT &a, &b;
ApproxEq(const ValueT& _a, const ValueT& _b): a(_a), b(_b) {}
operator bool() const {
return openvdb::math::isRelOrApproxEqual(
a, b, /*rel*/ValueT(1e-6f), /*abs*/ValueT(1e-8f));
}
};
// Specialization for Vec2
template<typename T>
struct ApproxEq<openvdb::math::Vec2<T> >
{
using VecT = openvdb::math::Vec2<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
// Specialization for Vec3
template<typename T>
struct ApproxEq<openvdb::math::Vec3<T> >
{
using VecT = openvdb::math::Vec3<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
// Specialization for Vec4
template<typename T>
struct ApproxEq<openvdb::math::Vec4<T> >
{
using VecT = openvdb::math::Vec4<T>;
using ValueT = typename VecT::value_type;
const VecT &a, &b;
ApproxEq(const VecT& _a, const VecT& _b): a(_a), b(_b) {}
operator bool() const { return a.eq(b, /*abs=*/ValueT(1e-8f)); }
};
} // unnamed namespace
////////////////////////////////////////
template<typename AGridT>
struct SOP_OpenVDB_Combine::DispatchOp
{
SOP_OpenVDB_Combine::CombineOp* combineOp;
DispatchOp(SOP_OpenVDB_Combine::CombineOp& op): combineOp(&op) {}
template<typename BGridT> void operator()(typename BGridT::ConstPtr);
}; // struct DispatchOp
// Helper class for use with UTvdbProcessTypedGrid()
struct SOP_OpenVDB_Combine::CombineOp
{
SOP_OpenVDB_Combine::Cache* self;
Operation op;
ResampleMode resample;
UT_String aGridName, bGridName;
hvdb::GridCPtr aBaseGrid, bBaseGrid;
hvdb::GridPtr outGrid;
hvdb::Interrupter interrupt;
CombineOp(): self(nullptr) {}
// Functor for use with UTvdbProcessTypedGridScalar() to return
// a scalar grid's background value as a floating-point quantity
struct BackgroundOp {
double value;
BackgroundOp(): value(0.0) {}
template<typename GridT> void operator()(const GridT& grid) {
value = static_cast<double>(grid.background());
}
};
static double getScalarBackgroundValue(const hvdb::Grid& baseGrid)
{
BackgroundOp bgOp;
UTvdbProcessTypedGridScalar(UTvdbGetGridType(baseGrid), baseGrid, bgOp);
return bgOp.value;
}
template<typename GridT>
typename GridT::Ptr resampleToMatch(const GridT& src, const hvdb::Grid& ref, int order)
{
using ValueT = typename GridT::ValueType;
const ValueT ZERO = openvdb::zeroVal<ValueT>();
const openvdb::math::Transform& refXform = ref.constTransform();
typename GridT::Ptr dest;
if (src.getGridClass() == openvdb::GRID_LEVEL_SET) {
// For level set grids, use the level set rebuild tool to both resample the
// source grid to match the reference grid and to rebuild the resulting level set.
const bool refIsLevelSet = ref.getGridClass() == openvdb::GRID_LEVEL_SET;
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT halfWidth = refIsLevelSet
? ValueT(ZERO + this->getScalarBackgroundValue(ref) * (1.0 / ref.voxelSize()[0]))
: ValueT(src.background() * (1.0 / src.voxelSize()[0]));
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
if (!openvdb::math::isFinite(halfWidth)) {
std::stringstream msg;
msg << "Resample to match: Illegal narrow band width = " << halfWidth
<< ", caused by grid '" << src.getName() << "' with background "
<< this->getScalarBackgroundValue(ref);
throw std::invalid_argument(msg.str());
}
try {
dest = openvdb::tools::doLevelSetRebuild(src, /*iso=*/ZERO,
/*exWidth=*/halfWidth, /*inWidth=*/halfWidth, &refXform, &interrupt);
} catch (openvdb::TypeError&) {
self->addWarning(SOP_MESSAGE, ("skipped rebuild of level set grid "
+ src.getName() + " of type " + src.type()).c_str());
dest.reset();
}
}
if (!dest && src.constTransform() != refXform) {
// For non-level set grids or if level set rebuild failed due to an unsupported
// grid type, use the grid transformer tool to resample the source grid to match
// the reference grid.
#if OPENVDB_ABI_VERSION_NUMBER <= 3
dest = src.copy(openvdb::CP_NEW);
#else
dest = src.copyWithNewTree();
#endif
dest->setTransform(refXform.copy());
using namespace openvdb;
switch (order) {
case 0: tools::resampleToMatch<tools::PointSampler>(src, *dest, interrupt); break;
case 1: tools::resampleToMatch<tools::BoxSampler>(src, *dest, interrupt); break;
case 2: tools::resampleToMatch<tools::QuadraticSampler>(src, *dest, interrupt); break;
}
}
return dest;
}
// If necessary, resample one grid so that its index space registers
// with the other grid's.
// Note that one of the grid pointers might change as a result.
template<typename AGridT, typename BGridT>
void resampleGrids(const AGridT*& aGrid, const BGridT*& bGrid)
{
if (!aGrid || !bGrid) return;
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needBoth = needA && needB;
const int samplingOrder = static_cast<int>(
self->evalInt("resampleinterp", 0, self->getTime()));
// One of RESAMPLE_A, RESAMPLE_B or RESAMPLE_OFF, specifying whether
// grid A, grid B or neither grid was resampled
int resampleWhich = RESAMPLE_OFF;
// Determine which of the two grids should be resampled.
if (resample == RESAMPLE_HI_RES || resample == RESAMPLE_LO_RES) {
const openvdb::Vec3d
aVoxSize = aGrid->voxelSize(),
bVoxSize = bGrid->voxelSize();
const double
aVoxVol = aVoxSize[0] * aVoxSize[1] * aVoxSize[2],
bVoxVol = bVoxSize[0] * bVoxSize[1] * bVoxSize[2];
resampleWhich = ((aVoxVol > bVoxVol && resample == RESAMPLE_LO_RES)
|| (aVoxVol < bVoxVol && resample == RESAMPLE_HI_RES))
? RESAMPLE_A : RESAMPLE_B;
} else {
resampleWhich = resample;
}
if (aGrid->constTransform() != bGrid->constTransform()) {
// If the A and B grid transforms don't match, one of the grids
// should be resampled into the other's index space.
if (resample == RESAMPLE_OFF) {
if (needBoth) {
// Resampling is disabled. Just log a warning.
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName << " transforms don't match";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} else {
if (needA && resampleWhich == RESAMPLE_A) {
// Resample grid A into grid B's index space.
aBaseGrid = this->resampleToMatch(*aGrid, *bGrid, samplingOrder);
aGrid = static_cast<const AGridT*>(aBaseGrid.get());
} else if (needB && resampleWhich == RESAMPLE_B) {
// Resample grid B into grid A's index space.
bBaseGrid = this->resampleToMatch(*bGrid, *aGrid, samplingOrder);
bGrid = static_cast<const BGridT*>(bBaseGrid.get());
}
}
}
if (aGrid->getGridClass() == openvdb::GRID_LEVEL_SET &&
bGrid->getGridClass() == openvdb::GRID_LEVEL_SET)
{
// If both grids are level sets, ensure that their background values match.
// (If one of the grids was resampled, then the background values should
// already match.)
const double
a = this->getScalarBackgroundValue(*aGrid),
b = this->getScalarBackgroundValue(*bGrid);
if (!ApproxEq<double>(a, b)) {
if (resample == RESAMPLE_OFF) {
if (needBoth) {
// Resampling/rebuilding is disabled. Just log a warning.
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName
<< " background values don't match ("
<< std::setprecision(3) << a << " vs. " << b << ");\n"
<< " the output grid will not be a valid level set";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
} else {
// One of the two grids needs a level set rebuild.
if (needA && resampleWhich == RESAMPLE_A) {
// Rebuild A to match B's background value.
aBaseGrid = this->resampleToMatch(*aGrid, *bGrid, samplingOrder);
aGrid = static_cast<const AGridT*>(aBaseGrid.get());
} else if (needB && resampleWhich == RESAMPLE_B) {
// Rebuild B to match A's background value.
bBaseGrid = this->resampleToMatch(*bGrid, *aGrid, samplingOrder);
bGrid = static_cast<const BGridT*>(bBaseGrid.get());
}
}
}
}
}
void checkVectorTypes(const hvdb::Grid* aGrid, const hvdb::Grid* bGrid)
{
if (!aGrid || !bGrid || !needAGrid(op) || !needBGrid(op)) return;
switch (op) {
case OP_TOPO_UNION:
case OP_TOPO_INTERSECTION:
case OP_TOPO_DIFFERENCE:
// No need to warn about different vector types for topology-only operations.
break;
default:
{
const openvdb::VecType
aVecType = aGrid->getVectorType(),
bVecType = bGrid->getVectorType();
if (aVecType != bVecType) {
std::ostringstream ostr;
ostr << aGridName << " and " << bGridName
<< " have different vector types\n"
<< " (" << hvdb::Grid::vecTypeToString(aVecType)
<< " vs. " << hvdb::Grid::vecTypeToString(bVecType) << ")";
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
break;
}
}
}
// Combine two grids of the same type.
template<typename GridT>
void combineSameType()
{
using ValueT = typename GridT::ValueType;
const bool
needA = needAGrid(op),
needB = needBGrid(op);
const float
aMult = float(self->evalFloat("amult", 0, self->getTime())),
bMult = float(self->evalFloat("bmult", 0, self->getTime()));
const GridT *aGrid = nullptr, *bGrid = nullptr;
if (aBaseGrid) aGrid = UTvdbGridCast<GridT>(aBaseGrid).get();
if (bBaseGrid) bGrid = UTvdbGridCast<GridT>(bBaseGrid).get();
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
// Warn if combining vector grids with different vector types.
if (needA && needB && openvdb::VecTraits<ValueT>::IsVec) {
this->checkVectorTypes(aGrid, bGrid);
}
// If necessary, resample one grid so that its index space
// registers with the other grid's.
if (aGrid && bGrid) this->resampleGrids(aGrid, bGrid);
const ValueT ZERO = openvdb::zeroVal<ValueT>();
// A temporary grid is needed for binary operations, because they
// cannibalize the B grid.
typename GridT::Ptr resultGrid, tempGrid;
switch (op) {
case OP_COPY_A:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
break;
case OP_COPY_B:
MulAdd<GridT>(bMult).process(*bGrid, resultGrid);
break;
case OP_INVERT:
MulAdd<GridT>(-aMult, 1.0).process(*aGrid, resultGrid);
break;
case OP_ADD:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compSum(*resultGrid, *tempGrid);
break;
case OP_SUBTRACT:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(-bMult).process(*bGrid, tempGrid);
openvdb::tools::compSum(*resultGrid, *tempGrid);
break;
case OP_MULTIPLY:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMul(*resultGrid, *tempGrid);
break;
case OP_DIVIDE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compDiv(*resultGrid, *tempGrid);
break;
case OP_MAXIMUM:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMax(*resultGrid, *tempGrid);
break;
case OP_MINIMUM:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compMin(*resultGrid, *tempGrid);
break;
case OP_BLEND1: // (1 - A) * B
{
const Blend1<ValueT> comp(aMult, bMult);
ValueT bg;
comp(aGrid->background(), ZERO, bg);
#if OPENVDB_ABI_VERSION_NUMBER <= 3
resultGrid = aGrid->copy(/*tree=*/openvdb::CP_NEW);
#else
resultGrid = aGrid->copyWithNewTree();
#endif
openvdb::tools::changeBackground(resultGrid->tree(), bg);
resultGrid->tree().combine2(aGrid->tree(), bGrid->tree(), comp, /*prune=*/false);
break;
}
case OP_BLEND2: // A + (1 - A) * B
{
const Blend2<ValueT> comp(aMult, bMult);
ValueT bg;
comp(aGrid->background(), ZERO, bg);
#if OPENVDB_ABI_VERSION_NUMBER <= 3
resultGrid = aGrid->copy(/*tree=*/openvdb::CP_NEW);
#else
resultGrid = aGrid->copyWithNewTree();
#endif
openvdb::tools::changeBackground(resultGrid->tree(), bg);
resultGrid->tree().combine2(aGrid->tree(), bGrid->tree(), comp, /*prune=*/false);
break;
}
case OP_UNION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgUnion(*resultGrid, *tempGrid);
break;
case OP_INTERSECTION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgIntersection(*resultGrid, *tempGrid);
break;
case OP_DIFFERENCE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::csgDifference(*resultGrid, *tempGrid);
break;
case OP_REPLACE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
MulAdd<GridT>(bMult).process(*bGrid, tempGrid);
openvdb::tools::compReplace(*resultGrid, *tempGrid);
break;
case OP_TOPO_UNION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
// Note: no need to scale the B grid for topology-only operations.
resultGrid->topologyUnion(*bGrid);
break;
case OP_TOPO_INTERSECTION:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyIntersection(*bGrid);
break;
case OP_TOPO_DIFFERENCE:
MulAdd<GridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyDifference(*bGrid);
break;
}
outGrid = this->postprocess<GridT>(resultGrid);
}
// Combine two grids of different types.
/// @todo Currently, only topology operations can be performed on grids of different types.
template<typename AGridT, typename BGridT>
void combineDifferentTypes()
{
const bool
needA = needAGrid(op),
needB = needBGrid(op);
const AGridT* aGrid = nullptr;
const BGridT* bGrid = nullptr;
if (aBaseGrid) aGrid = UTvdbGridCast<AGridT>(aBaseGrid).get();
if (bBaseGrid) bGrid = UTvdbGridCast<BGridT>(bBaseGrid).get();
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
// Warn if combining vector grids with different vector types.
if (needA && needB && openvdb::VecTraits<typename AGridT::ValueType>::IsVec
&& openvdb::VecTraits<typename BGridT::ValueType>::IsVec)
{
this->checkVectorTypes(aGrid, bGrid);
}
// If necessary, resample one grid so that its index space
// registers with the other grid's.
if (aGrid && bGrid) this->resampleGrids(aGrid, bGrid);
const float aMult = float(self->evalFloat("amult", 0, self->getTime()));
typename AGridT::Ptr resultGrid;
switch (op) {
case OP_TOPO_UNION:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
// Note: no need to scale the B grid for topology-only operations.
resultGrid->topologyUnion(*bGrid);
break;
case OP_TOPO_INTERSECTION:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyIntersection(*bGrid);
break;
case OP_TOPO_DIFFERENCE:
MulAdd<AGridT>(aMult).process(*aGrid, resultGrid);
resultGrid->topologyDifference(*bGrid);
break;
default:
{
std::ostringstream ostr;
ostr << "can't combine grid " << aGridName << " of type " << aGrid->type()
<< "\n with grid " << bGridName
<< " of type " << bGrid->type();
throw std::runtime_error(ostr.str());
break;
}
}
outGrid = this->postprocess<AGridT>(resultGrid);
}
template<typename GridT>
typename GridT::Ptr postprocess(typename GridT::Ptr resultGrid)
{
using ValueT = typename GridT::ValueType;
const ValueT ZERO = openvdb::zeroVal<ValueT>();
const bool
prune = self->evalInt("prune", 0, self->getTime()),
flood = self->evalInt("flood", 0, self->getTime()),
deactivate = self->evalInt("deactivate", 0, self->getTime());
if (deactivate) {
const float deactivationTolerance =
float(self->evalFloat("bgtolerance", 0, self->getTime()));
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT tolerance(ZERO + deactivationTolerance);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
// Mark active output tiles and voxels as inactive if their
// values match the output grid's background value.
// Do this first to facilitate pruning.
openvdb::tools::deactivate(*resultGrid, resultGrid->background(), tolerance);
}
if (flood && resultGrid->getGridClass() == openvdb::GRID_LEVEL_SET) {
openvdb::tools::signedFloodFill(resultGrid->tree());
}
if (prune) {
const float pruneTolerance = float(self->evalFloat("tolerance", 0, self->getTime()));
OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN
const ValueT tolerance(ZERO + pruneTolerance);
OPENVDB_NO_TYPE_CONVERSION_WARNING_END
openvdb::tools::prune(resultGrid->tree(), tolerance);
}
return resultGrid;
}
template<typename AGridT>
void operator()(typename AGridT::ConstPtr)
{
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needBoth = needA && needB;
if (!needBoth || !aBaseGrid || !bBaseGrid || aBaseGrid->type() == bBaseGrid->type()) {
this->combineSameType<AGridT>();
} else {
DispatchOp<AGridT> dispatcher(*this);
// Dispatch on the B grid's type.
int success = UTvdbProcessTypedGridTopology(
UTvdbGetGridType(*bBaseGrid), bBaseGrid, dispatcher);
if (!success) {
std::ostringstream ostr;
ostr << "grid " << bGridName << " has unsupported type " << bBaseGrid->type();
self->addWarning(SOP_MESSAGE, ostr.str().c_str());
}
}
}
}; // struct CombineOp
template<typename AGridT>
template<typename BGridT>
void
SOP_OpenVDB_Combine::DispatchOp<AGridT>::operator()(typename BGridT::ConstPtr)
{
combineOp->combineDifferentTypes<AGridT, BGridT>();
}
////////////////////////////////////////
hvdb::GridPtr
SOP_OpenVDB_Combine::Cache::combineGrids(
Operation op,
hvdb::GridCPtr aGrid,
hvdb::GridCPtr bGrid,
const UT_String& aGridName,
const UT_String& bGridName,
ResampleMode resample)
{
hvdb::GridPtr outGrid;
const bool
needA = needAGrid(op),
needB = needBGrid(op),
needLS = needLevelSets(op);
if (!needA && !needB) throw std::runtime_error("nothing to do");
if (needA && !aGrid) throw std::runtime_error("missing A grid");
if (needB && !bGrid) throw std::runtime_error("missing B grid");
if (needLS &&
((aGrid && aGrid->getGridClass() != openvdb::GRID_LEVEL_SET) ||
(bGrid && bGrid->getGridClass() != openvdb::GRID_LEVEL_SET)))
{
std::ostringstream ostr;
ostr << "expected level set grids for the " << sOpMenuItems[op*2+1]
<< " operation,\n found "
<< hvdb::Grid::gridClassToString(aGrid->getGridClass()) << " (" << aGridName << ") and "
<< hvdb::Grid::gridClassToString(bGrid->getGridClass()) << " (" << bGridName
<< ");\n the output grid will not be a valid level set";
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
if (needA && needB && aGrid->type() != bGrid->type()
&& op != OP_TOPO_UNION && op != OP_TOPO_INTERSECTION && op != OP_TOPO_DIFFERENCE)
{
std::ostringstream ostr;
ostr << "can't combine grid " << aGridName << " of type " << aGrid->type()
<< "\n with grid " << bGridName << " of type " << bGrid->type();
addWarning(SOP_MESSAGE, ostr.str().c_str());
return outGrid;
}
CombineOp compOp;
compOp.self = this;
compOp.op = op;
compOp.resample = resample;
compOp.aBaseGrid = aGrid;
compOp.bBaseGrid = bGrid;
compOp.aGridName = aGridName;
compOp.bGridName = bGridName;
compOp.interrupt = hvdb::Interrupter();
int success = UTvdbProcessTypedGridTopology(
UTvdbGetGridType(needA ? *aGrid : *bGrid), aGrid, compOp);
if (!success || !compOp.outGrid) {
std::ostringstream ostr;
if (aGrid->type() == bGrid->type()) {
ostr << "grids " << aGridName << " and " << bGridName
<< " have unsupported type " << aGrid->type();
} else {
ostr << "grid " << (needA ? aGridName : bGridName)
<< " has unsupported type " << (needA ? aGrid->type() : bGrid->type());
}
addWarning(SOP_MESSAGE, ostr.str().c_str());
}
return compOp.outGrid;
}
// Copyright (c) DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
|
#include "ParticleSystem.h"
#include "Helper.h"
#include <DirectXColors.h>
using DirectX::Colors::Black;
ParticleSystem::ParticleSystem(ComPtr<ID3D11Device> device, ComPtr<ID3D11DeviceContext> deviceContext, const ParticleSettings& settings)
: first_active_particle(0), first_free_particle(0), first_new_particle(0), first_retired_particle(0), current_time(0.0f),
startIndex(0), length(0), timeLeftOver(0.0f), settings(settings)
{
// each particle system needs it own particle shader because we rely on
// constant shader values, and we can't stomp over another particle system's
// cbuffer space (alternative is to re-write these values per frame, instead of per
// lifetime of the system).
particle_shader.reset(new ParticleShader(device, settings));
texture = std::make_shared<Texture>(device, deviceContext, settings.texture_name);
Initialize();
LoadContent(device);
}
void ParticleSystem::Update(const Matrix& viewMatrix, const Matrix& projectionMatrix, float dt)
{
current_time += dt;
float timeBetweenParticles = 1.0f / settings.particles_per_second;
if (dt > 0)
{
float timeToSpend = timeLeftOver + dt;
float currentTime = -timeLeftOver;
while (timeToSpend > timeBetweenParticles)
{
currentTime += timeBetweenParticles;
timeToSpend -= timeBetweenParticles;
LOG_INFO("Adding particle...");
Vector3 pos = Vector3(
RandomFloat(settings.min_position.x, settings.max_position.x),
RandomFloat(settings.min_position.y, settings.max_position.y),
RandomFloat(settings.min_position.z, settings.max_position.z));
AddParticle(pos);
}
timeLeftOver = timeToSpend;
}
RetireActiveParticles();
FreeRetiredParticles();
if (first_active_particle == first_free_particle)
current_time = 0.0f;
if (first_retired_particle == first_active_particle)
draw_counter = 0.0f;
particle_shader->Update(Matrix::Identity, viewMatrix, projectionMatrix);
}
void ParticleSystem::Draw(ComPtr<ID3D11Device> device, ComPtr<ID3D11DeviceContext> deviceContext)
{
if (first_new_particle != first_free_particle)
{
AddNewParticlesToVertexBuffer(deviceContext);
}
if (first_active_particle != first_free_particle)
{
if (settings.blend_state == BLEND_STATE::Alpha)
{
deviceContext->OMSetBlendState(StatesHelper::GetInstance().GetStates()->NonPremultiplied(), Black, 0xFFFFFFFF);
}
else if (settings.blend_state == BLEND_STATE::Additive)
{
deviceContext->OMSetBlendState(StatesHelper::GetInstance().GetStates()->Additive(), Black, 0xFFFFFFFF);
}
deviceContext->OMSetDepthStencilState(StatesHelper::GetInstance().GetStates()->DepthRead(), 0);
unsigned int stride = sizeof(ParticleVertex);
unsigned int offset = 0;
deviceContext->IASetVertexBuffers(0, 1, vertex_buffer->GetVertexBuffer().GetAddressOf(), &stride, &offset);
deviceContext->IASetIndexBuffer(this->vertex_buffer->GetIndexBuffer().Get() , DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
if (first_active_particle < first_free_particle)
{
particle_shader.get()->Draw(deviceContext, (first_free_particle - first_active_particle) * 6,
first_active_particle * 6, 0, texture.get(), Vector2::Zero, current_time);
}
else
{
particle_shader.get()->Draw(deviceContext, (settings.max_particles - first_active_particle) * 6,
first_active_particle * 6, 0, texture.get(), Vector2::Zero, current_time);
if (first_free_particle > 0)
{
particle_shader.get()->Draw(deviceContext, first_free_particle * 6, 0, 0, texture.get(),
Vector2::Zero, current_time, false);
}
}
}
draw_counter++;
}
void ParticleSystem::Initialize()
{
particles = shared_ptr<ParticleVertex>(new ParticleVertex[settings.max_particles * 4]);
auto p_particles = particles.get();
// make quads
for (int i = 0; i < settings.max_particles; ++i)
{
p_particles[i * 4 + 0].Corner = Vector2(-1.0f, -1.0f); // bottom left
p_particles[i * 4 + 1].Corner = Vector2(1.0f, -1.0f); // bottom right
p_particles[i * 4 + 2].Corner = Vector2(1.0f, 1.0f); // top right
p_particles[i * 4 + 3].Corner = Vector2(-1.0f, 1.0f); // top left
}
}
void ParticleSystem::LoadContent(ComPtr<ID3D11Device> device)
{
LoadParticleEffect();
vector<unsigned long> indices;
for (int i = 0; i < settings.max_particles; ++i)
{
indices.push_back(i * 4 + 0);
indices.push_back(i * 4 + 2);
indices.push_back(i * 4 + 1);
indices.push_back(i * 4 + 0);
indices.push_back(i * 4 + 3);
indices.push_back(i * 4 + 2);
}
// create a dynamic vertex buffer
vertex_buffer = VertexBuffer::CreateDynamic(device, sizeof(ParticleVertex),
settings.max_particles * 4, indices, indices.size());
}
void ParticleSystem::LoadParticleEffect()
{
}
void ParticleSystem::RetireActiveParticles()
{
float particle_duration = settings.duration;
while (first_active_particle != first_new_particle)
{
float particle_age = current_time - particles.get()[first_active_particle * 4].Time;
if (particle_age < particle_duration)
break;
particles.get()[first_active_particle * 4].Time = draw_counter;
first_active_particle++;
if (first_active_particle >= settings.max_particles)
first_active_particle = 0;
}
}
void ParticleSystem::FreeRetiredParticles()
{
while (first_retired_particle != first_active_particle)
{
int age = draw_counter - (int)particles.get()[first_retired_particle * 4].Time;
if (age < 3)
break;
first_retired_particle++;
if (first_retired_particle >= settings.max_particles)
first_retired_particle = 0;
}
}
void ParticleSystem::AddNewParticlesToVertexBuffer(ComPtr<ID3D11DeviceContext> deviceContext)
{
int stride = ParticleVertex::GetSize();
if (first_new_particle < first_free_particle)
{
// all new particles are in one consecutive range
// can upload with a single write
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
first_new_particle * 4, (first_free_particle - first_new_particle) * 4);
}
else
{
// our new particle range wraps past the end of the array, need to do 2 writes
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
first_new_particle * 4, (settings.max_particles - first_new_particle) * 4);
if (first_free_particle > 0)
{
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
0, first_free_particle * 4);
}
}
first_new_particle = first_free_particle;
}
void ParticleSystem::AddParticle(Vector3 position)
{
int next_free_particle = first_free_particle + 1;
if (next_free_particle >= settings.max_particles)
next_free_particle = 0;
if (next_free_particle == first_retired_particle)
return;
Vector3 velocity = Vector3
(
RandomFloat(settings.min_velocity.x, settings.max_velocity.x),
RandomFloat(settings.min_velocity.y, settings.max_velocity.y),
RandomFloat(settings.min_velocity.z, settings.max_velocity.z)
);
Color random = Color(RandomFloat(0.0f, 1.0f), RandomFloat(0.0f, 1.0f),
RandomFloat(0.0f, 1.0f), RandomFloat(0.0f, 1.0f));
for (int i = 0; i < 4; i++)
{
particles.get()[first_free_particle * 4 + i].Position = position;
particles.get()[first_free_particle * 4 + i].Velocity = velocity;
particles.get()[first_free_particle * 4 + i].Random = random;
particles.get()[first_free_particle * 4 + i].Time = current_time;
}
first_free_particle = next_free_particle;
}
Remote LOG_INFO from Update
#include "ParticleSystem.h"
#include "Helper.h"
#include <DirectXColors.h>
using DirectX::Colors::Black;
ParticleSystem::ParticleSystem(ComPtr<ID3D11Device> device, ComPtr<ID3D11DeviceContext> deviceContext, const ParticleSettings& settings)
: first_active_particle(0), first_free_particle(0), first_new_particle(0), first_retired_particle(0), current_time(0.0f),
startIndex(0), length(0), timeLeftOver(0.0f), settings(settings)
{
// each particle system needs it own particle shader because we rely on
// constant shader values, and we can't stomp over another particle system's
// cbuffer space (alternative is to re-write these values per frame, instead of per
// lifetime of the system).
particle_shader.reset(new ParticleShader(device, settings));
texture = std::make_shared<Texture>(device, deviceContext, settings.texture_name);
Initialize();
LoadContent(device);
}
void ParticleSystem::Update(const Matrix& viewMatrix, const Matrix& projectionMatrix, float dt)
{
current_time += dt;
float timeBetweenParticles = 1.0f / settings.particles_per_second;
if (dt > 0)
{
float timeToSpend = timeLeftOver + dt;
float currentTime = -timeLeftOver;
while (timeToSpend > timeBetweenParticles)
{
currentTime += timeBetweenParticles;
timeToSpend -= timeBetweenParticles;
Vector3 pos = Vector3(
RandomFloat(settings.min_position.x, settings.max_position.x),
RandomFloat(settings.min_position.y, settings.max_position.y),
RandomFloat(settings.min_position.z, settings.max_position.z));
AddParticle(pos);
}
timeLeftOver = timeToSpend;
}
RetireActiveParticles();
FreeRetiredParticles();
if (first_active_particle == first_free_particle)
current_time = 0.0f;
if (first_retired_particle == first_active_particle)
draw_counter = 0.0f;
particle_shader->Update(Matrix::Identity, viewMatrix, projectionMatrix);
}
void ParticleSystem::Draw(ComPtr<ID3D11Device> device, ComPtr<ID3D11DeviceContext> deviceContext)
{
if (first_new_particle != first_free_particle)
{
AddNewParticlesToVertexBuffer(deviceContext);
}
if (first_active_particle != first_free_particle)
{
if (settings.blend_state == BLEND_STATE::Alpha)
{
deviceContext->OMSetBlendState(StatesHelper::GetInstance().GetStates()->NonPremultiplied(), Black, 0xFFFFFFFF);
}
else if (settings.blend_state == BLEND_STATE::Additive)
{
deviceContext->OMSetBlendState(StatesHelper::GetInstance().GetStates()->Additive(), Black, 0xFFFFFFFF);
}
deviceContext->OMSetDepthStencilState(StatesHelper::GetInstance().GetStates()->DepthRead(), 0);
unsigned int stride = sizeof(ParticleVertex);
unsigned int offset = 0;
deviceContext->IASetVertexBuffers(0, 1, vertex_buffer->GetVertexBuffer().GetAddressOf(), &stride, &offset);
deviceContext->IASetIndexBuffer(this->vertex_buffer->GetIndexBuffer().Get() , DXGI_FORMAT_R32_UINT, 0);
deviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
if (first_active_particle < first_free_particle)
{
particle_shader.get()->Draw(deviceContext, (first_free_particle - first_active_particle) * 6,
first_active_particle * 6, 0, texture.get(), Vector2::Zero, current_time);
}
else
{
particle_shader.get()->Draw(deviceContext, (settings.max_particles - first_active_particle) * 6,
first_active_particle * 6, 0, texture.get(), Vector2::Zero, current_time);
if (first_free_particle > 0)
{
particle_shader.get()->Draw(deviceContext, first_free_particle * 6, 0, 0, texture.get(),
Vector2::Zero, current_time, false);
}
}
}
draw_counter++;
}
void ParticleSystem::Initialize()
{
particles = shared_ptr<ParticleVertex>(new ParticleVertex[settings.max_particles * 4]);
auto p_particles = particles.get();
// make quads
for (int i = 0; i < settings.max_particles; ++i)
{
p_particles[i * 4 + 0].Corner = Vector2(-1.0f, -1.0f); // bottom left
p_particles[i * 4 + 1].Corner = Vector2(1.0f, -1.0f); // bottom right
p_particles[i * 4 + 2].Corner = Vector2(1.0f, 1.0f); // top right
p_particles[i * 4 + 3].Corner = Vector2(-1.0f, 1.0f); // top left
}
}
void ParticleSystem::LoadContent(ComPtr<ID3D11Device> device)
{
LoadParticleEffect();
vector<unsigned long> indices;
for (int i = 0; i < settings.max_particles; ++i)
{
indices.push_back(i * 4 + 0);
indices.push_back(i * 4 + 2);
indices.push_back(i * 4 + 1);
indices.push_back(i * 4 + 0);
indices.push_back(i * 4 + 3);
indices.push_back(i * 4 + 2);
}
// create a dynamic vertex buffer
vertex_buffer = VertexBuffer::CreateDynamic(device, sizeof(ParticleVertex),
settings.max_particles * 4, indices, indices.size());
}
void ParticleSystem::LoadParticleEffect()
{
}
void ParticleSystem::RetireActiveParticles()
{
float particle_duration = settings.duration;
while (first_active_particle != first_new_particle)
{
float particle_age = current_time - particles.get()[first_active_particle * 4].Time;
if (particle_age < particle_duration)
break;
particles.get()[first_active_particle * 4].Time = draw_counter;
first_active_particle++;
if (first_active_particle >= settings.max_particles)
first_active_particle = 0;
}
}
void ParticleSystem::FreeRetiredParticles()
{
while (first_retired_particle != first_active_particle)
{
int age = draw_counter - (int)particles.get()[first_retired_particle * 4].Time;
if (age < 3)
break;
first_retired_particle++;
if (first_retired_particle >= settings.max_particles)
first_retired_particle = 0;
}
}
void ParticleSystem::AddNewParticlesToVertexBuffer(ComPtr<ID3D11DeviceContext> deviceContext)
{
int stride = ParticleVertex::GetSize();
if (first_new_particle < first_free_particle)
{
// all new particles are in one consecutive range
// can upload with a single write
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
first_new_particle * 4, (first_free_particle - first_new_particle) * 4);
}
else
{
// our new particle range wraps past the end of the array, need to do 2 writes
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
first_new_particle * 4, (settings.max_particles - first_new_particle) * 4);
if (first_free_particle > 0)
{
vertex_buffer.get()->SetData<ParticleVertex>(deviceContext, particles.get(),
0, first_free_particle * 4);
}
}
first_new_particle = first_free_particle;
}
void ParticleSystem::AddParticle(Vector3 position)
{
int next_free_particle = first_free_particle + 1;
if (next_free_particle >= settings.max_particles)
next_free_particle = 0;
if (next_free_particle == first_retired_particle)
return;
Vector3 velocity = Vector3
(
RandomFloat(settings.min_velocity.x, settings.max_velocity.x),
RandomFloat(settings.min_velocity.y, settings.max_velocity.y),
RandomFloat(settings.min_velocity.z, settings.max_velocity.z)
);
Color random = Color(RandomFloat(0.0f, 1.0f), RandomFloat(0.0f, 1.0f),
RandomFloat(0.0f, 1.0f), RandomFloat(0.0f, 1.0f));
for (int i = 0; i < 4; i++)
{
particles.get()[first_free_particle * 4 + i].Position = position;
particles.get()[first_free_particle * 4 + i].Velocity = velocity;
particles.get()[first_free_particle * 4 + i].Random = random;
particles.get()[first_free_particle * 4 + i].Time = current_time;
}
first_free_particle = next_free_particle;
}
|
//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayWGL.h: WGL implementation of egl::Display
#include "libANGLE/renderer/gl/wgl/DisplayWGL.h"
#include "common/debug.h"
#include "libANGLE/Config.h"
#include "libANGLE/Context.h"
#include "libANGLE/Display.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/gl/ContextGL.h"
#include "libANGLE/renderer/gl/RendererGL.h"
#include "libANGLE/renderer/gl/renderergl_utils.h"
#include "libANGLE/renderer/gl/wgl/ContextWGL.h"
#include "libANGLE/renderer/gl/wgl/D3DTextureSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/DXGISwapChainWindowSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/FunctionsWGL.h"
#include "libANGLE/renderer/gl/wgl/PbufferSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/RendererWGL.h"
#include "libANGLE/renderer/gl/wgl/WindowSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/wgl_utils.h"
#include "platform/Platform.h"
#include <EGL/eglext.h>
#include <sstream>
#include <string>
namespace rx
{
namespace
{
std::string GetErrorMessage()
{
DWORD errorCode = GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
if (size == 0)
{
std::ostringstream stream;
stream << "Failed to get the error message for '" << errorCode << "' due to the error '"
<< GetLastError() << "'";
message = stream.str();
}
if (messageBuffer != nullptr)
{
LocalFree(messageBuffer);
}
return message;
}
} // anonymous namespace
class FunctionsGLWindows : public FunctionsGL
{
public:
FunctionsGLWindows(HMODULE openGLModule, PFNWGLGETPROCADDRESSPROC getProcAddressWGL)
: mOpenGLModule(openGLModule), mGetProcAddressWGL(getProcAddressWGL)
{
ASSERT(mOpenGLModule);
ASSERT(mGetProcAddressWGL);
}
~FunctionsGLWindows() override {}
private:
void *loadProcAddress(const std::string &function) const override
{
void *proc = reinterpret_cast<void *>(mGetProcAddressWGL(function.c_str()));
if (!proc)
{
proc = reinterpret_cast<void *>(GetProcAddress(mOpenGLModule, function.c_str()));
}
return proc;
}
HMODULE mOpenGLModule;
PFNWGLGETPROCADDRESSPROC mGetProcAddressWGL;
};
DisplayWGL::DisplayWGL(const egl::DisplayState &state)
: DisplayGL(state),
mRenderer(nullptr),
mCurrentData(),
mOpenGLModule(nullptr),
mFunctionsWGL(nullptr),
mHasWGLCreateContextRobustness(false),
mHasRobustness(false),
mWindowClass(0),
mWindow(nullptr),
mDeviceContext(nullptr),
mPixelFormat(0),
mUseDXGISwapChains(false),
mHasDXInterop(false),
mDxgiModule(nullptr),
mD3d11Module(nullptr),
mD3D11DeviceHandle(nullptr),
mD3D11Device(nullptr),
mUseARBShare(true)
{}
DisplayWGL::~DisplayWGL() {}
egl::Error DisplayWGL::initialize(egl::Display *display)
{
egl::Error error = initializeImpl(display);
if (error.isError())
{
destroy();
return error;
}
return DisplayGL::initialize(display);
}
egl::Error DisplayWGL::initializeImpl(egl::Display *display)
{
mDisplayAttributes = display->getAttributeMap();
mOpenGLModule = LoadLibraryA("opengl32.dll");
if (!mOpenGLModule)
{
return egl::EglNotInitialized() << "Failed to load OpenGL library.";
}
mFunctionsWGL = new FunctionsWGL();
mFunctionsWGL->initialize(mOpenGLModule, nullptr);
// WGL can't grab extensions until it creates a context because it needs to load the driver's
// DLLs first. Create a dummy context to load the driver and determine which GL versions are
// available.
// Work around compile error from not defining "UNICODE" while Chromium does
const LPSTR idcArrow = MAKEINTRESOURCEA(32512);
std::ostringstream stream;
stream << "ANGLE DisplayWGL " << gl::FmtHex(display) << " Intermediate Window Class";
std::string className = stream.str();
WNDCLASSA intermediateClassDesc = {0};
intermediateClassDesc.style = CS_OWNDC;
intermediateClassDesc.lpfnWndProc = DefWindowProcA;
intermediateClassDesc.cbClsExtra = 0;
intermediateClassDesc.cbWndExtra = 0;
intermediateClassDesc.hInstance = GetModuleHandle(nullptr);
intermediateClassDesc.hIcon = nullptr;
intermediateClassDesc.hCursor = LoadCursorA(nullptr, idcArrow);
intermediateClassDesc.hbrBackground = 0;
intermediateClassDesc.lpszMenuName = nullptr;
intermediateClassDesc.lpszClassName = className.c_str();
mWindowClass = RegisterClassA(&intermediateClassDesc);
if (!mWindowClass)
{
return egl::EglNotInitialized()
<< "Failed to register intermediate OpenGL window class \"" << className.c_str()
<< "\":" << gl::FmtErr(HRESULT_CODE(GetLastError()));
}
HWND dummyWindow =
CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Dummy Window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
if (!dummyWindow)
{
return egl::EglNotInitialized() << "Failed to create dummy OpenGL window.";
}
HDC dummyDeviceContext = GetDC(dummyWindow);
if (!dummyDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to get the device context of the dummy OpenGL window.";
}
const PIXELFORMATDESCRIPTOR pixelFormatDescriptor = wgl::GetDefaultPixelFormatDescriptor();
int dummyPixelFormat = ChoosePixelFormat(dummyDeviceContext, &pixelFormatDescriptor);
if (dummyPixelFormat == 0)
{
return egl::EglNotInitialized()
<< "Could not find a compatible pixel format for the dummy OpenGL window.";
}
if (!SetPixelFormat(dummyDeviceContext, dummyPixelFormat, &pixelFormatDescriptor))
{
return egl::EglNotInitialized()
<< "Failed to set the pixel format on the intermediate OpenGL window.";
}
HGLRC dummyWGLContext = mFunctionsWGL->createContext(dummyDeviceContext);
if (!dummyDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to create a WGL context for the dummy OpenGL window.";
}
if (!mFunctionsWGL->makeCurrent(dummyDeviceContext, dummyWGLContext))
{
return egl::EglNotInitialized() << "Failed to make the dummy WGL context current.";
}
// Reinitialize the wgl functions to grab the extensions
mFunctionsWGL->initialize(mOpenGLModule, dummyDeviceContext);
mHasWGLCreateContextRobustness =
mFunctionsWGL->hasExtension("WGL_ARB_create_context_robustness");
// Destroy the dummy window and context
mFunctionsWGL->makeCurrent(dummyDeviceContext, nullptr);
mFunctionsWGL->deleteContext(dummyWGLContext);
ReleaseDC(dummyWindow, dummyDeviceContext);
DestroyWindow(dummyWindow);
const egl::AttributeMap &displayAttributes = display->getAttributeMap();
EGLint requestedDisplayType = static_cast<EGLint>(displayAttributes.get(
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
!mFunctionsWGL->hasExtension("WGL_EXT_create_context_es2_profile") &&
!mFunctionsWGL->hasExtension("WGL_EXT_create_context_es_profile"))
{
return egl::EglNotInitialized() << "Cannot create an OpenGL ES platform on Windows without "
"the WGL_EXT_create_context_es(2)_profile extension.";
}
// Create the real intermediate context and windows
mWindow = CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass),
"ANGLE Intermediate Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr,
nullptr, nullptr);
if (!mWindow)
{
return egl::EglNotInitialized() << "Failed to create intermediate OpenGL window.";
}
mDeviceContext = GetDC(mWindow);
if (!mDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to get the device context of the intermediate OpenGL window.";
}
if (mFunctionsWGL->choosePixelFormatARB)
{
std::vector<int> attribs = wgl::GetDefaultPixelFormatAttributes(false);
UINT matchingFormats = 0;
mFunctionsWGL->choosePixelFormatARB(mDeviceContext, &attribs[0], nullptr, 1u, &mPixelFormat,
&matchingFormats);
}
if (mPixelFormat == 0)
{
mPixelFormat = ChoosePixelFormat(mDeviceContext, &pixelFormatDescriptor);
}
if (mPixelFormat == 0)
{
return egl::EglNotInitialized()
<< "Could not find a compatible pixel format for the intermediate OpenGL window.";
}
if (!SetPixelFormat(mDeviceContext, mPixelFormat, &pixelFormatDescriptor))
{
return egl::EglNotInitialized()
<< "Failed to set the pixel format on the intermediate OpenGL window.";
}
ANGLE_TRY(createRenderer(&mRenderer));
const FunctionsGL *functionsGL = mRenderer->getFunctions();
mHasRobustness = functionsGL->getGraphicsResetStatus != nullptr;
if (mHasWGLCreateContextRobustness != mHasRobustness)
{
WARN() << "WGL_ARB_create_context_robustness exists but unable to create a context with "
"robustness.";
}
// Intel OpenGL ES drivers are not currently supported due to bugs in the driver and ANGLE
VendorID vendor = GetVendorID(functionsGL);
if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE && IsIntel(vendor))
{
return egl::EglNotInitialized() << "Intel OpenGL ES drivers are not supported.";
}
// Create DXGI swap chains for windows that come from other processes. Windows is unable to
// SetPixelFormat on windows from other processes when a sandbox is enabled.
HDC nativeDisplay = display->getNativeDisplayId();
HWND nativeWindow = WindowFromDC(nativeDisplay);
if (nativeWindow != nullptr)
{
DWORD currentProcessId = GetCurrentProcessId();
DWORD windowProcessId;
GetWindowThreadProcessId(nativeWindow, &windowProcessId);
// AMD drivers advertise the WGL_NV_DX_interop and WGL_NV_DX_interop2 extensions but fail
mUseDXGISwapChains = !IsAMD(vendor) && (currentProcessId != windowProcessId);
}
else
{
mUseDXGISwapChains = false;
}
mHasDXInterop = mFunctionsWGL->hasExtension("WGL_NV_DX_interop2");
if (mUseDXGISwapChains)
{
if (mHasDXInterop)
{
ANGLE_TRY(initializeD3DDevice());
}
else
{
// Want to use DXGI swap chains but WGL_NV_DX_interop2 is not present, fail
// initialization
return egl::EglNotInitialized() << "WGL_NV_DX_interop2 is required but not present.";
}
}
const gl::Version &maxVersion = mRenderer->getMaxSupportedESVersion();
if (maxVersion < gl::Version(2, 0))
{
return egl::EglNotInitialized() << "OpenGL ES 2.0 is not supportable.";
}
return egl::NoError();
}
void DisplayWGL::terminate()
{
DisplayGL::terminate();
destroy();
}
void DisplayWGL::destroy()
{
releaseD3DDevice(mD3D11DeviceHandle);
mRenderer.reset();
if (mFunctionsWGL)
{
if (mDeviceContext)
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
}
}
mCurrentData.clear();
SafeDelete(mFunctionsWGL);
if (mDeviceContext)
{
ReleaseDC(mWindow, mDeviceContext);
mDeviceContext = nullptr;
}
if (mWindow)
{
DestroyWindow(mWindow);
mWindow = nullptr;
}
if (mWindowClass)
{
if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass),
GetModuleHandle(nullptr)))
{
WARN() << "Failed to unregister OpenGL window class: " << gl::FmtHex(mWindowClass);
}
mWindowClass = NULL;
}
if (mOpenGLModule)
{
FreeLibrary(mOpenGLModule);
mOpenGLModule = nullptr;
}
SafeRelease(mD3D11Device);
if (mDxgiModule)
{
FreeLibrary(mDxgiModule);
mDxgiModule = nullptr;
}
if (mD3d11Module)
{
FreeLibrary(mD3d11Module);
mD3d11Module = nullptr;
}
ASSERT(mRegisteredD3DDevices.empty());
}
SurfaceImpl *DisplayWGL::createWindowSurface(const egl::SurfaceState &state,
EGLNativeWindowType window,
const egl::AttributeMap &attribs)
{
EGLint orientation = static_cast<EGLint>(attribs.get(EGL_SURFACE_ORIENTATION_ANGLE, 0));
if (mUseDXGISwapChains)
{
egl::Error error = initializeD3DDevice();
if (error.isError())
{
return nullptr;
}
return new DXGISwapChainWindowSurfaceWGL(
state, mRenderer->getStateManager(), window, mD3D11Device, mD3D11DeviceHandle,
mDeviceContext, mRenderer->getFunctions(), mFunctionsWGL, orientation);
}
else
{
return new WindowSurfaceWGL(state, window, mPixelFormat, mFunctionsWGL, orientation);
}
}
SurfaceImpl *DisplayWGL::createPbufferSurface(const egl::SurfaceState &state,
const egl::AttributeMap &attribs)
{
EGLint width = static_cast<EGLint>(attribs.get(EGL_WIDTH, 0));
EGLint height = static_cast<EGLint>(attribs.get(EGL_HEIGHT, 0));
bool largest = (attribs.get(EGL_LARGEST_PBUFFER, EGL_FALSE) == EGL_TRUE);
EGLenum textureFormat = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE));
EGLenum textureTarget = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_TARGET, EGL_NO_TEXTURE));
return new PbufferSurfaceWGL(state, width, height, textureFormat, textureTarget, largest,
mPixelFormat, mDeviceContext, mFunctionsWGL);
}
SurfaceImpl *DisplayWGL::createPbufferFromClientBuffer(const egl::SurfaceState &state,
EGLenum buftype,
EGLClientBuffer clientBuffer,
const egl::AttributeMap &attribs)
{
egl::Error error = initializeD3DDevice();
if (error.isError())
{
return nullptr;
}
return new D3DTextureSurfaceWGL(state, mRenderer->getStateManager(), buftype, clientBuffer,
this, mDeviceContext, mD3D11Device, mRenderer->getFunctions(),
mFunctionsWGL);
}
SurfaceImpl *DisplayWGL::createPixmapSurface(const egl::SurfaceState &state,
NativePixmapType nativePixmap,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
rx::ContextImpl *DisplayWGL::createContext(const gl::State &state,
gl::ErrorSet *errorSet,
const egl::Config *configuration,
const gl::Context *shareContext,
const egl::AttributeMap &attribs)
{
return new ContextWGL(state, errorSet, mRenderer);
}
DeviceImpl *DisplayWGL::createDevice()
{
UNREACHABLE();
return nullptr;
}
egl::ConfigSet DisplayWGL::generateConfigs()
{
egl::ConfigSet configs;
int minSwapInterval = 1;
int maxSwapInterval = 1;
if (mFunctionsWGL->swapIntervalEXT)
{
// No defined maximum swap interval in WGL_EXT_swap_control, use a reasonable number
minSwapInterval = 0;
maxSwapInterval = 8;
}
const gl::Version &maxVersion = getMaxSupportedESVersion();
ASSERT(maxVersion >= gl::Version(2, 0));
bool supportsES3 = maxVersion >= gl::Version(3, 0);
PIXELFORMATDESCRIPTOR pixelFormatDescriptor;
DescribePixelFormat(mDeviceContext, mPixelFormat, sizeof(pixelFormatDescriptor),
&pixelFormatDescriptor);
auto getAttrib = [this](int attrib) {
return wgl::QueryWGLFormatAttrib(mDeviceContext, mPixelFormat, attrib, mFunctionsWGL);
};
const EGLint optimalSurfaceOrientation =
mUseDXGISwapChains ? EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE : 0;
egl::Config config;
config.renderTargetFormat = GL_RGBA8; // TODO: use the bit counts to determine the format
config.depthStencilFormat =
GL_DEPTH24_STENCIL8; // TODO: use the bit counts to determine the format
config.bufferSize = pixelFormatDescriptor.cColorBits;
config.redSize = pixelFormatDescriptor.cRedBits;
config.greenSize = pixelFormatDescriptor.cGreenBits;
config.blueSize = pixelFormatDescriptor.cBlueBits;
config.luminanceSize = 0;
config.alphaSize = pixelFormatDescriptor.cAlphaBits;
config.alphaMaskSize = 0;
config.bindToTextureRGB = (getAttrib(WGL_BIND_TO_TEXTURE_RGB_ARB) == TRUE);
config.bindToTextureRGBA = (getAttrib(WGL_BIND_TO_TEXTURE_RGBA_ARB) == TRUE);
config.colorBufferType = EGL_RGB_BUFFER;
config.configCaveat = EGL_NONE;
config.conformant = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
config.depthSize = pixelFormatDescriptor.cDepthBits;
config.level = 0;
config.matchNativePixmap = EGL_NONE;
config.maxPBufferWidth = getAttrib(WGL_MAX_PBUFFER_WIDTH_ARB);
config.maxPBufferHeight = getAttrib(WGL_MAX_PBUFFER_HEIGHT_ARB);
config.maxPBufferPixels = getAttrib(WGL_MAX_PBUFFER_PIXELS_ARB);
config.maxSwapInterval = maxSwapInterval;
config.minSwapInterval = minSwapInterval;
config.nativeRenderable = EGL_TRUE; // Direct rendering
config.nativeVisualID = 0;
config.nativeVisualType = EGL_NONE;
config.renderableType = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
config.sampleBuffers = 0; // FIXME: enumerate multi-sampling
config.samples = 0;
config.stencilSize = pixelFormatDescriptor.cStencilBits;
config.surfaceType =
((pixelFormatDescriptor.dwFlags & PFD_DRAW_TO_WINDOW) ? EGL_WINDOW_BIT : 0) |
((getAttrib(WGL_DRAW_TO_PBUFFER_ARB) == TRUE) ? EGL_PBUFFER_BIT : 0) |
((getAttrib(WGL_SWAP_METHOD_ARB) == WGL_SWAP_COPY_ARB) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT
: 0);
config.optimalOrientation = optimalSurfaceOrientation;
config.colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
config.transparentType = EGL_NONE;
config.transparentRedValue = 0;
config.transparentGreenValue = 0;
config.transparentBlueValue = 0;
configs.add(config);
return configs;
}
bool DisplayWGL::testDeviceLost()
{
if (mHasRobustness)
{
return mRenderer->getResetStatus() != gl::GraphicsResetStatus::NoError;
}
return false;
}
egl::Error DisplayWGL::restoreLostDevice(const egl::Display *display)
{
return egl::EglBadDisplay();
}
bool DisplayWGL::isValidNativeWindow(EGLNativeWindowType window) const
{
return (IsWindow(window) == TRUE);
}
egl::Error DisplayWGL::validateClientBuffer(const egl::Config *configuration,
EGLenum buftype,
EGLClientBuffer clientBuffer,
const egl::AttributeMap &attribs) const
{
switch (buftype)
{
case EGL_D3D_TEXTURE_ANGLE:
case EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE:
ANGLE_TRY(const_cast<DisplayWGL *>(this)->initializeD3DDevice());
return D3DTextureSurfaceWGL::ValidateD3DTextureClientBuffer(buftype, clientBuffer,
mD3D11Device);
default:
return DisplayGL::validateClientBuffer(configuration, buftype, clientBuffer, attribs);
}
}
std::string DisplayWGL::getVendorString() const
{
// UNIMPLEMENTED();
return "";
}
egl::Error DisplayWGL::initializeD3DDevice()
{
if (mD3D11Device != nullptr)
{
return egl::NoError();
}
mDxgiModule = LoadLibrary(TEXT("dxgi.dll"));
if (!mDxgiModule)
{
return egl::EglNotInitialized() << "Failed to load DXGI library.";
}
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
if (!mD3d11Module)
{
return egl::EglNotInitialized() << "Failed to load d3d11 library.";
}
PFN_D3D11_CREATE_DEVICE d3d11CreateDevice = nullptr;
d3d11CreateDevice = reinterpret_cast<PFN_D3D11_CREATE_DEVICE>(
GetProcAddress(mD3d11Module, "D3D11CreateDevice"));
if (d3d11CreateDevice == nullptr)
{
return egl::EglNotInitialized() << "Could not retrieve D3D11CreateDevice address.";
}
HRESULT result = d3d11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0,
D3D11_SDK_VERSION, &mD3D11Device, nullptr, nullptr);
if (FAILED(result))
{
return egl::EglNotInitialized() << "Could not create D3D11 device, " << gl::FmtHR(result);
}
return registerD3DDevice(mD3D11Device, &mD3D11DeviceHandle);
}
void DisplayWGL::generateExtensions(egl::DisplayExtensions *outExtensions) const
{
// Only enable the surface orientation and post sub buffer for DXGI swap chain surfaces, they
// prefer to swap with inverted Y.
outExtensions->postSubBuffer = mUseDXGISwapChains;
outExtensions->surfaceOrientation = mUseDXGISwapChains;
outExtensions->createContextRobustness = mHasRobustness;
outExtensions->d3dTextureClientBuffer = mHasDXInterop;
outExtensions->d3dShareHandleClientBuffer = mHasDXInterop;
outExtensions->surfaceD3DTexture2DShareHandle = true;
outExtensions->querySurfacePointer = true;
outExtensions->keyedMutex = true;
// Contexts are virtualized so textures can be shared globally
outExtensions->displayTextureShareGroup = true;
outExtensions->surfacelessContext = true;
DisplayGL::generateExtensions(outExtensions);
}
void DisplayWGL::generateCaps(egl::Caps *outCaps) const
{
outCaps->textureNPOT = true;
}
egl::Error DisplayWGL::makeCurrentSurfaceless(gl::Context *context)
{
// Nothing to do because WGL always uses the same context and the previous surface can be left
// current.
return egl::NoError();
}
egl::Error DisplayWGL::waitClient(const gl::Context *context)
{
// Unimplemented as this is not needed for WGL
return egl::NoError();
}
egl::Error DisplayWGL::waitNative(const gl::Context *context, EGLint engine)
{
// Unimplemented as this is not needed for WGL
return egl::NoError();
}
egl::Error DisplayWGL::makeCurrent(egl::Surface *drawSurface,
egl::Surface *readSurface,
gl::Context *context)
{
CurrentNativeContext ¤tContext = mCurrentData[std::this_thread::get_id()];
HDC newDC = currentContext.dc;
if (drawSurface)
{
SurfaceWGL *drawSurfaceWGL = GetImplAs<SurfaceWGL>(drawSurface);
newDC = drawSurfaceWGL->getDC();
}
else
{
newDC = mDeviceContext;
}
HGLRC newContext = currentContext.glrc;
if (context)
{
ContextWGL *contextWGL = GetImplAs<ContextWGL>(context);
newContext = contextWGL->getContext();
}
else
{
newContext = 0;
}
if (newDC != currentContext.dc || newContext != currentContext.glrc)
{
ASSERT(newDC != 0);
if (!mFunctionsWGL->makeCurrent(newDC, newContext))
{
// TODO(geofflang): What error type here?
return egl::EglContextLost() << "Failed to make the WGL context current.";
}
currentContext.dc = newDC;
currentContext.glrc = newContext;
}
return DisplayGL::makeCurrent(drawSurface, readSurface, context);
}
egl::Error DisplayWGL::registerD3DDevice(IUnknown *device, HANDLE *outHandle)
{
ASSERT(device != nullptr);
ASSERT(outHandle != nullptr);
auto iter = mRegisteredD3DDevices.find(device);
if (iter != mRegisteredD3DDevices.end())
{
iter->second.refCount++;
*outHandle = iter->second.handle;
return egl::NoError();
}
HANDLE handle = mFunctionsWGL->dxOpenDeviceNV(device);
if (!handle)
{
return egl::EglBadParameter() << "Failed to open D3D device.";
}
device->AddRef();
D3DObjectHandle newDeviceInfo;
newDeviceInfo.handle = handle;
newDeviceInfo.refCount = 1;
mRegisteredD3DDevices[device] = newDeviceInfo;
*outHandle = handle;
return egl::NoError();
}
void DisplayWGL::releaseD3DDevice(HANDLE deviceHandle)
{
for (auto iter = mRegisteredD3DDevices.begin(); iter != mRegisteredD3DDevices.end(); iter++)
{
if (iter->second.handle == deviceHandle)
{
iter->second.refCount--;
if (iter->second.refCount == 0)
{
mFunctionsWGL->dxCloseDeviceNV(iter->second.handle);
iter->first->Release();
mRegisteredD3DDevices.erase(iter);
break;
}
}
}
}
gl::Version DisplayWGL::getMaxSupportedESVersion() const
{
return mRenderer->getMaxSupportedESVersion();
}
void DisplayWGL::destroyNativeContext(HGLRC context)
{
mFunctionsWGL->deleteContext(context);
}
HGLRC DisplayWGL::initializeContextAttribs(const egl::AttributeMap &eglAttributes,
HGLRC &sharedContext,
bool &useARBShare,
std::vector<int> &workerContextAttribs) const
{
EGLint requestedDisplayType = static_cast<EGLint>(
eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
// Create a context of the requested version, if any.
gl::Version requestedVersion(static_cast<EGLint>(eglAttributes.get(
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE)),
static_cast<EGLint>(eglAttributes.get(
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE)));
if (static_cast<EGLint>(requestedVersion.major) != EGL_DONT_CARE &&
static_cast<EGLint>(requestedVersion.minor) != EGL_DONT_CARE)
{
int profileMask = 0;
if (requestedDisplayType != EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
requestedVersion >= gl::Version(3, 2))
{
profileMask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
return createContextAttribs(requestedVersion, profileMask, sharedContext, useARBShare,
workerContextAttribs);
}
// Try all the GL version in order as a workaround for Mesa context creation where the driver
// doesn't automatically return the highest version available.
for (const auto &info : GenerateContextCreationToTry(requestedDisplayType, false))
{
int profileFlag = 0;
if (info.type == ContextCreationTry::Type::DESKTOP_CORE)
{
profileFlag |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
else if (info.type == ContextCreationTry::Type::ES)
{
profileFlag |= WGL_CONTEXT_ES_PROFILE_BIT_EXT;
}
HGLRC context = createContextAttribs(info.version, profileFlag, sharedContext, useARBShare,
workerContextAttribs);
if (context != nullptr)
{
return context;
}
}
return nullptr;
}
HGLRC DisplayWGL::createContextAttribs(const gl::Version &version,
int profileMask,
HGLRC &sharedContext,
bool &useARBShare,
std::vector<int> &workerContextAttribs) const
{
std::vector<int> attribs;
if (mHasWGLCreateContextRobustness)
{
attribs.push_back(WGL_CONTEXT_FLAGS_ARB);
attribs.push_back(WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB);
attribs.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
attribs.push_back(WGL_LOSE_CONTEXT_ON_RESET_ARB);
}
attribs.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
attribs.push_back(version.major);
attribs.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
attribs.push_back(version.minor);
if (profileMask != 0)
{
attribs.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
attribs.push_back(profileMask);
}
attribs.push_back(0);
attribs.push_back(0);
HGLRC context = mFunctionsWGL->createContextAttribsARB(mDeviceContext, nullptr, &attribs[0]);
// This shared context is never made current. It is safer than the main context to be used as
// a seed to create worker contexts from.
// It seems a WGL restriction not mentioned in MSDN, but some posts revealed it.
// https://www.opengl.org/discussion_boards/showthread.php/152648-wglShareLists-failing
// https://github.com/glfw/glfw/issues/402
sharedContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, context, &attribs[0]);
workerContextAttribs = attribs;
useARBShare = true;
return context;
}
egl::Error DisplayWGL::createRenderer(std::shared_ptr<RendererWGL> *outRenderer)
{
HGLRC context = nullptr;
HGLRC sharedContext = nullptr;
std::vector<int> workerContextAttribs;
if (mFunctionsWGL->createContextAttribsARB)
{
context = initializeContextAttribs(mDisplayAttributes, sharedContext, mUseARBShare,
workerContextAttribs);
}
// If wglCreateContextAttribsARB is unavailable or failed, try the standard wglCreateContext
if (!context)
{
// Don't have control over GL versions
context = mFunctionsWGL->createContext(mDeviceContext);
}
if (!context)
{
return egl::EglNotInitialized()
<< "Failed to create a WGL context for the intermediate OpenGL window."
<< GetErrorMessage();
}
if (!sharedContext)
{
sharedContext = mFunctionsWGL->createContext(mDeviceContext);
if (!mFunctionsWGL->shareLists(context, sharedContext))
{
mFunctionsWGL->deleteContext(sharedContext);
sharedContext = nullptr;
}
mUseARBShare = false;
}
if (!mFunctionsWGL->makeCurrent(mDeviceContext, context))
{
return egl::EglNotInitialized() << "Failed to make the intermediate WGL context current.";
}
CurrentNativeContext ¤tContext = mCurrentData[std::this_thread::get_id()];
currentContext.dc = mDeviceContext;
currentContext.glrc = context;
std::unique_ptr<FunctionsGL> functionsGL(
new FunctionsGLWindows(mOpenGLModule, mFunctionsWGL->getProcAddress));
functionsGL->initialize(mDisplayAttributes);
outRenderer->reset(new RendererWGL(std::move(functionsGL), mDisplayAttributes, this, context,
sharedContext, workerContextAttribs));
return egl::NoError();
}
class WorkerContextWGL final : public WorkerContext
{
public:
WorkerContextWGL(FunctionsWGL *functions,
HPBUFFERARB pbuffer,
HDC deviceContext,
HGLRC context);
~WorkerContextWGL() override;
bool makeCurrent() override;
void unmakeCurrent() override;
private:
FunctionsWGL *mFunctionsWGL;
HPBUFFERARB mPbuffer;
HDC mDeviceContext;
HGLRC mContext;
};
WorkerContextWGL::WorkerContextWGL(FunctionsWGL *functions,
HPBUFFERARB pbuffer,
HDC deviceContext,
HGLRC context)
: mFunctionsWGL(functions), mPbuffer(pbuffer), mDeviceContext(deviceContext), mContext(context)
{}
WorkerContextWGL::~WorkerContextWGL()
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
mFunctionsWGL->deleteContext(mContext);
mFunctionsWGL->releasePbufferDCARB(mPbuffer, mDeviceContext);
mFunctionsWGL->destroyPbufferARB(mPbuffer);
}
bool WorkerContextWGL::makeCurrent()
{
bool result = mFunctionsWGL->makeCurrent(mDeviceContext, mContext);
if (!result)
{
ERR() << GetErrorMessage();
}
return result;
}
void WorkerContextWGL::unmakeCurrent()
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
}
WorkerContext *DisplayWGL::createWorkerContext(std::string *infoLog,
HGLRC sharedContext,
const std::vector<int> &workerContextAttribs)
{
if (!sharedContext)
{
*infoLog += "Unable to create the shared context.";
return nullptr;
}
HPBUFFERARB workerPbuffer = nullptr;
HDC workerDeviceContext = nullptr;
HGLRC workerContext = nullptr;
#define CLEANUP_ON_ERROR() \
do \
{ \
if (workerContext) \
{ \
mFunctionsWGL->deleteContext(workerContext); \
} \
if (workerDeviceContext) \
{ \
mFunctionsWGL->releasePbufferDCARB(workerPbuffer, workerDeviceContext); \
} \
if (workerPbuffer) \
{ \
mFunctionsWGL->destroyPbufferARB(workerPbuffer); \
} \
} while (0)
const int attribs[] = {0, 0};
workerPbuffer = mFunctionsWGL->createPbufferARB(mDeviceContext, mPixelFormat, 1, 1, attribs);
if (!workerPbuffer)
{
*infoLog += GetErrorMessage();
return nullptr;
}
workerDeviceContext = mFunctionsWGL->getPbufferDCARB(workerPbuffer);
if (!workerDeviceContext)
{
*infoLog += GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
if (mUseARBShare)
{
workerContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, sharedContext,
&workerContextAttribs[0]);
}
else
{
workerContext = mFunctionsWGL->createContext(workerDeviceContext);
}
if (!workerContext)
{
GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
if (!mUseARBShare && !mFunctionsWGL->shareLists(sharedContext, workerContext))
{
GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
#undef CLEANUP_ON_ERROR
return new WorkerContextWGL(mFunctionsWGL, workerPbuffer, workerDeviceContext, workerContext);
}
void DisplayWGL::initializeFrontendFeatures(angle::FrontendFeatures *features) const
{
mRenderer->initializeFrontendFeatures(features);
}
void DisplayWGL::populateFeatureList(angle::FeatureList *features)
{
mRenderer->getFeatures().populateFeatureList(features);
}
} // namespace rx
Load the correct opengl32.dll
DisplayWGL.cpp is loading the opengl32.dll in out/debug, as opposed to the system's opengl32.dll.
Want system's dll.
Bug: angleproject:3641
Change-Id: I764ef44a942a0a6c4dac7082f82ae0fd4d95a139
Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/1687117
Commit-Queue: Clemen Deng <38d0724edd543da816dbc2c60b217f07a91e50bf@google.com>
Commit-Queue: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Reviewed-by: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Reviewed-by: Jonah Ryan-Davis <682bdb9e7d8ba359ef169b8db374e7a99d394a46@google.com>
//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayWGL.h: WGL implementation of egl::Display
#include "libANGLE/renderer/gl/wgl/DisplayWGL.h"
#include "common/debug.h"
#include "libANGLE/Config.h"
#include "libANGLE/Context.h"
#include "libANGLE/Display.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/gl/ContextGL.h"
#include "libANGLE/renderer/gl/RendererGL.h"
#include "libANGLE/renderer/gl/renderergl_utils.h"
#include "libANGLE/renderer/gl/wgl/ContextWGL.h"
#include "libANGLE/renderer/gl/wgl/D3DTextureSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/DXGISwapChainWindowSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/FunctionsWGL.h"
#include "libANGLE/renderer/gl/wgl/PbufferSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/RendererWGL.h"
#include "libANGLE/renderer/gl/wgl/WindowSurfaceWGL.h"
#include "libANGLE/renderer/gl/wgl/wgl_utils.h"
#include "platform/Platform.h"
#include <EGL/eglext.h>
#include <sstream>
#include <string>
namespace rx
{
namespace
{
std::string GetErrorMessage()
{
DWORD errorCode = GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
if (size == 0)
{
std::ostringstream stream;
stream << "Failed to get the error message for '" << errorCode << "' due to the error '"
<< GetLastError() << "'";
message = stream.str();
}
if (messageBuffer != nullptr)
{
LocalFree(messageBuffer);
}
return message;
}
} // anonymous namespace
class FunctionsGLWindows : public FunctionsGL
{
public:
FunctionsGLWindows(HMODULE openGLModule, PFNWGLGETPROCADDRESSPROC getProcAddressWGL)
: mOpenGLModule(openGLModule), mGetProcAddressWGL(getProcAddressWGL)
{
ASSERT(mOpenGLModule);
ASSERT(mGetProcAddressWGL);
}
~FunctionsGLWindows() override {}
private:
void *loadProcAddress(const std::string &function) const override
{
void *proc = reinterpret_cast<void *>(mGetProcAddressWGL(function.c_str()));
if (!proc)
{
proc = reinterpret_cast<void *>(GetProcAddress(mOpenGLModule, function.c_str()));
}
return proc;
}
HMODULE mOpenGLModule;
PFNWGLGETPROCADDRESSPROC mGetProcAddressWGL;
};
DisplayWGL::DisplayWGL(const egl::DisplayState &state)
: DisplayGL(state),
mRenderer(nullptr),
mCurrentData(),
mOpenGLModule(nullptr),
mFunctionsWGL(nullptr),
mHasWGLCreateContextRobustness(false),
mHasRobustness(false),
mWindowClass(0),
mWindow(nullptr),
mDeviceContext(nullptr),
mPixelFormat(0),
mUseDXGISwapChains(false),
mHasDXInterop(false),
mDxgiModule(nullptr),
mD3d11Module(nullptr),
mD3D11DeviceHandle(nullptr),
mD3D11Device(nullptr),
mUseARBShare(true)
{}
DisplayWGL::~DisplayWGL() {}
egl::Error DisplayWGL::initialize(egl::Display *display)
{
egl::Error error = initializeImpl(display);
if (error.isError())
{
destroy();
return error;
}
return DisplayGL::initialize(display);
}
egl::Error DisplayWGL::initializeImpl(egl::Display *display)
{
mDisplayAttributes = display->getAttributeMap();
mOpenGLModule = LoadLibraryExA("opengl32.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!mOpenGLModule)
{
return egl::EglNotInitialized() << "Failed to load OpenGL library.";
}
mFunctionsWGL = new FunctionsWGL();
mFunctionsWGL->initialize(mOpenGLModule, nullptr);
// WGL can't grab extensions until it creates a context because it needs to load the driver's
// DLLs first. Create a dummy context to load the driver and determine which GL versions are
// available.
// Work around compile error from not defining "UNICODE" while Chromium does
const LPSTR idcArrow = MAKEINTRESOURCEA(32512);
std::ostringstream stream;
stream << "ANGLE DisplayWGL " << gl::FmtHex(display) << " Intermediate Window Class";
std::string className = stream.str();
WNDCLASSA intermediateClassDesc = {0};
intermediateClassDesc.style = CS_OWNDC;
intermediateClassDesc.lpfnWndProc = DefWindowProcA;
intermediateClassDesc.cbClsExtra = 0;
intermediateClassDesc.cbWndExtra = 0;
intermediateClassDesc.hInstance = GetModuleHandle(nullptr);
intermediateClassDesc.hIcon = nullptr;
intermediateClassDesc.hCursor = LoadCursorA(nullptr, idcArrow);
intermediateClassDesc.hbrBackground = 0;
intermediateClassDesc.lpszMenuName = nullptr;
intermediateClassDesc.lpszClassName = className.c_str();
mWindowClass = RegisterClassA(&intermediateClassDesc);
if (!mWindowClass)
{
return egl::EglNotInitialized()
<< "Failed to register intermediate OpenGL window class \"" << className.c_str()
<< "\":" << gl::FmtErr(HRESULT_CODE(GetLastError()));
}
HWND dummyWindow =
CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Dummy Window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
if (!dummyWindow)
{
return egl::EglNotInitialized() << "Failed to create dummy OpenGL window.";
}
HDC dummyDeviceContext = GetDC(dummyWindow);
if (!dummyDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to get the device context of the dummy OpenGL window.";
}
const PIXELFORMATDESCRIPTOR pixelFormatDescriptor = wgl::GetDefaultPixelFormatDescriptor();
int dummyPixelFormat = ChoosePixelFormat(dummyDeviceContext, &pixelFormatDescriptor);
if (dummyPixelFormat == 0)
{
return egl::EglNotInitialized()
<< "Could not find a compatible pixel format for the dummy OpenGL window.";
}
if (!SetPixelFormat(dummyDeviceContext, dummyPixelFormat, &pixelFormatDescriptor))
{
return egl::EglNotInitialized()
<< "Failed to set the pixel format on the intermediate OpenGL window.";
}
HGLRC dummyWGLContext = mFunctionsWGL->createContext(dummyDeviceContext);
if (!dummyDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to create a WGL context for the dummy OpenGL window.";
}
if (!mFunctionsWGL->makeCurrent(dummyDeviceContext, dummyWGLContext))
{
return egl::EglNotInitialized() << "Failed to make the dummy WGL context current.";
}
// Reinitialize the wgl functions to grab the extensions
mFunctionsWGL->initialize(mOpenGLModule, dummyDeviceContext);
mHasWGLCreateContextRobustness =
mFunctionsWGL->hasExtension("WGL_ARB_create_context_robustness");
// Destroy the dummy window and context
mFunctionsWGL->makeCurrent(dummyDeviceContext, nullptr);
mFunctionsWGL->deleteContext(dummyWGLContext);
ReleaseDC(dummyWindow, dummyDeviceContext);
DestroyWindow(dummyWindow);
const egl::AttributeMap &displayAttributes = display->getAttributeMap();
EGLint requestedDisplayType = static_cast<EGLint>(displayAttributes.get(
EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
!mFunctionsWGL->hasExtension("WGL_EXT_create_context_es2_profile") &&
!mFunctionsWGL->hasExtension("WGL_EXT_create_context_es_profile"))
{
return egl::EglNotInitialized() << "Cannot create an OpenGL ES platform on Windows without "
"the WGL_EXT_create_context_es(2)_profile extension.";
}
// Create the real intermediate context and windows
mWindow = CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass),
"ANGLE Intermediate Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr,
nullptr, nullptr);
if (!mWindow)
{
return egl::EglNotInitialized() << "Failed to create intermediate OpenGL window.";
}
mDeviceContext = GetDC(mWindow);
if (!mDeviceContext)
{
return egl::EglNotInitialized()
<< "Failed to get the device context of the intermediate OpenGL window.";
}
if (mFunctionsWGL->choosePixelFormatARB)
{
std::vector<int> attribs = wgl::GetDefaultPixelFormatAttributes(false);
UINT matchingFormats = 0;
mFunctionsWGL->choosePixelFormatARB(mDeviceContext, &attribs[0], nullptr, 1u, &mPixelFormat,
&matchingFormats);
}
if (mPixelFormat == 0)
{
mPixelFormat = ChoosePixelFormat(mDeviceContext, &pixelFormatDescriptor);
}
if (mPixelFormat == 0)
{
return egl::EglNotInitialized()
<< "Could not find a compatible pixel format for the intermediate OpenGL window.";
}
if (!SetPixelFormat(mDeviceContext, mPixelFormat, &pixelFormatDescriptor))
{
return egl::EglNotInitialized()
<< "Failed to set the pixel format on the intermediate OpenGL window.";
}
ANGLE_TRY(createRenderer(&mRenderer));
const FunctionsGL *functionsGL = mRenderer->getFunctions();
mHasRobustness = functionsGL->getGraphicsResetStatus != nullptr;
if (mHasWGLCreateContextRobustness != mHasRobustness)
{
WARN() << "WGL_ARB_create_context_robustness exists but unable to create a context with "
"robustness.";
}
// Intel OpenGL ES drivers are not currently supported due to bugs in the driver and ANGLE
VendorID vendor = GetVendorID(functionsGL);
if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE && IsIntel(vendor))
{
return egl::EglNotInitialized() << "Intel OpenGL ES drivers are not supported.";
}
// Create DXGI swap chains for windows that come from other processes. Windows is unable to
// SetPixelFormat on windows from other processes when a sandbox is enabled.
HDC nativeDisplay = display->getNativeDisplayId();
HWND nativeWindow = WindowFromDC(nativeDisplay);
if (nativeWindow != nullptr)
{
DWORD currentProcessId = GetCurrentProcessId();
DWORD windowProcessId;
GetWindowThreadProcessId(nativeWindow, &windowProcessId);
// AMD drivers advertise the WGL_NV_DX_interop and WGL_NV_DX_interop2 extensions but fail
mUseDXGISwapChains = !IsAMD(vendor) && (currentProcessId != windowProcessId);
}
else
{
mUseDXGISwapChains = false;
}
mHasDXInterop = mFunctionsWGL->hasExtension("WGL_NV_DX_interop2");
if (mUseDXGISwapChains)
{
if (mHasDXInterop)
{
ANGLE_TRY(initializeD3DDevice());
}
else
{
// Want to use DXGI swap chains but WGL_NV_DX_interop2 is not present, fail
// initialization
return egl::EglNotInitialized() << "WGL_NV_DX_interop2 is required but not present.";
}
}
const gl::Version &maxVersion = mRenderer->getMaxSupportedESVersion();
if (maxVersion < gl::Version(2, 0))
{
return egl::EglNotInitialized() << "OpenGL ES 2.0 is not supportable.";
}
return egl::NoError();
}
void DisplayWGL::terminate()
{
DisplayGL::terminate();
destroy();
}
void DisplayWGL::destroy()
{
releaseD3DDevice(mD3D11DeviceHandle);
mRenderer.reset();
if (mFunctionsWGL)
{
if (mDeviceContext)
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
}
}
mCurrentData.clear();
SafeDelete(mFunctionsWGL);
if (mDeviceContext)
{
ReleaseDC(mWindow, mDeviceContext);
mDeviceContext = nullptr;
}
if (mWindow)
{
DestroyWindow(mWindow);
mWindow = nullptr;
}
if (mWindowClass)
{
if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass),
GetModuleHandle(nullptr)))
{
WARN() << "Failed to unregister OpenGL window class: " << gl::FmtHex(mWindowClass);
}
mWindowClass = NULL;
}
if (mOpenGLModule)
{
FreeLibrary(mOpenGLModule);
mOpenGLModule = nullptr;
}
SafeRelease(mD3D11Device);
if (mDxgiModule)
{
FreeLibrary(mDxgiModule);
mDxgiModule = nullptr;
}
if (mD3d11Module)
{
FreeLibrary(mD3d11Module);
mD3d11Module = nullptr;
}
ASSERT(mRegisteredD3DDevices.empty());
}
SurfaceImpl *DisplayWGL::createWindowSurface(const egl::SurfaceState &state,
EGLNativeWindowType window,
const egl::AttributeMap &attribs)
{
EGLint orientation = static_cast<EGLint>(attribs.get(EGL_SURFACE_ORIENTATION_ANGLE, 0));
if (mUseDXGISwapChains)
{
egl::Error error = initializeD3DDevice();
if (error.isError())
{
return nullptr;
}
return new DXGISwapChainWindowSurfaceWGL(
state, mRenderer->getStateManager(), window, mD3D11Device, mD3D11DeviceHandle,
mDeviceContext, mRenderer->getFunctions(), mFunctionsWGL, orientation);
}
else
{
return new WindowSurfaceWGL(state, window, mPixelFormat, mFunctionsWGL, orientation);
}
}
SurfaceImpl *DisplayWGL::createPbufferSurface(const egl::SurfaceState &state,
const egl::AttributeMap &attribs)
{
EGLint width = static_cast<EGLint>(attribs.get(EGL_WIDTH, 0));
EGLint height = static_cast<EGLint>(attribs.get(EGL_HEIGHT, 0));
bool largest = (attribs.get(EGL_LARGEST_PBUFFER, EGL_FALSE) == EGL_TRUE);
EGLenum textureFormat = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE));
EGLenum textureTarget = static_cast<EGLenum>(attribs.get(EGL_TEXTURE_TARGET, EGL_NO_TEXTURE));
return new PbufferSurfaceWGL(state, width, height, textureFormat, textureTarget, largest,
mPixelFormat, mDeviceContext, mFunctionsWGL);
}
SurfaceImpl *DisplayWGL::createPbufferFromClientBuffer(const egl::SurfaceState &state,
EGLenum buftype,
EGLClientBuffer clientBuffer,
const egl::AttributeMap &attribs)
{
egl::Error error = initializeD3DDevice();
if (error.isError())
{
return nullptr;
}
return new D3DTextureSurfaceWGL(state, mRenderer->getStateManager(), buftype, clientBuffer,
this, mDeviceContext, mD3D11Device, mRenderer->getFunctions(),
mFunctionsWGL);
}
SurfaceImpl *DisplayWGL::createPixmapSurface(const egl::SurfaceState &state,
NativePixmapType nativePixmap,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
rx::ContextImpl *DisplayWGL::createContext(const gl::State &state,
gl::ErrorSet *errorSet,
const egl::Config *configuration,
const gl::Context *shareContext,
const egl::AttributeMap &attribs)
{
return new ContextWGL(state, errorSet, mRenderer);
}
DeviceImpl *DisplayWGL::createDevice()
{
UNREACHABLE();
return nullptr;
}
egl::ConfigSet DisplayWGL::generateConfigs()
{
egl::ConfigSet configs;
int minSwapInterval = 1;
int maxSwapInterval = 1;
if (mFunctionsWGL->swapIntervalEXT)
{
// No defined maximum swap interval in WGL_EXT_swap_control, use a reasonable number
minSwapInterval = 0;
maxSwapInterval = 8;
}
const gl::Version &maxVersion = getMaxSupportedESVersion();
ASSERT(maxVersion >= gl::Version(2, 0));
bool supportsES3 = maxVersion >= gl::Version(3, 0);
PIXELFORMATDESCRIPTOR pixelFormatDescriptor;
DescribePixelFormat(mDeviceContext, mPixelFormat, sizeof(pixelFormatDescriptor),
&pixelFormatDescriptor);
auto getAttrib = [this](int attrib) {
return wgl::QueryWGLFormatAttrib(mDeviceContext, mPixelFormat, attrib, mFunctionsWGL);
};
const EGLint optimalSurfaceOrientation =
mUseDXGISwapChains ? EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE : 0;
egl::Config config;
config.renderTargetFormat = GL_RGBA8; // TODO: use the bit counts to determine the format
config.depthStencilFormat =
GL_DEPTH24_STENCIL8; // TODO: use the bit counts to determine the format
config.bufferSize = pixelFormatDescriptor.cColorBits;
config.redSize = pixelFormatDescriptor.cRedBits;
config.greenSize = pixelFormatDescriptor.cGreenBits;
config.blueSize = pixelFormatDescriptor.cBlueBits;
config.luminanceSize = 0;
config.alphaSize = pixelFormatDescriptor.cAlphaBits;
config.alphaMaskSize = 0;
config.bindToTextureRGB = (getAttrib(WGL_BIND_TO_TEXTURE_RGB_ARB) == TRUE);
config.bindToTextureRGBA = (getAttrib(WGL_BIND_TO_TEXTURE_RGBA_ARB) == TRUE);
config.colorBufferType = EGL_RGB_BUFFER;
config.configCaveat = EGL_NONE;
config.conformant = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
config.depthSize = pixelFormatDescriptor.cDepthBits;
config.level = 0;
config.matchNativePixmap = EGL_NONE;
config.maxPBufferWidth = getAttrib(WGL_MAX_PBUFFER_WIDTH_ARB);
config.maxPBufferHeight = getAttrib(WGL_MAX_PBUFFER_HEIGHT_ARB);
config.maxPBufferPixels = getAttrib(WGL_MAX_PBUFFER_PIXELS_ARB);
config.maxSwapInterval = maxSwapInterval;
config.minSwapInterval = minSwapInterval;
config.nativeRenderable = EGL_TRUE; // Direct rendering
config.nativeVisualID = 0;
config.nativeVisualType = EGL_NONE;
config.renderableType = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0);
config.sampleBuffers = 0; // FIXME: enumerate multi-sampling
config.samples = 0;
config.stencilSize = pixelFormatDescriptor.cStencilBits;
config.surfaceType =
((pixelFormatDescriptor.dwFlags & PFD_DRAW_TO_WINDOW) ? EGL_WINDOW_BIT : 0) |
((getAttrib(WGL_DRAW_TO_PBUFFER_ARB) == TRUE) ? EGL_PBUFFER_BIT : 0) |
((getAttrib(WGL_SWAP_METHOD_ARB) == WGL_SWAP_COPY_ARB) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT
: 0);
config.optimalOrientation = optimalSurfaceOrientation;
config.colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;
config.transparentType = EGL_NONE;
config.transparentRedValue = 0;
config.transparentGreenValue = 0;
config.transparentBlueValue = 0;
configs.add(config);
return configs;
}
bool DisplayWGL::testDeviceLost()
{
if (mHasRobustness)
{
return mRenderer->getResetStatus() != gl::GraphicsResetStatus::NoError;
}
return false;
}
egl::Error DisplayWGL::restoreLostDevice(const egl::Display *display)
{
return egl::EglBadDisplay();
}
bool DisplayWGL::isValidNativeWindow(EGLNativeWindowType window) const
{
return (IsWindow(window) == TRUE);
}
egl::Error DisplayWGL::validateClientBuffer(const egl::Config *configuration,
EGLenum buftype,
EGLClientBuffer clientBuffer,
const egl::AttributeMap &attribs) const
{
switch (buftype)
{
case EGL_D3D_TEXTURE_ANGLE:
case EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE:
ANGLE_TRY(const_cast<DisplayWGL *>(this)->initializeD3DDevice());
return D3DTextureSurfaceWGL::ValidateD3DTextureClientBuffer(buftype, clientBuffer,
mD3D11Device);
default:
return DisplayGL::validateClientBuffer(configuration, buftype, clientBuffer, attribs);
}
}
std::string DisplayWGL::getVendorString() const
{
// UNIMPLEMENTED();
return "";
}
egl::Error DisplayWGL::initializeD3DDevice()
{
if (mD3D11Device != nullptr)
{
return egl::NoError();
}
mDxgiModule = LoadLibrary(TEXT("dxgi.dll"));
if (!mDxgiModule)
{
return egl::EglNotInitialized() << "Failed to load DXGI library.";
}
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
if (!mD3d11Module)
{
return egl::EglNotInitialized() << "Failed to load d3d11 library.";
}
PFN_D3D11_CREATE_DEVICE d3d11CreateDevice = nullptr;
d3d11CreateDevice = reinterpret_cast<PFN_D3D11_CREATE_DEVICE>(
GetProcAddress(mD3d11Module, "D3D11CreateDevice"));
if (d3d11CreateDevice == nullptr)
{
return egl::EglNotInitialized() << "Could not retrieve D3D11CreateDevice address.";
}
HRESULT result = d3d11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0,
D3D11_SDK_VERSION, &mD3D11Device, nullptr, nullptr);
if (FAILED(result))
{
return egl::EglNotInitialized() << "Could not create D3D11 device, " << gl::FmtHR(result);
}
return registerD3DDevice(mD3D11Device, &mD3D11DeviceHandle);
}
void DisplayWGL::generateExtensions(egl::DisplayExtensions *outExtensions) const
{
// Only enable the surface orientation and post sub buffer for DXGI swap chain surfaces, they
// prefer to swap with inverted Y.
outExtensions->postSubBuffer = mUseDXGISwapChains;
outExtensions->surfaceOrientation = mUseDXGISwapChains;
outExtensions->createContextRobustness = mHasRobustness;
outExtensions->d3dTextureClientBuffer = mHasDXInterop;
outExtensions->d3dShareHandleClientBuffer = mHasDXInterop;
outExtensions->surfaceD3DTexture2DShareHandle = true;
outExtensions->querySurfacePointer = true;
outExtensions->keyedMutex = true;
// Contexts are virtualized so textures can be shared globally
outExtensions->displayTextureShareGroup = true;
outExtensions->surfacelessContext = true;
DisplayGL::generateExtensions(outExtensions);
}
void DisplayWGL::generateCaps(egl::Caps *outCaps) const
{
outCaps->textureNPOT = true;
}
egl::Error DisplayWGL::makeCurrentSurfaceless(gl::Context *context)
{
// Nothing to do because WGL always uses the same context and the previous surface can be left
// current.
return egl::NoError();
}
egl::Error DisplayWGL::waitClient(const gl::Context *context)
{
// Unimplemented as this is not needed for WGL
return egl::NoError();
}
egl::Error DisplayWGL::waitNative(const gl::Context *context, EGLint engine)
{
// Unimplemented as this is not needed for WGL
return egl::NoError();
}
egl::Error DisplayWGL::makeCurrent(egl::Surface *drawSurface,
egl::Surface *readSurface,
gl::Context *context)
{
CurrentNativeContext ¤tContext = mCurrentData[std::this_thread::get_id()];
HDC newDC = currentContext.dc;
if (drawSurface)
{
SurfaceWGL *drawSurfaceWGL = GetImplAs<SurfaceWGL>(drawSurface);
newDC = drawSurfaceWGL->getDC();
}
else
{
newDC = mDeviceContext;
}
HGLRC newContext = currentContext.glrc;
if (context)
{
ContextWGL *contextWGL = GetImplAs<ContextWGL>(context);
newContext = contextWGL->getContext();
}
else
{
newContext = 0;
}
if (newDC != currentContext.dc || newContext != currentContext.glrc)
{
ASSERT(newDC != 0);
if (!mFunctionsWGL->makeCurrent(newDC, newContext))
{
// TODO(geofflang): What error type here?
return egl::EglContextLost() << "Failed to make the WGL context current.";
}
currentContext.dc = newDC;
currentContext.glrc = newContext;
}
return DisplayGL::makeCurrent(drawSurface, readSurface, context);
}
egl::Error DisplayWGL::registerD3DDevice(IUnknown *device, HANDLE *outHandle)
{
ASSERT(device != nullptr);
ASSERT(outHandle != nullptr);
auto iter = mRegisteredD3DDevices.find(device);
if (iter != mRegisteredD3DDevices.end())
{
iter->second.refCount++;
*outHandle = iter->second.handle;
return egl::NoError();
}
HANDLE handle = mFunctionsWGL->dxOpenDeviceNV(device);
if (!handle)
{
return egl::EglBadParameter() << "Failed to open D3D device.";
}
device->AddRef();
D3DObjectHandle newDeviceInfo;
newDeviceInfo.handle = handle;
newDeviceInfo.refCount = 1;
mRegisteredD3DDevices[device] = newDeviceInfo;
*outHandle = handle;
return egl::NoError();
}
void DisplayWGL::releaseD3DDevice(HANDLE deviceHandle)
{
for (auto iter = mRegisteredD3DDevices.begin(); iter != mRegisteredD3DDevices.end(); iter++)
{
if (iter->second.handle == deviceHandle)
{
iter->second.refCount--;
if (iter->second.refCount == 0)
{
mFunctionsWGL->dxCloseDeviceNV(iter->second.handle);
iter->first->Release();
mRegisteredD3DDevices.erase(iter);
break;
}
}
}
}
gl::Version DisplayWGL::getMaxSupportedESVersion() const
{
return mRenderer->getMaxSupportedESVersion();
}
void DisplayWGL::destroyNativeContext(HGLRC context)
{
mFunctionsWGL->deleteContext(context);
}
HGLRC DisplayWGL::initializeContextAttribs(const egl::AttributeMap &eglAttributes,
HGLRC &sharedContext,
bool &useARBShare,
std::vector<int> &workerContextAttribs) const
{
EGLint requestedDisplayType = static_cast<EGLint>(
eglAttributes.get(EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE));
// Create a context of the requested version, if any.
gl::Version requestedVersion(static_cast<EGLint>(eglAttributes.get(
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE)),
static_cast<EGLint>(eglAttributes.get(
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE)));
if (static_cast<EGLint>(requestedVersion.major) != EGL_DONT_CARE &&
static_cast<EGLint>(requestedVersion.minor) != EGL_DONT_CARE)
{
int profileMask = 0;
if (requestedDisplayType != EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE &&
requestedVersion >= gl::Version(3, 2))
{
profileMask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
return createContextAttribs(requestedVersion, profileMask, sharedContext, useARBShare,
workerContextAttribs);
}
// Try all the GL version in order as a workaround for Mesa context creation where the driver
// doesn't automatically return the highest version available.
for (const auto &info : GenerateContextCreationToTry(requestedDisplayType, false))
{
int profileFlag = 0;
if (info.type == ContextCreationTry::Type::DESKTOP_CORE)
{
profileFlag |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
else if (info.type == ContextCreationTry::Type::ES)
{
profileFlag |= WGL_CONTEXT_ES_PROFILE_BIT_EXT;
}
HGLRC context = createContextAttribs(info.version, profileFlag, sharedContext, useARBShare,
workerContextAttribs);
if (context != nullptr)
{
return context;
}
}
return nullptr;
}
HGLRC DisplayWGL::createContextAttribs(const gl::Version &version,
int profileMask,
HGLRC &sharedContext,
bool &useARBShare,
std::vector<int> &workerContextAttribs) const
{
std::vector<int> attribs;
if (mHasWGLCreateContextRobustness)
{
attribs.push_back(WGL_CONTEXT_FLAGS_ARB);
attribs.push_back(WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB);
attribs.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
attribs.push_back(WGL_LOSE_CONTEXT_ON_RESET_ARB);
}
attribs.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
attribs.push_back(version.major);
attribs.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
attribs.push_back(version.minor);
if (profileMask != 0)
{
attribs.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
attribs.push_back(profileMask);
}
attribs.push_back(0);
attribs.push_back(0);
HGLRC context = mFunctionsWGL->createContextAttribsARB(mDeviceContext, nullptr, &attribs[0]);
// This shared context is never made current. It is safer than the main context to be used as
// a seed to create worker contexts from.
// It seems a WGL restriction not mentioned in MSDN, but some posts revealed it.
// https://www.opengl.org/discussion_boards/showthread.php/152648-wglShareLists-failing
// https://github.com/glfw/glfw/issues/402
sharedContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, context, &attribs[0]);
workerContextAttribs = attribs;
useARBShare = true;
return context;
}
egl::Error DisplayWGL::createRenderer(std::shared_ptr<RendererWGL> *outRenderer)
{
HGLRC context = nullptr;
HGLRC sharedContext = nullptr;
std::vector<int> workerContextAttribs;
if (mFunctionsWGL->createContextAttribsARB)
{
context = initializeContextAttribs(mDisplayAttributes, sharedContext, mUseARBShare,
workerContextAttribs);
}
// If wglCreateContextAttribsARB is unavailable or failed, try the standard wglCreateContext
if (!context)
{
// Don't have control over GL versions
context = mFunctionsWGL->createContext(mDeviceContext);
}
if (!context)
{
return egl::EglNotInitialized()
<< "Failed to create a WGL context for the intermediate OpenGL window."
<< GetErrorMessage();
}
if (!sharedContext)
{
sharedContext = mFunctionsWGL->createContext(mDeviceContext);
if (!mFunctionsWGL->shareLists(context, sharedContext))
{
mFunctionsWGL->deleteContext(sharedContext);
sharedContext = nullptr;
}
mUseARBShare = false;
}
if (!mFunctionsWGL->makeCurrent(mDeviceContext, context))
{
return egl::EglNotInitialized() << "Failed to make the intermediate WGL context current.";
}
CurrentNativeContext ¤tContext = mCurrentData[std::this_thread::get_id()];
currentContext.dc = mDeviceContext;
currentContext.glrc = context;
std::unique_ptr<FunctionsGL> functionsGL(
new FunctionsGLWindows(mOpenGLModule, mFunctionsWGL->getProcAddress));
functionsGL->initialize(mDisplayAttributes);
outRenderer->reset(new RendererWGL(std::move(functionsGL), mDisplayAttributes, this, context,
sharedContext, workerContextAttribs));
return egl::NoError();
}
class WorkerContextWGL final : public WorkerContext
{
public:
WorkerContextWGL(FunctionsWGL *functions,
HPBUFFERARB pbuffer,
HDC deviceContext,
HGLRC context);
~WorkerContextWGL() override;
bool makeCurrent() override;
void unmakeCurrent() override;
private:
FunctionsWGL *mFunctionsWGL;
HPBUFFERARB mPbuffer;
HDC mDeviceContext;
HGLRC mContext;
};
WorkerContextWGL::WorkerContextWGL(FunctionsWGL *functions,
HPBUFFERARB pbuffer,
HDC deviceContext,
HGLRC context)
: mFunctionsWGL(functions), mPbuffer(pbuffer), mDeviceContext(deviceContext), mContext(context)
{}
WorkerContextWGL::~WorkerContextWGL()
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
mFunctionsWGL->deleteContext(mContext);
mFunctionsWGL->releasePbufferDCARB(mPbuffer, mDeviceContext);
mFunctionsWGL->destroyPbufferARB(mPbuffer);
}
bool WorkerContextWGL::makeCurrent()
{
bool result = mFunctionsWGL->makeCurrent(mDeviceContext, mContext);
if (!result)
{
ERR() << GetErrorMessage();
}
return result;
}
void WorkerContextWGL::unmakeCurrent()
{
mFunctionsWGL->makeCurrent(mDeviceContext, nullptr);
}
WorkerContext *DisplayWGL::createWorkerContext(std::string *infoLog,
HGLRC sharedContext,
const std::vector<int> &workerContextAttribs)
{
if (!sharedContext)
{
*infoLog += "Unable to create the shared context.";
return nullptr;
}
HPBUFFERARB workerPbuffer = nullptr;
HDC workerDeviceContext = nullptr;
HGLRC workerContext = nullptr;
#define CLEANUP_ON_ERROR() \
do \
{ \
if (workerContext) \
{ \
mFunctionsWGL->deleteContext(workerContext); \
} \
if (workerDeviceContext) \
{ \
mFunctionsWGL->releasePbufferDCARB(workerPbuffer, workerDeviceContext); \
} \
if (workerPbuffer) \
{ \
mFunctionsWGL->destroyPbufferARB(workerPbuffer); \
} \
} while (0)
const int attribs[] = {0, 0};
workerPbuffer = mFunctionsWGL->createPbufferARB(mDeviceContext, mPixelFormat, 1, 1, attribs);
if (!workerPbuffer)
{
*infoLog += GetErrorMessage();
return nullptr;
}
workerDeviceContext = mFunctionsWGL->getPbufferDCARB(workerPbuffer);
if (!workerDeviceContext)
{
*infoLog += GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
if (mUseARBShare)
{
workerContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, sharedContext,
&workerContextAttribs[0]);
}
else
{
workerContext = mFunctionsWGL->createContext(workerDeviceContext);
}
if (!workerContext)
{
GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
if (!mUseARBShare && !mFunctionsWGL->shareLists(sharedContext, workerContext))
{
GetErrorMessage();
CLEANUP_ON_ERROR();
return nullptr;
}
#undef CLEANUP_ON_ERROR
return new WorkerContextWGL(mFunctionsWGL, workerPbuffer, workerDeviceContext, workerContext);
}
void DisplayWGL::initializeFrontendFeatures(angle::FrontendFeatures *features) const
{
mRenderer->initializeFrontendFeatures(features);
}
void DisplayWGL::populateFeatureList(angle::FeatureList *features)
{
mRenderer->getFeatures().populateFeatureList(features);
}
} // namespace rx
|
/***********************************************************************
tcp_connection.cpp - Implements the TCPConnection class.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#define MYSQLPP_NOT_HEADER
#include "common.h"
#include "tcp_connection.h"
#include "exceptions.h"
#if !defined(MYSQLPP_PLATFORM_WINDOWS)
# include <netdb.h>
#endif
#include <ctype.h>
#include <stdlib.h>
using namespace std;
namespace mysqlpp {
bool
TCPConnection::connect(const char* addr, const char* db,
const char* user, const char* pass)
{
error_message_.clear();
unsigned int port = 0;
string address;
if (addr) {
address = addr;
if (!parse_address(address, port, error_message_)) {
return false;
}
}
if (error_message_.empty()) {
return Connection::connect(db, address.c_str(), user, pass, port);
}
else {
if (throw_exceptions()) {
throw ConnectionFailed(error_message_.c_str());
}
else {
return false;
}
}
}
bool
TCPConnection::parse_address(std::string& addr, unsigned int& port,
std::string& error)
{
error.clear();
// Pull off service name or port number, if any
string service;
if (addr[0] == '[') {
// Might be IPv6 address plus port/service in RFC 2732 form.
string::size_type pos = addr.find(']');
if ((pos == string::npos) ||
(addr.find(':', pos + 1) != (pos + 1)) ||
(addr.find_first_of("[]", pos + 2) != string::npos)) {
error = "Malformed IPv6 [address]:service combination";
return false;
}
// We can separate address from port/service now
service = addr.substr(pos + 2);
addr = addr.substr(1, pos - 1);
// Ensure that address part is empty or has at least two colons
if (addr.size() &&
(((pos = addr.find(':')) == string::npos) ||
(addr.find(':', pos + 1) == string::npos))) {
error = "IPv6 literal needs at least two colons";
return false;
}
}
else {
// Can only be IPv4 address, so check for 0-1 colons
string::size_type pos = addr.find(':');
if (pos != string::npos) {
if (addr.find(':', pos + 1) != string::npos) {
error = "IPv4 address:service combo can have only one colon";
return false;
}
service = addr.substr(pos + 1);
addr = addr.substr(0, pos);
}
}
// Turn service into a port number, if it was given. If not, don't
// overwrite port because it could have a legal value passed in from
// Connection.
if (!service.empty()) {
if (isdigit(service[0])) {
port = atoi(service.c_str());
if ((port < 1) || (port > USHRT_MAX)) {
error = "Invalid TCP port number " + service;
return false;
}
}
else {
servent* pse = getservbyname(service.c_str(), "tcp");
if (pse) {
port = ntohs(pse->s_port);
}
else {
error = "Failed to look up TCP service " + service;
return false;
}
}
}
// Ensure that there are only alphanumeric characters, dots,
// dashes and colons in address. Anything else must be an error.
for (string::const_iterator it = addr.begin(); it != addr.end(); ++it) {
string::value_type c = *it;
if (!(isalnum(c) || (c == '.') || (c == '-') || (c == ':'))) {
error = "Bad character '";
error += c;
error += "' in TCP/IP address";
return false;
}
}
return true;
}
} // end namespace mysqlpp
Another #include fix for GCC 4.3, by Remi Collet
git-svn-id: 1a57124bbb9aca193a920d0ffd753d488afb922b@2215 5946f024-35f4-0310-b1b3-9a3be3380cfb
/***********************************************************************
tcp_connection.cpp - Implements the TCPConnection class.
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#define MYSQLPP_NOT_HEADER
#include "common.h"
#include "tcp_connection.h"
#include "exceptions.h"
#if !defined(MYSQLPP_PLATFORM_WINDOWS)
# include <netdb.h>
#endif
#include <ctype.h>
#include <stdlib.h>
#include <climits>
using namespace std;
namespace mysqlpp {
bool
TCPConnection::connect(const char* addr, const char* db,
const char* user, const char* pass)
{
error_message_.clear();
unsigned int port = 0;
string address;
if (addr) {
address = addr;
if (!parse_address(address, port, error_message_)) {
return false;
}
}
if (error_message_.empty()) {
return Connection::connect(db, address.c_str(), user, pass, port);
}
else {
if (throw_exceptions()) {
throw ConnectionFailed(error_message_.c_str());
}
else {
return false;
}
}
}
bool
TCPConnection::parse_address(std::string& addr, unsigned int& port,
std::string& error)
{
error.clear();
// Pull off service name or port number, if any
string service;
if (addr[0] == '[') {
// Might be IPv6 address plus port/service in RFC 2732 form.
string::size_type pos = addr.find(']');
if ((pos == string::npos) ||
(addr.find(':', pos + 1) != (pos + 1)) ||
(addr.find_first_of("[]", pos + 2) != string::npos)) {
error = "Malformed IPv6 [address]:service combination";
return false;
}
// We can separate address from port/service now
service = addr.substr(pos + 2);
addr = addr.substr(1, pos - 1);
// Ensure that address part is empty or has at least two colons
if (addr.size() &&
(((pos = addr.find(':')) == string::npos) ||
(addr.find(':', pos + 1) == string::npos))) {
error = "IPv6 literal needs at least two colons";
return false;
}
}
else {
// Can only be IPv4 address, so check for 0-1 colons
string::size_type pos = addr.find(':');
if (pos != string::npos) {
if (addr.find(':', pos + 1) != string::npos) {
error = "IPv4 address:service combo can have only one colon";
return false;
}
service = addr.substr(pos + 1);
addr = addr.substr(0, pos);
}
}
// Turn service into a port number, if it was given. If not, don't
// overwrite port because it could have a legal value passed in from
// Connection.
if (!service.empty()) {
if (isdigit(service[0])) {
port = atoi(service.c_str());
if ((port < 1) || (port > USHRT_MAX)) {
error = "Invalid TCP port number " + service;
return false;
}
}
else {
servent* pse = getservbyname(service.c_str(), "tcp");
if (pse) {
port = ntohs(pse->s_port);
}
else {
error = "Failed to look up TCP service " + service;
return false;
}
}
}
// Ensure that there are only alphanumeric characters, dots,
// dashes and colons in address. Anything else must be an error.
for (string::const_iterator it = addr.begin(); it != addr.end(); ++it) {
string::value_type c = *it;
if (!(isalnum(c) || (c == '.') || (c == '-') || (c == ':'))) {
error = "Bad character '";
error += c;
error += "' in TCP/IP address";
return false;
}
}
return true;
}
} // end namespace mysqlpp
|
//
// main.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/11/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include <iostream>
#include <memory>
#include <cstdio>
#include <SDL2/SDL.h>
#include "../../StaticAnalyser/StaticAnalyser.hpp"
#include "../../Machines/Utility/MachineForTarget.hpp"
#include "../../Machines/ConfigurationTarget.hpp"
#include "../../Machines/CRTMachine.hpp"
#include "../../Concurrency/BestEffortUpdater.hpp"
namespace {
struct CRTMachineDelegate: public CRTMachine::Machine::Delegate {
void machine_did_change_clock_rate(CRTMachine::Machine *machine) {
best_effort_updater->set_clock_rate(machine->get_clock_rate());
}
void machine_did_change_clock_is_unlimited(CRTMachine::Machine *machine) {
}
Concurrency::BestEffortUpdater *best_effort_updater;
};
struct BestEffortUpdaterDelegate: public Concurrency::BestEffortUpdater::Delegate {
void update(Concurrency::BestEffortUpdater *updater, int cycles, bool did_skip_previous_update) {
machine->crt_machine()->run_for(Cycles(cycles));
}
Machine::DynamicMachine *machine;
};
// This is set to a relatively large number for now.
const int AudioBufferSize = 1024;
struct SpeakerDelegate: public Outputs::Speaker::Delegate {
void speaker_did_complete_samples(Outputs::Speaker *speaker, const std::vector<int16_t> &buffer) {
if(SDL_GetQueuedAudioSize(audio_device) < AudioBufferSize*3)
SDL_QueueAudio(audio_device, reinterpret_cast<const void *>(buffer.data()), static_cast<Uint32>(buffer.size() * sizeof(uint16_t)));
updater->update();
}
SDL_AudioDeviceID audio_device;
Concurrency::BestEffortUpdater *updater;
};
bool KeyboardKeyForSDLScancode(SDL_Keycode scancode, Inputs::Keyboard::Key &key) {
#define BIND(x, y) case SDL_SCANCODE_##x: key = Inputs::Keyboard::Key::y; break;
switch(scancode) {
default: return false;
BIND(F1, F1) BIND(F2, F2) BIND(F3, F3) BIND(F4, F4) BIND(F5, F5) BIND(F6, F6)
BIND(F7, F7) BIND(F8, F8) BIND(F9, F9) BIND(F10, F10) BIND(F11, F11) BIND(F12, F12)
BIND(1, k1) BIND(2, k2) BIND(3, k3) BIND(4, k4) BIND(5, k5)
BIND(6, k6) BIND(7, k7) BIND(8, k8) BIND(9, k9) BIND(0, k0)
BIND(Q, Q) BIND(W, W) BIND(E, E) BIND(R, R) BIND(T, T)
BIND(Y, Y) BIND(U, U) BIND(I, I) BIND(O, O) BIND(P, P)
BIND(A, A) BIND(S, S) BIND(D, D) BIND(F, F) BIND(G, G)
BIND(H, H) BIND(J, J) BIND(K, K) BIND(L, L)
BIND(Z, Z) BIND(X, X) BIND(C, C) BIND(V, V)
BIND(B, B) BIND(N, N) BIND(M, M)
BIND(KP_7, KeyPad7) BIND(KP_8, KeyPad8) BIND(KP_9, KeyPad9)
BIND(KP_4, KeyPad4) BIND(KP_5, KeyPad5) BIND(KP_6, KeyPad6)
BIND(KP_1, KeyPad1) BIND(KP_2, KeyPad2) BIND(KP_3, KeyPad3)
BIND(KP_0, KeyPad0)
BIND(ESCAPE, Escape)
BIND(PRINTSCREEN, PrintScreen) BIND(SCROLLLOCK, ScrollLock) BIND(PAUSE, Pause)
BIND(GRAVE, BackTick) BIND(MINUS, Hyphen) BIND(EQUALS, Equals) BIND(BACKSPACE, BackSpace)
BIND(TAB, Tab)
BIND(LEFTBRACKET, OpenSquareBracket) BIND(RIGHTBRACKET, CloseSquareBracket)
BIND(BACKSLASH, BackSlash)
BIND(CAPSLOCK, CapsLock) BIND(SEMICOLON, Semicolon)
BIND(APOSTROPHE, Quote) BIND(RETURN, Enter)
BIND(LSHIFT, LeftShift) BIND(COMMA, Comma) BIND(PERIOD, FullStop)
BIND(SLASH, ForwardSlash) BIND(RSHIFT, RightShift)
BIND(LCTRL, LeftControl) BIND(LALT, LeftOption) BIND(LGUI, LeftMeta)
BIND(SPACE, Space)
BIND(RCTRL, RightControl) BIND(RALT, RightOption) BIND(RGUI, RightMeta)
BIND(LEFT, Left) BIND(RIGHT, Right) BIND(UP, Up) BIND(DOWN, Down)
BIND(INSERT, Insert) BIND(HOME, Home) BIND(PAGEUP, PageUp)
BIND(DELETE, Delete) BIND(END, End) BIND(PAGEDOWN, PageDown)
BIND(NUMLOCKCLEAR, NumLock) BIND(KP_DIVIDE, KeyPadSlash) BIND(KP_MULTIPLY, KeyPadAsterisk)
BIND(KP_PLUS, KeyPadPlus) BIND(KP_MINUS, KeyPadMinus) BIND(KP_ENTER, KeyPadEnter)
BIND(KP_DECIMAL, KeyPadDecimalPoint)
BIND(KP_EQUALS, KeyPadEquals)
BIND(HELP, Help)
// SDL doesn't seem to have scancodes for hash or keypad delete?
}
#undef BIND
return true;
}
}
int main(int argc, char *argv[]) {
SDL_Window *window = nullptr;
// Perform a sanity check on arguments.
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " [file]" << std::endl;
return -1;
}
// Determine the machine for the supplied file.
std::list<StaticAnalyser::Target> targets = StaticAnalyser::GetTargets(argv[1]);
if(targets.empty()) {
std::cerr << "Cannot open " << argv[1] << std::endl;
return -1;
}
Concurrency::BestEffortUpdater updater;
BestEffortUpdaterDelegate best_effort_updater_delegate;
CRTMachineDelegate crt_delegate;
SpeakerDelegate speaker_delegate;
// Create and configure a machine.
std::unique_ptr<::Machine::DynamicMachine> machine(::Machine::MachineForTarget(targets.front()));
updater.set_clock_rate(machine->crt_machine()->get_clock_rate());
crt_delegate.best_effort_updater = &updater;
best_effort_updater_delegate.machine = machine.get();
speaker_delegate.updater = &updater;
machine->crt_machine()->set_delegate(&crt_delegate);
updater.set_delegate(&best_effort_updater_delegate);
// Attempt to set up video and audio.
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
return -1;
}
// Ask for no depth buffer, a core profile and vsync-aligned rendering.
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetSwapInterval(1);
window = SDL_CreateWindow( "Clock Signal",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
400, 300,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if(!window)
{
std::cerr << "Could not create window" << std::endl;
return -1;
}
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, gl_context);
// For vanilla SDL purposes, assume system ROMs can be found in one of:
//
// /usr/local/share/CLK/[system]; or
// /usr/share/CLK/[system]
bool roms_loaded = machine->crt_machine()->set_rom_fetcher( [] (const std::string &machine, const std::vector<std::string> &names) -> std::vector<std::unique_ptr<std::vector<uint8_t>>> {
std::vector<std::unique_ptr<std::vector<uint8_t>>> results;
for(auto &name: names) {
std::string local_path = "/usr/local/share/CLK/" + machine + "/" + name;
FILE *file = fopen(local_path.c_str(), "r");
if(!file) {
std::string path = "/usr/share/CLK/" + machine + "/" + name;
file = fopen(path.c_str(), "r");
}
if(!file) {
results.emplace_back(nullptr);
continue;
}
std::unique_ptr<std::vector<uint8_t>> data(new std::vector<uint8_t>);
fseek(file, 0, SEEK_END);
data->resize(ftell(file));
fseek(file, 0, SEEK_SET);
fread(data->data(), 1, data->size(), file);
fclose(file);
results.emplace_back(std::move(data));
}
return results;
});
if(!roms_loaded) {
std::cerr << "Could not find system ROMs; please install to /usr/local/share/CLK/ or /usr/share/CLK/" << std::endl;
return -1;
}
machine->configuration_target()->configure_as_target(targets.front());
// Setup output, assuming a CRT machine for now, and prepare a best-effort updater.
machine->crt_machine()->setup_output(4.0 / 3.0);
machine->crt_machine()->get_crt()->set_output_gamma(2.2f);
// For now, lie about audio output intentions.
auto speaker = machine->crt_machine()->get_speaker();
if(speaker) {
// Create an audio pipe.
SDL_AudioSpec desired_audio_spec;
SDL_AudioSpec obtained_audio_spec;
SDL_zero(desired_audio_spec);
desired_audio_spec.freq = 48000; // TODO: how can I get SDL to reveal the output rate of this machine?
desired_audio_spec.format = AUDIO_S16;
desired_audio_spec.channels = 1;
desired_audio_spec.samples = AudioBufferSize;
speaker_delegate.audio_device = SDL_OpenAudioDevice(nullptr, 0, &desired_audio_spec, &obtained_audio_spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
speaker->set_output_rate(obtained_audio_spec.freq, obtained_audio_spec.samples);
speaker->set_delegate(&speaker_delegate);
SDL_PauseAudioDevice(speaker_delegate.audio_device, 0);
}
// Run the main event loop until the OS tells us to quit.
bool should_quit = false;
while(!should_quit) {
// Process all pending events.
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT: should_quit = true; break;
case SDL_KEYDOWN:
case SDL_KEYUP:
KeyboardMachine::Machine *keyboard_machine = machine->keyboard_machine();
if(!keyboard_machine) break;
Inputs::Keyboard::Key key = Inputs::Keyboard::Key::Space;
if(!KeyboardKeyForSDLScancode(event.key.keysym.scancode, key)) break;
keyboard_machine->get_keyboard().set_key_pressed(key, event.type == SDL_KEYDOWN);
break;
}
}
// Display a new frame and wait for vsync.
updater.update();
int width, height;
SDL_GetWindowSize(window, &width, &height);
machine->crt_machine()->get_crt()->draw_frame(static_cast<unsigned int>(width), static_cast<unsigned int>(height), false);
SDL_GL_SwapWindow(window);
}
// Clean up.
SDL_DestroyWindow( window );
SDL_Quit();
return 0;
}
Added check in SDL main that the expected number of bytes is read.
//
// main.cpp
// Clock Signal
//
// Created by Thomas Harte on 04/11/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include <iostream>
#include <memory>
#include <cstdio>
#include <SDL2/SDL.h>
#include "../../StaticAnalyser/StaticAnalyser.hpp"
#include "../../Machines/Utility/MachineForTarget.hpp"
#include "../../Machines/ConfigurationTarget.hpp"
#include "../../Machines/CRTMachine.hpp"
#include "../../Concurrency/BestEffortUpdater.hpp"
namespace {
struct CRTMachineDelegate: public CRTMachine::Machine::Delegate {
void machine_did_change_clock_rate(CRTMachine::Machine *machine) {
best_effort_updater->set_clock_rate(machine->get_clock_rate());
}
void machine_did_change_clock_is_unlimited(CRTMachine::Machine *machine) {
}
Concurrency::BestEffortUpdater *best_effort_updater;
};
struct BestEffortUpdaterDelegate: public Concurrency::BestEffortUpdater::Delegate {
void update(Concurrency::BestEffortUpdater *updater, int cycles, bool did_skip_previous_update) {
machine->crt_machine()->run_for(Cycles(cycles));
}
Machine::DynamicMachine *machine;
};
// This is set to a relatively large number for now.
const int AudioBufferSize = 1024;
struct SpeakerDelegate: public Outputs::Speaker::Delegate {
void speaker_did_complete_samples(Outputs::Speaker *speaker, const std::vector<int16_t> &buffer) {
if(SDL_GetQueuedAudioSize(audio_device) < AudioBufferSize*3)
SDL_QueueAudio(audio_device, reinterpret_cast<const void *>(buffer.data()), static_cast<Uint32>(buffer.size() * sizeof(uint16_t)));
updater->update();
}
SDL_AudioDeviceID audio_device;
Concurrency::BestEffortUpdater *updater;
};
bool KeyboardKeyForSDLScancode(SDL_Keycode scancode, Inputs::Keyboard::Key &key) {
#define BIND(x, y) case SDL_SCANCODE_##x: key = Inputs::Keyboard::Key::y; break;
switch(scancode) {
default: return false;
BIND(F1, F1) BIND(F2, F2) BIND(F3, F3) BIND(F4, F4) BIND(F5, F5) BIND(F6, F6)
BIND(F7, F7) BIND(F8, F8) BIND(F9, F9) BIND(F10, F10) BIND(F11, F11) BIND(F12, F12)
BIND(1, k1) BIND(2, k2) BIND(3, k3) BIND(4, k4) BIND(5, k5)
BIND(6, k6) BIND(7, k7) BIND(8, k8) BIND(9, k9) BIND(0, k0)
BIND(Q, Q) BIND(W, W) BIND(E, E) BIND(R, R) BIND(T, T)
BIND(Y, Y) BIND(U, U) BIND(I, I) BIND(O, O) BIND(P, P)
BIND(A, A) BIND(S, S) BIND(D, D) BIND(F, F) BIND(G, G)
BIND(H, H) BIND(J, J) BIND(K, K) BIND(L, L)
BIND(Z, Z) BIND(X, X) BIND(C, C) BIND(V, V)
BIND(B, B) BIND(N, N) BIND(M, M)
BIND(KP_7, KeyPad7) BIND(KP_8, KeyPad8) BIND(KP_9, KeyPad9)
BIND(KP_4, KeyPad4) BIND(KP_5, KeyPad5) BIND(KP_6, KeyPad6)
BIND(KP_1, KeyPad1) BIND(KP_2, KeyPad2) BIND(KP_3, KeyPad3)
BIND(KP_0, KeyPad0)
BIND(ESCAPE, Escape)
BIND(PRINTSCREEN, PrintScreen) BIND(SCROLLLOCK, ScrollLock) BIND(PAUSE, Pause)
BIND(GRAVE, BackTick) BIND(MINUS, Hyphen) BIND(EQUALS, Equals) BIND(BACKSPACE, BackSpace)
BIND(TAB, Tab)
BIND(LEFTBRACKET, OpenSquareBracket) BIND(RIGHTBRACKET, CloseSquareBracket)
BIND(BACKSLASH, BackSlash)
BIND(CAPSLOCK, CapsLock) BIND(SEMICOLON, Semicolon)
BIND(APOSTROPHE, Quote) BIND(RETURN, Enter)
BIND(LSHIFT, LeftShift) BIND(COMMA, Comma) BIND(PERIOD, FullStop)
BIND(SLASH, ForwardSlash) BIND(RSHIFT, RightShift)
BIND(LCTRL, LeftControl) BIND(LALT, LeftOption) BIND(LGUI, LeftMeta)
BIND(SPACE, Space)
BIND(RCTRL, RightControl) BIND(RALT, RightOption) BIND(RGUI, RightMeta)
BIND(LEFT, Left) BIND(RIGHT, Right) BIND(UP, Up) BIND(DOWN, Down)
BIND(INSERT, Insert) BIND(HOME, Home) BIND(PAGEUP, PageUp)
BIND(DELETE, Delete) BIND(END, End) BIND(PAGEDOWN, PageDown)
BIND(NUMLOCKCLEAR, NumLock) BIND(KP_DIVIDE, KeyPadSlash) BIND(KP_MULTIPLY, KeyPadAsterisk)
BIND(KP_PLUS, KeyPadPlus) BIND(KP_MINUS, KeyPadMinus) BIND(KP_ENTER, KeyPadEnter)
BIND(KP_DECIMAL, KeyPadDecimalPoint)
BIND(KP_EQUALS, KeyPadEquals)
BIND(HELP, Help)
// SDL doesn't seem to have scancodes for hash or keypad delete?
}
#undef BIND
return true;
}
}
int main(int argc, char *argv[]) {
SDL_Window *window = nullptr;
// Perform a sanity check on arguments.
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " [file]" << std::endl;
return -1;
}
// Determine the machine for the supplied file.
std::list<StaticAnalyser::Target> targets = StaticAnalyser::GetTargets(argv[1]);
if(targets.empty()) {
std::cerr << "Cannot open " << argv[1] << std::endl;
return -1;
}
Concurrency::BestEffortUpdater updater;
BestEffortUpdaterDelegate best_effort_updater_delegate;
CRTMachineDelegate crt_delegate;
SpeakerDelegate speaker_delegate;
// Create and configure a machine.
std::unique_ptr<::Machine::DynamicMachine> machine(::Machine::MachineForTarget(targets.front()));
updater.set_clock_rate(machine->crt_machine()->get_clock_rate());
crt_delegate.best_effort_updater = &updater;
best_effort_updater_delegate.machine = machine.get();
speaker_delegate.updater = &updater;
machine->crt_machine()->set_delegate(&crt_delegate);
updater.set_delegate(&best_effort_updater_delegate);
// Attempt to set up video and audio.
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
return -1;
}
// Ask for no depth buffer, a core profile and vsync-aligned rendering.
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetSwapInterval(1);
window = SDL_CreateWindow( "Clock Signal",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
400, 300,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if(!window)
{
std::cerr << "Could not create window" << std::endl;
return -1;
}
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, gl_context);
// For vanilla SDL purposes, assume system ROMs can be found in one of:
//
// /usr/local/share/CLK/[system]; or
// /usr/share/CLK/[system]
bool roms_loaded = machine->crt_machine()->set_rom_fetcher( [] (const std::string &machine, const std::vector<std::string> &names) -> std::vector<std::unique_ptr<std::vector<uint8_t>>> {
std::vector<std::unique_ptr<std::vector<uint8_t>>> results;
for(auto &name: names) {
std::string local_path = "/usr/local/share/CLK/" + machine + "/" + name;
FILE *file = std::fopen(local_path.c_str(), "rb");
if(!file) {
std::string path = "/usr/share/CLK/" + machine + "/" + name;
file = std::fopen(path.c_str(), "rb");
}
if(!file) {
results.emplace_back(nullptr);
continue;
}
std::unique_ptr<std::vector<uint8_t>> data(new std::vector<uint8_t>);
std::fseek(file, 0, SEEK_END);
data->resize(std::ftell(file));
std::fseek(file, 0, SEEK_SET);
std::size_t read = fread(data->data(), 1, data->size(), file);
std::fclose(file);
if(read == data->size())
results.emplace_back(std::move(data));
else
results.emplace_back(nullptr);
}
return results;
});
if(!roms_loaded) {
std::cerr << "Could not find system ROMs; please install to /usr/local/share/CLK/ or /usr/share/CLK/" << std::endl;
return -1;
}
machine->configuration_target()->configure_as_target(targets.front());
// Setup output, assuming a CRT machine for now, and prepare a best-effort updater.
machine->crt_machine()->setup_output(4.0 / 3.0);
machine->crt_machine()->get_crt()->set_output_gamma(2.2f);
// For now, lie about audio output intentions.
auto speaker = machine->crt_machine()->get_speaker();
if(speaker) {
// Create an audio pipe.
SDL_AudioSpec desired_audio_spec;
SDL_AudioSpec obtained_audio_spec;
SDL_zero(desired_audio_spec);
desired_audio_spec.freq = 48000; // TODO: how can I get SDL to reveal the output rate of this machine?
desired_audio_spec.format = AUDIO_S16;
desired_audio_spec.channels = 1;
desired_audio_spec.samples = AudioBufferSize;
speaker_delegate.audio_device = SDL_OpenAudioDevice(nullptr, 0, &desired_audio_spec, &obtained_audio_spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE);
speaker->set_output_rate(obtained_audio_spec.freq, obtained_audio_spec.samples);
speaker->set_delegate(&speaker_delegate);
SDL_PauseAudioDevice(speaker_delegate.audio_device, 0);
}
// Run the main event loop until the OS tells us to quit.
bool should_quit = false;
while(!should_quit) {
// Process all pending events.
SDL_Event event;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT: should_quit = true; break;
case SDL_KEYDOWN:
case SDL_KEYUP:
KeyboardMachine::Machine *keyboard_machine = machine->keyboard_machine();
if(!keyboard_machine) break;
Inputs::Keyboard::Key key = Inputs::Keyboard::Key::Space;
if(!KeyboardKeyForSDLScancode(event.key.keysym.scancode, key)) break;
keyboard_machine->get_keyboard().set_key_pressed(key, event.type == SDL_KEYDOWN);
break;
}
}
// Display a new frame and wait for vsync.
updater.update();
int width, height;
SDL_GetWindowSize(window, &width, &height);
machine->crt_machine()->get_crt()->draw_frame(static_cast<unsigned int>(width), static_cast<unsigned int>(height), false);
SDL_GL_SwapWindow(window);
}
// Clean up.
SDL_DestroyWindow( window );
SDL_Quit();
return 0;
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
#define __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
#include <set>
#include <string>
#include <mesos/mesos.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <process/owned.hpp>
#include <stout/boundedhashmap.hpp>
#include <stout/duration.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/lambda.hpp>
#include <stout/option.hpp>
#include "common/protobuf_utils.hpp"
#include "master/allocator/mesos/allocator.hpp"
#include "master/allocator/mesos/metrics.hpp"
#include "master/allocator/sorter/drf/sorter.hpp"
#include "master/allocator/sorter/random/sorter.hpp"
#include "master/constants.hpp"
namespace mesos {
namespace internal {
namespace master {
namespace allocator {
// We forward declare the hierarchical allocator process so that we
// can typedef an instantiation of it with DRF sorters.
template <
typename RoleSorter,
typename FrameworkSorter,
typename QuotaRoleSorter>
class HierarchicalAllocatorProcess;
typedef HierarchicalAllocatorProcess<DRFSorter, DRFSorter, DRFSorter>
HierarchicalDRFAllocatorProcess;
typedef MesosAllocator<HierarchicalDRFAllocatorProcess>
HierarchicalDRFAllocator;
typedef HierarchicalAllocatorProcess<RandomSorter, RandomSorter, RandomSorter>
HierarchicalRandomAllocatorProcess;
typedef MesosAllocator<HierarchicalRandomAllocatorProcess>
HierarchicalRandomAllocator;
namespace internal {
// Forward declarations.
class OfferFilter;
class InverseOfferFilter;
struct Framework
{
Framework(
const FrameworkInfo& frameworkInfo,
const std::set<std::string>& suppressedRoles,
bool active,
bool publishPerFrameworkMetrics);
std::set<std::string> roles;
std::set<std::string> suppressedRoles;
protobuf::framework::Capabilities capabilities;
// Active offer and inverse offer filters for the framework.
// Offer filters are tied to the role the filtered resources
// were allocated to.
hashmap<std::string, hashmap<SlaveID, hashset<OfferFilter*>>> offerFilters;
hashmap<SlaveID, hashset<InverseOfferFilter*>> inverseOfferFilters;
bool active;
bool publishPerFrameworkMetrics;
process::Owned<FrameworkMetrics> metrics;
// TODO(bbannier): Consider documenting examples on how to use this setting.
hashmap<std::string, std::vector<ResourceQuantities>> minAllocatableResources;
};
class Slave
{
public:
Slave(
const SlaveInfo& _info,
const protobuf::slave::Capabilities& _capabilities,
bool _activated,
const Resources& _total,
const Resources& _allocated)
: info(_info),
capabilities(_capabilities),
activated(_activated),
total(_total),
allocated(_allocated),
shared(_total.shared()),
hasGpu_(_total.gpus().getOrElse(0) > 0)
{
updateAvailable();
}
const Resources& getTotal() const { return total; }
const Resources& getAllocated() const { return allocated; }
const Resources& getAvailable() const { return available; }
bool hasGpu() const { return hasGpu_; }
void updateTotal(const Resources& newTotal) {
total = newTotal;
shared = total.shared();
hasGpu_ = total.gpus().getOrElse(0) > 0;
updateAvailable();
}
void allocate(const Resources& toAllocate)
{
allocated += toAllocate;
updateAvailable();
}
void unallocate(const Resources& toUnallocate)
{
allocated -= toUnallocate;
updateAvailable();
}
// The `SlaveInfo` that was passed to the allocator when the slave was added
// or updated. Currently only two fields are used: `hostname` for host
// whitelisting and in log messages, and `domain` for region-aware
// scheduling.
SlaveInfo info;
protobuf::slave::Capabilities capabilities;
bool activated; // Whether to offer resources.
// Represents a scheduled unavailability due to maintenance for a specific
// slave, and the responses from frameworks as to whether they will be able
// to gracefully handle this unavailability.
//
// NOTE: We currently implement maintenance in the allocator to be able to
// leverage state and features such as the FrameworkSorter and OfferFilter.
struct Maintenance
{
Maintenance(const Unavailability& _unavailability)
: unavailability(_unavailability) {}
// The start time and optional duration of the event.
Unavailability unavailability;
// A mapping of frameworks to the inverse offer status associated with
// this unavailability.
//
// NOTE: We currently lose this information during a master fail over
// since it is not persisted or replicated. This is ok as the new master's
// allocator will send out new inverse offers and re-collect the
// information. This is similar to all the outstanding offers from an old
// master being invalidated, and new offers being sent out.
hashmap<FrameworkID, mesos::allocator::InverseOfferStatus> statuses;
// Represents the "unit of accounting" for maintenance. When a
// `FrameworkID` is present in the hashset it means an inverse offer has
// been sent out. When it is not present it means no offer is currently
// outstanding.
hashset<FrameworkID> offersOutstanding;
};
// When the `maintenance` is set the slave is scheduled to be unavailable at
// a given point in time, for an optional duration. This information is used
// to send out `InverseOffers`.
Option<Maintenance> maintenance;
private:
void updateAvailable() {
// In order to subtract from the total,
// we strip the allocation information.
Resources allocated_ = allocated;
allocated_.unallocate();
// Calling `nonShared()` currently copies the underlying resources
// and is therefore rather expensive. We avoid it in the common
// case that there are no shared resources.
//
// TODO(mzhu): Ideally there would be a single logical path here.
// One solution is to have `Resources` be copy-on-write such that
// `nonShared()` performs no copying and instead points to a
// subset of the original `Resource` objects.
if (shared.empty()) {
available = total - allocated_;
} else {
// Since shared resources are offerable even when they are in use, we
// always include them as part of available resources.
available = (total.nonShared() - allocated_.nonShared()) + shared;
}
}
// Total amount of regular *and* oversubscribed resources.
Resources total;
// Regular *and* oversubscribed resources that are allocated.
//
// NOTE: We maintain multiple copies of each shared resource allocated
// to a slave, where the number of copies represents the number of times
// this shared resource has been allocated to (and has not been recovered
// from) a specific framework.
//
// NOTE: We keep track of the slave's allocated resources despite
// having that information in sorters. This is because the
// information in sorters is not accurate if some framework
// hasn't reregistered. See MESOS-2919 for details.
Resources allocated;
// We track the total and allocated resources on the slave to
// avoid calculating it in place every time.
//
// Note that `available` always contains all the shared resources on the
// agent regardless whether they have ever been allocated or not.
// NOTE, however, we currently only offer a shared resource only if it has
// not been offered in an allocation cycle to a framework. We do this mainly
// to preserve the normal offer behavior. This may change in the future
// depending on use cases.
//
// Note that it's possible for the slave to be over-allocated!
// In this case, allocated > total.
Resources available;
// We keep a copy of the shared resources to avoid unnecessary copying.
Resources shared;
// We cache whether the agent has gpus as an optimization.
bool hasGpu_;
};
// Implements the basic allocator algorithm - first pick a role by
// some criteria, then pick one of their frameworks to allocate to.
class HierarchicalAllocatorProcess : public MesosAllocatorProcess
{
public:
HierarchicalAllocatorProcess(
const std::function<Sorter*()>& roleSorterFactory,
const std::function<Sorter*()>& _frameworkSorterFactory,
const std::function<Sorter*()>& quotaRoleSorterFactory)
: initialized(false),
paused(true),
metrics(*this),
completedFrameworkMetrics(0),
roleSorter(roleSorterFactory()),
quotaRoleSorter(quotaRoleSorterFactory()),
frameworkSorterFactory(_frameworkSorterFactory) {}
~HierarchicalAllocatorProcess() override {}
process::PID<HierarchicalAllocatorProcess> self() const
{
return process::PID<Self>(this);
}
void initialize(
const mesos::allocator::Options& options,
const lambda::function<
void(const FrameworkID&,
const hashmap<std::string, hashmap<SlaveID, Resources>>&)>&
offerCallback,
const lambda::function<
void(const FrameworkID&,
const hashmap<SlaveID, UnavailableResources>&)>&
inverseOfferCallback) override;
void recover(
const int _expectedAgentCount,
const hashmap<std::string, Quota>& quotas) override;
void addFramework(
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const hashmap<SlaveID, Resources>& used,
bool active,
const std::set<std::string>& suppressedRoles) override;
void removeFramework(
const FrameworkID& frameworkId) override;
void activateFramework(
const FrameworkID& frameworkId) override;
void deactivateFramework(
const FrameworkID& frameworkId) override;
void updateFramework(
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const std::set<std::string>& suppressedRoles) override;
void addSlave(
const SlaveID& slaveId,
const SlaveInfo& slaveInfo,
const std::vector<SlaveInfo::Capability>& capabilities,
const Option<Unavailability>& unavailability,
const Resources& total,
const hashmap<FrameworkID, Resources>& used) override;
void removeSlave(
const SlaveID& slaveId) override;
void updateSlave(
const SlaveID& slave,
const SlaveInfo& slaveInfo,
const Option<Resources>& total = None(),
const Option<std::vector<SlaveInfo::Capability>>& capabilities = None())
override;
void addResourceProvider(
const SlaveID& slave,
const Resources& total,
const hashmap<FrameworkID, Resources>& used) override;
void deactivateSlave(
const SlaveID& slaveId) override;
void activateSlave(
const SlaveID& slaveId) override;
void updateWhitelist(
const Option<hashset<std::string>>& whitelist) override;
void requestResources(
const FrameworkID& frameworkId,
const std::vector<Request>& requests) override;
void updateAllocation(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
const Resources& offeredResources,
const std::vector<ResourceConversion>& conversions) override;
process::Future<Nothing> updateAvailable(
const SlaveID& slaveId,
const std::vector<Offer::Operation>& operations) override;
void updateUnavailability(
const SlaveID& slaveId,
const Option<Unavailability>& unavailability) override;
void updateInverseOffer(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Option<UnavailableResources>& unavailableResources,
const Option<mesos::allocator::InverseOfferStatus>& status,
const Option<Filters>& filters) override;
process::Future<
hashmap<SlaveID,
hashmap<FrameworkID, mesos::allocator::InverseOfferStatus>>>
getInverseOfferStatuses() override;
void recoverResources(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
const Resources& resources,
const Option<Filters>& filters) override;
void suppressOffers(
const FrameworkID& frameworkId,
const std::set<std::string>& roles) override;
void reviveOffers(
const FrameworkID& frameworkId,
const std::set<std::string>& roles) override;
void setQuota(
const std::string& role,
const Quota& quota) override;
void removeQuota(
const std::string& role) override;
void updateWeights(
const std::vector<WeightInfo>& weightInfos) override;
void pause() override;
void resume() override;
protected:
// Useful typedefs for dispatch/delay/defer to self()/this.
typedef HierarchicalAllocatorProcess Self;
typedef HierarchicalAllocatorProcess This;
// Allocate any allocatable resources from all known agents.
process::Future<Nothing> allocate();
// Allocate resources from the specified agent.
process::Future<Nothing> allocate(const SlaveID& slaveId);
// Allocate resources from the specified agents. The allocation
// is deferred and batched with other allocation requests.
process::Future<Nothing> allocate(const hashset<SlaveID>& slaveIds);
// Method that performs allocation work.
Nothing _allocate();
// Helper for `_allocate()` that allocates resources for offers.
void __allocate();
// Helper for `_allocate()` that deallocates resources for inverse offers.
void deallocate();
// Remove an offer filter for the specified role of the framework.
void expire(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
OfferFilter* offerFilter);
void _expire(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
OfferFilter* offerFilter);
// Remove an inverse offer filter for the specified framework.
void expire(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
InverseOfferFilter* inverseOfferFilter);
// Checks whether the slave is whitelisted.
bool isWhitelisted(const SlaveID& slaveId) const;
// Returns true if there is a resource offer filter for the
// specified role of this framework on this slave.
bool isFiltered(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
const Resources& resources) const;
// Returns true if there is an inverse offer filter for this framework
// on this slave.
bool isFiltered(
const FrameworkID& frameworkID,
const SlaveID& slaveID) const;
bool allocatable(
const Resources& resources,
const std::string& role,
const Framework& framework) const;
bool initialized;
bool paused;
mesos::allocator::Options options;
// Recovery data.
Option<int> expectedAgentCount;
lambda::function<
void(const FrameworkID&,
const hashmap<std::string, hashmap<SlaveID, Resources>>&)>
offerCallback;
lambda::function<
void(const FrameworkID&,
const hashmap<SlaveID, UnavailableResources>&)>
inverseOfferCallback;
friend Metrics;
Metrics metrics;
double _event_queue_dispatches()
{
return static_cast<double>(eventCount<process::DispatchEvent>());
}
double _resources_total(
const std::string& resource);
double _resources_offered_or_allocated(
const std::string& resource);
double _quota_allocated(
const std::string& role,
const std::string& resource);
double _offer_filters_active(
const std::string& role);
hashmap<FrameworkID, Framework> frameworks;
BoundedHashMap<FrameworkID, process::Owned<FrameworkMetrics>>
completedFrameworkMetrics;
hashmap<SlaveID, Slave> slaves;
// A set of agents that are kept as allocation candidates. Events
// may add or remove candidates to the set. When an allocation is
// processed, the set of candidates is cleared.
hashset<SlaveID> allocationCandidates;
// Future for the dispatched allocation that becomes
// ready after the allocation run is complete.
Option<process::Future<Nothing>> allocation;
// We track information about roles that we're aware of in the system.
// Specifically, we keep track of the roles when a framework subscribes to
// the role, and/or when there are resources allocated to the role
// (e.g. some tasks and/or executors are consuming resources under the role).
hashmap<std::string, hashset<FrameworkID>> roles;
// Configured guaranteed resource quantities for each role, if any.
// If a role does not have an entry here it has (the default)
// no guarantee.
hashmap<std::string, ResourceQuantities> quotaGuarantees;
// Aggregated resource reservations on all agents tied to a
// particular role, if any.
//
// Only roles with non-empty scalar reservation quantities will
// be stored in the map.
hashmap<std::string, ResourceQuantities> reservationScalarQuantities;
// Slaves to send offers for.
Option<hashset<std::string>> whitelist;
// There are two stages of allocation:
//
// Stage 1: Allocate to satisfy quota guarantees.
//
// Stage 2: Allocate above quota guarantees up to quota limits.
// Note that we need to hold back enough "headroom"
// to ensure that any unsatisfied quota can be
// satisfied later.
//
// Each stage comprises two levels of sorting, hence "hierarchical".
// Level 1 sorts across roles:
// Currently, only the allocated portion of the reserved resources are
// accounted for fairness calculation.
//
// TODO(mpark): Reserved resources should be accounted for fairness
// calculation whether they are allocated or not, since they model a long or
// forever running task. That is, the effect of reserving resources is
// equivalent to launching a task in that the resources that make up the
// reservation are not available to other roles as non-revocable.
//
// Level 2 sorts across frameworks within a particular role:
// Reserved resources at this level are, and should be accounted for
// fairness calculation only if they are allocated. This is because
// reserved resources are fairly shared across the frameworks in the role.
//
// The allocator relies on `Sorter`s to employ a particular sorting
// algorithm. Each level has its own sorter and hence may have different
// fairness calculations.
//
// NOTE: The hierarchical allocator considers revocable resources as
// regular resources when doing fairness calculations.
//
// TODO(vinod): Consider using a different fairness algorithm for
// revocable resources.
// A sorter for active roles. This sorter determines the order in which
// roles are allocated resources during Level 1 of the second stage.
// The total cluster resources are used as the resource pool.
process::Owned<Sorter> roleSorter;
// TODO(bmahler): Remove this in favor of either using the same sorting
// between satisfying guarantees and bursting above guarantees up to
// limits, or have a different sorting technique specifically for
// satisfying guarantees (e.g. MESOS-8026). This is tech debt from
// when a "quota role" was considered different from a "non-quota"
// role. However, they are the same, one just has a default quota.
//
// A dedicated sorter for roles that have a non-default quota.
// This sorter determines the order in which guarantees are allocated
// during Level 1 of the first stage. Since only non-revocable
// resources are available for quota, the total cluster non-revocable
// resources are used as the resource pool.
//
// NOTE: A role appears in `quotaRoleSorter` if it has a non-default
// quota (even if no frameworks are currently registered in that role).
// In contrast, `roleSorter` only contains entries for roles with one
// or more registered frameworks.
process::Owned<Sorter> quotaRoleSorter;
// A collection of sorters, one per active role. Each sorter determines
// the order in which frameworks that belong to the same role are allocated
// resources inside the role's share. These sorters are used during Level 2
// for both the first and the second stages. Since frameworks are sharing
// the resources allocated to a role, the role's allocation is used as
// the resource pool for each role specific framework sorter.
hashmap<std::string, process::Owned<Sorter>> frameworkSorters;
// Factory function for framework sorters.
const std::function<Sorter*()> frameworkSorterFactory;
private:
bool isFrameworkTrackedUnderRole(
const FrameworkID& frameworkId,
const std::string& role) const;
void trackFrameworkUnderRole(
const FrameworkID& frameworkId,
const std::string& role);
void untrackFrameworkUnderRole(
const FrameworkID& frameworkId,
const std::string& role);
// `trackReservations` and `untrackReservations` are helpers
// to track role resource reservations. We need to keep
// track of reservations to enforce role quota limit
// in the presence of unallocated reservations. See MESOS-4527.
//
// TODO(mzhu): Ideally, we want these helpers to instead track the
// reservations as *allocated* in the sorters even when the
// reservations have not been allocated yet. This will help to:
//
// (1) Solve the fairness issue when roles with unallocated
// reservations may game the allocator (See MESOS-8299).
//
// (2) Simplify the quota enforcement logic -- the allocator
// would no longer need to track reservations separately.
void trackReservations(
const hashmap<std::string, Resources>& reservations);
void untrackReservations(
const hashmap<std::string, Resources>& reservations);
// Helper to update the agent's total resources maintained in the allocator
// and the role and quota sorters (whose total resources match the agent's
// total resources). Returns true iff the stored agent total was changed.
bool updateSlaveTotal(const SlaveID& slaveId, const Resources& total);
// Helper that returns true if the given agent is located in a
// different region than the master. This can only be the case if
// the agent and the master are both configured with a fault domain.
bool isRemoteSlave(const Slave& slave) const;
// Helper function that checks if a framework is capable of
// receiving resources on the agent based on the framework capability.
//
// TODO(mzhu): Make this a `Framework` member function once we pull
// `struct Framework` out from being nested.
bool isCapableOfReceivingAgent(
const protobuf::framework::Capabilities& frameworkCapabilities,
const Slave& slave) const;
// Helper function that removes any resources that the framework is not
// capable of receiving based on the given framework capability.
//
// TODO(mzhu): Make this a `Framework` member function once we pull
// `struct Framework` out from being nested.
Resources stripIncapableResources(
const Resources& resources,
const protobuf::framework::Capabilities& frameworkCapabilities) const;
// Helper to track allocated resources on an agent.
void trackAllocatedResources(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Resources& allocated);
// Helper to untrack resources that are no longer allocated on an agent.
void untrackAllocatedResources(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Resources& allocated);
// Helper that removes all existing offer filters for the given slave
// id.
void removeFilters(const SlaveID& slaveId);
};
} // namespace internal {
// We map the templatized version of the `HierarchicalAllocatorProcess` to one
// that relies on sorter factories in the internal namespace. This allows us
// to keep the implementation of the allocator in the implementation file.
template <
typename RoleSorter,
typename FrameworkSorter,
typename QuotaRoleSorter>
class HierarchicalAllocatorProcess
: public internal::HierarchicalAllocatorProcess
{
public:
HierarchicalAllocatorProcess()
: ProcessBase(process::ID::generate("hierarchical-allocator")),
internal::HierarchicalAllocatorProcess(
[this]() -> Sorter* {
return new RoleSorter(this->self(), "allocator/mesos/roles/");
},
[]() -> Sorter* { return new FrameworkSorter(); },
[]() -> Sorter* { return new QuotaRoleSorter(); }) {}
};
} // namespace allocator {
} // namespace master {
} // namespace internal {
} // namespace mesos {
#endif // __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
Added a NOTE/TODO to track reservations in the allocator's roles map.
Currently, the `roles` map does not track a role if it has a
reservation but no allocation or framework subscription. This
was an oversight and is unintuitive.
Review: https://reviews.apache.org/r/70392
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
#define __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
#include <set>
#include <string>
#include <mesos/mesos.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <process/owned.hpp>
#include <stout/boundedhashmap.hpp>
#include <stout/duration.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/lambda.hpp>
#include <stout/option.hpp>
#include "common/protobuf_utils.hpp"
#include "master/allocator/mesos/allocator.hpp"
#include "master/allocator/mesos/metrics.hpp"
#include "master/allocator/sorter/drf/sorter.hpp"
#include "master/allocator/sorter/random/sorter.hpp"
#include "master/constants.hpp"
namespace mesos {
namespace internal {
namespace master {
namespace allocator {
// We forward declare the hierarchical allocator process so that we
// can typedef an instantiation of it with DRF sorters.
template <
typename RoleSorter,
typename FrameworkSorter,
typename QuotaRoleSorter>
class HierarchicalAllocatorProcess;
typedef HierarchicalAllocatorProcess<DRFSorter, DRFSorter, DRFSorter>
HierarchicalDRFAllocatorProcess;
typedef MesosAllocator<HierarchicalDRFAllocatorProcess>
HierarchicalDRFAllocator;
typedef HierarchicalAllocatorProcess<RandomSorter, RandomSorter, RandomSorter>
HierarchicalRandomAllocatorProcess;
typedef MesosAllocator<HierarchicalRandomAllocatorProcess>
HierarchicalRandomAllocator;
namespace internal {
// Forward declarations.
class OfferFilter;
class InverseOfferFilter;
struct Framework
{
Framework(
const FrameworkInfo& frameworkInfo,
const std::set<std::string>& suppressedRoles,
bool active,
bool publishPerFrameworkMetrics);
std::set<std::string> roles;
std::set<std::string> suppressedRoles;
protobuf::framework::Capabilities capabilities;
// Active offer and inverse offer filters for the framework.
// Offer filters are tied to the role the filtered resources
// were allocated to.
hashmap<std::string, hashmap<SlaveID, hashset<OfferFilter*>>> offerFilters;
hashmap<SlaveID, hashset<InverseOfferFilter*>> inverseOfferFilters;
bool active;
bool publishPerFrameworkMetrics;
process::Owned<FrameworkMetrics> metrics;
// TODO(bbannier): Consider documenting examples on how to use this setting.
hashmap<std::string, std::vector<ResourceQuantities>> minAllocatableResources;
};
class Slave
{
public:
Slave(
const SlaveInfo& _info,
const protobuf::slave::Capabilities& _capabilities,
bool _activated,
const Resources& _total,
const Resources& _allocated)
: info(_info),
capabilities(_capabilities),
activated(_activated),
total(_total),
allocated(_allocated),
shared(_total.shared()),
hasGpu_(_total.gpus().getOrElse(0) > 0)
{
updateAvailable();
}
const Resources& getTotal() const { return total; }
const Resources& getAllocated() const { return allocated; }
const Resources& getAvailable() const { return available; }
bool hasGpu() const { return hasGpu_; }
void updateTotal(const Resources& newTotal) {
total = newTotal;
shared = total.shared();
hasGpu_ = total.gpus().getOrElse(0) > 0;
updateAvailable();
}
void allocate(const Resources& toAllocate)
{
allocated += toAllocate;
updateAvailable();
}
void unallocate(const Resources& toUnallocate)
{
allocated -= toUnallocate;
updateAvailable();
}
// The `SlaveInfo` that was passed to the allocator when the slave was added
// or updated. Currently only two fields are used: `hostname` for host
// whitelisting and in log messages, and `domain` for region-aware
// scheduling.
SlaveInfo info;
protobuf::slave::Capabilities capabilities;
bool activated; // Whether to offer resources.
// Represents a scheduled unavailability due to maintenance for a specific
// slave, and the responses from frameworks as to whether they will be able
// to gracefully handle this unavailability.
//
// NOTE: We currently implement maintenance in the allocator to be able to
// leverage state and features such as the FrameworkSorter and OfferFilter.
struct Maintenance
{
Maintenance(const Unavailability& _unavailability)
: unavailability(_unavailability) {}
// The start time and optional duration of the event.
Unavailability unavailability;
// A mapping of frameworks to the inverse offer status associated with
// this unavailability.
//
// NOTE: We currently lose this information during a master fail over
// since it is not persisted or replicated. This is ok as the new master's
// allocator will send out new inverse offers and re-collect the
// information. This is similar to all the outstanding offers from an old
// master being invalidated, and new offers being sent out.
hashmap<FrameworkID, mesos::allocator::InverseOfferStatus> statuses;
// Represents the "unit of accounting" for maintenance. When a
// `FrameworkID` is present in the hashset it means an inverse offer has
// been sent out. When it is not present it means no offer is currently
// outstanding.
hashset<FrameworkID> offersOutstanding;
};
// When the `maintenance` is set the slave is scheduled to be unavailable at
// a given point in time, for an optional duration. This information is used
// to send out `InverseOffers`.
Option<Maintenance> maintenance;
private:
void updateAvailable() {
// In order to subtract from the total,
// we strip the allocation information.
Resources allocated_ = allocated;
allocated_.unallocate();
// Calling `nonShared()` currently copies the underlying resources
// and is therefore rather expensive. We avoid it in the common
// case that there are no shared resources.
//
// TODO(mzhu): Ideally there would be a single logical path here.
// One solution is to have `Resources` be copy-on-write such that
// `nonShared()` performs no copying and instead points to a
// subset of the original `Resource` objects.
if (shared.empty()) {
available = total - allocated_;
} else {
// Since shared resources are offerable even when they are in use, we
// always include them as part of available resources.
available = (total.nonShared() - allocated_.nonShared()) + shared;
}
}
// Total amount of regular *and* oversubscribed resources.
Resources total;
// Regular *and* oversubscribed resources that are allocated.
//
// NOTE: We maintain multiple copies of each shared resource allocated
// to a slave, where the number of copies represents the number of times
// this shared resource has been allocated to (and has not been recovered
// from) a specific framework.
//
// NOTE: We keep track of the slave's allocated resources despite
// having that information in sorters. This is because the
// information in sorters is not accurate if some framework
// hasn't reregistered. See MESOS-2919 for details.
Resources allocated;
// We track the total and allocated resources on the slave to
// avoid calculating it in place every time.
//
// Note that `available` always contains all the shared resources on the
// agent regardless whether they have ever been allocated or not.
// NOTE, however, we currently only offer a shared resource only if it has
// not been offered in an allocation cycle to a framework. We do this mainly
// to preserve the normal offer behavior. This may change in the future
// depending on use cases.
//
// Note that it's possible for the slave to be over-allocated!
// In this case, allocated > total.
Resources available;
// We keep a copy of the shared resources to avoid unnecessary copying.
Resources shared;
// We cache whether the agent has gpus as an optimization.
bool hasGpu_;
};
// Implements the basic allocator algorithm - first pick a role by
// some criteria, then pick one of their frameworks to allocate to.
class HierarchicalAllocatorProcess : public MesosAllocatorProcess
{
public:
HierarchicalAllocatorProcess(
const std::function<Sorter*()>& roleSorterFactory,
const std::function<Sorter*()>& _frameworkSorterFactory,
const std::function<Sorter*()>& quotaRoleSorterFactory)
: initialized(false),
paused(true),
metrics(*this),
completedFrameworkMetrics(0),
roleSorter(roleSorterFactory()),
quotaRoleSorter(quotaRoleSorterFactory()),
frameworkSorterFactory(_frameworkSorterFactory) {}
~HierarchicalAllocatorProcess() override {}
process::PID<HierarchicalAllocatorProcess> self() const
{
return process::PID<Self>(this);
}
void initialize(
const mesos::allocator::Options& options,
const lambda::function<
void(const FrameworkID&,
const hashmap<std::string, hashmap<SlaveID, Resources>>&)>&
offerCallback,
const lambda::function<
void(const FrameworkID&,
const hashmap<SlaveID, UnavailableResources>&)>&
inverseOfferCallback) override;
void recover(
const int _expectedAgentCount,
const hashmap<std::string, Quota>& quotas) override;
void addFramework(
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const hashmap<SlaveID, Resources>& used,
bool active,
const std::set<std::string>& suppressedRoles) override;
void removeFramework(
const FrameworkID& frameworkId) override;
void activateFramework(
const FrameworkID& frameworkId) override;
void deactivateFramework(
const FrameworkID& frameworkId) override;
void updateFramework(
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const std::set<std::string>& suppressedRoles) override;
void addSlave(
const SlaveID& slaveId,
const SlaveInfo& slaveInfo,
const std::vector<SlaveInfo::Capability>& capabilities,
const Option<Unavailability>& unavailability,
const Resources& total,
const hashmap<FrameworkID, Resources>& used) override;
void removeSlave(
const SlaveID& slaveId) override;
void updateSlave(
const SlaveID& slave,
const SlaveInfo& slaveInfo,
const Option<Resources>& total = None(),
const Option<std::vector<SlaveInfo::Capability>>& capabilities = None())
override;
void addResourceProvider(
const SlaveID& slave,
const Resources& total,
const hashmap<FrameworkID, Resources>& used) override;
void deactivateSlave(
const SlaveID& slaveId) override;
void activateSlave(
const SlaveID& slaveId) override;
void updateWhitelist(
const Option<hashset<std::string>>& whitelist) override;
void requestResources(
const FrameworkID& frameworkId,
const std::vector<Request>& requests) override;
void updateAllocation(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
const Resources& offeredResources,
const std::vector<ResourceConversion>& conversions) override;
process::Future<Nothing> updateAvailable(
const SlaveID& slaveId,
const std::vector<Offer::Operation>& operations) override;
void updateUnavailability(
const SlaveID& slaveId,
const Option<Unavailability>& unavailability) override;
void updateInverseOffer(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Option<UnavailableResources>& unavailableResources,
const Option<mesos::allocator::InverseOfferStatus>& status,
const Option<Filters>& filters) override;
process::Future<
hashmap<SlaveID,
hashmap<FrameworkID, mesos::allocator::InverseOfferStatus>>>
getInverseOfferStatuses() override;
void recoverResources(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
const Resources& resources,
const Option<Filters>& filters) override;
void suppressOffers(
const FrameworkID& frameworkId,
const std::set<std::string>& roles) override;
void reviveOffers(
const FrameworkID& frameworkId,
const std::set<std::string>& roles) override;
void setQuota(
const std::string& role,
const Quota& quota) override;
void removeQuota(
const std::string& role) override;
void updateWeights(
const std::vector<WeightInfo>& weightInfos) override;
void pause() override;
void resume() override;
protected:
// Useful typedefs for dispatch/delay/defer to self()/this.
typedef HierarchicalAllocatorProcess Self;
typedef HierarchicalAllocatorProcess This;
// Allocate any allocatable resources from all known agents.
process::Future<Nothing> allocate();
// Allocate resources from the specified agent.
process::Future<Nothing> allocate(const SlaveID& slaveId);
// Allocate resources from the specified agents. The allocation
// is deferred and batched with other allocation requests.
process::Future<Nothing> allocate(const hashset<SlaveID>& slaveIds);
// Method that performs allocation work.
Nothing _allocate();
// Helper for `_allocate()` that allocates resources for offers.
void __allocate();
// Helper for `_allocate()` that deallocates resources for inverse offers.
void deallocate();
// Remove an offer filter for the specified role of the framework.
void expire(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
OfferFilter* offerFilter);
void _expire(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
OfferFilter* offerFilter);
// Remove an inverse offer filter for the specified framework.
void expire(
const FrameworkID& frameworkId,
const SlaveID& slaveId,
InverseOfferFilter* inverseOfferFilter);
// Checks whether the slave is whitelisted.
bool isWhitelisted(const SlaveID& slaveId) const;
// Returns true if there is a resource offer filter for the
// specified role of this framework on this slave.
bool isFiltered(
const FrameworkID& frameworkId,
const std::string& role,
const SlaveID& slaveId,
const Resources& resources) const;
// Returns true if there is an inverse offer filter for this framework
// on this slave.
bool isFiltered(
const FrameworkID& frameworkID,
const SlaveID& slaveID) const;
bool allocatable(
const Resources& resources,
const std::string& role,
const Framework& framework) const;
bool initialized;
bool paused;
mesos::allocator::Options options;
// Recovery data.
Option<int> expectedAgentCount;
lambda::function<
void(const FrameworkID&,
const hashmap<std::string, hashmap<SlaveID, Resources>>&)>
offerCallback;
lambda::function<
void(const FrameworkID&,
const hashmap<SlaveID, UnavailableResources>&)>
inverseOfferCallback;
friend Metrics;
Metrics metrics;
double _event_queue_dispatches()
{
return static_cast<double>(eventCount<process::DispatchEvent>());
}
double _resources_total(
const std::string& resource);
double _resources_offered_or_allocated(
const std::string& resource);
double _quota_allocated(
const std::string& role,
const std::string& resource);
double _offer_filters_active(
const std::string& role);
hashmap<FrameworkID, Framework> frameworks;
BoundedHashMap<FrameworkID, process::Owned<FrameworkMetrics>>
completedFrameworkMetrics;
hashmap<SlaveID, Slave> slaves;
// A set of agents that are kept as allocation candidates. Events
// may add or remove candidates to the set. When an allocation is
// processed, the set of candidates is cleared.
hashset<SlaveID> allocationCandidates;
// Future for the dispatched allocation that becomes
// ready after the allocation run is complete.
Option<process::Future<Nothing>> allocation;
// We track information about roles that we're aware of in the system.
// Specifically, we keep track of the roles when a framework subscribes to
// the role, and/or when there are resources allocated to the role
// (e.g. some tasks and/or executors are consuming resources under the role).
//
// NOTE: There is currently not a role entry when there is a
// reservation but no allocation / framework!
//
// TODO(bmahler): Turn this into a `hashmap<string, Role>` that
// also tracks a role if it has reservations.
hashmap<std::string, hashset<FrameworkID>> roles;
// Configured guaranteed resource quantities for each role, if any.
// If a role does not have an entry here it has (the default)
// no guarantee.
hashmap<std::string, ResourceQuantities> quotaGuarantees;
// Aggregated resource reservations on all agents tied to a
// particular role, if any.
//
// Only roles with non-empty scalar reservation quantities will
// be stored in the map.
hashmap<std::string, ResourceQuantities> reservationScalarQuantities;
// Slaves to send offers for.
Option<hashset<std::string>> whitelist;
// There are two stages of allocation:
//
// Stage 1: Allocate to satisfy quota guarantees.
//
// Stage 2: Allocate above quota guarantees up to quota limits.
// Note that we need to hold back enough "headroom"
// to ensure that any unsatisfied quota can be
// satisfied later.
//
// Each stage comprises two levels of sorting, hence "hierarchical".
// Level 1 sorts across roles:
// Currently, only the allocated portion of the reserved resources are
// accounted for fairness calculation.
//
// TODO(mpark): Reserved resources should be accounted for fairness
// calculation whether they are allocated or not, since they model a long or
// forever running task. That is, the effect of reserving resources is
// equivalent to launching a task in that the resources that make up the
// reservation are not available to other roles as non-revocable.
//
// Level 2 sorts across frameworks within a particular role:
// Reserved resources at this level are, and should be accounted for
// fairness calculation only if they are allocated. This is because
// reserved resources are fairly shared across the frameworks in the role.
//
// The allocator relies on `Sorter`s to employ a particular sorting
// algorithm. Each level has its own sorter and hence may have different
// fairness calculations.
//
// NOTE: The hierarchical allocator considers revocable resources as
// regular resources when doing fairness calculations.
//
// TODO(vinod): Consider using a different fairness algorithm for
// revocable resources.
// A sorter for active roles. This sorter determines the order in which
// roles are allocated resources during Level 1 of the second stage.
// The total cluster resources are used as the resource pool.
process::Owned<Sorter> roleSorter;
// TODO(bmahler): Remove this in favor of either using the same sorting
// between satisfying guarantees and bursting above guarantees up to
// limits, or have a different sorting technique specifically for
// satisfying guarantees (e.g. MESOS-8026). This is tech debt from
// when a "quota role" was considered different from a "non-quota"
// role. However, they are the same, one just has a default quota.
//
// A dedicated sorter for roles that have a non-default quota.
// This sorter determines the order in which guarantees are allocated
// during Level 1 of the first stage. Since only non-revocable
// resources are available for quota, the total cluster non-revocable
// resources are used as the resource pool.
//
// NOTE: A role appears in `quotaRoleSorter` if it has a non-default
// quota (even if no frameworks are currently registered in that role).
// In contrast, `roleSorter` only contains entries for roles with one
// or more registered frameworks.
process::Owned<Sorter> quotaRoleSorter;
// A collection of sorters, one per active role. Each sorter determines
// the order in which frameworks that belong to the same role are allocated
// resources inside the role's share. These sorters are used during Level 2
// for both the first and the second stages. Since frameworks are sharing
// the resources allocated to a role, the role's allocation is used as
// the resource pool for each role specific framework sorter.
hashmap<std::string, process::Owned<Sorter>> frameworkSorters;
// Factory function for framework sorters.
const std::function<Sorter*()> frameworkSorterFactory;
private:
bool isFrameworkTrackedUnderRole(
const FrameworkID& frameworkId,
const std::string& role) const;
void trackFrameworkUnderRole(
const FrameworkID& frameworkId,
const std::string& role);
void untrackFrameworkUnderRole(
const FrameworkID& frameworkId,
const std::string& role);
// `trackReservations` and `untrackReservations` are helpers
// to track role resource reservations. We need to keep
// track of reservations to enforce role quota limit
// in the presence of unallocated reservations. See MESOS-4527.
//
// TODO(mzhu): Ideally, we want these helpers to instead track the
// reservations as *allocated* in the sorters even when the
// reservations have not been allocated yet. This will help to:
//
// (1) Solve the fairness issue when roles with unallocated
// reservations may game the allocator (See MESOS-8299).
//
// (2) Simplify the quota enforcement logic -- the allocator
// would no longer need to track reservations separately.
void trackReservations(
const hashmap<std::string, Resources>& reservations);
void untrackReservations(
const hashmap<std::string, Resources>& reservations);
// Helper to update the agent's total resources maintained in the allocator
// and the role and quota sorters (whose total resources match the agent's
// total resources). Returns true iff the stored agent total was changed.
bool updateSlaveTotal(const SlaveID& slaveId, const Resources& total);
// Helper that returns true if the given agent is located in a
// different region than the master. This can only be the case if
// the agent and the master are both configured with a fault domain.
bool isRemoteSlave(const Slave& slave) const;
// Helper function that checks if a framework is capable of
// receiving resources on the agent based on the framework capability.
//
// TODO(mzhu): Make this a `Framework` member function once we pull
// `struct Framework` out from being nested.
bool isCapableOfReceivingAgent(
const protobuf::framework::Capabilities& frameworkCapabilities,
const Slave& slave) const;
// Helper function that removes any resources that the framework is not
// capable of receiving based on the given framework capability.
//
// TODO(mzhu): Make this a `Framework` member function once we pull
// `struct Framework` out from being nested.
Resources stripIncapableResources(
const Resources& resources,
const protobuf::framework::Capabilities& frameworkCapabilities) const;
// Helper to track allocated resources on an agent.
void trackAllocatedResources(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Resources& allocated);
// Helper to untrack resources that are no longer allocated on an agent.
void untrackAllocatedResources(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const Resources& allocated);
// Helper that removes all existing offer filters for the given slave
// id.
void removeFilters(const SlaveID& slaveId);
};
} // namespace internal {
// We map the templatized version of the `HierarchicalAllocatorProcess` to one
// that relies on sorter factories in the internal namespace. This allows us
// to keep the implementation of the allocator in the implementation file.
template <
typename RoleSorter,
typename FrameworkSorter,
typename QuotaRoleSorter>
class HierarchicalAllocatorProcess
: public internal::HierarchicalAllocatorProcess
{
public:
HierarchicalAllocatorProcess()
: ProcessBase(process::ID::generate("hierarchical-allocator")),
internal::HierarchicalAllocatorProcess(
[this]() -> Sorter* {
return new RoleSorter(this->self(), "allocator/mesos/roles/");
},
[]() -> Sorter* { return new FrameworkSorter(); },
[]() -> Sorter* { return new QuotaRoleSorter(); }) {}
};
} // namespace allocator {
} // namespace master {
} // namespace internal {
} // namespace mesos {
#endif // __MASTER_ALLOCATOR_MESOS_HIERARCHICAL_HPP__
|
/**
* @file
* brief description, full stop.
*
* long description, many sentences.
*
*/
#include "angort.h"
#include "hash.h"
#include "cycle.h"
#include "types/symbol.h"
namespace angort {
HashObject::HashObject() : GarbageCollected() {
hash = new Hash();
}
HashObject::~HashObject(){
delete hash;
}
Iterator<Value *> *HashObject::makeValueIterator() {
return hash->createIterator(false);
}
Iterator<Value *> *HashObject::makeKeyIterator() {
return hash->createIterator(true);
}
Hash *HashType::set(Value *v){
v->clr();
v->t = this;
HashObject *h = new HashObject();
v->v.hash = h;
incRef(v);
return h->hash;
}
void HashType::set(Value *v,HashObject *ho){
v->clr();
v->t = this;
v->v.hash = ho;
incRef(v);
}
Hash *HashType::get(Value *v){
if(v->t != this)
throw RUNT("not a hash");
return v->v.hash->hash;
}
void HashType::setValue(Value *coll,Value *k,Value *v){
Hash *h = coll->v.hash->hash;
h->set(k,v);
}
void HashType::getValue(Value *coll,Value *k,Value *result){
Hash *h = coll->v.hash->hash;
if(h->find(k))
result->copy(h->getval());
else
result->clr();
}
int HashType::getCount(Value *coll){
Hash *h = coll->v.hash->hash;
return h->count();
}
void HashType::removeAndReturn(Value *coll,Value *k,Value *result){
Hash *h = coll->v.hash->hash;
if(h->find(k)){
result->copy(h->getval());
h->del(k);
} else
result->clr();
}
bool HashType::isIn(Value *coll,Value *item){
Hash *h = coll->v.hash->hash;
if(h->find(item))
return true;
else
return false;
}
void HashType::clone(Value *out,const Value *in,bool deep){
HashObject *p = new HashObject();
Hash *h = get(const_cast<Value *>(in));
// cast away constness - makeIterator() can't be const
// because it modifies refcounts
HashKeyIterator iter(h);
for(iter.first();!iter.isDone();iter.next()){
Value *k = iter.current();
Value *v;
if(h->find(k))
v = h->getval();
else
throw WTF;
// because collections can't be keys, we only need worry
// about the value for deep cloning.
if(deep){
Value deepv;
v->t->clone(&deepv,v);
p->hash->set(k,&deepv); // hash will copy the value
} else {
p->hash->set(k,v);
}
}
out->clr();
out->t = this;
out->v.hash = p;
incRef(out);
}
const char *HashType::toString(bool *allocated,const Value *v) const {
// first, does the hash contain the toString symbol key?
static int symbKey=-1;
if(symbKey<0)
symbKey = Types::tSymbol->getSymbol("toString");
Value k;
Types::tSymbol->set(&k,symbKey);
Hash *h = v->v.hash->hash;
if(h->find(&k)){
// is it a function?
Value *outval = h->getval();
if(outval->t->isCallable()){
Angort *a = Angort::getCallingInstance();
// Yes, so call the function and get the returned value
a->pushval()->copy(v);
// have to turn debugging off during this to avoid
// infinite recursion
int olddeb = a->debug;
a->debug=0;
a->runValue(outval);
outval = a->popval();
a->debug=olddeb;
return outval->t->toString(allocated,outval);
} else {
// if not, just turn it into a string and use that
return outval->t->toString(allocated,outval);
}
}
// otherwise, do the default operation
return Type::toString(allocated,v);
}
}
Typechecking for hash set value.
/**
* @file
* brief description, full stop.
*
* long description, many sentences.
*
*/
#include "angort.h"
#include "hash.h"
#include "cycle.h"
#include "types/symbol.h"
namespace angort {
HashObject::HashObject() : GarbageCollected() {
hash = new Hash();
}
HashObject::~HashObject(){
delete hash;
}
Iterator<Value *> *HashObject::makeValueIterator() {
return hash->createIterator(false);
}
Iterator<Value *> *HashObject::makeKeyIterator() {
return hash->createIterator(true);
}
Hash *HashType::set(Value *v){
v->clr();
v->t = this;
HashObject *h = new HashObject();
v->v.hash = h;
incRef(v);
return h->hash;
}
void HashType::set(Value *v,HashObject *ho){
v->clr();
v->t = this;
v->v.hash = ho;
incRef(v);
}
Hash *HashType::get(Value *v){
if(v->t != this)
throw RUNT("").set("not a hash, is a %s",v->t->name);
return v->v.hash->hash;
}
void HashType::setValue(Value *coll,Value *k,Value *v){
if(coll->t != this)
throw RUNT("").set("not a hash, is a %s",coll->t->name);
Hash *h = coll->v.hash->hash;
h->set(k,v);
}
void HashType::getValue(Value *coll,Value *k,Value *result){
Hash *h = coll->v.hash->hash;
if(h->find(k))
result->copy(h->getval());
else
result->clr();
}
int HashType::getCount(Value *coll){
Hash *h = coll->v.hash->hash;
return h->count();
}
void HashType::removeAndReturn(Value *coll,Value *k,Value *result){
Hash *h = coll->v.hash->hash;
if(h->find(k)){
result->copy(h->getval());
h->del(k);
} else
result->clr();
}
bool HashType::isIn(Value *coll,Value *item){
Hash *h = coll->v.hash->hash;
if(h->find(item))
return true;
else
return false;
}
void HashType::clone(Value *out,const Value *in,bool deep){
HashObject *p = new HashObject();
Hash *h = get(const_cast<Value *>(in));
// cast away constness - makeIterator() can't be const
// because it modifies refcounts
HashKeyIterator iter(h);
for(iter.first();!iter.isDone();iter.next()){
Value *k = iter.current();
Value *v;
if(h->find(k))
v = h->getval();
else
throw WTF;
// because collections can't be keys, we only need worry
// about the value for deep cloning.
if(deep){
Value deepv;
v->t->clone(&deepv,v);
p->hash->set(k,&deepv); // hash will copy the value
} else {
p->hash->set(k,v);
}
}
out->clr();
out->t = this;
out->v.hash = p;
incRef(out);
}
const char *HashType::toString(bool *allocated,const Value *v) const {
// first, does the hash contain the toString symbol key?
static int symbKey=-1;
if(symbKey<0)
symbKey = Types::tSymbol->getSymbol("toString");
Value k;
Types::tSymbol->set(&k,symbKey);
Hash *h = v->v.hash->hash;
if(h->find(&k)){
// is it a function?
Value *outval = h->getval();
if(outval->t->isCallable()){
Angort *a = Angort::getCallingInstance();
// Yes, so call the function and get the returned value
a->pushval()->copy(v);
// have to turn debugging off during this to avoid
// infinite recursion
int olddeb = a->debug;
a->debug=0;
a->runValue(outval);
outval = a->popval();
a->debug=olddeb;
return outval->t->toString(allocated,outval);
} else {
// if not, just turn it into a string and use that
return outval->t->toString(allocated,outval);
}
}
// otherwise, do the default operation
return Type::toString(allocated,v);
}
}
|
// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Apr 2004
// Bindings
#include "PyROOT.h"
#include "PyRootType.h"
#include "ObjectProxy.h"
#include "MethodProxy.h"
#include "TemplateProxy.h"
#include "PropertyProxy.h"
#include "RootWrapper.h"
#include "Pythonize.h"
#include "MethodHolder.h"
#include "ConstructorHolder.h"
#include "ClassMethodHolder.h"
#include "FunctionHolder.h"
#include "TSetItemHolder.h"
#include "MemoryRegulator.h"
#include "Utility.h"
#include "Adapters.h"
// ROOT
#include "TROOT.h"
#include "TSystem.h"
#include "TMethod.h"
#include "TDataMember.h"
#include "TBaseClass.h"
#include "TInterpreter.h"
#include "TGlobal.h"
#include "DllImport.h"
// CINT
#include "Api.h"
// Reflex
#ifdef PYROOT_USE_REFLEX
#include "Reflex/Scope.h"
#include "Reflex/Base.h"
#include "Reflex/Member.h"
#include "Reflex/Object.h"
#endif
// Standard
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <vector>
//- data _______________________________________________________________________
R__EXTERN PyObject* gRootModule;
namespace {
// to prevent having to walk scopes, track python classes by ROOT class
typedef std::map< void*, PyObject* > PyClassMap_t;
PyClassMap_t gPyClasses;
// helper for creating new ROOT python types
PyObject* CreateNewROOTPythonClass( const std::string& name, PyObject* pybases )
{
Py_XINCREF( pybases );
if ( ! pybases ) {
pybases = PyTuple_New( 1 );
Py_INCREF( &PyROOT::ObjectProxy_Type );
PyTuple_SET_ITEM( pybases, 0, (PyObject*)(void*)&PyROOT::ObjectProxy_Type );
}
PyObject* pymetabases = PyTuple_New( PyTuple_GET_SIZE( pybases ) );
for ( int i = 0; i < PyTuple_GET_SIZE( pybases ); ++i ) {
PyObject* btype = (PyObject*)PyTuple_GetItem( pybases, i )->ob_type;
Py_INCREF( btype );
PyTuple_SET_ITEM( pymetabases, i, btype );
}
PyObject* args = Py_BuildValue( (char*)"sO{}", (name+"_meta").c_str(), pymetabases );
Py_DECREF( pymetabases );
PyObject* pymeta = PyType_Type.tp_new( &PyROOT::PyRootType_Type, args, NULL );
if ( ! pymeta )
PyErr_Print();
Py_DECREF( args );
args = Py_BuildValue( (char*)"sO{}", name.c_str(), pybases );
PyObject* pyclass = PyType_Type.tp_new( (PyTypeObject*)pymeta, args, NULL );
Py_DECREF( args );
Py_DECREF( pymeta );
Py_DECREF( pybases );
return pyclass;
}
// helper to split between CINT and Reflex
Long_t GetDataMemberAddress( TClass* klass, TDataMember* mb )
{
Long_t offset = 0;
G__DataMemberInfo dmi = klass->GetClassInfo()->GetDataMember( mb->GetName(), &offset );
return dmi.Offset();
}
#ifdef PYROOT_USE_REFLEX
Long_t GetDataMemberAddress( const ROOT::Reflex::Scope&, const ROOT::Reflex::Member& mb )
{
return (Long_t)mb.Offset();
}
#endif
} // unnamed namespace
//- helpers --------------------------------------------------------------------
namespace {
inline void AddToScope( const char* label, TObject* obj, TClass* klass )
{
PyModule_AddObject( gRootModule, const_cast< char* >( label ),
PyROOT::BindRootObject( obj, klass ) );
}
std::set< std::string > gSTLTypes, gLoadedSTLTypes;
struct InitSTLTypes_t {
InitSTLTypes_t()
{
const char* stlTypes[] = { "complex", "exception",
"deque", "list", "queue", "stack", "vector",
"map", "multimap", "set", "multiset" };
std::string nss = "std::";
for ( int i = 0; i < int(sizeof(stlTypes)/sizeof(stlTypes[0])); ++i ) {
gSTLTypes.insert( stlTypes[ i ] );
gSTLTypes.insert( nss + stlTypes[ i ] );
}
gLoadedSTLTypes.insert( "vector" );
}
} initSTLTypes_;
Bool_t LoadDictionaryForSTLType( const std::string& tname, void* klass )
{
// if name is of a known STL class, tell CINT to load the dll(s), always reset klass
std::string sub = tname.substr( 0, tname.find( "<" ) );
if ( gSTLTypes.find( sub ) != gSTLTypes.end() ) {
// removal is required or the dictionary can't be updated properly
if ( klass != 0 )
TClass::RemoveClass( (TClass*)klass );
// make sure to only load once
if ( gLoadedSTLTypes.find( sub ) == gLoadedSTLTypes.end() ) {
// strip std:: part as needed to form proper file name
if ( sub.substr( 0, 5 ) == "std::" )
sub = sub.substr( 5, std::string::npos );
// tell CINT to go for it
gROOT->ProcessLine( (std::string( "#include <" ) + sub + ">").c_str() );
// prevent second attempt to load by erasing name
gLoadedSTLTypes.insert( sub );
gLoadedSTLTypes.insert( "std::" + sub );
}
return kTRUE;
}
// this point is only reached if this is not an STL class, but that's ok
return kTRUE;
}
} // unnamed namespace
//- public functions ---------------------------------------------------------
void PyROOT::InitRoot()
{
// setup interpreter locks to allow for threading in ROOT
PyEval_InitThreads();
// memory management
static TMemoryRegulator m;
gROOT->GetListOfCleanups()->Add( &m );
// bind ROOT globals that are needed in ROOT.py
AddToScope( "gROOT", gROOT, gROOT->IsA() );
AddToScope( "gSystem", gSystem, gSystem->IsA() );
AddToScope( "gInterpreter", gInterpreter, gInterpreter->IsA() );
}
//____________________________________________________________________________
template< class T, class B, class M >
int PyROOT::BuildRootClassDict( const T& klass, PyObject* pyclass ) {
// get the unscoped class name
std::string clName = klass.Name();
// some properties that'll affect building the dictionary
Bool_t isNamespace = klass.IsNamespace();
Bool_t hasConstructor = kFALSE;
// load all public methods and data members
typedef std::vector< PyCallable* > Callables_t;
typedef std::map< std::string, Callables_t > CallableCache_t;
CallableCache_t cache;
const size_t nMethods = klass.FunctionMemberSize();
for ( size_t inm = 0; inm < nMethods; ++inm ) {
const M& method = klass.FunctionMemberAt( inm );
// special case tracker
Bool_t setupSetItem = kFALSE;
// retrieve method name
std::string mtName = method.Name();
// filter empty names (happens for namespaces, is bug?)
if ( mtName == "" )
continue;
// filter C++ destructors
if ( mtName[0] == '~' )
continue;
// translate operators
if ( 8 < mtName.size() && mtName.substr( 0, 8 ) == "operator" ) {
std::string op = mtName.substr( 8, std::string::npos );
// stripping ...
std::string::size_type start = 0, end = op.size();
while ( start < end && isspace( op[ start ] ) ) ++start;
while ( start < end && isspace( op[ end-1 ] ) ) --end;
op = op.substr( start, end - start );
// filter assignment operator for later use
if ( op == "=" ) {
continue;
}
// map C++ operator to python equivalent, or made up name if no equivalent exists
Utility::TC2POperatorMapping_t::iterator pop = Utility::gC2POperatorMapping.find( op );
if ( pop != Utility::gC2POperatorMapping.end() ) {
mtName = pop->second;
} else if ( op == "[]" || op == "()" ) { // index or call
mtName = op == "()" ? "__call__" : "__getitem__";
// operator[]/() returning a reference type will be used for __setitem__
std::string cpd = Utility::Compound(
method.TypeOf().ReturnType().Name( ROOT::Reflex::Q | ROOT::Reflex::S ) );
if ( cpd[ cpd.size() - 1 ] == '&' )
setupSetItem = kTRUE;
} else if ( op == "*" ) {
// dereference v.s. multiplication of two instances
mtName = method.FunctionParameterSize() ? "__mul__" : "__deref__";
} else if ( op == "+" ) {
// unary positive v.s. addition of two instances
mtName = method.FunctionParameterSize() ? "__add__" : "__pos__";
} else if ( op == "-" ) {
// unary negative v.s. subtraction of two instances
mtName = method.FunctionParameterSize() ? "__sub__" : "__neg__";
} else if ( op == "++" ) {
// prefix v.s. postfix increment
mtName = method.FunctionParameterSize() ? "__postinc__" : "__preinc__";
} else if ( op == "--" ) {
// prefix v.s. postfix decrement
mtName = method.FunctionParameterSize() ? "__postdec__" : "__predec__";
} else if ( op == "->" ) { // class member access
mtName = "__follow__";
} else {
continue; // not handled (new, delete, etc.)
}
}
// decide on method type: member or static (which includes globals)
Bool_t isStatic = isNamespace || method.IsStatic();
// template members; handled by adding a dispatcher to the class
if ( ! isStatic && mtName[mtName.size()-1] == '>' ) {
std::string tmplname = mtName.substr( 0, mtName.find('<') );
TemplateProxy* pytmpl = TemplateProxy_New( tmplname, pyclass );
PyObject_SetAttrString(
pyclass, const_cast< char* >( tmplname.c_str() ), (PyObject*)pytmpl );
Py_DECREF( pytmpl );
// note: need to continue here to actually add the method ...
}
// public methods are normally visible, private methods are mangled python-wise
// note the overload implications which are name based, and note that rootcint
// does not create the interface methods for private/protected methods ...
if ( ! method.IsPublic() ) {
if ( mtName == clName ) // don't expose private ctors
continue;
else // mangle private methods
mtName = "_" + clName + "__" + mtName;
}
// construct the holder
PyCallable* pycall = 0;
if ( isStatic == kTRUE ) // class method
pycall = new TClassMethodHolder< T, M >( klass, method );
else if ( mtName == clName ) { // constructor
pycall = new TConstructorHolder< T, M >( klass, method );
mtName = "__init__";
hasConstructor = kTRUE;
} else // member function
pycall = new TMethodHolder< T, M >( klass, method );
// lookup method dispatcher and store method
Callables_t& md = (*(cache.insert(
std::make_pair( mtName, Callables_t() ) ).first)).second;
md.push_back( pycall );
// special case for operator[]/() that returns by ref, use for getitem/call and setitem
if ( setupSetItem ) {
Callables_t& setitem = (*(cache.insert(
std::make_pair( std::string( "__setitem__" ), Callables_t() ) ).first)).second;
setitem.push_back( new TSetItemHolder< T, M >( klass, method ) );
}
}
// add a pseudo-default ctor, if none defined
if ( ! isNamespace && ! hasConstructor )
cache[ "__init__" ].push_back( new TConstructorHolder< T, M >( klass ) );
// add the methods to the class dictionary
for ( CallableCache_t::iterator imd = cache.begin(); imd != cache.end(); ++imd ) {
MethodProxy* method = MethodProxy_New( imd->first, imd->second );
PyObject_SetAttrString(
pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
Py_DECREF( method );
}
// collect data members
const size_t nDataMembers = klass.DataMemberSize();
for ( size_t ind = 0; ind < nDataMembers; ++ind ) {
const M& mb = klass.DataMemberAt( ind );
// allow only public members
if ( ! mb.IsPublic() )
continue;
// enums (static enums are the defined values, non-static are data members, i.e. properties)
if ( mb.TypeOf().IsEnum() && mb.IsStatic() ) {
PyObject* val = PyInt_FromLong( *((Long_t*)GetDataMemberAddress( klass, mb ) ) );
PyObject_SetAttrString( pyclass, const_cast<char*>(mb.Name().c_str()), val );
Py_DECREF( val );
// properties (aka public data members)
} else {
PropertyProxy* property = PropertyProxy_New( mb );
// allow access at the instance level
PyObject_SetAttrString( pyclass,
const_cast< char* >( property->GetName().c_str() ), (PyObject*)property );
if ( mb.IsStatic() ) {
// allow access at the class level (always add after setting instance level)
PyObject_SetAttrString( (PyObject*)pyclass->ob_type,
const_cast< char* >( property->GetName().c_str() ), (PyObject*)property );
}
Py_DECREF( property );
}
}
// all ok, done
return 0;
}
//____________________________________________________________________________
template< class T, class B, class M >
PyObject* PyROOT::BuildRootClassBases( const T& klass )
{
size_t nbases = klass.BaseSize();
// collect bases while removing duplicates
std::vector< std::string > uqb;
uqb.reserve( nbases );
for ( size_t inb = 0; inb < nbases; ++inb ) {
const B& base = klass.BaseAt( inb );
std::string name = base.Name();
if ( std::find( uqb.begin(), uqb.end(), name ) == uqb.end() ) {
uqb.push_back( name );
}
}
// allocate a tuple for the base classes, special case for first base
nbases = uqb.size();
PyObject* pybases = PyTuple_New( nbases ? nbases : 1 );
if ( ! pybases )
return 0;
// build all the bases
if ( nbases == 0 ) {
Py_INCREF( &ObjectProxy_Type );
PyTuple_SET_ITEM( pybases, 0, (PyObject*)(void*)&ObjectProxy_Type );
} else {
for ( std::vector< std::string >::size_type ibase = 0; ibase < nbases; ++ibase ) {
PyObject* pyclass = MakeRootClassFromString< T, B, M >( uqb[ ibase ] );
if ( ! pyclass ) {
Py_DECREF( pybases );
return 0;
}
PyTuple_SET_ITEM( pybases, ibase, pyclass );
}
}
return pybases;
}
#ifdef PYROOT_USE_REFLEX
template PyObject* PyROOT::BuildRootClassBases< \
ROOT::Reflex::Scope, ROOT::Reflex::Base, ROOT::Reflex::Member >( const ROOT::Reflex::Scope& );
#endif
//____________________________________________________________________________
PyObject* PyROOT::MakeRootClass( PyObject*, PyObject* args )
{
std::string cname = PyString_AsString( PyTuple_GetItem( args, 0 ) );
if ( PyErr_Occurred() )
return 0;
return MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( cname );
}
//____________________________________________________________________________
PyObject* PyROOT::MakeRootClassFromType( TClass* klass )
{
// locate class by full name, if possible to prevent parsing scopes/templates anew
PyClassMap_t::iterator pci = gPyClasses.find( (void*)klass );
if ( pci != gPyClasses.end() ) {
PyObject* pyclass = PyWeakref_GetObject( pci->second );
if ( pyclass ) {
Py_INCREF( pyclass );
return pyclass;
}
}
// still here ... pyclass not created or no longer valid, need full parsing
return MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( klass->GetName() );
}
//____________________________________________________________________________
template< class T, class B, class M >
PyObject* PyROOT::MakeRootClassFromString( const std::string& fullname, PyObject* scope )
{
// force building of the class if a scope is specified (prevents loops)
Bool_t force = scope != 0;
// working copy
std::string name = fullname;
// determine scope name, if a python scope has been given
std::string scName = "";
if ( scope ) {
PyObject* pyscope = PyObject_GetAttrString( scope, const_cast< char* >( "__name__" ) );
if ( ! pyscope ) {
PyErr_Format( PyExc_SystemError, "given scope has no name for %s", name.c_str() );
return 0;
}
// should be a string
scName = PyString_AsString( pyscope );
Py_DECREF( pyscope );
if ( PyErr_Occurred() )
return 0;
// work with scope from now on
Py_INCREF( scope );
}
// retrieve ROOT class (this verifies name)
const std::string& lookup = scope ? (scName+"::"+name) : name;
T klass = T::ByName( lookup );
if ( ! (bool)klass || ( (bool)klass && klass.FunctionMemberSize() == 0 ) ) {
// special action for STL classes to enforce loading dict lib
LoadDictionaryForSTLType( name, klass.Id() );
// lookup again, if this was an STL class, we (may) now have a full dictionary
klass = T::ByName( lookup );
}
if ( ! (bool)klass && G__defined_templateclass( const_cast< char* >( lookup.c_str() ) ) ) {
// a "naked" templated class is requested: return callable proxy for instantiations
PyObject* pytcl = PyObject_GetAttrString( gRootModule, const_cast< char* >( "Template" ) );
PyObject* pytemplate = PyObject_CallFunction(
pytcl, const_cast< char* >( "s" ), const_cast< char* >( lookup.c_str() ) );
Py_DECREF( pytcl );
// cache the result
PyObject_SetAttrString( scope ? scope : gRootModule, (char*)name.c_str(), pytemplate );
// done, next step should be a call into this template
Py_XDECREF( scope );
return pytemplate;
}
if ( ! (bool)klass && G__defined_tagname( lookup.c_str(), 2 ) != -1 ) {
// an unloaded namespace is requested
PyObject* pyns = CreateNewROOTPythonClass( lookup, NULL );
// cache the result
PyObject_SetAttrString( scope ? scope : gRootModule, (char*)name.c_str(), pyns );
// done, next step should be a lookup into this namespace
Py_XDECREF( scope );
return pyns;
}
if ( ! (bool)klass ) { // if so, all options have been exhausted: it doesn't exist as such
if ( ! scope && fullname.find( "ROOT::" ) == std::string::npos ) { // not already in ROOT::
// final attempt, for convenience, the "ROOT" namespace isn't required, try again ...
PyObject* rtns = PyObject_GetAttrString( gRootModule, const_cast< char* >( "ROOT" ) );
PyObject* pyclass = PyObject_GetAttrString( rtns, (char*)fullname.c_str() );
Py_DECREF( rtns );
return pyclass;
}
PyErr_Format( PyExc_TypeError, "requested class \'%s\' does not exist", lookup.c_str() );
Py_XDECREF( scope );
return 0;
}
// locate the scope, if necessary, for building the class if not specified
if ( ! scope ) {
// need to deal with template paremeters that can have scopes themselves
Int_t tpl_open = 0;
std::string::size_type last = 0;
for ( std::string::size_type pos = 0; pos < name.size(); ++pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '<' )
++tpl_open;
else if ( c == '>' )
--tpl_open;
// by only checking for "::" the last part (class name) is dropped
else if ( tpl_open == 0 &&\
c == ':' && pos+1 < name.size() && name[ pos+1 ] == ':' ) {
// found a new scope part
std::string part = name.substr( last, pos-last );
PyObject* next = PyObject_GetAttrString(
scope ? scope : gRootModule, const_cast< char* >( part.c_str() ) );
if ( ! next ) { // lookup failed, try to create it
PyErr_Clear();
next = MakeRootClassFromString< T, B, M >( part, scope );
}
Py_XDECREF( scope );
if ( ! next ) // create failed, give up
return 0;
// found scope part
scope = next;
// done with part (note that pos is moved one ahead here)
last = pos+2; ++pos;
}
}
}
// use global scope if no inner scope found
if ( ! scope ) {
scope = gRootModule;
Py_INCREF( scope );
}
// use actual class name for binding
std::string actual = klass.Name( ROOT::Reflex::FINAL );
// first try to retrieve an existing class representation
PyObject* pyactual = PyString_FromString( actual.c_str() );
PyObject* pyclass = force ? 0 : PyObject_GetAttr( scope, pyactual );
Bool_t bClassFound = pyclass ? kTRUE : kFALSE;
// build if the class does not yet exist
if ( ! pyclass ) {
// ignore error generated from the failed lookup
PyErr_Clear();
// construct the base classes
PyObject* pybases = BuildRootClassBases< T, B, M >( klass );
if ( pybases != 0 ) {
// create a fresh Python class, given bases, name, and empty dictionary
pyclass = CreateNewROOTPythonClass(
klass.Name( ROOT::Reflex::FINAL | ROOT::Reflex::SCOPED ), pybases );
Py_DECREF( pybases );
}
// fill the dictionary, if successful
if ( pyclass != 0 ) {
if ( BuildRootClassDict< T, B, M >( klass, pyclass ) != 0 ) {
// something failed in building the dictionary
Py_DECREF( pyclass );
pyclass = 0;
} else
PyObject_SetAttr( scope, pyactual, pyclass );
}
}
if ( pyclass && name != actual ) // class exists, but is typedef-ed: simply map reference
PyObject_SetAttrString( scope, const_cast< char* >( name.c_str() ), pyclass );
Py_DECREF( pyactual );
Py_DECREF( scope );
if ( ! bClassFound ) { // add python-style features to newly minted classes
if ( ! Pythonize( pyclass, klass.Name() ) ) {
Py_XDECREF( pyclass );
pyclass = 0;
}
}
if ( pyclass ) // store a ref from ROOT TClass to new python class
gPyClasses[ klass.Id() ] = PyWeakref_NewRef( pyclass, NULL );
// all done
return pyclass;
}
#ifdef PYROOT_USE_REFLEX
template PyObject* PyROOT::MakeRootClassFromString< ROOT::Reflex::Scope,\
ROOT::Reflex::Base, ROOT::Reflex::Member >( const std::string&, PyObject* scope );
#endif
//____________________________________________________________________________
PyObject* PyROOT::GetRootGlobal( PyObject*, PyObject* args )
{
// get the requested name
std::string ename = PyString_AsString( PyTuple_GetItem( args, 0 ) );
if ( PyErr_Occurred() )
return 0;
return GetRootGlobalFromString( ename );
}
//____________________________________________________________________________
PyObject* PyROOT::GetRootGlobalFromString( const std::string& name )
{
// try named global variable/enum (first ROOT, then CINT: sync is too slow)
TGlobal* gb = (TGlobal*)gROOT->GetListOfGlobals( kFALSE )->FindObject( name.c_str() );
if ( gb ) return BindRootGlobal( gb );
G__DataMemberInfo dt;
while ( dt.Next() ) {
if ( dt.IsValid() && dt.Name() == name ) {
TGlobal gbl = TGlobal( new G__DataMemberInfo( dt ) );
return BindRootGlobal( &gbl );
}
}
// still here ... try functions (first ROOT, then CINT: sync is too slow)
TFunction* func =
(TFunction*)gROOT->GetListOfGlobalFunctions( kFALSE )->FindObject( name.c_str() );
if ( func )
return (PyObject*)MethodProxy_New( name,
new TFunctionHolder< TScopeAdapter, TMemberAdapter >( func ) );
std::vector< PyCallable* > overloads;
G__MethodInfo mt;
while ( mt.Next() ) {
if ( mt.IsValid() && mt.Name() == name ) {
// add to list of globals (same as synchronization would do for all funcs)
TFunction* func = new TFunction( new G__MethodInfo( mt ) );
gROOT->GetListOfGlobalFunctions()->Add( func );
overloads.push_back( new TFunctionHolder< TScopeAdapter, TMemberAdapter >( func ) );
}
}
if ( ! overloads.empty() )
return (PyObject*)MethodProxy_New( name, overloads );
// nothing found
PyErr_Format( PyExc_LookupError, "no such global: %s", name.c_str() );
return 0;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootObjectNoCast( void* address, TClass* klass, Bool_t isRef ) {
// only known or knowable objects will be bound (null object is ok)
if ( ! klass ) {
PyErr_SetString( PyExc_TypeError, "attempt to bind ROOT object w/o class" );
return 0;
}
// retrieve python class
PyObject* pyclass = MakeRootClassFromType( klass );
if ( ! pyclass )
return 0; // error has been set in MakeRootClass
// instantiate an object of this class
PyObject* args = PyTuple_New(0);
ObjectProxy* pyobj =
(ObjectProxy*)((PyTypeObject*)pyclass)->tp_new( (PyTypeObject*)pyclass, args, NULL );
Py_DECREF( args );
Py_DECREF( pyclass );
// bind, register and return if successful
if ( pyobj != 0 ) {
// fill proxy values
if ( ! isRef )
pyobj->Set( address, klass );
else
pyobj->Set( (void**)address, klass );
}
// successful completion
return (PyObject*)pyobj;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootObject( void* address, TClass* klass, Bool_t isRef )
{
// for safety (None can't be used as NULL pointer)
if ( ! address ) {
Py_INCREF( Py_None );
return Py_None;
}
// only known or knowable objects will be bound
if ( ! klass ) {
PyErr_SetString( PyExc_TypeError, "attempt to bind ROOT object w/o class" );
return 0;
}
// upgrade to real class for object returns
if ( ! isRef ) {
TClass* clActual = klass->GetActualClass( address );
if ( clActual && klass != clActual ) {
// root/meta base class offset fails in the case of virtual inheritance
// Long_t offset = clActual->GetBaseClassOffset( klass );
Long_t offset;
if (klass->GetClassInfo() && clActual->GetClassInfo()) {
offset = G__isanybase(klass->GetClassInfo()->Tagnum(), clActual->GetClassInfo()->Tagnum(), (Long_t)address );
} else {
offset = clActual->GetBaseClassOffset( klass );
}
address = (void*)((Long_t)address - offset);
klass = clActual;
}
}
// obtain pointer to TObject base class (if possible) for memory mgmt
TObject* object = klass->IsTObject() ? ((TObject*)( isRef ? *((void**)address) : address )) : 0;
if ( ! isRef && object ) {
object = (TObject*)klass->DynamicCast( TObject::Class(), object );
// use the old reference if the object already exists
PyObject* oldPyObject = TMemoryRegulator::RetrieveObject( object );
if ( oldPyObject )
return oldPyObject;
}
// actual binding
ObjectProxy* pyobj = (ObjectProxy*)BindRootObjectNoCast( address, klass, isRef );
// memory management, for TObject's only
if ( object )
TMemoryRegulator::RegisterObject( pyobj, object );
// completion (returned object may be zero w/ a python exception set)
return (PyObject*)pyobj;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootGlobal( TGlobal* gbl )
{
// gbl == 0 means global does not exist (rather than gbl is NULL pointer)
if ( ! gbl ) {
Py_INCREF( Py_None );
return Py_None;
}
// determine type and cast as appropriate
TClass* klass = TClass::GetClass( gbl->GetTypeName() );
if ( klass != 0 ) {
if ( Utility::Compound( gbl->GetFullTypeName() ) != "" )
return BindRootObject( (void*)gbl->GetAddress(), klass, kTRUE );
return BindRootObject( (void*)gbl->GetAddress(), klass );
}
if ( gbl->GetAddress() && // check for enums (which are const, not properties)
( G__TypeInfo( gbl->GetTypeName() ).Property() & G__BIT_ISENUM ) ) {
return PyInt_FromLong( *((int*)gbl->GetAddress()) );
}
// for built-in types, to ensure setability
return (PyObject*)PropertyProxy_New< TGlobal* >( gbl );
}
fix enum casting issue (valgrind report)
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@22360 27541ba8-7e3a-0410-8455-c3a389f83636
// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Apr 2004
// Bindings
#include "PyROOT.h"
#include "PyRootType.h"
#include "ObjectProxy.h"
#include "MethodProxy.h"
#include "TemplateProxy.h"
#include "PropertyProxy.h"
#include "RootWrapper.h"
#include "Pythonize.h"
#include "MethodHolder.h"
#include "ConstructorHolder.h"
#include "ClassMethodHolder.h"
#include "FunctionHolder.h"
#include "TSetItemHolder.h"
#include "MemoryRegulator.h"
#include "Utility.h"
#include "Adapters.h"
// ROOT
#include "TROOT.h"
#include "TSystem.h"
#include "TMethod.h"
#include "TDataMember.h"
#include "TBaseClass.h"
#include "TInterpreter.h"
#include "TGlobal.h"
#include "DllImport.h"
// CINT
#include "Api.h"
// Reflex
#ifdef PYROOT_USE_REFLEX
#include "Reflex/Scope.h"
#include "Reflex/Base.h"
#include "Reflex/Member.h"
#include "Reflex/Object.h"
#endif
// Standard
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <vector>
//- data _______________________________________________________________________
R__EXTERN PyObject* gRootModule;
namespace {
// to prevent having to walk scopes, track python classes by ROOT class
typedef std::map< void*, PyObject* > PyClassMap_t;
PyClassMap_t gPyClasses;
// helper for creating new ROOT python types
PyObject* CreateNewROOTPythonClass( const std::string& name, PyObject* pybases )
{
Py_XINCREF( pybases );
if ( ! pybases ) {
pybases = PyTuple_New( 1 );
Py_INCREF( &PyROOT::ObjectProxy_Type );
PyTuple_SET_ITEM( pybases, 0, (PyObject*)(void*)&PyROOT::ObjectProxy_Type );
}
PyObject* pymetabases = PyTuple_New( PyTuple_GET_SIZE( pybases ) );
for ( int i = 0; i < PyTuple_GET_SIZE( pybases ); ++i ) {
PyObject* btype = (PyObject*)PyTuple_GetItem( pybases, i )->ob_type;
Py_INCREF( btype );
PyTuple_SET_ITEM( pymetabases, i, btype );
}
PyObject* args = Py_BuildValue( (char*)"sO{}", (name+"_meta").c_str(), pymetabases );
Py_DECREF( pymetabases );
PyObject* pymeta = PyType_Type.tp_new( &PyROOT::PyRootType_Type, args, NULL );
if ( ! pymeta )
PyErr_Print();
Py_DECREF( args );
args = Py_BuildValue( (char*)"sO{}", name.c_str(), pybases );
PyObject* pyclass = PyType_Type.tp_new( (PyTypeObject*)pymeta, args, NULL );
Py_DECREF( args );
Py_DECREF( pymeta );
Py_DECREF( pybases );
return pyclass;
}
// helper to split between CINT and Reflex
Long_t GetDataMemberAddress( TClass* klass, TDataMember* mb )
{
Long_t offset = 0;
G__DataMemberInfo dmi = klass->GetClassInfo()->GetDataMember( mb->GetName(), &offset );
return dmi.Offset();
}
#ifdef PYROOT_USE_REFLEX
Long_t GetDataMemberAddress( const ROOT::Reflex::Scope&, const ROOT::Reflex::Member& mb )
{
return (Long_t)mb.Offset();
}
#endif
} // unnamed namespace
//- helpers --------------------------------------------------------------------
namespace {
inline void AddToScope( const char* label, TObject* obj, TClass* klass )
{
PyModule_AddObject( gRootModule, const_cast< char* >( label ),
PyROOT::BindRootObject( obj, klass ) );
}
std::set< std::string > gSTLTypes, gLoadedSTLTypes;
struct InitSTLTypes_t {
InitSTLTypes_t()
{
const char* stlTypes[] = { "complex", "exception",
"deque", "list", "queue", "stack", "vector",
"map", "multimap", "set", "multiset" };
std::string nss = "std::";
for ( int i = 0; i < int(sizeof(stlTypes)/sizeof(stlTypes[0])); ++i ) {
gSTLTypes.insert( stlTypes[ i ] );
gSTLTypes.insert( nss + stlTypes[ i ] );
}
gLoadedSTLTypes.insert( "vector" );
}
} initSTLTypes_;
Bool_t LoadDictionaryForSTLType( const std::string& tname, void* klass )
{
// if name is of a known STL class, tell CINT to load the dll(s), always reset klass
std::string sub = tname.substr( 0, tname.find( "<" ) );
if ( gSTLTypes.find( sub ) != gSTLTypes.end() ) {
// removal is required or the dictionary can't be updated properly
if ( klass != 0 )
TClass::RemoveClass( (TClass*)klass );
// make sure to only load once
if ( gLoadedSTLTypes.find( sub ) == gLoadedSTLTypes.end() ) {
// strip std:: part as needed to form proper file name
if ( sub.substr( 0, 5 ) == "std::" )
sub = sub.substr( 5, std::string::npos );
// tell CINT to go for it
gROOT->ProcessLine( (std::string( "#include <" ) + sub + ">").c_str() );
// prevent second attempt to load by erasing name
gLoadedSTLTypes.insert( sub );
gLoadedSTLTypes.insert( "std::" + sub );
}
return kTRUE;
}
// this point is only reached if this is not an STL class, but that's ok
return kTRUE;
}
} // unnamed namespace
//- public functions ---------------------------------------------------------
void PyROOT::InitRoot()
{
// setup interpreter locks to allow for threading in ROOT
PyEval_InitThreads();
// memory management
static TMemoryRegulator m;
gROOT->GetListOfCleanups()->Add( &m );
// bind ROOT globals that are needed in ROOT.py
AddToScope( "gROOT", gROOT, gROOT->IsA() );
AddToScope( "gSystem", gSystem, gSystem->IsA() );
AddToScope( "gInterpreter", gInterpreter, gInterpreter->IsA() );
}
//____________________________________________________________________________
template< class T, class B, class M >
int PyROOT::BuildRootClassDict( const T& klass, PyObject* pyclass ) {
// get the unscoped class name
std::string clName = klass.Name();
// some properties that'll affect building the dictionary
Bool_t isNamespace = klass.IsNamespace();
Bool_t hasConstructor = kFALSE;
// load all public methods and data members
typedef std::vector< PyCallable* > Callables_t;
typedef std::map< std::string, Callables_t > CallableCache_t;
CallableCache_t cache;
const size_t nMethods = klass.FunctionMemberSize();
for ( size_t inm = 0; inm < nMethods; ++inm ) {
const M& method = klass.FunctionMemberAt( inm );
// special case tracker
Bool_t setupSetItem = kFALSE;
// retrieve method name
std::string mtName = method.Name();
// filter empty names (happens for namespaces, is bug?)
if ( mtName == "" )
continue;
// filter C++ destructors
if ( mtName[0] == '~' )
continue;
// translate operators
if ( 8 < mtName.size() && mtName.substr( 0, 8 ) == "operator" ) {
std::string op = mtName.substr( 8, std::string::npos );
// stripping ...
std::string::size_type start = 0, end = op.size();
while ( start < end && isspace( op[ start ] ) ) ++start;
while ( start < end && isspace( op[ end-1 ] ) ) --end;
op = op.substr( start, end - start );
// filter assignment operator for later use
if ( op == "=" ) {
continue;
}
// map C++ operator to python equivalent, or made up name if no equivalent exists
Utility::TC2POperatorMapping_t::iterator pop = Utility::gC2POperatorMapping.find( op );
if ( pop != Utility::gC2POperatorMapping.end() ) {
mtName = pop->second;
} else if ( op == "[]" || op == "()" ) { // index or call
mtName = op == "()" ? "__call__" : "__getitem__";
// operator[]/() returning a reference type will be used for __setitem__
std::string cpd = Utility::Compound(
method.TypeOf().ReturnType().Name( ROOT::Reflex::Q | ROOT::Reflex::S ) );
if ( cpd[ cpd.size() - 1 ] == '&' )
setupSetItem = kTRUE;
} else if ( op == "*" ) {
// dereference v.s. multiplication of two instances
mtName = method.FunctionParameterSize() ? "__mul__" : "__deref__";
} else if ( op == "+" ) {
// unary positive v.s. addition of two instances
mtName = method.FunctionParameterSize() ? "__add__" : "__pos__";
} else if ( op == "-" ) {
// unary negative v.s. subtraction of two instances
mtName = method.FunctionParameterSize() ? "__sub__" : "__neg__";
} else if ( op == "++" ) {
// prefix v.s. postfix increment
mtName = method.FunctionParameterSize() ? "__postinc__" : "__preinc__";
} else if ( op == "--" ) {
// prefix v.s. postfix decrement
mtName = method.FunctionParameterSize() ? "__postdec__" : "__predec__";
} else if ( op == "->" ) { // class member access
mtName = "__follow__";
} else {
continue; // not handled (new, delete, etc.)
}
}
// decide on method type: member or static (which includes globals)
Bool_t isStatic = isNamespace || method.IsStatic();
// template members; handled by adding a dispatcher to the class
if ( ! isStatic && mtName[mtName.size()-1] == '>' ) {
std::string tmplname = mtName.substr( 0, mtName.find('<') );
TemplateProxy* pytmpl = TemplateProxy_New( tmplname, pyclass );
PyObject_SetAttrString(
pyclass, const_cast< char* >( tmplname.c_str() ), (PyObject*)pytmpl );
Py_DECREF( pytmpl );
// note: need to continue here to actually add the method ...
}
// public methods are normally visible, private methods are mangled python-wise
// note the overload implications which are name based, and note that rootcint
// does not create the interface methods for private/protected methods ...
if ( ! method.IsPublic() ) {
if ( mtName == clName ) // don't expose private ctors
continue;
else // mangle private methods
mtName = "_" + clName + "__" + mtName;
}
// construct the holder
PyCallable* pycall = 0;
if ( isStatic == kTRUE ) // class method
pycall = new TClassMethodHolder< T, M >( klass, method );
else if ( mtName == clName ) { // constructor
pycall = new TConstructorHolder< T, M >( klass, method );
mtName = "__init__";
hasConstructor = kTRUE;
} else // member function
pycall = new TMethodHolder< T, M >( klass, method );
// lookup method dispatcher and store method
Callables_t& md = (*(cache.insert(
std::make_pair( mtName, Callables_t() ) ).first)).second;
md.push_back( pycall );
// special case for operator[]/() that returns by ref, use for getitem/call and setitem
if ( setupSetItem ) {
Callables_t& setitem = (*(cache.insert(
std::make_pair( std::string( "__setitem__" ), Callables_t() ) ).first)).second;
setitem.push_back( new TSetItemHolder< T, M >( klass, method ) );
}
}
// add a pseudo-default ctor, if none defined
if ( ! isNamespace && ! hasConstructor )
cache[ "__init__" ].push_back( new TConstructorHolder< T, M >( klass ) );
// add the methods to the class dictionary
for ( CallableCache_t::iterator imd = cache.begin(); imd != cache.end(); ++imd ) {
MethodProxy* method = MethodProxy_New( imd->first, imd->second );
PyObject_SetAttrString(
pyclass, const_cast< char* >( method->GetName().c_str() ), (PyObject*)method );
Py_DECREF( method );
}
// collect data members
const size_t nDataMembers = klass.DataMemberSize();
for ( size_t ind = 0; ind < nDataMembers; ++ind ) {
const M& mb = klass.DataMemberAt( ind );
// allow only public members
if ( ! mb.IsPublic() )
continue;
// enums (static enums are the defined values, non-static are data members, i.e. properties)
if ( mb.TypeOf().IsEnum() && mb.IsStatic() ) {
PyObject* val = PyInt_FromLong( *((Int_t*)GetDataMemberAddress( klass, mb ) ) );
PyObject_SetAttrString( pyclass, const_cast<char*>(mb.Name().c_str()), val );
Py_DECREF( val );
// properties (aka public data members)
} else {
PropertyProxy* property = PropertyProxy_New( mb );
// allow access at the instance level
PyObject_SetAttrString( pyclass,
const_cast< char* >( property->GetName().c_str() ), (PyObject*)property );
if ( mb.IsStatic() ) {
// allow access at the class level (always add after setting instance level)
PyObject_SetAttrString( (PyObject*)pyclass->ob_type,
const_cast< char* >( property->GetName().c_str() ), (PyObject*)property );
}
Py_DECREF( property );
}
}
// all ok, done
return 0;
}
//____________________________________________________________________________
template< class T, class B, class M >
PyObject* PyROOT::BuildRootClassBases( const T& klass )
{
size_t nbases = klass.BaseSize();
// collect bases while removing duplicates
std::vector< std::string > uqb;
uqb.reserve( nbases );
for ( size_t inb = 0; inb < nbases; ++inb ) {
const B& base = klass.BaseAt( inb );
std::string name = base.Name();
if ( std::find( uqb.begin(), uqb.end(), name ) == uqb.end() ) {
uqb.push_back( name );
}
}
// allocate a tuple for the base classes, special case for first base
nbases = uqb.size();
PyObject* pybases = PyTuple_New( nbases ? nbases : 1 );
if ( ! pybases )
return 0;
// build all the bases
if ( nbases == 0 ) {
Py_INCREF( &ObjectProxy_Type );
PyTuple_SET_ITEM( pybases, 0, (PyObject*)(void*)&ObjectProxy_Type );
} else {
for ( std::vector< std::string >::size_type ibase = 0; ibase < nbases; ++ibase ) {
PyObject* pyclass = MakeRootClassFromString< T, B, M >( uqb[ ibase ] );
if ( ! pyclass ) {
Py_DECREF( pybases );
return 0;
}
PyTuple_SET_ITEM( pybases, ibase, pyclass );
}
}
return pybases;
}
#ifdef PYROOT_USE_REFLEX
template PyObject* PyROOT::BuildRootClassBases< \
ROOT::Reflex::Scope, ROOT::Reflex::Base, ROOT::Reflex::Member >( const ROOT::Reflex::Scope& );
#endif
//____________________________________________________________________________
PyObject* PyROOT::MakeRootClass( PyObject*, PyObject* args )
{
std::string cname = PyString_AsString( PyTuple_GetItem( args, 0 ) );
if ( PyErr_Occurred() )
return 0;
return MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( cname );
}
//____________________________________________________________________________
PyObject* PyROOT::MakeRootClassFromType( TClass* klass )
{
// locate class by full name, if possible to prevent parsing scopes/templates anew
PyClassMap_t::iterator pci = gPyClasses.find( (void*)klass );
if ( pci != gPyClasses.end() ) {
PyObject* pyclass = PyWeakref_GetObject( pci->second );
if ( pyclass ) {
Py_INCREF( pyclass );
return pyclass;
}
}
// still here ... pyclass not created or no longer valid, need full parsing
return MakeRootClassFromString< TScopeAdapter, TBaseAdapter, TMemberAdapter >( klass->GetName() );
}
//____________________________________________________________________________
template< class T, class B, class M >
PyObject* PyROOT::MakeRootClassFromString( const std::string& fullname, PyObject* scope )
{
// force building of the class if a scope is specified (prevents loops)
Bool_t force = scope != 0;
// working copy
std::string name = fullname;
// determine scope name, if a python scope has been given
std::string scName = "";
if ( scope ) {
PyObject* pyscope = PyObject_GetAttrString( scope, const_cast< char* >( "__name__" ) );
if ( ! pyscope ) {
PyErr_Format( PyExc_SystemError, "given scope has no name for %s", name.c_str() );
return 0;
}
// should be a string
scName = PyString_AsString( pyscope );
Py_DECREF( pyscope );
if ( PyErr_Occurred() )
return 0;
// work with scope from now on
Py_INCREF( scope );
}
// retrieve ROOT class (this verifies name)
const std::string& lookup = scope ? (scName+"::"+name) : name;
T klass = T::ByName( lookup );
if ( ! (bool)klass || ( (bool)klass && klass.FunctionMemberSize() == 0 ) ) {
// special action for STL classes to enforce loading dict lib
LoadDictionaryForSTLType( name, klass.Id() );
// lookup again, if this was an STL class, we (may) now have a full dictionary
klass = T::ByName( lookup );
}
if ( ! (bool)klass && G__defined_templateclass( const_cast< char* >( lookup.c_str() ) ) ) {
// a "naked" templated class is requested: return callable proxy for instantiations
PyObject* pytcl = PyObject_GetAttrString( gRootModule, const_cast< char* >( "Template" ) );
PyObject* pytemplate = PyObject_CallFunction(
pytcl, const_cast< char* >( "s" ), const_cast< char* >( lookup.c_str() ) );
Py_DECREF( pytcl );
// cache the result
PyObject_SetAttrString( scope ? scope : gRootModule, (char*)name.c_str(), pytemplate );
// done, next step should be a call into this template
Py_XDECREF( scope );
return pytemplate;
}
if ( ! (bool)klass && G__defined_tagname( lookup.c_str(), 2 ) != -1 ) {
// an unloaded namespace is requested
PyObject* pyns = CreateNewROOTPythonClass( lookup, NULL );
// cache the result
PyObject_SetAttrString( scope ? scope : gRootModule, (char*)name.c_str(), pyns );
// done, next step should be a lookup into this namespace
Py_XDECREF( scope );
return pyns;
}
if ( ! (bool)klass ) { // if so, all options have been exhausted: it doesn't exist as such
if ( ! scope && fullname.find( "ROOT::" ) == std::string::npos ) { // not already in ROOT::
// final attempt, for convenience, the "ROOT" namespace isn't required, try again ...
PyObject* rtns = PyObject_GetAttrString( gRootModule, const_cast< char* >( "ROOT" ) );
PyObject* pyclass = PyObject_GetAttrString( rtns, (char*)fullname.c_str() );
Py_DECREF( rtns );
return pyclass;
}
PyErr_Format( PyExc_TypeError, "requested class \'%s\' does not exist", lookup.c_str() );
Py_XDECREF( scope );
return 0;
}
// locate the scope, if necessary, for building the class if not specified
if ( ! scope ) {
// need to deal with template paremeters that can have scopes themselves
Int_t tpl_open = 0;
std::string::size_type last = 0;
for ( std::string::size_type pos = 0; pos < name.size(); ++pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '<' )
++tpl_open;
else if ( c == '>' )
--tpl_open;
// by only checking for "::" the last part (class name) is dropped
else if ( tpl_open == 0 &&\
c == ':' && pos+1 < name.size() && name[ pos+1 ] == ':' ) {
// found a new scope part
std::string part = name.substr( last, pos-last );
PyObject* next = PyObject_GetAttrString(
scope ? scope : gRootModule, const_cast< char* >( part.c_str() ) );
if ( ! next ) { // lookup failed, try to create it
PyErr_Clear();
next = MakeRootClassFromString< T, B, M >( part, scope );
}
Py_XDECREF( scope );
if ( ! next ) // create failed, give up
return 0;
// found scope part
scope = next;
// done with part (note that pos is moved one ahead here)
last = pos+2; ++pos;
}
}
}
// use global scope if no inner scope found
if ( ! scope ) {
scope = gRootModule;
Py_INCREF( scope );
}
// use actual class name for binding
std::string actual = klass.Name( ROOT::Reflex::FINAL );
// first try to retrieve an existing class representation
PyObject* pyactual = PyString_FromString( actual.c_str() );
PyObject* pyclass = force ? 0 : PyObject_GetAttr( scope, pyactual );
Bool_t bClassFound = pyclass ? kTRUE : kFALSE;
// build if the class does not yet exist
if ( ! pyclass ) {
// ignore error generated from the failed lookup
PyErr_Clear();
// construct the base classes
PyObject* pybases = BuildRootClassBases< T, B, M >( klass );
if ( pybases != 0 ) {
// create a fresh Python class, given bases, name, and empty dictionary
pyclass = CreateNewROOTPythonClass(
klass.Name( ROOT::Reflex::FINAL | ROOT::Reflex::SCOPED ), pybases );
Py_DECREF( pybases );
}
// fill the dictionary, if successful
if ( pyclass != 0 ) {
if ( BuildRootClassDict< T, B, M >( klass, pyclass ) != 0 ) {
// something failed in building the dictionary
Py_DECREF( pyclass );
pyclass = 0;
} else
PyObject_SetAttr( scope, pyactual, pyclass );
}
}
if ( pyclass && name != actual ) // class exists, but is typedef-ed: simply map reference
PyObject_SetAttrString( scope, const_cast< char* >( name.c_str() ), pyclass );
Py_DECREF( pyactual );
Py_DECREF( scope );
if ( ! bClassFound ) { // add python-style features to newly minted classes
if ( ! Pythonize( pyclass, klass.Name() ) ) {
Py_XDECREF( pyclass );
pyclass = 0;
}
}
if ( pyclass ) // store a ref from ROOT TClass to new python class
gPyClasses[ klass.Id() ] = PyWeakref_NewRef( pyclass, NULL );
// all done
return pyclass;
}
#ifdef PYROOT_USE_REFLEX
template PyObject* PyROOT::MakeRootClassFromString< ROOT::Reflex::Scope,\
ROOT::Reflex::Base, ROOT::Reflex::Member >( const std::string&, PyObject* scope );
#endif
//____________________________________________________________________________
PyObject* PyROOT::GetRootGlobal( PyObject*, PyObject* args )
{
// get the requested name
std::string ename = PyString_AsString( PyTuple_GetItem( args, 0 ) );
if ( PyErr_Occurred() )
return 0;
return GetRootGlobalFromString( ename );
}
//____________________________________________________________________________
PyObject* PyROOT::GetRootGlobalFromString( const std::string& name )
{
// try named global variable/enum (first ROOT, then CINT: sync is too slow)
TGlobal* gb = (TGlobal*)gROOT->GetListOfGlobals( kFALSE )->FindObject( name.c_str() );
if ( gb ) return BindRootGlobal( gb );
G__DataMemberInfo dt;
while ( dt.Next() ) {
if ( dt.IsValid() && dt.Name() == name ) {
TGlobal gbl = TGlobal( new G__DataMemberInfo( dt ) );
return BindRootGlobal( &gbl );
}
}
// still here ... try functions (first ROOT, then CINT: sync is too slow)
TFunction* func =
(TFunction*)gROOT->GetListOfGlobalFunctions( kFALSE )->FindObject( name.c_str() );
if ( func )
return (PyObject*)MethodProxy_New( name,
new TFunctionHolder< TScopeAdapter, TMemberAdapter >( func ) );
std::vector< PyCallable* > overloads;
G__MethodInfo mt;
while ( mt.Next() ) {
if ( mt.IsValid() && mt.Name() == name ) {
// add to list of globals (same as synchronization would do for all funcs)
TFunction* func = new TFunction( new G__MethodInfo( mt ) );
gROOT->GetListOfGlobalFunctions()->Add( func );
overloads.push_back( new TFunctionHolder< TScopeAdapter, TMemberAdapter >( func ) );
}
}
if ( ! overloads.empty() )
return (PyObject*)MethodProxy_New( name, overloads );
// nothing found
PyErr_Format( PyExc_LookupError, "no such global: %s", name.c_str() );
return 0;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootObjectNoCast( void* address, TClass* klass, Bool_t isRef ) {
// only known or knowable objects will be bound (null object is ok)
if ( ! klass ) {
PyErr_SetString( PyExc_TypeError, "attempt to bind ROOT object w/o class" );
return 0;
}
// retrieve python class
PyObject* pyclass = MakeRootClassFromType( klass );
if ( ! pyclass )
return 0; // error has been set in MakeRootClass
// instantiate an object of this class
PyObject* args = PyTuple_New(0);
ObjectProxy* pyobj =
(ObjectProxy*)((PyTypeObject*)pyclass)->tp_new( (PyTypeObject*)pyclass, args, NULL );
Py_DECREF( args );
Py_DECREF( pyclass );
// bind, register and return if successful
if ( pyobj != 0 ) {
// fill proxy values
if ( ! isRef )
pyobj->Set( address, klass );
else
pyobj->Set( (void**)address, klass );
}
// successful completion
return (PyObject*)pyobj;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootObject( void* address, TClass* klass, Bool_t isRef )
{
// for safety (None can't be used as NULL pointer)
if ( ! address ) {
Py_INCREF( Py_None );
return Py_None;
}
// only known or knowable objects will be bound
if ( ! klass ) {
PyErr_SetString( PyExc_TypeError, "attempt to bind ROOT object w/o class" );
return 0;
}
// upgrade to real class for object returns
if ( ! isRef ) {
TClass* clActual = klass->GetActualClass( address );
if ( clActual && klass != clActual ) {
// root/meta base class offset fails in the case of virtual inheritance
// Long_t offset = clActual->GetBaseClassOffset( klass );
Long_t offset;
if (klass->GetClassInfo() && clActual->GetClassInfo()) {
offset = G__isanybase(klass->GetClassInfo()->Tagnum(), clActual->GetClassInfo()->Tagnum(), (Long_t)address );
} else {
offset = clActual->GetBaseClassOffset( klass );
}
address = (void*)((Long_t)address - offset);
klass = clActual;
}
}
// obtain pointer to TObject base class (if possible) for memory mgmt
TObject* object = klass->IsTObject() ? ((TObject*)( isRef ? *((void**)address) : address )) : 0;
if ( ! isRef && object ) {
object = (TObject*)klass->DynamicCast( TObject::Class(), object );
// use the old reference if the object already exists
PyObject* oldPyObject = TMemoryRegulator::RetrieveObject( object );
if ( oldPyObject )
return oldPyObject;
}
// actual binding
ObjectProxy* pyobj = (ObjectProxy*)BindRootObjectNoCast( address, klass, isRef );
// memory management, for TObject's only
if ( object )
TMemoryRegulator::RegisterObject( pyobj, object );
// completion (returned object may be zero w/ a python exception set)
return (PyObject*)pyobj;
}
//____________________________________________________________________________
PyObject* PyROOT::BindRootGlobal( TGlobal* gbl )
{
// gbl == 0 means global does not exist (rather than gbl is NULL pointer)
if ( ! gbl ) {
Py_INCREF( Py_None );
return Py_None;
}
// determine type and cast as appropriate
TClass* klass = TClass::GetClass( gbl->GetTypeName() );
if ( klass != 0 ) {
if ( Utility::Compound( gbl->GetFullTypeName() ) != "" )
return BindRootObject( (void*)gbl->GetAddress(), klass, kTRUE );
return BindRootObject( (void*)gbl->GetAddress(), klass );
}
if ( gbl->GetAddress() && // check for enums (which are const, not properties)
( G__TypeInfo( gbl->GetTypeName() ).Property() & G__BIT_ISENUM ) ) {
return PyInt_FromLong( *((int*)gbl->GetAddress()) );
}
// for built-in types, to ensure setability
return (PyObject*)PropertyProxy_New< TGlobal* >( gbl );
}
|
#include "Arith256.h"
#include "Runtime.h"
#include "Type.h"
#include "Endianness.h"
#include <llvm/IR/Function.h>
#include <gmp.h>
namespace dev
{
namespace eth
{
namespace jit
{
Arith256::Arith256(llvm::IRBuilder<>& _builder) :
CompilerHelper(_builder)
{
using namespace llvm;
m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result");
m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1");
m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2");
m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3");
using Linkage = GlobalValue::LinkageTypes;
llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};
llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};
m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule());
m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule());
m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule());
m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule());
m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule());
m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule());
m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule());
m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule());
}
Arith256::~Arith256()
{}
llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)
{
m_builder.CreateStore(_arg1, m_arg1);
m_builder.CreateStore(_arg2, m_arg2);
m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);
return m_builder.CreateLoad(m_result);
}
llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
m_builder.CreateStore(_arg1, m_arg1);
m_builder.CreateStore(_arg2, m_arg2);
m_builder.CreateStore(_arg3, m_arg3);
m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);
return m_builder.CreateLoad(m_result);
}
llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_mul, _arg1, _arg2);
}
llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)
{
//return Endianness::toNative(m_builder, binaryOp(m_div, Endianness::toBE(m_builder, _arg1), Endianness::toBE(m_builder, _arg2)));
return binaryOp(m_div, _arg1, _arg2);
}
llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_mod, _arg1, _arg2);
}
llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_sdiv, _arg1, _arg2);
}
llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_smod, _arg1, _arg2);
}
llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_exp, _arg1, _arg2);
}
llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
return ternaryOp(m_addmod, _arg1, _arg2, _arg3);
}
llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
return ternaryOp(m_mulmod, _arg1, _arg2, _arg3);
}
namespace
{
using s256 = boost::multiprecision::int256_t;
inline s256 u2s(u256 _u)
{
static const bigint c_end = (bigint)1 << 256;
static const u256 c_send = (u256)1 << 255;
if (_u < c_send)
return (s256)_u;
else
return (s256)-(c_end - _u);
}
inline u256 s2u(s256 _u)
{
static const bigint c_end = (bigint)1 << 256;
if (_u >= 0)
return (u256)_u;
else
return (u256)(c_end + _u);
}
using uint128 = __uint128_t;
// uint128 add(uint128 a, uint128 b) { return a + b; }
// uint128 mul(uint128 a, uint128 b) { return a * b; }
//
// uint128 mulq(uint64_t x, uint64_t y)
// {
// return (uint128)x * (uint128)y;
// }
//
// uint128 addc(uint64_t x, uint64_t y)
// {
// return (uint128)x * (uint128)y;
// }
struct uint256
{
uint64_t lo;
uint64_t mid;
uint128 hi;
};
// uint256 add(uint256 x, uint256 y)
// {
// auto lo = (uint128) x.lo + y.lo;
// auto mid = (uint128) x.mid + y.mid + (lo >> 64);
// return {lo, mid, x.hi + y.hi + (mid >> 64)};
// }
uint256 mul(uint256 x, uint256 y)
{
auto t1 = (uint128) x.lo * y.lo;
auto t2 = (uint128) x.lo * y.mid;
auto t3 = x.lo * y.hi;
auto t4 = (uint128) x.mid * y.lo;
auto t5 = (uint128) x.mid * y.mid;
auto t6 = x.mid * y.hi;
auto t7 = x.hi * y.lo;
auto t8 = x.hi * y.mid;
auto lo = (uint64_t) t1;
auto m1 = (t1 >> 64) + (uint64_t) t2;
auto m2 = (uint64_t) m1;
auto mid = (uint128) m2 + (uint64_t) t4;
auto hi = (t2 >> 64) + t3 + (t4 >> 64) + t5 + (t6 << 64) + t7
+ (t8 << 64) + (m1 >> 64) + (mid >> 64);
return {lo, (uint64_t)mid, hi};
}
bool isZero(i256 const* _n)
{
return _n->a == 0 && _n->b == 0 && _n->c == 0 && _n->d == 0;
}
const auto nLimbs = sizeof(i256) / sizeof(mp_limb_t);
int countLimbs(i256 const* _n)
{
static const auto limbsInWord = sizeof(_n->a) / sizeof(mp_limb_t);
static_assert(limbsInWord == 1, "E?");
int l = nLimbs;
if (_n->d != 0) return l;
l -= limbsInWord;
if (_n->c != 0) return l;
l -= limbsInWord;
if (_n->b != 0) return l;
l -= limbsInWord;
if (_n->a != 0) return l;
return 0;
}
}
}
}
}
extern "C"
{
using namespace dev::eth::jit;
EXPORT void arith_mul(uint256* _arg1, uint256* _arg2, uint256* o_result)
{
*o_result = mul(*_arg1, *_arg2);
}
EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_tdiv_q(z, x, y);
// auto arg1 = llvm2eth(*_arg1);
// auto arg2 = llvm2eth(*_arg2);
// auto res = arg2 == 0 ? arg2 : arg1 / arg2;
// std::cout << "DIV " << arg1 << "/" << arg2 << " = " << res << std::endl;
// gmp_printf("GMP %Zd / %Zd = %Zd\n", x, y, z);
}
EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_tdiv_r(z, x, y);
}
EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)
{
auto arg1 = llvm2eth(*_arg1);
auto arg2 = llvm2eth(*_arg2);
*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2)));
}
EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)
{
auto arg1 = llvm2eth(*_arg1);
auto arg2 = llvm2eth(*_arg2);
*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2)));
}
EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
static mp_limb_t mod_limbs[nLimbs + 1] = {};
mod_limbs[nLimbs] = 1;
static const mpz_t mod{nLimbs + 1, nLimbs + 1, &mod_limbs[0]};
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_powm(z, x, y, mod);
}
EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
{
*o_result = {};
if (isZero(_arg3))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t m{nLimbs, countLimbs(_arg3), reinterpret_cast<mp_limb_t*>(_arg3)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
static mp_limb_t p_limbs[nLimbs * 2] = {};
static mpz_t p{nLimbs * 2, 0, &p_limbs[0]};
mpz_mul(p, x, y);
mpz_tdiv_r(z, p, m);
}
EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
{
*o_result = {};
if (isZero(_arg3))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t m{nLimbs, countLimbs(_arg3), reinterpret_cast<mp_limb_t*>(_arg3)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
static mp_limb_t s_limbs[nLimbs + 1] = {};
static mpz_t s{nLimbs + 1, 0, &s_limbs[0]};
mpz_add(s, x, y);
mpz_tdiv_r(z, s, m);
}
}
Implementation of SDIV & SMOD with gmp
#include "Arith256.h"
#include "Runtime.h"
#include "Type.h"
#include "Endianness.h"
#include <llvm/IR/Function.h>
#include <gmp.h>
namespace dev
{
namespace eth
{
namespace jit
{
Arith256::Arith256(llvm::IRBuilder<>& _builder) :
CompilerHelper(_builder)
{
using namespace llvm;
m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result");
m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1");
m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2");
m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3");
using Linkage = GlobalValue::LinkageTypes;
llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};
llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};
m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule());
m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule());
m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule());
m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule());
m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule());
m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule());
m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule());
m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule());
}
Arith256::~Arith256()
{}
llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)
{
m_builder.CreateStore(_arg1, m_arg1);
m_builder.CreateStore(_arg2, m_arg2);
m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);
return m_builder.CreateLoad(m_result);
}
llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
m_builder.CreateStore(_arg1, m_arg1);
m_builder.CreateStore(_arg2, m_arg2);
m_builder.CreateStore(_arg3, m_arg3);
m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);
return m_builder.CreateLoad(m_result);
}
llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_mul, _arg1, _arg2);
}
llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)
{
//return Endianness::toNative(m_builder, binaryOp(m_div, Endianness::toBE(m_builder, _arg1), Endianness::toBE(m_builder, _arg2)));
return binaryOp(m_div, _arg1, _arg2);
}
llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_mod, _arg1, _arg2);
}
llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_sdiv, _arg1, _arg2);
}
llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_smod, _arg1, _arg2);
}
llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)
{
return binaryOp(m_exp, _arg1, _arg2);
}
llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
return ternaryOp(m_addmod, _arg1, _arg2, _arg3);
}
llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
return ternaryOp(m_mulmod, _arg1, _arg2, _arg3);
}
namespace
{
using s256 = boost::multiprecision::int256_t;
inline s256 u2s(u256 _u)
{
static const bigint c_end = (bigint)1 << 256;
static const u256 c_send = (u256)1 << 255;
if (_u < c_send)
return (s256)_u;
else
return (s256)-(c_end - _u);
}
inline u256 s2u(s256 _u)
{
static const bigint c_end = (bigint)1 << 256;
if (_u >= 0)
return (u256)_u;
else
return (u256)(c_end + _u);
}
using uint128 = __uint128_t;
// uint128 add(uint128 a, uint128 b) { return a + b; }
// uint128 mul(uint128 a, uint128 b) { return a * b; }
//
// uint128 mulq(uint64_t x, uint64_t y)
// {
// return (uint128)x * (uint128)y;
// }
//
// uint128 addc(uint64_t x, uint64_t y)
// {
// return (uint128)x * (uint128)y;
// }
struct uint256
{
uint64_t lo;
uint64_t mid;
uint128 hi;
};
// uint256 add(uint256 x, uint256 y)
// {
// auto lo = (uint128) x.lo + y.lo;
// auto mid = (uint128) x.mid + y.mid + (lo >> 64);
// return {lo, mid, x.hi + y.hi + (mid >> 64)};
// }
uint256 mul(uint256 x, uint256 y)
{
auto t1 = (uint128) x.lo * y.lo;
auto t2 = (uint128) x.lo * y.mid;
auto t3 = x.lo * y.hi;
auto t4 = (uint128) x.mid * y.lo;
auto t5 = (uint128) x.mid * y.mid;
auto t6 = x.mid * y.hi;
auto t7 = x.hi * y.lo;
auto t8 = x.hi * y.mid;
auto lo = (uint64_t) t1;
auto m1 = (t1 >> 64) + (uint64_t) t2;
auto m2 = (uint64_t) m1;
auto mid = (uint128) m2 + (uint64_t) t4;
auto hi = (t2 >> 64) + t3 + (t4 >> 64) + t5 + (t6 << 64) + t7
+ (t8 << 64) + (m1 >> 64) + (mid >> 64);
return {lo, (uint64_t)mid, hi};
}
bool isZero(i256 const* _n)
{
return _n->a == 0 && _n->b == 0 && _n->c == 0 && _n->d == 0;
}
const auto nLimbs = sizeof(i256) / sizeof(mp_limb_t);
// FIXME: Not thread-safe
static mp_limb_t mod_limbs[] = {0, 0, 0, 0, 1};
static_assert(sizeof(mod_limbs) / sizeof(mod_limbs[0]) == nLimbs + 1, "mp_limb_t size mismatch");
static const mpz_t mod{nLimbs + 1, nLimbs + 1, &mod_limbs[0]};
static mp_limb_t tmp_limbs[nLimbs + 2];
static mpz_t tmp{nLimbs + 2, 0, &tmp_limbs[0]};
int countLimbs(i256 const* _n)
{
static const auto limbsInWord = sizeof(_n->a) / sizeof(mp_limb_t);
static_assert(limbsInWord == 1, "E?");
int l = nLimbs;
if (_n->d != 0) return l;
l -= limbsInWord;
if (_n->c != 0) return l;
l -= limbsInWord;
if (_n->b != 0) return l;
l -= limbsInWord;
if (_n->a != 0) return l;
return 0;
}
void u2s(mpz_t _u)
{
if (static_cast<std::make_signed<mp_limb_t>::type>(_u->_mp_d[nLimbs - 1]) < 0)
{
mpz_sub(tmp, mod, _u);
mpz_set(_u, tmp);
_u->_mp_size = -_u->_mp_size;
}
}
void s2u(mpz_t _s)
{
if (_s->_mp_size < 0)
{
mpz_add(tmp, mod, _s);
mpz_set(_s, tmp);
}
}
}
}
}
}
extern "C"
{
using namespace dev::eth::jit;
EXPORT void arith_mul(uint256* _arg1, uint256* _arg2, uint256* o_result)
{
*o_result = mul(*_arg1, *_arg2);
}
EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_tdiv_q(z, x, y);
// auto arg1 = llvm2eth(*_arg1);
// auto arg2 = llvm2eth(*_arg2);
// auto res = arg2 == 0 ? arg2 : arg1 / arg2;
// std::cout << "DIV " << arg1 << "/" << arg2 << " = " << res << std::endl;
// gmp_printf("GMP %Zd / %Zd = %Zd\n", x, y, z);
}
EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_tdiv_r(z, x, y);
}
EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
u2s(x);
u2s(y);
mpz_tdiv_q(z, x, y);
s2u(z);
}
EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
if (isZero(_arg2))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
u2s(x);
u2s(y);
mpz_tdiv_r(z, x, y);
s2u(z);
}
EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)
{
*o_result = {};
static mp_limb_t mod_limbs[nLimbs + 1] = {};
mod_limbs[nLimbs] = 1;
static const mpz_t mod{nLimbs + 1, nLimbs + 1, &mod_limbs[0]};
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
mpz_powm(z, x, y, mod);
}
EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
{
*o_result = {};
if (isZero(_arg3))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t m{nLimbs, countLimbs(_arg3), reinterpret_cast<mp_limb_t*>(_arg3)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
static mp_limb_t p_limbs[nLimbs * 2] = {};
static mpz_t p{nLimbs * 2, 0, &p_limbs[0]};
mpz_mul(p, x, y);
mpz_tdiv_r(z, p, m);
}
EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
{
*o_result = {};
if (isZero(_arg3))
return;
mpz_t x{nLimbs, countLimbs(_arg1), reinterpret_cast<mp_limb_t*>(_arg1)};
mpz_t y{nLimbs, countLimbs(_arg2), reinterpret_cast<mp_limb_t*>(_arg2)};
mpz_t m{nLimbs, countLimbs(_arg3), reinterpret_cast<mp_limb_t*>(_arg3)};
mpz_t z{nLimbs, 0, reinterpret_cast<mp_limb_t*>(o_result)};
static mp_limb_t s_limbs[nLimbs + 1] = {};
static mpz_t s{nLimbs + 1, 0, &s_limbs[0]};
mpz_add(s, x, y);
mpz_tdiv_r(z, s, m);
}
}
|
/*
python/pybind11_opencv.hpp: Transparent conversion for OpenCV cv::Mat matrices.
This header is based on pybind11/eigen.h.
Copyright (c) 2016 Patrik Huber
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in pybind11's LICENSE file.
*/
#pragma once
#include "pybind11/numpy.h"
#include "opencv2/core/core.hpp"
#include "opencv2/core/types_c.h"
#include <iostream>
NAMESPACE_BEGIN(pybind11)
NAMESPACE_BEGIN(detail)
/**
* @file python/pybind11_opencv.hpp
* @brief Transparent conversion to and from Python for OpenCV vector and matrix types.
*
* OpenCV and numpy both use row-major storage order by default, so the conversion works
* pretty much out of the box, even for multi-channel matrices.
* Handling of non-standard strides is not implemented.
* Handling of column-major numpy arrays is unsupported.
*/
/**
* @brief Transparent conversion for OpenCV's cv::Vec types to and from Python.
*/
template<typename T, int N>
struct type_caster<cv::Vec<T, N>>
{
using vector_type = cv::Vec<T, N>;
using Scalar = T;
static constexpr std::size_t num_elements = N;
bool load(handle src, bool)
{
auto buf = array_t<Scalar>::ensure(src);
if (!buf)
return false;
if (buf.ndim() == 1) // a 1-dimensional vector
{
if (buf.shape(0) != num_elements) {
return false; // not a N-elements vector (can this ever happen?)
}
if (buf.strides(0) != sizeof(Scalar))
{
std::cout << "An array with non-standard strides is given. Please pass a contiguous array." << std::endl;
return false;
}
value = cv::Vec<T, N>(buf.mutable_data());
}
else { // buf.ndim() != 1
return false;
}
return true;
}
static handle cast(const vector_type& src, return_value_policy /* policy */, handle /* parent */)
{
return array(
num_elements, // shape
src.val // data
).release();
}
// Specifies the doc-string for the type in Python:
PYBIND11_TYPE_CASTER(vector_type, _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name() +
_("[") + _<num_elements>() + _("]]"));
};
/**
* @brief Helper function to convert a Python array to a cv::Mat.
*
* This is an internal helper function that converts a pybind11::array to a cv::Mat.
* - The \p opencv_depth given must match the type of the data in \p buf.
* - \p buf must be a 1, 2 or 3-dimensional array.
* - The function expects a valid \p buf object.
*
* The buffer's mutable_data() is used directly, and I think no data is copied.
*
* @param buf Python buffer object.
* @param opencv_depth OpenCV "depth" (the data type, e.g. CV_8U).
* @return A cv::Mat pointing to the buffer's data or an empty Mat if an error occured.
*/
cv::Mat pyarray_to_mat(pybind11::array buf, int opencv_depth)
{
cv::Mat value;
if (buf.ndim() == 1)
{ // A numpy array, with only one dimension. A row-vector.
auto num_elements = buf.shape(0);
auto opencv_type = CV_MAKETYPE(opencv_depth, 1);
value = cv::Mat(1, num_elements, opencv_type, buf.mutable_data());
}
else if (buf.ndim() == 2)
{ // We got a matrix (but it can also be 1 x n or n x 1)
auto opencv_type = CV_MAKETYPE(opencv_depth, 1);
value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
}
else if (buf.ndim() == 3)
{ // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter)
auto num_chans = buf.shape(2); // Check whether 3 or 4 and abort otherwise??
auto opencv_type = CV_MAKETYPE(opencv_depth, num_chans);
value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
}
else { // buf.ndim() is not 1, 2 or 3.
return cv::Mat();
}
return value;
};
/**
* @brief Transparent conversion for OpenCV's cv::Mat type to and from Python.
*
* Converts cv::Mat's to and from Python. Can construct a cv::Mat from numpy arrays,
* as well as potentially other Python array types.
*
* - Supports only contiguous matrices
* - The numpy array has to be in default (row-major) storage order
* - Non-default strides are not implemented.
*
* Note about strides: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-step1
* And possibly use src.elemSize or src.elemSize1.
* See also the old bindings: https://github.com/patrikhuber/eos/commit/1c3b0113a3efcbb1a92efca646be663ef8593793
*/
template<>
struct type_caster<cv::Mat>
{
bool load(handle src, bool)
{
// Since cv::Mat has its time dynamically specified at run-time, we can't bind functions
// that take a cv::Mat to any particular Scalar type.
// Thus the data we get from python can be any type.
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
auto pyarray_dtype = buf.dtype();
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
int opencv_depth;
if (pyarray_dtype == pybind11::dtype::of<std::uint8_t>())
{
opencv_depth = CV_8U;
}
else if (pyarray_dtype == pybind11::dtype::of<float>())
{
opencv_depth = CV_32F;
}
else if (pyarray_dtype == pybind11::dtype::of<double>())
{
opencv_depth = CV_64F;
}
else
{
return false;
}
// Todo: Would be nice to add int32, as it's the default in python if you create a
// list with [1, 2, 3]. But it doesn't evaluate to true when comparing with
// all integer dtypes (int, int32, uint32, etc.).
value = pyarray_to_mat(buf, opencv_depth);
if (value.empty())
{
return false;
}
return true;
};
static handle cast(const cv::Mat& src, return_value_policy /* policy */, handle /* parent */)
{
if (!src.isContinuous())
{
throw std::runtime_error("Cannot cast non-contiguous cv::Mat objects to Python. Change the C++ code to return a contiguous cv::Mat.");
// We could probably support that with implementing strides properly.
}
const auto opencv_depth = src.depth();
const auto num_chans = src.channels();
std::vector<std::size_t> shape;
if (num_chans == 1)
{
shape = { (size_t)src.rows, (size_t)src.cols };
// if either of them is == 1, we could specify only 1 value for shape - but be careful with strides,
// if there's a col-vector, I don't think we can do it without using strides.
// Also, check what happens in python when we pass a col & row vec respectively.
}
else if (num_chans == 2 || num_chans == 3 || num_chans == 4)
{
shape = { (size_t)src.rows, (size_t)src.cols, (size_t)num_chans };
}
else {
throw std::runtime_error("Cannot return matrices with more than 4 channels back to Python.");
// We could probably implement this quite easily but >4 channel images/matrices don't occur often.
}
// Now return the data, depending on its type:
if (opencv_depth == CV_8U)
{
return array(pybind11::dtype::of<std::uint8_t>(), shape, src.data).release();
}
else if (opencv_depth == CV_32F)
{
return array(pybind11::dtype::of<float>(), shape, src.data).release();
}
else if (opencv_depth == CV_64F)
{
return array(pybind11::dtype::of<double>(), shape, src.data).release();
}
else {
throw std::runtime_error("Can currently only return matrices of type 8U, 32F and 64F back to Python. Other types can be added if needed.");
}
};
PYBIND11_TYPE_CASTER(cv::Mat, _("numpy.ndarray[uint8|float32|float64[m, n, d]]"));
};
NAMESPACE_END(detail)
NAMESPACE_END(pybind11)
Replaced dtype comparison with isinstance()
Apparently the dtype comparison compared pointer addresses, so it must've worked just by chance. Scary!
/*
python/pybind11_opencv.hpp: Transparent conversion for OpenCV cv::Mat matrices.
This header is based on pybind11/eigen.h.
Copyright (c) 2016 Patrik Huber
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in pybind11's LICENSE file.
*/
#pragma once
#include "pybind11/numpy.h"
#include "opencv2/core/core.hpp"
#include "opencv2/core/types_c.h"
#include <iostream>
NAMESPACE_BEGIN(pybind11)
NAMESPACE_BEGIN(detail)
/**
* @file python/pybind11_opencv.hpp
* @brief Transparent conversion to and from Python for OpenCV vector and matrix types.
*
* OpenCV and numpy both use row-major storage order by default, so the conversion works
* pretty much out of the box, even for multi-channel matrices.
* Handling of non-standard strides is not implemented.
* Handling of column-major numpy arrays is unsupported.
*/
/**
* @brief Transparent conversion for OpenCV's cv::Vec types to and from Python.
*/
template<typename T, int N>
struct type_caster<cv::Vec<T, N>>
{
using vector_type = cv::Vec<T, N>;
using Scalar = T;
static constexpr std::size_t num_elements = N;
bool load(handle src, bool)
{
auto buf = array_t<Scalar>::ensure(src);
if (!buf)
return false;
if (buf.ndim() == 1) // a 1-dimensional vector
{
if (buf.shape(0) != num_elements) {
return false; // not a N-elements vector (can this ever happen?)
}
if (buf.strides(0) != sizeof(Scalar))
{
std::cout << "An array with non-standard strides is given. Please pass a contiguous array." << std::endl;
return false;
}
value = cv::Vec<T, N>(buf.mutable_data());
}
else { // buf.ndim() != 1
return false;
}
return true;
}
static handle cast(const vector_type& src, return_value_policy /* policy */, handle /* parent */)
{
return array(
num_elements, // shape
src.val // data
).release();
}
// Specifies the doc-string for the type in Python:
PYBIND11_TYPE_CASTER(vector_type, _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name() +
_("[") + _<num_elements>() + _("]]"));
};
/**
* @brief Helper function to convert a Python array to a cv::Mat.
*
* This is an internal helper function that converts a pybind11::array to a cv::Mat.
* - The \p opencv_depth given must match the type of the data in \p buf.
* - \p buf must be a 1, 2 or 3-dimensional array.
* - The function expects a valid \p buf object.
*
* The buffer's mutable_data() is used directly, and I think no data is copied.
*
* @param buf Python buffer object.
* @param opencv_depth OpenCV "depth" (the data type, e.g. CV_8U).
* @return A cv::Mat pointing to the buffer's data or an empty Mat if an error occured.
*/
cv::Mat pyarray_to_mat(pybind11::array buf, int opencv_depth)
{
cv::Mat value;
if (buf.ndim() == 1)
{ // A numpy array, with only one dimension. A row-vector.
auto num_elements = buf.shape(0);
auto opencv_type = CV_MAKETYPE(opencv_depth, 1);
value = cv::Mat(1, num_elements, opencv_type, buf.mutable_data());
}
else if (buf.ndim() == 2)
{ // We got a matrix (but it can also be 1 x n or n x 1)
auto opencv_type = CV_MAKETYPE(opencv_depth, 1);
value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
}
else if (buf.ndim() == 3)
{ // We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter)
auto num_chans = buf.shape(2); // Check whether 3 or 4 and abort otherwise??
auto opencv_type = CV_MAKETYPE(opencv_depth, num_chans);
value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
}
else { // buf.ndim() is not 1, 2 or 3.
return cv::Mat();
}
return value;
};
/**
* @brief Transparent conversion for OpenCV's cv::Mat type to and from Python.
*
* Converts cv::Mat's to and from Python. Can construct a cv::Mat from numpy arrays,
* as well as potentially other Python array types.
*
* - Supports only contiguous matrices
* - The numpy array has to be in default (row-major) storage order
* - Non-default strides are not implemented.
*
* Note about strides: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-step1
* And possibly use src.elemSize or src.elemSize1.
* See also the old bindings: https://github.com/patrikhuber/eos/commit/1c3b0113a3efcbb1a92efca646be663ef8593793
*/
template<>
struct type_caster<cv::Mat>
{
bool load(handle src, bool)
{
// Since cv::Mat has its time dynamically specified at run-time, we can't bind functions
// that take a cv::Mat to any particular Scalar type.
// Thus the data we get from python can be any type.
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
int opencv_depth;
if (pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))
{
opencv_depth = CV_8U;
}
else if (pybind11::isinstance<pybind11::array_t<float>>(buf))
{
opencv_depth = CV_32F;
}
else if (pybind11::isinstance<pybind11::array_t<double>>(buf))
{
opencv_depth = CV_64F;
}
else
{
return false;
}
// Todo: Would be nice to add int32, as it's the default in python if you create a
// list with [1, 2, 3]. But it doesn't evaluate to true when comparing with
// all integer dtypes (int, int32, uint32, etc.).
value = pyarray_to_mat(buf, opencv_depth);
if (value.empty())
{
return false;
}
return true;
};
static handle cast(const cv::Mat& src, return_value_policy /* policy */, handle /* parent */)
{
if (!src.isContinuous())
{
throw std::runtime_error("Cannot cast non-contiguous cv::Mat objects to Python. Change the C++ code to return a contiguous cv::Mat.");
// We could probably support that with implementing strides properly.
}
const auto opencv_depth = src.depth();
const auto num_chans = src.channels();
std::vector<std::size_t> shape;
if (num_chans == 1)
{
shape = { (size_t)src.rows, (size_t)src.cols };
// if either of them is == 1, we could specify only 1 value for shape - but be careful with strides,
// if there's a col-vector, I don't think we can do it without using strides.
// Also, check what happens in python when we pass a col & row vec respectively.
}
else if (num_chans == 2 || num_chans == 3 || num_chans == 4)
{
shape = { (size_t)src.rows, (size_t)src.cols, (size_t)num_chans };
}
else {
throw std::runtime_error("Cannot return matrices with more than 4 channels back to Python.");
// We could probably implement this quite easily but >4 channel images/matrices don't occur often.
}
// Now return the data, depending on its type:
if (opencv_depth == CV_8U)
{
return array(pybind11::dtype::of<std::uint8_t>(), shape, src.data).release();
}
else if (opencv_depth == CV_32F)
{
return array(pybind11::dtype::of<float>(), shape, src.data).release();
}
else if (opencv_depth == CV_64F)
{
return array(pybind11::dtype::of<double>(), shape, src.data).release();
}
else {
throw std::runtime_error("Can currently only return matrices of type 8U, 32F and 64F back to Python. Other types can be added if needed.");
}
};
PYBIND11_TYPE_CASTER(cv::Mat, _("numpy.ndarray[uint8|float32|float64[m, n, d]]"));
};
NAMESPACE_END(detail)
NAMESPACE_END(pybind11)
|
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#undef OSVR_DEV_VERBOSE_DISABLE
// Internal Includes
#include <osvr/Common/ProcessDeviceDescriptor.h>
#include <osvr/Common/PathTree.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/RoutingConstants.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Common/AliasProcessor.h>
#include <osvr/Common/NormalizeDeviceDescriptor.h>
#include "PathParseAndRetrieve.h"
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/noncopyable.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
// Standard includes
#include <utility>
#include <tuple>
namespace osvr {
namespace common {
static const char INTERFACES_KEY[] = "interfaces";
static inline util::Flag
processInterfacesFromDescriptor(PathNode &devNode,
Json::Value const &desc) {
util::Flag changed;
if (!desc.isMember(INTERFACES_KEY)) {
// No interfaces member
return changed;
}
Json::Value const &ifaces = desc[INTERFACES_KEY];
if (!ifaces.isObject()) {
// Interfaces member isn't an object
return changed;
}
for (auto const &iface : ifaces.getMemberNames()) {
auto &ifaceNode = treePathRetrieve(devNode, iface);
if (elements::isNull(ifaceNode.value())) {
ifaceNode.value() = elements::InterfaceElement();
changed.set();
}
}
return changed;
}
static const char TARGET_KEY[] = "$target";
static const char SEMANTIC_KEY[] = "semantic";
static const char AUTOMATIC_KEY[] = "automaticAliases";
namespace {
class SemanticRecursion : boost::noncopyable {
public:
SemanticRecursion(PathNode &devNode) : m_devNode(devNode) {}
util::Flag operator()(Json::Value const &semanticObject) {
m_recurse(semanticObject, SEMANTIC_KEY);
return m_flag;
}
private:
bool m_add(Json::Value const ¤tLevel,
std::string const &relativeSemanticPath) {
return addAliasFromSourceAndRelativeDest(
m_devNode, currentLevel.toStyledString(),
relativeSemanticPath, ALIASPRIORITY_SEMANTICROUTE);
}
void m_recurse(Json::Value const ¤tLevel,
std::string const &relativeSemanticPath) {
if (currentLevel.isString()) {
m_flag += m_add(currentLevel, relativeSemanticPath);
return;
}
if (currentLevel.isObject()) {
Json::Value target = currentLevel[TARGET_KEY];
if (!target.isNull()) {
m_flag += m_add(target, relativeSemanticPath);
}
for (auto const &memberName :
currentLevel.getMemberNames()) {
if (TARGET_KEY == memberName) {
continue;
}
m_recurse(currentLevel[memberName],
relativeSemanticPath + getPathSeparator() +
memberName);
}
}
}
PathNode &m_devNode;
util::Flag m_flag;
};
} // namespace
static inline util::Flag
processSemanticFromDescriptor(PathNode &devNode, Json::Value const &desc) {
util::Flag changed;
Json::Value const &sem = desc[SEMANTIC_KEY];
if (!sem.isObject()) {
// Semantic member isn't an object or isn't a member
return changed;
}
SemanticRecursion f{devNode};
changed += f(sem);
return changed;
}
static inline bool processAutomaticFromDescriptor(PathNode &devNode,
Json::Value const &desc) {
Json::Value const &automatic = desc[AUTOMATIC_KEY];
return AliasProcessor{}
.setDefaultPriority(ALIASPRIORITY_AUTOMATIC)
.enableRelativePath()
.enableRelativeSource()
.enableWildcard()
.process(devNode, automatic);
}
/// Given a device name, which may or may not include a host, as well as a
/// fallback host and port, return a (dev, host) string pair.
static inline std::pair<std::string, std::string>
getDevHost(std::string const &deviceName, std::string const &host) {
auto atLocation = deviceName.find('@');
if (std::string::npos == atLocation) {
// No at-symbol - we append our hostname.
return std::make_pair(deviceName, host);
}
// Split host from device
std::string devName(deviceName);
devName.resize(atLocation);
return std::make_pair(devName, devName.substr(atLocation + 1));
}
bool processDeviceDescriptorForPathTree(PathTree &tree,
std::string const &deviceName,
std::string const &jsonDescriptor,
int listenPort,
std::string const &host) {
std::string devName{deviceName};
if (getPathSeparatorCharacter() == devName.at(0)) {
// Leading slash, which we'll need to drop from the device name
devName.erase(begin(devName));
}
util::Flag changed;
/// Set up device node
auto &devNode = tree.getNodeByPath(getPathSeparator() + devName);
auto devElt = boost::get<elements::DeviceElement>(&devNode.value());
if (nullptr == devElt) {
std::string dev;
std::string devHost;
// Split host from device, or use the default host and port.
std::tie(dev, devHost) = getDevHost(devName, host);
devNode.value() =
elements::DeviceElement::createDeviceElement(dev, devHost, listenPort);
devElt = boost::get<elements::DeviceElement>(&devNode.value());
changed.set();
}
/// normalize device descriptor
const std::string normalizedDescriptor =
normalizeDeviceDescriptor(jsonDescriptor);
/// Parse JSON to stuff into device node.
Json::Value descriptor;
{
Json::Reader reader;
if (!reader.parse(normalizedDescriptor, descriptor)) {
/// @todo warn about failed descriptor parse?
return changed.get();
}
}
if (descriptor == devElt->getDescriptor() && !changed) {
/// @todo no change in descriptor so no processing?
return changed.get();
}
devElt->getDescriptor() = descriptor;
changed += processDeviceDescriptorFromExistingDevice(devNode, *devElt);
return changed.get();
}
bool processDeviceDescriptorFromExistingDevice(
PathNode &devNode, elements::DeviceElement const &devElt) {
util::Flag changed;
changed +=
processInterfacesFromDescriptor(devNode, devElt.getDescriptor());
changed +=
processSemanticFromDescriptor(devNode, devElt.getDescriptor());
changed +=
processAutomaticFromDescriptor(devNode, devElt.getDescriptor());
return changed.get();
}
} // namespace common
} // namespace osvr
handle articulationSpec when processing device descriptor
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#undef OSVR_DEV_VERBOSE_DISABLE
// Internal Includes
#include <osvr/Common/ProcessDeviceDescriptor.h>
#include <osvr/Common/PathTree.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/RoutingConstants.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Common/AliasProcessor.h>
#include <osvr/Common/NormalizeDeviceDescriptor.h>
#include "PathParseAndRetrieve.h"
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/noncopyable.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
// Standard includes
#include <utility>
#include <tuple>
namespace osvr {
namespace common {
static const char INTERFACES_KEY[] = "interfaces";
static inline util::Flag
processInterfacesFromDescriptor(PathNode &devNode,
Json::Value const &desc) {
util::Flag changed;
if (!desc.isMember(INTERFACES_KEY)) {
// No interfaces member
return changed;
}
Json::Value const &ifaces = desc[INTERFACES_KEY];
if (!ifaces.isObject()) {
// Interfaces member isn't an object
return changed;
}
for (auto const &iface : ifaces.getMemberNames()) {
auto &ifaceNode = treePathRetrieve(devNode, iface);
if (elements::isNull(ifaceNode.value())) {
ifaceNode.value() = elements::InterfaceElement();
changed.set();
}
}
return changed;
}
static const char TARGET_KEY[] = "$target";
static const char SEMANTIC_KEY[] = "semantic";
static const char AUTOMATIC_KEY[] = "automaticAliases";
static const char ARTICULATION_KEY[] = "articulationSpec";
static const char DATA_KEY[] = "$data";
namespace {
class SemanticRecursion : boost::noncopyable {
public:
SemanticRecursion(PathNode &devNode) : m_devNode(devNode) {}
util::Flag operator()(Json::Value const &semanticObject) {
m_recurse(semanticObject, SEMANTIC_KEY);
return m_flag;
}
private:
bool m_add(Json::Value const ¤tLevel,
std::string const &relativeSemanticPath) {
return addAliasFromSourceAndRelativeDest(
m_devNode, currentLevel.toStyledString(),
relativeSemanticPath, ALIASPRIORITY_SEMANTICROUTE);
}
void m_recurse(Json::Value const ¤tLevel,
std::string const &relativeSemanticPath) {
if (currentLevel.isString()) {
m_flag += m_add(currentLevel, relativeSemanticPath);
return;
}
if (currentLevel.isObject()) {
Json::Value target = currentLevel[TARGET_KEY];
if (!target.isNull()) {
m_flag += m_add(target, relativeSemanticPath);
}
for (auto const &memberName :
currentLevel.getMemberNames()) {
if (TARGET_KEY == memberName) {
continue;
}
m_recurse(currentLevel[memberName],
relativeSemanticPath + getPathSeparator() +
memberName);
}
}
}
PathNode &m_devNode;
util::Flag m_flag;
};
class ArticulationsRecursion : boost::noncopyable {
public:
ArticulationsRecursion(PathNode &devNode) : m_devNode(devNode) {}
util::Flag operator()(Json::Value const &articulationsObject) {
m_recurse(articulationsObject, ARTICULATION_KEY);
return m_flag;
}
private:
bool m_add(Json::Value const ¤tLevel,
std::string const &relativeArticulationsPath) {
return addArticulation(m_devNode, currentLevel.toStyledString(),
relativeArticulationsPath);
}
void m_recurse(Json::Value const ¤tLevel,
std::string const &relativeArticulationsPath) {
// if (currentLevel.isString()) {
// m_flag += m_add(currentLevel, relativeArticulationsPath);
// return;
//}
if (currentLevel.isObject()) {
Json::Value data = currentLevel[DATA_KEY];
if (!data.isNull()) {
m_flag += m_add(data, relativeArticulationsPath);
}
for (auto const &memberName :
currentLevel.getMemberNames()) {
if (DATA_KEY == memberName) {
continue;
}
m_recurse(currentLevel[memberName],
relativeArticulationsPath +
getPathSeparator() + memberName);
}
}
}
PathNode &m_devNode;
util::Flag m_flag;
};
} // namespace
static inline util::Flag
processSemanticFromDescriptor(PathNode &devNode, Json::Value const &desc) {
util::Flag changed;
Json::Value const &sem = desc[SEMANTIC_KEY];
if (!sem.isObject()) {
// Semantic member isn't an object or isn't a member
return changed;
}
SemanticRecursion f{devNode};
changed += f(sem);
return changed;
}
static inline util::Flag
processArticulationSpecFromDescriptor(PathNode &devNode,
Json::Value const &desc) {
util::Flag changed;
Json::Value const &articulations = desc[ARTICULATION_KEY];
if (!articulations.isObject()) {
// Articulation spec member isn't an object or isn't a member
return changed;
}
ArticulationsRecursion f{devNode};
changed += f(articulations);
return changed;
}
static inline bool processAutomaticFromDescriptor(PathNode &devNode,
Json::Value const &desc) {
Json::Value const &automatic = desc[AUTOMATIC_KEY];
return AliasProcessor{}
.setDefaultPriority(ALIASPRIORITY_AUTOMATIC)
.enableRelativePath()
.enableRelativeSource()
.enableWildcard()
.process(devNode, automatic);
}
/// Given a device name, which may or may not include a host, as well as a
/// fallback host and port, return a (dev, host) string pair.
static inline std::pair<std::string, std::string>
getDevHost(std::string const &deviceName, std::string const &host) {
auto atLocation = deviceName.find('@');
if (std::string::npos == atLocation) {
// No at-symbol - we append our hostname.
return std::make_pair(deviceName, host);
}
// Split host from device
std::string devName(deviceName);
devName.resize(atLocation);
return std::make_pair(devName, devName.substr(atLocation + 1));
}
bool processDeviceDescriptorForPathTree(PathTree &tree,
std::string const &deviceName,
std::string const &jsonDescriptor,
int listenPort,
std::string const &host) {
std::string devName{deviceName};
if (getPathSeparatorCharacter() == devName.at(0)) {
// Leading slash, which we'll need to drop from the device name
devName.erase(begin(devName));
}
util::Flag changed;
/// Set up device node
auto &devNode = tree.getNodeByPath(getPathSeparator() + devName);
auto devElt = boost::get<elements::DeviceElement>(&devNode.value());
if (nullptr == devElt) {
std::string dev;
std::string devHost;
// Split host from device, or use the default host and port.
std::tie(dev, devHost) = getDevHost(devName, host);
devNode.value() =
elements::DeviceElement::createDeviceElement(dev, devHost, listenPort);
devElt = boost::get<elements::DeviceElement>(&devNode.value());
changed.set();
}
/// normalize device descriptor
const std::string normalizedDescriptor =
normalizeDeviceDescriptor(jsonDescriptor);
/// Parse JSON to stuff into device node.
Json::Value descriptor;
{
Json::Reader reader;
if (!reader.parse(normalizedDescriptor, descriptor)) {
/// @todo warn about failed descriptor parse?
return changed.get();
}
}
if (descriptor == devElt->getDescriptor() && !changed) {
/// @todo no change in descriptor so no processing?
return changed.get();
}
devElt->getDescriptor() = descriptor;
changed += processDeviceDescriptorFromExistingDevice(devNode, *devElt);
return changed.get();
}
bool processDeviceDescriptorFromExistingDevice(
PathNode &devNode, elements::DeviceElement const &devElt) {
util::Flag changed;
changed +=
processInterfacesFromDescriptor(devNode, devElt.getDescriptor());
changed +=
processSemanticFromDescriptor(devNode, devElt.getDescriptor());
changed +=
processAutomaticFromDescriptor(devNode, devElt.getDescriptor());
changed += processArticulationSpecFromDescriptor(
devNode, devElt.getDescriptor());
return changed.get();
}
} // namespace common
} // namespace osvr
|
#include "cellmlplugin.h"
#include "coreutils.h"
#include "CellMLBootstrap.hpp"
#include "IfaceCellML_APISPEC.hxx"
#include "cellml-api-cxx-support.hpp"
#include <QDebug>
#include <QDir>
#include <QUrl>
namespace OpenCOR {
namespace CellML {
PLUGININFO_FUNC CellMLPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", "A plugin to use the <a href=\"http://www.cellml.org/tools/api/\">CellML API</a>");
descriptions.insert("fr", "Une extension pour utiliser l'<a href=\"http://www.cellml.org/tools/api/\">API CellML</a>");
return PluginInfo(PluginInfo::V001,
PluginInfo::General,
PluginInfo::Api,
false,
QStringList(),
descriptions);
}
Q_EXPORT_PLUGIN2(CellML, CellMLPlugin)
void CellMLPlugin::initialize()
{
using namespace iface::cellml_api;
// Fetch a bootstrap object
CellMLBootstrap *cbs = CreateCellMLBootstrap();
// Retrieve the model loader
DOMModelLoader *ml = cbs->modelLoader();
// Load our test CellML model and return its cmeta:id
// Note: we do this within a try...catch statement since we might get an
// exception...
QString testCellmlModelFileName = QDir::tempPath()+QDir::separator()+"test_cellml_model.cellml";
Core::saveResourceAs(":test_cellml_model", testCellmlModelFileName);
try {
qDebug("Loading the model...");
Model *model = ml->loadFromURL(QUrl::fromLocalFile(testCellmlModelFileName).toString().toStdWString().c_str());
qDebug();
qDebug("Retrieving some model properties...");
// Retrieve the model's name
qDebug(" Model '%s'",
QString::fromWCharArray(model->name()).toLatin1().constData());
// Go through the model's components and their respective variables
CellMLComponentSet *comps = model->modelComponents();
CellMLComponentIterator *compsIter = comps->iterateComponents();
for (int i = 0; i < comps->length(); i++) {
CellMLComponent *comp = compsIter->nextComponent();
qDebug(" Component '%s'",
QString::fromWCharArray(comp->name()).toLatin1().constData());
CellMLVariableSet *vars = comp->variables();
CellMLVariableIterator *varsIter = vars->iterateVariables();
for(int j = 0; j < vars->length(); ++j)
qDebug(" Variable '%s'",
QString::fromStdWString(varsIter->nextVariable()->name()).toLatin1().constData());
}
// Go through the model's connections and information
ConnectionSet *conns = model->connections();
ConnectionIterator *connsIter = conns->iterateConnections();
for (int i = 0; i < conns->length(); i++) {
Connection *conn = connsIter->nextConnection();
MapComponents *compMap = conn->componentMapping();
qDebug(" Connection between '%s' and '%s'",
QString::fromStdWString(compMap->firstComponentName()).toLatin1().constData(),
QString::fromStdWString(compMap->secondComponentName()).toLatin1().constData());
MapVariablesSet *varMaps = conn->variableMappings();
MapVariablesIterator *varMapsIter = varMaps->iterateMapVariables();
for(int j = 0; j < varMaps->length(); ++j) {
MapVariables *mapVars = varMapsIter->nextMapVariables();
qDebug(" For variables '%s' and '%s'",
QString::fromStdWString(mapVars->firstVariableName()).toLatin1().constData(),
QString::fromStdWString(mapVars->secondVariableName()).toLatin1().constData());
}
}
// All done...
qDebug();
qDebug("All done...");
} catch (CellMLException &) {
qDebug("ERROR: %s.",
QString::fromWCharArray(ml->lastErrorMessage()).toLatin1().constData());
}
QFile::remove(testCellmlModelFileName);
}
QList<FileType> CellMLPlugin::fileTypes() const
{
// Return the CellML file type that the CellML plugin supports
return QList<FileType>() << FileType(qobject_cast<FileInterface *>(this),
CellmlMimeType, "cellml");
}
QString CellMLPlugin::fileTypeDescription(const QString &mMimeType) const
{
// Return the description for the requested Mime type, that is as long as it
// is for the CellML Mime type
if (!mMimeType.compare(CellmlMimeType))
return tr("CellML File");
else
// Not a Mime type that we can recognise, so...
return FileInterface::fileTypeDescription(mMimeType);
}
} }
Got some code to run a CellML file. However, though it all works fine, it looks rather cumbersome to me.
#include "cellmlplugin.h"
#include "coreutils.h"
#include "cellml-api-cxx-support.hpp"
#include "CellMLBootstrap.hpp"
#include "IfaceCellML_APISPEC.hxx"
#include "IfaceCIS.hxx"
#include "CISBootstrap.hpp"
#include <QDebug>
#include <QDir>
#include <QThread>
#include <QUrl>
namespace OpenCOR {
namespace CellML {
PLUGININFO_FUNC CellMLPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", "A plugin to use the <a href=\"http://www.cellml.org/tools/api/\">CellML API</a>");
descriptions.insert("fr", "Une extension pour utiliser l'<a href=\"http://www.cellml.org/tools/api/\">API CellML</a>");
return PluginInfo(PluginInfo::V001,
PluginInfo::General,
PluginInfo::Api,
false,
QStringList(),
descriptions);
}
Q_EXPORT_PLUGIN2(CellML, CellMLPlugin)
class SleeperThread : public QThread
{
public:
static void msleep(unsigned long msecs)
{
QThread::msleep(msecs);
}
};
class TestProgressObserver : public iface::cellml_services::IntegrationProgressObserver
{
public:
TestProgressObserver(iface::cellml_services::CellMLCompiledModel *pCompiledModel) :
mCompiledModel(pCompiledModel),
mCodeInformation(pCompiledModel->codeInformation()),
mRefCount(1),
mFinished(false)
{
iface::cellml_services::ComputationTargetIterator *cti = mCodeInformation->iterateTargets();
bool first = true;
mHeader = QString();
while (true) {
iface::cellml_services::ComputationTarget* ct = cti->nextComputationTarget();
if (!ct)
break;
if ( ((ct->type() == iface::cellml_services::STATE_VARIABLE)
|| (ct->type() == iface::cellml_services::ALGEBRAIC)
|| (ct->type() == iface::cellml_services::VARIABLE_OF_INTEGRATION))
&& (ct->degree() == 0)) {
if (!first)
mHeader += ",";
else
first = false;
mHeader += QString::fromWCharArray(ct->variable()->name());
}
}
}
virtual void add_ref() throw(std::exception &)
{
++mRefCount;
}
virtual void release_ref() throw(std::exception &)
{
--mRefCount;
if (!mRefCount)
delete this;
}
virtual char * objid() throw (std::exception &)
{
return strdup("singletonTestProgressObserver");
}
virtual void * query_interface(const char *pIface) throw (std::exception &)
{
if (!strcmp(pIface, "xpcom::IObject"))
return static_cast<iface::XPCOM::IObject *>(this);
else if (!strcmp(pIface, "cellml_services::IntegrationProgressObserver"))
return static_cast<iface::cellml_services::IntegrationProgressObserver *> (this);
return 0;
}
virtual void computedConstants(uint32_t, double *pValues) throw (std::exception &)
{
iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets();
qDebug(" Computed constants...");
while (true) {
iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget();
if (!target)
break;
if ( (target->type() == iface::cellml_services::CONSTANT)
&& !target->degree())
qDebug(" %s = %g",
QString::fromWCharArray(target->variable()->name()).toLatin1().constData(),
pValues[target->assignedIndex()]);
}
}
virtual void results(uint32_t pNbOfValues, double *pValues) throw (std::exception&)
{
static bool needInit = true;
if (needInit) {
qDebug(" Results...");
qDebug(" %s", mHeader.toLatin1().constData());
needInit = false;
}
uint32_t rateIndexCount = mCodeInformation->rateIndexCount();
uint32_t recSize = 2*rateIndexCount
+mCodeInformation->algebraicIndexCount()
+1;
if (!recSize)
return;
for (uint32_t i = 0; i < pNbOfValues; i += recSize)
{
bool first = true;
iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets();
QString values = QString();
while (true)
{
iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget();
if (!target)
break;
if (target->degree())
continue;
uint32_t varOff = 0;
switch (target->type()) {
case iface::cellml_services::STATE_VARIABLE:
varOff = 1+target->assignedIndex();
break;
case iface::cellml_services::VARIABLE_OF_INTEGRATION:
varOff = 0;
break;
case iface::cellml_services::ALGEBRAIC:
varOff = 1+2*rateIndexCount+target->assignedIndex();
break;
default:
continue;
}
if (!first)
values += ",";
else
first = false;
values += QString::number(pValues[i+varOff]);
}
qDebug(" %s", values.toLatin1().constData());
}
}
virtual void done() throw (std::exception &)
{
mFinished = true;
}
virtual void failed(const char *pErrorMsg) throw (std::exception &)
{
qDebug("ERROR: integration failed (%s).", pErrorMsg);
mFinished = true;
}
bool finished()
{
return mFinished;
}
private:
iface::cellml_services::CellMLCompiledModel *mCompiledModel;
iface::cellml_services::CodeInformation *mCodeInformation;
uint32_t mRefCount;
bool mFinished;
QString mHeader;
};
void CellMLPlugin::initialize()
{
// Fetch a bootstrap object
iface::cellml_api::CellMLBootstrap *cbs = CreateCellMLBootstrap();
// Retrieve the model loader
iface::cellml_api::DOMModelLoader *ml = cbs->modelLoader();
// Load our test CellML model and return its cmeta:id
// Note: we do this within a try...catch statement since we might get an
// exception...
QString testCellmlModelFileName = QDir::tempPath()+QDir::separator()+"test_cellml_model.cellml";
Core::saveResourceAs(":test_cellml_model", testCellmlModelFileName);
qDebug("Loading the model...");
iface::cellml_api::Model *model;
try {
model = ml->loadFromURL(QUrl::fromLocalFile(testCellmlModelFileName).toString().toStdWString().c_str());
} catch (iface::cellml_api::CellMLException &) {
qDebug("ERROR: %s.",
QString::fromWCharArray(ml->lastErrorMessage()).toLatin1().constData());
return;
}
qDebug();
qDebug("Retrieving some model properties...");
// Retrieve the model's name
qDebug(" Model '%s'",
QString::fromWCharArray(model->name()).toLatin1().constData());
// Go through the model's components and their respective variables
iface::cellml_api::CellMLComponentSet *comps = model->modelComponents();
iface::cellml_api::CellMLComponentIterator *compsIter = comps->iterateComponents();
for (int i = 0; i < comps->length(); i++) {
iface::cellml_api::CellMLComponent *comp = compsIter->nextComponent();
qDebug(" Component '%s'",
QString::fromWCharArray(comp->name()).toLatin1().constData());
iface::cellml_api::CellMLVariableSet *vars = comp->variables();
iface::cellml_api::CellMLVariableIterator *varsIter = vars->iterateVariables();
for(int j = 0; j < vars->length(); ++j)
qDebug(" Variable '%s'",
QString::fromStdWString(varsIter->nextVariable()->name()).toLatin1().constData());
}
// Go through the model's connections and information
iface::cellml_api::ConnectionSet *conns = model->connections();
iface::cellml_api::ConnectionIterator *connsIter = conns->iterateConnections();
for (int i = 0; i < conns->length(); i++) {
iface::cellml_api::Connection *conn = connsIter->nextConnection();
iface::cellml_api::MapComponents *compMap = conn->componentMapping();
qDebug(" Connection between '%s' and '%s'",
QString::fromStdWString(compMap->firstComponentName()).toLatin1().constData(),
QString::fromStdWString(compMap->secondComponentName()).toLatin1().constData());
iface::cellml_api::MapVariablesSet *varMaps = conn->variableMappings();
iface::cellml_api::MapVariablesIterator *varMapsIter = varMaps->iterateMapVariables();
for(int j = 0; j < varMaps->length(); ++j) {
iface::cellml_api::MapVariables *mapVars = varMapsIter->nextMapVariables();
qDebug(" For variables '%s' and '%s'",
QString::fromStdWString(mapVars->firstVariableName()).toLatin1().constData(),
QString::fromStdWString(mapVars->secondVariableName()).toLatin1().constData());
}
}
// Run the model
qDebug();
qDebug("Running the model...");
iface::cellml_services::CellMLIntegrationService* cis = CreateIntegrationService();
iface::cellml_services::ODESolverCompiledModel* compiledModel = 0;
qDebug(" Compiling the model...");
try
{
compiledModel = cis->compileModelODE(model);
} catch (iface::cellml_api::CellMLException &) {
qDebug("ERROR: %s.",
QString::fromWCharArray(cis->lastError()).toLatin1().constData());
return;
} catch (...) {
qDebug("ERROR: unexpected exception calling compileModel.");
return;
}
qDebug(" Creating the ODE solver run...");
iface::cellml_services::ODESolverRun *odeSolverRun = cis->createODEIntegrationRun(compiledModel);
TestProgressObserver* progressObserver = new TestProgressObserver(compiledModel);
odeSolverRun->setProgressObserver(progressObserver);
odeSolverRun->stepType(iface::cellml_services::BDF_IMPLICIT_1_5_SOLVE);
odeSolverRun->setResultRange(0, 50, 0);
odeSolverRun->setTabulationStepControl(1, true);
odeSolverRun->start();
while (!progressObserver->finished())
SleeperThread::msleep(1000);
// All done...
qDebug();
qDebug("All done...");
QFile::remove(testCellmlModelFileName);
}
QList<FileType> CellMLPlugin::fileTypes() const
{
// Return the CellML file type that the CellML plugin supports
return QList<FileType>() << FileType(qobject_cast<FileInterface *>(this),
CellmlMimeType, "cellml");
}
QString CellMLPlugin::fileTypeDescription(const QString &mMimeType) const
{
// Return the description for the requested Mime type, that is as long as it
// is for the CellML Mime type
if (!mMimeType.compare(CellmlMimeType))
return tr("CellML File");
else
// Not a Mime type that we can recognise, so...
return FileInterface::fileTypeDescription(mMimeType);
}
} }
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basetextdocument.h"
#include "basetextdocumentlayout.h"
#include "basetexteditor.h"
#include "storagesettings.h"
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
#include <QtGui/QMainWindow>
#include <QtGui/QSyntaxHighlighter>
#include <QtGui/QApplication>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
#include <utils/reloadpromptutils.h>
using namespace TextEditor;
DocumentMarker::DocumentMarker(QTextDocument *doc)
: ITextMarkable(doc), document(doc)
{
}
bool DocumentMarker::addMark(TextEditor::ITextMark *mark, int line)
{
QTC_ASSERT(line >= 1, return false);
int blockNumber = line - 1;
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
QTC_ASSERT(documentLayout, return false);
QTextBlock block = document->findBlockByNumber(blockNumber);
if (block.isValid()) {
TextBlockUserData *userData = BaseTextDocumentLayout::userData(block);
userData->addMark(mark);
mark->updateLineNumber(blockNumber + 1);
mark->updateBlock(block);
documentLayout->hasMarks = true;
documentLayout->requestUpdate();
return true;
}
return false;
}
TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
QTC_ASSERT(line >= 1, return TextMarks());
int blockNumber = line - 1;
QTextBlock block = document->findBlockByNumber(blockNumber);
if (block.isValid()) {
if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
return userData->marks();
}
return TextMarks();
}
void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
bool needUpdate = false;
QTextBlock block = document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
needUpdate |= data->removeMark(mark);
}
block = block.next();
}
if (needUpdate)
updateMark(0);
}
bool DocumentMarker::hasMark(TextEditor::ITextMark *mark) const
{
QTextBlock block = document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
if (data->hasMark(mark))
return true;
}
block = block.next();
}
return false;
}
void DocumentMarker::updateMark(ITextMark *mark)
{
Q_UNUSED(mark)
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
QTC_ASSERT(documentLayout, return);
documentLayout->requestUpdate();
}
BaseTextDocument::BaseTextDocument()
: m_document(new QTextDocument(this)),
m_highlighter(0)
{
m_documentMarker = new DocumentMarker(m_document);
m_lineTerminatorMode = NativeLineTerminator;
m_fileIsReadOnly = false;
m_isBinaryData = false;
m_codec = QTextCodec::codecForLocale();
QSettings *settings = Core::ICore::instance()->settings();
if (QTextCodec *candidate = QTextCodec::codecForName(
settings->value(QLatin1String("General/DefaultFileEncoding")).toByteArray()))
m_codec = candidate;
m_hasDecodingError = false;
}
BaseTextDocument::~BaseTextDocument()
{
documentClosing();
delete m_document;
m_document = 0;
}
QString BaseTextDocument::mimeType() const
{
return m_mimeType;
}
void BaseTextDocument::setMimeType(const QString &mt)
{
m_mimeType = mt;
}
bool BaseTextDocument::save(const QString &fileName)
{
QTextCursor cursor(m_document);
cursor.beginEditBlock();
if (m_storageSettings.m_cleanWhitespace)
cleanWhitespace(cursor, m_storageSettings.m_cleanIndentation, m_storageSettings.m_inEntireDocument);
if (m_storageSettings.m_addFinalNewLine)
ensureFinalNewLine(cursor);
cursor.endEditBlock();
QString fName = m_fileName;
if (!fileName.isEmpty())
fName = fileName;
QFile file(fName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
return false;
QString plainText = m_document->toPlainText();
if (m_lineTerminatorMode == CRLFLineTerminator)
plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
file.write(m_codec->fromUnicode(plainText));
if (!file.flush())
return false;
file.close();
const QFileInfo fi(fName);
m_fileName = QDir::cleanPath(fi.absoluteFilePath());
m_document->setModified(false);
emit titleChanged(fi.fileName());
emit changed();
m_isBinaryData = false;
m_hasDecodingError = false;
m_decodingErrorSample.clear();
return true;
}
bool BaseTextDocument::isReadOnly() const
{
if (m_isBinaryData || m_hasDecodingError)
return true;
if (m_fileName.isEmpty()) //have no corresponding file, so editing is ok
return false;
return m_fileIsReadOnly;
}
bool BaseTextDocument::isModified() const
{
return m_document->isModified();
}
void BaseTextDocument::checkPermissions()
{
bool previousReadOnly = m_fileIsReadOnly;
if (!m_fileName.isEmpty()) {
const QFileInfo fi(m_fileName);
m_fileIsReadOnly = !fi.isWritable();
} else {
m_fileIsReadOnly = false;
}
if (previousReadOnly != m_fileIsReadOnly)
emit changed();
}
bool BaseTextDocument::open(const QString &fileName)
{
QString title = tr("untitled");
if (!fileName.isEmpty()) {
const QFileInfo fi(fileName);
m_fileIsReadOnly = !fi.isWritable();
m_fileName = QDir::cleanPath(fi.absoluteFilePath());
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
title = fi.fileName();
QByteArray buf = file.readAll();
int bytesRead = buf.size();
QTextCodec *codec = m_codec;
// code taken from qtextstream
if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
|| (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-32");
} else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
|| (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-16");
} else if (!codec) {
codec = QTextCodec::codecForLocale();
}
// end code taken from qtextstream
m_codec = codec;
#if 0 // should work, but does not, Qt bug with "system" codec
QTextDecoder *decoder = m_codec->makeDecoder();
QString text = decoder->toUnicode(buf);
m_hasDecodingError = (decoder->hasFailure());
delete decoder;
#else
QString text = m_codec->toUnicode(buf);
QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
// the minSize trick lets us ignore unicode headers
int minSize = qMin(verifyBuf.size(), buf.size());
m_hasDecodingError = (minSize < buf.size()- 4
|| memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
buf.constData() + buf.size() - minSize, minSize));
#endif
if (m_hasDecodingError) {
int p = buf.indexOf('\n', 16384);
if (p < 0)
m_decodingErrorSample = buf;
else
m_decodingErrorSample = buf.left(p);
} else {
m_decodingErrorSample.clear();
}
int lf = text.indexOf('\n');
if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
m_lineTerminatorMode = CRLFLineTerminator;
} else if (lf >= 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
m_lineTerminatorMode = NativeLineTerminator;
}
m_document->setModified(false);
if (m_isBinaryData)
m_document->setHtml(tr("<em>Binary data</em>"));
else
m_document->setPlainText(text);
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_document->documentLayout());
QTC_ASSERT(documentLayout, return true);
documentLayout->lastSaveRevision = m_document->revision();
m_document->setModified(false);
emit titleChanged(title);
emit changed();
}
return true;
}
void BaseTextDocument::reload(QTextCodec *codec)
{
QTC_ASSERT(codec, return);
m_codec = codec;
reload();
}
void BaseTextDocument::reload()
{
emit aboutToReload();
documentClosing(); // removes text marks non-permanently
if (open(m_fileName))
emit reloaded();
}
Core::IFile::ReloadBehavior BaseTextDocument::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
if (type == TypePermissions)
return BehaviorSilent;
if (type == TypeContents) {
if (state == TriggerInternal && !isModified())
return BehaviorSilent;
return BehaviorAsk;
}
return BehaviorAsk;
}
void BaseTextDocument::reload(ReloadFlag flag, ChangeType type)
{
if (flag == FlagIgnore)
return;
if (type == TypePermissions) {
checkPermissions();
} else {
reload();
}
}
void BaseTextDocument::setSyntaxHighlighter(QSyntaxHighlighter *highlighter)
{
if (m_highlighter)
delete m_highlighter;
m_highlighter = highlighter;
m_highlighter->setParent(this);
m_highlighter->setDocument(m_document);
}
void BaseTextDocument::cleanWhitespace(const QTextCursor &cursor)
{
bool hasSelection = cursor.hasSelection();
QTextCursor copyCursor = cursor;
copyCursor.beginEditBlock();
cleanWhitespace(copyCursor, true, true);
if (!hasSelection)
ensureFinalNewLine(copyCursor);
copyCursor.endEditBlock();
}
void BaseTextDocument::cleanWhitespace(QTextCursor &cursor, bool cleanIndentation, bool inEntireDocument)
{
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_document->documentLayout());
QTextBlock block = m_document->findBlock(cursor.selectionStart());
QTextBlock end;
if (cursor.hasSelection())
end = m_document->findBlock(cursor.selectionEnd()-1).next();
while (block.isValid() && block != end) {
if (inEntireDocument || block.revision() != documentLayout->lastSaveRevision) {
QString blockText = block.text();
if (int trailing = m_tabSettings.trailingWhitespaces(blockText)) {
cursor.setPosition(block.position() + block.length() - 1);
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing);
cursor.removeSelectedText();
}
if (cleanIndentation && !m_tabSettings.isIndentationClean(block)) {
cursor.setPosition(block.position());
int firstNonSpace = m_tabSettings.firstNonSpace(blockText);
if (firstNonSpace == blockText.length()) {
cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
} else {
int column = m_tabSettings.columnAt(blockText, firstNonSpace);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace);
QString indentationString = m_tabSettings.indentationString(0, column, block);
cursor.insertText(indentationString);
}
}
}
block = block.next();
}
}
void BaseTextDocument::ensureFinalNewLine(QTextCursor& cursor)
{
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator)
{
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
cursor.insertText(QLatin1String("\n"));
}
}
void BaseTextDocument::documentClosing()
{
QTextBlock block = m_document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData()))
data->documentClosing();
block = block.next();
}
}
Maintain the right cursor when undoing "clean whitespace" after saving
Previously it would always jump to the start of the document, since
that's where the newly created text cursor is at the beginEditBlock
call. Avoid this when saving the current editor by starting with the
cursor of the editor.
Reviewed-by: mae
Task-number: QTCREATORBUG-1807
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "basetextdocument.h"
#include "basetextdocumentlayout.h"
#include "basetexteditor.h"
#include "storagesettings.h"
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
#include <QtGui/QMainWindow>
#include <QtGui/QSyntaxHighlighter>
#include <QtGui/QApplication>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
#include <utils/reloadpromptutils.h>
using namespace TextEditor;
DocumentMarker::DocumentMarker(QTextDocument *doc)
: ITextMarkable(doc), document(doc)
{
}
bool DocumentMarker::addMark(TextEditor::ITextMark *mark, int line)
{
QTC_ASSERT(line >= 1, return false);
int blockNumber = line - 1;
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
QTC_ASSERT(documentLayout, return false);
QTextBlock block = document->findBlockByNumber(blockNumber);
if (block.isValid()) {
TextBlockUserData *userData = BaseTextDocumentLayout::userData(block);
userData->addMark(mark);
mark->updateLineNumber(blockNumber + 1);
mark->updateBlock(block);
documentLayout->hasMarks = true;
documentLayout->requestUpdate();
return true;
}
return false;
}
TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
QTC_ASSERT(line >= 1, return TextMarks());
int blockNumber = line - 1;
QTextBlock block = document->findBlockByNumber(blockNumber);
if (block.isValid()) {
if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(block))
return userData->marks();
}
return TextMarks();
}
void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
bool needUpdate = false;
QTextBlock block = document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
needUpdate |= data->removeMark(mark);
}
block = block.next();
}
if (needUpdate)
updateMark(0);
}
bool DocumentMarker::hasMark(TextEditor::ITextMark *mark) const
{
QTextBlock block = document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
if (data->hasMark(mark))
return true;
}
block = block.next();
}
return false;
}
void DocumentMarker::updateMark(ITextMark *mark)
{
Q_UNUSED(mark)
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
QTC_ASSERT(documentLayout, return);
documentLayout->requestUpdate();
}
BaseTextDocument::BaseTextDocument()
: m_document(new QTextDocument(this)),
m_highlighter(0)
{
m_documentMarker = new DocumentMarker(m_document);
m_lineTerminatorMode = NativeLineTerminator;
m_fileIsReadOnly = false;
m_isBinaryData = false;
m_codec = QTextCodec::codecForLocale();
QSettings *settings = Core::ICore::instance()->settings();
if (QTextCodec *candidate = QTextCodec::codecForName(
settings->value(QLatin1String("General/DefaultFileEncoding")).toByteArray()))
m_codec = candidate;
m_hasDecodingError = false;
}
BaseTextDocument::~BaseTextDocument()
{
documentClosing();
delete m_document;
m_document = 0;
}
QString BaseTextDocument::mimeType() const
{
return m_mimeType;
}
void BaseTextDocument::setMimeType(const QString &mt)
{
m_mimeType = mt;
}
bool BaseTextDocument::save(const QString &fileName)
{
QTextCursor cursor(m_document);
// When saving the current editor, make sure to maintain the cursor position for undo
Core::IEditor *currentEditor = Core::EditorManager::instance()->currentEditor();
if (BaseTextEditorEditable *editable = qobject_cast<BaseTextEditorEditable*>(currentEditor)) {
if (editable->file() == this)
cursor = editable->editor()->textCursor();
}
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::Start);
if (m_storageSettings.m_cleanWhitespace)
cleanWhitespace(cursor, m_storageSettings.m_cleanIndentation, m_storageSettings.m_inEntireDocument);
if (m_storageSettings.m_addFinalNewLine)
ensureFinalNewLine(cursor);
cursor.endEditBlock();
QString fName = m_fileName;
if (!fileName.isEmpty())
fName = fileName;
QFile file(fName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
return false;
QString plainText = m_document->toPlainText();
if (m_lineTerminatorMode == CRLFLineTerminator)
plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
file.write(m_codec->fromUnicode(plainText));
if (!file.flush())
return false;
file.close();
const QFileInfo fi(fName);
m_fileName = QDir::cleanPath(fi.absoluteFilePath());
m_document->setModified(false);
emit titleChanged(fi.fileName());
emit changed();
m_isBinaryData = false;
m_hasDecodingError = false;
m_decodingErrorSample.clear();
return true;
}
bool BaseTextDocument::isReadOnly() const
{
if (m_isBinaryData || m_hasDecodingError)
return true;
if (m_fileName.isEmpty()) //have no corresponding file, so editing is ok
return false;
return m_fileIsReadOnly;
}
bool BaseTextDocument::isModified() const
{
return m_document->isModified();
}
void BaseTextDocument::checkPermissions()
{
bool previousReadOnly = m_fileIsReadOnly;
if (!m_fileName.isEmpty()) {
const QFileInfo fi(m_fileName);
m_fileIsReadOnly = !fi.isWritable();
} else {
m_fileIsReadOnly = false;
}
if (previousReadOnly != m_fileIsReadOnly)
emit changed();
}
bool BaseTextDocument::open(const QString &fileName)
{
QString title = tr("untitled");
if (!fileName.isEmpty()) {
const QFileInfo fi(fileName);
m_fileIsReadOnly = !fi.isWritable();
m_fileName = QDir::cleanPath(fi.absoluteFilePath());
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return false;
title = fi.fileName();
QByteArray buf = file.readAll();
int bytesRead = buf.size();
QTextCodec *codec = m_codec;
// code taken from qtextstream
if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
|| (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-32");
} else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
|| (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
codec = QTextCodec::codecForName("UTF-16");
} else if (!codec) {
codec = QTextCodec::codecForLocale();
}
// end code taken from qtextstream
m_codec = codec;
#if 0 // should work, but does not, Qt bug with "system" codec
QTextDecoder *decoder = m_codec->makeDecoder();
QString text = decoder->toUnicode(buf);
m_hasDecodingError = (decoder->hasFailure());
delete decoder;
#else
QString text = m_codec->toUnicode(buf);
QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
// the minSize trick lets us ignore unicode headers
int minSize = qMin(verifyBuf.size(), buf.size());
m_hasDecodingError = (minSize < buf.size()- 4
|| memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
buf.constData() + buf.size() - minSize, minSize));
#endif
if (m_hasDecodingError) {
int p = buf.indexOf('\n', 16384);
if (p < 0)
m_decodingErrorSample = buf;
else
m_decodingErrorSample = buf.left(p);
} else {
m_decodingErrorSample.clear();
}
int lf = text.indexOf('\n');
if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
m_lineTerminatorMode = CRLFLineTerminator;
} else if (lf >= 0) {
m_lineTerminatorMode = LFLineTerminator;
} else {
m_lineTerminatorMode = NativeLineTerminator;
}
m_document->setModified(false);
if (m_isBinaryData)
m_document->setHtml(tr("<em>Binary data</em>"));
else
m_document->setPlainText(text);
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_document->documentLayout());
QTC_ASSERT(documentLayout, return true);
documentLayout->lastSaveRevision = m_document->revision();
m_document->setModified(false);
emit titleChanged(title);
emit changed();
}
return true;
}
void BaseTextDocument::reload(QTextCodec *codec)
{
QTC_ASSERT(codec, return);
m_codec = codec;
reload();
}
void BaseTextDocument::reload()
{
emit aboutToReload();
documentClosing(); // removes text marks non-permanently
if (open(m_fileName))
emit reloaded();
}
Core::IFile::ReloadBehavior BaseTextDocument::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
if (type == TypePermissions)
return BehaviorSilent;
if (type == TypeContents) {
if (state == TriggerInternal && !isModified())
return BehaviorSilent;
return BehaviorAsk;
}
return BehaviorAsk;
}
void BaseTextDocument::reload(ReloadFlag flag, ChangeType type)
{
if (flag == FlagIgnore)
return;
if (type == TypePermissions) {
checkPermissions();
} else {
reload();
}
}
void BaseTextDocument::setSyntaxHighlighter(QSyntaxHighlighter *highlighter)
{
if (m_highlighter)
delete m_highlighter;
m_highlighter = highlighter;
m_highlighter->setParent(this);
m_highlighter->setDocument(m_document);
}
void BaseTextDocument::cleanWhitespace(const QTextCursor &cursor)
{
bool hasSelection = cursor.hasSelection();
QTextCursor copyCursor = cursor;
copyCursor.beginEditBlock();
cleanWhitespace(copyCursor, true, true);
if (!hasSelection)
ensureFinalNewLine(copyCursor);
copyCursor.endEditBlock();
}
void BaseTextDocument::cleanWhitespace(QTextCursor &cursor, bool cleanIndentation, bool inEntireDocument)
{
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_document->documentLayout());
QTextBlock block = m_document->findBlock(cursor.selectionStart());
QTextBlock end;
if (cursor.hasSelection())
end = m_document->findBlock(cursor.selectionEnd()-1).next();
while (block.isValid() && block != end) {
if (inEntireDocument || block.revision() != documentLayout->lastSaveRevision) {
QString blockText = block.text();
if (int trailing = m_tabSettings.trailingWhitespaces(blockText)) {
cursor.setPosition(block.position() + block.length() - 1);
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing);
cursor.removeSelectedText();
}
if (cleanIndentation && !m_tabSettings.isIndentationClean(block)) {
cursor.setPosition(block.position());
int firstNonSpace = m_tabSettings.firstNonSpace(blockText);
if (firstNonSpace == blockText.length()) {
cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
} else {
int column = m_tabSettings.columnAt(blockText, firstNonSpace);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace);
QString indentationString = m_tabSettings.indentationString(0, column, block);
cursor.insertText(indentationString);
}
}
}
block = block.next();
}
}
void BaseTextDocument::ensureFinalNewLine(QTextCursor& cursor)
{
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator)
{
cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
cursor.insertText(QLatin1String("\n"));
}
}
void BaseTextDocument::documentClosing()
{
QTextBlock block = m_document->begin();
while (block.isValid()) {
if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData()))
data->documentClosing();
block = block.next();
}
}
|
#ifndef CONST_NODE_HPP
#define CONST_NODE_HPP
#include <core/deterministic_node.hpp>
#include <helper/vnode.hpp>
#include <helper/node_counter.hpp>
#include <helper/abstract_node_factory.hpp>
#include <string>
namespace mcmc_utilities
{
template <typename T>
class const_node
:public deterministic_node<T>
{
private:
T v;
public:
const_node(T v1)
:deterministic_node<T>(0,1),v(v1)
{
}
T do_calc(size_t idx,const std::vector<T>&)const override
{
return v;
}
std::shared_ptr<node<T> > do_clone()const override
{
return std::shared_ptr<node<T> >(new const_node(v));
}
};
template <typename T>
class const_vnode
:public vnode<T>
{
public:
T value;
public:
const_vnode(std::string n,T v)
:vnode<T>("const",n),value(v)
{
this->binded=true;
}
public:
std::shared_ptr<node<T> > get_node()const override
{
return std::shared_ptr<node<T> >(new const_node<T>(value));
}
std::shared_ptr<vnode<T> > clone()const override
{
return std::shared_ptr<vnode<T> >(new const_vnode<T>(*this));
}
};
template <typename T>
class const_node_factory
:public abstract_node_factory<T>
{
public:
const_node_factory()
:abstract_node_factory<T>({},{"v"},{"value"})
{}
public:
std::shared_ptr<node<T> >
do_get_node(const std::vector<T>& hparam)const override
{
return std::shared_ptr<node<T> >(new const_node<T>(hparam[0]));
}
std::string do_get_node_type()const override
{
return std::string("deterministic");
}
};
using vconst=const_vnode<double>;
};
#endif
make const_node able to be set new value
#ifndef CONST_NODE_HPP
#define CONST_NODE_HPP
#include <core/deterministic_node.hpp>
#include <helper/vnode.hpp>
#include <helper/node_counter.hpp>
#include <helper/abstract_node_factory.hpp>
#include <string>
namespace mcmc_utilities
{
template <typename T>
class const_node
:public deterministic_node<T>
{
private:
T v;
public:
const_node(T v1)
:deterministic_node<T>(0,1),v(v1)
{
}
T do_calc(size_t idx,const std::vector<T>&)const override
{
return v;
}
std::shared_ptr<node<T> > do_clone()const override
{
return std::shared_ptr<node<T> >(new const_node(v));
}
void set_value(T v1)
{
v=v1;
}
};
template <typename T>
class const_vnode
:public vnode<T>
{
public:
T value;
public:
const_vnode(std::string n,T v)
:vnode<T>("const",n),value(v)
{
this->binded=true;
}
public:
std::shared_ptr<node<T> > get_node()const override
{
return std::shared_ptr<node<T> >(new const_node<T>(value));
}
std::shared_ptr<vnode<T> > clone()const override
{
return std::shared_ptr<vnode<T> >(new const_vnode<T>(*this));
}
};
template <typename T>
class const_node_factory
:public abstract_node_factory<T>
{
public:
const_node_factory()
:abstract_node_factory<T>({},{"v"},{"value"})
{}
public:
std::shared_ptr<node<T> >
do_get_node(const std::vector<T>& hparam)const override
{
return std::shared_ptr<node<T> >(new const_node<T>(hparam[0]));
}
std::string do_get_node_type()const override
{
return std::string("deterministic");
}
};
using vconst=const_vnode<double>;
};
#endif
|
/******************************************************************************
* include files
*****************************************************************************/
#include <stdio.h>
#include <assert.h>
#include <string>
extern "C" {
#include "xed-interface.h"
};
#include "code-ranges.h"
#include "function-entries.h"
#include "process-ranges.h"
/******************************************************************************
* macros
*****************************************************************************/
#define is_call_iclass(x) \
((x == XED_ICLASS_CALL_FAR) || (x == XED_ICLASS_CALL_NEAR))
/******************************************************************************
* forward declarations
*****************************************************************************/
static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr,
void *start, void *end);
static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr);
static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr);
static bool invalid_routine_start(unsigned char *ins);
static void addsub(char *ins, xed_decoded_inst_t *xptr, xed_iclass_enum_t iclass,
long ins_offset);
static void process_move(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_push(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_pop(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_enter(char *ins, long ins_offset);
static void process_leave(char *ins, long ins_offset);
static bool bkwd_jump_into_protected_range(char *ins, long offset,
xed_decoded_inst_t *xptr);
static bool validate_tail_call_from_jump(char *ins, long offset,
xed_decoded_inst_t *xptr);
/******************************************************************************
* local variables
*****************************************************************************/
static xed_state_t xed_machine_state_x86_64 = { XED_MACHINE_MODE_LONG_64,
XED_ADDRESS_WIDTH_64b,
XED_ADDRESS_WIDTH_64b };
static char *prologue_start = NULL;
static char *set_rbp = NULL;
static char *push_rbp = NULL;
/******************************************************************************
* interface operations
*****************************************************************************/
void
process_range_init()
{
xed_tables_init();
}
#define RELOCATE(u, offset) (((char *) (u)) - (offset))
void
process_range(long offset, void *vstart, void *vend, bool fn_discovery)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_t *xptr = &xedd;
xed_error_enum_t xed_error;
int error_count = 0;
char *ins = (char *) vstart;
char *end = (char *) vend;
vector<void *> fstarts;
entries_in_range(ins + offset, end + offset, fstarts);
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID;
void **fstart = &fstarts[0];
char *guidepost = RELOCATE(*fstart, offset);
while (ins < end) {
if (ins >= guidepost) {
if (ins > guidepost) {
//--------------------------------------------------------------
// we missed a guidepost; disassembly was not properly aligned.
// realign ins to match the guidepost
//--------------------------------------------------------------
#ifdef DEBUG_GUIDEPOST
printf("resetting ins to guidepost %p from %p\n",
guidepost + offset, ins + offset);
#endif
ins = guidepost;
}
//----------------------------------------------------------------
// all is well; our disassembly is properly aligned.
// advance to the next guidepost
//
// NOTE: since the vector of fstarts contains end,
// the fstart pointer will never go past the end of the
// fstarts array.
//----------------------------------------------------------------
fstart++; guidepost = RELOCATE(*fstart, offset);
}
xed_decoded_inst_zero_keep_mode(xptr);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
if (xed_error != XED_ERROR_NONE) {
error_count++; /* note the error */
ins++; /* skip this byte */
continue; /* continue onward ... */
}
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch(xiclass) {
case XED_ICLASS_ADD:
case XED_ICLASS_SUB:
addsub(ins, xptr, xiclass, offset);
break;
case XED_ICLASS_CALL_FAR:
case XED_ICLASS_CALL_NEAR:
/* if (fn_discovery) */ process_call(ins, offset, xptr, vstart, vend);
break;
case XED_ICLASS_JMP:
case XED_ICLASS_JMP_FAR:
if (xed_decoded_inst_noperands(xptr) == 2) {
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
const xed_operand_t *op1 = xed_inst_operand(xi, 1);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
xed_operand_type_enum_t op1_type = xed_operand_type(op1);
if ((xed_operand_name(op0) == XED_OPERAND_MEM0) &&
(xed_operand_name(op1) == XED_OPERAND_REG0) &&
(xed_operand_nonterminal_name(op1) == XED_NONTERMINAL_RIP)) {
// idiom for GOT indexing in PLT
// don't consider the instruction afterward a potential function start
break;
}
if ((xed_operand_name(op0) == XED_OPERAND_REG0) &&
(xed_operand_name(op1) == XED_OPERAND_REG1) &&
(xed_operand_nonterminal_name(op1) == XED_NONTERMINAL_RIP)) {
// idiom for a switch using a jump table:
// don't consider the instruction afterward a potential function start
break;
}
}
bkwd_jump_into_protected_range(ins, offset, xptr);
if (fn_discovery && !is_call_iclass(prev_xiclass)) {
// regarding use of !is_call above: don't infer function start
// if we run into code from C++ that consists of a call followed
// by an unconditional jump
if (validate_tail_call_from_jump(ins, offset, xptr)) {
after_unconditional(ins, offset, xptr);
}
}
break;
case XED_ICLASS_RET_FAR:
case XED_ICLASS_RET_NEAR:
if (fn_discovery) after_unconditional(ins, offset, xptr);
break;
case XED_ICLASS_JB:
case XED_ICLASS_JBE:
case XED_ICLASS_JL:
case XED_ICLASS_JLE:
case XED_ICLASS_JNB:
case XED_ICLASS_JNBE:
case XED_ICLASS_JNL:
case XED_ICLASS_JNLE:
case XED_ICLASS_JNO:
case XED_ICLASS_JNP:
case XED_ICLASS_JNS:
case XED_ICLASS_JNZ:
case XED_ICLASS_JO:
case XED_ICLASS_JP:
case XED_ICLASS_JRCXZ:
case XED_ICLASS_JS:
case XED_ICLASS_JZ:
if (fn_discovery) process_branch(ins, offset , xptr);
break;
case XED_ICLASS_PUSH:
case XED_ICLASS_PUSHFQ:
case XED_ICLASS_PUSHFD:
case XED_ICLASS_PUSHF:
process_push(ins, xptr, offset);
break;
case XED_ICLASS_POP:
case XED_ICLASS_POPF:
case XED_ICLASS_POPFD:
case XED_ICLASS_POPFQ:
process_pop(ins, xptr, offset);
break;
case XED_ICLASS_ENTER:
process_enter(ins, offset);
break;
case XED_ICLASS_MOV:
process_move(ins, xptr, offset);
break;
case XED_ICLASS_LEAVE:
process_leave(ins, offset);
break;
default:
break;
}
prev_xiclass = xiclass;
ins += xed_decoded_inst_get_length(xptr);
}
}
/******************************************************************************
* private operations
*****************************************************************************/
static int
is_padding(int c)
{
return (c == 0x66) || (c == 0x90);
}
//----------------------------------------------------------------------------
// code that is unreachable after a return or an unconditional jump is a
// potential function entry point. try to screen out the cases that don't
// make sense. infer function entry points for the rest.
//----------------------------------------------------------------------------
static void
after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr)
{
ins += xed_decoded_inst_get_length(xptr);
unsigned char *uins = (unsigned char *) ins;
unsigned char *potential_function_addr = uins + offset;
for (; is_padding(*uins); uins++); // skip remaining padding
//--------------------------------------------------------------------
// only infer a function entry before padding bytes if there isn't
// already one after padding bytes
//--------------------------------------------------------------------
if (contains_function_entry(uins + offset) == false) {
if (!invalid_routine_start(uins)) {
add_stripped_function_entry(potential_function_addr);
}
}
}
static void *
get_branch_target(char *ins, xed_decoded_inst_t *xptr,
xed_operand_values_t *vals)
{
int bytes = xed_operand_values_get_branch_displacement_length(vals);
int offset = 0;
switch(bytes) {
case 1:
offset = (signed char) xed_operand_values_get_branch_displacement_byte(vals,0);
break;
case 4:
offset = xed_operand_values_get_branch_displacement_int32(vals);
break;
default:
assert(0);
}
char *end_of_call_inst = ins + xed_decoded_inst_get_length(xptr);
char *target = end_of_call_inst + offset;
return target;
}
static void
process_call(char *ins, long offset, xed_decoded_inst_t *xptr,
void *start, void *end)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
void *vaddr = get_branch_target(ins + offset,xptr,vals);
if (consider_possible_fn_address(vaddr)) {
add_stripped_function_entry(vaddr);
}
}
}
}
static bool
bkwd_jump_into_protected_range(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
void *start, *end;
if (target < relocated_ins) {
start = target;
end = relocated_ins;
if (inside_protected_range(target)) {
add_protected_range(start, end);
return true;
}
}
}
}
return false;
}
static bool
validate_tail_call_from_jump(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
if (target < relocated_ins) {
// backward jump; if this is a tail call, it should fall on a function
// entry already in the function entries table
if (query_function_entry(target)) return true;
} else {
// forward jump; if this is a tail call, it should
xed_decoded_inst_t xedd_tmp;
xed_decoded_inst_t *xptr = &xedd_tmp;
xed_error_enum_t xed_error;
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID;
while (ins < target) {
xed_decoded_inst_zero_keep_mode(xptr);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
if (xed_error != XED_ERROR_NONE) {
ins++; /* skip this byte */
continue; /* continue onward ... */
}
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch(xiclass) {
// unconditional jump
case XED_ICLASS_JMP: case XED_ICLASS_JMP_FAR:
// return
case XED_ICLASS_RET_FAR: case XED_ICLASS_RET_NEAR:
// conditional branch
case XED_ICLASS_JB: case XED_ICLASS_JBE:
case XED_ICLASS_JL: case XED_ICLASS_JLE:
case XED_ICLASS_JNB: case XED_ICLASS_JNBE:
case XED_ICLASS_JNL: case XED_ICLASS_JNLE:
case XED_ICLASS_JNO: case XED_ICLASS_JNP:
case XED_ICLASS_JNS: case XED_ICLASS_JNZ:
case XED_ICLASS_JO: case XED_ICLASS_JP:
case XED_ICLASS_JRCXZ: case XED_ICLASS_JS:
case XED_ICLASS_JZ:
return true;
default:
break;
}
ins += xed_decoded_inst_get_length(xptr);
}
}
}
}
return false;
}
static void
process_branch(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
void *start, *end;
if (target < relocated_ins) {
unsigned char *tloc = (unsigned char *) target - offset;
for (; is_padding(*(tloc-1)); tloc--) {
// extend branch range to before padding
target--;
}
start = target;
end = relocated_ins;
} else {
start = relocated_ins;
//-----------------------------------------------------
// add one to ensure that the branch target is part of
// the "covered" range
//-----------------------------------------------------
end = ((char *) target) + 1;
}
add_protected_range(start, end);
}
}
}
static int
mem_below_rsp_or_rbp(xed_decoded_inst_t *xptr, int oindex)
{
xed_reg_enum_t basereg = xed_decoded_inst_get_base_reg(xptr, oindex);
if (basereg == XED_REG_RBP) {
return 1;
} else if (basereg == XED_REG_RSP) {
int64_t offset =
xed_decoded_inst_get_memory_displacement(xptr, oindex);
if (offset > 0) {
return 1;
}
} else if (basereg == XED_REG_RAX) {
return 1;
}
return 0;
}
static bool
inst_accesses_callers_mem(xed_decoded_inst_t *xptr)
{
// if the instruction accesses memory below the rsp or rbp, this is
// not a valid first instruction for a routine. if this is the first
// instruction in a routine, this must be manipulating values in the
// caller's frame, not its own.
int noperands = xed_decoded_inst_number_of_memory_operands(xptr);
int not_my_mem = 0;
switch (noperands) {
case 2: not_my_mem |= mem_below_rsp_or_rbp(xptr, 1);
case 1: not_my_mem |= mem_below_rsp_or_rbp(xptr, 0);
case 0:
break;
default:
assert(0 && "unexpected number of memory operands");
}
if (not_my_mem) return true;
return false;
}
static bool
from_ax_reg(xed_decoded_inst_t *xptr)
{
int noperands = xed_decoded_inst_noperands(xptr);
if (noperands == 2) {
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op1 = xed_inst_operand(xi, 1);
xed_operand_enum_t op1_name = xed_operand_name(op1);
#if 0
if ((xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOV) ||
(xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOVSXD)) {
#endif
if ((op1_name == XED_OPERAND_REG1) &&
((xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_RAX) ||
(xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_EAX) ||
(xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_AX))) {
return true;
}
#if 0
}
#endif
}
return false;
}
static bool
is_null(unsigned char *ins, int n)
{
unsigned char result = 0;
unsigned char *end = ins + n;
while (ins < end) result |= *ins++;
if (result == 0) return true;
else return false;
}
static bool
invalid_routine_start(unsigned char *ins)
{
xed_decoded_inst_t xdi;
xed_decoded_inst_zero_set_mode(&xdi, &xed_machine_state_x86_64);
xed_error_enum_t xed_error = xed_decode(&xdi, (uint8_t*) ins, 15);
if (xed_error == XED_ERROR_NONE) {
if (is_null(ins, xed_decoded_inst_get_length(&xdi))) return true;
if (inst_accesses_callers_mem(&xdi)) return true;
if (from_ax_reg(&xdi)) return true;
}
return false;
}
void x86_dump_ins(void *ins)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_t *xptr = &xedd;
xed_error_enum_t xed_error;
char inst_buf[1024];
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
xed_format_xed(xptr, inst_buf, sizeof(inst_buf), (uint64_t) ins);
printf("(%p, %d bytes, %s) %s \n" , ins, xed_decoded_inst_get_length(xptr),
xed_iclass_enum_t2str(xed_decoded_inst_get_iclass(xptr)), inst_buf);
}
// #define DEBUG_ADDSUB
static void
addsub(char *ins, xed_decoded_inst_t *xptr, xed_iclass_enum_t iclass, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t* op0 = xed_inst_operand(xi,0);
const xed_operand_t* op1 = xed_inst_operand(xi,1);
xed_operand_enum_t op0_name = xed_operand_name(op0);
static long prologue_offset = 0;
if ((op0_name == XED_OPERAND_REG0) &&
(xed_decoded_inst_get_reg(xptr, op0_name) == XED_REG_RSP)) {
if (xed_operand_name(op1) == XED_OPERAND_IMM0) {
//---------------------------------------------------------------------------
// we are adjusting the stack pointer by a constant offset
//---------------------------------------------------------------------------
int sign = (iclass == XED_ICLASS_ADD) ? 1 : -1;
long immedv = sign * xed_decoded_inst_get_signed_immediate(xptr);
if (immedv < 0) {
prologue_start = ins;
prologue_offset = -immedv;
#ifdef DEBUG_ADDSUB
fprintf(stderr,"prologue %ld\n", immedv);
#endif
} else {
#ifdef DEBUG_ADDSUB
fprintf(stderr,"epilogue %ld\n", immedv);
#endif
if (immedv == prologue_offset) {
// add one to both endpoints
// -- ensure that add/sub in the prologue IS NOT part of the range
// (it may be the first instruction in the function - we don't want
// to prevent it from starting a function)
// -- ensure that add/sub in the epilogue IS part of the range
char *end = ins + 1;
add_protected_range(prologue_start + ins_offset + 1,
ins + ins_offset + 1);
#ifdef DEBUG_ADDSUB
fprintf(stderr,"range [%p, %p] offset %ld\n",
prologue_start + ins_offset, end + ins_offset, immedv);
#endif
}
}
}
}
}
// don't track the push, track the move rsp to rbp or esp to ebp
static void
process_move(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
const xed_operand_t *op1 = xed_inst_operand(xi, 1);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_enum_t op1_name = xed_operand_name(op1);
if ((op0_name == XED_OPERAND_REG0) && (op1_name == XED_OPERAND_REG1)) {
//-------------------------------------------------------------------------
// register-to-register move
//-------------------------------------------------------------------------
xed_reg_enum_t reg0 = xed_decoded_inst_get_reg(xptr, op0_name);
xed_reg_enum_t reg1 = xed_decoded_inst_get_reg(xptr, op1_name);
if (((reg0 == XED_REG_RBP) || (reg0 == XED_REG_EBP)) &&
((reg1 == XED_REG_RSP) || (reg1 == XED_REG_ESP))) {
//=========================================================================
// instruction: initialize BP with value of SP to set up a frame pointer
//=========================================================================
set_rbp = ins;
}
}
}
static void
process_push(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if (op0_name == XED_OPERAND_REG0) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op0_name);
if (regname == XED_REG_RBP) {
push_rbp = ins;
}
}
}
static void
process_pop(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if (op0_name == XED_OPERAND_REG0) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op0_name);
if (regname == XED_REG_RBP) {
add_protected_range(push_rbp + ins_offset + 1, ins + ins_offset + 1);
}
}
}
static void
process_enter(char *ins, long ins_offset)
{
set_rbp = ins;
}
static void
process_leave(char *ins, long ins_offset)
{
add_protected_range(set_rbp + ins_offset + 1, ins + ins_offset + 1);
}
several improvements to the unstripper:
- if instruction following unconditional jump appears to be
an obvious function start (push rsp, or add -,sp)
don't require that the preceeding jump be a valid tail call
- remove check that instruction preceding jump is a not a call.
(this was a hack that is no longer useful and now was found
to do harm)
- rework code checking to see if function start appears to read
rax/eax/ax.
- adjust addsub to consider esp as well as rsp
- let push/pop pairs for things other than rbp create
protected ranges as well.
/******************************************************************************
* include files
*****************************************************************************/
#include <stdio.h>
#include <assert.h>
#include <string>
extern "C" {
#include "xed-interface.h"
};
#include "code-ranges.h"
#include "function-entries.h"
#include "process-ranges.h"
/******************************************************************************
* forward declarations
*****************************************************************************/
static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr,
void *start, void *end);
static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr);
static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr);
static bool invalid_routine_start(unsigned char *ins);
static void addsub(char *ins, xed_decoded_inst_t *xptr, xed_iclass_enum_t iclass,
long ins_offset);
static void process_move(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_push(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_pop(char *ins, xed_decoded_inst_t *xptr, long ins_offset);
static void process_enter(char *ins, long ins_offset);
static void process_leave(char *ins, long ins_offset);
static bool bkwd_jump_into_protected_range(char *ins, long offset,
xed_decoded_inst_t *xptr);
static bool validate_tail_call_from_jump(char *ins, long offset,
xed_decoded_inst_t *xptr);
static bool nextins_looks_like_fn_start(char *ins, long offset,
xed_decoded_inst_t *xptrin);
/******************************************************************************
* local variables
*****************************************************************************/
static xed_state_t xed_machine_state_x86_64 = { XED_MACHINE_MODE_LONG_64,
XED_ADDRESS_WIDTH_64b,
XED_ADDRESS_WIDTH_64b };
static char *prologue_start = NULL;
static char *set_rbp = NULL;
static char *push_rbp = NULL;
static char *push_other = NULL;
/******************************************************************************
* interface operations
*****************************************************************************/
void
process_range_init()
{
xed_tables_init();
}
#define RELOCATE(u, offset) (((char *) (u)) - (offset))
void
process_range(long offset, void *vstart, void *vend, bool fn_discovery)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_t *xptr = &xedd;
xed_error_enum_t xed_error;
int error_count = 0;
char *ins = (char *) vstart;
char *end = (char *) vend;
vector<void *> fstarts;
entries_in_range(ins + offset, end + offset, fstarts);
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID;
void **fstart = &fstarts[0];
char *guidepost = RELOCATE(*fstart, offset);
while (ins < end) {
if (ins >= guidepost) {
if (ins > guidepost) {
//--------------------------------------------------------------
// we missed a guidepost; disassembly was not properly aligned.
// realign ins to match the guidepost
//--------------------------------------------------------------
#ifdef DEBUG_GUIDEPOST
printf("resetting ins to guidepost %p from %p\n",
guidepost + offset, ins + offset);
#endif
ins = guidepost;
}
//----------------------------------------------------------------
// all is well; our disassembly is properly aligned.
// advance to the next guidepost
//
// NOTE: since the vector of fstarts contains end,
// the fstart pointer will never go past the end of the
// fstarts array.
//----------------------------------------------------------------
fstart++; guidepost = RELOCATE(*fstart, offset);
}
xed_decoded_inst_zero_keep_mode(xptr);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
if (xed_error != XED_ERROR_NONE) {
error_count++; /* note the error */
ins++; /* skip this byte */
continue; /* continue onward ... */
}
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch(xiclass) {
case XED_ICLASS_ADD:
case XED_ICLASS_SUB:
addsub(ins, xptr, xiclass, offset);
break;
case XED_ICLASS_CALL_FAR:
case XED_ICLASS_CALL_NEAR:
/* if (fn_discovery) */ process_call(ins, offset, xptr, vstart, vend);
break;
case XED_ICLASS_JMP:
case XED_ICLASS_JMP_FAR:
if (xed_decoded_inst_noperands(xptr) == 2) {
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
const xed_operand_t *op1 = xed_inst_operand(xi, 1);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
xed_operand_type_enum_t op1_type = xed_operand_type(op1);
if ((xed_operand_name(op0) == XED_OPERAND_MEM0) &&
(xed_operand_name(op1) == XED_OPERAND_REG0) &&
(xed_operand_nonterminal_name(op1) == XED_NONTERMINAL_RIP)) {
// idiom for GOT indexing in PLT
// don't consider the instruction afterward a potential function start
break;
}
if ((xed_operand_name(op0) == XED_OPERAND_REG0) &&
(xed_operand_name(op1) == XED_OPERAND_REG1) &&
(xed_operand_nonterminal_name(op1) == XED_NONTERMINAL_RIP)) {
// idiom for a switch using a jump table:
// don't consider the instruction afterward a potential function start
break;
}
}
bkwd_jump_into_protected_range(ins, offset, xptr);
if (fn_discovery &&
(validate_tail_call_from_jump(ins, offset, xptr) ||
nextins_looks_like_fn_start(ins, offset, xptr))) {
after_unconditional(ins, offset, xptr);
}
break;
case XED_ICLASS_RET_FAR:
case XED_ICLASS_RET_NEAR:
if (fn_discovery) after_unconditional(ins, offset, xptr);
break;
case XED_ICLASS_JB:
case XED_ICLASS_JBE:
case XED_ICLASS_JL:
case XED_ICLASS_JLE:
case XED_ICLASS_JNB:
case XED_ICLASS_JNBE:
case XED_ICLASS_JNL:
case XED_ICLASS_JNLE:
case XED_ICLASS_JNO:
case XED_ICLASS_JNP:
case XED_ICLASS_JNS:
case XED_ICLASS_JNZ:
case XED_ICLASS_JO:
case XED_ICLASS_JP:
case XED_ICLASS_JRCXZ:
case XED_ICLASS_JS:
case XED_ICLASS_JZ:
if (fn_discovery) process_branch(ins, offset , xptr);
break;
case XED_ICLASS_PUSH:
case XED_ICLASS_PUSHFQ:
case XED_ICLASS_PUSHFD:
case XED_ICLASS_PUSHF:
process_push(ins, xptr, offset);
break;
case XED_ICLASS_POP:
case XED_ICLASS_POPF:
case XED_ICLASS_POPFD:
case XED_ICLASS_POPFQ:
process_pop(ins, xptr, offset);
break;
case XED_ICLASS_ENTER:
process_enter(ins, offset);
break;
case XED_ICLASS_MOV:
process_move(ins, xptr, offset);
break;
case XED_ICLASS_LEAVE:
process_leave(ins, offset);
break;
default:
break;
}
prev_xiclass = xiclass;
ins += xed_decoded_inst_get_length(xptr);
}
}
/******************************************************************************
* private operations
*****************************************************************************/
static int
is_padding(int c)
{
return (c == 0x66) || (c == 0x90);
}
//----------------------------------------------------------------------------
// code that is unreachable after a return or an unconditional jump is a
// potential function entry point. try to screen out the cases that don't
// make sense. infer function entry points for the rest.
//----------------------------------------------------------------------------
static void
after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr)
{
ins += xed_decoded_inst_get_length(xptr);
unsigned char *uins = (unsigned char *) ins;
unsigned char *potential_function_addr = uins + offset;
for (; is_padding(*uins); uins++); // skip remaining padding
//--------------------------------------------------------------------
// only infer a function entry before padding bytes if there isn't
// already one after padding bytes
//--------------------------------------------------------------------
if (contains_function_entry(uins + offset) == false) {
if (!invalid_routine_start(uins)) {
add_stripped_function_entry(potential_function_addr);
}
}
}
static void *
get_branch_target(char *ins, xed_decoded_inst_t *xptr,
xed_operand_values_t *vals)
{
int bytes = xed_operand_values_get_branch_displacement_length(vals);
int offset = 0;
switch(bytes) {
case 1:
offset = (signed char) xed_operand_values_get_branch_displacement_byte(vals,0);
break;
case 4:
offset = xed_operand_values_get_branch_displacement_int32(vals);
break;
default:
assert(0);
}
char *end_of_call_inst = ins + xed_decoded_inst_get_length(xptr);
char *target = end_of_call_inst + offset;
return target;
}
static void
process_call(char *ins, long offset, xed_decoded_inst_t *xptr,
void *start, void *end)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
void *vaddr = get_branch_target(ins + offset,xptr,vals);
if (consider_possible_fn_address(vaddr)) {
add_stripped_function_entry(vaddr);
}
}
}
}
static bool
bkwd_jump_into_protected_range(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
void *start, *end;
if (target < relocated_ins) {
start = target;
end = relocated_ins;
if (inside_protected_range(target)) {
add_protected_range(start, end);
return true;
}
}
}
}
return false;
}
static bool
validate_tail_call_from_jump(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
if (target < relocated_ins) {
// backward jump; if this is a tail call, it should fall on a function
// entry already in the function entries table
if (query_function_entry(target)) return true;
} else {
// forward jump; if this is a tail call, it should
xed_decoded_inst_t xedd_tmp;
xed_decoded_inst_t *xptr = &xedd_tmp;
xed_error_enum_t xed_error;
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID;
while (ins < target) {
xed_decoded_inst_zero_keep_mode(xptr);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
if (xed_error != XED_ERROR_NONE) {
ins++; /* skip this byte */
continue; /* continue onward ... */
}
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch(xiclass) {
// unconditional jump
case XED_ICLASS_JMP: case XED_ICLASS_JMP_FAR:
// return
case XED_ICLASS_RET_FAR: case XED_ICLASS_RET_NEAR:
// conditional branch
case XED_ICLASS_JB: case XED_ICLASS_JBE:
case XED_ICLASS_JL: case XED_ICLASS_JLE:
case XED_ICLASS_JNB: case XED_ICLASS_JNBE:
case XED_ICLASS_JNL: case XED_ICLASS_JNLE:
case XED_ICLASS_JNO: case XED_ICLASS_JNP:
case XED_ICLASS_JNS: case XED_ICLASS_JNZ:
case XED_ICLASS_JO: case XED_ICLASS_JP:
case XED_ICLASS_JRCXZ: case XED_ICLASS_JS:
case XED_ICLASS_JZ:
return true;
default:
break;
}
ins += xed_decoded_inst_get_length(xptr);
}
}
}
}
return false;
}
static bool
nextins_looks_like_fn_start(char *ins, long offset, xed_decoded_inst_t *xptrin)
{
xed_decoded_inst_t xedd_tmp;
xed_decoded_inst_t *xptr = &xedd_tmp;
xed_error_enum_t xed_error;
ins = ins + xed_decoded_inst_get_length(xptrin);
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
for(;;) {
xed_decoded_inst_zero_keep_mode(xptr);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
if (xed_error != XED_ERROR_NONE) return false;
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch(xiclass) {
case XED_ICLASS_NOP: case XED_ICLASS_NOP2: case XED_ICLASS_NOP3:
case XED_ICLASS_NOP4: case XED_ICLASS_NOP5: case XED_ICLASS_NOP6:
case XED_ICLASS_NOP7: case XED_ICLASS_NOP8: case XED_ICLASS_NOP9:
// nop: move to the next instruction
ins = ins + xed_decoded_inst_get_length(xptr);
break;
case XED_ICLASS_PUSH:
case XED_ICLASS_PUSHFQ:
case XED_ICLASS_PUSHFD:
case XED_ICLASS_PUSHF:
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if (op0_name == XED_OPERAND_REG0) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op0_name);
if (regname == XED_REG_RBP) {
return true;
}
}
}
return false;
case XED_ICLASS_ADD:
case XED_ICLASS_SUB:
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t* op0 = xed_inst_operand(xi,0);
const xed_operand_t* op1 = xed_inst_operand(xi,1);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if ((op0_name == XED_OPERAND_REG0) &&
(xed_decoded_inst_get_reg(xptr, op0_name) == XED_REG_RSP)) {
if (xed_operand_name(op1) == XED_OPERAND_IMM0) {
//---------------------------------------------------------------------------
// we are adjusting the stack pointer by a constant offset
//---------------------------------------------------------------------------
int sign = (xiclass == XED_ICLASS_ADD) ? 1 : -1;
long immedv = sign * xed_decoded_inst_get_signed_immediate(xptr);
if (immedv < 0) return true;
}
}
}
return false;
default:
// not a nop, or what is expected for the start of a routine.
return false;
break;
}
}
return false;
}
static void
process_branch(char *ins, long offset, xed_decoded_inst_t *xptr)
{
char *relocated_ins = ins + offset;
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_type_enum_t op0_type = xed_operand_type(op0);
if (op0_name == XED_OPERAND_RELBR &&
op0_type == XED_OPERAND_TYPE_IMM_CONST) {
xed_operand_values_t *vals = xed_decoded_inst_operands(xptr);
if (xed_operand_values_has_branch_displacement(vals)) {
char *target = (char *) get_branch_target(relocated_ins, xptr, vals);
void *start, *end;
if (target < relocated_ins) {
unsigned char *tloc = (unsigned char *) target - offset;
for (; is_padding(*(tloc-1)); tloc--) {
// extend branch range to before padding
target--;
}
start = target;
end = relocated_ins;
} else {
start = relocated_ins;
//-----------------------------------------------------
// add one to ensure that the branch target is part of
// the "covered" range
//-----------------------------------------------------
end = ((char *) target) + 1;
}
add_protected_range(start, end);
}
}
}
static int
mem_below_rsp_or_rbp(xed_decoded_inst_t *xptr, int oindex)
{
xed_reg_enum_t basereg = xed_decoded_inst_get_base_reg(xptr, oindex);
if (basereg == XED_REG_RBP) {
return 1;
} else if (basereg == XED_REG_RSP) {
int64_t offset =
xed_decoded_inst_get_memory_displacement(xptr, oindex);
if (offset > 0) {
return 1;
}
} else if (basereg == XED_REG_RAX) {
return 1;
}
return 0;
}
static bool
inst_accesses_callers_mem(xed_decoded_inst_t *xptr)
{
// if the instruction accesses memory below the rsp or rbp, this is
// not a valid first instruction for a routine. if this is the first
// instruction in a routine, this must be manipulating values in the
// caller's frame, not its own.
int noperands = xed_decoded_inst_number_of_memory_operands(xptr);
int not_my_mem = 0;
switch (noperands) {
case 2: not_my_mem |= mem_below_rsp_or_rbp(xptr, 1);
case 1: not_my_mem |= mem_below_rsp_or_rbp(xptr, 0);
case 0:
break;
default:
assert(0 && "unexpected number of memory operands");
}
if (not_my_mem) return true;
return false;
}
#if 0
static bool
from_ax_reg(xed_decoded_inst_t *xptr)
{
static xed_operand_enum_t regnames[] = { XED_OPERAND_REG0, XED_OPERAND_REG1 };
int noperands = xed_decoded_inst_noperands(xptr);
int opid;
if (noperands == 2) {
opid = 1;
} else {
xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr);
switch (xiclass) {
case XED_ICLASS_PUSH:
case XED_ICLASS_PUSHFQ:
case XED_ICLASS_PUSHFD:
case XED_ICLASS_PUSHF:
opid = 0;
break;
default:
return false;
}
}
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op = xed_inst_operand(xi, opid);
xed_operand_enum_t op_name = xed_operand_name(op);
if ((op_name == regnames[opid]) &&
((xed_decoded_inst_get_reg(xptr, op_name) == XED_REG_RAX) ||
(xed_decoded_inst_get_reg(xptr, op_name) == XED_REG_EAX) ||
(xed_decoded_inst_get_reg(xptr, op_name) == XED_REG_AX))) {
return true;
}
return false;
}
#endif
static bool
from_ax_reg(xed_decoded_inst_t *xptr)
{
static xed_operand_enum_t regops[] = { XED_OPERAND_REG0, XED_OPERAND_REG1 };
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
int noperands = xed_decoded_inst_noperands(xptr);
if (noperands > 2) noperands = 2; // we don't care about more than two operands
for (int opid = 0; opid < noperands; opid++) {
const xed_operand_t *op = xed_inst_operand(xi, opid);
xed_operand_enum_t op_name = xed_operand_name(op);
if (op_name == regops[opid]) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op_name);
if ((regname == XED_REG_RAX) || (regname == XED_REG_EAX) || (regname == XED_REG_AX)) {
// operand may perform a read
switch(xed_operand_rw(op)) {
case XED_OPERAND_ACTION_R: // read
// case XED_OPERAND_ACTION_RW: // read and written: skip this case - xor %eax, %eax is OK
case XED_OPERAND_ACTION_RCW: // read and conditionlly written
case XED_OPERAND_ACTION_CR: // conditionally read
case XED_OPERAND_ACTION_CRW: // conditionlly read, always written
return true;
default:
return false;
}
}
}
}
return false;
}
static bool
is_null(unsigned char *ins, int n)
{
unsigned char result = 0;
unsigned char *end = ins + n;
while (ins < end) result |= *ins++;
if (result == 0) return true;
else return false;
}
static bool
invalid_routine_start(unsigned char *ins)
{
xed_decoded_inst_t xdi;
xed_decoded_inst_zero_set_mode(&xdi, &xed_machine_state_x86_64);
xed_error_enum_t xed_error = xed_decode(&xdi, (uint8_t*) ins, 15);
if (xed_error == XED_ERROR_NONE) {
if (is_null(ins, xed_decoded_inst_get_length(&xdi))) return true;
if (inst_accesses_callers_mem(&xdi)) return true;
if (from_ax_reg(&xdi)) return true;
}
return false;
}
void x86_dump_ins(void *ins)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_t *xptr = &xedd;
xed_error_enum_t xed_error;
char inst_buf[1024];
xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64);
xed_error = xed_decode(xptr, (uint8_t*) ins, 15);
xed_format_xed(xptr, inst_buf, sizeof(inst_buf), (uint64_t) ins);
printf("(%p, %d bytes, %s) %s \n" , ins, xed_decoded_inst_get_length(xptr),
xed_iclass_enum_t2str(xed_decoded_inst_get_iclass(xptr)), inst_buf);
}
// #define DEBUG_ADDSUB
static void
addsub(char *ins, xed_decoded_inst_t *xptr, xed_iclass_enum_t iclass, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t* op0 = xed_inst_operand(xi,0);
const xed_operand_t* op1 = xed_inst_operand(xi,1);
xed_operand_enum_t op0_name = xed_operand_name(op0);
static long prologue_offset = 0;
if ((op0_name == XED_OPERAND_REG0) &&
((xed_decoded_inst_get_reg(xptr, op0_name) == XED_REG_RSP) ||
(xed_decoded_inst_get_reg(xptr, op0_name) == XED_REG_ESP) ||
(xed_decoded_inst_get_reg(xptr, op0_name) == XED_REG_SP))) {
if (xed_operand_name(op1) == XED_OPERAND_IMM0) {
//---------------------------------------------------------------------------
// we are adjusting the stack pointer by a constant offset
//---------------------------------------------------------------------------
int sign = (iclass == XED_ICLASS_ADD) ? 1 : -1;
long immedv = sign * xed_decoded_inst_get_signed_immediate(xptr);
if (immedv < 0) {
prologue_start = ins;
prologue_offset = -immedv;
#ifdef DEBUG_ADDSUB
fprintf(stderr,"prologue %ld\n", immedv);
#endif
} else {
#ifdef DEBUG_ADDSUB
fprintf(stderr,"epilogue %ld\n", immedv);
#endif
if (immedv == prologue_offset) {
// add one to both endpoints
// -- ensure that add/sub in the prologue IS NOT part of the range
// (it may be the first instruction in the function - we don't want
// to prevent it from starting a function)
// -- ensure that add/sub in the epilogue IS part of the range
char *end = ins + 1;
add_protected_range(prologue_start + ins_offset + 1,
ins + ins_offset + 1);
#ifdef DEBUG_ADDSUB
fprintf(stderr,"range [%p, %p] offset %ld\n",
prologue_start + ins_offset, end + ins_offset, immedv);
#endif
}
}
}
}
}
// don't track the push, track the move rsp to rbp or esp to ebp
static void
process_move(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
const xed_operand_t *op1 = xed_inst_operand(xi, 1);
xed_operand_enum_t op0_name = xed_operand_name(op0);
xed_operand_enum_t op1_name = xed_operand_name(op1);
if ((op0_name == XED_OPERAND_REG0) && (op1_name == XED_OPERAND_REG1)) {
//-------------------------------------------------------------------------
// register-to-register move
//-------------------------------------------------------------------------
xed_reg_enum_t reg0 = xed_decoded_inst_get_reg(xptr, op0_name);
xed_reg_enum_t reg1 = xed_decoded_inst_get_reg(xptr, op1_name);
if (((reg0 == XED_REG_RBP) || (reg0 == XED_REG_EBP)) &&
((reg1 == XED_REG_RSP) || (reg1 == XED_REG_ESP))) {
//=========================================================================
// instruction: initialize BP with value of SP to set up a frame pointer
//=========================================================================
set_rbp = ins;
}
}
}
static void
process_push(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if (op0_name == XED_OPERAND_REG0) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op0_name);
if (regname == XED_REG_RBP) {
push_rbp = ins;
} else {
push_other = ins;
}
}
}
static void
process_pop(char *ins, xed_decoded_inst_t *xptr, long ins_offset)
{
const xed_inst_t *xi = xed_decoded_inst_inst(xptr);
const xed_operand_t *op0 = xed_inst_operand(xi, 0);
xed_operand_enum_t op0_name = xed_operand_name(op0);
if (op0_name == XED_OPERAND_REG0) {
xed_reg_enum_t regname = xed_decoded_inst_get_reg(xptr, op0_name);
if (regname == XED_REG_RBP) {
add_protected_range(push_rbp + ins_offset + 1, ins + ins_offset + 1);
} else {
if (push_other) add_protected_range(push_other + ins_offset + 1, ins + ins_offset + 1);
}
}
}
static void
process_enter(char *ins, long ins_offset)
{
set_rbp = ins;
}
static void
process_leave(char *ins, long ins_offset)
{
add_protected_range(set_rbp + ins_offset + 1, ins + ins_offset + 1);
}
|
#include "QsLog.h"
#include "configuration.h"
#include "ParamCompareDialog.h"
#include "ui_ParamCompareDialog.h"
#include <QMessageBox>
#include <QTableWidget>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
#include <QCheckBox>
#include <QPushButton>
#include <QTimer>
#define PCD_COLUMN_PARAM_NAME 0
#define PCD_COLUMN_VALUE 1
#define PCD_COLUMN_NEW_VALUE 2
#define PCD_COLUMN_CHECKBOX 3
ParamCompareDialog::ParamCompareDialog(QMap<QString, UASParameter* >& paramaterList,
const QString& filename, QWidget *parent) :
QDialog(parent),
ui(new Ui::ParamCompareDialog),
m_currentList(¶materList),
m_newList(new QMap<QString, UASParameter*>()),
m_fileToCompare(filename)
{
ui->setupUi(this);
QStringList headerList;
headerList << tr("Parameter") << tr("Value") << tr("New Value") << tr("Use");
QTableWidget* table = ui->compareTableWidget;
table->setColumnCount(headerList.count());
table->setHorizontalHeaderLabels(headerList);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setAlternatingRowColors(true);
table->setColumnWidth(PCD_COLUMN_CHECKBOX, 40);
initConnections();
if(filename.count()>0){
QTimer::singleShot(200, this, SLOT(loadParameterWithFile()));
}
}
ParamCompareDialog::~ParamCompareDialog()
{
delete ui;
}
void ParamCompareDialog::initConnections()
{
connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(loadParameterFile()));
connect(ui->continueButton, SIGNAL(clicked()), this, SLOT(saveNewParameters()));
connect(ui->checkAllBox, SIGNAL(clicked()), this, SLOT(checkAll()));
}
void ParamCompareDialog::setAcceptButtonLabel(const QString &label)
{
if (ui) ui->continueButton->setText(label);
}
void ParamCompareDialog::loadParameterFile()
{
ui->compareTableWidget->setRowCount(0);
QDir parameterDir = QDir(QGC::parameterDirectory());
if(!parameterDir.exists())
parameterDir.mkdir(parameterDir.path());
QString filename = QFileDialog::getOpenFileName(this,tr("Open File To Compare"),
QGC::parameterDirectory(), "*.param");
QApplication::processEvents(); // Helps clear dialog from screen
if(filename.length() == 0) {
return;
}
QApplication::processEvents(); // Helps clear dialog from screen
loadParameterFile(filename);
}
void ParamCompareDialog::loadParameterWithFile()
{
ui->loadButton->hide();
loadParameterFile(m_fileToCompare);
}
void ParamCompareDialog::loadParameterFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::information(this,"Error",tr("Unable to open the file.").arg(filename));
return;
}
QString filestring = file.readAll();
file.close();
populateParamListFromString(filestring, m_newList, this);
compareLists();
}
void ParamCompareDialog::populateParamListFromString(QString paramString, QMap<QString, UASParameter*>* list,
QWidget* widget = NULL)
{
QStringList paramSplit = paramString.split("\n");
bool summaryComplete = false;
bool summaryShown = false;
QString summaryText;
foreach (QString paramLine, paramSplit) {
if (!paramLine.startsWith("#")) {
summaryComplete = true;
QStringList lineSplit = paramLine.split(",");
if (lineSplit.size() == 2)
{
bool ok;
QLOG_DEBUG() << "load param: " << lineSplit[0] << "=" << lineSplit[1];
UASParameter* param = new UASParameter();
param->setName(lineSplit[0]);
double value = lineSplit[1].toFloat(&ok);
if (ok){
param->setValue(QVariant(value));
} else {
QLOG_ERROR() << "Conversion Failure";
param->setValue(QVariant("NaN"));
}
list->insert(param->name(), param);
}
} else {
QLOG_DEBUG() << "Comment: " << paramLine;
if (!summaryShown && !summaryComplete){
// removes the '#' and any whites space before or after
summaryText.append(paramLine.remove(0,1).trimmed() + "\n");
}
}
if (!summaryShown && summaryComplete){
QLOG_DEBUG() << "Show Summary: " << summaryText;
if (summaryText.count()>0){
QMessageBox::information(widget,tr("Param File Summary"),summaryText,QMessageBox::Ok);
}
summaryShown = true;
}
}
}
void ParamCompareDialog::compareLists()
{
QList<QString> keys = m_newList->keys(); // This needs to be an amalgamated list of all keys
ui->compareTableWidget->setSortingEnabled(false);
for(int count = 0; count < keys.count(); ++count){
UASParameter* currentParam = m_currentList->value(keys[count]);
if (currentParam != NULL){
UASParameter* newParam = m_newList->value(keys[count]);
if (currentParam->value() != newParam->value() ){
QLOG_DEBUG() << "Difference : " << currentParam->name()
<< " current: " << currentParam->value() << " new:" << newParam->value();
int rowCount = ui->compareTableWidget->rowCount();
ui->compareTableWidget->setRowCount(ui->compareTableWidget->rowCount()+1);
QTableWidgetItem* widgetItemParam = new QTableWidgetItem(keys[count]);
widgetItemParam->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled );
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_PARAM_NAME, widgetItemParam);
QTableWidgetItem* widgetItemValue = new QTableWidgetItem();
widgetItemValue->setData(Qt::DisplayRole, currentParam->value());
widgetItemValue->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_VALUE, widgetItemValue);
QTableWidgetItem* widgetItemNewValue = new QTableWidgetItem();
widgetItemNewValue->setData(Qt::DisplayRole, newParam->value());
widgetItemNewValue->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsEditable);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_NEW_VALUE, widgetItemNewValue);
QTableWidgetItem* widgetItemCheckbox= new QTableWidgetItem();
widgetItemCheckbox->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
widgetItemCheckbox->setCheckState(Qt::Checked);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_CHECKBOX, widgetItemCheckbox);
}
}
}
}
void ParamCompareDialog::saveNewParameters()
{
QLOG_DEBUG() << " Save selected Parameters";
QTableWidget* table = ui->compareTableWidget;
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
// Get hold of the UASParameter
QTableWidgetItem* paramName = table->item(rowCount, PCD_COLUMN_PARAM_NAME);
QTableWidgetItem* paramCheck= table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (paramName && (paramCheck->checkState() == Qt::Checked)){
UASParameter* param = m_currentList->value(paramName->text());
// then update it's value in the current list
// [TODO] this would be an action of the Param Manager
param->setValue(table->item(rowCount, PCD_COLUMN_NEW_VALUE)->data(Qt::DisplayRole));
QLOG_DEBUG() << "Applied to m_currentList:" << param << " = "
<< table->item(rowCount, PCD_COLUMN_NEW_VALUE)->data(Qt::DisplayRole);
}
}
accept(); // dismiss the dialog
}
void ParamCompareDialog::checkAll()
{
QLOG_DEBUG() << " check uncheck all parameters";
QTableWidget* table = ui->compareTableWidget;
if(ui->checkAllBox->isChecked()){
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
QTableWidgetItem* item = table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (item) item->setCheckState(Qt::Checked);
}
} else {
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
QTableWidgetItem* item = table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (item) item->setCheckState(Qt::Unchecked);
}
}
}
Fixes #239: Missed file for commit f8eab2987c
(oops friday afternoon!)
#include "QsLog.h"
#include "configuration.h"
#include "ParamCompareDialog.h"
#include "ui_ParamCompareDialog.h"
#include <QMessageBox>
#include <QTableWidget>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
#include <QCheckBox>
#include <QPushButton>
#include <QTimer>
#define PCD_COLUMN_PARAM_NAME 0
#define PCD_COLUMN_VALUE 1
#define PCD_COLUMN_NEW_VALUE 2
#define PCD_COLUMN_CHECKBOX 3
ParamCompareDialog::ParamCompareDialog(QMap<QString, UASParameter* >& paramaterList,
const QString& filename, QWidget *parent) :
QDialog(parent),
ui(new Ui::ParamCompareDialog),
m_currentList(¶materList),
m_newList(new QMap<QString, UASParameter*>()),
m_fileToCompare(filename)
{
ui->setupUi(this);
QStringList headerList;
headerList << tr("Parameter") << tr("Value") << tr("New Value") << tr("Use");
QTableWidget* table = ui->compareTableWidget;
table->setColumnCount(headerList.count());
table->setHorizontalHeaderLabels(headerList);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setAlternatingRowColors(true);
table->setColumnWidth(PCD_COLUMN_CHECKBOX, 40);
initConnections();
if(filename.count()>0){
QTimer::singleShot(200, this, SLOT(loadParameterWithFile()));
}
}
ParamCompareDialog::~ParamCompareDialog()
{
delete ui;
}
void ParamCompareDialog::initConnections()
{
connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(loadParameterFile()));
connect(ui->continueButton, SIGNAL(clicked()), this, SLOT(saveNewParameters()));
connect(ui->checkAllBox, SIGNAL(clicked()), this, SLOT(checkAll()));
}
void ParamCompareDialog::setAcceptButtonLabel(const QString &label)
{
if (ui) ui->continueButton->setText(label);
}
void ParamCompareDialog::loadParameterFile()
{
ui->compareTableWidget->setRowCount(0);
QDir parameterDir = QDir(QGC::parameterDirectory());
if(!parameterDir.exists())
parameterDir.mkdir(parameterDir.path());
QString filename = QFileDialog::getOpenFileName(this,tr("Open File To Compare"),
QGC::parameterDirectory(), "*.param");
QApplication::processEvents(); // Helps clear dialog from screen
if(filename.length() == 0) {
return;
}
QApplication::processEvents(); // Helps clear dialog from screen
loadParameterFile(filename);
}
void ParamCompareDialog::loadParameterWithFile()
{
ui->loadButton->hide();
loadParameterFile(m_fileToCompare);
}
void ParamCompareDialog::loadParameterFile(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::information(this,"Error",tr("Unable to open the file.").arg(filename));
return;
}
QString filestring = file.readAll();
file.close();
populateParamListFromString(filestring, m_newList, this);
compareLists();
}
void ParamCompareDialog::populateParamListFromString(QString paramString, QMap<QString, UASParameter*>* list,
QWidget* widget = NULL)
{
QStringList paramSplit = paramString.split("\n");
bool summaryComplete = false;
bool summaryShown = false;
QString summaryText;
foreach (QString paramLine, paramSplit) {
if (!paramLine.startsWith("#")) {
summaryComplete = true;
QStringList lineSplit = paramLine.split(",");
if (lineSplit.size() == 2)
{
bool ok;
QLOG_DEBUG() << "load param: " << lineSplit[0] << "=" << lineSplit[1];
UASParameter* param = new UASParameter();
param->setName(lineSplit[0]);
double value = lineSplit[1].toFloat(&ok);
if (ok){
param->setValue(QVariant(value));
} else {
QLOG_ERROR() << "Conversion Failure";
param->setValue(QVariant("NaN"));
}
list->insert(param->name(), param);
}
} else {
QLOG_DEBUG() << "Comment: " << paramLine;
if (!summaryShown && !summaryComplete){
// removes the '#' and any whites space before or after
summaryText.append(paramLine.remove(0,1).trimmed() + "\n");
}
}
if (!summaryShown && summaryComplete){
QLOG_DEBUG() << "Show Summary: " << summaryText;
if (summaryText.count()>0){
QMessageBox::information(widget,tr("Param File Summary"),summaryText,QMessageBox::Ok);
}
summaryShown = true;
}
}
}
void ParamCompareDialog::compareLists()
{
QList<QString> keys = m_newList->keys(); // This needs to be an amalgamated list of all keys
ui->compareTableWidget->setSortingEnabled(false);
for(int count = 0; count < keys.count(); ++count){
UASParameter* currentParam = m_currentList->value(keys[count]);
if (currentParam != NULL){
UASParameter* newParam = m_newList->value(keys[count]);
if (currentParam->value().toDouble() != newParam->value().toDouble() ){
QLOG_DEBUG() << "Difference : " << currentParam->name()
<< " current: " << currentParam->value() << " new:" << newParam->value();
int rowCount = ui->compareTableWidget->rowCount();
ui->compareTableWidget->setRowCount(ui->compareTableWidget->rowCount()+1);
QTableWidgetItem* widgetItemParam = new QTableWidgetItem(keys[count]);
widgetItemParam->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled );
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_PARAM_NAME, widgetItemParam);
QTableWidgetItem* widgetItemValue = new QTableWidgetItem();
widgetItemValue->setData(Qt::DisplayRole, currentParam->value());
widgetItemValue->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_VALUE, widgetItemValue);
QTableWidgetItem* widgetItemNewValue = new QTableWidgetItem();
widgetItemNewValue->setData(Qt::DisplayRole, newParam->value());
widgetItemNewValue->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsEditable);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_NEW_VALUE, widgetItemNewValue);
QTableWidgetItem* widgetItemCheckbox= new QTableWidgetItem();
widgetItemCheckbox->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
widgetItemCheckbox->setCheckState(Qt::Checked);
ui->compareTableWidget->setItem(rowCount, PCD_COLUMN_CHECKBOX, widgetItemCheckbox);
}
}
}
}
void ParamCompareDialog::saveNewParameters()
{
QLOG_DEBUG() << " Save selected Parameters";
QTableWidget* table = ui->compareTableWidget;
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
// Get hold of the UASParameter
QTableWidgetItem* paramName = table->item(rowCount, PCD_COLUMN_PARAM_NAME);
QTableWidgetItem* paramCheck= table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (paramName && (paramCheck->checkState() == Qt::Checked)){
UASParameter* param = m_currentList->value(paramName->text());
// then update it's value in the current list
// [TODO] this would be an action of the Param Manager
param->setValue(table->item(rowCount, PCD_COLUMN_NEW_VALUE)->data(Qt::DisplayRole));
QLOG_DEBUG() << "Applied to m_currentList:" << param << " = "
<< table->item(rowCount, PCD_COLUMN_NEW_VALUE)->data(Qt::DisplayRole);
}
}
accept(); // dismiss the dialog
}
void ParamCompareDialog::checkAll()
{
QLOG_DEBUG() << " check uncheck all parameters";
QTableWidget* table = ui->compareTableWidget;
if(ui->checkAllBox->isChecked()){
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
QTableWidgetItem* item = table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (item) item->setCheckState(Qt::Checked);
}
} else {
for(int rowCount = 0; rowCount < table->rowCount(); ++rowCount){
QTableWidgetItem* item = table->item(rowCount, PCD_COLUMN_CHECKBOX);
if (item) item->setCheckState(Qt::Unchecked);
}
}
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// task for analysis of V0s (K0S, (anti-)Lambda) in charged jets
// Author: Vit Kucera (vit.kucera@cern.ch)
#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TH2D.h"
#include "THnSparse.h"
#include "TCanvas.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include <TDatabasePDG.h>
#include <TPDGCode.h>
#include "AliPIDResponse.h"
#include "AliInputEventHandler.h"
#include "AliAODMCHeader.h"
#include "AliAODMCParticle.h"
#include "TClonesArray.h"
//#include "AliEventInfoObject.cxx"
//#include "AliV0Object.cxx"
//#include "AliJetObject.cxx"
#include "TRandom3.h"
#include "AliAnalysisTaskV0sInJets.h"
ClassImp(AliAnalysisTaskV0sInJets)
// upper edges of centrality bins
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10, 30, 50, 80}; // Alice Zimmermann
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10, 20, 40, 60, 80}; // Vit Kucera, initial binning
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {5, 10, 20, 40, 60, 80}; // Iouri Belikov, LF analysis
const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10}; // only central
// axis: pT of V0
const Double_t AliAnalysisTaskV0sInJets::fgkdBinsPtV0[2] = {0, 12};
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtV0 = sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtV0)/sizeof((AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[0])-1;
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtV0Init = int(((AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[AliAnalysisTaskV0sInJets::fgkiNBinsPtV0]-(AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[0])/0.1); // bin width 0.1 GeV/c
// axis: pT of jets
const Double_t AliAnalysisTaskV0sInJets::fgkdBinsPtJet[2] = {0, 100};
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtJet = sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtJet)/sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtJet[0])-1;
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtJetInit = int(((AliAnalysisTaskV0sInJets::fgkdBinsPtJet)[AliAnalysisTaskV0sInJets::fgkiNBinsPtJet]-(AliAnalysisTaskV0sInJets::fgkdBinsPtJet)[0])/5.); // bin width 5 GeV/c
// axis: K0S invariant mass
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsMassK0s = 300;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassK0sMin = 0.35;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassK0sMax = 0.65;
// axis: Lambda invariant mass
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsMassLambda = 200;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassLambdaMin = 1.05;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassLambdaMax = 1.25;
// Default constructor
AliAnalysisTaskV0sInJets::AliAnalysisTaskV0sInJets():
AliAnalysisTaskSE(),
fAODIn(0),
fAODOut(0),
fOutputListStd(0),
fOutputListQA(0),
fOutputListCuts(0),
fOutputListMC(0),
// ftreeOut(0),
fiAODAnalysis(1),
fdCutDCAToPrimVtxMin(0.1),
fdCutDCADaughtersMax(1.),
fdCutNSigmadEdxMax(3),
fdCutCPAMin(0.998),
fdCutNTauMax(5),
fsJetBranchName(0),
fsJetBgBranchName(0),
fdCutPtJetMin(0),
fdCutPtTrackMin(5),
fdRadiusJet(0.4),
fbJetSelection(0),
fbMCAnalysis(0),
// fbTreeOutput(0),
fRandom(0),
fdCutVertexZ(10),
fdCutVertexR2(1),
fdCutCentLow(0),
fdCutCentHigh(80),
/*
fBranchV0Rec(0),
fBranchV0Gen(0),
fBranchJet(0),
fEventInfo(0),
*/
fdCentrality(0),
fh1EventCounterCut(0),
fh1EventCent(0),
fh1EventCent2(0),
fh2EventCentTracks(0),
fh1V0CandPerEvent(0),
fh1NRndConeCent(0),
fh1NMedConeCent(0),
fh1AreaExcluded(0),
fh2CCK0s(0),
fh2CCLambda(0),
fh3CCMassCorrelBoth(0),
fh3CCMassCorrelKNotL(0),
fh3CCMassCorrelLNotK(0)
{
for (Int_t i =0; i < fgkiNQAIndeces; i++)
{
fh1QAV0Status[i] = 0;
fh1QAV0TPCRefit[i] = 0;
fh1QAV0TPCRows[i] = 0;
fh1QAV0TPCFindable[i] = 0;
fh1QAV0TPCRowsFind[i] = 0;
fh1QAV0Eta[i] = 0;
fh2QAV0EtaRows[i] = 0;
fh2QAV0PtRows[i] = 0;
fh2QAV0PhiRows[i] = 0;
fh2QAV0NClRows[i] = 0;
fh2QAV0EtaNCl[i] = 0;
fh2QAV0EtaPtK0sPeak[i] = 0;
fh2QAV0EtaEtaK0s[i] = 0;
fh2QAV0PhiPhiK0s[i] = 0;
fh1QAV0RapK0s[i] = 0;
fh2QAV0PtPtK0sPeak[i] = 0;
fh2ArmPodK0s[i] = 0;
fh2QAV0EtaPtLambdaPeak[i] = 0;
fh2QAV0EtaEtaLambda[i] = 0;
fh2QAV0PhiPhiLambda[i] = 0;
fh1QAV0RapLambda[i] = 0;
fh2QAV0PtPtLambdaPeak[i] = 0;
fh2ArmPodLambda[i] = 0;
fh2QAV0EtaPtALambdaPeak[i] = 0;
fh2QAV0EtaEtaALambda[i] = 0;
fh2QAV0PhiPhiALambda[i] = 0;
fh1QAV0RapALambda[i] = 0;
fh2QAV0PtPtALambdaPeak[i] = 0;
fh2ArmPodALambda[i] = 0;
fh1QAV0Pt[i] = 0;
fh1QAV0Charge[i] = 0;
fh1QAV0DCAVtx[i] = 0;
fh1QAV0DCAV0[i] = 0;
fh1QAV0Cos[i] = 0;
fh1QAV0R[i] = 0;
fh1QACTau2D[i] = 0;
fh1QACTau3D[i] = 0;
fh2ArmPod[i] = 0;
fh2CutTPCRowsK0s[i] = 0;
fh2CutTPCRowsLambda[i] = 0;
fh2CutPtPosK0s[i] = 0;
fh2CutPtNegK0s[i] = 0;
fh2CutPtPosLambda[i] = 0;
fh2CutPtNegLambda[i] = 0;
fh2CutDCAVtx[i] = 0;
fh2CutDCAV0[i] = 0;
fh2CutCos[i] = 0;
fh2CutR[i] = 0;
fh2CutEtaK0s[i] = 0;
fh2CutEtaLambda[i] = 0;
fh2CutRapK0s[i] = 0;
fh2CutRapLambda[i] = 0;
fh2CutCTauK0s[i] = 0;
fh2CutCTauLambda[i] = 0;
fh2CutPIDPosK0s[i] = 0;
fh2CutPIDNegK0s[i] = 0;
fh2CutPIDPosLambda[i] = 0;
fh2CutPIDNegLambda[i] = 0;
fh2Tau3DVs2D[i] = 0;
}
for (Int_t i = 0; i<fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = 0;
fh1V0InvMassLambdaAll[i] = 0;
fh1V0InvMassALambdaAll[i] = 0;
}
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = 0;
fh1V0CounterCentK0s[i] = 0;
fh1V0CounterCentLambda[i] = 0;
fh1V0CounterCentALambda[i] = 0;
fh1V0CandPerEventCentK0s[i] = 0;
fh1V0CandPerEventCentLambda[i] = 0;
fh1V0CandPerEventCentALambda[i] = 0;
fh1V0InvMassK0sCent[i] = 0;
fh1V0InvMassLambdaCent[i] = 0;
fh1V0InvMassALambdaCent[i] = 0;
fh1V0K0sPtMCGen[i] = 0;
fh2V0K0sPtMassMCRec[i] = 0;
fh1V0K0sPtMCRecFalse[i] = 0;
fh2V0K0sEtaPtMCGen[i] = 0;
fh3V0K0sEtaPtMassMCRec[i] = 0;
fh2V0K0sInJetPtMCGen[i] = 0;
fh3V0K0sInJetPtMassMCRec[i] = 0;
fh3V0K0sInJetEtaPtMCGen[i] = 0;
fh4V0K0sInJetEtaPtMassMCRec[i] = 0;
fh2V0K0sMCResolMPt[i] = 0;
fh2V0K0sMCPtGenPtRec[i] = 0;
fh1V0LambdaPtMCGen[i] = 0;
fh2V0LambdaPtMassMCRec[i] = 0;
fh1V0LambdaPtMCRecFalse[i] = 0;
fh2V0LambdaEtaPtMCGen[i] = 0;
fh3V0LambdaEtaPtMassMCRec[i] = 0;
fh2V0LambdaInJetPtMCGen[i] = 0;
fh3V0LambdaInJetPtMassMCRec[i] = 0;
fh3V0LambdaInJetEtaPtMCGen[i] = 0;
fh4V0LambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0LambdaMCResolMPt[i] = 0;
fh2V0LambdaMCPtGenPtRec[i] = 0;
fhnV0LambdaInclMCFD[i] = 0;
fhnV0LambdaInJetsMCFD[i] = 0;
fhnV0LambdaBulkMCFD[i] = 0;
fh1V0XiPtMCGen[i] = 0;
fh1V0ALambdaPt[i] = 0;
fh1V0ALambdaPtMCGen[i] = 0;
fh1V0ALambdaPtMCRec[i] = 0;
fh2V0ALambdaPtMassMCRec[i] = 0;
fh1V0ALambdaPtMCRecFalse[i] = 0;
fh2V0ALambdaEtaPtMCGen[i] = 0;
fh3V0ALambdaEtaPtMassMCRec[i] = 0;
fh2V0ALambdaInJetPtMCGen[i] = 0;
fh2V0ALambdaInJetPtMCRec[i] = 0;
fh3V0ALambdaInJetPtMassMCRec[i] = 0;
fh3V0ALambdaInJetEtaPtMCGen[i] = 0;
fh4V0ALambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0ALambdaMCResolMPt[i] = 0;
fh2V0ALambdaMCPtGenPtRec[i] = 0;
fhnV0ALambdaInclMCFD[i] = 0;
fhnV0ALambdaInJetsMCFD[i] = 0;
fhnV0ALambdaBulkMCFD[i] = 0;
fh1V0AXiPtMCGen[i] = 0;
// eta daughters
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// Inclusive
fhnV0InclusiveK0s[i] = 0;
fhnV0InclusiveLambda[i] = 0;
fhnV0InclusiveALambda[i] = 0;
// Cones
fhnV0InJetK0s[i] = 0;
fhnV0InPerpK0s[i] = 0;
fhnV0InRndK0s[i] = 0;
fhnV0InMedK0s[i] = 0;
fhnV0OutJetK0s[i] = 0;
fhnV0NoJetK0s[i] = 0;
fhnV0InJetLambda[i] = 0;
fhnV0InPerpLambda[i] = 0;
fhnV0InRndLambda[i] = 0;
fhnV0InMedLambda[i] = 0;
fhnV0OutJetLambda[i] = 0;
fhnV0NoJetLambda[i] = 0;
fhnV0InJetALambda[i] = 0;
fhnV0InPerpALambda[i] = 0;
fhnV0InRndALambda[i] = 0;
fhnV0InMedALambda[i] = 0;
fhnV0OutJetALambda[i] = 0;
fhnV0NoJetALambda[i] = 0;
fh2V0PtJetAngleK0s[i] = 0;
fh2V0PtJetAngleLambda[i] = 0;
fh2V0PtJetAngleALambda[i] = 0;
fh1DCAInK0s[i] = 0;
fh1DCAInLambda[i] = 0;
fh1DCAInALambda[i] = 0;
fh1DCAOutK0s[i] = 0;
fh1DCAOutLambda[i] = 0;
fh1DCAOutALambda[i] = 0;
fh1DeltaZK0s[i] = 0;
fh1DeltaZLambda[i] = 0;
fh1DeltaZALambda[i] = 0;
fh1PtJet[i] = 0;
fh1EtaJet[i] = 0;
fh2EtaPtJet[i] = 0;
fh1PhiJet[i] = 0;
fh1NJetPerEvent[i] = 0;
fh2EtaPhiRndCone[i] = 0;
fh2EtaPhiMedCone[i] = 0;
fh1VtxZ[i] = 0;
fh2VtxXY[i] = 0;
}
}
// Constructor
AliAnalysisTaskV0sInJets::AliAnalysisTaskV0sInJets(const char* name):
AliAnalysisTaskSE(name),
fAODIn(0),
fAODOut(0),
fOutputListStd(0),
fOutputListQA(0),
fOutputListCuts(0),
fOutputListMC(0),
// ftreeOut(0),
fiAODAnalysis(1),
fdCutDCAToPrimVtxMin(0.1),
fdCutDCADaughtersMax(1.),
fdCutNSigmadEdxMax(3),
fdCutCPAMin(0.998),
fdCutNTauMax(5),
fsJetBranchName(0),
fsJetBgBranchName(0),
fdCutPtJetMin(0),
fdCutPtTrackMin(5),
fdRadiusJet(0.4),
fbJetSelection(0),
fbMCAnalysis(0),
// fbTreeOutput(0),
fRandom(0),
fdCutVertexZ(10),
fdCutVertexR2(1),
fdCutCentLow(0),
fdCutCentHigh(80),
/*
fBranchV0Rec(0),
fBranchV0Gen(0),
fBranchJet(0),
fEventInfo(0),
*/
fdCentrality(0),
fh1EventCounterCut(0),
fh1EventCent(0),
fh1EventCent2(0),
fh2EventCentTracks(0),
fh1V0CandPerEvent(0),
fh1NRndConeCent(0),
fh1NMedConeCent(0),
fh1AreaExcluded(0),
fh2CCK0s(0),
fh2CCLambda(0),
fh3CCMassCorrelBoth(0),
fh3CCMassCorrelKNotL(0),
fh3CCMassCorrelLNotK(0)
{
for (Int_t i =0; i < fgkiNQAIndeces; i++)
{
fh1QAV0Status[i] = 0;
fh1QAV0TPCRefit[i] = 0;
fh1QAV0TPCRows[i] = 0;
fh1QAV0TPCFindable[i] = 0;
fh1QAV0TPCRowsFind[i] = 0;
fh1QAV0Eta[i] = 0;
fh2QAV0EtaRows[i] = 0;
fh2QAV0PtRows[i] = 0;
fh2QAV0PhiRows[i] = 0;
fh2QAV0NClRows[i] = 0;
fh2QAV0EtaNCl[i] = 0;
fh2QAV0EtaPtK0sPeak[i] = 0;
fh2QAV0EtaEtaK0s[i] = 0;
fh2QAV0PhiPhiK0s[i] = 0;
fh1QAV0RapK0s[i] = 0;
fh2QAV0PtPtK0sPeak[i] = 0;
fh2ArmPodK0s[i] = 0;
fh2QAV0EtaPtLambdaPeak[i] = 0;
fh2QAV0EtaEtaLambda[i] = 0;
fh2QAV0PhiPhiLambda[i] = 0;
fh1QAV0RapLambda[i] = 0;
fh2QAV0PtPtLambdaPeak[i] = 0;
fh2ArmPodLambda[i] = 0;
fh2QAV0EtaPtALambdaPeak[i] = 0;
fh2QAV0EtaEtaALambda[i] = 0;
fh2QAV0PhiPhiALambda[i] = 0;
fh1QAV0RapALambda[i] = 0;
fh2QAV0PtPtALambdaPeak[i] = 0;
fh2ArmPodALambda[i] = 0;
fh1QAV0Pt[i] = 0;
fh1QAV0Charge[i] = 0;
fh1QAV0DCAVtx[i] = 0;
fh1QAV0DCAV0[i] = 0;
fh1QAV0Cos[i] = 0;
fh1QAV0R[i] = 0;
fh1QACTau2D[i] = 0;
fh1QACTau3D[i] = 0;
fh2ArmPod[i] = 0;
fh2CutTPCRowsK0s[i] = 0;
fh2CutTPCRowsLambda[i] = 0;
fh2CutPtPosK0s[i] = 0;
fh2CutPtNegK0s[i] = 0;
fh2CutPtPosLambda[i] = 0;
fh2CutPtNegLambda[i] = 0;
fh2CutDCAVtx[i] = 0;
fh2CutDCAV0[i] = 0;
fh2CutCos[i] = 0;
fh2CutR[i] = 0;
fh2CutEtaK0s[i] = 0;
fh2CutEtaLambda[i] = 0;
fh2CutRapK0s[i] = 0;
fh2CutRapLambda[i] = 0;
fh2CutCTauK0s[i] = 0;
fh2CutCTauLambda[i] = 0;
fh2CutPIDPosK0s[i] = 0;
fh2CutPIDNegK0s[i] = 0;
fh2CutPIDPosLambda[i] = 0;
fh2CutPIDNegLambda[i] = 0;
fh2Tau3DVs2D[i] = 0;
}
for (Int_t i = 0; i<fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = 0;
fh1V0InvMassLambdaAll[i] = 0;
fh1V0InvMassALambdaAll[i] = 0;
}
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = 0;
fh1V0CounterCentK0s[i] = 0;
fh1V0CounterCentLambda[i] = 0;
fh1V0CounterCentALambda[i] = 0;
fh1V0CandPerEventCentK0s[i] = 0;
fh1V0CandPerEventCentLambda[i] = 0;
fh1V0CandPerEventCentALambda[i] = 0;
fh1V0InvMassK0sCent[i] = 0;
fh1V0InvMassLambdaCent[i] = 0;
fh1V0InvMassALambdaCent[i] = 0;
fh1V0K0sPtMCGen[i] = 0;
fh2V0K0sPtMassMCRec[i] = 0;
fh1V0K0sPtMCRecFalse[i] = 0;
fh2V0K0sEtaPtMCGen[i] = 0;
fh3V0K0sEtaPtMassMCRec[i] = 0;
fh2V0K0sInJetPtMCGen[i] = 0;
fh3V0K0sInJetPtMassMCRec[i] = 0;
fh3V0K0sInJetEtaPtMCGen[i] = 0;
fh4V0K0sInJetEtaPtMassMCRec[i] = 0;
fh2V0K0sMCResolMPt[i] = 0;
fh2V0K0sMCPtGenPtRec[i] = 0;
fh1V0LambdaPtMCGen[i] = 0;
fh2V0LambdaPtMassMCRec[i] = 0;
fh1V0LambdaPtMCRecFalse[i] = 0;
fh2V0LambdaEtaPtMCGen[i] = 0;
fh3V0LambdaEtaPtMassMCRec[i] = 0;
fh2V0LambdaInJetPtMCGen[i] = 0;
fh3V0LambdaInJetPtMassMCRec[i] = 0;
fh3V0LambdaInJetEtaPtMCGen[i] = 0;
fh4V0LambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0LambdaMCResolMPt[i] = 0;
fh2V0LambdaMCPtGenPtRec[i] = 0;
fhnV0LambdaInclMCFD[i] = 0;
fhnV0LambdaInJetsMCFD[i] = 0;
fhnV0LambdaBulkMCFD[i] = 0;
fh1V0XiPtMCGen[i] = 0;
fh1V0ALambdaPt[i] = 0;
fh1V0ALambdaPtMCGen[i] = 0;
fh1V0ALambdaPtMCRec[i] = 0;
fh2V0ALambdaPtMassMCRec[i] = 0;
fh1V0ALambdaPtMCRecFalse[i] = 0;
fh2V0ALambdaEtaPtMCGen[i] = 0;
fh3V0ALambdaEtaPtMassMCRec[i] = 0;
fh2V0ALambdaInJetPtMCGen[i] = 0;
fh2V0ALambdaInJetPtMCRec[i] = 0;
fh3V0ALambdaInJetPtMassMCRec[i] = 0;
fh3V0ALambdaInJetEtaPtMCGen[i] = 0;
fh4V0ALambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0ALambdaMCResolMPt[i] = 0;
fh2V0ALambdaMCPtGenPtRec[i] = 0;
fhnV0ALambdaInclMCFD[i] = 0;
fhnV0ALambdaInJetsMCFD[i] = 0;
fhnV0ALambdaBulkMCFD[i] = 0;
fh1V0AXiPtMCGen[i] = 0;
// eta daughters
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// Inclusive
fhnV0InclusiveK0s[i] = 0;
fhnV0InclusiveLambda[i] = 0;
fhnV0InclusiveALambda[i] = 0;
// Cones
fhnV0InJetK0s[i] = 0;
fhnV0InPerpK0s[i] = 0;
fhnV0InRndK0s[i] = 0;
fhnV0InMedK0s[i] = 0;
fhnV0OutJetK0s[i] = 0;
fhnV0NoJetK0s[i] = 0;
fhnV0InJetLambda[i] = 0;
fhnV0InPerpLambda[i] = 0;
fhnV0InRndLambda[i] = 0;
fhnV0InMedLambda[i] = 0;
fhnV0OutJetLambda[i] = 0;
fhnV0NoJetLambda[i] = 0;
fhnV0InJetALambda[i] = 0;
fhnV0InPerpALambda[i] = 0;
fhnV0InRndALambda[i] = 0;
fhnV0InMedALambda[i] = 0;
fhnV0OutJetALambda[i] = 0;
fhnV0NoJetALambda[i] = 0;
fh2V0PtJetAngleK0s[i] = 0;
fh2V0PtJetAngleLambda[i] = 0;
fh2V0PtJetAngleALambda[i] = 0;
fh1DCAInK0s[i] = 0;
fh1DCAInLambda[i] = 0;
fh1DCAInALambda[i] = 0;
fh1DCAOutK0s[i] = 0;
fh1DCAOutLambda[i] = 0;
fh1DCAOutALambda[i] = 0;
fh1DeltaZK0s[i] = 0;
fh1DeltaZLambda[i] = 0;
fh1DeltaZALambda[i] = 0;
fh1PtJet[i] = 0;
fh1EtaJet[i] = 0;
fh2EtaPtJet[i] = 0;
fh1PhiJet[i] = 0;
fh1NJetPerEvent[i] = 0;
fh2EtaPhiRndCone[i] = 0;
fh2EtaPhiMedCone[i] = 0;
fh1VtxZ[i] = 0;
fh2VtxXY[i] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TList container
DefineOutput(1, TList::Class());
DefineOutput(2, TList::Class());
DefineOutput(3, TList::Class());
DefineOutput(4, TList::Class());
DefineOutput(5, TTree::Class());
}
AliAnalysisTaskV0sInJets::~AliAnalysisTaskV0sInJets()
{
/*
if (fBranchV0Rec)
fBranchV0Rec->Delete();
delete fBranchV0Rec;
fBranchV0Rec = 0;
if (fBranchV0Gen)
fBranchV0Gen->Delete();
delete fBranchV0Gen;
fBranchV0Gen = 0;
if (fBranchJet)
fBranchJet->Delete();
delete fBranchJet;
fBranchJet = 0;
if (fEventInfo)
fEventInfo->Delete();
delete fEventInfo;
fEventInfo = 0;
*/
delete fRandom;
fRandom = 0;
}
void AliAnalysisTaskV0sInJets::UserCreateOutputObjects()
{
// Create histograms
// Called once
fRandom = new TRandom3(0);
/*
if (!fBranchV0Rec && fbTreeOutput)
{
// fBranchV0Rec = new TClonesArray("AliAODv0",0);
fBranchV0Rec = new TClonesArray("AliV0Object",0);
fBranchV0Rec->SetName("branch_V0Rec");
}
if (!fBranchV0Gen && fbTreeOutput)
{
fBranchV0Gen = new TClonesArray("AliAODMCParticle",0);
fBranchV0Gen->SetName("branch_V0Gen");
}
if (!fBranchJet && fbTreeOutput)
{
// fBranchJet = new TClonesArray("AliAODJet",0);
fBranchJet = new TClonesArray("AliJetObject",0);
fBranchJet->SetName("branch_Jet");
}
if (!fEventInfo && fbTreeOutput)
{
fEventInfo = new AliEventInfoObject();
fEventInfo->SetName("eventInfo");
}
Int_t dSizeBuffer = 32000; // default 32000
if (fbTreeOutput)
{
ftreeOut = new TTree("treeV0","Tree V0");
ftreeOut->Branch("branch_V0Rec",&fBranchV0Rec,dSizeBuffer,2);
ftreeOut->Branch("branch_V0Gen",&fBranchV0Gen,dSizeBuffer,2);
ftreeOut->Branch("branch_Jet",&fBranchJet,dSizeBuffer,2);
ftreeOut->Branch("eventInfo",&fEventInfo,dSizeBuffer,2);
}
*/
fOutputListStd = new TList();
fOutputListStd->SetOwner();
fOutputListQA = new TList();
fOutputListQA->SetOwner();
fOutputListCuts = new TList();
fOutputListCuts->SetOwner();
fOutputListMC = new TList();
fOutputListMC->SetOwner();
// event categories
const Int_t iNCategEvent = 6;
TString categEvent[iNCategEvent] = {"coll. candid.","AOD OK","vtx & cent","with V0","with jets","jet selection"};
// labels for stages of V0 selection
TString categV0[fgkiNCategV0] = {"all"/*0*/,"mass range"/*1*/,"rec. method"/*2*/,"tracks TPC"/*3*/,"track pt"/*4*/,"DCA prim v"/*5*/,"DCA daughters"/*6*/,"CPA"/*7*/,"volume"/*8*/,"track #it{#eta}"/*9*/,"V0 #it{y} & #it{#eta}"/*10*/,"lifetime"/*11*/,"PID"/*12*/,"Arm.-Pod."/*13*/,"inclusive"/*14*/,"in jet event"/*15*/,"in jet"/*16*/};
fh1EventCounterCut = new TH1D("fh1EventCounterCut","Number of events after filtering;selection filter;counts",iNCategEvent,0,iNCategEvent);
for (Int_t i = 0; i < iNCategEvent; i++)
fh1EventCounterCut->GetXaxis()->SetBinLabel(i+1,categEvent[i].Data());
fh1EventCent2 = new TH1D("fh1EventCent2","Number of events vs centrality;centrality;counts",100,0,100);
fh2EventCentTracks = new TH2D("fh2EventCentTracks","Number of tracks vs centrality;centrality;tracks;counts",100,0,100,150,0,15e3);
fh1EventCent = new TH1D("fh1EventCent","Number of events in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1EventCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1NRndConeCent = new TH1D("fh1NRndConeCent","Number of rnd. cones in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1NRndConeCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1NMedConeCent = new TH1D("fh1NMedConeCent","Number of med.-cl. cones in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1NMedConeCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1AreaExcluded = new TH1D("fh1AreaExcluded","Area of excluded cones in centrality bins;centrality;area",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1AreaExcluded->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fOutputListStd->Add(fh1EventCounterCut);
fOutputListStd->Add(fh1EventCent);
fOutputListStd->Add(fh1EventCent2);
fOutputListStd->Add(fh1NRndConeCent);
fOutputListStd->Add(fh1NMedConeCent);
fOutputListStd->Add(fh1AreaExcluded);
fOutputListStd->Add(fh2EventCentTracks);
fh1V0CandPerEvent = new TH1D("fh1V0CandPerEvent","Number of all V0 candidates per event;candidates;events",1000,0,1000);
fOutputListStd->Add(fh1V0CandPerEvent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = new TH1D(Form("fh1EventCounterCutCent_%d",i),Form("Number of events after filtering, cent %s;selection filter;counts",GetCentBinLabel(i).Data()),iNCategEvent,0,iNCategEvent);
for (Int_t j = 0; j < iNCategEvent; j++)
fh1EventCounterCutCent[i]->GetXaxis()->SetBinLabel(j+1,categEvent[j].Data());
fh1V0CandPerEventCentK0s[i] = new TH1D(Form("fh1V0CandPerEventCentK0s_%d",i),Form("Number of selected K0s candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CandPerEventCentLambda[i] = new TH1D(Form("fh1V0CandPerEventCentLambda_%d",i),Form("Number of selected Lambda candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CandPerEventCentALambda[i] = new TH1D(Form("fh1V0CandPerEventCentALambda_%d",i),Form("Number of selected ALambda candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CounterCentK0s[i] = new TH1D(Form("fh1V0CounterCentK0s_%d",i),Form("Number of K0s candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
fh1V0CounterCentLambda[i] = new TH1D(Form("fh1V0CounterCentLambda_%d",i),Form("Number of Lambda candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
fh1V0CounterCentALambda[i] = new TH1D(Form("fh1V0CounterCentALambda_%d",i),Form("Number of ALambda candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
for (Int_t j = 0; j < fgkiNCategV0; j++)
{
fh1V0CounterCentK0s[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
fh1V0CounterCentLambda[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
fh1V0CounterCentALambda[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
}
fOutputListStd->Add(fh1EventCounterCutCent[i]);
fOutputListStd->Add(fh1V0CandPerEventCentK0s[i]);
fOutputListStd->Add(fh1V0CandPerEventCentLambda[i]);
fOutputListStd->Add(fh1V0CandPerEventCentALambda[i]);
fOutputListStd->Add(fh1V0CounterCentK0s[i]);
fOutputListStd->Add(fh1V0CounterCentLambda[i]);
fOutputListStd->Add(fh1V0CounterCentALambda[i]);
}
// pt binning for V0 and jets
Int_t iNBinsPtV0 = fgkiNBinsPtV0Init;
Double_t dPtV0Min = fgkdBinsPtV0[0];
Double_t dPtV0Max = fgkdBinsPtV0[fgkiNBinsPtV0];
Int_t iNJetPtBins = fgkiNBinsPtJetInit;
Double_t dJetPtMin = fgkdBinsPtJet[0];
Double_t dJetPtMax = fgkdBinsPtJet[fgkiNBinsPtJet];
fh2CCK0s = new TH2D("fh2CCK0s","K0s candidates in Lambda peak",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2CCLambda = new TH2D("fh2CCLambda","Lambda candidates in K0s peak",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,iNBinsPtV0,dPtV0Min,dPtV0Max);
Int_t binsCorrel[3] = {fgkiNBinsMassK0s, fgkiNBinsMassLambda, iNBinsPtV0};
Double_t xminCorrel[3] = {fgkdMassK0sMin, fgkdMassLambdaMin, dPtV0Min};
Double_t xmaxCorrel[3] = {fgkdMassK0sMax, fgkdMassLambdaMax, dPtV0Max};
// Int_t binsCorrel[3] = {200, 200, iNBinsPtV0};
// Double_t xminCorrel[3] = {0, 0, dPtV0Min};
// Double_t xmaxCorrel[3] = {2, 2, dPtV0Max};
fh3CCMassCorrelBoth = new THnSparseD("fh3CCMassCorrelBoth","Mass correlation: K0S && Lambda;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fh3CCMassCorrelKNotL = new THnSparseD("fh3CCMassCorrelKNotL","Mass correlation: K0S, not Lambda;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fh3CCMassCorrelLNotK = new THnSparseD("fh3CCMassCorrelLNotK","Mass correlation: Lambda, not K0S;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fOutputListQA->Add(fh2CCK0s);
fOutputListQA->Add(fh2CCLambda);
fOutputListQA->Add(fh3CCMassCorrelBoth);
fOutputListQA->Add(fh3CCMassCorrelKNotL);
fOutputListQA->Add(fh3CCMassCorrelLNotK);
Double_t dStepEtaV0 = 0.025;
Double_t dRangeEtaV0Max = 0.8;
const Int_t iNBinsEtaV0 = 2*Int_t(dRangeEtaV0Max/dStepEtaV0);
// inclusive
const Int_t iNDimIncl = 3;
Int_t binsKIncl[iNDimIncl] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0};
Double_t xminKIncl[iNDimIncl] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxKIncl[iNDimIncl] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max};
Int_t binsLIncl[iNDimIncl] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0};
Double_t xminLIncl[iNDimIncl] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxLIncl[iNDimIncl] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max};
// binning in jets
const Int_t iNDimInJC = 4;
Int_t binsKInJC[iNDimInJC] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins};
Double_t xminKInJC[iNDimInJC] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin};
Double_t xmaxKInJC[iNDimInJC] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax};
Int_t binsLInJC[iNDimInJC] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins};
Double_t xminLInJC[iNDimInJC] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin};
Double_t xmaxLInJC[iNDimInJC] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax};
// binning eff inclusive vs eta-pT
Double_t dStepDeltaEta = 0.1;
Double_t dRangeDeltaEtaMax = 0.5;
const Int_t iNBinsDeltaEta = 2*Int_t(dRangeDeltaEtaMax/dStepDeltaEta);
Int_t binsEtaK[3] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0};
Double_t xminEtaK[3] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxEtaK[3] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max};
Int_t binsEtaL[3] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0};
Double_t xminEtaL[3] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxEtaL[3] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max};
// binning eff in jets vs eta-pT
// associated
Int_t binsEtaKInRec[5] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaKInRec[5] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaKInRec[5] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
Int_t binsEtaLInRec[5] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaLInRec[5] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaLInRec[5] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
// generated
Int_t binsEtaInGen[4] = {iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaInGen[4] = {dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaInGen[4] = {dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
// daughter eta: charge-etaD-ptD-etaV0-ptV0-ptJet
const Int_t iNDimEtaD = 6;
Int_t binsEtaDaughter[iNDimEtaD] = {2, 20, iNBinsPtV0, iNBinsEtaV0, iNBinsPtV0, iNJetPtBins};
Double_t xminEtaDaughter[iNDimEtaD] = {0, -1, dPtV0Min, -dRangeEtaV0Max, dPtV0Min, dJetPtMin};
Double_t xmaxEtaDaughter[iNDimEtaD] = {2, 1, dPtV0Max, dRangeEtaV0Max, dPtV0Max, dJetPtMax};
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1V0InvMassK0sCent[i] = new TH1D(Form("fh1V0InvMassK0sCent_%d",i),Form("K0s: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fh1V0InvMassLambdaCent[i] = new TH1D(Form("fh1V0InvMassLambdaCent_%d",i),Form("Lambda: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fh1V0InvMassALambdaCent[i] = new TH1D(Form("fh1V0InvMassALambdaCent_%d",i),Form("ALambda: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListStd->Add(fh1V0InvMassK0sCent[i]);
fOutputListStd->Add(fh1V0InvMassLambdaCent[i]);
fOutputListStd->Add(fh1V0InvMassALambdaCent[i]);
// Inclusive
fhnV0InclusiveK0s[i] = new THnSparseD(Form("fhnV0InclusiveK0s_C%d",i), "K0s: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fhnV0InclusiveLambda[i] = new THnSparseD(Form("fhnV0InclusiveLambda_C%d",i), "Lambda: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fhnV0InclusiveALambda[i] = new THnSparseD(Form("fhnV0InclusiveALambda_C%d",i), "ALambda: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InclusiveK0s[i]);
fOutputListStd->Add(fhnV0InclusiveLambda[i]);
fOutputListStd->Add(fhnV0InclusiveALambda[i]);
// In cones
fhnV0InJetK0s[i] = new THnSparseD(Form("fhnV0InJetK0s_%d",i),Form("K0s: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListStd->Add(fhnV0InJetK0s[i]);
fhnV0InPerpK0s[i] = new THnSparseD(Form("fhnV0InPerpK0s_%d",i),Form("K0s: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListStd->Add(fhnV0InPerpK0s[i]);
fhnV0InRndK0s[i] = new THnSparseD(Form("fhnV0InRndK0s_%d",i),Form("K0s: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0InRndK0s[i]);
fhnV0InMedK0s[i] = new THnSparseD(Form("fhnV0InMedK0s_%d",i),Form("K0s: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0InMedK0s[i]);
fhnV0OutJetK0s[i] = new THnSparseD(Form("fhnV0OutJetK0s_%d",i),Form("K0s: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0OutJetK0s[i]);
fhnV0NoJetK0s[i] = new THnSparseD(Form("fhnV0NoJetK0s_%d",i),Form("K0s: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0NoJetK0s[i]);
fhnV0InJetLambda[i] = new THnSparseD(Form("fhnV0InJetLambda_%d",i),Form("Lambda: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InJetLambda[i]);
fhnV0InPerpLambda[i] = new THnSparseD(Form("fhnV0InPerpLambda_%d",i),Form("Lambda: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InPerpLambda[i]);
fhnV0InRndLambda[i] = new THnSparseD(Form("fhnV0InRndLambda_%d",i),Form("Lambda: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InRndLambda[i]);
fhnV0InMedLambda[i] = new THnSparseD(Form("fhnV0InMedLambda_%d",i),Form("Lambda: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InMedLambda[i]);
fhnV0OutJetLambda[i] = new THnSparseD(Form("fhnV0OutJetLambda_%d",i),Form("Lambda: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0OutJetLambda[i]);
fhnV0NoJetLambda[i] = new THnSparseD(Form("fhnV0NoJetLambda_%d",i),Form("Lambda: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0NoJetLambda[i]);
fhnV0InJetALambda[i] = new THnSparseD(Form("fhnV0InJetALambda_%d",i),Form("ALambda: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InJetALambda[i]);
fhnV0InPerpALambda[i] = new THnSparseD(Form("fhnV0InPerpALambda_%d",i),Form("ALambda: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InPerpALambda[i]);
fhnV0InRndALambda[i] = new THnSparseD(Form("fhnV0InRndALambda_%d",i),Form("ALambda: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InRndALambda[i]);
fhnV0InMedALambda[i] = new THnSparseD(Form("fhnV0InMedALambda_%d",i),Form("ALambda: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InMedALambda[i]);
fhnV0OutJetALambda[i] = new THnSparseD(Form("fhnV0OutJetALambda_%d",i),Form("ALambda: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0OutJetALambda[i]);
fhnV0NoJetALambda[i] = new THnSparseD(Form("fhnV0NoJetALambda_%d",i),Form("ALambda: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0NoJetALambda[i]);
fh2V0PtJetAngleK0s[i] = new TH2D(Form("fh2V0PtJetAngleK0s_%d",i),Form("K0s: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleK0s[i]);
fh2V0PtJetAngleLambda[i] = new TH2D(Form("fh2V0PtJetAngleLambda_%d",i),Form("Lambda: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleLambda[i]);
fh2V0PtJetAngleALambda[i] = new TH2D(Form("fh2V0PtJetAngleALambda_%d",i),Form("ALambda: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleALambda[i]);
fh1DCAInK0s[i] = new TH1D(Form("fh1DCAInK0s_%d",i),Form("K0s in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInK0s[i]);
fh1DCAInLambda[i] = new TH1D(Form("fh1DCAInLambda_%d",i),Form("Lambda in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInLambda[i]);
fh1DCAInALambda[i] = new TH1D(Form("fh1DCAInALambda_%d",i),Form("ALambda in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInALambda[i]);
fh1DCAOutK0s[i] = new TH1D(Form("fh1DCAOutK0s_%d",i),Form("K0s outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutK0s[i]);
fh1DCAOutLambda[i] = new TH1D(Form("fh1DCAOutLambda_%d",i),Form("Lambda outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutLambda[i]);
fh1DCAOutALambda[i] = new TH1D(Form("fh1DCAOutALambda_%d",i),Form("ALambda outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutALambda[i]);
fh1DeltaZK0s[i] = new TH1D(Form("fh1DeltaZK0s_%d",i),Form("K0s: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZK0s[i]);
fh1DeltaZLambda[i] = new TH1D(Form("fh1DeltaZLambda_%d",i),Form("Lambda: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZLambda[i]);
fh1DeltaZALambda[i] = new TH1D(Form("fh1DeltaZALambda_%d",i),Form("ALambda: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZALambda[i]);
// jet histograms
fh1PtJet[i] = new TH1D(Form("fh1PtJet_%d",i),Form("Jet pt spectrum, cent: %s;#it{p}_{T} jet (GeV/#it{c})",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListStd->Add(fh1PtJet[i]);
fh1EtaJet[i] = new TH1D(Form("fh1EtaJet_%d",i),Form("Jet eta spectrum, cent: %s;#it{#eta} jet",GetCentBinLabel(i).Data()),80,-1.,1.);
fOutputListStd->Add(fh1EtaJet[i]);
fh2EtaPtJet[i] = new TH2D(Form("fh2EtaPtJet_%d",i),Form("Jet eta vs pT spectrum, cent: %s;#it{#eta} jet;#it{p}_{T} jet (GeV/#it{c})",GetCentBinLabel(i).Data()),80,-1.,1.,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListStd->Add(fh2EtaPtJet[i]);
fh2EtaPhiRndCone[i] = new TH2D(Form("fh2EtaPhiRndCone_%d",i),Form("Rnd. cones: eta vs phi, cent: %s;#it{#eta} cone;#it{#phi} cone",GetCentBinLabel(i).Data()),80,-1.,1.,100,0.,TMath::TwoPi());
fOutputListStd->Add(fh2EtaPhiRndCone[i]);
fh2EtaPhiMedCone[i] = new TH2D(Form("fh2EtaPhiMedCone_%d",i),Form("Med.-cl. cones: eta vs phi, cent: %s;#it{#eta} cone;#it{#phi} cone",GetCentBinLabel(i).Data()),80,-1.,1.,100,0.,TMath::TwoPi());
fOutputListStd->Add(fh2EtaPhiMedCone[i]);
fh1PhiJet[i] = new TH1D(Form("fh1PhiJet_%d",i),Form("Jet phi spectrum, cent: %s;#it{#phi} jet",GetCentBinLabel(i).Data()),100,0.,TMath::TwoPi());
fOutputListStd->Add(fh1PhiJet[i]);
fh1NJetPerEvent[i] = new TH1D(Form("fh1NJetPerEvent_%d",i),Form("Number of selected jets per event, cent: %s;# jets;# events",GetCentBinLabel(i).Data()),100,0.,100.);
fOutputListStd->Add(fh1NJetPerEvent[i]);
// event histograms
fh1VtxZ[i] = new TH1D(Form("fh1VtxZ_%d",i),Form("#it{z} coordinate of the primary vertex, cent: %s;#it{z} (cm)",GetCentBinLabel(i).Data()),150,-1.5*fdCutVertexZ,1.5*fdCutVertexZ);
fOutputListQA->Add(fh1VtxZ[i]);
fh2VtxXY[i] = new TH2D(Form("fh2VtxXY_%d",i),Form("#it{xy} coordinate of the primary vertex, cent: %s;#it{x} (cm);#it{y} (cm)",GetCentBinLabel(i).Data()),200,-0.2,0.2,500,-0.5,0.5);
fOutputListQA->Add(fh2VtxXY[i]);
// fOutputListStd->Add([i]);
if (fbMCAnalysis)
{
// inclusive pt
fh1V0K0sPtMCGen[i] = new TH1D(Form("fh1V0K0sPtMCGen_%d",i),Form("MC K0s generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0K0sPtMCGen[i]);
fh2V0K0sPtMassMCRec[i] = new TH2D(Form("fh2V0K0sPtMassMCRec_%d",i),Form("MC K0s associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fOutputListMC->Add(fh2V0K0sPtMassMCRec[i]);
fh1V0K0sPtMCRecFalse[i] = new TH1D(Form("fh1V0K0sPtMCRecFalse_%d",i),Form("MC K0s false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0K0sPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0K0sEtaPtMCGen[i] = new TH2D(Form("fh2V0K0sEtaPtMCGen_%d",i),Form("MC K0s generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0K0sEtaPtMCGen[i]);
fh3V0K0sEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0K0sEtaPtMassMCRec_%d",i),Form("MC K0s associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaK,xminEtaK,xmaxEtaK);
fOutputListMC->Add(fh3V0K0sEtaPtMassMCRec[i]);
// in jet pt
fh2V0K0sInJetPtMCGen[i] = new TH2D(Form("fh2V0K0sInJetPtMCGen_%d",i),Form("MC K0s in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0K0sInJetPtMCGen[i]);
fh3V0K0sInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0K0sInJetPtMassMCRec_%d",i),Form("MC K0s in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListMC->Add(fh3V0K0sInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0K0sInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0K0sInJetEtaPtMCGen_%d",i),Form("MC K0s generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0K0sInJetEtaPtMCGen[i]);
fh4V0K0sInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0K0sInJetEtaPtMassMCRec_%d",i),Form("MC K0s associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaKInRec,xminEtaKInRec,xmaxEtaKInRec);
fOutputListMC->Add(fh4V0K0sInJetEtaPtMassMCRec[i]);
fh2V0K0sMCResolMPt[i] = new TH2D(Form("fh2V0K0sMCResolMPt_%d",i),Form("MC K0s associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0K0sMCResolMPt[i]);
fh2V0K0sMCPtGenPtRec[i] = new TH2D(Form("fh2V0K0sMCPtGenPtRec_%d",i),Form("MC K0s associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0K0sMCPtGenPtRec[i]);
// inclusive pt
fh1V0LambdaPtMCGen[i] = new TH1D(Form("fh1V0LambdaPtMCGen_%d",i),Form("MC Lambda generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0LambdaPtMCGen[i]);
fh2V0LambdaPtMassMCRec[i] = new TH2D(Form("fh2V0LambdaPtMassMCRec_%d",i),Form("MC Lambda associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListMC->Add(fh2V0LambdaPtMassMCRec[i]);
fh1V0LambdaPtMCRecFalse[i] = new TH1D(Form("fh1V0LambdaPtMCRecFalse_%d",i),Form("MC Lambda false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0LambdaPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0LambdaEtaPtMCGen[i] = new TH2D(Form("fh2V0LambdaEtaPtMCGen_%d",i),Form("MC Lambda generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0LambdaEtaPtMCGen[i]);
fh3V0LambdaEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0LambdaEtaPtMassMCRec_%d",i),Form("MC Lambda associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaL,xminEtaL,xmaxEtaL);
fOutputListMC->Add(fh3V0LambdaEtaPtMassMCRec[i]);
// in jet pt
fh2V0LambdaInJetPtMCGen[i] = new TH2D(Form("fh2V0LambdaInJetPtMCGen_%d",i),Form("MC Lambda in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0LambdaInJetPtMCGen[i]);
fh3V0LambdaInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0LambdaInJetPtMassMCRec_%d",i),Form("MC Lambda in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListMC->Add(fh3V0LambdaInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0LambdaInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0LambdaInJetEtaPtMCGen_%d",i),Form("MC Lambda generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0LambdaInJetEtaPtMCGen[i]);
fh4V0LambdaInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0LambdaInJetEtaPtMassMCRec_%d",i),Form("MC Lambda associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaLInRec,xminEtaLInRec,xmaxEtaLInRec);
fOutputListMC->Add(fh4V0LambdaInJetEtaPtMassMCRec[i]);
fh2V0LambdaMCResolMPt[i] = new TH2D(Form("fh2V0LambdaMCResolMPt_%d",i),Form("MC Lambda associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0LambdaMCResolMPt[i]);
fh2V0LambdaMCPtGenPtRec[i] = new TH2D(Form("fh2V0LambdaMCPtGenPtRec_%d",i),Form("MC Lambda associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0LambdaMCPtGenPtRec[i]);
// inclusive pt
fh1V0ALambdaPtMCGen[i] = new TH1D(Form("fh1V0ALambdaPtMCGen_%d",i),Form("MC ALambda generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0ALambdaPtMCGen[i]);
fh2V0ALambdaPtMassMCRec[i] = new TH2D(Form("fh2V0ALambdaPtMassMCRec_%d",i),Form("MC ALambda associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListMC->Add(fh2V0ALambdaPtMassMCRec[i]);
fh1V0ALambdaPtMCRecFalse[i] = new TH1D(Form("fh1V0ALambdaPtMCRecFalse_%d",i),Form("MC ALambda false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0ALambdaPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0ALambdaEtaPtMCGen[i] = new TH2D(Form("fh2V0ALambdaEtaPtMCGen_%d",i),Form("MC ALambda generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0ALambdaEtaPtMCGen[i]);
fh3V0ALambdaEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0ALambdaEtaPtMassMCRec_%d",i),Form("MC ALambda associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaL,xminEtaL,xmaxEtaL);
fOutputListMC->Add(fh3V0ALambdaEtaPtMassMCRec[i]);
// in jet pt
fh2V0ALambdaInJetPtMCGen[i] = new TH2D(Form("fh2V0ALambdaInJetPtMCGen_%d",i),Form("MC ALambda in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0ALambdaInJetPtMCGen[i]);
fh3V0ALambdaInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0ALambdaInJetPtMassMCRec_%d",i),Form("MC ALambda in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListMC->Add(fh3V0ALambdaInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0ALambdaInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0ALambdaInJetEtaPtMCGen_%d",i),Form("MC ALambda generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0ALambdaInJetEtaPtMCGen[i]);
fh4V0ALambdaInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0ALambdaInJetEtaPtMassMCRec_%d",i),Form("MC ALambda associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaLInRec,xminEtaLInRec,xmaxEtaLInRec);
fOutputListMC->Add(fh4V0ALambdaInJetEtaPtMassMCRec[i]);
fh2V0ALambdaMCResolMPt[i] = new TH2D(Form("fh2V0ALambdaMCResolMPt_%d",i),Form("MC ALambda associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0ALambdaMCResolMPt[i]);
fh2V0ALambdaMCPtGenPtRec[i] = new TH2D(Form("fh2V0ALambdaMCPtGenPtRec_%d",i),Form("MC ALambda associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0ALambdaMCPtGenPtRec[i]);
Int_t iNBinsPtXi = 80;
Double_t dPtXiMin = 0;
Double_t dPtXiMax = 8;
const Int_t iNDimFD = 3;
Int_t binsFD[iNDimFD] = {iNBinsPtV0, iNBinsPtXi, iNJetPtBins};
Double_t xminFD[iNDimFD] = {dPtV0Min, dPtXiMin, dJetPtMin};
Double_t xmaxFD[iNDimFD] = {dPtV0Max, dPtXiMax, dJetPtMax};
fhnV0LambdaInclMCFD[i] = new THnSparseD(Form("fhnV0LambdaInclMCFD_%d",i),Form("MC Lambda associated, inclusive, from Xi: pt-pt, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaInclMCFD[i]);
fhnV0LambdaInJetsMCFD[i] = new THnSparseD(Form("fhnV0LambdaInJetsMCFD_%d",i),Form("MC Lambda associated, in JC, from Xi: pt-pt-ptJet, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaInJetsMCFD[i]);
fhnV0LambdaBulkMCFD[i] = new THnSparseD(Form("fhnV0LambdaBulkMCFD_%d",i),Form("MC Lambda associated, in no jet events, from Xi: pt-pt, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaBulkMCFD[i]);
fh1V0XiPtMCGen[i] = new TH1D(Form("fh1V0XiPtMCGen_%d",i),Form("MC Xi^{-} generated: Pt spectrum, cent %s;#it{p}_{T}^{#Xi^{-},gen.} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtXi,dPtXiMin,dPtXiMax);
fOutputListMC->Add(fh1V0XiPtMCGen[i]);
fhnV0ALambdaInclMCFD[i] = new THnSparseD(Form("fhnV0ALambdaInclMCFD_%d",i),Form("MC ALambda associated, from AXi: pt-pt, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaInclMCFD[i]);
fhnV0ALambdaInJetsMCFD[i] = new THnSparseD(Form("fhnV0ALambdaInJetsMCFD_%d",i),Form("MC ALambda associated, in JC, from AXi: pt-pt-ptJet, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaInJetsMCFD[i]);
fhnV0ALambdaBulkMCFD[i] = new THnSparseD(Form("fhnV0ALambdaBulkMCFD_%d",i),Form("MC ALambda associated, in no jet events, from AXi: pt-pt-ptJet, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaBulkMCFD[i]);
fh1V0AXiPtMCGen[i] = new TH1D(Form("fh1V0AXiPtMCGen_%d",i),Form("MC AXi^{-} generated: Pt spectrum, cent %s;#it{p}_{T}^{A#Xi^{-},gen.} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtXi,dPtXiMin,dPtXiMax);
fOutputListMC->Add(fh1V0AXiPtMCGen[i]);
// daughter eta
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0K0sInclDaughterEtaPtPtMCGen_%d",i),Form("MC K0S, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0K0sInclDaughterEtaPtPtMCRec_%d",i),Form("MC K0S, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0K0sInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC K0S, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0K0sInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC K0S, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0LambdaInclDaughterEtaPtPtMCGen_%d",i),Form("MC Lambda, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0LambdaInclDaughterEtaPtPtMCRec_%d",i),Form("MC Lambda, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0LambdaInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC Lambda, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0LambdaInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC Lambda, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0ALambdaInclDaughterEtaPtPtMCGen_%d",i),Form("MC ALambda, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0ALambdaInclDaughterEtaPtPtMCRec_%d",i),Form("MC ALambda, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0ALambdaInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC ALambda, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0ALambdaInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC ALambda, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fOutputListMC->Add(fhnV0K0sInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0K0sInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0K0sInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0K0sInJetsDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0LambdaInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0LambdaInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0ALambdaInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0ALambdaInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i]);
}
}
// QA Histograms
for (Int_t i = 0; i < fgkiNQAIndeces; i++)
{
// [i] = new TH1D(Form("%d",i),";;Counts",,,);
fh1QAV0Status[i] = new TH1D(Form("fh1QAV0Status_%d",i),"QA: V0 status",2,0,2);
fh1QAV0TPCRefit[i] = new TH1D(Form("fh1QAV0TPCRefit_%d",i),"QA: TPC refit",2,0,2);
fh1QAV0TPCRows[i] = new TH1D(Form("fh1QAV0TPCRows_%d",i),"QA: TPC Rows",160,0,160);
fh1QAV0TPCFindable[i] = new TH1D(Form("fh1QAV0TPCFindable_%d",i),"QA: TPC Findable",160,0,160);
fh1QAV0TPCRowsFind[i] = new TH1D(Form("fh1QAV0TPCRowsFind_%d",i),"QA: TPC Rows/Findable",100,0,2);
fh1QAV0Eta[i] = new TH1D(Form("fh1QAV0Eta_%d",i),"QA: Daughter Eta",200,-2,2);
fh2QAV0EtaRows[i] = new TH2D(Form("fh2QAV0EtaRows_%d",i),"QA: Daughter Eta vs TPC rows;#eta;TPC rows",200,-2,2,160,0,160);
fh2QAV0PtRows[i] = new TH2D(Form("fh2QAV0PtRows_%d",i),"QA: Daughter Pt vs TPC rows;pt;TPC rows",100,0,10,160,0,160);
fh2QAV0PhiRows[i] = new TH2D(Form("fh2QAV0PhiRows_%d",i),"QA: Daughter Phi vs TPC rows;#phi;TPC rows",100,0,TMath::TwoPi(),160,0,160);
fh2QAV0NClRows[i] = new TH2D(Form("fh2QAV0NClRows_%d",i),"QA: Daughter NCl vs TPC rows;findable clusters;TPC rows",100,0,160,160,0,160);
fh2QAV0EtaNCl[i] = new TH2D(Form("fh2QAV0EtaNCl_%d",i),"QA: Daughter Eta vs NCl;#eta;findable clusters",200,-2,2,160,0,160);
fh2QAV0EtaPtK0sPeak[i] = new TH2D(Form("fh2QAV0EtaPtK0sPeak_%d",i),"QA: K0s: Daughter Eta vs V0 pt, peak;track eta;V0 pt",200,-2,2,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2QAV0EtaEtaK0s[i] = new TH2D(Form("fh2QAV0EtaEtaK0s_%d",i),"QA: K0s: Eta vs Eta Daughter",200,-2,2,200,-2,2);
fh2QAV0PhiPhiK0s[i] = new TH2D(Form("fh2QAV0PhiPhiK0s_%d",i),"QA: K0s: Phi vs Phi Daughter",200,0,TMath::TwoPi(),200,0,TMath::TwoPi());
fh1QAV0RapK0s[i] = new TH1D(Form("fh1QAV0RapK0s_%d",i),"QA: K0s: V0 Rapidity",200,-2,2);
fh2QAV0PtPtK0sPeak[i] = new TH2D(Form("fh2QAV0PtPtK0sPeak_%d",i),"QA: K0s: Daughter Pt vs Pt;neg pt;pos pt",100,0,5,100,0,5);
fh2QAV0EtaPtLambdaPeak[i] = new TH2D(Form("fh2QAV0EtaPtLambdaPeak_%d",i),"QA: Lambda: Daughter Eta vs V0 pt, peak;track eta;V0 pt",200,-2,2,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2QAV0EtaEtaLambda[i] = new TH2D(Form("fh2QAV0EtaEtaLambda_%d",i),"QA: Lambda: Eta vs Eta Daughter",200,-2,2,200,-2,2);
fh2QAV0PhiPhiLambda[i] = new TH2D(Form("fh2QAV0PhiPhiLambda_%d",i),"QA: Lambda: Phi vs Phi Daughter",200,0,TMath::TwoPi(),200,0,TMath::TwoPi());
fh1QAV0RapLambda[i] = new TH1D(Form("fh1QAV0RapLambda_%d",i),"QA: Lambda: V0 Rapidity",200,-2,2);
fh2QAV0PtPtLambdaPeak[i] = new TH2D(Form("fh2QAV0PtPtLambdaPeak_%d",i),"QA: Lambda: Daughter Pt vs Pt;neg pt;pos pt",100,0,5,100,0,5);
fh1QAV0Pt[i] = new TH1D(Form("fh1QAV0Pt_%d",i),"QA: Daughter Pt",100,0,5);
fh1QAV0Charge[i] = new TH1D(Form("fh1QAV0Charge_%d",i),"QA: V0 Charge",3,-1,2);
fh1QAV0DCAVtx[i] = new TH1D(Form("fh1QAV0DCAVtx_%d",i),"QA: DCA daughters to primary vertex",100,0,10);
fh1QAV0DCAV0[i] = new TH1D(Form("fh1QAV0DCAV0_%d",i),"QA: DCA daughters",100,0,2);
fh1QAV0Cos[i] = new TH1D(Form("fh1QAV0Cos_%d",i),"QA: CPA",10000,0.9,1);
fh1QAV0R[i] = new TH1D(Form("fh1QAV0R_%d",i),"QA: R",1500,0,150);
fh1QACTau2D[i] = new TH1D(Form("fh1QACTau2D_%d",i),"QA: K0s: c#tau 2D;mR/pt#tau",100,0,10);
fh1QACTau3D[i] = new TH1D(Form("fh1QACTau3D_%d",i),"QA: K0s: c#tau 3D;mL/p#tau",100,0,10);
fh2ArmPod[i] = new TH2D(Form("fh2ArmPod_%d",i),"Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodK0s[i] = new TH2D(Form("fh2ArmPodK0s_%d",i),"K0s: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodLambda[i] = new TH2D(Form("fh2ArmPodLambda_%d",i),"Lambda: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodALambda[i] = new TH2D(Form("fh2ArmPodALambda_%d",i),"ALambda: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2CutTPCRowsK0s[i] = new TH2D(Form("fh2CutTPCRowsK0s_%d",i),"Cuts: K0s: TPC Rows vs mass;#it{m}_{inv} (GeV/#it{c}^{2});TPC rows",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,160,0,160);
fh2CutTPCRowsLambda[i] = new TH2D(Form("fh2CutTPCRowsLambda_%d",i),"Cuts: Lambda: TPC Rows vs mass;#it{m}_{inv} (GeV/#it{c}^{2});TPC rows",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,160,0,160);
fh2CutPtPosK0s[i] = new TH2D(Form("fh2CutPtPosK0s_%d",i),"Cuts: K0s: Pt pos;#it{m}_{inv} (GeV/#it{c}^{2});pt pos",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,5);
fh2CutPtNegK0s[i] = new TH2D(Form("fh2CutPtNegK0s_%d",i),"Cuts: K0s: Pt neg;#it{m}_{inv} (GeV/#it{c}^{2});pt neg",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,5);
fh2CutPtPosLambda[i] = new TH2D(Form("fh2CutPtPosLambda_%d",i),"Cuts: Lambda: Pt pos;#it{m}_{inv} (GeV/#it{c}^{2});pt pos",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,5);
fh2CutPtNegLambda[i] = new TH2D(Form("fh2CutPtNegLambda_%d",i),"Cuts: Lambda: Pt neg;#it{m}_{inv} (GeV/#it{c}^{2});pt neg",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,5);
fh2CutDCAVtx[i] = new TH2D(Form("fh2CutDCAVtx_%d",i),"Cuts: DCA daughters to prim. vtx.;#it{m}_{inv} (GeV/#it{c}^{2});DCA daughter to prim. vtx. (cm)",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutDCAV0[i] = new TH2D(Form("fh2CutDCAV0_%d",i),"Cuts: DCA daughters;#it{m}_{inv} (GeV/#it{c}^{2});DCA daughters / #sigma_{TPC}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,2);
fh2CutCos[i] = new TH2D(Form("fh2CutCos_%d",i),"Cuts: CPA;#it{m}_{inv} (GeV/#it{c}^{2});CPA",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,10000,0.9,1);
fh2CutR[i] = new TH2D(Form("fh2CutR_%d",i),"Cuts: R;#it{m}_{inv} (GeV/#it{c}^{2});R (cm)",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,1500,0,150);
fh2CutEtaK0s[i] = new TH2D(Form("fh2CutEtaK0s_%d",i),"Cuts: K0s: Eta;#it{m}_{inv} (GeV/#it{c}^{2});#eta",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,200,-2,2);
fh2CutEtaLambda[i] = new TH2D(Form("fh2CutEtaLambda_%d",i),"Cuts: Lambda: Eta;#it{m}_{inv} (GeV/#it{c}^{2});#eta",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,200,-2,2);
fh2CutRapK0s[i] = new TH2D(Form("fh2CutRapK0s_%d",i),"Cuts: K0s: Rapidity;#it{m}_{inv} (GeV/#it{c}^{2});y",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,200,-2,2);
fh2CutRapLambda[i] = new TH2D(Form("fh2CutRapLambda_%d",i),"Cuts: Lambda: Rapidity;#it{m}_{inv} (GeV/#it{c}^{2});y",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,200,-2,2);
fh2CutCTauK0s[i] = new TH2D(Form("fh2CutCTauK0s_%d",i),"Cuts: K0s: #it{c#tau};#it{m}_{inv} (GeV/#it{c}^{2});#it{mL/p#tau}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutCTauLambda[i] = new TH2D(Form("fh2CutCTauLambda_%d",i),"Cuts: Lambda: #it{c#tau};#it{m}_{inv} (GeV/#it{c}^{2});#it{mL/p#tau}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2CutPIDPosK0s[i] = new TH2D(Form("fh2CutPIDPosK0s_%d",i),"Cuts: K0s: PID pos;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutPIDNegK0s[i] = new TH2D(Form("fh2CutPIDNegK0s_%d",i),"Cuts: K0s: PID neg;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutPIDPosLambda[i] = new TH2D(Form("fh2CutPIDPosLambda_%d",i),"Cuts: Lambda: PID pos;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2CutPIDNegLambda[i] = new TH2D(Form("fh2CutPIDNegLambda_%d",i),"Cuts: Lambda: PID neg;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2Tau3DVs2D[i] = new TH2D(Form("fh2Tau3DVs2D_%d",i),"Decay 3D vs 2D;pt;3D/2D",100,0,10,200,0.5,1.5);
fOutputListQA->Add(fh1QAV0Status[i]);
fOutputListQA->Add(fh1QAV0TPCRefit[i]);
fOutputListQA->Add(fh1QAV0TPCRows[i]);
fOutputListQA->Add(fh1QAV0TPCFindable[i]);
fOutputListQA->Add(fh1QAV0TPCRowsFind[i]);
fOutputListQA->Add(fh1QAV0Eta[i]);
fOutputListQA->Add(fh2QAV0EtaRows[i]);
fOutputListQA->Add(fh2QAV0PtRows[i]);
fOutputListQA->Add(fh2QAV0PhiRows[i]);
fOutputListQA->Add(fh2QAV0NClRows[i]);
fOutputListQA->Add(fh2QAV0EtaNCl[i]);
fOutputListQA->Add(fh2QAV0EtaPtK0sPeak[i]);
fOutputListQA->Add(fh2QAV0EtaEtaK0s[i]);
fOutputListQA->Add(fh2QAV0PhiPhiK0s[i]);
fOutputListQA->Add(fh1QAV0RapK0s[i]);
fOutputListQA->Add(fh2QAV0PtPtK0sPeak[i]);
fOutputListQA->Add(fh2QAV0EtaPtLambdaPeak[i]);
fOutputListQA->Add(fh2QAV0EtaEtaLambda[i]);
fOutputListQA->Add(fh2QAV0PhiPhiLambda[i]);
fOutputListQA->Add(fh1QAV0RapLambda[i]);
fOutputListQA->Add(fh2QAV0PtPtLambdaPeak[i]);
fOutputListQA->Add(fh1QAV0Pt[i]);
fOutputListQA->Add(fh1QAV0Charge[i]);
fOutputListQA->Add(fh1QAV0DCAVtx[i]);
fOutputListQA->Add(fh1QAV0DCAV0[i]);
fOutputListQA->Add(fh1QAV0Cos[i]);
fOutputListQA->Add(fh1QAV0R[i]);
fOutputListQA->Add(fh1QACTau2D[i]);
fOutputListQA->Add(fh1QACTau3D[i]);
fOutputListQA->Add(fh2ArmPod[i]);
fOutputListQA->Add(fh2ArmPodK0s[i]);
fOutputListQA->Add(fh2ArmPodLambda[i]);
fOutputListQA->Add(fh2ArmPodALambda[i]);
fOutputListCuts->Add(fh2CutTPCRowsK0s[i]);
fOutputListCuts->Add(fh2CutTPCRowsLambda[i]);
fOutputListCuts->Add(fh2CutPtPosK0s[i]);
fOutputListCuts->Add(fh2CutPtNegK0s[i]);
fOutputListCuts->Add(fh2CutPtPosLambda[i]);
fOutputListCuts->Add(fh2CutPtNegLambda[i]);
fOutputListCuts->Add(fh2CutDCAVtx[i]);
fOutputListCuts->Add(fh2CutDCAV0[i]);
fOutputListCuts->Add(fh2CutCos[i]);
fOutputListCuts->Add(fh2CutR[i]);
fOutputListCuts->Add(fh2CutEtaK0s[i]);
fOutputListCuts->Add(fh2CutEtaLambda[i]);
fOutputListCuts->Add(fh2CutRapK0s[i]);
fOutputListCuts->Add(fh2CutRapLambda[i]);
fOutputListCuts->Add(fh2CutCTauK0s[i]);
fOutputListCuts->Add(fh2CutCTauLambda[i]);
fOutputListCuts->Add(fh2CutPIDPosK0s[i]);
fOutputListCuts->Add(fh2CutPIDNegK0s[i]);
fOutputListCuts->Add(fh2CutPIDPosLambda[i]);
fOutputListCuts->Add(fh2CutPIDNegLambda[i]);
fOutputListCuts->Add(fh2Tau3DVs2D[i]);
}
for (Int_t i = 0; i < fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = new TH1D(Form("fh1V0InvMassK0sAll_%d",i), Form("K0s: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fh1V0InvMassLambdaAll[i] = new TH1D(Form("fh1V0InvMassLambdaAll_%d",i), Form("Lambda: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fh1V0InvMassALambdaAll[i] = new TH1D(Form("fh1V0InvMassALambdaAll_%d",i), Form("ALambda: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListStd->Add(fh1V0InvMassK0sAll[i]);
fOutputListStd->Add(fh1V0InvMassLambdaAll[i]);
fOutputListStd->Add(fh1V0InvMassALambdaAll[i]);
}
for (Int_t i = 0; i < fOutputListStd->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListStd->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListStd->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListQA->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListQA->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListQA->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListCuts->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListCuts->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListCuts->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListMC->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListMC->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListMC->At(i));
if(hn) hn->Sumw2();
}
PostData(1,fOutputListStd);
PostData(2,fOutputListQA);
PostData(3,fOutputListCuts);
PostData(4,fOutputListMC);
// if (fbTreeOutput)
// PostData(5,ftreeOut);
}
void AliAnalysisTaskV0sInJets::UserExec(Option_t *)
{
// Main loop, called for each event
if(fDebug>5) printf("TaskV0sInJets: UserExec: Start\n");
/*
// reset branches for each event
if (fBranchV0Rec)
fBranchV0Rec->Clear();
if (fBranchV0Gen)
fBranchV0Gen->Clear();
if (fBranchJet)
fBranchJet->Clear();
if (fEventInfo)
fEventInfo->Reset();
*/
if (!fiAODAnalysis)
return;
if(fDebug>2) printf("TaskV0sInJets: AOD analysis\n");
fh1EventCounterCut->Fill(0); // all available selected events (collision candidates)
if(fDebug>5) printf("TaskV0sInJets: UserExec: Loading AOD\n");
fAODIn = dynamic_cast<AliAODEvent*>(InputEvent()); // input AOD
fAODOut = AODEvent(); // output AOD
if (!fAODOut)
{
if(fDebug>0) printf("TaskV0sInJets: No output AOD found\n");
return;
}
if (!fAODIn)
{
if(fDebug>0) printf("TaskV0sInJets: No input AOD found\n");
return;
}
if(fDebug>5) printf("TaskV0sInJets: UserExec: Loading AOD OK\n");
TClonesArray* arrayMC = 0; // array particles in the MC event
AliAODMCHeader* headerMC = 0; // MC header
Int_t iNTracksMC = 0; // number of MC tracks
Double_t dPrimVtxMCX=0., dPrimVtxMCY=0., dPrimVtxMCZ=0.; // position of the MC primary vertex
// Simulation info
if (fbMCAnalysis)
{
arrayMC = (TClonesArray*)fAODIn->FindListObject(AliAODMCParticle::StdBranchName());
if (!arrayMC)
{
if(fDebug>0) printf("TaskV0sInJets: No MC array found\n");
return;
}
if(fDebug>5) printf("TaskV0sInJets: MC array found\n");
iNTracksMC = arrayMC->GetEntriesFast();
if(fDebug>5) printf("TaskV0sInJets: There are %d MC tracks in this event\n",iNTracksMC);
// if (!iNTracksMC)
// return;
headerMC = (AliAODMCHeader*)fAODIn->FindListObject(AliAODMCHeader::StdBranchName());
if (!headerMC)
{
if(fDebug>0) printf("TaskV0sInJets: No MC header found\n");
return;
}
// get position of the MC primary vertex
dPrimVtxMCX=headerMC->GetVtxX();
dPrimVtxMCY=headerMC->GetVtxY();
dPrimVtxMCZ=headerMC->GetVtxZ();
}
// PID Response Task object
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*)mgr->GetInputEventHandler();
AliPIDResponse* fPIDResponse = inputHandler->GetPIDResponse();
if (!fPIDResponse)
{
if(fDebug>0) printf("TaskV0sInJets: No PID response object found\n");
return;
}
// AOD files are OK
fh1EventCounterCut->Fill(1);
// Event selection
if (!IsSelectedForJets(fAODIn,fdCutVertexZ,fdCutVertexR2,fdCutCentLow,fdCutCentHigh,1,0.1)) // cut on |delta z| in 2011 data between SPD vertex and nominal primary vertex
// if (!IsSelectedForJets(fAODIn,fdCutVertexZ,fdCutVertexR2,fdCutCentLow,fdCutCentHigh)) // no need for cutting in 2010 data
{
if(fDebug>5) printf("TaskV0sInJets: Event rejected\n");
return;
}
// fdCentrality = fAODIn->GetHeader()->GetCentrality(); // event centrality
fdCentrality = fAODIn->GetHeader()->GetCentralityP()->GetCentralityPercentile("V0M"); // event centrality
Int_t iCentIndex = GetCentralityBinIndex(fdCentrality); // get index of centrality bin
if (iCentIndex<0)
{
if(fDebug>5) printf("TaskV0sInJets: Event is out of histogram range\n");
return;
}
fh1EventCounterCut->Fill(2); // selected events (vertex, centrality)
fh1EventCounterCutCent[iCentIndex]->Fill(2);
UInt_t iNTracks = fAODIn->GetNumberOfTracks(); // get number of tracks in event
if(fDebug>5) printf("TaskV0sInJets: There are %d tracks in this event\n",iNTracks);
// if (!iNTracks)
// return;
Int_t iNV0s = fAODIn->GetNumberOfV0s(); // get the number of V0 candidates
if (!iNV0s)
{
if(fDebug>2) printf("TaskV0sInJets: No V0s found in event\n");
// return;
}
/*===== Event is OK for the analysis =====*/
fh1EventCent->Fill(iCentIndex);
fh1EventCent2->Fill(fdCentrality);
fh2EventCentTracks->Fill(fdCentrality,iNTracks);
// if (fbTreeOutput)
// fEventInfo->SetAODEvent(fAODIn);
// printf("V0sInJets: EventInfo: Centrality: %f\n",fEventInfo->GetCentrality());
if (iNV0s)
{
fh1EventCounterCut->Fill(3); // events with V0s
fh1EventCounterCutCent[iCentIndex]->Fill(3);
}
// Int_t iNV0SelV0Rec = 0;
// Int_t iNV0SelV0Gen = 0;
AliAODv0* v0 = 0; // pointer to V0 candidates
// AliV0Object* objectV0 = 0;
TVector3 vecV0Momentum; // 3D vector of V0 momentum
Double_t dMassV0K0s = 0; // invariant mass of the K0s candidate
Double_t dMassV0Lambda = 0; // invariant mass of the Lambda candidate
Double_t dMassV0ALambda = 0; // invariant mass of the Lambda candidate
Int_t iNV0CandTot = 0; // counter of all V0 candidates at the beginning
Int_t iNV0CandK0s = 0; // counter of K0s candidates at the end
Int_t iNV0CandLambda = 0; // counter of Lambda candidates at the end
Int_t iNV0CandALambda = 0; // counter of Lambda candidates at the end
Bool_t bUseOldCuts = 0; // old reconstruction cuts
Bool_t bUseAliceCuts = 0; // cuts used by Alice Zimmermann
Bool_t bUseIouriCuts = 0; // cuts used by Iouri
Bool_t bPrintCuts = 0; // print out which cuts are applied
Bool_t bPrintJetSelection = 0; // print out which jets are selected
// Values of V0 reconstruction cuts:
// Daughter tracks
Int_t iRefit = AliAODTrack::kTPCrefit; // TPC refit for daughter tracks
Double_t dDCAToPrimVtxMin = fdCutDCAToPrimVtxMin; // 0.1; // [cm] min DCA of daughters to the prim vtx
Double_t dDCADaughtersMax = fdCutDCADaughtersMax; // 1.; // [sigma of TPC tracking] max DCA between daughters
Double_t dEtaDaughterMax = 0.8; // max |pseudorapidity| of daughter tracks
Double_t dNSigmadEdxMax = fdCutNSigmadEdxMax;// 3.; // [sigma dE/dx] max difference between measured and expected signal of dE/dx in the TPC
Double_t dPtProtonPIDMax = 1.; // [GeV/c] maxium pT of proton for applying PID cut
// V0 candidate
Bool_t bOnFly = 0; // on-the-fly (yes) or offline (no) reconstructed
Double_t dCPAMin = fdCutCPAMin;// 0.998; // min cosine of the pointing angle
Double_t dRadiusDecayMin = 5.; // [cm] min radial distance of the decay vertex
Double_t dRadiusDecayMax = 100.; // [cm] max radial distance of the decay vertex
Double_t dEtaMax = 0.7; // max |pseudorapidity| of V0
Double_t dNTauMax = fdCutNTauMax; // 5.0; // [tau] max proper lifetime in multiples of the mean lifetime
// Old cuts Start
Double_t dNCrossedRowsTPCMin = 70.; // min number of crossed TPC rows (turned off)
// Double_t dCrossedRowsOverFindMin = 0.8; // min ratio crossed rows / findable clusters (turned off)
// Double_t dCrossedRowsOverFindMax = 1e3; // max ratio crossed rows / findable clusters (turned off)
Double_t dPtDaughterMin = 0.150; // [GeV/c] min transverse momentum of daughter tracks (turned off)
Double_t dRapMax = 0.75; // max |rapidity| of V0 (turned off)
// Old cuts End
// Other cuts
Double_t dNSigmaMassMax = 3.; // [sigma m] max difference between candidate mass and real particle mass (used only for mass peak method of signal extraction)
Double_t dDistPrimaryMax = 0.01; // [cm] max distance of production point to the primary vertex (criterion for choice of MC particles considered as primary)
// Selection of active cuts
Bool_t bCutEtaDaughter = 1; // daughter pseudorapidity
Bool_t bCutRapV0 = 0; // V0 rapidity
Bool_t bCutEtaV0 = 1; // V0 pseudorapidity
Bool_t bCutTau = 1; // V0 lifetime
Bool_t bCutPid = 1; // PID (TPC dE/dx)
Bool_t bCutArmPod = 1; // Armenteros-Podolanski for K0S
// Bool_t bCutCross = 0; // cross contamination
if (bUseOldCuts)
{
bCutRapV0 = 1;
dEtaMax = 0.75;
dNTauMax = 3.0;
}
else if (bUseAliceCuts)
{
// bOnFly = 1;
dEtaMax = 0.75;
dNTauMax = 5.0;
}
else if (bUseIouriCuts)
{
bCutRapV0 = 1;
bCutEtaV0 = 0;
dNTauMax = 3.0;
dRapMax = 0.5;
}
Double_t dCTauK0s = 2.6844; // [cm] c tau of K0S
Double_t dCTauLambda = 7.89; // [cm] c tau of Lambda
// Load PDG values of particle masses
Double_t dMassPDGK0s = TDatabasePDG::Instance()->GetParticle(kK0Short)->Mass();
Double_t dMassPDGLambda = TDatabasePDG::Instance()->GetParticle(kLambda0)->Mass();
// PDG codes of used particles
Int_t iPdgCodePion = 211;
Int_t iPdgCodeProton = 2212;
Int_t iPdgCodeK0s = 310;
Int_t iPdgCodeLambda = 3122;
// Jet selection: fdCutPtJetMin, fdCutPtTrackMin
Double_t dJetEtaWindow = dEtaMax-fdRadiusJet; // max jet |pseudorapidity|, to make sure that V0s can appear in the entire jet area
Double_t dCutJetAreaMin = 0.6*TMath::Pi()*fdRadiusJet*fdRadiusJet; // minimum jet area
Double_t dRadiusExcludeCone = 2*fdRadiusJet; // radius of cones around jets excluded for V0 outside jets
Bool_t bLeadingJetOnly = 0;
if (bUseAliceCuts)
{
fdCutPtJetMin = 5;
fdCutPtTrackMin = 5;
dCutJetAreaMin = 0;
bLeadingJetOnly = 0;
}
// Int_t iNJetAll = 0; // number of reconstructed jets in fBranchJet
// iNJetAll = fBranchJet->GetEntriesFast(); // number of reconstructed jets
TClonesArray* jetArray = 0; // object where the input jets are stored
TClonesArray* jetArrayBg = 0; // object where the kt clusters are stored
Int_t iNJet = 0; // number of reconstructed jets in the input
TClonesArray* jetArraySel = new TClonesArray("AliAODJet",0); // object where the selected jets are copied
Int_t iNJetSel = 0; // number of selected reconstructed jets
// iNJetSel = jetArraySel->GetEntriesFast(); // number of selected reconstructed jets
TClonesArray* jetArrayPerp = new TClonesArray("AliAODJet",0); // object where the perp. cones are stored
Int_t iNJetPerp = 0; // number of perpendicular cones
AliAODJet* jet = 0; // pointer to a jet
// AliJetObject* objectJet = 0;
AliAODJet* jetPerp = 0; // pointer to a perp. cone
AliAODJet* jetRnd = 0; // pointer to a rand. cone
AliAODJet* jetMed = 0; // pointer to a median cluster
TVector3 vecJetMomentum; // 3D vector of jet momentum
// TVector3 vecPerpConeMomentum; // 3D vector of perpendicular cone momentum
// TVector3 vecRndConeMomentum; // 3D vector of random cone momentum
Bool_t bJetEventGood = kTRUE; // indicator of good jet events
// printf("iNJetAll, iNJetSel: %d %d\n",iNJetAll,iNJetSel);
if (fbJetSelection) // analysis of V0s in jets is switched on
{
jetArray = (TClonesArray*)(fAODOut->FindListObject(fsJetBranchName.Data())); // find object with jets in the output AOD
if (!jetArray)
{
if(fDebug>0) printf("TaskV0sInJets: No array of name: %s\n",fsJetBranchName.Data());
bJetEventGood = kFALSE;
}
if (bJetEventGood)
iNJet = jetArray->GetEntriesFast();
if (bJetEventGood && !iNJet) // check whether there are some jets
{
if(fDebug>2) printf("TaskV0sInJets: No jets in array\n");
bJetEventGood = kFALSE;
}
if (bJetEventGood)
{
// printf("TaskV0sInJets: Loading bg array of name: %s\n",fsJetBgBranchName.Data());
jetArrayBg = (TClonesArray*)(fAODOut->FindListObject(fsJetBgBranchName.Data())); // find object with jets in the output AOD
if (!jetArrayBg)
{
if(fDebug>0) printf("TaskV0sInJets: No bg array of name: %s\n",fsJetBgBranchName.Data());
// bJetEventGood = kFALSE;
}
}
}
else // no in-jet analysis
bJetEventGood = kFALSE;
// select good jets and copy them to another array
if (bJetEventGood)
{
if (bLeadingJetOnly)
iNJet = 1; // only leading jets
if(fDebug>5) printf("TaskV0sInJets: Jet selection for %d jets\n",iNJet);
for (Int_t iJet = 0; iJet<iNJet; iJet++)
{
AliAODJet* jetSel = (AliAODJet*)jetArray->At(iJet); // load a jet in the list
if (!jetSel)
{
if(fDebug>0) printf("TaskV0sInJets: Cannot load jet %d\n",iJet);
continue;
}
if (bPrintJetSelection)
if(fDebug>7) printf("jet: i = %d, pT = %f, eta = %f, phi = %f, pt lead tr = %f ",iJet,jetSel->Pt(),jetSel->Eta(),jetSel->Phi(),jetSel->GetPtLeading());
// printf("TaskV0sInJets: Checking pt > %.2f for jet %d with pt %.2f\n",fdCutPtJetMin,iJet,jetSel->Pt());
if (jetSel->Pt() < fdCutPtJetMin) // selection of high-pt jets
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (pt)\n");
continue;
}
// printf("TaskV0sInJets: Checking |eta| < %.2f for jet %d with |eta| %.2f\n",dJetEtaWindow,iJet,TMath::Abs(jetSel->Eta()));
if (TMath::Abs(jetSel->Eta()) > dJetEtaWindow) // selection of jets in the chosen pseudorapidity range
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (eta)\n");
continue;
}
if (!bUseOldCuts)
{
if (jetSel->EffectiveAreaCharged() < dCutJetAreaMin)
continue;
}
Int_t iNTracksInJet = 0;
Double_t dPtLeadTrack = 0; // pt of the leading track
// Int_t iLeadTrack = 0;
iNTracksInJet = jetSel->GetRefTracks()->GetEntriesFast(); // number od tracks that constitute the jet
// printf("TaskV0sInJets: Searching for leading track from %d tracks in jet %d\n",iNTracksInJet,iJet);
if (fdCutPtTrackMin > 0) // a positive min leading track pt is set
{
for (Int_t j = 0; j < iNTracksInJet; j++) // find the track with the highest pt
{
AliAODTrack* track = (AliAODTrack*)jetSel->GetTrack(j); // is this the leading track?
if (!track)
continue;
// printf("TaskV0sInJets: %d: %.2f\n",j,track->Pt());
if (track->Pt() > dPtLeadTrack)
{
dPtLeadTrack = track->Pt();
// iLeadTrack = j;
}
}
// printf("Leading track pT: my: %f, ali: %f\n",dPtLeadTrack,jetSel->GetPtLeading());
// printf("TaskV0sInJets: Checking leading track pt > %.2f for pt %.2f of track %d in jet %d\n",fdCutPtTrackMin,dPtLeadTrack,iLeadTrack,iJet);
if (dPtLeadTrack < fdCutPtTrackMin) // selection of high-pt jet-track events
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (track pt)\n");
continue;
}
}
if (bPrintJetSelection)
if(fDebug>7) printf("accepted\n");
if(fDebug>5) printf("TaskV0sInJets: Jet %d with pt %.2f passed selection\n",iJet,jetSel->Pt());
/*
if (fbTreeOutput)
{
// new ((*fBranchJet)[iNJetAll++]) AliAODJet(*((AliAODJet*)jetSel));
objectJet = new ((*fBranchJet)[iNJetAll++]) AliJetObject(jetSel); // copy selected jet to the array
// objectJet->SetPtLeadingTrack(dPtLeadTrack);
objectJet->SetRadius(fdRadiusJet);
objectJet = 0;
}
*/
TLorentzVector vecPerpPlus(*(jetSel->MomentumVector()));
vecPerpPlus.RotateZ(TMath::Pi()/2.); // rotate vector by 90 deg around z
TLorentzVector vecPerpMinus(*(jetSel->MomentumVector()));
vecPerpMinus.RotateZ(-TMath::Pi()/2.); // rotate vector by -90 deg around z
// AliAODJet jetTmp = AliAODJet(vecPerp);
if(fDebug>5) printf("TaskV0sInJets: Adding perp. cones number %d, %d\n",iNJetPerp,iNJetPerp+1);
// printf("TaskV0sInJets: Adding perp. cone number %d: pT %f, phi %f, eta %f, pT %f, phi %f, eta %f\n",iNJetSel,vecPerp.Pt(),vecPerp.Phi(),vecPerp.Eta(),jetTmp.Pt(),jetTmp.Phi(),jetTmp.Eta());
new ((*jetArrayPerp)[iNJetPerp++]) AliAODJet(vecPerpPlus); // write perp. cone to the array
new ((*jetArrayPerp)[iNJetPerp++]) AliAODJet(vecPerpMinus); // write perp. cone to the array
if(fDebug>5) printf("TaskV0sInJets: Adding jet number %d\n",iNJetSel);
// printf("TaskV0sInJets: Adding jet number %d: pT %f, phi %f, eta %f\n",iNJetSel,jetSel->Pt(),jetSel->Phi(),jetSel->Eta());
new ((*jetArraySel)[iNJetSel++]) AliAODJet(*((AliAODJet*)jetSel)); // copy selected jet to the array
}
if(fDebug>5) printf("TaskV0sInJets: Added jets: %d\n",iNJetSel);
iNJetSel = jetArraySel->GetEntriesFast();
if(fDebug>2) printf("TaskV0sInJets: Selected jets in array: %d\n",iNJetSel);
fh1NJetPerEvent[iCentIndex]->Fill(iNJetSel);
// fill jet spectra
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jet = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
fh1PtJet[iCentIndex]->Fill(jet->Pt()); // pt spectrum of selected jets
fh1EtaJet[iCentIndex]->Fill(jet->Eta()); // eta spectrum of selected jets
fh2EtaPtJet[iCentIndex]->Fill(jet->Eta(),jet->Pt()); // eta-pT spectrum of selected jets
fh1PhiJet[iCentIndex]->Fill(jet->Phi()); // phi spectrum of selected jets
Double_t dAreaExcluded = TMath::Pi()*dRadiusExcludeCone*dRadiusExcludeCone; // area of the cone
dAreaExcluded -= AreaCircSegment(dRadiusExcludeCone,dEtaMax-jet->Eta()); // positive eta overhang
dAreaExcluded -= AreaCircSegment(dRadiusExcludeCone,dEtaMax+jet->Eta()); // negative eta overhang
fh1AreaExcluded->Fill(iCentIndex,dAreaExcluded);
}
jet = 0;
}
if (bJetEventGood) // there should be some reconstructed jets
{
fh1EventCounterCut->Fill(4); // events with jet(s)
fh1EventCounterCutCent[iCentIndex]->Fill(4); // events with jet(s)
if (iNJetSel)
{
fh1EventCounterCut->Fill(5); // events with selected jets
fh1EventCounterCutCent[iCentIndex]->Fill(5);
}
}
if (iNJetSel)
{
jetRnd = GetRandomCone(jetArraySel,dJetEtaWindow,2*fdRadiusJet);
if (jetRnd)
{
fh1NRndConeCent->Fill(iCentIndex);
fh2EtaPhiRndCone[iCentIndex]->Fill(jetRnd->Eta(),jetRnd->Phi());
}
jetMed = GetMedianCluster(jetArrayBg,dJetEtaWindow);
if (jetMed)
{
fh1NMedConeCent->Fill(iCentIndex);
fh2EtaPhiMedCone[iCentIndex]->Fill(jetMed->Eta(),jetMed->Phi());
}
}
// Loading primary vertex info
AliAODVertex* primVtx = fAODIn->GetPrimaryVertex(); // get the primary vertex
Double_t dPrimVtxPos[3]; // primary vertex position {x,y,z}
primVtx->GetXYZ(dPrimVtxPos);
fh1VtxZ[iCentIndex]->Fill(dPrimVtxPos[2]);
fh2VtxXY[iCentIndex]->Fill(dPrimVtxPos[0],dPrimVtxPos[1]);
/*===== Start of loop over V0 candidates =====*/
if(fDebug>2) printf("TaskV0sInJets: Start of V0 loop\n");
for (Int_t iV0 = 0; iV0 < iNV0s; iV0++)
{
v0 = fAODIn->GetV0(iV0); // get next candidate from the list in AOD
if (!v0)
continue;
iNV0CandTot++;
// Initialization of status indicators
Bool_t bIsCandidateK0s = kTRUE; // candidate for K0s
Bool_t bIsCandidateLambda = kTRUE; // candidate for Lambda
Bool_t bIsCandidateALambda = kTRUE; // candidate for Lambda
Bool_t bIsInPeakK0s = kFALSE; // candidate within the K0s mass peak
Bool_t bIsInPeakLambda = kFALSE; // candidate within the Lambda mass peak
Bool_t bIsInConeJet = kFALSE; // candidate within the jet cones
Bool_t bIsInConePerp = kFALSE; // candidate within the perpendicular cone
Bool_t bIsInConeRnd = kFALSE; // candidate within the random cone
Bool_t bIsInConeMed = kFALSE; // candidate within the median-cluster cone
Bool_t bIsOutsideCones = kFALSE; // candidate outside excluded cones
// Invariant mass calculation
dMassV0K0s = v0->MassK0Short();
dMassV0Lambda = v0->MassLambda();
dMassV0ALambda = v0->MassAntiLambda();
Int_t iCutIndex = 0; // indicator of current selection step
// 0
// All V0 candidates
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// Skip candidates outside the histogram range
if ( (dMassV0K0s < fgkdMassK0sMin) || (dMassV0K0s >= fgkdMassK0sMax) )
bIsCandidateK0s = kFALSE;
if ( (dMassV0Lambda < fgkdMassLambdaMin) || (dMassV0Lambda >= fgkdMassLambdaMax) )
bIsCandidateLambda = kFALSE;
if ( (dMassV0ALambda < fgkdMassLambdaMin) || (dMassV0ALambda >= fgkdMassLambdaMax) )
bIsCandidateALambda = kFALSE;
if (!bIsCandidateK0s && !bIsCandidateLambda && !bIsCandidateALambda)
continue;
Double_t dPtV0 = TMath::Sqrt(v0->Pt2V0()); // transverse momentum of V0
vecV0Momentum = TVector3(v0->Px(),v0->Py(),v0->Pz()); // set the vector of V0 momentum
// Sigma of the mass peak window
Double_t dMassPeakWindowK0s = dNSigmaMassMax*MassPeakSigmaOld(dPtV0,0);
Double_t dMassPeakWindowLambda = dNSigmaMassMax*MassPeakSigmaOld(dPtV0,1);
// Double_t dMassPeakWindowK0s = dNSigmaMassMax*MassPeakSigma(iCentIndex,dPtV0,0);
// Double_t dMassPeakWindowLambda = dNSigmaMassMax*MassPeakSigma(iCentIndex,dPtV0,1);
// Invariant mass peak selection
if (TMath::Abs(dMassV0K0s-dMassPDGK0s) < dMassPeakWindowK0s)
bIsInPeakK0s = kTRUE;
if (TMath::Abs(dMassV0Lambda-dMassPDGLambda) < dMassPeakWindowLambda)
bIsInPeakLambda = kTRUE;
// Retrieving all relevant properties of the V0 candidate
Bool_t bOnFlyStatus = v0->GetOnFlyStatus(); // online (on fly) reconstructed vs offline reconstructed
const AliAODTrack* trackPos = (AliAODTrack*)v0->GetDaughter(0); // positive daughter track
const AliAODTrack* trackNeg = (AliAODTrack*)v0->GetDaughter(1); // negative daughter track
Double_t dPtDaughterPos = trackPos->Pt(); // transverse momentum of a daughter track
Double_t dPtDaughterNeg = trackNeg->Pt();
Double_t dNRowsPos = trackPos->GetTPCClusterInfo(2,1); // crossed TPC pad rows of a daughter track
Double_t dNRowsNeg = trackNeg->GetTPCClusterInfo(2,1);
Double_t dDCAToPrimVtxPos = TMath::Abs(v0->DcaPosToPrimVertex()); // dca of a daughter to the primary vertex
Double_t dDCAToPrimVtxNeg = TMath::Abs(v0->DcaNegToPrimVertex());
Double_t dDCADaughters = v0->DcaV0Daughters(); // dca between daughters
Double_t dCPA = v0->CosPointingAngle(primVtx); // cosine of the pointing angle
Double_t dSecVtxPos[3]; // V0 vertex position {x,y,z}
// Double_t dSecVtxPos[3] = {v0->DecayVertexV0X(),v0->DecayVertexV0Y(),v0->DecayVertexV0Z()}; // V0 vertex position
v0->GetSecondaryVtx(dSecVtxPos);
Double_t dRadiusDecay = TMath::Sqrt(dSecVtxPos[0]*dSecVtxPos[0] + dSecVtxPos[1]*dSecVtxPos[1]); // distance of the V0 vertex from the z-axis
Double_t dEtaDaughterNeg = trackNeg->Eta(); // = v0->EtaProng(1), pseudorapidity of a daughter track
Double_t dEtaDaughterPos = trackPos->Eta(); // = v0->EtaProng(0)
Double_t dRapK0s = v0->RapK0Short(); // rapidity calculated for K0s assumption
Double_t dRapLambda = v0->RapLambda(); // rapidity calculated for Lambda assumption
Double_t dEtaV0 = v0->Eta(); // V0 pseudorapidity
// Double_t dPhiV0 = v0->Phi(); // V0 pseudorapidity
Double_t dDecayPath[3];
for (Int_t iPos = 0; iPos < 3; iPos++)
dDecayPath[iPos] = dSecVtxPos[iPos]-dPrimVtxPos[iPos]; // vector of the V0 path
Double_t dDecLen = TMath::Sqrt(dDecayPath[0]*dDecayPath[0]+dDecayPath[1]*dDecayPath[1]+dDecayPath[2]*dDecayPath[2]); // path length L
Double_t dDecLen2D = TMath::Sqrt(dDecayPath[0]*dDecayPath[0]+dDecayPath[1]*dDecayPath[1]); // transverse path length R
Double_t dLOverP = dDecLen/v0->P(); // L/p
Double_t dROverPt = dDecLen2D/dPtV0; // R/pT
Double_t dMLOverPK0s = dMassPDGK0s*dLOverP; // m*L/p = c*(proper lifetime)
// Double_t dMLOverPLambda = dMassPDGLambda*dLOverP; // m*L/p
Double_t dMROverPtK0s = dMassPDGK0s*dROverPt; // m*R/pT
Double_t dMROverPtLambda = dMassPDGLambda*dROverPt; // m*R/pT
Double_t dNSigmaPosPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackPos,AliPID::kPion)); // difference between measured and expected signal of the dE/dx in the TPC
Double_t dNSigmaPosProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackPos,AliPID::kProton));
Double_t dNSigmaNegPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackNeg,AliPID::kPion));
Double_t dNSigmaNegProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackNeg,AliPID::kProton));
Double_t dAlpha = v0->AlphaV0(); // Armenteros-Podolanski alpha
Double_t dPtArm = v0->PtArmV0(); // Armenteros-Podolanski pT
AliAODVertex* prodVtxDaughterPos = (AliAODVertex*)(trackPos->GetProdVertex()); // production vertex of the positive daughter track
Char_t cTypeVtxProdPos = prodVtxDaughterPos->GetType(); // type of the production vertex
AliAODVertex* prodVtxDaughterNeg = (AliAODVertex*)(trackNeg->GetProdVertex()); // production vertex of the negative daughter track
Char_t cTypeVtxProdNeg = prodVtxDaughterNeg->GetType(); // type of the production vertex
fh2Tau3DVs2D[0]->Fill(dPtV0,dLOverP/dROverPt);
// QA histograms before cuts
FillQAHistogramV0(primVtx,v0,0,bIsCandidateK0s,bIsCandidateLambda,bIsInPeakK0s,bIsInPeakLambda);
// Cut vs mass histograms before cuts
if (bIsCandidateK0s)
{
fh2CutTPCRowsK0s[0]->Fill(dMassV0K0s,dNRowsPos);
fh2CutTPCRowsK0s[0]->Fill(dMassV0K0s,dNRowsNeg);
fh2CutPtPosK0s[0]->Fill(dMassV0K0s,dPtDaughterPos);
fh2CutPtNegK0s[0]->Fill(dMassV0K0s,dPtDaughterNeg);
fh2CutDCAVtx[0]->Fill(dMassV0K0s,dDCAToPrimVtxPos);
fh2CutDCAVtx[0]->Fill(dMassV0K0s,dDCAToPrimVtxNeg);
fh2CutDCAV0[0]->Fill(dMassV0K0s,dDCADaughters);
fh2CutCos[0]->Fill(dMassV0K0s,dCPA);
fh2CutR[0]->Fill(dMassV0K0s,dRadiusDecay);
fh2CutEtaK0s[0]->Fill(dMassV0K0s,dEtaDaughterPos);
fh2CutEtaK0s[0]->Fill(dMassV0K0s,dEtaDaughterNeg);
fh2CutRapK0s[0]->Fill(dMassV0K0s,dRapK0s);
fh2CutCTauK0s[0]->Fill(dMassV0K0s,dMROverPtK0s/dCTauK0s);
fh2CutPIDPosK0s[0]->Fill(dMassV0K0s,dNSigmaPosPion);
fh2CutPIDNegK0s[0]->Fill(dMassV0K0s,dNSigmaNegPion);
}
if (bIsCandidateLambda)
{
fh2CutTPCRowsLambda[0]->Fill(dMassV0Lambda,dNRowsPos);
fh2CutTPCRowsLambda[0]->Fill(dMassV0Lambda,dNRowsNeg);
fh2CutPtPosLambda[0]->Fill(dMassV0Lambda,dPtDaughterPos);
fh2CutPtNegLambda[0]->Fill(dMassV0Lambda,dPtDaughterNeg);
fh2CutEtaLambda[0]->Fill(dMassV0Lambda,dEtaDaughterPos);
fh2CutEtaLambda[0]->Fill(dMassV0Lambda,dEtaDaughterNeg);
fh2CutRapLambda[0]->Fill(dMassV0Lambda,dRapLambda);
fh2CutCTauLambda[0]->Fill(dMassV0Lambda,dMROverPtLambda/dCTauLambda);
fh2CutPIDPosLambda[0]->Fill(dMassV0Lambda,dNSigmaPosProton);
fh2CutPIDNegLambda[0]->Fill(dMassV0Lambda,dNSigmaNegPion);
}
/*===== Start of reconstruction cutting =====*/
// 1
// All V0 candidates
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
/* Start of global cuts */
// 2
// Reconstruction method
if (bPrintCuts) printf("Rec: Applying cut: Reconstruction method: on-the-fly? %s\n",(bOnFly ? "yes" : "no"));
if (bOnFlyStatus!=bOnFly)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 3
// Tracks TPC OK
if (bPrintCuts) printf("Rec: Applying cut: Correct charge of daughters\n");
if ( !trackNeg || !trackPos )
continue;
if (trackNeg->Charge() == trackPos->Charge()) // daughters have different charge?
continue;
if (trackNeg->Charge() != -1) // daughters have expected charge?
continue;
if (trackPos->Charge() != 1) // daughters have expected charge?
continue;
if (bPrintCuts) printf("Rec: Applying cut: TPC refit: %d\n",iRefit);
if (!trackNeg->IsOn(iRefit)) // TPC refit is ON?
continue;
if (bPrintCuts) printf("Rec: Applying cut: Type of production vertex of daughter: Not %d\n",AliAODVertex::kKink);
if(cTypeVtxProdNeg == AliAODVertex::kKink) // kink daughter rejection
continue;
// Old cuts Start
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Number of TPC rows: > %f\n",dNCrossedRowsTPCMin);
if (dNRowsNeg < dNCrossedRowsTPCMin) // Crossed TPC padrows
continue;
// Int_t findable = trackNeg->GetTPCNclsF(); // Findable clusters
// if (findable <= 0)
// continue;
// if (dNRowsNeg/findable < dCrossedRowsOverFindMin)
// continue;
// if (dNRowsNeg/findable > dCrossedRowsOverFindMax)
// continue;
}
// Old cuts End
if (!trackPos->IsOn(iRefit))
continue;
if(cTypeVtxProdPos == AliAODVertex::kKink) // kink daughter rejection
continue;
// Old cuts Start
if (bUseOldCuts)
{
if (dNRowsPos < dNCrossedRowsTPCMin)
continue;
// findable = trackPos->GetTPCNclsF();
// if (findable <= 0)
// continue;
// if (dNRowsPos/findable < dCrossedRowsOverFindMin)
// continue;
// if (dNRowsPos/findable > dCrossedRowsOverFindMax)
// continue;
}
// Old cuts End
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 4
// Daughters: transverse momentum cut
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Daughter pT: > %f\n",dPtDaughterMin);
if ( ( dPtDaughterNeg < dPtDaughterMin ) || ( dPtDaughterPos < dPtDaughterMin ) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 5
// Daughters: Impact parameter of daughters to prim vtx
if (bPrintCuts) printf("Rec: Applying cut: Daughter DCA to prim vtx: > %f\n",dDCAToPrimVtxMin);
if ( ( dDCAToPrimVtxNeg < dDCAToPrimVtxMin ) || ( dDCAToPrimVtxPos < dDCAToPrimVtxMin ) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 6
// Daughters: DCA
if (bPrintCuts) printf("Rec: Applying cut: DCA between daughters: < %f\n",dDCADaughtersMax);
if (dDCADaughters > dDCADaughtersMax)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 7
// V0: Cosine of the pointing angle
if (bPrintCuts) printf("Rec: Applying cut: CPA: > %f\n",dCPAMin);
if (dCPA < dCPAMin)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 8
// V0: Fiducial volume
if (bPrintCuts) printf("Rec: Applying cut: Decay radius: > %f, < %f\n",dRadiusDecayMin,dRadiusDecayMax);
if ( (dRadiusDecay < dRadiusDecayMin) || (dRadiusDecay > dRadiusDecayMax) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 9
// Daughters: pseudorapidity cut
if (bCutEtaDaughter)
{
if (bPrintCuts) printf("Rec: Applying cut: Daughter |eta|: < %f\n",dEtaDaughterMax);
if ( (TMath::Abs(dEtaDaughterNeg) > dEtaDaughterMax) || (TMath::Abs(dEtaDaughterPos) > dEtaDaughterMax) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
/* End of global cuts */
/* Start of particle-dependent cuts */
// 10
// V0: rapidity cut & pseudorapidity cut
if (bCutRapV0)
{
if (bPrintCuts) printf("Rec: Applying cut: V0 |y|: < %f\n",dRapMax);
if (TMath::Abs(dRapK0s) > dRapMax)
bIsCandidateK0s = kFALSE;
if (TMath::Abs(dRapLambda) > dRapMax)
{
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
}
if (bCutEtaV0)
{
if (bPrintCuts) printf("Rec: Applying cut: V0 |eta|: < %f\n",dEtaMax);
if (TMath::Abs(dEtaV0) > dEtaMax)
{
bIsCandidateK0s = kFALSE;
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 11
// Lifetime cut
if (bCutTau)
{
if (bPrintCuts) printf("Rec: Applying cut: Proper lifetime: < %f\n",dNTauMax);
if (dMROverPtK0s > dNTauMax*dCTauK0s)
bIsCandidateK0s = kFALSE;
if (dMROverPtLambda > dNTauMax*dCTauLambda)
{
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 12
// Daughter PID
if (bCutPid)
{
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Delta dE/dx (both daughters): < %f\n",dNSigmadEdxMax);
if (dNSigmaPosPion > dNSigmadEdxMax || dNSigmaNegPion > dNSigmadEdxMax) // pi+, pi-
bIsCandidateK0s = kFALSE;
if (dNSigmaPosProton > dNSigmadEdxMax || dNSigmaNegPion > dNSigmadEdxMax) // p+, pi-
bIsCandidateLambda = kFALSE;
if (dNSigmaNegProton > dNSigmadEdxMax || dNSigmaPosPion > dNSigmadEdxMax) // p-, pi+
bIsCandidateALambda = kFALSE;
}
else
{
if (bPrintCuts) printf("Rec: Applying cut: Delta dE/dx (proton below %f GeV/c): < %f\n",dPtProtonPIDMax,dNSigmadEdxMax);
if ( (dPtDaughterPos < dPtProtonPIDMax) && (dNSigmaPosProton > dNSigmadEdxMax) ) // p+
bIsCandidateLambda = kFALSE;
if ( (dPtDaughterNeg < dPtProtonPIDMax) && (dNSigmaNegProton > dNSigmadEdxMax) ) // p-
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
Double_t valueCorrel[3] = {dMassV0K0s,dMassV0Lambda,dPtV0};
if (bIsCandidateK0s && bIsCandidateLambda)
fh3CCMassCorrelBoth->Fill(valueCorrel); // correlation of mass distribution of candidates selected as both K0s and Lambda
if (bIsCandidateK0s && !bIsCandidateLambda)
fh3CCMassCorrelKNotL->Fill(valueCorrel); // correlation of mass distribution of candidates selected as K0s and not Lambda
if (!bIsCandidateK0s && bIsCandidateLambda)
fh3CCMassCorrelLNotK->Fill(valueCorrel); // correlation of mass distribution of candidates selected as not K0s and Lambda
// 13
// Armenteros-Podolanski cut
if (bCutArmPod)
{
if (bPrintCuts) printf("Rec: Applying cut: Armenteros-Podolanski (K0S): pT > %f * |alpha|\n",0.2);
if(dPtArm < TMath::Abs(0.2*dAlpha))
bIsCandidateK0s = kFALSE;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// Cross contamination
if (bIsInPeakK0s)
{
if (bIsCandidateLambda) // Lambda candidates in K0s peak, excluded from Lambda candidates by CC cut
fh2CCLambda->Fill(dMassV0Lambda,dPtV0);
}
if (bIsInPeakLambda)
{
if (bIsCandidateK0s) // K0s candidates in Lambda peak, excluded from K0s candidates by CC cut
fh2CCK0s->Fill(dMassV0K0s,dPtV0);
}
// if (bCutCross)
// {
// if (bIsInPeakK0s)
// bIsCandidateLambda = kFALSE;
// if (bIsInPeakLambda)
// bIsCandidateK0s = kFALSE;
// FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
// }
// iCutIndex++;
/* End of particle-dependent cuts */
/*===== End of reconstruction cutting =====*/
if (!bIsCandidateK0s && !bIsCandidateLambda && !bIsCandidateALambda)
continue;
/*
if(fDebug>5) printf("TaskV0sInJets: Adding selected V0 to branch\n");
// Add selected candidates to the output tree branch
if ((bIsCandidateK0s || bIsCandidateLambda || bIsCandidateALambda) && fbTreeOutput)
{
objectV0 = new ((*fBranchV0Rec)[iNV0SelV0Rec++]) AliV0Object(v0,primVtx);
// new ((*fBranchV0Rec)[iNV0SelV0Rec++]) AliAODv0(*((AliAODv0*)v0));
objectV0->SetIsCandidateK0S(bIsCandidateK0s);
objectV0->SetIsCandidateLambda(bIsCandidateLambda);
objectV0->SetIsCandidateALambda(bIsCandidateALambda);
objectV0->SetNSigmaPosProton(dNSigmaPosProton);
objectV0->SetNSigmaNegProton(dNSigmaNegProton);
}
*/
// Selection of V0s in jet cones, perpendicular cones, random cones, outside cones
if (bJetEventGood && iNJetSel && (bIsCandidateK0s || bIsCandidateLambda || bIsCandidateALambda))
{
// Selection of V0s in jet cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in %d jet cones\n",bIsCandidateK0s,bIsCandidateLambda,iNJetSel);
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jet = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
vecJetMomentum = TVector3(jet->Px(),jet->Py(),jet->Pz()); // set the vector of jet momentum
if(fDebug>5) printf("TaskV0sInJets: Checking if V0 %d %d in jet cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
if (IsParticleInCone(v0,jet,fdRadiusJet)) // If good jet in event, find out whether V0 is in that jet
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in jet cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
bIsInConeJet = kTRUE;
break;
}
}
// Selection of V0s in perp. cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in %d perp. cones\n",bIsCandidateK0s,bIsCandidateLambda,iNJetSel);
for (Int_t iJet = 0; iJet<iNJetPerp; iJet++)
{
jetPerp = (AliAODJet*)jetArrayPerp->At(iJet); // load a jet in the list
if(fDebug>5) printf("TaskV0sInJets: Checking if V0 %d %d in perp. cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
if (IsParticleInCone(v0,jetPerp,fdRadiusJet)) // V0 in perp. cone
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in perp. cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
bIsInConePerp = kTRUE;
break;
}
}
// Selection of V0s in random cones
if (jetRnd)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in the rnd. cone\n",bIsCandidateK0s,bIsCandidateLambda);
if (IsParticleInCone(v0,jetRnd,fdRadiusJet)) // V0 in rnd. cone?
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in the rnd. cone\n",bIsCandidateK0s,bIsCandidateLambda);
bIsInConeRnd = kTRUE;
}
}
// Selection of V0s in median-cluster cones
if (jetMed)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in the med. cone\n",bIsCandidateK0s,bIsCandidateLambda);
if (IsParticleInCone(v0,jetMed,fdRadiusJet)) // V0 in rnd. cone?
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in the med. cone\n",bIsCandidateK0s,bIsCandidateLambda);
bIsInConeMed = kTRUE;
}
}
// Selection of V0s outside jet cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d outside jet cones\n",bIsCandidateK0s,bIsCandidateLambda);
if (!OverlapWithJets(jetArraySel,v0,dRadiusExcludeCone)) // V0 oustide jet cones
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found outside jet cones\n",bIsCandidateK0s,bIsCandidateLambda);
bIsOutsideCones = kTRUE;
}
}
// QA histograms after cuts
FillQAHistogramV0(primVtx,v0,1,bIsCandidateK0s,bIsCandidateLambda,bIsInPeakK0s,bIsInPeakLambda);
// Cut vs mass histograms after cuts
if (bIsCandidateK0s)
{
fh2CutTPCRowsK0s[1]->Fill(dMassV0K0s,dNRowsPos);
fh2CutTPCRowsK0s[1]->Fill(dMassV0K0s,dNRowsNeg);
fh2CutPtPosK0s[1]->Fill(dMassV0K0s,dPtDaughterPos);
fh2CutPtNegK0s[1]->Fill(dMassV0K0s,dPtDaughterNeg);
fh2CutDCAVtx[1]->Fill(dMassV0K0s,dDCAToPrimVtxPos);
fh2CutDCAVtx[1]->Fill(dMassV0K0s,dDCAToPrimVtxNeg);
fh2CutDCAV0[1]->Fill(dMassV0K0s,dDCADaughters);
fh2CutCos[1]->Fill(dMassV0K0s,dCPA);
fh2CutR[1]->Fill(dMassV0K0s,dRadiusDecay);
fh2CutEtaK0s[1]->Fill(dMassV0K0s,dEtaDaughterPos);
fh2CutEtaK0s[1]->Fill(dMassV0K0s,dEtaDaughterNeg);
fh2CutRapK0s[1]->Fill(dMassV0K0s,dRapK0s);
fh2CutCTauK0s[1]->Fill(dMassV0K0s,dMROverPtK0s/dCTauK0s);
fh2CutPIDPosK0s[1]->Fill(dMassV0K0s,dNSigmaPosPion);
fh2CutPIDNegK0s[1]->Fill(dMassV0K0s,dNSigmaNegPion);
fh1DeltaZK0s[iCentIndex]->Fill(dDecayPath[2]);
}
if (bIsCandidateLambda)
{
fh2CutTPCRowsLambda[1]->Fill(dMassV0Lambda,dNRowsPos);
fh2CutTPCRowsLambda[1]->Fill(dMassV0Lambda,dNRowsNeg);
fh2CutPtPosLambda[1]->Fill(dMassV0Lambda,dPtDaughterPos);
fh2CutPtNegLambda[1]->Fill(dMassV0Lambda,dPtDaughterNeg);
fh2CutEtaLambda[1]->Fill(dMassV0Lambda,dEtaDaughterPos);
fh2CutEtaLambda[1]->Fill(dMassV0Lambda,dEtaDaughterNeg);
fh2CutRapLambda[1]->Fill(dMassV0Lambda,dRapLambda);
fh2CutCTauLambda[1]->Fill(dMassV0Lambda,dMROverPtLambda/dCTauLambda);
fh2CutPIDPosLambda[1]->Fill(dMassV0Lambda,dNSigmaPosProton);
fh2CutPIDNegLambda[1]->Fill(dMassV0Lambda,dNSigmaNegPion);
fh1DeltaZLambda[iCentIndex]->Fill(dDecayPath[2]);
}
/*===== Start of filling V0 spectra =====*/
Double_t dAngle = TMath::Pi(); // angle between V0 momentum and jet momentum
if (bIsInConeJet)
{
dAngle = vecV0Momentum.Angle(vecJetMomentum);
}
// iCutIndex = 14
if (bIsCandidateK0s)
{
// 14 K0s candidates after cuts
// printf("K0S: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0K0s,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex, iCentIndex);
Double_t valueKIncl[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InclusiveK0s[iCentIndex]->Fill(valueKIncl);
fh1V0InvMassK0sCent[iCentIndex]->Fill(dMassV0K0s);
fh1QACTau2D[1]->Fill(dMROverPtK0s/dCTauK0s);
fh1QACTau3D[1]->Fill(dMLOverPK0s/dCTauK0s);
fh2Tau3DVs2D[1]->Fill(dPtV0,dLOverP/dROverPt);
if (iNJetSel)
{
// 15 K0s in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 K0s in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex+2, iCentIndex);
Double_t valueKInJC[4] = {dMassV0K0s,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetK0s[iCentIndex]->Fill(valueKInJC);
fh2V0PtJetAngleK0s[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueKOutJC[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0OutJetK0s[iCentIndex]->Fill(valueKOutJC);
}
if (bIsInConePerp)
{
Double_t valueKInPC[4] = {dMassV0K0s,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpK0s[iCentIndex]->Fill(valueKInPC);
}
if (bIsInConeRnd)
{
Double_t valueKInRnd[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InRndK0s[iCentIndex]->Fill(valueKInRnd);
}
if (bIsInConeMed)
{
Double_t valueKInMed[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InMedK0s[iCentIndex]->Fill(valueKInMed);
}
if (!iNJetSel)
{
Double_t valueKNoJet[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0NoJetK0s[iCentIndex]->Fill(valueKNoJet);
}
iNV0CandK0s++;
}
if (bIsCandidateLambda)
{
// 14 Lambda candidates after cuts
// printf("La: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0Lambda,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex, iCentIndex);
Double_t valueLIncl[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InclusiveLambda[iCentIndex]->Fill(valueLIncl);
fh1V0InvMassLambdaCent[iCentIndex]->Fill(dMassV0Lambda);
if (iNJetSel)
{
// 15 Lambda in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 Lambda in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex+2, iCentIndex);
Double_t valueLInJC[4] = {dMassV0Lambda,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetLambda[iCentIndex]->Fill(valueLInJC);
fh2V0PtJetAngleLambda[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueLOutJet[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0OutJetLambda[iCentIndex]->Fill(valueLOutJet);
}
if (bIsInConePerp)
{
Double_t valueLInPC[4] = {dMassV0Lambda,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpLambda[iCentIndex]->Fill(valueLInPC);
}
if (bIsInConeRnd)
{
Double_t valueLInRnd[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InRndLambda[iCentIndex]->Fill(valueLInRnd);
}
if (bIsInConeMed)
{
Double_t valueLInMed[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InMedLambda[iCentIndex]->Fill(valueLInMed);
}
if (!iNJetSel)
{
Double_t valueLNoJet[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0NoJetLambda[iCentIndex]->Fill(valueLNoJet);
}
iNV0CandLambda++;
}
if (bIsCandidateALambda)
{
// 14 ALambda candidates after cuts
// printf("AL: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0ALambda,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex, iCentIndex);
Double_t valueALIncl[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InclusiveALambda[iCentIndex]->Fill(valueALIncl);
fh1V0InvMassALambdaCent[iCentIndex]->Fill(dMassV0ALambda);
if (iNJetSel)
{
// 15 ALambda in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 ALambda in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex+2, iCentIndex);
Double_t valueLInJC[4] = {dMassV0ALambda,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetALambda[iCentIndex]->Fill(valueLInJC);
fh2V0PtJetAngleALambda[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueALOutJet[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0OutJetALambda[iCentIndex]->Fill(valueALOutJet);
}
if (bIsInConePerp)
{
Double_t valueLInPC[4] = {dMassV0ALambda,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpALambda[iCentIndex]->Fill(valueLInPC);
}
if (bIsInConeRnd)
{
Double_t valueALInRnd[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InRndALambda[iCentIndex]->Fill(valueALInRnd);
}
if (bIsInConeMed)
{
Double_t valueALInMed[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InMedALambda[iCentIndex]->Fill(valueALInMed);
}
if (!iNJetSel)
{
Double_t valueALNoJet[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0NoJetALambda[iCentIndex]->Fill(valueALNoJet);
}
iNV0CandALambda++;
}
/*===== End of filling V0 spectra =====*/
/*===== Association of reconstructed V0 candidates with MC particles =====*/
if (fbMCAnalysis)
{
// Associate selected candidates only
// if ( !(bIsCandidateK0s && bIsInPeakK0s) && !(bIsCandidateLambda && bIsInPeakLambda) ) // signal candidates
if ( !(bIsCandidateK0s) && !(bIsCandidateLambda) && !(bIsCandidateALambda) ) // chosen candidates with any mass
continue;
// Get MC labels of reconstructed daughter tracks
Int_t iLabelPos = TMath::Abs(trackPos->GetLabel());
Int_t iLabelNeg = TMath::Abs(trackNeg->GetLabel());
// Make sure MC daughters are in the array range
if ( (iLabelNeg<0) || (iLabelNeg>=iNTracksMC) || (iLabelPos<0) || (iLabelPos>=iNTracksMC) )
continue;
// Get MC particles corresponding to reconstructed daughter tracks
AliAODMCParticle* particleMCDaughterNeg = (AliAODMCParticle*)arrayMC->At(iLabelNeg);
AliAODMCParticle* particleMCDaughterPos = (AliAODMCParticle*)arrayMC->At(iLabelPos);
if (!particleMCDaughterNeg || !particleMCDaughterPos)
continue;
// Make sure MC daughter particles are not physical primary
if ( (particleMCDaughterNeg->IsPhysicalPrimary()) || (particleMCDaughterPos->IsPhysicalPrimary()) )
continue;
// Get identities of MC daughter particles
Int_t iPdgCodeDaughterPos = particleMCDaughterPos->GetPdgCode();
Int_t iPdgCodeDaughterNeg = particleMCDaughterNeg->GetPdgCode();
// Get index of the mother particle for each MC daughter particle
Int_t iIndexMotherPos = particleMCDaughterPos->GetMother();
Int_t iIndexMotherNeg = particleMCDaughterNeg->GetMother();
if ( (iIndexMotherNeg<0) || (iIndexMotherNeg>=iNTracksMC) || (iIndexMotherPos<0) || (iIndexMotherPos>=iNTracksMC) )
continue;
// Check whether MC daughter particles have the same mother
if (iIndexMotherNeg != iIndexMotherPos)
continue;
// Get the MC mother particle of both MC daughter particles
AliAODMCParticle* particleMCMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherPos);
if (!particleMCMother)
continue;
// Get identity of the MC mother particle
Int_t iPdgCodeMother = particleMCMother->GetPdgCode();
// Skip not interesting particles
if ( (iPdgCodeMother != iPdgCodeK0s) && (TMath::Abs(iPdgCodeMother) != iPdgCodeLambda) )
continue;
// Check identity of the MC mother particle and the decay channel
// Is MC mother particle K0S?
Bool_t bV0MCIsK0s = ( (iPdgCodeMother==iPdgCodeK0s) && (iPdgCodeDaughterPos==+iPdgCodePion) && (iPdgCodeDaughterNeg==-iPdgCodePion) );
// Is MC mother particle Lambda?
Bool_t bV0MCIsLambda = ( (iPdgCodeMother==+iPdgCodeLambda) && (iPdgCodeDaughterPos==+iPdgCodeProton) && (iPdgCodeDaughterNeg==-iPdgCodePion) );
// Is MC mother particle anti-Lambda?
Bool_t bV0MCIsALambda = ( (iPdgCodeMother==-iPdgCodeLambda) && (iPdgCodeDaughterPos==+iPdgCodePion) && (iPdgCodeDaughterNeg==-iPdgCodeProton) );
Double_t dPtV0Gen = particleMCMother->Pt();
// Double_t dRapV0MC = particleMCMother->Y();
Double_t dEtaV0Gen = particleMCMother->Eta();
// Double_t dPhiV0Gen = particleMCMother->Phi();
// Is MC mother particle physical primary? Attention!! Definition of IsPhysicalPrimary may change!!
// Bool_t bV0MCIsPrimary = particleMCMother->IsPhysicalPrimary();
// Get the MC mother particle of the MC mother particle
Int_t iIndexMotherOfMother = particleMCMother->GetMother();
AliAODMCParticle* particleMCMotherOfMother = 0;
if (iIndexMotherOfMother >= 0)
particleMCMotherOfMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherOfMother);
// Get identity of the MC mother particle of the MC mother particle if it exists
Int_t iPdgCodeMotherOfMother = 0;
if (particleMCMotherOfMother)
iPdgCodeMotherOfMother = particleMCMotherOfMother->GetPdgCode();
// Check if the MC mother particle of the MC mother particle is a physical primary Sigma (3212 - Sigma0, 3224 - Sigma*+, 3214 - Sigma*0, 3114 - Sigma*-)
// Bool_t bV0MCComesFromSigma = kFALSE; // Is MC mother particle daughter of a Sigma?
// if ( (particleMCMotherOfMother && particleMCMotherOfMother->IsPhysicalPrimary()) && ( (TMath::Abs(iPdgCodeMotherOfMother)==3212) || (TMath::Abs(iPdgCodeMotherOfMother)==3224) || (TMath::Abs(iPdgCodeMotherOfMother)==3214) || (TMath::Abs(iPdgCodeMotherOfMother)==3114) ) )
// bV0MCComesFromSigma = kTRUE;
// Should MC mother particle be considered as primary when it is Lambda?
// Bool_t bV0MCIsPrimaryLambda = (bV0MCIsPrimary || bV0MCComesFromSigma);
// Check if the MC mother particle of the MC mother particle is a Xi (3322 - Xi0, 3312 - Xi-)
Bool_t bV0MCComesFromXi = ( (particleMCMotherOfMother) && ( (iPdgCodeMotherOfMother==3322) || (iPdgCodeMotherOfMother==3312) ) ); // Is MC mother particle daughter of a Xi?
Bool_t bV0MCComesFromAXi = ( (particleMCMotherOfMother) && ( (iPdgCodeMotherOfMother==-3322) || (iPdgCodeMotherOfMother==-3312) ) ); // Is MC mother particle daughter of a anti-Xi?
// Get the distance between production point of the MC mother particle and the primary vertex
Double_t dx = dPrimVtxMCX-particleMCMother->Xv();
Double_t dy = dPrimVtxMCY-particleMCMother->Yv();
Double_t dz = dPrimVtxMCZ-particleMCMother->Zv();
Double_t dDistPrimary = TMath::Sqrt(dx*dx + dy*dy + dz*dz);
Bool_t bV0MCIsPrimaryDist = (dDistPrimary < dDistPrimaryMax); // Is close enough to be considered primary-like?
// phi, eta resolution for V0-reconstruction
// Double_t dResolutionV0Eta = particleMCMother->Eta()-v0->Eta();
// Double_t dResolutionV0Phi = particleMCMother->Phi()-v0->Phi();
/*
if (fbTreeOutput)
{
objectV0->SetPtTrue(dPtV0Gen);
objectV0->SetEtaTrue(dEtaV0Gen);
objectV0->SetPhiTrue(dPhiV0Gen);
objectV0->SetPDGCode(iPdgCodeMother);
objectV0->SetPDGCodeMother(iPdgCodeMotherOfMother);
}
*/
// K0s
// if (bIsCandidateK0s && bIsInPeakK0s) // selected candidates in peak
if (bIsCandidateK0s) // selected candidates with any mass
{
// if (bV0MCIsK0s && bV0MCIsPrimary) // well reconstructed candidates
if (bV0MCIsK0s && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0K0sPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0K0s);
Double_t valueEtaK[3] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen};
fh3V0K0sEtaPtMassMCRec[iCentIndex]->Fill(valueEtaK);
Double_t valueEtaDKNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0K0sInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKNeg);
Double_t valueEtaDKPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0K0sInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKPos);
fh2V0K0sMCResolMPt[iCentIndex]->Fill(dMassV0K0s-dMassPDGK0s,dPtV0);
fh2V0K0sMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a candidate in jet
{
Double_t valueKInJCMC[4] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0K0sInJetPtMassMCRec[iCentIndex]->Fill(valueKInJCMC);
Double_t valueEtaKIn[5] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0K0sInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaKIn);
Double_t valueEtaDKJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0K0sInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKJCNeg);
Double_t valueEtaDKJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0K0sInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKJCPos);
}
}
if (bV0MCIsK0s && !bV0MCIsPrimaryDist) // not primary K0s
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0K0sPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
// Lambda
// if (bIsCandidateLambda && bIsInPeakLambda) // selected candidates in peak
if (bIsCandidateLambda) // selected candidates with any mass
{
// if (bV0MCIsLambda && bV0MCIsPrimaryLambda) // well reconstructed candidates
if (bV0MCIsLambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0LambdaPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0Lambda);
Double_t valueEtaL[3] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen};
fh3V0LambdaEtaPtMassMCRec[iCentIndex]->Fill(valueEtaL);
Double_t valueEtaDLNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0LambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLNeg);
Double_t valueEtaDLPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0LambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLPos);
fh2V0LambdaMCResolMPt[iCentIndex]->Fill(dMassV0Lambda-dMassPDGLambda,dPtV0);
fh2V0LambdaMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a reconstructed candidate in jet
{
Double_t valueLInJCMC[4] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0LambdaInJetPtMassMCRec[iCentIndex]->Fill(valueLInJCMC);
Double_t valueEtaLIn[5] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0LambdaInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaLIn);
Double_t valueEtaDLJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLJCNeg);
Double_t valueEtaDLJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLJCPos);
}
}
// Fill the feed-down histograms
if (bV0MCIsLambda && bV0MCComesFromXi)
{
// if (fbTreeOutput)
// objectV0->SetOrigin(2);
Double_t valueFDLIncl[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),0.};
fhnV0LambdaInclMCFD[iCentIndex]->Fill(valueFDLIncl);
if (bIsInConeRnd)
{
fhnV0LambdaBulkMCFD[iCentIndex]->Fill(valueFDLIncl);
}
if (bIsInConeJet)
{
Double_t valueFDLInJets[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),jet->Pt()};
fhnV0LambdaInJetsMCFD[iCentIndex]->Fill(valueFDLInJets);
}
}
if (bV0MCIsLambda && !bV0MCIsPrimaryDist && !bV0MCComesFromXi) // not primary Lambda
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0LambdaPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
// anti-Lambda
// if (bIsCandidateALambda && bIsInPeakALambda) // selected candidates in peak
if (bIsCandidateALambda) // selected candidates with any mass
{
// if (bV0MCIsALambda && bV0MCIsPrimaryALambda) // well reconstructed candidates
if (bV0MCIsALambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0ALambdaPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0ALambda);
Double_t valueEtaAL[3] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen};
fh3V0ALambdaEtaPtMassMCRec[iCentIndex]->Fill(valueEtaAL);
Double_t valueEtaDALNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0ALambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALNeg);
Double_t valueEtaDALPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0ALambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALPos);
fh2V0ALambdaMCResolMPt[iCentIndex]->Fill(dMassV0ALambda-dMassPDGLambda,dPtV0);
fh2V0ALambdaMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a reconstructed candidate in jet
{
Double_t valueALInJCMC[4] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0ALambdaInJetPtMassMCRec[iCentIndex]->Fill(valueALInJCMC);
Double_t valueEtaALIn[5] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0ALambdaInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaALIn);
Double_t valueEtaDALJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALJCNeg);
Double_t valueEtaDALJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALJCPos);
}
}
// Fill the feed-down histograms
if (bV0MCIsALambda && bV0MCComesFromAXi)
{
// if (fbTreeOutput)
// objectV0->SetOrigin(2);
Double_t valueFDALIncl[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),0.};
fhnV0ALambdaInclMCFD[iCentIndex]->Fill(valueFDALIncl);
if (bIsInConeRnd)
{
fhnV0ALambdaBulkMCFD[iCentIndex]->Fill(valueFDALIncl);
}
if (bIsInConeJet)
{
Double_t valueFDALInJets[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),jet->Pt()};
fhnV0ALambdaInJetsMCFD[iCentIndex]->Fill(valueFDALInJets);
}
}
if (bV0MCIsALambda && !bV0MCIsPrimaryDist && !bV0MCComesFromAXi) // not primary anti-Lambda
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0ALambdaPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
}
/*===== End Association of reconstructed V0 candidates with MC particles =====*/
}
/*===== End of V0 loop =====*/
fh1V0CandPerEvent->Fill(iNV0CandTot);
fh1V0CandPerEventCentK0s[iCentIndex]->Fill(iNV0CandK0s);
fh1V0CandPerEventCentLambda[iCentIndex]->Fill(iNV0CandLambda);
fh1V0CandPerEventCentALambda[iCentIndex]->Fill(iNV0CandALambda);
if(fDebug>2) printf("TaskV0sInJets: End of V0 loop\n");
// Spectra of generated particles
if (fbMCAnalysis)
{
for (Int_t iPartMC = 0; iPartMC < iNTracksMC; iPartMC++)
{
// Get MC particle
AliAODMCParticle* particleMC = (AliAODMCParticle*)arrayMC->At(iPartMC);
if(!particleMC)
continue;
// Get identity of MC particle
Int_t iPdgCodeParticleMC = particleMC->GetPdgCode();
// Fill Xi spectrum (3322 - Xi0, 3312 - Xi-)
// if ( (iPdgCodeParticleMC==3322) || (iPdgCodeParticleMC==3312) )
if ( (iPdgCodeParticleMC==3312) && (TMath::Abs(particleMC->Y())<0.5) )
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0XiPtMCGen[iCentIndex]->Fill(particleMC->Pt());
}
if ( (iPdgCodeParticleMC==-3312) && (TMath::Abs(particleMC->Y())<0.5) )
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0AXiPtMCGen[iCentIndex]->Fill(particleMC->Pt());
}
// Skip not interesting particles
if ( (iPdgCodeParticleMC != iPdgCodeK0s) && (TMath::Abs(iPdgCodeParticleMC) != iPdgCodeLambda) )
continue;
// Check identity of the MC V0 particle
// Is MC V0 particle K0S?
Bool_t bV0MCIsK0s = (iPdgCodeParticleMC==iPdgCodeK0s);
// Is MC V0 particle Lambda?
Bool_t bV0MCIsLambda = (iPdgCodeParticleMC==+iPdgCodeLambda);
// Is MC V0 particle anti-Lambda?
Bool_t bV0MCIsALambda = (iPdgCodeParticleMC==-iPdgCodeLambda);
Double_t dPtV0Gen = particleMC->Pt();
Double_t dRapV0Gen = particleMC->Y();
Double_t dEtaV0Gen = particleMC->Eta();
// V0 rapidity cut
if (bCutRapV0)
{
if (bPrintCuts) printf("Gen: Applying cut: V0 |y|: < %f\n",dRapMax);
if ( (TMath::Abs(dRapV0Gen) > dRapMax) )
continue;
}
// V0 pseudorapidity cut
if (bCutEtaV0)
{
if (bPrintCuts) printf("Gen: Applying cut: V0 |eta|: < %f\n",dEtaMax);
if ( (TMath::Abs(dEtaV0Gen) > dEtaMax) )
continue;
}
/*
// Is MC V0 particle physical primary? Attention!! Definition of IsPhysicalPrimary may change!!
Bool_t bV0MCIsPrimary = particleMC->IsPhysicalPrimary();
// Get the MC mother particle of the MC V0 particle
Int_t iIndexMotherOfMother = particleMC->GetMother();
AliAODMCParticle* particleMCMotherOfMother = 0;
if (iIndexMotherOfMother >= 0)
particleMCMotherOfMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherOfMother);
// Get identity of the MC mother particle of the MC V0 particle if it exists
Int_t iPdgCodeMotherOfMother = 0;
if (particleMCMotherOfMother)
iPdgCodeMotherOfMother = particleMCMotherOfMother->GetPdgCode();
// Check if the MC mother particle is a physical primary Sigma
Bool_t bV0MCComesFromSigma = kFALSE;
if ((particleMCMotherOfMother && particleMCMotherOfMother->IsPhysicalPrimary()) && (TMath::Abs(iPdgCodeMotherOfMother)==3212) || (TMath::Abs(iPdgCodeMotherOfMother)==3224) || (TMath::Abs(iPdgCodeMotherOfMother)==3214) || (TMath::Abs(iPdgCodeMotherOfMother)==3114) )
bV0MCComesFromSigma = kTRUE;
// Should the MC V0 particle be considered as primary when it is Lambda?
Bool_t bV0MCIsPrimaryLambda = (bV0MCIsPrimary || bV0MCComesFromSigma);
*/
// Reject non primary particles
// if (!bV0MCIsPrimaryLambda)
// continue;
// Get the distance between the production point of the MC V0 particle and the primary vertex
Double_t dx = dPrimVtxMCX-particleMC->Xv();
Double_t dy = dPrimVtxMCY-particleMC->Yv();
Double_t dz = dPrimVtxMCZ-particleMC->Zv();
Double_t dDistPrimary = TMath::Sqrt(dx*dx + dy*dy + dz*dz);
Bool_t bV0MCIsPrimaryDist = (dDistPrimary < dDistPrimaryMax); // Is close enough to be considered primary-like?
// Check whether the MC V0 particle is in a MC jet
AliAODJet* jetMC = 0;
Bool_t bIsMCV0InJet = kFALSE;
if (iNJetSel)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for gen V0 in %d MC jets\n",iNJetSel);
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jetMC = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
if(fDebug>5) printf("TaskV0sInJets: Checking if gen V0 in MC jet %d\n",iJet);
if (IsParticleInCone(particleMC,jetMC,fdRadiusJet)) // If good jet in event, find out whether V0 is in that jet
{
if(fDebug>5) printf("TaskV0sInJets: gen V0 found in MC jet %d\n",iJet);
bIsMCV0InJet = kTRUE;
break;
}
}
}
// Select only primary-like MC V0 particles
// K0s
// if (bV0MCIsK0s && bV0MCIsPrimary) // well reconstructed candidates
if (bV0MCIsK0s && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0K0sPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0K0sEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0K0sInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaKInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0K0sInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaKInGen);
}
}
// Lambda
// if (bV0MCIsLambda && bV0MCIsPrimaryLambda) // well reconstructed candidates
if (bV0MCIsLambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0LambdaPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0LambdaEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0LambdaInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaLInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0LambdaInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaLInGen);
}
}
// anti-Lambda
// if (bV0MCIsALambda && bV0MCIsPrimaryALambda) // well reconstructed candidates
if (bV0MCIsALambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0ALambdaPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0ALambdaEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0ALambdaInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaALInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0ALambdaInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaALInGen);
}
}
}
}
// if (fbTreeOutput)
// ftreeOut->Fill();
jetArraySel->Delete();
delete jetArraySel;
jetArrayPerp->Delete();
delete jetArrayPerp;
if (jetRnd)
delete jetRnd;
jetRnd = 0;
PostData(1,fOutputListStd);
PostData(2,fOutputListQA);
PostData(3,fOutputListCuts);
PostData(4,fOutputListMC);
// if (fbTreeOutput)
// PostData(5,ftreeOut);
// if(fDebug>5) printf("TaskV0sInJets: UserExec: End\n");
}
void AliAnalysisTaskV0sInJets::FillQAHistogramV0(AliAODVertex* vtx, const AliAODv0* vZero, Int_t iIndexHisto, Bool_t IsCandK0s, Bool_t IsCandLambda, Bool_t IsInPeakK0s, Bool_t IsInPeakLambda)
{
if (!IsCandK0s && !IsCandLambda)
return;
// Double_t dMassK0s = vZero->MassK0Short();
// Double_t dMassLambda = vZero->MassLambda();
fh1QAV0Status[iIndexHisto]->Fill(vZero->GetOnFlyStatus());
AliAODTrack* trackNeg=(AliAODTrack*)vZero->GetDaughter(1); // negative track
AliAODTrack* trackPos=(AliAODTrack*)vZero->GetDaughter(0); // positive track
Short_t fTotalCharge = 0;
for (Int_t i = 0; i < 2; i++)
{
AliAODTrack* track = (AliAODTrack*)vZero->GetDaughter(i); // track
// Tracks TPC OK
fh1QAV0TPCRefit[iIndexHisto]->Fill(track->IsOn(AliAODTrack::kTPCrefit));
Double_t nCrossedRowsTPC = track->GetTPCClusterInfo(2,1);
fh1QAV0TPCRows[iIndexHisto]->Fill(nCrossedRowsTPC);
Int_t findable = track->GetTPCNclsF();
fh1QAV0TPCFindable[iIndexHisto]->Fill(findable);
if (findable != 0)
{
fh1QAV0TPCRowsFind[iIndexHisto]->Fill(nCrossedRowsTPC/findable);
}
// Daughters: pseudo-rapidity cut
fh1QAV0Eta[iIndexHisto]->Fill(track->Eta());
if ( (nCrossedRowsTPC > (160./(250.-85.)*(255.*TMath::Abs(tan(track->Theta()))-85.))+20.) && (track->Eta() < 0) && (track->Pt() > 0.15) )
// if (IsCandK0s)
{
fh2QAV0EtaRows[iIndexHisto]->Fill(track->Eta(),nCrossedRowsTPC);
fh2QAV0PtRows[iIndexHisto]->Fill(track->Pt(),nCrossedRowsTPC);
fh2QAV0PhiRows[iIndexHisto]->Fill(track->Phi(),nCrossedRowsTPC);
fh2QAV0NClRows[iIndexHisto]->Fill(findable,nCrossedRowsTPC);
fh2QAV0EtaNCl[iIndexHisto]->Fill(track->Eta(),findable);
}
// Daughters: transverse momentum cut
fh1QAV0Pt[iIndexHisto]->Fill(track->Pt());
fTotalCharge+=track->Charge();
}
fh1QAV0Charge[iIndexHisto]->Fill(fTotalCharge);
// Daughters: Impact parameter of daughters to prim vtx
fh1QAV0DCAVtx[iIndexHisto]->Fill(TMath::Abs(vZero->DcaNegToPrimVertex()));
fh1QAV0DCAVtx[iIndexHisto]->Fill(TMath::Abs(vZero->DcaPosToPrimVertex()));
// fh2CutDCAVtx[iIndexHisto]->Fill(dMassK0s,TMath::Abs(vZero->DcaNegToPrimVertex()));
// Daughters: DCA
fh1QAV0DCAV0[iIndexHisto]->Fill(vZero->DcaV0Daughters());
// fh2CutDCAV0[iIndexHisto]->Fill(dMassK0s,vZero->DcaV0Daughters());
// V0: Cosine of the pointing angle
fh1QAV0Cos[iIndexHisto]->Fill(vZero->CosPointingAngle(vtx));
// fh2CutCos[iIndexHisto]->Fill(dMassK0s,vZero->CosPointingAngle(vtx));
// V0: Fiducial volume
Double_t xyz[3];
vZero->GetSecondaryVtx(xyz);
Double_t r2=xyz[0]*xyz[0] + xyz[1]*xyz[1];
fh1QAV0R[iIndexHisto]->Fill(TMath::Sqrt(r2));
Double_t dAlpha = vZero->AlphaV0();
Double_t dPtArm = vZero->PtArmV0();
if (IsCandK0s)
{
if (IsInPeakK0s)
{
// fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(trackNeg->Eta(),vZero->Pt());
// fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(trackPos->Eta(),vZero->Pt());
fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(vZero->Eta(),vZero->Pt());
fh2QAV0PtPtK0sPeak[iIndexHisto]->Fill(trackNeg->Pt(),trackPos->Pt());
fh2ArmPodK0s[iIndexHisto]->Fill(dAlpha,dPtArm);
}
fh2QAV0EtaEtaK0s[iIndexHisto]->Fill(trackNeg->Eta(),trackPos->Eta());
fh2QAV0PhiPhiK0s[iIndexHisto]->Fill(trackNeg->Phi(),trackPos->Phi());
fh1QAV0RapK0s[iIndexHisto]->Fill(vZero->RapK0Short());
}
if (IsCandLambda)
{
if (IsInPeakLambda)
{
// fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(trackNeg->Eta(),vZero->Pt());
// fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(trackPos->Eta(),vZero->Pt());
fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(vZero->Eta(),vZero->Pt());
fh2QAV0PtPtLambdaPeak[iIndexHisto]->Fill(trackNeg->Pt(),trackPos->Pt());
fh2ArmPodLambda[iIndexHisto]->Fill(dAlpha,dPtArm);
}
fh2QAV0EtaEtaLambda[iIndexHisto]->Fill(trackNeg->Eta(),trackPos->Eta());
fh2QAV0PhiPhiLambda[iIndexHisto]->Fill(trackNeg->Phi(),trackPos->Phi());
fh1QAV0RapLambda[iIndexHisto]->Fill(vZero->RapLambda());
}
fh2ArmPod[iIndexHisto]->Fill(dAlpha,dPtArm);
}
void AliAnalysisTaskV0sInJets::FillCandidates(Double_t mK, Double_t mL, Double_t mAL, Bool_t isK, Bool_t isL, Bool_t isAL, Int_t iCut/*cut index*/, Int_t iCent/*cent index*/)
{
if (isK)
{
fh1V0CounterCentK0s[iCent]->Fill(iCut);
fh1V0InvMassK0sAll[iCut]->Fill(mK);
}
if (isL)
{
fh1V0CounterCentLambda[iCent]->Fill(iCut);
fh1V0InvMassLambdaAll[iCut]->Fill(mL);
}
if (isAL)
{
fh1V0CounterCentALambda[iCent]->Fill(iCut);
fh1V0InvMassALambdaAll[iCut]->Fill(mAL);
}
}
Bool_t AliAnalysisTaskV0sInJets::IsParticleInCone(const AliVParticle* part1, const AliVParticle* part2, Double_t dRMax) const
{
// decides whether a particle is inside a jet cone
if (!part1 || !part2)
return kFALSE;
TVector3 vecMom2(part2->Px(),part2->Py(),part2->Pz());
TVector3 vecMom1(part1->Px(),part1->Py(),part1->Pz());
Double_t dR = vecMom2.DeltaR(vecMom1); // = sqrt(dEta*dEta+dPhi*dPhi)
if(dR<dRMax) // momentum vectors of part1 and part2 are closer than dRMax
return kTRUE;
return kFALSE;
}
Bool_t AliAnalysisTaskV0sInJets::OverlapWithJets(const TClonesArray* array, const AliVParticle* part, Double_t dDistance) const
{
// decides whether a cone overlaps with other jets
if (!part)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: No part\n");
return kFALSE;
}
if (!array)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: No array\n");
return kFALSE;
}
Int_t iNJets = array->GetEntriesFast();
if (iNJets<=0)
{
if(fDebug>2) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Warning: No jets\n");
return kFALSE;
}
AliVParticle* jet = 0;
for (Int_t iJet=0; iJet<iNJets; iJet++)
{
jet = (AliVParticle*)array->At(iJet);
if (!jet)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: Failed to load jet %d/%d\n",iJet,iNJets);
continue;
}
if (IsParticleInCone(part,jet,dDistance))
return kTRUE;
}
return kFALSE;
}
AliAODJet* AliAnalysisTaskV0sInJets::GetRandomCone(const TClonesArray* array, Double_t dEtaConeMax, Double_t dDistance) const
{
// generate a random cone which does not overlap with selected jets
// printf("Generating random cone...\n");
TLorentzVector vecCone;
AliAODJet* part = 0;
Double_t dEta, dPhi;
Int_t iNTrialsMax = 10;
Bool_t bStatus = kFALSE;
for (Int_t iTry=0; iTry<iNTrialsMax; iTry++)
{
// printf("Try %d\n",iTry);
dEta = dEtaConeMax*(2*fRandom->Rndm()-1.); // random eta in [-dEtaConeMax,+dEtaConeMax]
dPhi = TMath::TwoPi()*fRandom->Rndm(); // random phi in [0,2*Pi]
vecCone.SetPtEtaPhiM(1.,dEta,dPhi,0.);
part = new AliAODJet(vecCone);
if (!OverlapWithJets(array,part,dDistance))
{
bStatus = kTRUE;
// printf("Success\n");
break;
}
else
delete part;
}
if (!bStatus)
part = 0;
return part;
}
AliAODJet* AliAnalysisTaskV0sInJets::GetMedianCluster(const TClonesArray* array, Double_t dEtaConeMax) const
{
// sort kt clusters according to pT/area and return the middle one, basic code taken from AliAnalysisTaskJetChem
if (!array)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::GetMedianCluster: Error: No array\n");
return NULL;
}
Int_t iNCl = array->GetEntriesFast();
if (iNCl<3) // need at least 3 clusters (skipping 2 highest)
{
if(fDebug>2) printf("AliAnalysisTaskV0sInJets::GetMedianCluster: Warning: Too little clusters\n");
return NULL;
}
// get list of densities
Double_t* dBgDensity = new Double_t[iNCl];
Int_t* iIndexList = new Int_t[iNCl];
for (Int_t ij=0; ij<iNCl; ij++)
{
AliAODJet* clusterBg = (AliAODJet*)(array->At(ij));
if (!clusterBg)
{
delete[] dBgDensity;
delete[] iIndexList;
return NULL;
}
Double_t dPtBg = clusterBg->Pt();
Double_t dAreaBg = clusterBg->EffectiveAreaCharged();
Double_t dDensityBg = 0;
if(dAreaBg>0)
dDensityBg = dPtBg/dAreaBg;
dBgDensity[ij] = dDensityBg;
iIndexList[ij] = ij;
}
// sort iIndexList according to descending dBgDensity
TMath::Sort(iNCl, dBgDensity, iIndexList);
// get median cluster with median density
AliAODJet* clusterMed = 0;
Int_t iIndexMed = 0;
if (TMath::Odd(iNCl)) // odd number of clusters
{
iIndexMed = iIndexList[(Int_t) (0.5*(iNCl+1))]; // = (n - skip + 1)/2 + 1, skip = 2
}
else // even number: picking randomly one of the two closest to median
{
Int_t iIndexMed1 = iIndexList[(Int_t) (0.5*iNCl)]; // = (n - skip)/2 + 1, skip = 2
iIndexMed = ( (fRandom->Rndm()>0.5) ? iIndexMed1 : (iIndexMed1+1) ); // select one randomly to avoid adding areas
}
clusterMed = (AliAODJet*)(array->At(iIndexMed));
delete[] dBgDensity;
delete[] iIndexList;
if (TMath::Abs(clusterMed->Eta())>dEtaConeMax)
return NULL;
return clusterMed;
}
Double_t AliAnalysisTaskV0sInJets::AreaCircSegment(Double_t dRadius, Double_t dDistance) const
{
// calculate area of a circular segment defined by the circle radius and the (oriented) distance between the secant line and the circle centre
Double_t dEpsilon = 1e-2;
Double_t dR = dRadius;
Double_t dD = dDistance;
if (TMath::Abs(dR)<dEpsilon)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::AreaCircSegment: Error: Too small radius: %f < %f\n",dR,dEpsilon);
return 0.;
}
if (dD>=dR)
return 0.;
if (dD<=-dR)
return TMath::Pi()*dR*dR;
return dR*dR*TMath::ACos(dD/dR)-dD*TMath::Sqrt(dR*dR-dD*dD);
}
Bool_t AliAnalysisTaskV0sInJets::IsSelectedForJets(AliAODEvent* fAOD, Double_t dVtxZCut, Double_t dVtxR2Cut, Double_t dCentCutLo, Double_t dCentCutUp, Bool_t bCutDeltaZ, Double_t dDeltaZMax)
{
// event selection
AliAODVertex* vertex = fAOD->GetPrimaryVertex();
if (!vertex)
return kFALSE;
if (vertex->GetNContributors() < 3)
return kFALSE;
TString vtxTitle(vertex->GetTitle());
if (vtxTitle.Contains("TPCVertex"))
return kFALSE;
Double_t zVertex = vertex->GetZ();
if (TMath::Abs(zVertex) > dVtxZCut)
return kFALSE;
if (bCutDeltaZ)
{
AliAODVertex* vertexSPD = fAOD->GetPrimaryVertexSPD();
if (!vertexSPD)
{
// printf("IsSelectedForJets: Error: No SPD vertex\n");
return kFALSE;
}
Double_t zVertexSPD = vertexSPD->GetZ();
if (TMath::Abs(zVertex-zVertexSPD) > dDeltaZMax)
{
// printf("IsSelectedForJets: Rejecting event due to delta z = %f - %f = %f\n",zVertex,zVertexSPD,zVertex-zVertexSPD);
return kFALSE;
}
// printf("IsSelectedForJets: Event OK: %f - %f = %f\n",zVertex,zVertexSPD,zVertex-zVertexSPD);
}
Double_t xVertex = vertex->GetX();
Double_t yVertex = vertex->GetY();
Double_t radiusSq = yVertex*yVertex+xVertex*xVertex;
if (radiusSq > dVtxR2Cut)
return kFALSE;
Double_t centrality;
// centrality = fAOD->GetHeader()->GetCentrality();
centrality = fAOD->GetHeader()->GetCentralityP()->GetCentralityPercentile("V0M");
if (centrality < 0)
return kFALSE;
if( (dCentCutUp < 0) || (dCentCutLo < 0) || (dCentCutUp > 100) || (dCentCutLo > 100) || (dCentCutLo > dCentCutUp) )
return kFALSE;
if ( (centrality < dCentCutLo) || (centrality > dCentCutUp) )
return kFALSE;
return kTRUE;
}
Int_t AliAnalysisTaskV0sInJets::GetCentralityBinIndex(Double_t centrality)
{
// returns index of the centrality bin corresponding to the provided value of centrality
if (centrality < 0 || centrality > fgkiCentBinRanges[fgkiNBinsCent-1])
return -1;
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
if (centrality <= fgkiCentBinRanges[i])
return i;
}
return -1;
}
Int_t AliAnalysisTaskV0sInJets::GetCentralityBinEdge(Int_t index)
{
// returns the upper edge of the centrality bin corresponding to the provided value of index
if (index < 0 || index >= fgkiNBinsCent)
return -1;
return fgkiCentBinRanges[index];
}
TString AliAnalysisTaskV0sInJets::GetCentBinLabel(Int_t index)
{
// get string with centrality range for given bin
TString lowerEdge = ( (index == 0) ? "0" : Form("%d",GetCentralityBinEdge(index-1)));
TString upperEdge = Form("%d",GetCentralityBinEdge(index));
return Form("%s-%s %%",lowerEdge.Data(),upperEdge.Data());
}
Double_t AliAnalysisTaskV0sInJets::MassPeakSigmaOld(Double_t pt, Int_t particle)
{
// estimation of the sigma of the invariant-mass peak as a function of pT and particle type
switch (particle)
{
case 0: // K0S
return 0.0044 + 0.0004*(pt - 1.);
break;
case 1: // Lambda
return 0.0023 + 0.00034*(pt - 1.);
break;
default:
return 0;
break;
}
}
Fixed bug in iIndexMed.
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// task for analysis of V0s (K0S, (anti-)Lambda) in charged jets
// Author: Vit Kucera (vit.kucera@cern.ch)
#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TH2D.h"
#include "THnSparse.h"
#include "TCanvas.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliAODTrack.h"
#include <TDatabasePDG.h>
#include <TPDGCode.h>
#include "AliPIDResponse.h"
#include "AliInputEventHandler.h"
#include "AliAODMCHeader.h"
#include "AliAODMCParticle.h"
#include "TClonesArray.h"
//#include "AliEventInfoObject.cxx"
//#include "AliV0Object.cxx"
//#include "AliJetObject.cxx"
#include "TRandom3.h"
#include "AliAnalysisTaskV0sInJets.h"
ClassImp(AliAnalysisTaskV0sInJets)
// upper edges of centrality bins
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10, 30, 50, 80}; // Alice Zimmermann
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10, 20, 40, 60, 80}; // Vit Kucera, initial binning
//const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {5, 10, 20, 40, 60, 80}; // Iouri Belikov, LF analysis
const Int_t AliAnalysisTaskV0sInJets::fgkiCentBinRanges[AliAnalysisTaskV0sInJets::fgkiNBinsCent] = {10}; // only central
// axis: pT of V0
const Double_t AliAnalysisTaskV0sInJets::fgkdBinsPtV0[2] = {0, 12};
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtV0 = sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtV0)/sizeof((AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[0])-1;
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtV0Init = int(((AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[AliAnalysisTaskV0sInJets::fgkiNBinsPtV0]-(AliAnalysisTaskV0sInJets::fgkdBinsPtV0)[0])/0.1); // bin width 0.1 GeV/c
// axis: pT of jets
const Double_t AliAnalysisTaskV0sInJets::fgkdBinsPtJet[2] = {0, 100};
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtJet = sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtJet)/sizeof(AliAnalysisTaskV0sInJets::fgkdBinsPtJet[0])-1;
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsPtJetInit = int(((AliAnalysisTaskV0sInJets::fgkdBinsPtJet)[AliAnalysisTaskV0sInJets::fgkiNBinsPtJet]-(AliAnalysisTaskV0sInJets::fgkdBinsPtJet)[0])/5.); // bin width 5 GeV/c
// axis: K0S invariant mass
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsMassK0s = 300;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassK0sMin = 0.35;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassK0sMax = 0.65;
// axis: Lambda invariant mass
const Int_t AliAnalysisTaskV0sInJets::fgkiNBinsMassLambda = 200;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassLambdaMin = 1.05;
const Double_t AliAnalysisTaskV0sInJets::fgkdMassLambdaMax = 1.25;
// Default constructor
AliAnalysisTaskV0sInJets::AliAnalysisTaskV0sInJets():
AliAnalysisTaskSE(),
fAODIn(0),
fAODOut(0),
fOutputListStd(0),
fOutputListQA(0),
fOutputListCuts(0),
fOutputListMC(0),
// ftreeOut(0),
fiAODAnalysis(1),
fdCutDCAToPrimVtxMin(0.1),
fdCutDCADaughtersMax(1.),
fdCutNSigmadEdxMax(3),
fdCutCPAMin(0.998),
fdCutNTauMax(5),
fsJetBranchName(0),
fsJetBgBranchName(0),
fdCutPtJetMin(0),
fdCutPtTrackMin(5),
fdRadiusJet(0.4),
fbJetSelection(0),
fbMCAnalysis(0),
// fbTreeOutput(0),
fRandom(0),
fdCutVertexZ(10),
fdCutVertexR2(1),
fdCutCentLow(0),
fdCutCentHigh(80),
/*
fBranchV0Rec(0),
fBranchV0Gen(0),
fBranchJet(0),
fEventInfo(0),
*/
fdCentrality(0),
fh1EventCounterCut(0),
fh1EventCent(0),
fh1EventCent2(0),
fh2EventCentTracks(0),
fh1V0CandPerEvent(0),
fh1NRndConeCent(0),
fh1NMedConeCent(0),
fh1AreaExcluded(0),
fh2CCK0s(0),
fh2CCLambda(0),
fh3CCMassCorrelBoth(0),
fh3CCMassCorrelKNotL(0),
fh3CCMassCorrelLNotK(0)
{
for (Int_t i =0; i < fgkiNQAIndeces; i++)
{
fh1QAV0Status[i] = 0;
fh1QAV0TPCRefit[i] = 0;
fh1QAV0TPCRows[i] = 0;
fh1QAV0TPCFindable[i] = 0;
fh1QAV0TPCRowsFind[i] = 0;
fh1QAV0Eta[i] = 0;
fh2QAV0EtaRows[i] = 0;
fh2QAV0PtRows[i] = 0;
fh2QAV0PhiRows[i] = 0;
fh2QAV0NClRows[i] = 0;
fh2QAV0EtaNCl[i] = 0;
fh2QAV0EtaPtK0sPeak[i] = 0;
fh2QAV0EtaEtaK0s[i] = 0;
fh2QAV0PhiPhiK0s[i] = 0;
fh1QAV0RapK0s[i] = 0;
fh2QAV0PtPtK0sPeak[i] = 0;
fh2ArmPodK0s[i] = 0;
fh2QAV0EtaPtLambdaPeak[i] = 0;
fh2QAV0EtaEtaLambda[i] = 0;
fh2QAV0PhiPhiLambda[i] = 0;
fh1QAV0RapLambda[i] = 0;
fh2QAV0PtPtLambdaPeak[i] = 0;
fh2ArmPodLambda[i] = 0;
fh2QAV0EtaPtALambdaPeak[i] = 0;
fh2QAV0EtaEtaALambda[i] = 0;
fh2QAV0PhiPhiALambda[i] = 0;
fh1QAV0RapALambda[i] = 0;
fh2QAV0PtPtALambdaPeak[i] = 0;
fh2ArmPodALambda[i] = 0;
fh1QAV0Pt[i] = 0;
fh1QAV0Charge[i] = 0;
fh1QAV0DCAVtx[i] = 0;
fh1QAV0DCAV0[i] = 0;
fh1QAV0Cos[i] = 0;
fh1QAV0R[i] = 0;
fh1QACTau2D[i] = 0;
fh1QACTau3D[i] = 0;
fh2ArmPod[i] = 0;
fh2CutTPCRowsK0s[i] = 0;
fh2CutTPCRowsLambda[i] = 0;
fh2CutPtPosK0s[i] = 0;
fh2CutPtNegK0s[i] = 0;
fh2CutPtPosLambda[i] = 0;
fh2CutPtNegLambda[i] = 0;
fh2CutDCAVtx[i] = 0;
fh2CutDCAV0[i] = 0;
fh2CutCos[i] = 0;
fh2CutR[i] = 0;
fh2CutEtaK0s[i] = 0;
fh2CutEtaLambda[i] = 0;
fh2CutRapK0s[i] = 0;
fh2CutRapLambda[i] = 0;
fh2CutCTauK0s[i] = 0;
fh2CutCTauLambda[i] = 0;
fh2CutPIDPosK0s[i] = 0;
fh2CutPIDNegK0s[i] = 0;
fh2CutPIDPosLambda[i] = 0;
fh2CutPIDNegLambda[i] = 0;
fh2Tau3DVs2D[i] = 0;
}
for (Int_t i = 0; i<fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = 0;
fh1V0InvMassLambdaAll[i] = 0;
fh1V0InvMassALambdaAll[i] = 0;
}
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = 0;
fh1V0CounterCentK0s[i] = 0;
fh1V0CounterCentLambda[i] = 0;
fh1V0CounterCentALambda[i] = 0;
fh1V0CandPerEventCentK0s[i] = 0;
fh1V0CandPerEventCentLambda[i] = 0;
fh1V0CandPerEventCentALambda[i] = 0;
fh1V0InvMassK0sCent[i] = 0;
fh1V0InvMassLambdaCent[i] = 0;
fh1V0InvMassALambdaCent[i] = 0;
fh1V0K0sPtMCGen[i] = 0;
fh2V0K0sPtMassMCRec[i] = 0;
fh1V0K0sPtMCRecFalse[i] = 0;
fh2V0K0sEtaPtMCGen[i] = 0;
fh3V0K0sEtaPtMassMCRec[i] = 0;
fh2V0K0sInJetPtMCGen[i] = 0;
fh3V0K0sInJetPtMassMCRec[i] = 0;
fh3V0K0sInJetEtaPtMCGen[i] = 0;
fh4V0K0sInJetEtaPtMassMCRec[i] = 0;
fh2V0K0sMCResolMPt[i] = 0;
fh2V0K0sMCPtGenPtRec[i] = 0;
fh1V0LambdaPtMCGen[i] = 0;
fh2V0LambdaPtMassMCRec[i] = 0;
fh1V0LambdaPtMCRecFalse[i] = 0;
fh2V0LambdaEtaPtMCGen[i] = 0;
fh3V0LambdaEtaPtMassMCRec[i] = 0;
fh2V0LambdaInJetPtMCGen[i] = 0;
fh3V0LambdaInJetPtMassMCRec[i] = 0;
fh3V0LambdaInJetEtaPtMCGen[i] = 0;
fh4V0LambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0LambdaMCResolMPt[i] = 0;
fh2V0LambdaMCPtGenPtRec[i] = 0;
fhnV0LambdaInclMCFD[i] = 0;
fhnV0LambdaInJetsMCFD[i] = 0;
fhnV0LambdaBulkMCFD[i] = 0;
fh1V0XiPtMCGen[i] = 0;
fh1V0ALambdaPt[i] = 0;
fh1V0ALambdaPtMCGen[i] = 0;
fh1V0ALambdaPtMCRec[i] = 0;
fh2V0ALambdaPtMassMCRec[i] = 0;
fh1V0ALambdaPtMCRecFalse[i] = 0;
fh2V0ALambdaEtaPtMCGen[i] = 0;
fh3V0ALambdaEtaPtMassMCRec[i] = 0;
fh2V0ALambdaInJetPtMCGen[i] = 0;
fh2V0ALambdaInJetPtMCRec[i] = 0;
fh3V0ALambdaInJetPtMassMCRec[i] = 0;
fh3V0ALambdaInJetEtaPtMCGen[i] = 0;
fh4V0ALambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0ALambdaMCResolMPt[i] = 0;
fh2V0ALambdaMCPtGenPtRec[i] = 0;
fhnV0ALambdaInclMCFD[i] = 0;
fhnV0ALambdaInJetsMCFD[i] = 0;
fhnV0ALambdaBulkMCFD[i] = 0;
fh1V0AXiPtMCGen[i] = 0;
// eta daughters
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// Inclusive
fhnV0InclusiveK0s[i] = 0;
fhnV0InclusiveLambda[i] = 0;
fhnV0InclusiveALambda[i] = 0;
// Cones
fhnV0InJetK0s[i] = 0;
fhnV0InPerpK0s[i] = 0;
fhnV0InRndK0s[i] = 0;
fhnV0InMedK0s[i] = 0;
fhnV0OutJetK0s[i] = 0;
fhnV0NoJetK0s[i] = 0;
fhnV0InJetLambda[i] = 0;
fhnV0InPerpLambda[i] = 0;
fhnV0InRndLambda[i] = 0;
fhnV0InMedLambda[i] = 0;
fhnV0OutJetLambda[i] = 0;
fhnV0NoJetLambda[i] = 0;
fhnV0InJetALambda[i] = 0;
fhnV0InPerpALambda[i] = 0;
fhnV0InRndALambda[i] = 0;
fhnV0InMedALambda[i] = 0;
fhnV0OutJetALambda[i] = 0;
fhnV0NoJetALambda[i] = 0;
fh2V0PtJetAngleK0s[i] = 0;
fh2V0PtJetAngleLambda[i] = 0;
fh2V0PtJetAngleALambda[i] = 0;
fh1DCAInK0s[i] = 0;
fh1DCAInLambda[i] = 0;
fh1DCAInALambda[i] = 0;
fh1DCAOutK0s[i] = 0;
fh1DCAOutLambda[i] = 0;
fh1DCAOutALambda[i] = 0;
fh1DeltaZK0s[i] = 0;
fh1DeltaZLambda[i] = 0;
fh1DeltaZALambda[i] = 0;
fh1PtJet[i] = 0;
fh1EtaJet[i] = 0;
fh2EtaPtJet[i] = 0;
fh1PhiJet[i] = 0;
fh1NJetPerEvent[i] = 0;
fh2EtaPhiRndCone[i] = 0;
fh2EtaPhiMedCone[i] = 0;
fh1VtxZ[i] = 0;
fh2VtxXY[i] = 0;
}
}
// Constructor
AliAnalysisTaskV0sInJets::AliAnalysisTaskV0sInJets(const char* name):
AliAnalysisTaskSE(name),
fAODIn(0),
fAODOut(0),
fOutputListStd(0),
fOutputListQA(0),
fOutputListCuts(0),
fOutputListMC(0),
// ftreeOut(0),
fiAODAnalysis(1),
fdCutDCAToPrimVtxMin(0.1),
fdCutDCADaughtersMax(1.),
fdCutNSigmadEdxMax(3),
fdCutCPAMin(0.998),
fdCutNTauMax(5),
fsJetBranchName(0),
fsJetBgBranchName(0),
fdCutPtJetMin(0),
fdCutPtTrackMin(5),
fdRadiusJet(0.4),
fbJetSelection(0),
fbMCAnalysis(0),
// fbTreeOutput(0),
fRandom(0),
fdCutVertexZ(10),
fdCutVertexR2(1),
fdCutCentLow(0),
fdCutCentHigh(80),
/*
fBranchV0Rec(0),
fBranchV0Gen(0),
fBranchJet(0),
fEventInfo(0),
*/
fdCentrality(0),
fh1EventCounterCut(0),
fh1EventCent(0),
fh1EventCent2(0),
fh2EventCentTracks(0),
fh1V0CandPerEvent(0),
fh1NRndConeCent(0),
fh1NMedConeCent(0),
fh1AreaExcluded(0),
fh2CCK0s(0),
fh2CCLambda(0),
fh3CCMassCorrelBoth(0),
fh3CCMassCorrelKNotL(0),
fh3CCMassCorrelLNotK(0)
{
for (Int_t i =0; i < fgkiNQAIndeces; i++)
{
fh1QAV0Status[i] = 0;
fh1QAV0TPCRefit[i] = 0;
fh1QAV0TPCRows[i] = 0;
fh1QAV0TPCFindable[i] = 0;
fh1QAV0TPCRowsFind[i] = 0;
fh1QAV0Eta[i] = 0;
fh2QAV0EtaRows[i] = 0;
fh2QAV0PtRows[i] = 0;
fh2QAV0PhiRows[i] = 0;
fh2QAV0NClRows[i] = 0;
fh2QAV0EtaNCl[i] = 0;
fh2QAV0EtaPtK0sPeak[i] = 0;
fh2QAV0EtaEtaK0s[i] = 0;
fh2QAV0PhiPhiK0s[i] = 0;
fh1QAV0RapK0s[i] = 0;
fh2QAV0PtPtK0sPeak[i] = 0;
fh2ArmPodK0s[i] = 0;
fh2QAV0EtaPtLambdaPeak[i] = 0;
fh2QAV0EtaEtaLambda[i] = 0;
fh2QAV0PhiPhiLambda[i] = 0;
fh1QAV0RapLambda[i] = 0;
fh2QAV0PtPtLambdaPeak[i] = 0;
fh2ArmPodLambda[i] = 0;
fh2QAV0EtaPtALambdaPeak[i] = 0;
fh2QAV0EtaEtaALambda[i] = 0;
fh2QAV0PhiPhiALambda[i] = 0;
fh1QAV0RapALambda[i] = 0;
fh2QAV0PtPtALambdaPeak[i] = 0;
fh2ArmPodALambda[i] = 0;
fh1QAV0Pt[i] = 0;
fh1QAV0Charge[i] = 0;
fh1QAV0DCAVtx[i] = 0;
fh1QAV0DCAV0[i] = 0;
fh1QAV0Cos[i] = 0;
fh1QAV0R[i] = 0;
fh1QACTau2D[i] = 0;
fh1QACTau3D[i] = 0;
fh2ArmPod[i] = 0;
fh2CutTPCRowsK0s[i] = 0;
fh2CutTPCRowsLambda[i] = 0;
fh2CutPtPosK0s[i] = 0;
fh2CutPtNegK0s[i] = 0;
fh2CutPtPosLambda[i] = 0;
fh2CutPtNegLambda[i] = 0;
fh2CutDCAVtx[i] = 0;
fh2CutDCAV0[i] = 0;
fh2CutCos[i] = 0;
fh2CutR[i] = 0;
fh2CutEtaK0s[i] = 0;
fh2CutEtaLambda[i] = 0;
fh2CutRapK0s[i] = 0;
fh2CutRapLambda[i] = 0;
fh2CutCTauK0s[i] = 0;
fh2CutCTauLambda[i] = 0;
fh2CutPIDPosK0s[i] = 0;
fh2CutPIDNegK0s[i] = 0;
fh2CutPIDPosLambda[i] = 0;
fh2CutPIDNegLambda[i] = 0;
fh2Tau3DVs2D[i] = 0;
}
for (Int_t i = 0; i<fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = 0;
fh1V0InvMassLambdaAll[i] = 0;
fh1V0InvMassALambdaAll[i] = 0;
}
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = 0;
fh1V0CounterCentK0s[i] = 0;
fh1V0CounterCentLambda[i] = 0;
fh1V0CounterCentALambda[i] = 0;
fh1V0CandPerEventCentK0s[i] = 0;
fh1V0CandPerEventCentLambda[i] = 0;
fh1V0CandPerEventCentALambda[i] = 0;
fh1V0InvMassK0sCent[i] = 0;
fh1V0InvMassLambdaCent[i] = 0;
fh1V0InvMassALambdaCent[i] = 0;
fh1V0K0sPtMCGen[i] = 0;
fh2V0K0sPtMassMCRec[i] = 0;
fh1V0K0sPtMCRecFalse[i] = 0;
fh2V0K0sEtaPtMCGen[i] = 0;
fh3V0K0sEtaPtMassMCRec[i] = 0;
fh2V0K0sInJetPtMCGen[i] = 0;
fh3V0K0sInJetPtMassMCRec[i] = 0;
fh3V0K0sInJetEtaPtMCGen[i] = 0;
fh4V0K0sInJetEtaPtMassMCRec[i] = 0;
fh2V0K0sMCResolMPt[i] = 0;
fh2V0K0sMCPtGenPtRec[i] = 0;
fh1V0LambdaPtMCGen[i] = 0;
fh2V0LambdaPtMassMCRec[i] = 0;
fh1V0LambdaPtMCRecFalse[i] = 0;
fh2V0LambdaEtaPtMCGen[i] = 0;
fh3V0LambdaEtaPtMassMCRec[i] = 0;
fh2V0LambdaInJetPtMCGen[i] = 0;
fh3V0LambdaInJetPtMassMCRec[i] = 0;
fh3V0LambdaInJetEtaPtMCGen[i] = 0;
fh4V0LambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0LambdaMCResolMPt[i] = 0;
fh2V0LambdaMCPtGenPtRec[i] = 0;
fhnV0LambdaInclMCFD[i] = 0;
fhnV0LambdaInJetsMCFD[i] = 0;
fhnV0LambdaBulkMCFD[i] = 0;
fh1V0XiPtMCGen[i] = 0;
fh1V0ALambdaPt[i] = 0;
fh1V0ALambdaPtMCGen[i] = 0;
fh1V0ALambdaPtMCRec[i] = 0;
fh2V0ALambdaPtMassMCRec[i] = 0;
fh1V0ALambdaPtMCRecFalse[i] = 0;
fh2V0ALambdaEtaPtMCGen[i] = 0;
fh3V0ALambdaEtaPtMassMCRec[i] = 0;
fh2V0ALambdaInJetPtMCGen[i] = 0;
fh2V0ALambdaInJetPtMCRec[i] = 0;
fh3V0ALambdaInJetPtMassMCRec[i] = 0;
fh3V0ALambdaInJetEtaPtMCGen[i] = 0;
fh4V0ALambdaInJetEtaPtMassMCRec[i] = 0;
fh2V0ALambdaMCResolMPt[i] = 0;
fh2V0ALambdaMCPtGenPtRec[i] = 0;
fhnV0ALambdaInclMCFD[i] = 0;
fhnV0ALambdaInJetsMCFD[i] = 0;
fhnV0ALambdaBulkMCFD[i] = 0;
fh1V0AXiPtMCGen[i] = 0;
// eta daughters
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = 0;
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = 0;
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = 0;
// Inclusive
fhnV0InclusiveK0s[i] = 0;
fhnV0InclusiveLambda[i] = 0;
fhnV0InclusiveALambda[i] = 0;
// Cones
fhnV0InJetK0s[i] = 0;
fhnV0InPerpK0s[i] = 0;
fhnV0InRndK0s[i] = 0;
fhnV0InMedK0s[i] = 0;
fhnV0OutJetK0s[i] = 0;
fhnV0NoJetK0s[i] = 0;
fhnV0InJetLambda[i] = 0;
fhnV0InPerpLambda[i] = 0;
fhnV0InRndLambda[i] = 0;
fhnV0InMedLambda[i] = 0;
fhnV0OutJetLambda[i] = 0;
fhnV0NoJetLambda[i] = 0;
fhnV0InJetALambda[i] = 0;
fhnV0InPerpALambda[i] = 0;
fhnV0InRndALambda[i] = 0;
fhnV0InMedALambda[i] = 0;
fhnV0OutJetALambda[i] = 0;
fhnV0NoJetALambda[i] = 0;
fh2V0PtJetAngleK0s[i] = 0;
fh2V0PtJetAngleLambda[i] = 0;
fh2V0PtJetAngleALambda[i] = 0;
fh1DCAInK0s[i] = 0;
fh1DCAInLambda[i] = 0;
fh1DCAInALambda[i] = 0;
fh1DCAOutK0s[i] = 0;
fh1DCAOutLambda[i] = 0;
fh1DCAOutALambda[i] = 0;
fh1DeltaZK0s[i] = 0;
fh1DeltaZLambda[i] = 0;
fh1DeltaZALambda[i] = 0;
fh1PtJet[i] = 0;
fh1EtaJet[i] = 0;
fh2EtaPtJet[i] = 0;
fh1PhiJet[i] = 0;
fh1NJetPerEvent[i] = 0;
fh2EtaPhiRndCone[i] = 0;
fh2EtaPhiMedCone[i] = 0;
fh1VtxZ[i] = 0;
fh2VtxXY[i] = 0;
}
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TList container
DefineOutput(1, TList::Class());
DefineOutput(2, TList::Class());
DefineOutput(3, TList::Class());
DefineOutput(4, TList::Class());
DefineOutput(5, TTree::Class());
}
AliAnalysisTaskV0sInJets::~AliAnalysisTaskV0sInJets()
{
/*
if (fBranchV0Rec)
fBranchV0Rec->Delete();
delete fBranchV0Rec;
fBranchV0Rec = 0;
if (fBranchV0Gen)
fBranchV0Gen->Delete();
delete fBranchV0Gen;
fBranchV0Gen = 0;
if (fBranchJet)
fBranchJet->Delete();
delete fBranchJet;
fBranchJet = 0;
if (fEventInfo)
fEventInfo->Delete();
delete fEventInfo;
fEventInfo = 0;
*/
delete fRandom;
fRandom = 0;
}
void AliAnalysisTaskV0sInJets::UserCreateOutputObjects()
{
// Create histograms
// Called once
fRandom = new TRandom3(0);
/*
if (!fBranchV0Rec && fbTreeOutput)
{
// fBranchV0Rec = new TClonesArray("AliAODv0",0);
fBranchV0Rec = new TClonesArray("AliV0Object",0);
fBranchV0Rec->SetName("branch_V0Rec");
}
if (!fBranchV0Gen && fbTreeOutput)
{
fBranchV0Gen = new TClonesArray("AliAODMCParticle",0);
fBranchV0Gen->SetName("branch_V0Gen");
}
if (!fBranchJet && fbTreeOutput)
{
// fBranchJet = new TClonesArray("AliAODJet",0);
fBranchJet = new TClonesArray("AliJetObject",0);
fBranchJet->SetName("branch_Jet");
}
if (!fEventInfo && fbTreeOutput)
{
fEventInfo = new AliEventInfoObject();
fEventInfo->SetName("eventInfo");
}
Int_t dSizeBuffer = 32000; // default 32000
if (fbTreeOutput)
{
ftreeOut = new TTree("treeV0","Tree V0");
ftreeOut->Branch("branch_V0Rec",&fBranchV0Rec,dSizeBuffer,2);
ftreeOut->Branch("branch_V0Gen",&fBranchV0Gen,dSizeBuffer,2);
ftreeOut->Branch("branch_Jet",&fBranchJet,dSizeBuffer,2);
ftreeOut->Branch("eventInfo",&fEventInfo,dSizeBuffer,2);
}
*/
fOutputListStd = new TList();
fOutputListStd->SetOwner();
fOutputListQA = new TList();
fOutputListQA->SetOwner();
fOutputListCuts = new TList();
fOutputListCuts->SetOwner();
fOutputListMC = new TList();
fOutputListMC->SetOwner();
// event categories
const Int_t iNCategEvent = 6;
TString categEvent[iNCategEvent] = {"coll. candid.","AOD OK","vtx & cent","with V0","with jets","jet selection"};
// labels for stages of V0 selection
TString categV0[fgkiNCategV0] = {"all"/*0*/,"mass range"/*1*/,"rec. method"/*2*/,"tracks TPC"/*3*/,"track pt"/*4*/,"DCA prim v"/*5*/,"DCA daughters"/*6*/,"CPA"/*7*/,"volume"/*8*/,"track #it{#eta}"/*9*/,"V0 #it{y} & #it{#eta}"/*10*/,"lifetime"/*11*/,"PID"/*12*/,"Arm.-Pod."/*13*/,"inclusive"/*14*/,"in jet event"/*15*/,"in jet"/*16*/};
fh1EventCounterCut = new TH1D("fh1EventCounterCut","Number of events after filtering;selection filter;counts",iNCategEvent,0,iNCategEvent);
for (Int_t i = 0; i < iNCategEvent; i++)
fh1EventCounterCut->GetXaxis()->SetBinLabel(i+1,categEvent[i].Data());
fh1EventCent2 = new TH1D("fh1EventCent2","Number of events vs centrality;centrality;counts",100,0,100);
fh2EventCentTracks = new TH2D("fh2EventCentTracks","Number of tracks vs centrality;centrality;tracks;counts",100,0,100,150,0,15e3);
fh1EventCent = new TH1D("fh1EventCent","Number of events in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1EventCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1NRndConeCent = new TH1D("fh1NRndConeCent","Number of rnd. cones in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1NRndConeCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1NMedConeCent = new TH1D("fh1NMedConeCent","Number of med.-cl. cones in centrality bins;centrality;counts",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1NMedConeCent->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fh1AreaExcluded = new TH1D("fh1AreaExcluded","Area of excluded cones in centrality bins;centrality;area",fgkiNBinsCent,0,fgkiNBinsCent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
fh1AreaExcluded->GetXaxis()->SetBinLabel(i+1,GetCentBinLabel(i).Data());
fOutputListStd->Add(fh1EventCounterCut);
fOutputListStd->Add(fh1EventCent);
fOutputListStd->Add(fh1EventCent2);
fOutputListStd->Add(fh1NRndConeCent);
fOutputListStd->Add(fh1NMedConeCent);
fOutputListStd->Add(fh1AreaExcluded);
fOutputListStd->Add(fh2EventCentTracks);
fh1V0CandPerEvent = new TH1D("fh1V0CandPerEvent","Number of all V0 candidates per event;candidates;events",1000,0,1000);
fOutputListStd->Add(fh1V0CandPerEvent);
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1EventCounterCutCent[i] = new TH1D(Form("fh1EventCounterCutCent_%d",i),Form("Number of events after filtering, cent %s;selection filter;counts",GetCentBinLabel(i).Data()),iNCategEvent,0,iNCategEvent);
for (Int_t j = 0; j < iNCategEvent; j++)
fh1EventCounterCutCent[i]->GetXaxis()->SetBinLabel(j+1,categEvent[j].Data());
fh1V0CandPerEventCentK0s[i] = new TH1D(Form("fh1V0CandPerEventCentK0s_%d",i),Form("Number of selected K0s candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CandPerEventCentLambda[i] = new TH1D(Form("fh1V0CandPerEventCentLambda_%d",i),Form("Number of selected Lambda candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CandPerEventCentALambda[i] = new TH1D(Form("fh1V0CandPerEventCentALambda_%d",i),Form("Number of selected ALambda candidates per event, cent %s;candidates;events",GetCentBinLabel(i).Data()),100,0,100);
fh1V0CounterCentK0s[i] = new TH1D(Form("fh1V0CounterCentK0s_%d",i),Form("Number of K0s candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
fh1V0CounterCentLambda[i] = new TH1D(Form("fh1V0CounterCentLambda_%d",i),Form("Number of Lambda candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
fh1V0CounterCentALambda[i] = new TH1D(Form("fh1V0CounterCentALambda_%d",i),Form("Number of ALambda candidates after cuts, cent %s;cut;counts",GetCentBinLabel(i).Data()),fgkiNCategV0,0,fgkiNCategV0);
for (Int_t j = 0; j < fgkiNCategV0; j++)
{
fh1V0CounterCentK0s[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
fh1V0CounterCentLambda[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
fh1V0CounterCentALambda[i]->GetXaxis()->SetBinLabel(j+1,categV0[j].Data());
}
fOutputListStd->Add(fh1EventCounterCutCent[i]);
fOutputListStd->Add(fh1V0CandPerEventCentK0s[i]);
fOutputListStd->Add(fh1V0CandPerEventCentLambda[i]);
fOutputListStd->Add(fh1V0CandPerEventCentALambda[i]);
fOutputListStd->Add(fh1V0CounterCentK0s[i]);
fOutputListStd->Add(fh1V0CounterCentLambda[i]);
fOutputListStd->Add(fh1V0CounterCentALambda[i]);
}
// pt binning for V0 and jets
Int_t iNBinsPtV0 = fgkiNBinsPtV0Init;
Double_t dPtV0Min = fgkdBinsPtV0[0];
Double_t dPtV0Max = fgkdBinsPtV0[fgkiNBinsPtV0];
Int_t iNJetPtBins = fgkiNBinsPtJetInit;
Double_t dJetPtMin = fgkdBinsPtJet[0];
Double_t dJetPtMax = fgkdBinsPtJet[fgkiNBinsPtJet];
fh2CCK0s = new TH2D("fh2CCK0s","K0s candidates in Lambda peak",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2CCLambda = new TH2D("fh2CCLambda","Lambda candidates in K0s peak",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,iNBinsPtV0,dPtV0Min,dPtV0Max);
Int_t binsCorrel[3] = {fgkiNBinsMassK0s, fgkiNBinsMassLambda, iNBinsPtV0};
Double_t xminCorrel[3] = {fgkdMassK0sMin, fgkdMassLambdaMin, dPtV0Min};
Double_t xmaxCorrel[3] = {fgkdMassK0sMax, fgkdMassLambdaMax, dPtV0Max};
// Int_t binsCorrel[3] = {200, 200, iNBinsPtV0};
// Double_t xminCorrel[3] = {0, 0, dPtV0Min};
// Double_t xmaxCorrel[3] = {2, 2, dPtV0Max};
fh3CCMassCorrelBoth = new THnSparseD("fh3CCMassCorrelBoth","Mass correlation: K0S && Lambda;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fh3CCMassCorrelKNotL = new THnSparseD("fh3CCMassCorrelKNotL","Mass correlation: K0S, not Lambda;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fh3CCMassCorrelLNotK = new THnSparseD("fh3CCMassCorrelLNotK","Mass correlation: Lambda, not K0S;m K0S;m Lambda;pT",3,binsCorrel,xminCorrel,xmaxCorrel);
fOutputListQA->Add(fh2CCK0s);
fOutputListQA->Add(fh2CCLambda);
fOutputListQA->Add(fh3CCMassCorrelBoth);
fOutputListQA->Add(fh3CCMassCorrelKNotL);
fOutputListQA->Add(fh3CCMassCorrelLNotK);
Double_t dStepEtaV0 = 0.025;
Double_t dRangeEtaV0Max = 0.8;
const Int_t iNBinsEtaV0 = 2*Int_t(dRangeEtaV0Max/dStepEtaV0);
// inclusive
const Int_t iNDimIncl = 3;
Int_t binsKIncl[iNDimIncl] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0};
Double_t xminKIncl[iNDimIncl] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxKIncl[iNDimIncl] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max};
Int_t binsLIncl[iNDimIncl] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0};
Double_t xminLIncl[iNDimIncl] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxLIncl[iNDimIncl] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max};
// binning in jets
const Int_t iNDimInJC = 4;
Int_t binsKInJC[iNDimInJC] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins};
Double_t xminKInJC[iNDimInJC] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin};
Double_t xmaxKInJC[iNDimInJC] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax};
Int_t binsLInJC[iNDimInJC] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins};
Double_t xminLInJC[iNDimInJC] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin};
Double_t xmaxLInJC[iNDimInJC] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax};
// binning eff inclusive vs eta-pT
Double_t dStepDeltaEta = 0.1;
Double_t dRangeDeltaEtaMax = 0.5;
const Int_t iNBinsDeltaEta = 2*Int_t(dRangeDeltaEtaMax/dStepDeltaEta);
Int_t binsEtaK[3] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0};
Double_t xminEtaK[3] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxEtaK[3] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max};
Int_t binsEtaL[3] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0};
Double_t xminEtaL[3] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max};
Double_t xmaxEtaL[3] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max};
// binning eff in jets vs eta-pT
// associated
Int_t binsEtaKInRec[5] = {fgkiNBinsMassK0s, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaKInRec[5] = {fgkdMassK0sMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaKInRec[5] = {fgkdMassK0sMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
Int_t binsEtaLInRec[5] = {fgkiNBinsMassLambda, iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaLInRec[5] = {fgkdMassLambdaMin, dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaLInRec[5] = {fgkdMassLambdaMax, dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
// generated
Int_t binsEtaInGen[4] = {iNBinsPtV0, iNBinsEtaV0, iNJetPtBins, iNBinsDeltaEta};
Double_t xminEtaInGen[4] = {dPtV0Min, -dRangeEtaV0Max, dJetPtMin, -dRangeDeltaEtaMax};
Double_t xmaxEtaInGen[4] = {dPtV0Max, dRangeEtaV0Max, dJetPtMax, dRangeDeltaEtaMax};
// daughter eta: charge-etaD-ptD-etaV0-ptV0-ptJet
const Int_t iNDimEtaD = 6;
Int_t binsEtaDaughter[iNDimEtaD] = {2, 20, iNBinsPtV0, iNBinsEtaV0, iNBinsPtV0, iNJetPtBins};
Double_t xminEtaDaughter[iNDimEtaD] = {0, -1, dPtV0Min, -dRangeEtaV0Max, dPtV0Min, dJetPtMin};
Double_t xmaxEtaDaughter[iNDimEtaD] = {2, 1, dPtV0Max, dRangeEtaV0Max, dPtV0Max, dJetPtMax};
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
fh1V0InvMassK0sCent[i] = new TH1D(Form("fh1V0InvMassK0sCent_%d",i),Form("K0s: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fh1V0InvMassLambdaCent[i] = new TH1D(Form("fh1V0InvMassLambdaCent_%d",i),Form("Lambda: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fh1V0InvMassALambdaCent[i] = new TH1D(Form("fh1V0InvMassALambdaCent_%d",i),Form("ALambda: V0 invariant mass, cent %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",GetCentBinLabel(i).Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListStd->Add(fh1V0InvMassK0sCent[i]);
fOutputListStd->Add(fh1V0InvMassLambdaCent[i]);
fOutputListStd->Add(fh1V0InvMassALambdaCent[i]);
// Inclusive
fhnV0InclusiveK0s[i] = new THnSparseD(Form("fhnV0InclusiveK0s_C%d",i), "K0s: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fhnV0InclusiveLambda[i] = new THnSparseD(Form("fhnV0InclusiveLambda_C%d",i), "Lambda: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fhnV0InclusiveALambda[i] = new THnSparseD(Form("fhnV0InclusiveALambda_C%d",i), "ALambda: V0 invariant mass vs pt;#it{m}_{inv} (GeV/#it{c}^{2});pt (GeV/#it{c});counts",iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InclusiveK0s[i]);
fOutputListStd->Add(fhnV0InclusiveLambda[i]);
fOutputListStd->Add(fhnV0InclusiveALambda[i]);
// In cones
fhnV0InJetK0s[i] = new THnSparseD(Form("fhnV0InJetK0s_%d",i),Form("K0s: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListStd->Add(fhnV0InJetK0s[i]);
fhnV0InPerpK0s[i] = new THnSparseD(Form("fhnV0InPerpK0s_%d",i),Form("K0s: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListStd->Add(fhnV0InPerpK0s[i]);
fhnV0InRndK0s[i] = new THnSparseD(Form("fhnV0InRndK0s_%d",i),Form("K0s: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0InRndK0s[i]);
fhnV0InMedK0s[i] = new THnSparseD(Form("fhnV0InMedK0s_%d",i),Form("K0s: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0InMedK0s[i]);
fhnV0OutJetK0s[i] = new THnSparseD(Form("fhnV0OutJetK0s_%d",i),Form("K0s: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0OutJetK0s[i]);
fhnV0NoJetK0s[i] = new THnSparseD(Form("fhnV0NoJetK0s_%d",i),Form("K0s: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsKIncl,xminKIncl,xmaxKIncl);
fOutputListStd->Add(fhnV0NoJetK0s[i]);
fhnV0InJetLambda[i] = new THnSparseD(Form("fhnV0InJetLambda_%d",i),Form("Lambda: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InJetLambda[i]);
fhnV0InPerpLambda[i] = new THnSparseD(Form("fhnV0InPerpLambda_%d",i),Form("Lambda: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InPerpLambda[i]);
fhnV0InRndLambda[i] = new THnSparseD(Form("fhnV0InRndLambda_%d",i),Form("Lambda: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InRndLambda[i]);
fhnV0InMedLambda[i] = new THnSparseD(Form("fhnV0InMedLambda_%d",i),Form("Lambda: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InMedLambda[i]);
fhnV0OutJetLambda[i] = new THnSparseD(Form("fhnV0OutJetLambda_%d",i),Form("Lambda: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0OutJetLambda[i]);
fhnV0NoJetLambda[i] = new THnSparseD(Form("fhnV0NoJetLambda_%d",i),Form("Lambda: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0NoJetLambda[i]);
fhnV0InJetALambda[i] = new THnSparseD(Form("fhnV0InJetALambda_%d",i),Form("ALambda: Mass vs Pt in jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InJetALambda[i]);
fhnV0InPerpALambda[i] = new THnSparseD(Form("fhnV0InPerpALambda_%d",i),Form("ALambda: Mass vs Pt in perp. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListStd->Add(fhnV0InPerpALambda[i]);
fhnV0InRndALambda[i] = new THnSparseD(Form("fhnV0InRndALambda_%d",i),Form("ALambda: Mass vs Pt in rnd. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InRndALambda[i]);
fhnV0InMedALambda[i] = new THnSparseD(Form("fhnV0InMedALambda_%d",i),Form("ALambda: Mass vs Pt in med.-cl. cones, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0InMedALambda[i]);
fhnV0OutJetALambda[i] = new THnSparseD(Form("fhnV0OutJetALambda_%d",i),Form("ALambda: Pt outside jets, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0OutJetALambda[i]);
fhnV0NoJetALambda[i] = new THnSparseD(Form("fhnV0NoJetALambda_%d",i),Form("ALambda: Pt in jet-less events, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});#it{p}_{T}^{V0} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimIncl,binsLIncl,xminLIncl,xmaxLIncl);
fOutputListStd->Add(fhnV0NoJetALambda[i]);
fh2V0PtJetAngleK0s[i] = new TH2D(Form("fh2V0PtJetAngleK0s_%d",i),Form("K0s: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleK0s[i]);
fh2V0PtJetAngleLambda[i] = new TH2D(Form("fh2V0PtJetAngleLambda_%d",i),Form("Lambda: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleLambda[i]);
fh2V0PtJetAngleALambda[i] = new TH2D(Form("fh2V0PtJetAngleALambda_%d",i),Form("ALambda: #it{p}_{T}^{jet} vs angle V0-jet, cent: %s;#it{p}_{T}^{jet};#it{#alpha}",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax,100,0,fdRadiusJet+0.1);
fOutputListStd->Add(fh2V0PtJetAngleALambda[i]);
fh1DCAInK0s[i] = new TH1D(Form("fh1DCAInK0s_%d",i),Form("K0s in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInK0s[i]);
fh1DCAInLambda[i] = new TH1D(Form("fh1DCAInLambda_%d",i),Form("Lambda in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInLambda[i]);
fh1DCAInALambda[i] = new TH1D(Form("fh1DCAInALambda_%d",i),Form("ALambda in jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAInALambda[i]);
fh1DCAOutK0s[i] = new TH1D(Form("fh1DCAOutK0s_%d",i),Form("K0s outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutK0s[i]);
fh1DCAOutLambda[i] = new TH1D(Form("fh1DCAOutLambda_%d",i),Form("Lambda outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutLambda[i]);
fh1DCAOutALambda[i] = new TH1D(Form("fh1DCAOutALambda_%d",i),Form("ALambda outside jets: DCA daughters, cent %s;DCA (#sigma)",GetCentBinLabel(i).Data()),50,0,1);
fOutputListQA->Add(fh1DCAOutALambda[i]);
fh1DeltaZK0s[i] = new TH1D(Form("fh1DeltaZK0s_%d",i),Form("K0s: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZK0s[i]);
fh1DeltaZLambda[i] = new TH1D(Form("fh1DeltaZLambda_%d",i),Form("Lambda: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZLambda[i]);
fh1DeltaZALambda[i] = new TH1D(Form("fh1DeltaZALambda_%d",i),Form("ALambda: #Delta#it{z} vertices, cent %s;#it{z} (cm)",GetCentBinLabel(i).Data()),50,-10,10);
fOutputListQA->Add(fh1DeltaZALambda[i]);
// jet histograms
fh1PtJet[i] = new TH1D(Form("fh1PtJet_%d",i),Form("Jet pt spectrum, cent: %s;#it{p}_{T} jet (GeV/#it{c})",GetCentBinLabel(i).Data()),iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListStd->Add(fh1PtJet[i]);
fh1EtaJet[i] = new TH1D(Form("fh1EtaJet_%d",i),Form("Jet eta spectrum, cent: %s;#it{#eta} jet",GetCentBinLabel(i).Data()),80,-1.,1.);
fOutputListStd->Add(fh1EtaJet[i]);
fh2EtaPtJet[i] = new TH2D(Form("fh2EtaPtJet_%d",i),Form("Jet eta vs pT spectrum, cent: %s;#it{#eta} jet;#it{p}_{T} jet (GeV/#it{c})",GetCentBinLabel(i).Data()),80,-1.,1.,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListStd->Add(fh2EtaPtJet[i]);
fh2EtaPhiRndCone[i] = new TH2D(Form("fh2EtaPhiRndCone_%d",i),Form("Rnd. cones: eta vs phi, cent: %s;#it{#eta} cone;#it{#phi} cone",GetCentBinLabel(i).Data()),80,-1.,1.,100,0.,TMath::TwoPi());
fOutputListStd->Add(fh2EtaPhiRndCone[i]);
fh2EtaPhiMedCone[i] = new TH2D(Form("fh2EtaPhiMedCone_%d",i),Form("Med.-cl. cones: eta vs phi, cent: %s;#it{#eta} cone;#it{#phi} cone",GetCentBinLabel(i).Data()),80,-1.,1.,100,0.,TMath::TwoPi());
fOutputListStd->Add(fh2EtaPhiMedCone[i]);
fh1PhiJet[i] = new TH1D(Form("fh1PhiJet_%d",i),Form("Jet phi spectrum, cent: %s;#it{#phi} jet",GetCentBinLabel(i).Data()),100,0.,TMath::TwoPi());
fOutputListStd->Add(fh1PhiJet[i]);
fh1NJetPerEvent[i] = new TH1D(Form("fh1NJetPerEvent_%d",i),Form("Number of selected jets per event, cent: %s;# jets;# events",GetCentBinLabel(i).Data()),100,0.,100.);
fOutputListStd->Add(fh1NJetPerEvent[i]);
// event histograms
fh1VtxZ[i] = new TH1D(Form("fh1VtxZ_%d",i),Form("#it{z} coordinate of the primary vertex, cent: %s;#it{z} (cm)",GetCentBinLabel(i).Data()),150,-1.5*fdCutVertexZ,1.5*fdCutVertexZ);
fOutputListQA->Add(fh1VtxZ[i]);
fh2VtxXY[i] = new TH2D(Form("fh2VtxXY_%d",i),Form("#it{xy} coordinate of the primary vertex, cent: %s;#it{x} (cm);#it{y} (cm)",GetCentBinLabel(i).Data()),200,-0.2,0.2,500,-0.5,0.5);
fOutputListQA->Add(fh2VtxXY[i]);
// fOutputListStd->Add([i]);
if (fbMCAnalysis)
{
// inclusive pt
fh1V0K0sPtMCGen[i] = new TH1D(Form("fh1V0K0sPtMCGen_%d",i),Form("MC K0s generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0K0sPtMCGen[i]);
fh2V0K0sPtMassMCRec[i] = new TH2D(Form("fh2V0K0sPtMassMCRec_%d",i),Form("MC K0s associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fOutputListMC->Add(fh2V0K0sPtMassMCRec[i]);
fh1V0K0sPtMCRecFalse[i] = new TH1D(Form("fh1V0K0sPtMCRecFalse_%d",i),Form("MC K0s false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0K0sPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0K0sEtaPtMCGen[i] = new TH2D(Form("fh2V0K0sEtaPtMCGen_%d",i),Form("MC K0s generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0K0sEtaPtMCGen[i]);
fh3V0K0sEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0K0sEtaPtMassMCRec_%d",i),Form("MC K0s associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaK,xminEtaK,xmaxEtaK);
fOutputListMC->Add(fh3V0K0sEtaPtMassMCRec[i]);
// in jet pt
fh2V0K0sInJetPtMCGen[i] = new TH2D(Form("fh2V0K0sInJetPtMCGen_%d",i),Form("MC K0s in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0K0sInJetPtMCGen[i]);
fh3V0K0sInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0K0sInJetPtMassMCRec_%d",i),Form("MC K0s in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsKInJC,xminKInJC,xmaxKInJC);
fOutputListMC->Add(fh3V0K0sInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0K0sInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0K0sInJetEtaPtMCGen_%d",i),Form("MC K0s generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0K0sInJetEtaPtMCGen[i]);
fh4V0K0sInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0K0sInJetEtaPtMassMCRec_%d",i),Form("MC K0s associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaKInRec,xminEtaKInRec,xmaxEtaKInRec);
fOutputListMC->Add(fh4V0K0sInJetEtaPtMassMCRec[i]);
fh2V0K0sMCResolMPt[i] = new TH2D(Form("fh2V0K0sMCResolMPt_%d",i),Form("MC K0s associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0K0sMCResolMPt[i]);
fh2V0K0sMCPtGenPtRec[i] = new TH2D(Form("fh2V0K0sMCPtGenPtRec_%d",i),Form("MC K0s associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0K0sMCPtGenPtRec[i]);
// inclusive pt
fh1V0LambdaPtMCGen[i] = new TH1D(Form("fh1V0LambdaPtMCGen_%d",i),Form("MC Lambda generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0LambdaPtMCGen[i]);
fh2V0LambdaPtMassMCRec[i] = new TH2D(Form("fh2V0LambdaPtMassMCRec_%d",i),Form("MC Lambda associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListMC->Add(fh2V0LambdaPtMassMCRec[i]);
fh1V0LambdaPtMCRecFalse[i] = new TH1D(Form("fh1V0LambdaPtMCRecFalse_%d",i),Form("MC Lambda false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0LambdaPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0LambdaEtaPtMCGen[i] = new TH2D(Form("fh2V0LambdaEtaPtMCGen_%d",i),Form("MC Lambda generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0LambdaEtaPtMCGen[i]);
fh3V0LambdaEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0LambdaEtaPtMassMCRec_%d",i),Form("MC Lambda associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaL,xminEtaL,xmaxEtaL);
fOutputListMC->Add(fh3V0LambdaEtaPtMassMCRec[i]);
// in jet pt
fh2V0LambdaInJetPtMCGen[i] = new TH2D(Form("fh2V0LambdaInJetPtMCGen_%d",i),Form("MC Lambda in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0LambdaInJetPtMCGen[i]);
fh3V0LambdaInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0LambdaInJetPtMassMCRec_%d",i),Form("MC Lambda in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListMC->Add(fh3V0LambdaInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0LambdaInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0LambdaInJetEtaPtMCGen_%d",i),Form("MC Lambda generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0LambdaInJetEtaPtMCGen[i]);
fh4V0LambdaInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0LambdaInJetEtaPtMassMCRec_%d",i),Form("MC Lambda associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaLInRec,xminEtaLInRec,xmaxEtaLInRec);
fOutputListMC->Add(fh4V0LambdaInJetEtaPtMassMCRec[i]);
fh2V0LambdaMCResolMPt[i] = new TH2D(Form("fh2V0LambdaMCResolMPt_%d",i),Form("MC Lambda associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0LambdaMCResolMPt[i]);
fh2V0LambdaMCPtGenPtRec[i] = new TH2D(Form("fh2V0LambdaMCPtGenPtRec_%d",i),Form("MC Lambda associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0LambdaMCPtGenPtRec[i]);
// inclusive pt
fh1V0ALambdaPtMCGen[i] = new TH1D(Form("fh1V0ALambdaPtMCGen_%d",i),Form("MC ALambda generated: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0ALambdaPtMCGen[i]);
fh2V0ALambdaPtMassMCRec[i] = new TH2D(Form("fh2V0ALambdaPtMassMCRec_%d",i),Form("MC ALambda associated: pt-m spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{m}_{inv} (GeV/#it{c}^{2})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListMC->Add(fh2V0ALambdaPtMassMCRec[i]);
fh1V0ALambdaPtMCRecFalse[i] = new TH1D(Form("fh1V0ALambdaPtMCRecFalse_%d",i),Form("MC ALambda false: pt spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh1V0ALambdaPtMCRecFalse[i]);
// inclusive pt-eta
fh2V0ALambdaEtaPtMCGen[i] = new TH2D(Form("fh2V0ALambdaEtaPtMCGen_%d",i),Form("MC ALambda generated: pt-eta spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsEtaV0,-dRangeEtaV0Max,dRangeEtaV0Max);
fOutputListMC->Add(fh2V0ALambdaEtaPtMCGen[i]);
fh3V0ALambdaEtaPtMassMCRec[i] = new THnSparseD(Form("fh3V0ALambdaEtaPtMassMCRec_%d",i),Form("MC ALambda associated: m-pt-eta spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta",GetCentBinLabel(i).Data()),3,binsEtaL,xminEtaL,xmaxEtaL);
fOutputListMC->Add(fh3V0ALambdaEtaPtMassMCRec[i]);
// in jet pt
fh2V0ALambdaInJetPtMCGen[i] = new TH2D(Form("fh2V0ALambdaInJetPtMCGen_%d",i),Form("MC ALambda in jet generated: pt-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNJetPtBins,dJetPtMin,dJetPtMax);
fOutputListMC->Add(fh2V0ALambdaInJetPtMCGen[i]);
fh3V0ALambdaInJetPtMassMCRec[i] = new THnSparseD(Form("fh3V0ALambdaInJetPtMassMCRec_%d",i),Form("MC ALambda in jet associated: m-pt-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimInJC,binsLInJC,xminLInJC,xmaxLInJC);
fOutputListMC->Add(fh3V0ALambdaInJetPtMassMCRec[i]);
// in jet pt-eta
fh3V0ALambdaInJetEtaPtMCGen[i] = new THnSparseD(Form("fh3V0ALambdaInJetEtaPtMCGen_%d",i),Form("MC ALambda generated: pt-eta-ptJet spectrum, cent: %s;MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),4,binsEtaInGen,xminEtaInGen,xmaxEtaInGen);
fOutputListMC->Add(fh3V0ALambdaInJetEtaPtMCGen[i]);
fh4V0ALambdaInJetEtaPtMassMCRec[i] = new THnSparseD(Form("fh4V0ALambdaInJetEtaPtMassMCRec_%d",i),Form("MC ALambda associated: m-pt-eta-ptJet spectrum, cent: %s;#it{m}_{inv} (GeV/#it{c}^{2});MC #it{p}_{T} (GeV/#it{c});#eta;#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),5,binsEtaLInRec,xminEtaLInRec,xmaxEtaLInRec);
fOutputListMC->Add(fh4V0ALambdaInJetEtaPtMassMCRec[i]);
fh2V0ALambdaMCResolMPt[i] = new TH2D(Form("fh2V0ALambdaMCResolMPt_%d",i),Form("MC ALambda associated: #Delta#it{m} vs pt, cent %s;#Delta#it{m} = #it{m}_{inv} - #it{m}_{true} (GeV/#it{c}^{2});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),100,-0.02,0.02,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0ALambdaMCResolMPt[i]);
fh2V0ALambdaMCPtGenPtRec[i] = new TH2D(Form("fh2V0ALambdaMCPtGenPtRec_%d",i),Form("MC ALambda associated: pt gen vs pt rec, cent %s;#it{p}_{T}^{gen} (GeV/#it{c});#it{p}_{T}^{rec} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtV0,dPtV0Min,dPtV0Max,iNBinsPtV0,dPtV0Min,dPtV0Max);
fOutputListMC->Add(fh2V0ALambdaMCPtGenPtRec[i]);
Int_t iNBinsPtXi = 80;
Double_t dPtXiMin = 0;
Double_t dPtXiMax = 8;
const Int_t iNDimFD = 3;
Int_t binsFD[iNDimFD] = {iNBinsPtV0, iNBinsPtXi, iNJetPtBins};
Double_t xminFD[iNDimFD] = {dPtV0Min, dPtXiMin, dJetPtMin};
Double_t xmaxFD[iNDimFD] = {dPtV0Max, dPtXiMax, dJetPtMax};
fhnV0LambdaInclMCFD[i] = new THnSparseD(Form("fhnV0LambdaInclMCFD_%d",i),Form("MC Lambda associated, inclusive, from Xi: pt-pt, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaInclMCFD[i]);
fhnV0LambdaInJetsMCFD[i] = new THnSparseD(Form("fhnV0LambdaInJetsMCFD_%d",i),Form("MC Lambda associated, in JC, from Xi: pt-pt-ptJet, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaInJetsMCFD[i]);
fhnV0LambdaBulkMCFD[i] = new THnSparseD(Form("fhnV0LambdaBulkMCFD_%d",i),Form("MC Lambda associated, in no jet events, from Xi: pt-pt, cent %s;#it{p}_{T}^{#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0LambdaBulkMCFD[i]);
fh1V0XiPtMCGen[i] = new TH1D(Form("fh1V0XiPtMCGen_%d",i),Form("MC Xi^{-} generated: Pt spectrum, cent %s;#it{p}_{T}^{#Xi^{-},gen.} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtXi,dPtXiMin,dPtXiMax);
fOutputListMC->Add(fh1V0XiPtMCGen[i]);
fhnV0ALambdaInclMCFD[i] = new THnSparseD(Form("fhnV0ALambdaInclMCFD_%d",i),Form("MC ALambda associated, from AXi: pt-pt, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaInclMCFD[i]);
fhnV0ALambdaInJetsMCFD[i] = new THnSparseD(Form("fhnV0ALambdaInJetsMCFD_%d",i),Form("MC ALambda associated, in JC, from AXi: pt-pt-ptJet, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaInJetsMCFD[i]);
fhnV0ALambdaBulkMCFD[i] = new THnSparseD(Form("fhnV0ALambdaBulkMCFD_%d",i),Form("MC ALambda associated, in no jet events, from AXi: pt-pt-ptJet, cent %s;#it{p}_{T}^{A#Lambda,gen.} (GeV/#it{c});#it{p}_{T}^{A#Xi,gen.} (GeV/#it{c});#it{p}_{T}^{jet} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNDimFD,binsFD,xminFD,xmaxFD);
fOutputListMC->Add(fhnV0ALambdaBulkMCFD[i]);
fh1V0AXiPtMCGen[i] = new TH1D(Form("fh1V0AXiPtMCGen_%d",i),Form("MC AXi^{-} generated: Pt spectrum, cent %s;#it{p}_{T}^{A#Xi^{-},gen.} (GeV/#it{c})",GetCentBinLabel(i).Data()),iNBinsPtXi,dPtXiMin,dPtXiMax);
fOutputListMC->Add(fh1V0AXiPtMCGen[i]);
// daughter eta
// fhnV0K0sInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0K0sInclDaughterEtaPtPtMCGen_%d",i),Form("MC K0S, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0K0sInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0K0sInclDaughterEtaPtPtMCRec_%d",i),Form("MC K0S, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0K0sInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0K0sInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC K0S, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0K0sInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0K0sInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC K0S, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0LambdaInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0LambdaInclDaughterEtaPtPtMCGen_%d",i),Form("MC Lambda, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0LambdaInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0LambdaInclDaughterEtaPtPtMCRec_%d",i),Form("MC Lambda, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0LambdaInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC Lambda, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0LambdaInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC Lambda, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0ALambdaInclDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0ALambdaInclDaughterEtaPtPtMCGen_%d",i),Form("MC ALambda, inclusive, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0ALambdaInclDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0ALambdaInclDaughterEtaPtPtMCRec_%d",i),Form("MC ALambda, inclusive, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i] = new THnSparseD(Form("fhnV0ALambdaInJetsDaughterEtaPtPtMCGen_%d",i),Form("MC ALambda, in JC, gen., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i] = new THnSparseD(Form("fhnV0ALambdaInJetsDaughterEtaPtPtMCRec_%d",i),Form("MC ALambda, in JC, assoc., daughters: charge-etaD-ptD-etaV0-ptV0-ptJet, cent: %s;charge;eta daughter;pT daughter;eta V0;pT V0;pT jet",GetCentBinLabel(i).Data()),iNDimEtaD,binsEtaDaughter,xminEtaDaughter,xmaxEtaDaughter);
// fOutputListMC->Add(fhnV0K0sInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0K0sInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0K0sInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0K0sInJetsDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0LambdaInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0LambdaInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0LambdaInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0LambdaInJetsDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0ALambdaInclDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0ALambdaInclDaughterEtaPtPtMCRec[i]);
// fOutputListMC->Add(fhnV0ALambdaInJetsDaughterEtaPtPtMCGen[i]);
fOutputListMC->Add(fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[i]);
}
}
// QA Histograms
for (Int_t i = 0; i < fgkiNQAIndeces; i++)
{
// [i] = new TH1D(Form("%d",i),";;Counts",,,);
fh1QAV0Status[i] = new TH1D(Form("fh1QAV0Status_%d",i),"QA: V0 status",2,0,2);
fh1QAV0TPCRefit[i] = new TH1D(Form("fh1QAV0TPCRefit_%d",i),"QA: TPC refit",2,0,2);
fh1QAV0TPCRows[i] = new TH1D(Form("fh1QAV0TPCRows_%d",i),"QA: TPC Rows",160,0,160);
fh1QAV0TPCFindable[i] = new TH1D(Form("fh1QAV0TPCFindable_%d",i),"QA: TPC Findable",160,0,160);
fh1QAV0TPCRowsFind[i] = new TH1D(Form("fh1QAV0TPCRowsFind_%d",i),"QA: TPC Rows/Findable",100,0,2);
fh1QAV0Eta[i] = new TH1D(Form("fh1QAV0Eta_%d",i),"QA: Daughter Eta",200,-2,2);
fh2QAV0EtaRows[i] = new TH2D(Form("fh2QAV0EtaRows_%d",i),"QA: Daughter Eta vs TPC rows;#eta;TPC rows",200,-2,2,160,0,160);
fh2QAV0PtRows[i] = new TH2D(Form("fh2QAV0PtRows_%d",i),"QA: Daughter Pt vs TPC rows;pt;TPC rows",100,0,10,160,0,160);
fh2QAV0PhiRows[i] = new TH2D(Form("fh2QAV0PhiRows_%d",i),"QA: Daughter Phi vs TPC rows;#phi;TPC rows",100,0,TMath::TwoPi(),160,0,160);
fh2QAV0NClRows[i] = new TH2D(Form("fh2QAV0NClRows_%d",i),"QA: Daughter NCl vs TPC rows;findable clusters;TPC rows",100,0,160,160,0,160);
fh2QAV0EtaNCl[i] = new TH2D(Form("fh2QAV0EtaNCl_%d",i),"QA: Daughter Eta vs NCl;#eta;findable clusters",200,-2,2,160,0,160);
fh2QAV0EtaPtK0sPeak[i] = new TH2D(Form("fh2QAV0EtaPtK0sPeak_%d",i),"QA: K0s: Daughter Eta vs V0 pt, peak;track eta;V0 pt",200,-2,2,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2QAV0EtaEtaK0s[i] = new TH2D(Form("fh2QAV0EtaEtaK0s_%d",i),"QA: K0s: Eta vs Eta Daughter",200,-2,2,200,-2,2);
fh2QAV0PhiPhiK0s[i] = new TH2D(Form("fh2QAV0PhiPhiK0s_%d",i),"QA: K0s: Phi vs Phi Daughter",200,0,TMath::TwoPi(),200,0,TMath::TwoPi());
fh1QAV0RapK0s[i] = new TH1D(Form("fh1QAV0RapK0s_%d",i),"QA: K0s: V0 Rapidity",200,-2,2);
fh2QAV0PtPtK0sPeak[i] = new TH2D(Form("fh2QAV0PtPtK0sPeak_%d",i),"QA: K0s: Daughter Pt vs Pt;neg pt;pos pt",100,0,5,100,0,5);
fh2QAV0EtaPtLambdaPeak[i] = new TH2D(Form("fh2QAV0EtaPtLambdaPeak_%d",i),"QA: Lambda: Daughter Eta vs V0 pt, peak;track eta;V0 pt",200,-2,2,iNBinsPtV0,dPtV0Min,dPtV0Max);
fh2QAV0EtaEtaLambda[i] = new TH2D(Form("fh2QAV0EtaEtaLambda_%d",i),"QA: Lambda: Eta vs Eta Daughter",200,-2,2,200,-2,2);
fh2QAV0PhiPhiLambda[i] = new TH2D(Form("fh2QAV0PhiPhiLambda_%d",i),"QA: Lambda: Phi vs Phi Daughter",200,0,TMath::TwoPi(),200,0,TMath::TwoPi());
fh1QAV0RapLambda[i] = new TH1D(Form("fh1QAV0RapLambda_%d",i),"QA: Lambda: V0 Rapidity",200,-2,2);
fh2QAV0PtPtLambdaPeak[i] = new TH2D(Form("fh2QAV0PtPtLambdaPeak_%d",i),"QA: Lambda: Daughter Pt vs Pt;neg pt;pos pt",100,0,5,100,0,5);
fh1QAV0Pt[i] = new TH1D(Form("fh1QAV0Pt_%d",i),"QA: Daughter Pt",100,0,5);
fh1QAV0Charge[i] = new TH1D(Form("fh1QAV0Charge_%d",i),"QA: V0 Charge",3,-1,2);
fh1QAV0DCAVtx[i] = new TH1D(Form("fh1QAV0DCAVtx_%d",i),"QA: DCA daughters to primary vertex",100,0,10);
fh1QAV0DCAV0[i] = new TH1D(Form("fh1QAV0DCAV0_%d",i),"QA: DCA daughters",100,0,2);
fh1QAV0Cos[i] = new TH1D(Form("fh1QAV0Cos_%d",i),"QA: CPA",10000,0.9,1);
fh1QAV0R[i] = new TH1D(Form("fh1QAV0R_%d",i),"QA: R",1500,0,150);
fh1QACTau2D[i] = new TH1D(Form("fh1QACTau2D_%d",i),"QA: K0s: c#tau 2D;mR/pt#tau",100,0,10);
fh1QACTau3D[i] = new TH1D(Form("fh1QACTau3D_%d",i),"QA: K0s: c#tau 3D;mL/p#tau",100,0,10);
fh2ArmPod[i] = new TH2D(Form("fh2ArmPod_%d",i),"Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodK0s[i] = new TH2D(Form("fh2ArmPodK0s_%d",i),"K0s: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodLambda[i] = new TH2D(Form("fh2ArmPodLambda_%d",i),"Lambda: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2ArmPodALambda[i] = new TH2D(Form("fh2ArmPodALambda_%d",i),"ALambda: Armenteros-Podolanski;#alpha;#it{p}_{T}^{Arm}",100,-1.,1.,50,0.,0.25);
fh2CutTPCRowsK0s[i] = new TH2D(Form("fh2CutTPCRowsK0s_%d",i),"Cuts: K0s: TPC Rows vs mass;#it{m}_{inv} (GeV/#it{c}^{2});TPC rows",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,160,0,160);
fh2CutTPCRowsLambda[i] = new TH2D(Form("fh2CutTPCRowsLambda_%d",i),"Cuts: Lambda: TPC Rows vs mass;#it{m}_{inv} (GeV/#it{c}^{2});TPC rows",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,160,0,160);
fh2CutPtPosK0s[i] = new TH2D(Form("fh2CutPtPosK0s_%d",i),"Cuts: K0s: Pt pos;#it{m}_{inv} (GeV/#it{c}^{2});pt pos",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,5);
fh2CutPtNegK0s[i] = new TH2D(Form("fh2CutPtNegK0s_%d",i),"Cuts: K0s: Pt neg;#it{m}_{inv} (GeV/#it{c}^{2});pt neg",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,5);
fh2CutPtPosLambda[i] = new TH2D(Form("fh2CutPtPosLambda_%d",i),"Cuts: Lambda: Pt pos;#it{m}_{inv} (GeV/#it{c}^{2});pt pos",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,5);
fh2CutPtNegLambda[i] = new TH2D(Form("fh2CutPtNegLambda_%d",i),"Cuts: Lambda: Pt neg;#it{m}_{inv} (GeV/#it{c}^{2});pt neg",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,5);
fh2CutDCAVtx[i] = new TH2D(Form("fh2CutDCAVtx_%d",i),"Cuts: DCA daughters to prim. vtx.;#it{m}_{inv} (GeV/#it{c}^{2});DCA daughter to prim. vtx. (cm)",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutDCAV0[i] = new TH2D(Form("fh2CutDCAV0_%d",i),"Cuts: DCA daughters;#it{m}_{inv} (GeV/#it{c}^{2});DCA daughters / #sigma_{TPC}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,2);
fh2CutCos[i] = new TH2D(Form("fh2CutCos_%d",i),"Cuts: CPA;#it{m}_{inv} (GeV/#it{c}^{2});CPA",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,10000,0.9,1);
fh2CutR[i] = new TH2D(Form("fh2CutR_%d",i),"Cuts: R;#it{m}_{inv} (GeV/#it{c}^{2});R (cm)",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,1500,0,150);
fh2CutEtaK0s[i] = new TH2D(Form("fh2CutEtaK0s_%d",i),"Cuts: K0s: Eta;#it{m}_{inv} (GeV/#it{c}^{2});#eta",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,200,-2,2);
fh2CutEtaLambda[i] = new TH2D(Form("fh2CutEtaLambda_%d",i),"Cuts: Lambda: Eta;#it{m}_{inv} (GeV/#it{c}^{2});#eta",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,200,-2,2);
fh2CutRapK0s[i] = new TH2D(Form("fh2CutRapK0s_%d",i),"Cuts: K0s: Rapidity;#it{m}_{inv} (GeV/#it{c}^{2});y",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,200,-2,2);
fh2CutRapLambda[i] = new TH2D(Form("fh2CutRapLambda_%d",i),"Cuts: Lambda: Rapidity;#it{m}_{inv} (GeV/#it{c}^{2});y",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,200,-2,2);
fh2CutCTauK0s[i] = new TH2D(Form("fh2CutCTauK0s_%d",i),"Cuts: K0s: #it{c#tau};#it{m}_{inv} (GeV/#it{c}^{2});#it{mL/p#tau}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutCTauLambda[i] = new TH2D(Form("fh2CutCTauLambda_%d",i),"Cuts: Lambda: #it{c#tau};#it{m}_{inv} (GeV/#it{c}^{2});#it{mL/p#tau}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2CutPIDPosK0s[i] = new TH2D(Form("fh2CutPIDPosK0s_%d",i),"Cuts: K0s: PID pos;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutPIDNegK0s[i] = new TH2D(Form("fh2CutPIDNegK0s_%d",i),"Cuts: K0s: PID neg;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax,100,0,10);
fh2CutPIDPosLambda[i] = new TH2D(Form("fh2CutPIDPosLambda_%d",i),"Cuts: Lambda: PID pos;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2CutPIDNegLambda[i] = new TH2D(Form("fh2CutPIDNegLambda_%d",i),"Cuts: Lambda: PID neg;#it{m}_{inv} (GeV/#it{c}^{2});##sigma_{d#it{E}/d#it{x}}",fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax,100,0,10);
fh2Tau3DVs2D[i] = new TH2D(Form("fh2Tau3DVs2D_%d",i),"Decay 3D vs 2D;pt;3D/2D",100,0,10,200,0.5,1.5);
fOutputListQA->Add(fh1QAV0Status[i]);
fOutputListQA->Add(fh1QAV0TPCRefit[i]);
fOutputListQA->Add(fh1QAV0TPCRows[i]);
fOutputListQA->Add(fh1QAV0TPCFindable[i]);
fOutputListQA->Add(fh1QAV0TPCRowsFind[i]);
fOutputListQA->Add(fh1QAV0Eta[i]);
fOutputListQA->Add(fh2QAV0EtaRows[i]);
fOutputListQA->Add(fh2QAV0PtRows[i]);
fOutputListQA->Add(fh2QAV0PhiRows[i]);
fOutputListQA->Add(fh2QAV0NClRows[i]);
fOutputListQA->Add(fh2QAV0EtaNCl[i]);
fOutputListQA->Add(fh2QAV0EtaPtK0sPeak[i]);
fOutputListQA->Add(fh2QAV0EtaEtaK0s[i]);
fOutputListQA->Add(fh2QAV0PhiPhiK0s[i]);
fOutputListQA->Add(fh1QAV0RapK0s[i]);
fOutputListQA->Add(fh2QAV0PtPtK0sPeak[i]);
fOutputListQA->Add(fh2QAV0EtaPtLambdaPeak[i]);
fOutputListQA->Add(fh2QAV0EtaEtaLambda[i]);
fOutputListQA->Add(fh2QAV0PhiPhiLambda[i]);
fOutputListQA->Add(fh1QAV0RapLambda[i]);
fOutputListQA->Add(fh2QAV0PtPtLambdaPeak[i]);
fOutputListQA->Add(fh1QAV0Pt[i]);
fOutputListQA->Add(fh1QAV0Charge[i]);
fOutputListQA->Add(fh1QAV0DCAVtx[i]);
fOutputListQA->Add(fh1QAV0DCAV0[i]);
fOutputListQA->Add(fh1QAV0Cos[i]);
fOutputListQA->Add(fh1QAV0R[i]);
fOutputListQA->Add(fh1QACTau2D[i]);
fOutputListQA->Add(fh1QACTau3D[i]);
fOutputListQA->Add(fh2ArmPod[i]);
fOutputListQA->Add(fh2ArmPodK0s[i]);
fOutputListQA->Add(fh2ArmPodLambda[i]);
fOutputListQA->Add(fh2ArmPodALambda[i]);
fOutputListCuts->Add(fh2CutTPCRowsK0s[i]);
fOutputListCuts->Add(fh2CutTPCRowsLambda[i]);
fOutputListCuts->Add(fh2CutPtPosK0s[i]);
fOutputListCuts->Add(fh2CutPtNegK0s[i]);
fOutputListCuts->Add(fh2CutPtPosLambda[i]);
fOutputListCuts->Add(fh2CutPtNegLambda[i]);
fOutputListCuts->Add(fh2CutDCAVtx[i]);
fOutputListCuts->Add(fh2CutDCAV0[i]);
fOutputListCuts->Add(fh2CutCos[i]);
fOutputListCuts->Add(fh2CutR[i]);
fOutputListCuts->Add(fh2CutEtaK0s[i]);
fOutputListCuts->Add(fh2CutEtaLambda[i]);
fOutputListCuts->Add(fh2CutRapK0s[i]);
fOutputListCuts->Add(fh2CutRapLambda[i]);
fOutputListCuts->Add(fh2CutCTauK0s[i]);
fOutputListCuts->Add(fh2CutCTauLambda[i]);
fOutputListCuts->Add(fh2CutPIDPosK0s[i]);
fOutputListCuts->Add(fh2CutPIDNegK0s[i]);
fOutputListCuts->Add(fh2CutPIDPosLambda[i]);
fOutputListCuts->Add(fh2CutPIDNegLambda[i]);
fOutputListCuts->Add(fh2Tau3DVs2D[i]);
}
for (Int_t i = 0; i < fgkiNCategV0; i++)
{
fh1V0InvMassK0sAll[i] = new TH1D(Form("fh1V0InvMassK0sAll_%d",i), Form("K0s: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassK0s,fgkdMassK0sMin,fgkdMassK0sMax);
fh1V0InvMassLambdaAll[i] = new TH1D(Form("fh1V0InvMassLambdaAll_%d",i), Form("Lambda: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fh1V0InvMassALambdaAll[i] = new TH1D(Form("fh1V0InvMassALambdaAll_%d",i), Form("ALambda: V0 invariant mass, %s;#it{m}_{inv} (GeV/#it{c}^{2});counts",categV0[i].Data()),fgkiNBinsMassLambda,fgkdMassLambdaMin,fgkdMassLambdaMax);
fOutputListStd->Add(fh1V0InvMassK0sAll[i]);
fOutputListStd->Add(fh1V0InvMassLambdaAll[i]);
fOutputListStd->Add(fh1V0InvMassALambdaAll[i]);
}
for (Int_t i = 0; i < fOutputListStd->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListStd->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListStd->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListQA->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListQA->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListQA->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListCuts->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListCuts->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListCuts->At(i));
if(hn) hn->Sumw2();
}
for (Int_t i = 0; i < fOutputListMC->GetEntries(); ++i)
{
TH1* h1 = dynamic_cast<TH1*>(fOutputListMC->At(i));
if (h1)
{
h1->Sumw2();
continue;
}
THnSparse* hn = dynamic_cast<THnSparse*>(fOutputListMC->At(i));
if(hn) hn->Sumw2();
}
PostData(1,fOutputListStd);
PostData(2,fOutputListQA);
PostData(3,fOutputListCuts);
PostData(4,fOutputListMC);
// if (fbTreeOutput)
// PostData(5,ftreeOut);
}
void AliAnalysisTaskV0sInJets::UserExec(Option_t *)
{
// Main loop, called for each event
if(fDebug>5) printf("TaskV0sInJets: UserExec: Start\n");
/*
// reset branches for each event
if (fBranchV0Rec)
fBranchV0Rec->Clear();
if (fBranchV0Gen)
fBranchV0Gen->Clear();
if (fBranchJet)
fBranchJet->Clear();
if (fEventInfo)
fEventInfo->Reset();
*/
if (!fiAODAnalysis)
return;
if(fDebug>2) printf("TaskV0sInJets: AOD analysis\n");
fh1EventCounterCut->Fill(0); // all available selected events (collision candidates)
if(fDebug>5) printf("TaskV0sInJets: UserExec: Loading AOD\n");
fAODIn = dynamic_cast<AliAODEvent*>(InputEvent()); // input AOD
fAODOut = AODEvent(); // output AOD
if (!fAODOut)
{
if(fDebug>0) printf("TaskV0sInJets: No output AOD found\n");
return;
}
if (!fAODIn)
{
if(fDebug>0) printf("TaskV0sInJets: No input AOD found\n");
return;
}
if(fDebug>5) printf("TaskV0sInJets: UserExec: Loading AOD OK\n");
TClonesArray* arrayMC = 0; // array particles in the MC event
AliAODMCHeader* headerMC = 0; // MC header
Int_t iNTracksMC = 0; // number of MC tracks
Double_t dPrimVtxMCX=0., dPrimVtxMCY=0., dPrimVtxMCZ=0.; // position of the MC primary vertex
// Simulation info
if (fbMCAnalysis)
{
arrayMC = (TClonesArray*)fAODIn->FindListObject(AliAODMCParticle::StdBranchName());
if (!arrayMC)
{
if(fDebug>0) printf("TaskV0sInJets: No MC array found\n");
return;
}
if(fDebug>5) printf("TaskV0sInJets: MC array found\n");
iNTracksMC = arrayMC->GetEntriesFast();
if(fDebug>5) printf("TaskV0sInJets: There are %d MC tracks in this event\n",iNTracksMC);
// if (!iNTracksMC)
// return;
headerMC = (AliAODMCHeader*)fAODIn->FindListObject(AliAODMCHeader::StdBranchName());
if (!headerMC)
{
if(fDebug>0) printf("TaskV0sInJets: No MC header found\n");
return;
}
// get position of the MC primary vertex
dPrimVtxMCX=headerMC->GetVtxX();
dPrimVtxMCY=headerMC->GetVtxY();
dPrimVtxMCZ=headerMC->GetVtxZ();
}
// PID Response Task object
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*)mgr->GetInputEventHandler();
AliPIDResponse* fPIDResponse = inputHandler->GetPIDResponse();
if (!fPIDResponse)
{
if(fDebug>0) printf("TaskV0sInJets: No PID response object found\n");
return;
}
// AOD files are OK
fh1EventCounterCut->Fill(1);
// Event selection
if (!IsSelectedForJets(fAODIn,fdCutVertexZ,fdCutVertexR2,fdCutCentLow,fdCutCentHigh,1,0.1)) // cut on |delta z| in 2011 data between SPD vertex and nominal primary vertex
// if (!IsSelectedForJets(fAODIn,fdCutVertexZ,fdCutVertexR2,fdCutCentLow,fdCutCentHigh)) // no need for cutting in 2010 data
{
if(fDebug>5) printf("TaskV0sInJets: Event rejected\n");
return;
}
// fdCentrality = fAODIn->GetHeader()->GetCentrality(); // event centrality
fdCentrality = fAODIn->GetHeader()->GetCentralityP()->GetCentralityPercentile("V0M"); // event centrality
Int_t iCentIndex = GetCentralityBinIndex(fdCentrality); // get index of centrality bin
if (iCentIndex<0)
{
if(fDebug>5) printf("TaskV0sInJets: Event is out of histogram range\n");
return;
}
fh1EventCounterCut->Fill(2); // selected events (vertex, centrality)
fh1EventCounterCutCent[iCentIndex]->Fill(2);
UInt_t iNTracks = fAODIn->GetNumberOfTracks(); // get number of tracks in event
if(fDebug>5) printf("TaskV0sInJets: There are %d tracks in this event\n",iNTracks);
// if (!iNTracks)
// return;
Int_t iNV0s = fAODIn->GetNumberOfV0s(); // get the number of V0 candidates
if (!iNV0s)
{
if(fDebug>2) printf("TaskV0sInJets: No V0s found in event\n");
// return;
}
/*===== Event is OK for the analysis =====*/
fh1EventCent->Fill(iCentIndex);
fh1EventCent2->Fill(fdCentrality);
fh2EventCentTracks->Fill(fdCentrality,iNTracks);
// if (fbTreeOutput)
// fEventInfo->SetAODEvent(fAODIn);
// printf("V0sInJets: EventInfo: Centrality: %f\n",fEventInfo->GetCentrality());
if (iNV0s)
{
fh1EventCounterCut->Fill(3); // events with V0s
fh1EventCounterCutCent[iCentIndex]->Fill(3);
}
// Int_t iNV0SelV0Rec = 0;
// Int_t iNV0SelV0Gen = 0;
AliAODv0* v0 = 0; // pointer to V0 candidates
// AliV0Object* objectV0 = 0;
TVector3 vecV0Momentum; // 3D vector of V0 momentum
Double_t dMassV0K0s = 0; // invariant mass of the K0s candidate
Double_t dMassV0Lambda = 0; // invariant mass of the Lambda candidate
Double_t dMassV0ALambda = 0; // invariant mass of the Lambda candidate
Int_t iNV0CandTot = 0; // counter of all V0 candidates at the beginning
Int_t iNV0CandK0s = 0; // counter of K0s candidates at the end
Int_t iNV0CandLambda = 0; // counter of Lambda candidates at the end
Int_t iNV0CandALambda = 0; // counter of Lambda candidates at the end
Bool_t bUseOldCuts = 0; // old reconstruction cuts
Bool_t bUseAliceCuts = 0; // cuts used by Alice Zimmermann
Bool_t bUseIouriCuts = 0; // cuts used by Iouri
Bool_t bPrintCuts = 0; // print out which cuts are applied
Bool_t bPrintJetSelection = 0; // print out which jets are selected
// Values of V0 reconstruction cuts:
// Daughter tracks
Int_t iRefit = AliAODTrack::kTPCrefit; // TPC refit for daughter tracks
Double_t dDCAToPrimVtxMin = fdCutDCAToPrimVtxMin; // 0.1; // [cm] min DCA of daughters to the prim vtx
Double_t dDCADaughtersMax = fdCutDCADaughtersMax; // 1.; // [sigma of TPC tracking] max DCA between daughters
Double_t dEtaDaughterMax = 0.8; // max |pseudorapidity| of daughter tracks
Double_t dNSigmadEdxMax = fdCutNSigmadEdxMax;// 3.; // [sigma dE/dx] max difference between measured and expected signal of dE/dx in the TPC
Double_t dPtProtonPIDMax = 1.; // [GeV/c] maxium pT of proton for applying PID cut
// V0 candidate
Bool_t bOnFly = 0; // on-the-fly (yes) or offline (no) reconstructed
Double_t dCPAMin = fdCutCPAMin;// 0.998; // min cosine of the pointing angle
Double_t dRadiusDecayMin = 5.; // [cm] min radial distance of the decay vertex
Double_t dRadiusDecayMax = 100.; // [cm] max radial distance of the decay vertex
Double_t dEtaMax = 0.7; // max |pseudorapidity| of V0
Double_t dNTauMax = fdCutNTauMax; // 5.0; // [tau] max proper lifetime in multiples of the mean lifetime
// Old cuts Start
Double_t dNCrossedRowsTPCMin = 70.; // min number of crossed TPC rows (turned off)
// Double_t dCrossedRowsOverFindMin = 0.8; // min ratio crossed rows / findable clusters (turned off)
// Double_t dCrossedRowsOverFindMax = 1e3; // max ratio crossed rows / findable clusters (turned off)
Double_t dPtDaughterMin = 0.150; // [GeV/c] min transverse momentum of daughter tracks (turned off)
Double_t dRapMax = 0.75; // max |rapidity| of V0 (turned off)
// Old cuts End
// Other cuts
Double_t dNSigmaMassMax = 3.; // [sigma m] max difference between candidate mass and real particle mass (used only for mass peak method of signal extraction)
Double_t dDistPrimaryMax = 0.01; // [cm] max distance of production point to the primary vertex (criterion for choice of MC particles considered as primary)
// Selection of active cuts
Bool_t bCutEtaDaughter = 1; // daughter pseudorapidity
Bool_t bCutRapV0 = 0; // V0 rapidity
Bool_t bCutEtaV0 = 1; // V0 pseudorapidity
Bool_t bCutTau = 1; // V0 lifetime
Bool_t bCutPid = 1; // PID (TPC dE/dx)
Bool_t bCutArmPod = 1; // Armenteros-Podolanski for K0S
// Bool_t bCutCross = 0; // cross contamination
if (bUseOldCuts)
{
bCutRapV0 = 1;
dEtaMax = 0.75;
dNTauMax = 3.0;
}
else if (bUseAliceCuts)
{
// bOnFly = 1;
dEtaMax = 0.75;
dNTauMax = 5.0;
}
else if (bUseIouriCuts)
{
bCutRapV0 = 1;
bCutEtaV0 = 0;
dNTauMax = 3.0;
dRapMax = 0.5;
}
Double_t dCTauK0s = 2.6844; // [cm] c tau of K0S
Double_t dCTauLambda = 7.89; // [cm] c tau of Lambda
// Load PDG values of particle masses
Double_t dMassPDGK0s = TDatabasePDG::Instance()->GetParticle(kK0Short)->Mass();
Double_t dMassPDGLambda = TDatabasePDG::Instance()->GetParticle(kLambda0)->Mass();
// PDG codes of used particles
Int_t iPdgCodePion = 211;
Int_t iPdgCodeProton = 2212;
Int_t iPdgCodeK0s = 310;
Int_t iPdgCodeLambda = 3122;
// Jet selection: fdCutPtJetMin, fdCutPtTrackMin
Double_t dJetEtaWindow = dEtaMax-fdRadiusJet; // max jet |pseudorapidity|, to make sure that V0s can appear in the entire jet area
Double_t dCutJetAreaMin = 0.6*TMath::Pi()*fdRadiusJet*fdRadiusJet; // minimum jet area
Double_t dRadiusExcludeCone = 2*fdRadiusJet; // radius of cones around jets excluded for V0 outside jets
Bool_t bLeadingJetOnly = 0;
if (bUseAliceCuts)
{
fdCutPtJetMin = 5;
fdCutPtTrackMin = 5;
dCutJetAreaMin = 0;
bLeadingJetOnly = 0;
}
// Int_t iNJetAll = 0; // number of reconstructed jets in fBranchJet
// iNJetAll = fBranchJet->GetEntriesFast(); // number of reconstructed jets
TClonesArray* jetArray = 0; // object where the input jets are stored
TClonesArray* jetArrayBg = 0; // object where the kt clusters are stored
Int_t iNJet = 0; // number of reconstructed jets in the input
TClonesArray* jetArraySel = new TClonesArray("AliAODJet",0); // object where the selected jets are copied
Int_t iNJetSel = 0; // number of selected reconstructed jets
// iNJetSel = jetArraySel->GetEntriesFast(); // number of selected reconstructed jets
TClonesArray* jetArrayPerp = new TClonesArray("AliAODJet",0); // object where the perp. cones are stored
Int_t iNJetPerp = 0; // number of perpendicular cones
AliAODJet* jet = 0; // pointer to a jet
// AliJetObject* objectJet = 0;
AliAODJet* jetPerp = 0; // pointer to a perp. cone
AliAODJet* jetRnd = 0; // pointer to a rand. cone
AliAODJet* jetMed = 0; // pointer to a median cluster
TVector3 vecJetMomentum; // 3D vector of jet momentum
// TVector3 vecPerpConeMomentum; // 3D vector of perpendicular cone momentum
// TVector3 vecRndConeMomentum; // 3D vector of random cone momentum
Bool_t bJetEventGood = kTRUE; // indicator of good jet events
// printf("iNJetAll, iNJetSel: %d %d\n",iNJetAll,iNJetSel);
if (fbJetSelection) // analysis of V0s in jets is switched on
{
jetArray = (TClonesArray*)(fAODOut->FindListObject(fsJetBranchName.Data())); // find object with jets in the output AOD
if (!jetArray)
{
if(fDebug>0) printf("TaskV0sInJets: No array of name: %s\n",fsJetBranchName.Data());
bJetEventGood = kFALSE;
}
if (bJetEventGood)
iNJet = jetArray->GetEntriesFast();
if (bJetEventGood && !iNJet) // check whether there are some jets
{
if(fDebug>2) printf("TaskV0sInJets: No jets in array\n");
bJetEventGood = kFALSE;
}
if (bJetEventGood)
{
// printf("TaskV0sInJets: Loading bg array of name: %s\n",fsJetBgBranchName.Data());
jetArrayBg = (TClonesArray*)(fAODOut->FindListObject(fsJetBgBranchName.Data())); // find object with jets in the output AOD
if (!jetArrayBg)
{
if(fDebug>0) printf("TaskV0sInJets: No bg array of name: %s\n",fsJetBgBranchName.Data());
// bJetEventGood = kFALSE;
}
}
}
else // no in-jet analysis
bJetEventGood = kFALSE;
// select good jets and copy them to another array
if (bJetEventGood)
{
if (bLeadingJetOnly)
iNJet = 1; // only leading jets
if(fDebug>5) printf("TaskV0sInJets: Jet selection for %d jets\n",iNJet);
for (Int_t iJet = 0; iJet<iNJet; iJet++)
{
AliAODJet* jetSel = (AliAODJet*)jetArray->At(iJet); // load a jet in the list
if (!jetSel)
{
if(fDebug>0) printf("TaskV0sInJets: Cannot load jet %d\n",iJet);
continue;
}
if (bPrintJetSelection)
if(fDebug>7) printf("jet: i = %d, pT = %f, eta = %f, phi = %f, pt lead tr = %f ",iJet,jetSel->Pt(),jetSel->Eta(),jetSel->Phi(),jetSel->GetPtLeading());
// printf("TaskV0sInJets: Checking pt > %.2f for jet %d with pt %.2f\n",fdCutPtJetMin,iJet,jetSel->Pt());
if (jetSel->Pt() < fdCutPtJetMin) // selection of high-pt jets
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (pt)\n");
continue;
}
// printf("TaskV0sInJets: Checking |eta| < %.2f for jet %d with |eta| %.2f\n",dJetEtaWindow,iJet,TMath::Abs(jetSel->Eta()));
if (TMath::Abs(jetSel->Eta()) > dJetEtaWindow) // selection of jets in the chosen pseudorapidity range
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (eta)\n");
continue;
}
if (!bUseOldCuts)
{
if (jetSel->EffectiveAreaCharged() < dCutJetAreaMin)
continue;
}
Int_t iNTracksInJet = 0;
Double_t dPtLeadTrack = 0; // pt of the leading track
// Int_t iLeadTrack = 0;
iNTracksInJet = jetSel->GetRefTracks()->GetEntriesFast(); // number od tracks that constitute the jet
// printf("TaskV0sInJets: Searching for leading track from %d tracks in jet %d\n",iNTracksInJet,iJet);
if (fdCutPtTrackMin > 0) // a positive min leading track pt is set
{
for (Int_t j = 0; j < iNTracksInJet; j++) // find the track with the highest pt
{
AliAODTrack* track = (AliAODTrack*)jetSel->GetTrack(j); // is this the leading track?
if (!track)
continue;
// printf("TaskV0sInJets: %d: %.2f\n",j,track->Pt());
if (track->Pt() > dPtLeadTrack)
{
dPtLeadTrack = track->Pt();
// iLeadTrack = j;
}
}
// printf("Leading track pT: my: %f, ali: %f\n",dPtLeadTrack,jetSel->GetPtLeading());
// printf("TaskV0sInJets: Checking leading track pt > %.2f for pt %.2f of track %d in jet %d\n",fdCutPtTrackMin,dPtLeadTrack,iLeadTrack,iJet);
if (dPtLeadTrack < fdCutPtTrackMin) // selection of high-pt jet-track events
{
if (bPrintJetSelection)
if(fDebug>7) printf("rejected (track pt)\n");
continue;
}
}
if (bPrintJetSelection)
if(fDebug>7) printf("accepted\n");
if(fDebug>5) printf("TaskV0sInJets: Jet %d with pt %.2f passed selection\n",iJet,jetSel->Pt());
/*
if (fbTreeOutput)
{
// new ((*fBranchJet)[iNJetAll++]) AliAODJet(*((AliAODJet*)jetSel));
objectJet = new ((*fBranchJet)[iNJetAll++]) AliJetObject(jetSel); // copy selected jet to the array
// objectJet->SetPtLeadingTrack(dPtLeadTrack);
objectJet->SetRadius(fdRadiusJet);
objectJet = 0;
}
*/
TLorentzVector vecPerpPlus(*(jetSel->MomentumVector()));
vecPerpPlus.RotateZ(TMath::Pi()/2.); // rotate vector by 90 deg around z
TLorentzVector vecPerpMinus(*(jetSel->MomentumVector()));
vecPerpMinus.RotateZ(-TMath::Pi()/2.); // rotate vector by -90 deg around z
// AliAODJet jetTmp = AliAODJet(vecPerp);
if(fDebug>5) printf("TaskV0sInJets: Adding perp. cones number %d, %d\n",iNJetPerp,iNJetPerp+1);
// printf("TaskV0sInJets: Adding perp. cone number %d: pT %f, phi %f, eta %f, pT %f, phi %f, eta %f\n",iNJetSel,vecPerp.Pt(),vecPerp.Phi(),vecPerp.Eta(),jetTmp.Pt(),jetTmp.Phi(),jetTmp.Eta());
new ((*jetArrayPerp)[iNJetPerp++]) AliAODJet(vecPerpPlus); // write perp. cone to the array
new ((*jetArrayPerp)[iNJetPerp++]) AliAODJet(vecPerpMinus); // write perp. cone to the array
if(fDebug>5) printf("TaskV0sInJets: Adding jet number %d\n",iNJetSel);
// printf("TaskV0sInJets: Adding jet number %d: pT %f, phi %f, eta %f\n",iNJetSel,jetSel->Pt(),jetSel->Phi(),jetSel->Eta());
new ((*jetArraySel)[iNJetSel++]) AliAODJet(*((AliAODJet*)jetSel)); // copy selected jet to the array
}
if(fDebug>5) printf("TaskV0sInJets: Added jets: %d\n",iNJetSel);
iNJetSel = jetArraySel->GetEntriesFast();
if(fDebug>2) printf("TaskV0sInJets: Selected jets in array: %d\n",iNJetSel);
fh1NJetPerEvent[iCentIndex]->Fill(iNJetSel);
// fill jet spectra
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jet = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
fh1PtJet[iCentIndex]->Fill(jet->Pt()); // pt spectrum of selected jets
fh1EtaJet[iCentIndex]->Fill(jet->Eta()); // eta spectrum of selected jets
fh2EtaPtJet[iCentIndex]->Fill(jet->Eta(),jet->Pt()); // eta-pT spectrum of selected jets
fh1PhiJet[iCentIndex]->Fill(jet->Phi()); // phi spectrum of selected jets
Double_t dAreaExcluded = TMath::Pi()*dRadiusExcludeCone*dRadiusExcludeCone; // area of the cone
dAreaExcluded -= AreaCircSegment(dRadiusExcludeCone,dEtaMax-jet->Eta()); // positive eta overhang
dAreaExcluded -= AreaCircSegment(dRadiusExcludeCone,dEtaMax+jet->Eta()); // negative eta overhang
fh1AreaExcluded->Fill(iCentIndex,dAreaExcluded);
}
jet = 0;
}
if (bJetEventGood) // there should be some reconstructed jets
{
fh1EventCounterCut->Fill(4); // events with jet(s)
fh1EventCounterCutCent[iCentIndex]->Fill(4); // events with jet(s)
if (iNJetSel)
{
fh1EventCounterCut->Fill(5); // events with selected jets
fh1EventCounterCutCent[iCentIndex]->Fill(5);
}
}
if (iNJetSel)
{
jetRnd = GetRandomCone(jetArraySel,dJetEtaWindow,2*fdRadiusJet);
if (jetRnd)
{
fh1NRndConeCent->Fill(iCentIndex);
fh2EtaPhiRndCone[iCentIndex]->Fill(jetRnd->Eta(),jetRnd->Phi());
}
jetMed = GetMedianCluster(jetArrayBg,dJetEtaWindow);
if (jetMed)
{
fh1NMedConeCent->Fill(iCentIndex);
fh2EtaPhiMedCone[iCentIndex]->Fill(jetMed->Eta(),jetMed->Phi());
}
}
// Loading primary vertex info
AliAODVertex* primVtx = fAODIn->GetPrimaryVertex(); // get the primary vertex
Double_t dPrimVtxPos[3]; // primary vertex position {x,y,z}
primVtx->GetXYZ(dPrimVtxPos);
fh1VtxZ[iCentIndex]->Fill(dPrimVtxPos[2]);
fh2VtxXY[iCentIndex]->Fill(dPrimVtxPos[0],dPrimVtxPos[1]);
/*===== Start of loop over V0 candidates =====*/
if(fDebug>2) printf("TaskV0sInJets: Start of V0 loop\n");
for (Int_t iV0 = 0; iV0 < iNV0s; iV0++)
{
v0 = fAODIn->GetV0(iV0); // get next candidate from the list in AOD
if (!v0)
continue;
iNV0CandTot++;
// Initialization of status indicators
Bool_t bIsCandidateK0s = kTRUE; // candidate for K0s
Bool_t bIsCandidateLambda = kTRUE; // candidate for Lambda
Bool_t bIsCandidateALambda = kTRUE; // candidate for Lambda
Bool_t bIsInPeakK0s = kFALSE; // candidate within the K0s mass peak
Bool_t bIsInPeakLambda = kFALSE; // candidate within the Lambda mass peak
Bool_t bIsInConeJet = kFALSE; // candidate within the jet cones
Bool_t bIsInConePerp = kFALSE; // candidate within the perpendicular cone
Bool_t bIsInConeRnd = kFALSE; // candidate within the random cone
Bool_t bIsInConeMed = kFALSE; // candidate within the median-cluster cone
Bool_t bIsOutsideCones = kFALSE; // candidate outside excluded cones
// Invariant mass calculation
dMassV0K0s = v0->MassK0Short();
dMassV0Lambda = v0->MassLambda();
dMassV0ALambda = v0->MassAntiLambda();
Int_t iCutIndex = 0; // indicator of current selection step
// 0
// All V0 candidates
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// Skip candidates outside the histogram range
if ( (dMassV0K0s < fgkdMassK0sMin) || (dMassV0K0s >= fgkdMassK0sMax) )
bIsCandidateK0s = kFALSE;
if ( (dMassV0Lambda < fgkdMassLambdaMin) || (dMassV0Lambda >= fgkdMassLambdaMax) )
bIsCandidateLambda = kFALSE;
if ( (dMassV0ALambda < fgkdMassLambdaMin) || (dMassV0ALambda >= fgkdMassLambdaMax) )
bIsCandidateALambda = kFALSE;
if (!bIsCandidateK0s && !bIsCandidateLambda && !bIsCandidateALambda)
continue;
Double_t dPtV0 = TMath::Sqrt(v0->Pt2V0()); // transverse momentum of V0
vecV0Momentum = TVector3(v0->Px(),v0->Py(),v0->Pz()); // set the vector of V0 momentum
// Sigma of the mass peak window
Double_t dMassPeakWindowK0s = dNSigmaMassMax*MassPeakSigmaOld(dPtV0,0);
Double_t dMassPeakWindowLambda = dNSigmaMassMax*MassPeakSigmaOld(dPtV0,1);
// Double_t dMassPeakWindowK0s = dNSigmaMassMax*MassPeakSigma(iCentIndex,dPtV0,0);
// Double_t dMassPeakWindowLambda = dNSigmaMassMax*MassPeakSigma(iCentIndex,dPtV0,1);
// Invariant mass peak selection
if (TMath::Abs(dMassV0K0s-dMassPDGK0s) < dMassPeakWindowK0s)
bIsInPeakK0s = kTRUE;
if (TMath::Abs(dMassV0Lambda-dMassPDGLambda) < dMassPeakWindowLambda)
bIsInPeakLambda = kTRUE;
// Retrieving all relevant properties of the V0 candidate
Bool_t bOnFlyStatus = v0->GetOnFlyStatus(); // online (on fly) reconstructed vs offline reconstructed
const AliAODTrack* trackPos = (AliAODTrack*)v0->GetDaughter(0); // positive daughter track
const AliAODTrack* trackNeg = (AliAODTrack*)v0->GetDaughter(1); // negative daughter track
Double_t dPtDaughterPos = trackPos->Pt(); // transverse momentum of a daughter track
Double_t dPtDaughterNeg = trackNeg->Pt();
Double_t dNRowsPos = trackPos->GetTPCClusterInfo(2,1); // crossed TPC pad rows of a daughter track
Double_t dNRowsNeg = trackNeg->GetTPCClusterInfo(2,1);
Double_t dDCAToPrimVtxPos = TMath::Abs(v0->DcaPosToPrimVertex()); // dca of a daughter to the primary vertex
Double_t dDCAToPrimVtxNeg = TMath::Abs(v0->DcaNegToPrimVertex());
Double_t dDCADaughters = v0->DcaV0Daughters(); // dca between daughters
Double_t dCPA = v0->CosPointingAngle(primVtx); // cosine of the pointing angle
Double_t dSecVtxPos[3]; // V0 vertex position {x,y,z}
// Double_t dSecVtxPos[3] = {v0->DecayVertexV0X(),v0->DecayVertexV0Y(),v0->DecayVertexV0Z()}; // V0 vertex position
v0->GetSecondaryVtx(dSecVtxPos);
Double_t dRadiusDecay = TMath::Sqrt(dSecVtxPos[0]*dSecVtxPos[0] + dSecVtxPos[1]*dSecVtxPos[1]); // distance of the V0 vertex from the z-axis
Double_t dEtaDaughterNeg = trackNeg->Eta(); // = v0->EtaProng(1), pseudorapidity of a daughter track
Double_t dEtaDaughterPos = trackPos->Eta(); // = v0->EtaProng(0)
Double_t dRapK0s = v0->RapK0Short(); // rapidity calculated for K0s assumption
Double_t dRapLambda = v0->RapLambda(); // rapidity calculated for Lambda assumption
Double_t dEtaV0 = v0->Eta(); // V0 pseudorapidity
// Double_t dPhiV0 = v0->Phi(); // V0 pseudorapidity
Double_t dDecayPath[3];
for (Int_t iPos = 0; iPos < 3; iPos++)
dDecayPath[iPos] = dSecVtxPos[iPos]-dPrimVtxPos[iPos]; // vector of the V0 path
Double_t dDecLen = TMath::Sqrt(dDecayPath[0]*dDecayPath[0]+dDecayPath[1]*dDecayPath[1]+dDecayPath[2]*dDecayPath[2]); // path length L
Double_t dDecLen2D = TMath::Sqrt(dDecayPath[0]*dDecayPath[0]+dDecayPath[1]*dDecayPath[1]); // transverse path length R
Double_t dLOverP = dDecLen/v0->P(); // L/p
Double_t dROverPt = dDecLen2D/dPtV0; // R/pT
Double_t dMLOverPK0s = dMassPDGK0s*dLOverP; // m*L/p = c*(proper lifetime)
// Double_t dMLOverPLambda = dMassPDGLambda*dLOverP; // m*L/p
Double_t dMROverPtK0s = dMassPDGK0s*dROverPt; // m*R/pT
Double_t dMROverPtLambda = dMassPDGLambda*dROverPt; // m*R/pT
Double_t dNSigmaPosPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackPos,AliPID::kPion)); // difference between measured and expected signal of the dE/dx in the TPC
Double_t dNSigmaPosProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackPos,AliPID::kProton));
Double_t dNSigmaNegPion = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackNeg,AliPID::kPion));
Double_t dNSigmaNegProton = TMath::Abs(fPIDResponse->NumberOfSigmasTPC(trackNeg,AliPID::kProton));
Double_t dAlpha = v0->AlphaV0(); // Armenteros-Podolanski alpha
Double_t dPtArm = v0->PtArmV0(); // Armenteros-Podolanski pT
AliAODVertex* prodVtxDaughterPos = (AliAODVertex*)(trackPos->GetProdVertex()); // production vertex of the positive daughter track
Char_t cTypeVtxProdPos = prodVtxDaughterPos->GetType(); // type of the production vertex
AliAODVertex* prodVtxDaughterNeg = (AliAODVertex*)(trackNeg->GetProdVertex()); // production vertex of the negative daughter track
Char_t cTypeVtxProdNeg = prodVtxDaughterNeg->GetType(); // type of the production vertex
fh2Tau3DVs2D[0]->Fill(dPtV0,dLOverP/dROverPt);
// QA histograms before cuts
FillQAHistogramV0(primVtx,v0,0,bIsCandidateK0s,bIsCandidateLambda,bIsInPeakK0s,bIsInPeakLambda);
// Cut vs mass histograms before cuts
if (bIsCandidateK0s)
{
fh2CutTPCRowsK0s[0]->Fill(dMassV0K0s,dNRowsPos);
fh2CutTPCRowsK0s[0]->Fill(dMassV0K0s,dNRowsNeg);
fh2CutPtPosK0s[0]->Fill(dMassV0K0s,dPtDaughterPos);
fh2CutPtNegK0s[0]->Fill(dMassV0K0s,dPtDaughterNeg);
fh2CutDCAVtx[0]->Fill(dMassV0K0s,dDCAToPrimVtxPos);
fh2CutDCAVtx[0]->Fill(dMassV0K0s,dDCAToPrimVtxNeg);
fh2CutDCAV0[0]->Fill(dMassV0K0s,dDCADaughters);
fh2CutCos[0]->Fill(dMassV0K0s,dCPA);
fh2CutR[0]->Fill(dMassV0K0s,dRadiusDecay);
fh2CutEtaK0s[0]->Fill(dMassV0K0s,dEtaDaughterPos);
fh2CutEtaK0s[0]->Fill(dMassV0K0s,dEtaDaughterNeg);
fh2CutRapK0s[0]->Fill(dMassV0K0s,dRapK0s);
fh2CutCTauK0s[0]->Fill(dMassV0K0s,dMROverPtK0s/dCTauK0s);
fh2CutPIDPosK0s[0]->Fill(dMassV0K0s,dNSigmaPosPion);
fh2CutPIDNegK0s[0]->Fill(dMassV0K0s,dNSigmaNegPion);
}
if (bIsCandidateLambda)
{
fh2CutTPCRowsLambda[0]->Fill(dMassV0Lambda,dNRowsPos);
fh2CutTPCRowsLambda[0]->Fill(dMassV0Lambda,dNRowsNeg);
fh2CutPtPosLambda[0]->Fill(dMassV0Lambda,dPtDaughterPos);
fh2CutPtNegLambda[0]->Fill(dMassV0Lambda,dPtDaughterNeg);
fh2CutEtaLambda[0]->Fill(dMassV0Lambda,dEtaDaughterPos);
fh2CutEtaLambda[0]->Fill(dMassV0Lambda,dEtaDaughterNeg);
fh2CutRapLambda[0]->Fill(dMassV0Lambda,dRapLambda);
fh2CutCTauLambda[0]->Fill(dMassV0Lambda,dMROverPtLambda/dCTauLambda);
fh2CutPIDPosLambda[0]->Fill(dMassV0Lambda,dNSigmaPosProton);
fh2CutPIDNegLambda[0]->Fill(dMassV0Lambda,dNSigmaNegPion);
}
/*===== Start of reconstruction cutting =====*/
// 1
// All V0 candidates
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
/* Start of global cuts */
// 2
// Reconstruction method
if (bPrintCuts) printf("Rec: Applying cut: Reconstruction method: on-the-fly? %s\n",(bOnFly ? "yes" : "no"));
if (bOnFlyStatus!=bOnFly)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 3
// Tracks TPC OK
if (bPrintCuts) printf("Rec: Applying cut: Correct charge of daughters\n");
if ( !trackNeg || !trackPos )
continue;
if (trackNeg->Charge() == trackPos->Charge()) // daughters have different charge?
continue;
if (trackNeg->Charge() != -1) // daughters have expected charge?
continue;
if (trackPos->Charge() != 1) // daughters have expected charge?
continue;
if (bPrintCuts) printf("Rec: Applying cut: TPC refit: %d\n",iRefit);
if (!trackNeg->IsOn(iRefit)) // TPC refit is ON?
continue;
if (bPrintCuts) printf("Rec: Applying cut: Type of production vertex of daughter: Not %d\n",AliAODVertex::kKink);
if(cTypeVtxProdNeg == AliAODVertex::kKink) // kink daughter rejection
continue;
// Old cuts Start
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Number of TPC rows: > %f\n",dNCrossedRowsTPCMin);
if (dNRowsNeg < dNCrossedRowsTPCMin) // Crossed TPC padrows
continue;
// Int_t findable = trackNeg->GetTPCNclsF(); // Findable clusters
// if (findable <= 0)
// continue;
// if (dNRowsNeg/findable < dCrossedRowsOverFindMin)
// continue;
// if (dNRowsNeg/findable > dCrossedRowsOverFindMax)
// continue;
}
// Old cuts End
if (!trackPos->IsOn(iRefit))
continue;
if(cTypeVtxProdPos == AliAODVertex::kKink) // kink daughter rejection
continue;
// Old cuts Start
if (bUseOldCuts)
{
if (dNRowsPos < dNCrossedRowsTPCMin)
continue;
// findable = trackPos->GetTPCNclsF();
// if (findable <= 0)
// continue;
// if (dNRowsPos/findable < dCrossedRowsOverFindMin)
// continue;
// if (dNRowsPos/findable > dCrossedRowsOverFindMax)
// continue;
}
// Old cuts End
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 4
// Daughters: transverse momentum cut
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Daughter pT: > %f\n",dPtDaughterMin);
if ( ( dPtDaughterNeg < dPtDaughterMin ) || ( dPtDaughterPos < dPtDaughterMin ) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 5
// Daughters: Impact parameter of daughters to prim vtx
if (bPrintCuts) printf("Rec: Applying cut: Daughter DCA to prim vtx: > %f\n",dDCAToPrimVtxMin);
if ( ( dDCAToPrimVtxNeg < dDCAToPrimVtxMin ) || ( dDCAToPrimVtxPos < dDCAToPrimVtxMin ) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 6
// Daughters: DCA
if (bPrintCuts) printf("Rec: Applying cut: DCA between daughters: < %f\n",dDCADaughtersMax);
if (dDCADaughters > dDCADaughtersMax)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 7
// V0: Cosine of the pointing angle
if (bPrintCuts) printf("Rec: Applying cut: CPA: > %f\n",dCPAMin);
if (dCPA < dCPAMin)
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 8
// V0: Fiducial volume
if (bPrintCuts) printf("Rec: Applying cut: Decay radius: > %f, < %f\n",dRadiusDecayMin,dRadiusDecayMax);
if ( (dRadiusDecay < dRadiusDecayMin) || (dRadiusDecay > dRadiusDecayMax) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
iCutIndex++;
// 9
// Daughters: pseudorapidity cut
if (bCutEtaDaughter)
{
if (bPrintCuts) printf("Rec: Applying cut: Daughter |eta|: < %f\n",dEtaDaughterMax);
if ( (TMath::Abs(dEtaDaughterNeg) > dEtaDaughterMax) || (TMath::Abs(dEtaDaughterPos) > dEtaDaughterMax) )
continue;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
/* End of global cuts */
/* Start of particle-dependent cuts */
// 10
// V0: rapidity cut & pseudorapidity cut
if (bCutRapV0)
{
if (bPrintCuts) printf("Rec: Applying cut: V0 |y|: < %f\n",dRapMax);
if (TMath::Abs(dRapK0s) > dRapMax)
bIsCandidateK0s = kFALSE;
if (TMath::Abs(dRapLambda) > dRapMax)
{
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
}
if (bCutEtaV0)
{
if (bPrintCuts) printf("Rec: Applying cut: V0 |eta|: < %f\n",dEtaMax);
if (TMath::Abs(dEtaV0) > dEtaMax)
{
bIsCandidateK0s = kFALSE;
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 11
// Lifetime cut
if (bCutTau)
{
if (bPrintCuts) printf("Rec: Applying cut: Proper lifetime: < %f\n",dNTauMax);
if (dMROverPtK0s > dNTauMax*dCTauK0s)
bIsCandidateK0s = kFALSE;
if (dMROverPtLambda > dNTauMax*dCTauLambda)
{
bIsCandidateLambda = kFALSE;
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// 12
// Daughter PID
if (bCutPid)
{
if (bUseOldCuts)
{
if (bPrintCuts) printf("Rec: Applying cut: Delta dE/dx (both daughters): < %f\n",dNSigmadEdxMax);
if (dNSigmaPosPion > dNSigmadEdxMax || dNSigmaNegPion > dNSigmadEdxMax) // pi+, pi-
bIsCandidateK0s = kFALSE;
if (dNSigmaPosProton > dNSigmadEdxMax || dNSigmaNegPion > dNSigmadEdxMax) // p+, pi-
bIsCandidateLambda = kFALSE;
if (dNSigmaNegProton > dNSigmadEdxMax || dNSigmaPosPion > dNSigmadEdxMax) // p-, pi+
bIsCandidateALambda = kFALSE;
}
else
{
if (bPrintCuts) printf("Rec: Applying cut: Delta dE/dx (proton below %f GeV/c): < %f\n",dPtProtonPIDMax,dNSigmadEdxMax);
if ( (dPtDaughterPos < dPtProtonPIDMax) && (dNSigmaPosProton > dNSigmadEdxMax) ) // p+
bIsCandidateLambda = kFALSE;
if ( (dPtDaughterNeg < dPtProtonPIDMax) && (dNSigmaNegProton > dNSigmadEdxMax) ) // p-
bIsCandidateALambda = kFALSE;
}
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
Double_t valueCorrel[3] = {dMassV0K0s,dMassV0Lambda,dPtV0};
if (bIsCandidateK0s && bIsCandidateLambda)
fh3CCMassCorrelBoth->Fill(valueCorrel); // correlation of mass distribution of candidates selected as both K0s and Lambda
if (bIsCandidateK0s && !bIsCandidateLambda)
fh3CCMassCorrelKNotL->Fill(valueCorrel); // correlation of mass distribution of candidates selected as K0s and not Lambda
if (!bIsCandidateK0s && bIsCandidateLambda)
fh3CCMassCorrelLNotK->Fill(valueCorrel); // correlation of mass distribution of candidates selected as not K0s and Lambda
// 13
// Armenteros-Podolanski cut
if (bCutArmPod)
{
if (bPrintCuts) printf("Rec: Applying cut: Armenteros-Podolanski (K0S): pT > %f * |alpha|\n",0.2);
if(dPtArm < TMath::Abs(0.2*dAlpha))
bIsCandidateK0s = kFALSE;
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
}
iCutIndex++;
// Cross contamination
if (bIsInPeakK0s)
{
if (bIsCandidateLambda) // Lambda candidates in K0s peak, excluded from Lambda candidates by CC cut
fh2CCLambda->Fill(dMassV0Lambda,dPtV0);
}
if (bIsInPeakLambda)
{
if (bIsCandidateK0s) // K0s candidates in Lambda peak, excluded from K0s candidates by CC cut
fh2CCK0s->Fill(dMassV0K0s,dPtV0);
}
// if (bCutCross)
// {
// if (bIsInPeakK0s)
// bIsCandidateLambda = kFALSE;
// if (bIsInPeakLambda)
// bIsCandidateK0s = kFALSE;
// FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, bIsCandidateLambda, bIsCandidateALambda, iCutIndex, iCentIndex);
// }
// iCutIndex++;
/* End of particle-dependent cuts */
/*===== End of reconstruction cutting =====*/
if (!bIsCandidateK0s && !bIsCandidateLambda && !bIsCandidateALambda)
continue;
/*
if(fDebug>5) printf("TaskV0sInJets: Adding selected V0 to branch\n");
// Add selected candidates to the output tree branch
if ((bIsCandidateK0s || bIsCandidateLambda || bIsCandidateALambda) && fbTreeOutput)
{
objectV0 = new ((*fBranchV0Rec)[iNV0SelV0Rec++]) AliV0Object(v0,primVtx);
// new ((*fBranchV0Rec)[iNV0SelV0Rec++]) AliAODv0(*((AliAODv0*)v0));
objectV0->SetIsCandidateK0S(bIsCandidateK0s);
objectV0->SetIsCandidateLambda(bIsCandidateLambda);
objectV0->SetIsCandidateALambda(bIsCandidateALambda);
objectV0->SetNSigmaPosProton(dNSigmaPosProton);
objectV0->SetNSigmaNegProton(dNSigmaNegProton);
}
*/
// Selection of V0s in jet cones, perpendicular cones, random cones, outside cones
if (bJetEventGood && iNJetSel && (bIsCandidateK0s || bIsCandidateLambda || bIsCandidateALambda))
{
// Selection of V0s in jet cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in %d jet cones\n",bIsCandidateK0s,bIsCandidateLambda,iNJetSel);
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jet = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
vecJetMomentum = TVector3(jet->Px(),jet->Py(),jet->Pz()); // set the vector of jet momentum
if(fDebug>5) printf("TaskV0sInJets: Checking if V0 %d %d in jet cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
if (IsParticleInCone(v0,jet,fdRadiusJet)) // If good jet in event, find out whether V0 is in that jet
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in jet cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
bIsInConeJet = kTRUE;
break;
}
}
// Selection of V0s in perp. cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in %d perp. cones\n",bIsCandidateK0s,bIsCandidateLambda,iNJetSel);
for (Int_t iJet = 0; iJet<iNJetPerp; iJet++)
{
jetPerp = (AliAODJet*)jetArrayPerp->At(iJet); // load a jet in the list
if(fDebug>5) printf("TaskV0sInJets: Checking if V0 %d %d in perp. cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
if (IsParticleInCone(v0,jetPerp,fdRadiusJet)) // V0 in perp. cone
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in perp. cone %d\n",bIsCandidateK0s,bIsCandidateLambda,iJet);
bIsInConePerp = kTRUE;
break;
}
}
// Selection of V0s in random cones
if (jetRnd)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in the rnd. cone\n",bIsCandidateK0s,bIsCandidateLambda);
if (IsParticleInCone(v0,jetRnd,fdRadiusJet)) // V0 in rnd. cone?
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in the rnd. cone\n",bIsCandidateK0s,bIsCandidateLambda);
bIsInConeRnd = kTRUE;
}
}
// Selection of V0s in median-cluster cones
if (jetMed)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d in the med. cone\n",bIsCandidateK0s,bIsCandidateLambda);
if (IsParticleInCone(v0,jetMed,fdRadiusJet)) // V0 in med. cone?
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found in the med. cone\n",bIsCandidateK0s,bIsCandidateLambda);
bIsInConeMed = kTRUE;
}
}
// Selection of V0s outside jet cones
if(fDebug>5) printf("TaskV0sInJets: Searching for V0 %d %d outside jet cones\n",bIsCandidateK0s,bIsCandidateLambda);
if (!OverlapWithJets(jetArraySel,v0,dRadiusExcludeCone)) // V0 oustide jet cones
{
if(fDebug>5) printf("TaskV0sInJets: V0 %d %d found outside jet cones\n",bIsCandidateK0s,bIsCandidateLambda);
bIsOutsideCones = kTRUE;
}
}
// QA histograms after cuts
FillQAHistogramV0(primVtx,v0,1,bIsCandidateK0s,bIsCandidateLambda,bIsInPeakK0s,bIsInPeakLambda);
// Cut vs mass histograms after cuts
if (bIsCandidateK0s)
{
fh2CutTPCRowsK0s[1]->Fill(dMassV0K0s,dNRowsPos);
fh2CutTPCRowsK0s[1]->Fill(dMassV0K0s,dNRowsNeg);
fh2CutPtPosK0s[1]->Fill(dMassV0K0s,dPtDaughterPos);
fh2CutPtNegK0s[1]->Fill(dMassV0K0s,dPtDaughterNeg);
fh2CutDCAVtx[1]->Fill(dMassV0K0s,dDCAToPrimVtxPos);
fh2CutDCAVtx[1]->Fill(dMassV0K0s,dDCAToPrimVtxNeg);
fh2CutDCAV0[1]->Fill(dMassV0K0s,dDCADaughters);
fh2CutCos[1]->Fill(dMassV0K0s,dCPA);
fh2CutR[1]->Fill(dMassV0K0s,dRadiusDecay);
fh2CutEtaK0s[1]->Fill(dMassV0K0s,dEtaDaughterPos);
fh2CutEtaK0s[1]->Fill(dMassV0K0s,dEtaDaughterNeg);
fh2CutRapK0s[1]->Fill(dMassV0K0s,dRapK0s);
fh2CutCTauK0s[1]->Fill(dMassV0K0s,dMROverPtK0s/dCTauK0s);
fh2CutPIDPosK0s[1]->Fill(dMassV0K0s,dNSigmaPosPion);
fh2CutPIDNegK0s[1]->Fill(dMassV0K0s,dNSigmaNegPion);
fh1DeltaZK0s[iCentIndex]->Fill(dDecayPath[2]);
}
if (bIsCandidateLambda)
{
fh2CutTPCRowsLambda[1]->Fill(dMassV0Lambda,dNRowsPos);
fh2CutTPCRowsLambda[1]->Fill(dMassV0Lambda,dNRowsNeg);
fh2CutPtPosLambda[1]->Fill(dMassV0Lambda,dPtDaughterPos);
fh2CutPtNegLambda[1]->Fill(dMassV0Lambda,dPtDaughterNeg);
fh2CutEtaLambda[1]->Fill(dMassV0Lambda,dEtaDaughterPos);
fh2CutEtaLambda[1]->Fill(dMassV0Lambda,dEtaDaughterNeg);
fh2CutRapLambda[1]->Fill(dMassV0Lambda,dRapLambda);
fh2CutCTauLambda[1]->Fill(dMassV0Lambda,dMROverPtLambda/dCTauLambda);
fh2CutPIDPosLambda[1]->Fill(dMassV0Lambda,dNSigmaPosProton);
fh2CutPIDNegLambda[1]->Fill(dMassV0Lambda,dNSigmaNegPion);
fh1DeltaZLambda[iCentIndex]->Fill(dDecayPath[2]);
}
/*===== Start of filling V0 spectra =====*/
Double_t dAngle = TMath::Pi(); // angle between V0 momentum and jet momentum
if (bIsInConeJet)
{
dAngle = vecV0Momentum.Angle(vecJetMomentum);
}
// iCutIndex = 14
if (bIsCandidateK0s)
{
// 14 K0s candidates after cuts
// printf("K0S: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0K0s,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex, iCentIndex);
Double_t valueKIncl[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InclusiveK0s[iCentIndex]->Fill(valueKIncl);
fh1V0InvMassK0sCent[iCentIndex]->Fill(dMassV0K0s);
fh1QACTau2D[1]->Fill(dMROverPtK0s/dCTauK0s);
fh1QACTau3D[1]->Fill(dMLOverPK0s/dCTauK0s);
fh2Tau3DVs2D[1]->Fill(dPtV0,dLOverP/dROverPt);
if (iNJetSel)
{
// 15 K0s in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 K0s in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, bIsCandidateK0s, kFALSE, kFALSE, iCutIndex+2, iCentIndex);
Double_t valueKInJC[4] = {dMassV0K0s,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetK0s[iCentIndex]->Fill(valueKInJC);
fh2V0PtJetAngleK0s[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueKOutJC[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0OutJetK0s[iCentIndex]->Fill(valueKOutJC);
}
if (bIsInConePerp)
{
Double_t valueKInPC[4] = {dMassV0K0s,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpK0s[iCentIndex]->Fill(valueKInPC);
}
if (bIsInConeRnd)
{
Double_t valueKInRnd[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InRndK0s[iCentIndex]->Fill(valueKInRnd);
}
if (bIsInConeMed)
{
Double_t valueKInMed[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0InMedK0s[iCentIndex]->Fill(valueKInMed);
}
if (!iNJetSel)
{
Double_t valueKNoJet[3] = {dMassV0K0s,dPtV0,dEtaV0};
fhnV0NoJetK0s[iCentIndex]->Fill(valueKNoJet);
}
iNV0CandK0s++;
}
if (bIsCandidateLambda)
{
// 14 Lambda candidates after cuts
// printf("La: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0Lambda,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex, iCentIndex);
Double_t valueLIncl[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InclusiveLambda[iCentIndex]->Fill(valueLIncl);
fh1V0InvMassLambdaCent[iCentIndex]->Fill(dMassV0Lambda);
if (iNJetSel)
{
// 15 Lambda in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 Lambda in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, bIsCandidateLambda, kFALSE, iCutIndex+2, iCentIndex);
Double_t valueLInJC[4] = {dMassV0Lambda,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetLambda[iCentIndex]->Fill(valueLInJC);
fh2V0PtJetAngleLambda[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueLOutJet[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0OutJetLambda[iCentIndex]->Fill(valueLOutJet);
}
if (bIsInConePerp)
{
Double_t valueLInPC[4] = {dMassV0Lambda,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpLambda[iCentIndex]->Fill(valueLInPC);
}
if (bIsInConeRnd)
{
Double_t valueLInRnd[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InRndLambda[iCentIndex]->Fill(valueLInRnd);
}
if (bIsInConeMed)
{
Double_t valueLInMed[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0InMedLambda[iCentIndex]->Fill(valueLInMed);
}
if (!iNJetSel)
{
Double_t valueLNoJet[3] = {dMassV0Lambda,dPtV0,dEtaV0};
fhnV0NoJetLambda[iCentIndex]->Fill(valueLNoJet);
}
iNV0CandLambda++;
}
if (bIsCandidateALambda)
{
// 14 ALambda candidates after cuts
// printf("AL: i = %d, m = %f, pT = %f, eta = %f, phi = %f\n",iV0,dMassV0ALambda,dPtV0,dEtaV0,dPhiV0);
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex, iCentIndex);
Double_t valueALIncl[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InclusiveALambda[iCentIndex]->Fill(valueALIncl);
fh1V0InvMassALambdaCent[iCentIndex]->Fill(dMassV0ALambda);
if (iNJetSel)
{
// 15 ALambda in jet events
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex+1, iCentIndex);
}
if (bIsInConeJet)
{
// 16 ALambda in jets
FillCandidates(dMassV0K0s, dMassV0Lambda, dMassV0ALambda, kFALSE, kFALSE, bIsCandidateALambda, iCutIndex+2, iCentIndex);
Double_t valueLInJC[4] = {dMassV0ALambda,dPtV0,dEtaV0,jet->Pt()};
fhnV0InJetALambda[iCentIndex]->Fill(valueLInJC);
fh2V0PtJetAngleALambda[iCentIndex]->Fill(jet->Pt(),dAngle);
}
if (bIsOutsideCones)
{
Double_t valueALOutJet[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0OutJetALambda[iCentIndex]->Fill(valueALOutJet);
}
if (bIsInConePerp)
{
Double_t valueLInPC[4] = {dMassV0ALambda,dPtV0,dEtaV0,jetPerp->Pt()};
fhnV0InPerpALambda[iCentIndex]->Fill(valueLInPC);
}
if (bIsInConeRnd)
{
Double_t valueALInRnd[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InRndALambda[iCentIndex]->Fill(valueALInRnd);
}
if (bIsInConeMed)
{
Double_t valueALInMed[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0InMedALambda[iCentIndex]->Fill(valueALInMed);
}
if (!iNJetSel)
{
Double_t valueALNoJet[3] = {dMassV0ALambda,dPtV0,dEtaV0};
fhnV0NoJetALambda[iCentIndex]->Fill(valueALNoJet);
}
iNV0CandALambda++;
}
/*===== End of filling V0 spectra =====*/
/*===== Association of reconstructed V0 candidates with MC particles =====*/
if (fbMCAnalysis)
{
// Associate selected candidates only
// if ( !(bIsCandidateK0s && bIsInPeakK0s) && !(bIsCandidateLambda && bIsInPeakLambda) ) // signal candidates
if ( !(bIsCandidateK0s) && !(bIsCandidateLambda) && !(bIsCandidateALambda) ) // chosen candidates with any mass
continue;
// Get MC labels of reconstructed daughter tracks
Int_t iLabelPos = TMath::Abs(trackPos->GetLabel());
Int_t iLabelNeg = TMath::Abs(trackNeg->GetLabel());
// Make sure MC daughters are in the array range
if ( (iLabelNeg<0) || (iLabelNeg>=iNTracksMC) || (iLabelPos<0) || (iLabelPos>=iNTracksMC) )
continue;
// Get MC particles corresponding to reconstructed daughter tracks
AliAODMCParticle* particleMCDaughterNeg = (AliAODMCParticle*)arrayMC->At(iLabelNeg);
AliAODMCParticle* particleMCDaughterPos = (AliAODMCParticle*)arrayMC->At(iLabelPos);
if (!particleMCDaughterNeg || !particleMCDaughterPos)
continue;
// Make sure MC daughter particles are not physical primary
if ( (particleMCDaughterNeg->IsPhysicalPrimary()) || (particleMCDaughterPos->IsPhysicalPrimary()) )
continue;
// Get identities of MC daughter particles
Int_t iPdgCodeDaughterPos = particleMCDaughterPos->GetPdgCode();
Int_t iPdgCodeDaughterNeg = particleMCDaughterNeg->GetPdgCode();
// Get index of the mother particle for each MC daughter particle
Int_t iIndexMotherPos = particleMCDaughterPos->GetMother();
Int_t iIndexMotherNeg = particleMCDaughterNeg->GetMother();
if ( (iIndexMotherNeg<0) || (iIndexMotherNeg>=iNTracksMC) || (iIndexMotherPos<0) || (iIndexMotherPos>=iNTracksMC) )
continue;
// Check whether MC daughter particles have the same mother
if (iIndexMotherNeg != iIndexMotherPos)
continue;
// Get the MC mother particle of both MC daughter particles
AliAODMCParticle* particleMCMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherPos);
if (!particleMCMother)
continue;
// Get identity of the MC mother particle
Int_t iPdgCodeMother = particleMCMother->GetPdgCode();
// Skip not interesting particles
if ( (iPdgCodeMother != iPdgCodeK0s) && (TMath::Abs(iPdgCodeMother) != iPdgCodeLambda) )
continue;
// Check identity of the MC mother particle and the decay channel
// Is MC mother particle K0S?
Bool_t bV0MCIsK0s = ( (iPdgCodeMother==iPdgCodeK0s) && (iPdgCodeDaughterPos==+iPdgCodePion) && (iPdgCodeDaughterNeg==-iPdgCodePion) );
// Is MC mother particle Lambda?
Bool_t bV0MCIsLambda = ( (iPdgCodeMother==+iPdgCodeLambda) && (iPdgCodeDaughterPos==+iPdgCodeProton) && (iPdgCodeDaughterNeg==-iPdgCodePion) );
// Is MC mother particle anti-Lambda?
Bool_t bV0MCIsALambda = ( (iPdgCodeMother==-iPdgCodeLambda) && (iPdgCodeDaughterPos==+iPdgCodePion) && (iPdgCodeDaughterNeg==-iPdgCodeProton) );
Double_t dPtV0Gen = particleMCMother->Pt();
// Double_t dRapV0MC = particleMCMother->Y();
Double_t dEtaV0Gen = particleMCMother->Eta();
// Double_t dPhiV0Gen = particleMCMother->Phi();
// Is MC mother particle physical primary? Attention!! Definition of IsPhysicalPrimary may change!!
// Bool_t bV0MCIsPrimary = particleMCMother->IsPhysicalPrimary();
// Get the MC mother particle of the MC mother particle
Int_t iIndexMotherOfMother = particleMCMother->GetMother();
AliAODMCParticle* particleMCMotherOfMother = 0;
if (iIndexMotherOfMother >= 0)
particleMCMotherOfMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherOfMother);
// Get identity of the MC mother particle of the MC mother particle if it exists
Int_t iPdgCodeMotherOfMother = 0;
if (particleMCMotherOfMother)
iPdgCodeMotherOfMother = particleMCMotherOfMother->GetPdgCode();
// Check if the MC mother particle of the MC mother particle is a physical primary Sigma (3212 - Sigma0, 3224 - Sigma*+, 3214 - Sigma*0, 3114 - Sigma*-)
// Bool_t bV0MCComesFromSigma = kFALSE; // Is MC mother particle daughter of a Sigma?
// if ( (particleMCMotherOfMother && particleMCMotherOfMother->IsPhysicalPrimary()) && ( (TMath::Abs(iPdgCodeMotherOfMother)==3212) || (TMath::Abs(iPdgCodeMotherOfMother)==3224) || (TMath::Abs(iPdgCodeMotherOfMother)==3214) || (TMath::Abs(iPdgCodeMotherOfMother)==3114) ) )
// bV0MCComesFromSigma = kTRUE;
// Should MC mother particle be considered as primary when it is Lambda?
// Bool_t bV0MCIsPrimaryLambda = (bV0MCIsPrimary || bV0MCComesFromSigma);
// Check if the MC mother particle of the MC mother particle is a Xi (3322 - Xi0, 3312 - Xi-)
Bool_t bV0MCComesFromXi = ( (particleMCMotherOfMother) && ( (iPdgCodeMotherOfMother==3322) || (iPdgCodeMotherOfMother==3312) ) ); // Is MC mother particle daughter of a Xi?
Bool_t bV0MCComesFromAXi = ( (particleMCMotherOfMother) && ( (iPdgCodeMotherOfMother==-3322) || (iPdgCodeMotherOfMother==-3312) ) ); // Is MC mother particle daughter of a anti-Xi?
// Get the distance between production point of the MC mother particle and the primary vertex
Double_t dx = dPrimVtxMCX-particleMCMother->Xv();
Double_t dy = dPrimVtxMCY-particleMCMother->Yv();
Double_t dz = dPrimVtxMCZ-particleMCMother->Zv();
Double_t dDistPrimary = TMath::Sqrt(dx*dx + dy*dy + dz*dz);
Bool_t bV0MCIsPrimaryDist = (dDistPrimary < dDistPrimaryMax); // Is close enough to be considered primary-like?
// phi, eta resolution for V0-reconstruction
// Double_t dResolutionV0Eta = particleMCMother->Eta()-v0->Eta();
// Double_t dResolutionV0Phi = particleMCMother->Phi()-v0->Phi();
/*
if (fbTreeOutput)
{
objectV0->SetPtTrue(dPtV0Gen);
objectV0->SetEtaTrue(dEtaV0Gen);
objectV0->SetPhiTrue(dPhiV0Gen);
objectV0->SetPDGCode(iPdgCodeMother);
objectV0->SetPDGCodeMother(iPdgCodeMotherOfMother);
}
*/
// K0s
// if (bIsCandidateK0s && bIsInPeakK0s) // selected candidates in peak
if (bIsCandidateK0s) // selected candidates with any mass
{
// if (bV0MCIsK0s && bV0MCIsPrimary) // well reconstructed candidates
if (bV0MCIsK0s && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0K0sPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0K0s);
Double_t valueEtaK[3] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen};
fh3V0K0sEtaPtMassMCRec[iCentIndex]->Fill(valueEtaK);
Double_t valueEtaDKNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0K0sInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKNeg);
Double_t valueEtaDKPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0K0sInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKPos);
fh2V0K0sMCResolMPt[iCentIndex]->Fill(dMassV0K0s-dMassPDGK0s,dPtV0);
fh2V0K0sMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a candidate in jet
{
Double_t valueKInJCMC[4] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0K0sInJetPtMassMCRec[iCentIndex]->Fill(valueKInJCMC);
Double_t valueEtaKIn[5] = {dMassV0K0s,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0K0sInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaKIn);
Double_t valueEtaDKJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0K0sInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKJCNeg);
Double_t valueEtaDKJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0K0sInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDKJCPos);
}
}
if (bV0MCIsK0s && !bV0MCIsPrimaryDist) // not primary K0s
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0K0sPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
// Lambda
// if (bIsCandidateLambda && bIsInPeakLambda) // selected candidates in peak
if (bIsCandidateLambda) // selected candidates with any mass
{
// if (bV0MCIsLambda && bV0MCIsPrimaryLambda) // well reconstructed candidates
if (bV0MCIsLambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0LambdaPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0Lambda);
Double_t valueEtaL[3] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen};
fh3V0LambdaEtaPtMassMCRec[iCentIndex]->Fill(valueEtaL);
Double_t valueEtaDLNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0LambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLNeg);
Double_t valueEtaDLPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0LambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLPos);
fh2V0LambdaMCResolMPt[iCentIndex]->Fill(dMassV0Lambda-dMassPDGLambda,dPtV0);
fh2V0LambdaMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a reconstructed candidate in jet
{
Double_t valueLInJCMC[4] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0LambdaInJetPtMassMCRec[iCentIndex]->Fill(valueLInJCMC);
Double_t valueEtaLIn[5] = {dMassV0Lambda,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0LambdaInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaLIn);
Double_t valueEtaDLJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLJCNeg);
Double_t valueEtaDLJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0LambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDLJCPos);
}
}
// Fill the feed-down histograms
if (bV0MCIsLambda && bV0MCComesFromXi)
{
// if (fbTreeOutput)
// objectV0->SetOrigin(2);
Double_t valueFDLIncl[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),0.};
fhnV0LambdaInclMCFD[iCentIndex]->Fill(valueFDLIncl);
if (bIsInConeRnd)
{
fhnV0LambdaBulkMCFD[iCentIndex]->Fill(valueFDLIncl);
}
if (bIsInConeJet)
{
Double_t valueFDLInJets[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),jet->Pt()};
fhnV0LambdaInJetsMCFD[iCentIndex]->Fill(valueFDLInJets);
}
}
if (bV0MCIsLambda && !bV0MCIsPrimaryDist && !bV0MCComesFromXi) // not primary Lambda
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0LambdaPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
// anti-Lambda
// if (bIsCandidateALambda && bIsInPeakALambda) // selected candidates in peak
if (bIsCandidateALambda) // selected candidates with any mass
{
// if (bV0MCIsALambda && bV0MCIsPrimaryALambda) // well reconstructed candidates
if (bV0MCIsALambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// objectV0->SetOrigin(1);
fh2V0ALambdaPtMassMCRec[iCentIndex]->Fill(dPtV0Gen,dMassV0ALambda);
Double_t valueEtaAL[3] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen};
fh3V0ALambdaEtaPtMassMCRec[iCentIndex]->Fill(valueEtaAL);
Double_t valueEtaDALNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0ALambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALNeg);
Double_t valueEtaDALPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,0};
fhnV0ALambdaInclDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALPos);
fh2V0ALambdaMCResolMPt[iCentIndex]->Fill(dMassV0ALambda-dMassPDGLambda,dPtV0);
fh2V0ALambdaMCPtGenPtRec[iCentIndex]->Fill(dPtV0Gen,dPtV0);
if (bIsInConeJet) // true V0 associated to a reconstructed candidate in jet
{
Double_t valueALInJCMC[4] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen,jet->Pt()};
fh3V0ALambdaInJetPtMassMCRec[iCentIndex]->Fill(valueALInJCMC);
Double_t valueEtaALIn[5] = {dMassV0ALambda,dPtV0Gen,dEtaV0Gen,jet->Pt(),dEtaV0Gen-jet->Eta()};
fh4V0ALambdaInJetEtaPtMassMCRec[iCentIndex]->Fill(valueEtaALIn);
Double_t valueEtaDALJCNeg[6] = {0,particleMCDaughterNeg->Eta(),particleMCDaughterNeg->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALJCNeg);
Double_t valueEtaDALJCPos[6] = {1,particleMCDaughterPos->Eta(),particleMCDaughterPos->Pt(),dEtaV0Gen,dPtV0Gen,jet->Pt()};
fhnV0ALambdaInJetsDaughterEtaPtPtMCRec[iCentIndex]->Fill(valueEtaDALJCPos);
}
}
// Fill the feed-down histograms
if (bV0MCIsALambda && bV0MCComesFromAXi)
{
// if (fbTreeOutput)
// objectV0->SetOrigin(2);
Double_t valueFDALIncl[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),0.};
fhnV0ALambdaInclMCFD[iCentIndex]->Fill(valueFDALIncl);
if (bIsInConeRnd)
{
fhnV0ALambdaBulkMCFD[iCentIndex]->Fill(valueFDALIncl);
}
if (bIsInConeJet)
{
Double_t valueFDALInJets[3] = {dPtV0Gen,particleMCMotherOfMother->Pt(),jet->Pt()};
fhnV0ALambdaInJetsMCFD[iCentIndex]->Fill(valueFDALInJets);
}
}
if (bV0MCIsALambda && !bV0MCIsPrimaryDist && !bV0MCComesFromAXi) // not primary anti-Lambda
{
// if (fbTreeOutput)
// objectV0->SetOrigin(-1);
fh1V0ALambdaPtMCRecFalse[iCentIndex]->Fill(dPtV0Gen);
}
}
}
/*===== End Association of reconstructed V0 candidates with MC particles =====*/
}
/*===== End of V0 loop =====*/
fh1V0CandPerEvent->Fill(iNV0CandTot);
fh1V0CandPerEventCentK0s[iCentIndex]->Fill(iNV0CandK0s);
fh1V0CandPerEventCentLambda[iCentIndex]->Fill(iNV0CandLambda);
fh1V0CandPerEventCentALambda[iCentIndex]->Fill(iNV0CandALambda);
if(fDebug>2) printf("TaskV0sInJets: End of V0 loop\n");
// Spectra of generated particles
if (fbMCAnalysis)
{
for (Int_t iPartMC = 0; iPartMC < iNTracksMC; iPartMC++)
{
// Get MC particle
AliAODMCParticle* particleMC = (AliAODMCParticle*)arrayMC->At(iPartMC);
if(!particleMC)
continue;
// Get identity of MC particle
Int_t iPdgCodeParticleMC = particleMC->GetPdgCode();
// Fill Xi spectrum (3322 - Xi0, 3312 - Xi-)
// if ( (iPdgCodeParticleMC==3322) || (iPdgCodeParticleMC==3312) )
if ( (iPdgCodeParticleMC==3312) && (TMath::Abs(particleMC->Y())<0.5) )
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0XiPtMCGen[iCentIndex]->Fill(particleMC->Pt());
}
if ( (iPdgCodeParticleMC==-3312) && (TMath::Abs(particleMC->Y())<0.5) )
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0AXiPtMCGen[iCentIndex]->Fill(particleMC->Pt());
}
// Skip not interesting particles
if ( (iPdgCodeParticleMC != iPdgCodeK0s) && (TMath::Abs(iPdgCodeParticleMC) != iPdgCodeLambda) )
continue;
// Check identity of the MC V0 particle
// Is MC V0 particle K0S?
Bool_t bV0MCIsK0s = (iPdgCodeParticleMC==iPdgCodeK0s);
// Is MC V0 particle Lambda?
Bool_t bV0MCIsLambda = (iPdgCodeParticleMC==+iPdgCodeLambda);
// Is MC V0 particle anti-Lambda?
Bool_t bV0MCIsALambda = (iPdgCodeParticleMC==-iPdgCodeLambda);
Double_t dPtV0Gen = particleMC->Pt();
Double_t dRapV0Gen = particleMC->Y();
Double_t dEtaV0Gen = particleMC->Eta();
// V0 rapidity cut
if (bCutRapV0)
{
if (bPrintCuts) printf("Gen: Applying cut: V0 |y|: < %f\n",dRapMax);
if ( (TMath::Abs(dRapV0Gen) > dRapMax) )
continue;
}
// V0 pseudorapidity cut
if (bCutEtaV0)
{
if (bPrintCuts) printf("Gen: Applying cut: V0 |eta|: < %f\n",dEtaMax);
if ( (TMath::Abs(dEtaV0Gen) > dEtaMax) )
continue;
}
/*
// Is MC V0 particle physical primary? Attention!! Definition of IsPhysicalPrimary may change!!
Bool_t bV0MCIsPrimary = particleMC->IsPhysicalPrimary();
// Get the MC mother particle of the MC V0 particle
Int_t iIndexMotherOfMother = particleMC->GetMother();
AliAODMCParticle* particleMCMotherOfMother = 0;
if (iIndexMotherOfMother >= 0)
particleMCMotherOfMother = (AliAODMCParticle*)arrayMC->At(iIndexMotherOfMother);
// Get identity of the MC mother particle of the MC V0 particle if it exists
Int_t iPdgCodeMotherOfMother = 0;
if (particleMCMotherOfMother)
iPdgCodeMotherOfMother = particleMCMotherOfMother->GetPdgCode();
// Check if the MC mother particle is a physical primary Sigma
Bool_t bV0MCComesFromSigma = kFALSE;
if ((particleMCMotherOfMother && particleMCMotherOfMother->IsPhysicalPrimary()) && (TMath::Abs(iPdgCodeMotherOfMother)==3212) || (TMath::Abs(iPdgCodeMotherOfMother)==3224) || (TMath::Abs(iPdgCodeMotherOfMother)==3214) || (TMath::Abs(iPdgCodeMotherOfMother)==3114) )
bV0MCComesFromSigma = kTRUE;
// Should the MC V0 particle be considered as primary when it is Lambda?
Bool_t bV0MCIsPrimaryLambda = (bV0MCIsPrimary || bV0MCComesFromSigma);
*/
// Reject non primary particles
// if (!bV0MCIsPrimaryLambda)
// continue;
// Get the distance between the production point of the MC V0 particle and the primary vertex
Double_t dx = dPrimVtxMCX-particleMC->Xv();
Double_t dy = dPrimVtxMCY-particleMC->Yv();
Double_t dz = dPrimVtxMCZ-particleMC->Zv();
Double_t dDistPrimary = TMath::Sqrt(dx*dx + dy*dy + dz*dz);
Bool_t bV0MCIsPrimaryDist = (dDistPrimary < dDistPrimaryMax); // Is close enough to be considered primary-like?
// Check whether the MC V0 particle is in a MC jet
AliAODJet* jetMC = 0;
Bool_t bIsMCV0InJet = kFALSE;
if (iNJetSel)
{
if(fDebug>5) printf("TaskV0sInJets: Searching for gen V0 in %d MC jets\n",iNJetSel);
for (Int_t iJet = 0; iJet<iNJetSel; iJet++)
{
jetMC = (AliAODJet*)jetArraySel->At(iJet); // load a jet in the list
if(fDebug>5) printf("TaskV0sInJets: Checking if gen V0 in MC jet %d\n",iJet);
if (IsParticleInCone(particleMC,jetMC,fdRadiusJet)) // If good jet in event, find out whether V0 is in that jet
{
if(fDebug>5) printf("TaskV0sInJets: gen V0 found in MC jet %d\n",iJet);
bIsMCV0InJet = kTRUE;
break;
}
}
}
// Select only primary-like MC V0 particles
// K0s
// if (bV0MCIsK0s && bV0MCIsPrimary) // well reconstructed candidates
if (bV0MCIsK0s && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0K0sPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0K0sEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0K0sInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaKInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0K0sInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaKInGen);
}
}
// Lambda
// if (bV0MCIsLambda && bV0MCIsPrimaryLambda) // well reconstructed candidates
if (bV0MCIsLambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0LambdaPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0LambdaEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0LambdaInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaLInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0LambdaInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaLInGen);
}
}
// anti-Lambda
// if (bV0MCIsALambda && bV0MCIsPrimaryALambda) // well reconstructed candidates
if (bV0MCIsALambda && bV0MCIsPrimaryDist) // well reconstructed candidates
{
// if (fbTreeOutput)
// new ((*fBranchV0Gen)[iNV0SelV0Gen++]) AliAODMCParticle(*((AliAODMCParticle*)particleMC));
fh1V0ALambdaPtMCGen[iCentIndex]->Fill(dPtV0Gen);
fh2V0ALambdaEtaPtMCGen[iCentIndex]->Fill(dPtV0Gen,dEtaV0Gen);
if (bIsMCV0InJet)
{
fh2V0ALambdaInJetPtMCGen[iCentIndex]->Fill(dPtV0Gen,jetMC->Pt());
Double_t valueEtaALInGen[4] = {dPtV0Gen,dEtaV0Gen,jetMC->Pt(),dEtaV0Gen-jetMC->Eta()};
fh3V0ALambdaInJetEtaPtMCGen[iCentIndex]->Fill(valueEtaALInGen);
}
}
}
}
// if (fbTreeOutput)
// ftreeOut->Fill();
jetArraySel->Delete();
delete jetArraySel;
jetArrayPerp->Delete();
delete jetArrayPerp;
if (jetRnd)
delete jetRnd;
jetRnd = 0;
PostData(1,fOutputListStd);
PostData(2,fOutputListQA);
PostData(3,fOutputListCuts);
PostData(4,fOutputListMC);
// if (fbTreeOutput)
// PostData(5,ftreeOut);
// if(fDebug>5) printf("TaskV0sInJets: UserExec: End\n");
}
void AliAnalysisTaskV0sInJets::FillQAHistogramV0(AliAODVertex* vtx, const AliAODv0* vZero, Int_t iIndexHisto, Bool_t IsCandK0s, Bool_t IsCandLambda, Bool_t IsInPeakK0s, Bool_t IsInPeakLambda)
{
if (!IsCandK0s && !IsCandLambda)
return;
// Double_t dMassK0s = vZero->MassK0Short();
// Double_t dMassLambda = vZero->MassLambda();
fh1QAV0Status[iIndexHisto]->Fill(vZero->GetOnFlyStatus());
AliAODTrack* trackNeg=(AliAODTrack*)vZero->GetDaughter(1); // negative track
AliAODTrack* trackPos=(AliAODTrack*)vZero->GetDaughter(0); // positive track
Short_t fTotalCharge = 0;
for (Int_t i = 0; i < 2; i++)
{
AliAODTrack* track = (AliAODTrack*)vZero->GetDaughter(i); // track
// Tracks TPC OK
fh1QAV0TPCRefit[iIndexHisto]->Fill(track->IsOn(AliAODTrack::kTPCrefit));
Double_t nCrossedRowsTPC = track->GetTPCClusterInfo(2,1);
fh1QAV0TPCRows[iIndexHisto]->Fill(nCrossedRowsTPC);
Int_t findable = track->GetTPCNclsF();
fh1QAV0TPCFindable[iIndexHisto]->Fill(findable);
if (findable != 0)
{
fh1QAV0TPCRowsFind[iIndexHisto]->Fill(nCrossedRowsTPC/findable);
}
// Daughters: pseudo-rapidity cut
fh1QAV0Eta[iIndexHisto]->Fill(track->Eta());
if ( (nCrossedRowsTPC > (160./(250.-85.)*(255.*TMath::Abs(tan(track->Theta()))-85.))+20.) && (track->Eta() < 0) && (track->Pt() > 0.15) )
// if (IsCandK0s)
{
fh2QAV0EtaRows[iIndexHisto]->Fill(track->Eta(),nCrossedRowsTPC);
fh2QAV0PtRows[iIndexHisto]->Fill(track->Pt(),nCrossedRowsTPC);
fh2QAV0PhiRows[iIndexHisto]->Fill(track->Phi(),nCrossedRowsTPC);
fh2QAV0NClRows[iIndexHisto]->Fill(findable,nCrossedRowsTPC);
fh2QAV0EtaNCl[iIndexHisto]->Fill(track->Eta(),findable);
}
// Daughters: transverse momentum cut
fh1QAV0Pt[iIndexHisto]->Fill(track->Pt());
fTotalCharge+=track->Charge();
}
fh1QAV0Charge[iIndexHisto]->Fill(fTotalCharge);
// Daughters: Impact parameter of daughters to prim vtx
fh1QAV0DCAVtx[iIndexHisto]->Fill(TMath::Abs(vZero->DcaNegToPrimVertex()));
fh1QAV0DCAVtx[iIndexHisto]->Fill(TMath::Abs(vZero->DcaPosToPrimVertex()));
// fh2CutDCAVtx[iIndexHisto]->Fill(dMassK0s,TMath::Abs(vZero->DcaNegToPrimVertex()));
// Daughters: DCA
fh1QAV0DCAV0[iIndexHisto]->Fill(vZero->DcaV0Daughters());
// fh2CutDCAV0[iIndexHisto]->Fill(dMassK0s,vZero->DcaV0Daughters());
// V0: Cosine of the pointing angle
fh1QAV0Cos[iIndexHisto]->Fill(vZero->CosPointingAngle(vtx));
// fh2CutCos[iIndexHisto]->Fill(dMassK0s,vZero->CosPointingAngle(vtx));
// V0: Fiducial volume
Double_t xyz[3];
vZero->GetSecondaryVtx(xyz);
Double_t r2=xyz[0]*xyz[0] + xyz[1]*xyz[1];
fh1QAV0R[iIndexHisto]->Fill(TMath::Sqrt(r2));
Double_t dAlpha = vZero->AlphaV0();
Double_t dPtArm = vZero->PtArmV0();
if (IsCandK0s)
{
if (IsInPeakK0s)
{
// fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(trackNeg->Eta(),vZero->Pt());
// fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(trackPos->Eta(),vZero->Pt());
fh2QAV0EtaPtK0sPeak[iIndexHisto]->Fill(vZero->Eta(),vZero->Pt());
fh2QAV0PtPtK0sPeak[iIndexHisto]->Fill(trackNeg->Pt(),trackPos->Pt());
fh2ArmPodK0s[iIndexHisto]->Fill(dAlpha,dPtArm);
}
fh2QAV0EtaEtaK0s[iIndexHisto]->Fill(trackNeg->Eta(),trackPos->Eta());
fh2QAV0PhiPhiK0s[iIndexHisto]->Fill(trackNeg->Phi(),trackPos->Phi());
fh1QAV0RapK0s[iIndexHisto]->Fill(vZero->RapK0Short());
}
if (IsCandLambda)
{
if (IsInPeakLambda)
{
// fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(trackNeg->Eta(),vZero->Pt());
// fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(trackPos->Eta(),vZero->Pt());
fh2QAV0EtaPtLambdaPeak[iIndexHisto]->Fill(vZero->Eta(),vZero->Pt());
fh2QAV0PtPtLambdaPeak[iIndexHisto]->Fill(trackNeg->Pt(),trackPos->Pt());
fh2ArmPodLambda[iIndexHisto]->Fill(dAlpha,dPtArm);
}
fh2QAV0EtaEtaLambda[iIndexHisto]->Fill(trackNeg->Eta(),trackPos->Eta());
fh2QAV0PhiPhiLambda[iIndexHisto]->Fill(trackNeg->Phi(),trackPos->Phi());
fh1QAV0RapLambda[iIndexHisto]->Fill(vZero->RapLambda());
}
fh2ArmPod[iIndexHisto]->Fill(dAlpha,dPtArm);
}
void AliAnalysisTaskV0sInJets::FillCandidates(Double_t mK, Double_t mL, Double_t mAL, Bool_t isK, Bool_t isL, Bool_t isAL, Int_t iCut/*cut index*/, Int_t iCent/*cent index*/)
{
if (isK)
{
fh1V0CounterCentK0s[iCent]->Fill(iCut);
fh1V0InvMassK0sAll[iCut]->Fill(mK);
}
if (isL)
{
fh1V0CounterCentLambda[iCent]->Fill(iCut);
fh1V0InvMassLambdaAll[iCut]->Fill(mL);
}
if (isAL)
{
fh1V0CounterCentALambda[iCent]->Fill(iCut);
fh1V0InvMassALambdaAll[iCut]->Fill(mAL);
}
}
Bool_t AliAnalysisTaskV0sInJets::IsParticleInCone(const AliVParticle* part1, const AliVParticle* part2, Double_t dRMax) const
{
// decides whether a particle is inside a jet cone
if (!part1 || !part2)
return kFALSE;
TVector3 vecMom2(part2->Px(),part2->Py(),part2->Pz());
TVector3 vecMom1(part1->Px(),part1->Py(),part1->Pz());
Double_t dR = vecMom2.DeltaR(vecMom1); // = sqrt(dEta*dEta+dPhi*dPhi)
if(dR<dRMax) // momentum vectors of part1 and part2 are closer than dRMax
return kTRUE;
return kFALSE;
}
Bool_t AliAnalysisTaskV0sInJets::OverlapWithJets(const TClonesArray* array, const AliVParticle* part, Double_t dDistance) const
{
// decides whether a cone overlaps with other jets
if (!part)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: No part\n");
return kFALSE;
}
if (!array)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: No array\n");
return kFALSE;
}
Int_t iNJets = array->GetEntriesFast();
if (iNJets<=0)
{
if(fDebug>2) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Warning: No jets\n");
return kFALSE;
}
AliVParticle* jet = 0;
for (Int_t iJet=0; iJet<iNJets; iJet++)
{
jet = (AliVParticle*)array->At(iJet);
if (!jet)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::OverlapWithJets: Error: Failed to load jet %d/%d\n",iJet,iNJets);
continue;
}
if (IsParticleInCone(part,jet,dDistance))
return kTRUE;
}
return kFALSE;
}
AliAODJet* AliAnalysisTaskV0sInJets::GetRandomCone(const TClonesArray* array, Double_t dEtaConeMax, Double_t dDistance) const
{
// generate a random cone which does not overlap with selected jets
// printf("Generating random cone...\n");
TLorentzVector vecCone;
AliAODJet* part = 0;
Double_t dEta, dPhi;
Int_t iNTrialsMax = 10;
Bool_t bStatus = kFALSE;
for (Int_t iTry=0; iTry<iNTrialsMax; iTry++)
{
// printf("Try %d\n",iTry);
dEta = dEtaConeMax*(2*fRandom->Rndm()-1.); // random eta in [-dEtaConeMax,+dEtaConeMax]
dPhi = TMath::TwoPi()*fRandom->Rndm(); // random phi in [0,2*Pi]
vecCone.SetPtEtaPhiM(1.,dEta,dPhi,0.);
part = new AliAODJet(vecCone);
if (!OverlapWithJets(array,part,dDistance))
{
bStatus = kTRUE;
// printf("Success\n");
break;
}
else
delete part;
}
if (!bStatus)
part = 0;
return part;
}
AliAODJet* AliAnalysisTaskV0sInJets::GetMedianCluster(const TClonesArray* array, Double_t dEtaConeMax) const
{
// sort kt clusters by pT/area and return the middle one, based on code in AliAnalysisTaskJetChem
if (!array)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::GetMedianCluster: Error: No array\n");
return NULL;
}
Int_t iNCl = array->GetEntriesFast();
// Int_t iNClE = array->GetEntries();
if (iNCl<3) // need at least 3 clusters (skipping 2 highest)
{
if(fDebug>2) printf("AliAnalysisTaskV0sInJets::GetMedianCluster: Warning: Too little clusters\n");
return NULL;
}
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: EntriesFast: %d, Entries: %d\n",iNCl,iNClE);
// get list of densities
Double_t* dBgDensity = new Double_t[iNCl];
Int_t* iIndexList = new Int_t[iNCl];
for (Int_t ij=0; ij<iNCl; ij++)
{
AliAODJet* clusterBg = (AliAODJet*)(array->At(ij));
if (!clusterBg)
{
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: cluster %d/%d not ok\n",ij,iNCl);
delete[] dBgDensity;
delete[] iIndexList;
return NULL;
}
Double_t dPtBg = clusterBg->Pt();
Double_t dAreaBg = clusterBg->EffectiveAreaCharged();
Double_t dDensityBg = 0;
if(dAreaBg>0)
dDensityBg = dPtBg/dAreaBg;
dBgDensity[ij] = dDensityBg;
iIndexList[ij] = ij;
}
// sort iIndexList by dBgDensity in descending order
TMath::Sort(iNCl, dBgDensity, iIndexList);
// get median cluster with median density
AliAODJet* clusterMed = 0;
Int_t iIndexMed = 0;
if (TMath::Odd(iNCl)) // odd number of clusters
{
iIndexMed = iIndexList[(Int_t) (0.5*(iNCl+1))]; // = (n - skip + 1)/2 + 1, skip = 2
}
else // even number: picking randomly one of the two closest to median
{
Int_t iIndexMed1 = iIndexList[(Int_t) (0.5*iNCl)]; // = (n - skip)/2 + 1, skip = 2
Int_t iIndexMed2 = iIndexList[(Int_t) (0.5*iNCl+1)]; // = (n - skip)/2 + 1 + 1, skip = 2
iIndexMed = ( (fRandom->Rndm()>0.5) ? iIndexMed1 : iIndexMed2 ); // select one randomly to avoid adding areas
}
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: getting median cluster %d/%d ok\n",iIndexMed,iNCl);
clusterMed = (AliAODJet*)(array->At(iIndexMed));
delete[] dBgDensity;
delete[] iIndexList;
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: checking eta cut %g\n",dEtaConeMax);
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: checking eta cut |%g| < %g?\n",clusterMed->Eta(),dEtaConeMax);
if (TMath::Abs(clusterMed->Eta())>dEtaConeMax)
return NULL;
// printf("AliAnalysisTaskV0sInJets::GetMedianCluster: cluster %d/%d passed\n",iIndexMed,iNCl);
return clusterMed;
}
Double_t AliAnalysisTaskV0sInJets::AreaCircSegment(Double_t dRadius, Double_t dDistance) const
{
// calculate area of a circular segment defined by the circle radius and the (oriented) distance between the secant line and the circle centre
Double_t dEpsilon = 1e-2;
Double_t dR = dRadius;
Double_t dD = dDistance;
if (TMath::Abs(dR)<dEpsilon)
{
if(fDebug>0) printf("AliAnalysisTaskV0sInJets::AreaCircSegment: Error: Too small radius: %f < %f\n",dR,dEpsilon);
return 0.;
}
if (dD>=dR)
return 0.;
if (dD<=-dR)
return TMath::Pi()*dR*dR;
return dR*dR*TMath::ACos(dD/dR)-dD*TMath::Sqrt(dR*dR-dD*dD);
}
Bool_t AliAnalysisTaskV0sInJets::IsSelectedForJets(AliAODEvent* fAOD, Double_t dVtxZCut, Double_t dVtxR2Cut, Double_t dCentCutLo, Double_t dCentCutUp, Bool_t bCutDeltaZ, Double_t dDeltaZMax)
{
// event selection
AliAODVertex* vertex = fAOD->GetPrimaryVertex();
if (!vertex)
return kFALSE;
if (vertex->GetNContributors() < 3)
return kFALSE;
TString vtxTitle(vertex->GetTitle());
if (vtxTitle.Contains("TPCVertex"))
return kFALSE;
Double_t zVertex = vertex->GetZ();
if (TMath::Abs(zVertex) > dVtxZCut)
return kFALSE;
if (bCutDeltaZ)
{
AliAODVertex* vertexSPD = fAOD->GetPrimaryVertexSPD();
if (!vertexSPD)
{
// printf("IsSelectedForJets: Error: No SPD vertex\n");
return kFALSE;
}
Double_t zVertexSPD = vertexSPD->GetZ();
if (TMath::Abs(zVertex-zVertexSPD) > dDeltaZMax)
{
// printf("IsSelectedForJets: Rejecting event due to delta z = %f - %f = %f\n",zVertex,zVertexSPD,zVertex-zVertexSPD);
return kFALSE;
}
// printf("IsSelectedForJets: Event OK: %f - %f = %f\n",zVertex,zVertexSPD,zVertex-zVertexSPD);
}
Double_t xVertex = vertex->GetX();
Double_t yVertex = vertex->GetY();
Double_t radiusSq = yVertex*yVertex+xVertex*xVertex;
if (radiusSq > dVtxR2Cut)
return kFALSE;
Double_t centrality;
// centrality = fAOD->GetHeader()->GetCentrality();
centrality = fAOD->GetHeader()->GetCentralityP()->GetCentralityPercentile("V0M");
if (centrality < 0)
return kFALSE;
if( (dCentCutUp < 0) || (dCentCutLo < 0) || (dCentCutUp > 100) || (dCentCutLo > 100) || (dCentCutLo > dCentCutUp) )
return kFALSE;
if ( (centrality < dCentCutLo) || (centrality > dCentCutUp) )
return kFALSE;
return kTRUE;
}
Int_t AliAnalysisTaskV0sInJets::GetCentralityBinIndex(Double_t centrality)
{
// returns index of the centrality bin corresponding to the provided value of centrality
if (centrality < 0 || centrality > fgkiCentBinRanges[fgkiNBinsCent-1])
return -1;
for (Int_t i = 0; i < fgkiNBinsCent; i++)
{
if (centrality <= fgkiCentBinRanges[i])
return i;
}
return -1;
}
Int_t AliAnalysisTaskV0sInJets::GetCentralityBinEdge(Int_t index)
{
// returns the upper edge of the centrality bin corresponding to the provided value of index
if (index < 0 || index >= fgkiNBinsCent)
return -1;
return fgkiCentBinRanges[index];
}
TString AliAnalysisTaskV0sInJets::GetCentBinLabel(Int_t index)
{
// get string with centrality range for given bin
TString lowerEdge = ( (index == 0) ? "0" : Form("%d",GetCentralityBinEdge(index-1)));
TString upperEdge = Form("%d",GetCentralityBinEdge(index));
return Form("%s-%s %%",lowerEdge.Data(),upperEdge.Data());
}
Double_t AliAnalysisTaskV0sInJets::MassPeakSigmaOld(Double_t pt, Int_t particle)
{
// estimation of the sigma of the invariant-mass peak as a function of pT and particle type
switch (particle)
{
case 0: // K0S
return 0.0044 + 0.0004*(pt - 1.);
break;
case 1: // Lambda
return 0.0023 + 0.00034*(pt - 1.);
break;
default:
return 0;
break;
}
}
|
/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib>
#include <cstdio>
#include "OSGConfig.h"
#include "OSGShaderProgram.h"
#include "OSGGLFuncProtos.h"
#include <boost/bind.hpp>
OSG_BEGIN_NAMESPACE
// Documentation for this class is emitted in the
// OSGShaderProgramBase.cpp file.
// To modify it, please change the .fcd file (OSGShaderProgram.fcd) and
// regenerate the base file.
/***************************************************************************\
* Class variables *
\***************************************************************************/
UInt32 ShaderProgram::_extSHL = Window::invalidExtensionID;
UInt32 ShaderProgram::_extCG = Window::invalidExtensionID;
UInt32 ShaderProgram::_extGeoShader4 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extGPUShader4 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extTransformFeedback2 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extUniformBufferObject = Window::invalidExtensionID;
UInt32 ShaderProgram::FuncIdCreateShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdDeleteShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdShaderSource = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdCompileShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdAttachShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetShaderiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetShaderInfoLog = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdCreateProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdDeleteProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdLinkProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetProgramiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetProgramInfoLog = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUseProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformLocation = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix2fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix3fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix4fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformfv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdProgramParameteri = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBindAttribLocation = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBindBufferBase = Window::invalidFunctionID;
UInt32
ShaderProgram::FuncIdTransformFeedbackVaryings = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBeginTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdEndTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdPauseTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdResumeTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformBlockIndex = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformBlockBinding = Window::invalidFunctionID;
const Char8 *ShaderProgram::NextBufferToken = "gl_NextBuffer";
ShaderProgram::ProgramIdPool *ShaderProgram::_pProgIdPool = NULL;
template<> inline
void SimpleReusePool<Int32,
ShaderProgram::ProgramIdPoolTag,
SingleLockPolicy >::initializeValue(void)
{
_currentValue = 1;
}
/***************************************************************************\
* Class methods *
\***************************************************************************/
void ShaderProgram::initMethod(InitPhase ePhase)
{
Inherited::initMethod(ePhase);
if(ePhase == TypeObject::SystemPost)
{
_extSHL =
Window::registerExtension("GL_ARB_shading_language_100");
_extCG =
Window::registerExtension("GL_EXT_Cg_shader");
_extGeoShader4 =
Window::registerExtension("GL_EXT_geometry_shader4");
_extGPUShader4 =
Window::registerExtension("GL_EXT_gpu_shader4");
_extTransformFeedback2 =
Window::registerExtension("GL_EXT_transform_feedback2");
_extUniformBufferObject =
Window::registerExtension("GL_ARB_uniform_buffer_object");
#ifdef OSG_OGL2_SHADERFUNCS
FuncIdCreateShader =
Window::registerFunction
(OSG_DLSYM_UNDERSCORE"glCreateShader",
_extSHL);
FuncIdDeleteShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteShader",
_extSHL);
FuncIdShaderSource =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glShaderSource",
_extSHL);
FuncIdCompileShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCompileShader",
_extSHL);
FuncIdAttachShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glAttachShader",
_extSHL);
FuncIdGetShaderiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetShaderiv",
_extSHL);
FuncIdGetShaderInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetShaderInfoLog",
_extSHL);
FuncIdCreateProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCreateProgram",
_extSHL);
FuncIdDeleteProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteProgram",
_extSHL);
FuncIdLinkProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glLinkProgram",
_extSHL);
FuncIdGetProgramiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetProgramiv",
_extSHL);
FuncIdGetProgramInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetProgramInfoLog",
_extSHL);
FuncIdUseProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUseProgram",
_extSHL);
#else
FuncIdCreateShader =
Window::registerFunction
(OSG_DLSYM_UNDERSCORE"glCreateShaderObjectARB",
_extSHL);
FuncIdDeleteShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteObjectARB",
_extSHL);
FuncIdShaderSource =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glShaderSourceARB",
_extSHL);
FuncIdCompileShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCompileShaderARB",
_extSHL);
FuncIdAttachShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glAttachObjectARB",
_extSHL);
FuncIdGetShaderiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetObjectParameterivARB",
_extSHL);
FuncIdGetShaderInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetInfoLogARB",
_extSHL);
FuncIdCreateProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCreateProgramObjectARB",
_extSHL);
FuncIdDeleteProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteObjectARB",
_extSHL);
FuncIdLinkProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glLinkProgramARB",
_extSHL);
FuncIdGetProgramiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetObjectParameterivARB",
_extSHL);
FuncIdGetProgramInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetInfoLogARB",
_extSHL);
FuncIdUseProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUseProgramObjectARB",
_extSHL);
#endif
FuncIdGetUniformLocation =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformLocationARB",
_extSHL);
// int{,2,3,4} uniforms
FuncIdUniform1i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1iARB",
_extSHL);
FuncIdUniform2i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2iARB",
_extSHL);
FuncIdUniform3i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3iARB",
_extSHL);
FuncIdUniform4i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4iARB",
_extSHL);
// uint{,2,3,4} uniforms
FuncIdUniform1ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1uiEXT",
_extSHL);
FuncIdUniform2ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2uiEXT",
_extSHL);
FuncIdUniform3ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3uiEXT",
_extSHL);
FuncIdUniform4ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4uiEXT",
_extSHL);
// float, vec{2,3,4} uniforms
FuncIdUniform1f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1fARB",
_extSHL);
FuncIdUniform2f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2fARB",
_extSHL);
FuncIdUniform3f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3fARB",
_extSHL);
FuncIdUniform4f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4fARB",
_extSHL);
// int{,2,3,4} uniform arrays
FuncIdUniform1iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1ivARB",
_extSHL);
FuncIdUniform2iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2ivARB",
_extSHL);
FuncIdUniform3iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3ivARB",
_extSHL);
FuncIdUniform4iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4ivARB",
_extSHL);
// uint{,2,3,4} uniform arrays
FuncIdUniform1uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1uivEXT",
_extSHL);
FuncIdUniform2uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2uivEXT",
_extSHL);
FuncIdUniform3uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3uivEXT",
_extSHL);
FuncIdUniform4uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4uivEXT",
_extSHL);
// float, vec{2,3,4} uniform arrays
FuncIdUniform1fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1fvARB",
_extSHL);
FuncIdUniform2fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2fvARB",
_extSHL);
FuncIdUniform3fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3fvARB",
_extSHL);
FuncIdUniform4fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4fvARB",
_extSHL);
FuncIdUniformMatrix2fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix2fvARB",
_extSHL);
FuncIdUniformMatrix3fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix3fvARB",
_extSHL);
FuncIdUniformMatrix4fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix4fvARB",
_extSHL);
FuncIdGetUniformiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformivARB",
_extSHL);
FuncIdGetUniformfv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformfvARB",
_extSHL);
FuncIdProgramParameteri =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glProgramParameteriEXT",
_extGeoShader4);
FuncIdBindAttribLocation =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBindAttribLocationARB",
_extSHL);
FuncIdBindBufferBase =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBindBufferBase",
_extTransformFeedback2);
FuncIdTransformFeedbackVaryings =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glTransformFeedbackVaryings",
_extTransformFeedback2);
FuncIdBeginTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBeginTransformFeedback",
_extTransformFeedback2);
FuncIdEndTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glEndTransformFeedback",
_extTransformFeedback2);
FuncIdPauseTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glPauseTransformFeedback",
_extTransformFeedback2);
FuncIdResumeTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glResumeTransformFeedback",
_extTransformFeedback2);
FuncIdGetUniformBlockIndex =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformBlockIndex",
_extUniformBufferObject);
FuncIdUniformBlockBinding =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformBlockBinding",
_extUniformBufferObject);
}
}
/***************************************************************************\
* Instance methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*----------------------- constructors & destructors ----------------------*/
ShaderProgram::ShaderProgram(void) :
Inherited( ),
_uiProgId (0)
{
}
ShaderProgram::ShaderProgram(const ShaderProgram &source) :
Inherited(source),
_uiProgId (0 )
{
}
ShaderProgram::~ShaderProgram(void)
{
}
void ShaderProgram::onCreate(const ShaderProgram *source)
{
Inherited::onCreate(source);
// ignore prototypes.
if(GlobalSystemState == Startup)
{
if(_pProgIdPool == NULL)
{
_pProgIdPool = new ProgramIdPool;
}
return;
}
setGLId(
Window::registerGLObject(
boost::bind(&ShaderProgram::handleGL,
ShaderProgramMTUncountedPtr(this),
_1, _2, _3, _4),
&ShaderProgram::handleDestroyGL));
_uiProgId = _pProgIdPool->create();
}
void ShaderProgram::onCreateAspect(const ShaderProgram *createAspect,
const ShaderProgram *source)
{
Inherited::onCreateAspect(createAspect, source);
_uiProgId = createAspect->_uiProgId;
}
void ShaderProgram::onDestroy(UInt32 uiId)
{
if(GlobalSystemState == OSG::Running)
{
_pProgIdPool->release(_uiProgId);
if(getGLId() > 0)
Window::destroyGLObject(getGLId(), 1);
}
else if(GlobalSystemState == OSG::Shutdown)
{
delete _pProgIdPool;
_pProgIdPool = NULL;
}
Inherited::onDestroy(uiId);
}
void ShaderProgram::onDestroyAspect(UInt32 uiContainerId,
UInt32 uiAspect )
{
Inherited::onDestroyAspect(uiContainerId, uiAspect);
}
void ShaderProgram::resolveLinks(void)
{
MFDestroyedFunctorsType::const_iterator dfIt =
_mfDestroyedFunctors.begin();
MFDestroyedFunctorsType::const_iterator dfEnd =
_mfDestroyedFunctors.end();
for(; dfIt != dfEnd; ++dfIt)
{
if(dfIt->_func.empty() == false)
(dfIt->_func)(this, 0x0000, ChangedOrigin::External);
}
Inherited::resolveLinks();
}
UInt32 ShaderProgram::handleGL(DrawEnv *pEnv,
UInt32 id,
Window::GLObjectStatusE mode,
UInt64 uiOptions)
{
Window *pWin = pEnv->getWindow();
if(pWin->hasExtOrVersion(_extSHL, 0x0200, 0x0200) == false)
{
FWARNING(("OpenGL Shading Language is not supported, couldn't find "
"extension 'GL_ARB_shading_language_100'!\n"));
pWin->setGLObjectId(id, 0);
return 0;
}
if(mode == Window::initialize ||
mode == Window::reinitialize ||
mode == Window::needrefresh )
{
if( mode != Window::needrefresh &&
_sfProgram.getValue().empty() == false )
{
GLuint uiShader = GLuint(pWin->getGLObjectId(getGLId()));
#ifdef OSG_DEBUG
if(mode == Window::initialize && uiShader != 0)
{
FWARNING(("ShaderProgram::handleGL: "
"Initialize with non-zero GL object Id.\n"));
uiShader = 0;
}
#endif
// if(uiShader == 0)
if(mode == Window::initialize)
{
OSGGETGLFUNCBYID_GL3_ES(glCreateShader,
osgGlCreateShader,
FuncIdCreateShader,
pWin);
GLenum shaderType = _sfShaderType.getValue();
if(_sfCgFrontEnd.getValue() == true)
{
if(pWin->hasExtension(_extCG))
{
switch(shaderType)
{
case GL_VERTEX_SHADER:
shaderType = GL_CG_VERTEX_SHADER_EXT;
break;
case GL_FRAGMENT_SHADER:
shaderType = GL_CG_FRAGMENT_SHADER_EXT;
break;
}
}
else
{
FWARNING(("EXT_Cg_shader extension not supported, "
"using GLSL front end!\n"));
}
}
uiShader = osgGlCreateShader(shaderType);
}
const Char8 *source = _sfProgram.getValue().c_str();
OSGGETGLFUNCBYID_GL3_ES(glShaderSource,
osgGlShaderSource,
FuncIdShaderSource,
pWin);
OSGGETGLFUNCBYID_GL3_ES(glCompileShader,
osgGlCompileShader,
FuncIdCompileShader,
pWin);
OSGGETGLFUNCBYID_GL3_ES(glGetShaderiv,
osgGlGetShaderiv,
FuncIdGetShaderiv,
pWin);
if(_sfDefines.getValue().empty() == true)
{
osgGlShaderSource(uiShader,
1,
static_cast<const char **>(&source),
0);
}
else
{
const Char8 *defines = _sfDefines.getValue().c_str();
const char *shaderSources[2] =
{
defines,
source
};
osgGlShaderSource(uiShader,
2,
shaderSources,
0);
}
osgGlCompileShader(uiShader);
GLint iStatus = 0;
osgGlGetShaderiv( uiShader,
GL_COMPILE_STATUS,
&iStatus);
if(iStatus == 0)
{
Char8 *szDebug;
GLint iDebugLength;
osgGlGetShaderiv( uiShader,
GL_INFO_LOG_LENGTH,
&iDebugLength);
szDebug = new Char8[iDebugLength];
OSGGETGLFUNCBYID_GL3_ES(glGetShaderInfoLog,
osgGlGetShaderInfoLog,
FuncIdGetShaderInfoLog,
pWin);
osgGlGetShaderInfoLog( uiShader,
iDebugLength,
&iDebugLength,
szDebug );
FFATAL(("Couldn't compile shader program (0x%x)!\n%s\n",
_sfShaderType.getValue(),
szDebug));
delete [] szDebug;
// log source that failed to compile
FINFO(("Shader source was:\n"));
if(_sfDefines.getValue().empty() == false)
{
FPINFO(("%s\n", _sfDefines.getValue().c_str()));
}
FPINFO(("%s\n", source));
OSGGETGLFUNCBYID_GL3_ES(glDeleteShader,
osgGlDeleteShader,
FuncIdDeleteShader,
pWin);
osgGlDeleteShader(uiShader);
uiShader = 0;
}
pWin->setGLObjectId(getGLId(), uiShader);
}
//updateProgramParameters(win);
//updateParameters(win,
//*getMFParameters(),
//true,
//true /*mode != Window::needrefresh*/);
}
return 0;
}
void ShaderProgram::handleDestroyGL(DrawEnv *pEnv,
UInt32 id,
Window::GLObjectStatusE mode)
{
Window *pWin = pEnv->getWindow();
if(!pWin->hasExtOrVersion(_extSHL, 0x0200, 0x0200))
{
FWARNING(("OpenGL Shading Language is not supported, couldn't find "
"extension 'GL_ARB_shading_language_100'!\n"));
pWin->setGLObjectId(id, 0);
return;
}
if(mode == Window::destroy)
{
GLuint uiShader = GLuint(pWin->getGLObjectId(id));
if(uiShader != 0)
{
OSGGETGLFUNCBYID_GL3_ES(glDeleteShader,
osgGlDeleteShader,
FuncIdDeleteShader,
pWin);
osgGlDeleteShader(uiShader);
pWin->setGLObjectId(id, 0);
}
}
else if(mode == Window::finaldestroy)
{
;//SWARNING << "Last program user destroyed" << std::endl;
}
}
/*----------------------------- class specific ----------------------------*/
void ShaderProgram::changed(ConstFieldMaskArg whichField,
UInt32 origin,
BitVector details)
{
Inherited::changed(whichField, origin, details);
if(0x0000 != (whichField & VariablesFieldMask))
{
if(details == 0x0001)
{
MFParentFieldContainerPtr::const_iterator parentsIt =
this->_mfParents.begin();
MFParentFieldContainerPtr::const_iterator parentsEnd =
this->_mfParents.end();
while(parentsIt != parentsEnd)
{
(*parentsIt)->changed(
TypeTraits<BitVector>::One << parentsIt.getParentFieldPos(),
ChangedOrigin::Child,
VariablesFieldMask);
++parentsIt;
}
}
}
if(0x0000 != (whichField & ProgramFieldMask))
{
MFParentFieldContainerPtr::const_iterator parentsIt =
this->_mfParents.begin();
MFParentFieldContainerPtr::const_iterator parentsEnd =
this->_mfParents.end();
while(parentsIt != parentsEnd)
{
(*parentsIt)->changed(
TypeTraits<BitVector>::One << parentsIt.getParentFieldPos(),
ChangedOrigin::Child,
ProgramFieldMask);
++parentsIt;
}
Window::reinitializeGLObject(this->getGLId());
}
}
ShaderProgramTransitPtr ShaderProgram::createVertexShader(
bool bCreateDefAttribMap)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_VERTEX_SHADER);
if(bCreateDefAttribMap == true)
returnValue->createDefaulAttribMapping();
return returnValue;
}
ShaderProgramTransitPtr ShaderProgram::createGeometryShader(void)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_GEOMETRY_SHADER_EXT);
return returnValue;
}
ShaderProgramTransitPtr ShaderProgram::createFragmentShader(void)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_FRAGMENT_SHADER);
return returnValue;
}
void ShaderProgram::accumulateFeedback(
DrawEnv *pEnv,
UInt32 uiProgram,
std::vector<const Char8 *> &vTFVaryings,
UInt32 &uiVaryingBufferIndex)
{
if(((_sfShaderType.getValue() == GL_VERTEX_SHADER) ||
(_sfShaderType.getValue() == GL_GEOMETRY_SHADER_EXT) ) == false)
{
return;
}
if(vTFVaryings.size() != 0)
{
vTFVaryings.push_back(NextBufferToken);
}
MFFeedbackVaryingsType::const_iterator vIt =
this->getMFFeedbackVaryings()->begin();
MFFeedbackVaryingsType::const_iterator vEnd =
this->getMFFeedbackVaryings()->end ();
for(; vIt != vEnd; ++vIt)
{
vTFVaryings.push_back((*vIt).c_str());
}
}
void ShaderProgram::addParent(FieldContainer * const pParent,
UInt16 uiParentFieldId)
{
editMField(ParentsFieldMask, _mfParents);
OSG_ASSERT(pParent != NULL);
_mfParents.push_back(pParent, uiParentFieldId);
}
void ShaderProgram::subParent(FieldContainer * const pParent)
{
Int32 iParentIdx = _mfParents.findIndex(pParent);
if(iParentIdx != -1)
{
editMField(ParentsFieldMask, _mfParents);
_mfParents.erase(iParentIdx);
}
}
void ShaderProgram::dump( UInt32 ,
const BitVector ) const
{
SLOG << "Dump ShaderProgram NI" << std::endl;
}
bool ShaderProgram::readProgram(const Char8 *file)
{
return readProgram(editSFProgram()->getValue(), file);
}
bool ShaderProgram::subUniformVariable(const Char8 *name)
{
if(_sfVariables.getValue() != NULL)
{
#if 0
return _sfVariables.getValue()->subUniformVariable(
name,
editMFVariableLocations(),
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->subUniformVariable(
name,
NULL,
NULL);
#endif
}
return false;
}
void ShaderProgram::clearUniformVariables(void)
{
if(_sfVariables.getValue() != NULL)
{
_sfVariables.getValue()->clearUniformVariables();
}
}
bool ShaderProgram::subUniformBlock(const Char8 *name)
{
if(_sfVariables.getValue() != NULL)
{
#if 0
return _sfVariables.getValue()->subUniformBlock(
name,
editMFBlockLocations(),
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->subUniformBlock(
name,
NULL,
NULL);
#endif
}
return false;
}
bool ShaderProgram::addProceduralVariable(const Char8 *name,
ProcVarFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
#if 0
return _sfVariables.getValue()->addProceduralVariable(
name,
pFunc,
uiDependency,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addProceduralVariable(
name,
pFunc,
uiDependency,
NULL);
#endif
}
bool ShaderProgram::addNodeProceduralVariable(
const Char8 *name,
ProcVarNodeFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
#if 0
return _sfVariables.getValue()->addNodeProceduralVariable(
name,
pFunc,
uiDependency,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addNodeProceduralVariable(
name,
pFunc,
uiDependency,
NULL);
#endif
}
/*! \nohierarchy
*/
struct ParamEqual
{
GLenum _ref;
ParamEqual(GLenum ref) :
_ref(ref)
{
}
bool operator() (const ShaderParameter &lhs)
{
return lhs.first == _ref;
}
};
void ShaderProgram::setProgramParameter(GLenum name, UInt32 value)
{
editMField(ParameterFieldMask, _mfParameter);
MFShaderParameter::iterator pIt =
std::find_if(_mfParameter.begin(),
_mfParameter.end (),
ParamEqual (name));
if(pIt != _mfParameter.end())
{
pIt->second = value;
}
else
{
ShaderParameter tmpParam;
tmpParam.first = name;
tmpParam.second = value;
_mfParameter.push_back(tmpParam);
}
}
void ShaderProgram::subProgramParameter(GLenum name)
{
MFShaderParameter::iterator pIt =
std::find_if(_mfParameter.begin(),
_mfParameter.end (),
ParamEqual (name));
if(pIt != _mfParameter.end())
{
editMField(ParameterFieldMask, _mfParameter);
_mfParameter.erase(pIt);
}
}
struct AttribEqual
{
UInt16 _ref;
AttribEqual(UInt16 ref) :
_ref(ref)
{
}
bool operator() (const ShaderAttribute &lhs)
{
return lhs.first == _ref;
}
};
void ShaderProgram::setProgramAttribute(UInt16 uiIndex, std::string szName)
{
editMField(AttributesFieldMask, _mfAttributes);
MFShaderAttribute::iterator aIt =
std::find_if(_mfAttributes.begin(),
_mfAttributes.end (),
AttribEqual (uiIndex));
if(aIt != _mfAttributes.end())
{
aIt->second = szName;
}
else
{
ShaderAttribute tmpAttr;
tmpAttr.first = uiIndex;
tmpAttr.second = szName;
_mfAttributes.push_back(tmpAttr);
}
}
void ShaderProgram::subProgramAttribute(UInt16 uiIndex)
{
MFAttributesType::iterator aIt =
std::find_if(_mfAttributes.begin(),
_mfAttributes.end (),
AttribEqual (uiIndex));
if(aIt != _mfAttributes.end())
{
editMField(AttributesFieldMask, _mfAttributes);
_mfAttributes.erase(aIt);
}
}
void ShaderProgram::createDefaulAttribMapping(void)
{
if(_sfShaderType.getValue() == GL_VERTEX_SHADER)
{
this->setProgramAttribute(ShaderConstants::Attribute0Index,
"osg_Vertex" );
this->setProgramAttribute(ShaderConstants::Attribute2Index,
"osg_Normal" );
this->setProgramAttribute(ShaderConstants::Attribute3Index,
"osg_Color" );
this->setProgramAttribute(ShaderConstants::Attribute4Index,
"osg_SecondaryColor" );
this->setProgramAttribute(ShaderConstants::Attribute8Index,
"osg_MultiTexCoord0" );
this->setProgramAttribute(ShaderConstants::Attribute9Index,
"osg_MultiTexCoord1" );
this->setProgramAttribute(ShaderConstants::Attribute10Index,
"osg_MultiTexCoord2" );
this->setProgramAttribute(ShaderConstants::Attribute11Index,
"osg_MultiTexCoord3" );
this->setProgramAttribute(ShaderConstants::Attribute12Index,
"osg_MultiTexCoord4" );
this->setProgramAttribute(ShaderConstants::Attribute13Index,
"osg_MultiTexCoord5" );
this->setProgramAttribute(ShaderConstants::Attribute14Index,
"osg_MultiTexCoord6" );
this->setProgramAttribute(ShaderConstants::Attribute15Index,
"osg_MultiTexCoord7" );
}
else
{
FWARNING(("attrib map can only be created for a vertex shader"));
}
}
bool ShaderProgram::addOSGVariable(const Char8 *name)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pVar =
ShaderProgramVariables::create();
setVariables(pVar);
}
#if 0
return _sfVariables.getValue()->addOSGVariable(
name,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addOSGVariable(name,
NULL);
#endif
}
bool ShaderProgram::updateProceduralVariable(const Char8 *name,
ProcVarFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
return _sfVariables.getValue()->updateProceduralVariable(name,
pFunc,
uiDependency);
}
bool ShaderProgram::updateNodeProceduralVariable(
const Char8 *name,
ProcVarNodeFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
return _sfVariables.getValue()->updateNodeProceduralVariable(name,
pFunc,
uiDependency);
}
bool ShaderProgram::readProgram( std::string &szTarget,
const Char8 *szFilename)
{
std::ifstream s(szFilename);
if(s.good())
{
return readProgram(szTarget, s);
}
else
{
FWARNING(("ShaderChunk::readProgram: couldn't open '%s' "
"for reading!\n", szFilename));
return false;
}
}
bool ShaderProgram::readProgram(std::string &szTarget,
std::istream &iStream)
{
#define BUFSIZE 200
szTarget.erase();
Char8 buf[BUFSIZE];
if(!iStream.good())
{
FWARNING(("SHLChunk::readProgram: stream is not good!\n"));
return false;
}
do
{
iStream.read(buf, BUFSIZE);
szTarget.append(buf, iStream.gcount());
}
while(!iStream.eof());
return true;
}
OSG_END_NAMESPACE
fixed: error in valid <-> invalid <-> valid shader source sequence (thanks to M. Weiler for the detailed report)
/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib>
#include <cstdio>
#include "OSGConfig.h"
#include "OSGShaderProgram.h"
#include "OSGGLFuncProtos.h"
#include <boost/bind.hpp>
OSG_BEGIN_NAMESPACE
// Documentation for this class is emitted in the
// OSGShaderProgramBase.cpp file.
// To modify it, please change the .fcd file (OSGShaderProgram.fcd) and
// regenerate the base file.
/***************************************************************************\
* Class variables *
\***************************************************************************/
UInt32 ShaderProgram::_extSHL = Window::invalidExtensionID;
UInt32 ShaderProgram::_extCG = Window::invalidExtensionID;
UInt32 ShaderProgram::_extGeoShader4 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extGPUShader4 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extTransformFeedback2 = Window::invalidExtensionID;
UInt32 ShaderProgram::_extUniformBufferObject = Window::invalidExtensionID;
UInt32 ShaderProgram::FuncIdCreateShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdDeleteShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdShaderSource = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdCompileShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdAttachShader = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetShaderiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetShaderInfoLog = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdCreateProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdDeleteProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdLinkProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetProgramiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetProgramInfoLog = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUseProgram = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformLocation = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4i = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4ui = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4f = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4iv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4uiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform1fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform2fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform3fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniform4fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix2fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix3fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformMatrix4fv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformiv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformfv = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdProgramParameteri = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBindAttribLocation = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBindBufferBase = Window::invalidFunctionID;
UInt32
ShaderProgram::FuncIdTransformFeedbackVaryings = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdBeginTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdEndTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdPauseTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdResumeTransformFeedback = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdGetUniformBlockIndex = Window::invalidFunctionID;
UInt32 ShaderProgram::FuncIdUniformBlockBinding = Window::invalidFunctionID;
const Char8 *ShaderProgram::NextBufferToken = "gl_NextBuffer";
ShaderProgram::ProgramIdPool *ShaderProgram::_pProgIdPool = NULL;
template<> inline
void SimpleReusePool<Int32,
ShaderProgram::ProgramIdPoolTag,
SingleLockPolicy >::initializeValue(void)
{
_currentValue = 1;
}
/***************************************************************************\
* Class methods *
\***************************************************************************/
void ShaderProgram::initMethod(InitPhase ePhase)
{
Inherited::initMethod(ePhase);
if(ePhase == TypeObject::SystemPost)
{
_extSHL =
Window::registerExtension("GL_ARB_shading_language_100");
_extCG =
Window::registerExtension("GL_EXT_Cg_shader");
_extGeoShader4 =
Window::registerExtension("GL_EXT_geometry_shader4");
_extGPUShader4 =
Window::registerExtension("GL_EXT_gpu_shader4");
_extTransformFeedback2 =
Window::registerExtension("GL_EXT_transform_feedback2");
_extUniformBufferObject =
Window::registerExtension("GL_ARB_uniform_buffer_object");
#ifdef OSG_OGL2_SHADERFUNCS
FuncIdCreateShader =
Window::registerFunction
(OSG_DLSYM_UNDERSCORE"glCreateShader",
_extSHL);
FuncIdDeleteShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteShader",
_extSHL);
FuncIdShaderSource =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glShaderSource",
_extSHL);
FuncIdCompileShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCompileShader",
_extSHL);
FuncIdAttachShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glAttachShader",
_extSHL);
FuncIdGetShaderiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetShaderiv",
_extSHL);
FuncIdGetShaderInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetShaderInfoLog",
_extSHL);
FuncIdCreateProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCreateProgram",
_extSHL);
FuncIdDeleteProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteProgram",
_extSHL);
FuncIdLinkProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glLinkProgram",
_extSHL);
FuncIdGetProgramiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetProgramiv",
_extSHL);
FuncIdGetProgramInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetProgramInfoLog",
_extSHL);
FuncIdUseProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUseProgram",
_extSHL);
#else
FuncIdCreateShader =
Window::registerFunction
(OSG_DLSYM_UNDERSCORE"glCreateShaderObjectARB",
_extSHL);
FuncIdDeleteShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteObjectARB",
_extSHL);
FuncIdShaderSource =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glShaderSourceARB",
_extSHL);
FuncIdCompileShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCompileShaderARB",
_extSHL);
FuncIdAttachShader =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glAttachObjectARB",
_extSHL);
FuncIdGetShaderiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetObjectParameterivARB",
_extSHL);
FuncIdGetShaderInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetInfoLogARB",
_extSHL);
FuncIdCreateProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glCreateProgramObjectARB",
_extSHL);
FuncIdDeleteProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glDeleteObjectARB",
_extSHL);
FuncIdLinkProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glLinkProgramARB",
_extSHL);
FuncIdGetProgramiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetObjectParameterivARB",
_extSHL);
FuncIdGetProgramInfoLog =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetInfoLogARB",
_extSHL);
FuncIdUseProgram =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUseProgramObjectARB",
_extSHL);
#endif
FuncIdGetUniformLocation =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformLocationARB",
_extSHL);
// int{,2,3,4} uniforms
FuncIdUniform1i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1iARB",
_extSHL);
FuncIdUniform2i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2iARB",
_extSHL);
FuncIdUniform3i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3iARB",
_extSHL);
FuncIdUniform4i =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4iARB",
_extSHL);
// uint{,2,3,4} uniforms
FuncIdUniform1ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1uiEXT",
_extSHL);
FuncIdUniform2ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2uiEXT",
_extSHL);
FuncIdUniform3ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3uiEXT",
_extSHL);
FuncIdUniform4ui =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4uiEXT",
_extSHL);
// float, vec{2,3,4} uniforms
FuncIdUniform1f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1fARB",
_extSHL);
FuncIdUniform2f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2fARB",
_extSHL);
FuncIdUniform3f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3fARB",
_extSHL);
FuncIdUniform4f =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4fARB",
_extSHL);
// int{,2,3,4} uniform arrays
FuncIdUniform1iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1ivARB",
_extSHL);
FuncIdUniform2iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2ivARB",
_extSHL);
FuncIdUniform3iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3ivARB",
_extSHL);
FuncIdUniform4iv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4ivARB",
_extSHL);
// uint{,2,3,4} uniform arrays
FuncIdUniform1uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1uivEXT",
_extSHL);
FuncIdUniform2uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2uivEXT",
_extSHL);
FuncIdUniform3uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3uivEXT",
_extSHL);
FuncIdUniform4uiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4uivEXT",
_extSHL);
// float, vec{2,3,4} uniform arrays
FuncIdUniform1fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform1fvARB",
_extSHL);
FuncIdUniform2fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform2fvARB",
_extSHL);
FuncIdUniform3fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform3fvARB",
_extSHL);
FuncIdUniform4fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniform4fvARB",
_extSHL);
FuncIdUniformMatrix2fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix2fvARB",
_extSHL);
FuncIdUniformMatrix3fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix3fvARB",
_extSHL);
FuncIdUniformMatrix4fv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformMatrix4fvARB",
_extSHL);
FuncIdGetUniformiv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformivARB",
_extSHL);
FuncIdGetUniformfv =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformfvARB",
_extSHL);
FuncIdProgramParameteri =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glProgramParameteriEXT",
_extGeoShader4);
FuncIdBindAttribLocation =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBindAttribLocationARB",
_extSHL);
FuncIdBindBufferBase =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBindBufferBase",
_extTransformFeedback2);
FuncIdTransformFeedbackVaryings =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glTransformFeedbackVaryings",
_extTransformFeedback2);
FuncIdBeginTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glBeginTransformFeedback",
_extTransformFeedback2);
FuncIdEndTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glEndTransformFeedback",
_extTransformFeedback2);
FuncIdPauseTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glPauseTransformFeedback",
_extTransformFeedback2);
FuncIdResumeTransformFeedback =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glResumeTransformFeedback",
_extTransformFeedback2);
FuncIdGetUniformBlockIndex =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glGetUniformBlockIndex",
_extUniformBufferObject);
FuncIdUniformBlockBinding =
Window::registerFunction (
OSG_DLSYM_UNDERSCORE"glUniformBlockBinding",
_extUniformBufferObject);
}
}
/***************************************************************************\
* Instance methods *
\***************************************************************************/
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*----------------------- constructors & destructors ----------------------*/
ShaderProgram::ShaderProgram(void) :
Inherited( ),
_uiProgId (0)
{
}
ShaderProgram::ShaderProgram(const ShaderProgram &source) :
Inherited(source),
_uiProgId (0 )
{
}
ShaderProgram::~ShaderProgram(void)
{
}
void ShaderProgram::onCreate(const ShaderProgram *source)
{
Inherited::onCreate(source);
// ignore prototypes.
if(GlobalSystemState == Startup)
{
if(_pProgIdPool == NULL)
{
_pProgIdPool = new ProgramIdPool;
}
return;
}
setGLId(
Window::registerGLObject(
boost::bind(&ShaderProgram::handleGL,
ShaderProgramMTUncountedPtr(this),
_1, _2, _3, _4),
&ShaderProgram::handleDestroyGL));
_uiProgId = _pProgIdPool->create();
}
void ShaderProgram::onCreateAspect(const ShaderProgram *createAspect,
const ShaderProgram *source)
{
Inherited::onCreateAspect(createAspect, source);
_uiProgId = createAspect->_uiProgId;
}
void ShaderProgram::onDestroy(UInt32 uiId)
{
if(GlobalSystemState == OSG::Running)
{
_pProgIdPool->release(_uiProgId);
if(getGLId() > 0)
Window::destroyGLObject(getGLId(), 1);
}
else if(GlobalSystemState == OSG::Shutdown)
{
delete _pProgIdPool;
_pProgIdPool = NULL;
}
Inherited::onDestroy(uiId);
}
void ShaderProgram::onDestroyAspect(UInt32 uiContainerId,
UInt32 uiAspect )
{
Inherited::onDestroyAspect(uiContainerId, uiAspect);
}
void ShaderProgram::resolveLinks(void)
{
MFDestroyedFunctorsType::const_iterator dfIt =
_mfDestroyedFunctors.begin();
MFDestroyedFunctorsType::const_iterator dfEnd =
_mfDestroyedFunctors.end();
for(; dfIt != dfEnd; ++dfIt)
{
if(dfIt->_func.empty() == false)
(dfIt->_func)(this, 0x0000, ChangedOrigin::External);
}
Inherited::resolveLinks();
}
UInt32 ShaderProgram::handleGL(DrawEnv *pEnv,
UInt32 id,
Window::GLObjectStatusE mode,
UInt64 uiOptions)
{
Window *pWin = pEnv->getWindow();
if(pWin->hasExtOrVersion(_extSHL, 0x0200, 0x0200) == false)
{
FWARNING(("OpenGL Shading Language is not supported, couldn't find "
"extension 'GL_ARB_shading_language_100'!\n"));
pWin->setGLObjectId(id, 0);
return 0;
}
if(mode == Window::initialize ||
mode == Window::reinitialize ||
mode == Window::needrefresh )
{
if( mode != Window::needrefresh &&
_sfProgram.getValue().empty() == false )
{
GLuint uiShader = GLuint(pWin->getGLObjectId(getGLId()));
#ifdef OSG_DEBUG
if(mode == Window::initialize && uiShader != 0)
{
FWARNING(("ShaderProgram::handleGL: "
"Initialize with non-zero GL object Id.\n"));
uiShader = 0;
}
#endif
if(uiShader == 0)
// if(mode == Window::initialize)
{
OSGGETGLFUNCBYID_GL3_ES(glCreateShader,
osgGlCreateShader,
FuncIdCreateShader,
pWin);
GLenum shaderType = _sfShaderType.getValue();
if(_sfCgFrontEnd.getValue() == true)
{
if(pWin->hasExtension(_extCG))
{
switch(shaderType)
{
case GL_VERTEX_SHADER:
shaderType = GL_CG_VERTEX_SHADER_EXT;
break;
case GL_FRAGMENT_SHADER:
shaderType = GL_CG_FRAGMENT_SHADER_EXT;
break;
}
}
else
{
FWARNING(("EXT_Cg_shader extension not supported, "
"using GLSL front end!\n"));
}
}
uiShader = osgGlCreateShader(shaderType);
}
if(uiShader == 0)
return 0;
const Char8 *source = _sfProgram.getValue().c_str();
OSGGETGLFUNCBYID_GL3_ES(glShaderSource,
osgGlShaderSource,
FuncIdShaderSource,
pWin);
OSGGETGLFUNCBYID_GL3_ES(glCompileShader,
osgGlCompileShader,
FuncIdCompileShader,
pWin);
OSGGETGLFUNCBYID_GL3_ES(glGetShaderiv,
osgGlGetShaderiv,
FuncIdGetShaderiv,
pWin);
if(_sfDefines.getValue().empty() == true)
{
osgGlShaderSource(uiShader,
1,
static_cast<const char **>(&source),
0);
}
else
{
const Char8 *defines = _sfDefines.getValue().c_str();
const char *shaderSources[2] =
{
defines,
source
};
osgGlShaderSource(uiShader,
2,
shaderSources,
0);
}
osgGlCompileShader(uiShader);
GLint iStatus = 0;
osgGlGetShaderiv( uiShader,
GL_COMPILE_STATUS,
&iStatus);
if(iStatus == 0)
{
GLint iDebugLength;
osgGlGetShaderiv( uiShader,
GL_INFO_LOG_LENGTH,
&iDebugLength);
if(iDebugLength > 0)
{
Char8 *szDebug = new Char8[iDebugLength];
OSGGETGLFUNCBYID_GL3_ES(glGetShaderInfoLog,
osgGlGetShaderInfoLog,
FuncIdGetShaderInfoLog,
pWin);
osgGlGetShaderInfoLog( uiShader,
iDebugLength,
&iDebugLength,
szDebug );
FFATAL(( "Couldn't compile shader program (0x%x)!\n%s\n",
_sfShaderType.getValue(),
szDebug));
delete [] szDebug;
}
// log source that failed to compile
FINFO(("Shader source was:\n"));
if(_sfDefines.getValue().empty() == false)
{
FPINFO(("%s\n", _sfDefines.getValue().c_str()));
}
FPINFO(("%s\n", source));
OSGGETGLFUNCBYID_GL3_ES(glDeleteShader,
osgGlDeleteShader,
FuncIdDeleteShader,
pWin);
osgGlDeleteShader(uiShader);
uiShader = 0;
}
pWin->setGLObjectId(getGLId(), uiShader);
}
//updateProgramParameters(win);
//updateParameters(win,
//*getMFParameters(),
//true,
//true /*mode != Window::needrefresh*/);
}
return 0;
}
void ShaderProgram::handleDestroyGL(DrawEnv *pEnv,
UInt32 id,
Window::GLObjectStatusE mode)
{
Window *pWin = pEnv->getWindow();
if(!pWin->hasExtOrVersion(_extSHL, 0x0200, 0x0200))
{
FWARNING(("OpenGL Shading Language is not supported, couldn't find "
"extension 'GL_ARB_shading_language_100'!\n"));
pWin->setGLObjectId(id, 0);
return;
}
if(mode == Window::destroy)
{
GLuint uiShader = GLuint(pWin->getGLObjectId(id));
if(uiShader != 0)
{
OSGGETGLFUNCBYID_GL3_ES(glDeleteShader,
osgGlDeleteShader,
FuncIdDeleteShader,
pWin);
osgGlDeleteShader(uiShader);
pWin->setGLObjectId(id, 0);
}
}
else if(mode == Window::finaldestroy)
{
;//SWARNING << "Last program user destroyed" << std::endl;
}
}
/*----------------------------- class specific ----------------------------*/
void ShaderProgram::changed(ConstFieldMaskArg whichField,
UInt32 origin,
BitVector details)
{
Inherited::changed(whichField, origin, details);
if(0x0000 != (whichField & VariablesFieldMask))
{
if(details == 0x0001)
{
MFParentFieldContainerPtr::const_iterator parentsIt =
this->_mfParents.begin();
MFParentFieldContainerPtr::const_iterator parentsEnd =
this->_mfParents.end();
while(parentsIt != parentsEnd)
{
(*parentsIt)->changed(
TypeTraits<BitVector>::One << parentsIt.getParentFieldPos(),
ChangedOrigin::Child,
VariablesFieldMask);
++parentsIt;
}
}
}
if(0x0000 != (whichField & ProgramFieldMask))
{
MFParentFieldContainerPtr::const_iterator parentsIt =
this->_mfParents.begin();
MFParentFieldContainerPtr::const_iterator parentsEnd =
this->_mfParents.end();
while(parentsIt != parentsEnd)
{
(*parentsIt)->changed(
TypeTraits<BitVector>::One << parentsIt.getParentFieldPos(),
ChangedOrigin::Child,
ProgramFieldMask);
++parentsIt;
}
Window::reinitializeGLObject(this->getGLId());
}
}
ShaderProgramTransitPtr ShaderProgram::createVertexShader(
bool bCreateDefAttribMap)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_VERTEX_SHADER);
if(bCreateDefAttribMap == true)
returnValue->createDefaulAttribMapping();
return returnValue;
}
ShaderProgramTransitPtr ShaderProgram::createGeometryShader(void)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_GEOMETRY_SHADER_EXT);
return returnValue;
}
ShaderProgramTransitPtr ShaderProgram::createFragmentShader(void)
{
ShaderProgramTransitPtr returnValue = ShaderProgram::create();
returnValue->setShaderType(GL_FRAGMENT_SHADER);
return returnValue;
}
void ShaderProgram::accumulateFeedback(
DrawEnv *pEnv,
UInt32 uiProgram,
std::vector<const Char8 *> &vTFVaryings,
UInt32 &uiVaryingBufferIndex)
{
if(((_sfShaderType.getValue() == GL_VERTEX_SHADER) ||
(_sfShaderType.getValue() == GL_GEOMETRY_SHADER_EXT) ) == false)
{
return;
}
if(vTFVaryings.size() != 0)
{
vTFVaryings.push_back(NextBufferToken);
}
MFFeedbackVaryingsType::const_iterator vIt =
this->getMFFeedbackVaryings()->begin();
MFFeedbackVaryingsType::const_iterator vEnd =
this->getMFFeedbackVaryings()->end ();
for(; vIt != vEnd; ++vIt)
{
vTFVaryings.push_back((*vIt).c_str());
}
}
void ShaderProgram::addParent(FieldContainer * const pParent,
UInt16 uiParentFieldId)
{
editMField(ParentsFieldMask, _mfParents);
OSG_ASSERT(pParent != NULL);
_mfParents.push_back(pParent, uiParentFieldId);
}
void ShaderProgram::subParent(FieldContainer * const pParent)
{
Int32 iParentIdx = _mfParents.findIndex(pParent);
if(iParentIdx != -1)
{
editMField(ParentsFieldMask, _mfParents);
_mfParents.erase(iParentIdx);
}
}
void ShaderProgram::dump( UInt32 ,
const BitVector ) const
{
SLOG << "Dump ShaderProgram NI" << std::endl;
}
bool ShaderProgram::readProgram(const Char8 *file)
{
return readProgram(editSFProgram()->getValue(), file);
}
bool ShaderProgram::subUniformVariable(const Char8 *name)
{
if(_sfVariables.getValue() != NULL)
{
#if 0
return _sfVariables.getValue()->subUniformVariable(
name,
editMFVariableLocations(),
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->subUniformVariable(
name,
NULL,
NULL);
#endif
}
return false;
}
void ShaderProgram::clearUniformVariables(void)
{
if(_sfVariables.getValue() != NULL)
{
_sfVariables.getValue()->clearUniformVariables();
}
}
bool ShaderProgram::subUniformBlock(const Char8 *name)
{
if(_sfVariables.getValue() != NULL)
{
#if 0
return _sfVariables.getValue()->subUniformBlock(
name,
editMFBlockLocations(),
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->subUniformBlock(
name,
NULL,
NULL);
#endif
}
return false;
}
bool ShaderProgram::addProceduralVariable(const Char8 *name,
ProcVarFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
#if 0
return _sfVariables.getValue()->addProceduralVariable(
name,
pFunc,
uiDependency,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addProceduralVariable(
name,
pFunc,
uiDependency,
NULL);
#endif
}
bool ShaderProgram::addNodeProceduralVariable(
const Char8 *name,
ProcVarNodeFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
#if 0
return _sfVariables.getValue()->addNodeProceduralVariable(
name,
pFunc,
uiDependency,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addNodeProceduralVariable(
name,
pFunc,
uiDependency,
NULL);
#endif
}
/*! \nohierarchy
*/
struct ParamEqual
{
GLenum _ref;
ParamEqual(GLenum ref) :
_ref(ref)
{
}
bool operator() (const ShaderParameter &lhs)
{
return lhs.first == _ref;
}
};
void ShaderProgram::setProgramParameter(GLenum name, UInt32 value)
{
editMField(ParameterFieldMask, _mfParameter);
MFShaderParameter::iterator pIt =
std::find_if(_mfParameter.begin(),
_mfParameter.end (),
ParamEqual (name));
if(pIt != _mfParameter.end())
{
pIt->second = value;
}
else
{
ShaderParameter tmpParam;
tmpParam.first = name;
tmpParam.second = value;
_mfParameter.push_back(tmpParam);
}
}
void ShaderProgram::subProgramParameter(GLenum name)
{
MFShaderParameter::iterator pIt =
std::find_if(_mfParameter.begin(),
_mfParameter.end (),
ParamEqual (name));
if(pIt != _mfParameter.end())
{
editMField(ParameterFieldMask, _mfParameter);
_mfParameter.erase(pIt);
}
}
struct AttribEqual
{
UInt16 _ref;
AttribEqual(UInt16 ref) :
_ref(ref)
{
}
bool operator() (const ShaderAttribute &lhs)
{
return lhs.first == _ref;
}
};
void ShaderProgram::setProgramAttribute(UInt16 uiIndex, std::string szName)
{
editMField(AttributesFieldMask, _mfAttributes);
MFShaderAttribute::iterator aIt =
std::find_if(_mfAttributes.begin(),
_mfAttributes.end (),
AttribEqual (uiIndex));
if(aIt != _mfAttributes.end())
{
aIt->second = szName;
}
else
{
ShaderAttribute tmpAttr;
tmpAttr.first = uiIndex;
tmpAttr.second = szName;
_mfAttributes.push_back(tmpAttr);
}
}
void ShaderProgram::subProgramAttribute(UInt16 uiIndex)
{
MFAttributesType::iterator aIt =
std::find_if(_mfAttributes.begin(),
_mfAttributes.end (),
AttribEqual (uiIndex));
if(aIt != _mfAttributes.end())
{
editMField(AttributesFieldMask, _mfAttributes);
_mfAttributes.erase(aIt);
}
}
void ShaderProgram::createDefaulAttribMapping(void)
{
if(_sfShaderType.getValue() == GL_VERTEX_SHADER)
{
this->setProgramAttribute(ShaderConstants::Attribute0Index,
"osg_Vertex" );
this->setProgramAttribute(ShaderConstants::Attribute2Index,
"osg_Normal" );
this->setProgramAttribute(ShaderConstants::Attribute3Index,
"osg_Color" );
this->setProgramAttribute(ShaderConstants::Attribute4Index,
"osg_SecondaryColor" );
this->setProgramAttribute(ShaderConstants::Attribute8Index,
"osg_MultiTexCoord0" );
this->setProgramAttribute(ShaderConstants::Attribute9Index,
"osg_MultiTexCoord1" );
this->setProgramAttribute(ShaderConstants::Attribute10Index,
"osg_MultiTexCoord2" );
this->setProgramAttribute(ShaderConstants::Attribute11Index,
"osg_MultiTexCoord3" );
this->setProgramAttribute(ShaderConstants::Attribute12Index,
"osg_MultiTexCoord4" );
this->setProgramAttribute(ShaderConstants::Attribute13Index,
"osg_MultiTexCoord5" );
this->setProgramAttribute(ShaderConstants::Attribute14Index,
"osg_MultiTexCoord6" );
this->setProgramAttribute(ShaderConstants::Attribute15Index,
"osg_MultiTexCoord7" );
}
else
{
FWARNING(("attrib map can only be created for a vertex shader"));
}
}
bool ShaderProgram::addOSGVariable(const Char8 *name)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pVar =
ShaderProgramVariables::create();
setVariables(pVar);
}
#if 0
return _sfVariables.getValue()->addOSGVariable(
name,
editMFProceduralVariableLocations());
#else
return _sfVariables.getValue()->addOSGVariable(name,
NULL);
#endif
}
bool ShaderProgram::updateProceduralVariable(const Char8 *name,
ProcVarFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
return _sfVariables.getValue()->updateProceduralVariable(name,
pFunc,
uiDependency);
}
bool ShaderProgram::updateNodeProceduralVariable(
const Char8 *name,
ProcVarNodeFunctor pFunc,
UInt32 uiDependency)
{
if(_sfVariables.getValue() == NULL)
{
ShaderProgramVariablesUnrecPtr pParam =
ShaderProgramVariables::create();
setVariables(pParam);
}
return _sfVariables.getValue()->updateNodeProceduralVariable(name,
pFunc,
uiDependency);
}
bool ShaderProgram::readProgram( std::string &szTarget,
const Char8 *szFilename)
{
std::ifstream s(szFilename);
if(s.good())
{
return readProgram(szTarget, s);
}
else
{
FWARNING(("ShaderChunk::readProgram: couldn't open '%s' "
"for reading!\n", szFilename));
return false;
}
}
bool ShaderProgram::readProgram(std::string &szTarget,
std::istream &iStream)
{
#define BUFSIZE 200
szTarget.erase();
Char8 buf[BUFSIZE];
if(!iStream.good())
{
FWARNING(("SHLChunk::readProgram: stream is not good!\n"));
return false;
}
do
{
iStream.read(buf, BUFSIZE);
szTarget.append(buf, iStream.gcount());
}
while(!iStream.eof());
return true;
}
OSG_END_NAMESPACE
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/hid/winkey/winkey_input_driver.h"
#include "xenia/base/platform_win.h"
#include "xenia/hid/hid_flags.h"
namespace xe {
namespace hid {
namespace winkey {
WinKeyInputDriver::WinKeyInputDriver(InputSystem* input_system)
: InputDriver(input_system), packet_number_(1) {}
WinKeyInputDriver::~WinKeyInputDriver() = default;
X_STATUS WinKeyInputDriver::Setup() { return X_STATUS_SUCCESS; }
X_RESULT WinKeyInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
X_INPUT_CAPABILITIES* out_caps) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
// TODO(benvanik): confirm with a real XInput controller.
out_caps->type = 0x01; // XINPUT_DEVTYPE_GAMEPAD
out_caps->sub_type = 0x01; // XINPUT_DEVSUBTYPE_GAMEPAD
out_caps->flags = 0;
out_caps->gamepad.buttons = 0xFFFF;
out_caps->gamepad.left_trigger = 0xFF;
out_caps->gamepad.right_trigger = 0xFF;
out_caps->gamepad.thumb_lx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ly = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_rx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ry = (int16_t)0xFFFFu;
out_caps->vibration.left_motor_speed = 0;
out_caps->vibration.right_motor_speed = 0;
return X_ERROR_SUCCESS;
}
#define IS_KEY_TOGGLED(key) ((GetKeyState(key) & 0x1) == 0x1)
#define IS_KEY_DOWN(key) ((GetAsyncKeyState(key) & 0x8000) == 0x8000)
X_RESULT WinKeyInputDriver::GetState(uint32_t user_index,
X_INPUT_STATE* out_state) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
packet_number_++;
uint16_t buttons = 0;
uint8_t left_trigger = 0;
uint8_t right_trigger = 0;
int16_t thumb_lx = 0;
int16_t thumb_ly = 0;
int16_t thumb_rx = 0;
int16_t thumb_ry = 0;
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (IS_KEY_DOWN(0x41)) {
// A
buttons |= 0x0004; // XINPUT_GAMEPAD_DPAD_LEFT
}
if (IS_KEY_DOWN(0x44)) {
// D
buttons |= 0x0008; // XINPUT_GAMEPAD_DPAD_RIGHT
}
if (IS_KEY_DOWN(0x53)) {
// S
buttons |= 0x0002; // XINPUT_GAMEPAD_DPAD_DOWN
}
if (IS_KEY_DOWN(0x57)) {
// W
buttons |= 0x0001; // XINPUT_GAMEPAD_DPAD_UP
}
} else {
// left stick
if (IS_KEY_DOWN(0x41)) {
// A
thumb_lx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x44)) {
// D
thumb_lx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x53)) {
// S
thumb_ly += SHRT_MIN;
}
if (IS_KEY_DOWN(0x57)) {
// W
thumb_ly += SHRT_MAX;
}
}
if (IS_KEY_DOWN(0x4C)) {
// L
buttons |= 0x4000; // XINPUT_GAMEPAD_X
}
if (IS_KEY_DOWN(VK_OEM_7)) {
// '
buttons |= 0x2000; // XINPUT_GAMEPAD_B
}
if (IS_KEY_DOWN(VK_OEM_1)) {
// ;
buttons |= 0x1000; // XINPUT_GAMEPAD_A
}
if (IS_KEY_DOWN(0x50)) {
// P
buttons |= 0x8000; // XINPUT_GAMEPAD_Y
}
if (IS_KEY_DOWN(0x5A)) {
// Z
buttons |= 0x0020; // XINPUT_GAMEPAD_BACK
}
if (IS_KEY_DOWN(0x58)) {
// X
buttons |= 0x0010; // XINPUT_GAMEPAD_START
}
out_state->packet_number = packet_number_;
out_state->gamepad.buttons = buttons;
out_state->gamepad.left_trigger = left_trigger;
out_state->gamepad.right_trigger = right_trigger;
out_state->gamepad.thumb_lx = thumb_lx;
out_state->gamepad.thumb_ly = thumb_ly;
out_state->gamepad.thumb_rx = thumb_rx;
out_state->gamepad.thumb_ry = thumb_ry;
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::SetState(uint32_t user_index,
X_INPUT_VIBRATION* vibration) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
X_INPUT_KEYSTROKE* out_keystroke) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT result = X_ERROR_EMPTY;
uint16_t virtual_key = 0;
uint16_t unicode = 0;
uint16_t keystroke_flags = 0;
uint8_t hid_code = 0;
out_keystroke->virtual_key = virtual_key;
out_keystroke->unicode = unicode;
out_keystroke->flags = keystroke_flags;
out_keystroke->user_index = 0;
out_keystroke->hid_code = hid_code;
// X_ERROR_EMPTY if no new keys
// X_ERROR_DEVICE_NOT_CONNECTED if no device
// X_ERROR_SUCCESS if key
return result;
}
} // namespace winkey
} // namespace hid
} // namespace xe
Winkey support GetKeystroke (need to fix flags though) and support right stick
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/hid/winkey/winkey_input_driver.h"
#include "xenia/base/platform_win.h"
#include "xenia/hid/hid_flags.h"
namespace xe {
namespace hid {
namespace winkey {
WinKeyInputDriver::WinKeyInputDriver(InputSystem* input_system)
: InputDriver(input_system), packet_number_(1) {}
WinKeyInputDriver::~WinKeyInputDriver() = default;
X_STATUS WinKeyInputDriver::Setup() { return X_STATUS_SUCCESS; }
X_RESULT WinKeyInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
X_INPUT_CAPABILITIES* out_caps) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
// TODO(benvanik): confirm with a real XInput controller.
out_caps->type = 0x01; // XINPUT_DEVTYPE_GAMEPAD
out_caps->sub_type = 0x01; // XINPUT_DEVSUBTYPE_GAMEPAD
out_caps->flags = 0;
out_caps->gamepad.buttons = 0xFFFF;
out_caps->gamepad.left_trigger = 0xFF;
out_caps->gamepad.right_trigger = 0xFF;
out_caps->gamepad.thumb_lx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ly = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_rx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ry = (int16_t)0xFFFFu;
out_caps->vibration.left_motor_speed = 0;
out_caps->vibration.right_motor_speed = 0;
return X_ERROR_SUCCESS;
}
#define IS_KEY_TOGGLED(key) ((GetKeyState(key) & 0x1) == 0x1)
#define IS_KEY_DOWN(key) ((GetAsyncKeyState(key) & 0x8000) == 0x8000)
X_RESULT WinKeyInputDriver::GetState(uint32_t user_index,
X_INPUT_STATE* out_state) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
packet_number_++;
uint16_t buttons = 0;
uint8_t left_trigger = 0;
uint8_t right_trigger = 0;
int16_t thumb_lx = 0;
int16_t thumb_ly = 0;
int16_t thumb_rx = 0;
int16_t thumb_ry = 0;
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (IS_KEY_DOWN(0x41)) {
// A
buttons |= 0x0004; // XINPUT_GAMEPAD_DPAD_LEFT
}
if (IS_KEY_DOWN(0x44)) {
// D
buttons |= 0x0008; // XINPUT_GAMEPAD_DPAD_RIGHT
}
if (IS_KEY_DOWN(0x53)) {
// S
buttons |= 0x0002; // XINPUT_GAMEPAD_DPAD_DOWN
}
if (IS_KEY_DOWN(0x57)) {
// W
buttons |= 0x0001; // XINPUT_GAMEPAD_DPAD_UP
}
} else {
// left stick
if (IS_KEY_DOWN(0x41)) {
// A
thumb_lx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x44)) {
// D
thumb_lx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x53)) {
// S
thumb_ly += SHRT_MIN;
}
if (IS_KEY_DOWN(0x57)) {
// W
thumb_ly += SHRT_MAX;
}
}
// Right stick
if (IS_KEY_DOWN(0x26)) {
// Up
thumb_ry += SHRT_MAX;
}
if (IS_KEY_DOWN(0x28)) {
// Down
thumb_ry += SHRT_MIN;
}
if (IS_KEY_DOWN(0x27)) {
// Right
thumb_rx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x25)) {
// Left
thumb_rx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x4C)) {
// L
buttons |= 0x4000; // XINPUT_GAMEPAD_X
}
if (IS_KEY_DOWN(VK_OEM_7)) {
// '
buttons |= 0x2000; // XINPUT_GAMEPAD_B
}
if (IS_KEY_DOWN(VK_OEM_1)) {
// ;
buttons |= 0x1000; // XINPUT_GAMEPAD_A
}
if (IS_KEY_DOWN(0x50)) {
// P
buttons |= 0x8000; // XINPUT_GAMEPAD_Y
}
if (IS_KEY_DOWN(0x5A)) {
// Z
buttons |= 0x0020; // XINPUT_GAMEPAD_BACK
}
if (IS_KEY_DOWN(0x58)) {
// X
buttons |= 0x0010; // XINPUT_GAMEPAD_START
}
out_state->packet_number = packet_number_;
out_state->gamepad.buttons = buttons;
out_state->gamepad.left_trigger = left_trigger;
out_state->gamepad.right_trigger = right_trigger;
out_state->gamepad.thumb_lx = thumb_lx;
out_state->gamepad.thumb_ly = thumb_ly;
out_state->gamepad.thumb_rx = thumb_rx;
out_state->gamepad.thumb_ry = thumb_ry;
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::SetState(uint32_t user_index,
X_INPUT_VIBRATION* vibration) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
X_INPUT_KEYSTROKE* out_keystroke) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT result = X_ERROR_EMPTY;
uint16_t virtual_key = 0;
uint16_t unicode = 0;
uint16_t keystroke_flags = 0;
uint8_t hid_code = 0;
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (IS_KEY_DOWN(0x41)) {
// A
virtual_key = 0x5812; // VK_PAD_DPAD_LEFT
} else if (IS_KEY_DOWN(0x44)) {
// D
virtual_key = 0x5813; // VK_PAD_DPAD_RIGHT
} else if (IS_KEY_DOWN(0x53)) {
// S
virtual_key = 0x5811; // VK_PAD_DPAD_DOWN
} else if (IS_KEY_DOWN(0x57)) {
// W
virtual_key = 0x5810; // VK_PAD_DPAD_UP
}
} else {
// left stick
if (IS_KEY_DOWN(0x57)) {
// W
virtual_key = 0x5820; // VK_PAD_LTHUMB_UP
}
if (IS_KEY_DOWN(0x53)) {
// S
virtual_key = 0x5821; // VK_PAD_LTHUMB_DOWN
}
if (IS_KEY_DOWN(0x44)) {
// D
virtual_key = 0x5822; // VK_PAD_LTHUMB_RIGHT
}
if (IS_KEY_DOWN(0x41)) {
// A
virtual_key = 0x5823; // VK_PAD_LTHUMB_LEFT
}
}
// Right stick
if (IS_KEY_DOWN(0x26)) {
// Up
virtual_key = 0x5830;
}
if (IS_KEY_DOWN(0x28)) {
// Down
virtual_key = 0x5831;
}
if (IS_KEY_DOWN(0x27)) {
// Right
virtual_key = 0x5832;
}
if (IS_KEY_DOWN(0x25)) {
// Left
virtual_key = 0x5833;
}
if (IS_KEY_DOWN(0x4C)) {
// L
virtual_key = 0x5802; // VK_PAD_X
} else if (IS_KEY_DOWN(VK_OEM_7)) {
// '
virtual_key = 0x5801; // VK_PAD_B
} else if (IS_KEY_DOWN(VK_OEM_1)) {
// ;
virtual_key = 0x5800; // VK_PAD_A
} else if (IS_KEY_DOWN(0x50)) {
// P
virtual_key = 0x5803; // VK_PAD_Y
}
if (IS_KEY_DOWN(0x58)) {
// X
virtual_key = 0x5814; // VK_PAD_START
}
if (IS_KEY_DOWN(0x5A)) {
// Z
virtual_key = 0x5815; // VK_PAD_BACK
}
if (virtual_key != 0) {
keystroke_flags |= 0x0001; // XINPUT_KEYSTROKE_DOWN
result = X_ERROR_SUCCESS;
}
out_keystroke->virtual_key = virtual_key;
out_keystroke->unicode = unicode;
out_keystroke->flags = keystroke_flags;
out_keystroke->user_index = 0;
out_keystroke->hid_code = hid_code;
// X_ERROR_EMPTY if no new keys
// X_ERROR_DEVICE_NOT_CONNECTED if no device
// X_ERROR_SUCCESS if key
return result;
}
} // namespace winkey
} // namespace hid
} // namespace xe
|
#ifndef STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP
#define STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/err.hpp>
#include <tuple>
namespace stan {
namespace math {
namespace internal {
constexpr int constexpr_sum() { return 0; }
template <typename Arg0, typename... Args>
constexpr int constexpr_sum(Arg0 arg0, Args... args) {
return arg0 + constexpr_sum(args...);
}
constexpr bool constexpr_all() { return true; }
template <typename Arg0, typename... Args>
constexpr bool constexpr_all(Arg0 arg0, Args... args) {
return arg0 && constexpr_all(args...);
}
} // namespace internal
/**
* Represents multiple exprs that will be calculated in same loop.
* @tparam T_expressions types of exprs
*/
template <typename... T_expressions>
class eigen_expressions_ {
public:
/**
* Constructor.
* @param exprs expresions that will be calculated in same loop.
* @throw invalid_argument expressions have different sizes (for row major
* expressions rows and columns are swapped for the check)
*/
explicit eigen_expressions_(T_expressions&&... exprs)
: exprs_(std::forward<T_expressions>(exprs)...) {
index_apply<sizeof...(T_expressions) - 1>([&](auto... Is) {
constexpr auto first_flags = Eigen::internal::evaluator<std::decay_t<
std::tuple_element_t<0, std::tuple<T_expressions...>>>>::Flags;
static_cast<void>(std::initializer_list<int>{
((((Eigen::internal::evaluator<std::decay_t<std::tuple_element_t<
Is + 1, std::tuple<T_expressions...>>>>::Flags
^ first_flags)
& Eigen::RowMajorBit)
? check_matching_dims("eigen_expressions_.eigen_expressions_",
"first expression", std::get<0>(exprs_),
"transposed expression",
std::get<Is + 1>(exprs_).transpose())
: check_matching_dims("eigen_expressions_.eigen_expressions_",
"first expression", std::get<0>(exprs_),
"expression", std::get<Is + 1>(exprs_))),
0)...});
});
}
private:
std::tuple<T_expressions...> exprs_;
template <typename... T_results>
friend class eigen_results_;
};
/**
* Deduces types for constructing \c expressions_ object.
* @tparam T_expressions types of exprs
* @param exprs exprs that will be used in same kernel.
*/
template <typename... T_expressions,
require_all_eigen_t<T_expressions...>* = nullptr>
eigen_expressions_<T_expressions...> eigen_expressions(
T_expressions&&... exprs) {
return eigen_expressions_<T_expressions...>(
std::forward<T_expressions>(exprs)...);
}
/**
* Represents results that will be calculated in same loop.
* @tparam T_results types of results
*/
template <typename... T_results>
class eigen_results_ {
std::tuple<T_results...> results_;
/**
* Assign expressions to results using linear indexing.
* @tparam Linear whether to use linear indexing
* @tparam T_expr_evals types of expression evaluators
* @param expr_evals evaluators for expressions to assign
* @param rows number of rows
* @param cols number of cols
*/
template <bool Linear, typename... T_expr_evals,
std::enable_if_t<Linear>* = nullptr>
inline void assign(const std::tuple<T_expr_evals...>& expr_evals,
Eigen::Index rows, Eigen::Index cols) {
for (size_t i = 0; i < rows * cols; i++) {
index_apply<sizeof...(T_results)>([&](auto... Is) {
static_cast<void>(
std::initializer_list<int>{(std::get<Is>(this->results_).coeffRef(i)
= std::get<Is>(expr_evals).coeff(i),
0)...});
});
}
}
/**
* Assign expressions to results using 2d indexing.
* @tparam Linear whether to use linear indexing
* @tparam T_expr_evals types of expression evaluators
* @param expr_evals evaluators for expressions to assign
* @param rows number of rows
* @param cols number of cols
*/
template <bool Linear, typename... T_expr_evals,
std::enable_if_t<!Linear>* = nullptr>
inline void assign(const std::tuple<T_expr_evals...>& expr_evals,
Eigen::Index rows, Eigen::Index cols) {
constexpr bool is_first_row_major
= std::decay_t<decltype(std::get<0>(expr_evals))>::Flags
& Eigen::RowMajorBit;
const Eigen::Index outer_dimension = is_first_row_major ? rows : cols;
const Eigen::Index inner_dimension = is_first_row_major ? cols : rows;
for (size_t i = 0; i < outer_dimension; i++) {
for (size_t j = 0; j < inner_dimension; j++) {
index_apply<sizeof...(T_results)>([&](auto... Is) {
static_cast<void>(std::initializer_list<int>{
((std::decay_t<decltype(std::get<0>(expr_evals))>::Flags
& Eigen::RowMajorBit
? std::get<Is>(this->results_).coeffRef(i, j)
= std::get<Is>(expr_evals).coeff(i, j)
: std::get<Is>(this->results_).coeffRef(j, i)
= std::get<Is>(expr_evals).coeff(j, i)),
0)...});
});
}
}
}
/**
* Selects and calls appropriate `assign`.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void assign_select(const eigen_expressions_<T_expressions...>& expressions) {
constexpr bool all_linear = internal::constexpr_all(
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags
& Eigen::LinearAccessBit)...,
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_results>>::Flags
& Eigen::LinearAccessBit)...);
constexpr int N_row_major = internal::constexpr_sum(
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags
& Eigen::RowMajorBit)...,
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_results>>::Flags
& Eigen::RowMajorBit)...);
constexpr int N_col_major
= sizeof...(T_results) + sizeof...(T_expressions) - N_row_major;
index_apply<sizeof...(T_results)>([&](auto... Is) {
std::tuple<Eigen::internal::evaluator<
std::decay_t<decltype(std::get<Is>(expressions.exprs_))>>...>
expression_evaluators(std::get<Is>(expressions.exprs_)...);
this->assign<all_linear && (N_col_major == 0 || N_row_major == 0)>(
expression_evaluators,
std::get<0>(expressions.exprs_).rows(),
std::get<0>(expressions.exprs_).cols());
});
}
public:
/**
* Constructor.
* @param results results that will be calculated in same kernel
*/
explicit eigen_results_(T_results&&... results)
: results_(std::forward<T_results>(results)...) {}
/**
* Assigning \c expressions_cl object to \c eigen_results_ object evals the
* expressions into results.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void operator=(const eigen_expressions_<T_expressions...>& expressions) {
index_apply<sizeof...(T_results)>([&, this](auto... Is) {
static_cast<void>(std::initializer_list<int>{
(Eigen::internal::resize_if_allowed(
std::get<Is>(this->results_), std::get<Is>(expressions.exprs_),
Eigen::internal::assign_op<int, int>()),
// types in the assign_op don't matter for the resizing
0)...});
});
assign_select(expressions);
}
/**
* Add \c eigen_results_ to \c expressions_cl in place.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void operator+=(const eigen_expressions_<T_expressions...>& expressions) {
index_apply<sizeof...(T_results)>([&, this](auto... Is) {
this->assign_select(eigen_expressions((
std::get<Is>(this->results_) + std::get<Is>(expressions.exprs_))...));
});
}
};
/**
* Deduces types for constructing \c results_cl object.
* @tparam T_results types of results
* @param results results that will be calculated in same kernel.
*/
template <typename... T_results, require_all_eigen_t<T_results...>* = nullptr>
eigen_results_<T_results...> eigen_results(T_results&&... results) {
return eigen_results_<T_results...>(std::forward<T_results>(results)...);
}
} // namespace math
} // namespace stan
#endif
[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)
#ifndef STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP
#define STAN_MATH_PRIM_FUNCTOR_MULTI_EXPRESSION_HPP
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/err.hpp>
#include <tuple>
namespace stan {
namespace math {
namespace internal {
constexpr int constexpr_sum() { return 0; }
template <typename Arg0, typename... Args>
constexpr int constexpr_sum(Arg0 arg0, Args... args) {
return arg0 + constexpr_sum(args...);
}
constexpr bool constexpr_all() { return true; }
template <typename Arg0, typename... Args>
constexpr bool constexpr_all(Arg0 arg0, Args... args) {
return arg0 && constexpr_all(args...);
}
} // namespace internal
/**
* Represents multiple exprs that will be calculated in same loop.
* @tparam T_expressions types of exprs
*/
template <typename... T_expressions>
class eigen_expressions_ {
public:
/**
* Constructor.
* @param exprs expresions that will be calculated in same loop.
* @throw invalid_argument expressions have different sizes (for row major
* expressions rows and columns are swapped for the check)
*/
explicit eigen_expressions_(T_expressions&&... exprs)
: exprs_(std::forward<T_expressions>(exprs)...) {
index_apply<sizeof...(T_expressions) - 1>([&](auto... Is) {
constexpr auto first_flags = Eigen::internal::evaluator<std::decay_t<
std::tuple_element_t<0, std::tuple<T_expressions...>>>>::Flags;
static_cast<void>(std::initializer_list<int>{
((((Eigen::internal::evaluator<std::decay_t<std::tuple_element_t<
Is + 1, std::tuple<T_expressions...>>>>::Flags
^ first_flags)
& Eigen::RowMajorBit)
? check_matching_dims("eigen_expressions_.eigen_expressions_",
"first expression", std::get<0>(exprs_),
"transposed expression",
std::get<Is + 1>(exprs_).transpose())
: check_matching_dims("eigen_expressions_.eigen_expressions_",
"first expression", std::get<0>(exprs_),
"expression", std::get<Is + 1>(exprs_))),
0)...});
});
}
private:
std::tuple<T_expressions...> exprs_;
template <typename... T_results>
friend class eigen_results_;
};
/**
* Deduces types for constructing \c expressions_ object.
* @tparam T_expressions types of exprs
* @param exprs exprs that will be used in same kernel.
*/
template <typename... T_expressions,
require_all_eigen_t<T_expressions...>* = nullptr>
eigen_expressions_<T_expressions...> eigen_expressions(
T_expressions&&... exprs) {
return eigen_expressions_<T_expressions...>(
std::forward<T_expressions>(exprs)...);
}
/**
* Represents results that will be calculated in same loop.
* @tparam T_results types of results
*/
template <typename... T_results>
class eigen_results_ {
std::tuple<T_results...> results_;
/**
* Assign expressions to results using linear indexing.
* @tparam Linear whether to use linear indexing
* @tparam T_expr_evals types of expression evaluators
* @param expr_evals evaluators for expressions to assign
* @param rows number of rows
* @param cols number of cols
*/
template <bool Linear, typename... T_expr_evals,
std::enable_if_t<Linear>* = nullptr>
inline void assign(const std::tuple<T_expr_evals...>& expr_evals,
Eigen::Index rows, Eigen::Index cols) {
for (size_t i = 0; i < rows * cols; i++) {
index_apply<sizeof...(T_results)>([&](auto... Is) {
static_cast<void>(
std::initializer_list<int>{(std::get<Is>(this->results_).coeffRef(i)
= std::get<Is>(expr_evals).coeff(i),
0)...});
});
}
}
/**
* Assign expressions to results using 2d indexing.
* @tparam Linear whether to use linear indexing
* @tparam T_expr_evals types of expression evaluators
* @param expr_evals evaluators for expressions to assign
* @param rows number of rows
* @param cols number of cols
*/
template <bool Linear, typename... T_expr_evals,
std::enable_if_t<!Linear>* = nullptr>
inline void assign(const std::tuple<T_expr_evals...>& expr_evals,
Eigen::Index rows, Eigen::Index cols) {
constexpr bool is_first_row_major
= std::decay_t<decltype(std::get<0>(expr_evals))>::Flags
& Eigen::RowMajorBit;
const Eigen::Index outer_dimension = is_first_row_major ? rows : cols;
const Eigen::Index inner_dimension = is_first_row_major ? cols : rows;
for (size_t i = 0; i < outer_dimension; i++) {
for (size_t j = 0; j < inner_dimension; j++) {
index_apply<sizeof...(T_results)>([&](auto... Is) {
static_cast<void>(std::initializer_list<int>{
((std::decay_t<decltype(std::get<0>(expr_evals))>::Flags
& Eigen::RowMajorBit
? std::get<Is>(this->results_).coeffRef(i, j)
= std::get<Is>(expr_evals).coeff(i, j)
: std::get<Is>(this->results_).coeffRef(j, i)
= std::get<Is>(expr_evals).coeff(j, i)),
0)...});
});
}
}
}
/**
* Selects and calls appropriate `assign`.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void assign_select(const eigen_expressions_<T_expressions...>& expressions) {
constexpr bool all_linear = internal::constexpr_all(
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags
& Eigen::LinearAccessBit)...,
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_results>>::Flags
& Eigen::LinearAccessBit)...);
constexpr int N_row_major = internal::constexpr_sum(
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_expressions>>::Flags
& Eigen::RowMajorBit)...,
static_cast<bool>(
Eigen::internal::evaluator<std::decay_t<T_results>>::Flags
& Eigen::RowMajorBit)...);
constexpr int N_col_major
= sizeof...(T_results) + sizeof...(T_expressions) - N_row_major;
index_apply<sizeof...(T_results)>([&](auto... Is) {
std::tuple<Eigen::internal::evaluator<
std::decay_t<decltype(std::get<Is>(expressions.exprs_))>>...>
expression_evaluators(std::get<Is>(expressions.exprs_)...);
this->assign<all_linear && (N_col_major == 0 || N_row_major == 0)>(
expression_evaluators, std::get<0>(expressions.exprs_).rows(),
std::get<0>(expressions.exprs_).cols());
});
}
public:
/**
* Constructor.
* @param results results that will be calculated in same kernel
*/
explicit eigen_results_(T_results&&... results)
: results_(std::forward<T_results>(results)...) {}
/**
* Assigning \c expressions_cl object to \c eigen_results_ object evals the
* expressions into results.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void operator=(const eigen_expressions_<T_expressions...>& expressions) {
index_apply<sizeof...(T_results)>([&, this](auto... Is) {
static_cast<void>(std::initializer_list<int>{
(Eigen::internal::resize_if_allowed(
std::get<Is>(this->results_), std::get<Is>(expressions.exprs_),
Eigen::internal::assign_op<int, int>()),
// types in the assign_op don't matter for the resizing
0)...});
});
assign_select(expressions);
}
/**
* Add \c eigen_results_ to \c expressions_cl in place.
* @tparam T_expressions types of expressions
* @param expressions expressions
*/
template <typename... T_expressions,
std::enable_if_t<sizeof...(T_results)
== sizeof...(T_expressions)>* = nullptr>
void operator+=(const eigen_expressions_<T_expressions...>& expressions) {
index_apply<sizeof...(T_results)>([&, this](auto... Is) {
this->assign_select(eigen_expressions((
std::get<Is>(this->results_) + std::get<Is>(expressions.exprs_))...));
});
}
};
/**
* Deduces types for constructing \c results_cl object.
* @tparam T_results types of results
* @param results results that will be calculated in same kernel.
*/
template <typename... T_results, require_all_eigen_t<T_results...>* = nullptr>
eigen_results_<T_results...> eigen_results(T_results&&... results) {
return eigen_results_<T_results...>(std::forward<T_results>(results)...);
}
} // namespace math
} // namespace stan
#endif
|
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/control_flow_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/public/tensor.h"
namespace tensorflow {
// A switch op has two inputs and two outputs. It forwards the value of
// Input:0 to the output specified by input:1. Input:1 is a boolean tensor.
// Input:0 is forwarded to output:0 if input:1 is false, otherwise to
// output:1.
class SwitchOp : public OpKernel {
public:
explicit SwitchOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& outputPorts = context->input(1);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(outputPorts.shape()),
errors::InvalidArgument("The second input must be a scalar, "
"but it has shape ",
outputPorts.shape().ShortDebugString()));
bool pred = outputPorts.scalar<bool>()();
int port = (pred) ? 1 : 0;
if (IsRefType(context->input_dtype(0))) {
context->forward_ref_input_to_ref_output(0, port);
} else {
context->set_output(port, context->input(0));
}
}
bool IsExpensive() override { return false; }
~SwitchOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(SwitchOp);
};
#define REGISTER_CPU_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("Switch") \
.Device(DEVICE_CPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_CPU_REF_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("RefSwitch") \
.Device(DEVICE_CPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_GPU_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("Switch") \
.Device(DEVICE_GPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_GPU_REF_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("RefSwitch") \
.Device(DEVICE_GPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
TF_CALL_ALL_TYPES(REGISTER_CPU_SWITCH);
TF_CALL_ALL_TYPES(REGISTER_CPU_REF_SWITCH);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_SWITCH);
REGISTER_GPU_SWITCH(int64);
REGISTER_GPU_SWITCH(bool);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_REF_SWITCH);
REGISTER_GPU_REF_SWITCH(int32);
REGISTER_GPU_REF_SWITCH(int64);
REGISTER_GPU_REF_SWITCH(bool);
#undef REGISTER_CPU_SWITCH
#undef REGISTER_CPU_REF_SWITCH
#undef REGISTER_GPU_SWITCH
#undef REGISTER_GPU_REF_SWITCH
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Switch")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("pred")
.HostMemory("output_false")
.HostMemory("output_true")
.TypeConstraint<int32>("T"),
SwitchOp);
class RefSelectOp : public OpKernel {
public:
explicit RefSelectOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("N", &num_ref_inputs_));
}
void Compute(OpKernelContext* context) override {
const Tensor& index_tensor = context->input(0);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(index_tensor.shape()),
errors::InvalidArgument("Index must be a scalar, "
"but it has shape ",
index_tensor.shape().ShortDebugString()));
int32 index = index_tensor.scalar<int32>()();
OP_REQUIRES(context, index >= 0 && index < num_ref_inputs_,
errors::InvalidArgument("Index must be in the range [0, ",
num_ref_inputs_, ") but got ", index));
context->forward_ref_input_to_ref_output(index + 1, 0);
}
bool IsExpensive() override { return false; }
~RefSelectOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(RefSelectOp);
private:
int num_ref_inputs_;
};
#define REGISTER_CPU_REF_SELECT(type) \
REGISTER_KERNEL_BUILDER(Name("RefSelect") \
.Device(DEVICE_CPU) \
.HostMemory("index") \
.TypeConstraint<type>("T"), \
RefSelectOp)
TF_CALL_ALL_TYPES(REGISTER_CPU_REF_SELECT);
#undef REGISTER_CPU_REF_SWITCH
// A merge op has n inputs and two outputs. It forwards the value of the
// first input that becomes available to its first output, and the
// index of the first input to its second output.
class MergeOp : public OpKernel {
public:
explicit MergeOp(OpKernelConstruction* context) : OpKernel(context) {
const DataType dt = context->input_type(0);
const int num_in = context->num_inputs();
OP_REQUIRES_OK(context, context->MatchSignature(DataTypeVector(num_in, dt),
{dt, DT_INT32}));
}
void Compute(OpKernelContext* context) override {
bool input_seen = false;
for (int i = 0; i < context->num_inputs(); ++i) {
if (context->has_input(i)) {
if (input_seen) {
context->SetStatus(errors::Internal(
"Merge can not have more than one valid input."));
return;
}
input_seen = true;
context->set_output(0, context->input(i));
Tensor* value_index = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape({}),
&value_index));
value_index->scalar<int32>()() = i;
}
}
}
bool IsExpensive() override { return false; }
~MergeOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(MergeOp);
};
REGISTER_KERNEL_BUILDER(Name("Merge").Device(DEVICE_CPU), MergeOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Merge") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.HostMemory("value_index"), \
MergeOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Merge")
.Device(DEVICE_GPU)
.HostMemory("inputs")
.HostMemory("output")
.HostMemory("value_index")
.TypeConstraint<int32>("T"),
MergeOp);
// An enter op has one input and one output. It creates or finds
// the child frame that is uniquely identified by the frame_name,
// and makes its input available to the child frame.
class EnterOp : public OpKernel {
public:
explicit EnterOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
if (IsRefType(context->input_dtype(0))) {
context->forward_ref_input_to_ref_output(0, 0);
} else {
context->set_output(0, context->input(0));
}
}
bool IsExpensive() override { return false; }
~EnterOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(EnterOp);
};
REGISTER_KERNEL_BUILDER(Name("Enter").Device(DEVICE_CPU), EnterOp);
REGISTER_KERNEL_BUILDER(Name("RefEnter").Device(DEVICE_CPU), EnterOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Enter").Device(DEVICE_GPU).TypeConstraint<type>("T"), EnterOp);
#define REGISTER_GPU_REF_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("RefEnter").Device(DEVICE_GPU).TypeConstraint<type>("T"), EnterOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_NUMBER_TYPES(REGISTER_GPU_REF_KERNEL);
#undef REGISTER_GPU_KERNEL
#undef REGISTER_GPU_REF_KERNEL
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Enter")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("output")
.TypeConstraint<int32>("T"),
EnterOp);
// Special GPU kernels for string.
REGISTER_KERNEL_BUILDER(Name("Enter")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("output")
.TypeConstraint<string>("T"),
EnterOp);
REGISTER_KERNEL_BUILDER(Name("RefEnter")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("output")
.TypeConstraint<string>("T"),
EnterOp);
// An exit op has one input and one output. It exits the current
// frame to its parent frame, and makes its input available to the
// parent frame.
class ExitOp : public OpKernel {
public:
explicit ExitOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~ExitOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(ExitOp);
};
REGISTER_KERNEL_BUILDER(Name("Exit").Device(DEVICE_CPU), ExitOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Exit").Device(DEVICE_GPU).TypeConstraint<type>("T"), ExitOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Exit")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("output")
.TypeConstraint<int32>("T"),
ExitOp);
// A next_iteration op has one input and one output. It makes its input
// available to the next iteration.
class NextIterationOp : public OpKernel {
public:
explicit NextIterationOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~NextIterationOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(NextIterationOp);
};
REGISTER_KERNEL_BUILDER(Name("NextIteration").Device(DEVICE_CPU),
NextIterationOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("NextIteration").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
NextIterationOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("NextIteration")
.Device(DEVICE_GPU)
.HostMemory("data")
.HostMemory("output")
.TypeConstraint<int32>("T"),
NextIterationOp);
// A LoopCond op has one input and one output. The input is a boolean
// scalar representing the taken branches of the "pivot" Switch that
// determines loop termination. As a contract, any high-level front-end
// should always use port '0' of the "pivot" switches for loop exit.
class LoopCondOp : public OpKernel {
public:
explicit LoopCondOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~LoopCondOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(LoopCondOp);
};
REGISTER_KERNEL_BUILDER(Name("LoopCond").Device(DEVICE_CPU), LoopCondOp);
REGISTER_KERNEL_BUILDER(Name("LoopCond")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output"),
LoopCondOp);
// ControlTrigger kernels
REGISTER_KERNEL_BUILDER(Name("ControlTrigger").Device(DEVICE_CPU),
ControlTriggerOp);
REGISTER_KERNEL_BUILDER(Name("ControlTrigger").Device(DEVICE_GPU),
ControlTriggerOp);
} // namespace tensorflow
Clean up GPU kernel registrations for control flow ops.
Change: 112492676
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/control_flow_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/public/tensor.h"
namespace tensorflow {
// A switch op has two inputs and two outputs. It forwards the value of
// Input:0 to the output specified by input:1. Input:1 is a boolean tensor.
// Input:0 is forwarded to output:0 if input:1 is false, otherwise to
// output:1.
class SwitchOp : public OpKernel {
public:
explicit SwitchOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& outputPorts = context->input(1);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(outputPorts.shape()),
errors::InvalidArgument("The second input must be a scalar, "
"but it has shape ",
outputPorts.shape().ShortDebugString()));
bool pred = outputPorts.scalar<bool>()();
int port = (pred) ? 1 : 0;
if (IsRefType(context->input_dtype(0))) {
context->forward_ref_input_to_ref_output(0, port);
} else {
context->set_output(port, context->input(0));
}
}
bool IsExpensive() override { return false; }
~SwitchOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(SwitchOp);
};
#define REGISTER_CPU_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("Switch") \
.Device(DEVICE_CPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_CPU_REF_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("RefSwitch") \
.Device(DEVICE_CPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_GPU_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("Switch") \
.Device(DEVICE_GPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_GPU_REF_SWITCH(type) \
REGISTER_KERNEL_BUILDER(Name("RefSwitch") \
.Device(DEVICE_GPU) \
.HostMemory("pred") \
.TypeConstraint<type>("T"), \
SwitchOp)
TF_CALL_ALL_TYPES(REGISTER_CPU_SWITCH);
TF_CALL_ALL_TYPES(REGISTER_CPU_REF_SWITCH);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_SWITCH);
REGISTER_GPU_SWITCH(bool);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_REF_SWITCH);
REGISTER_GPU_REF_SWITCH(bool);
#undef REGISTER_CPU_SWITCH
#undef REGISTER_CPU_REF_SWITCH
#undef REGISTER_GPU_SWITCH
#undef REGISTER_GPU_REF_SWITCH
// Special GPU kernels for int32 and string.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Switch") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("pred") \
.HostMemory("output_false") \
.HostMemory("output_true") \
.TypeConstraint<type>("T"), \
SwitchOp)
#define REGISTER_GPU_HOST_REF_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("RefSwitch") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("pred") \
.HostMemory("output_false") \
.HostMemory("output_true") \
.TypeConstraint<type>("T"), \
SwitchOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_REF_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(string);
REGISTER_GPU_HOST_REF_KERNEL(string);
#undef REGISTER_GPU_HOST_KERNEL
#undef REGISTER_GPU_HOST_REF_KERNEL
class RefSelectOp : public OpKernel {
public:
explicit RefSelectOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("N", &num_ref_inputs_));
}
void Compute(OpKernelContext* context) override {
const Tensor& index_tensor = context->input(0);
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(index_tensor.shape()),
errors::InvalidArgument("Index must be a scalar, "
"but it has shape ",
index_tensor.shape().ShortDebugString()));
int32 index = index_tensor.scalar<int32>()();
OP_REQUIRES(context, index >= 0 && index < num_ref_inputs_,
errors::InvalidArgument("Index must be in the range [0, ",
num_ref_inputs_, ") but got ", index));
context->forward_ref_input_to_ref_output(index + 1, 0);
}
bool IsExpensive() override { return false; }
~RefSelectOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(RefSelectOp);
private:
int num_ref_inputs_;
};
#define REGISTER_CPU_REF_SELECT(type) \
REGISTER_KERNEL_BUILDER(Name("RefSelect") \
.Device(DEVICE_CPU) \
.HostMemory("index") \
.TypeConstraint<type>("T"), \
RefSelectOp)
TF_CALL_ALL_TYPES(REGISTER_CPU_REF_SELECT);
#undef REGISTER_CPU_REF_SWITCH
// A merge op has n inputs and two outputs. It forwards the value of the
// first input that becomes available to its first output, and the
// index of the first input to its second output.
class MergeOp : public OpKernel {
public:
explicit MergeOp(OpKernelConstruction* context) : OpKernel(context) {
const DataType dt = context->input_type(0);
const int num_in = context->num_inputs();
OP_REQUIRES_OK(context, context->MatchSignature(DataTypeVector(num_in, dt),
{dt, DT_INT32}));
}
void Compute(OpKernelContext* context) override {
bool input_seen = false;
for (int i = 0; i < context->num_inputs(); ++i) {
if (context->has_input(i)) {
if (input_seen) {
context->SetStatus(errors::Internal(
"Merge can not have more than one valid input."));
return;
}
input_seen = true;
context->set_output(0, context->input(i));
Tensor* value_index = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape({}),
&value_index));
value_index->scalar<int32>()() = i;
}
}
}
bool IsExpensive() override { return false; }
~MergeOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(MergeOp);
};
REGISTER_KERNEL_BUILDER(Name("Merge").Device(DEVICE_CPU), MergeOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Merge") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.HostMemory("value_index"), \
MergeOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and string.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Merge") \
.Device(DEVICE_GPU) \
.HostMemory("inputs") \
.HostMemory("output") \
.HostMemory("value_index") \
.TypeConstraint<type>("T"), \
MergeOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(string);
#undef REGISTER_GPU_HOST_KERNEL
// An enter op has one input and one output. It creates or finds
// the child frame that is uniquely identified by the frame_name,
// and makes its input available to the child frame.
class EnterOp : public OpKernel {
public:
explicit EnterOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
if (IsRefType(context->input_dtype(0))) {
context->forward_ref_input_to_ref_output(0, 0);
} else {
context->set_output(0, context->input(0));
}
}
bool IsExpensive() override { return false; }
~EnterOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(EnterOp);
};
REGISTER_KERNEL_BUILDER(Name("Enter").Device(DEVICE_CPU), EnterOp);
REGISTER_KERNEL_BUILDER(Name("RefEnter").Device(DEVICE_CPU), EnterOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Enter").Device(DEVICE_GPU).TypeConstraint<type>("T"), EnterOp)
#define REGISTER_GPU_REF_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("RefEnter").Device(DEVICE_GPU).TypeConstraint<type>("T"), EnterOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_REF_KERNEL);
REGISTER_GPU_KERNEL(bool);
REGISTER_GPU_REF_KERNEL(bool);
#undef REGISTER_GPU_KERNEL
#undef REGISTER_GPU_REF_KERNEL
// Special GPU kernels for int32 and string.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Enter") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
EnterOp)
#define REGISTER_GPU_HOST_REF_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("RefEnter") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
EnterOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_REF_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(string);
REGISTER_GPU_HOST_REF_KERNEL(string);
#undef REGISTER_GPU_HOST_KERNEL
#undef REGISTER_GPU_HOST_REF_KERNEL
// An exit op has one input and one output. It exits the current
// frame to its parent frame, and makes its input available to the
// parent frame.
class ExitOp : public OpKernel {
public:
explicit ExitOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~ExitOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(ExitOp);
};
REGISTER_KERNEL_BUILDER(Name("Exit").Device(DEVICE_CPU), ExitOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Exit").Device(DEVICE_GPU).TypeConstraint<type>("T"), ExitOp);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and string.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("Exit") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
ExitOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(string);
#undef REGISTER_GPU_HOST_KERNEL
// A next_iteration op has one input and one output. It makes its input
// available to the next iteration.
class NextIterationOp : public OpKernel {
public:
explicit NextIterationOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~NextIterationOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(NextIterationOp);
};
REGISTER_KERNEL_BUILDER(Name("NextIteration").Device(DEVICE_CPU),
NextIterationOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("NextIteration").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
NextIterationOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and string.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("NextIteration") \
.Device(DEVICE_GPU) \
.HostMemory("data") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
NextIterationOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(string);
#undef REGISTER_GPU_HOST_KERNEL
// A LoopCond op has one input and one output. The input is a boolean
// scalar representing the taken branches of the "pivot" Switch that
// determines loop termination. As a contract, any high-level front-end
// should always use port '0' of the "pivot" switches for loop exit.
class LoopCondOp : public OpKernel {
public:
explicit LoopCondOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
context->set_output(0, context->input(0));
}
bool IsExpensive() override { return false; }
~LoopCondOp() override {}
TF_DISALLOW_COPY_AND_ASSIGN(LoopCondOp);
};
REGISTER_KERNEL_BUILDER(Name("LoopCond").Device(DEVICE_CPU), LoopCondOp);
REGISTER_KERNEL_BUILDER(Name("LoopCond")
.Device(DEVICE_GPU)
.HostMemory("input")
.HostMemory("output"),
LoopCondOp);
// ControlTrigger kernels
REGISTER_KERNEL_BUILDER(Name("ControlTrigger").Device(DEVICE_CPU),
ControlTriggerOp);
REGISTER_KERNEL_BUILDER(Name("ControlTrigger").Device(DEVICE_GPU),
ControlTriggerOp);
} // namespace tensorflow
|
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
struct X1 {
X1();
};
struct X2 {
X2();
~X2();
};
void vararg(...);
void f(X1 x1, X2 x2) {
vararg(x1); // okay
vararg(x2); // expected-error{{cannot pass object of non-trivial type 'X2' through variadic function; call will abort at runtime}}
}
namespace PR11131 {
struct S;
S &getS();
void f(...);
void g() {
(void)sizeof(f(getS()));
}
}
Test that we correctly deal with multiple copy constructors when detecting
non-trivial special members for varargs calls.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@168476 91177308-0d34-0410-b5e6-96231b3b80d8
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
struct X1 {
X1();
};
struct X2 {
X2();
~X2();
};
struct X3 {
X3(const X3&) = default;
};
struct X4 {
X4(const X4&) = default;
X4(X4&);
};
void vararg(...);
void f(X1 x1, X2 x2, X3 x3, X4 x4) {
vararg(x1); // OK
vararg(x2); // expected-error{{cannot pass object of non-trivial type 'X2' through variadic function; call will abort at runtime}}
vararg(x3); // OK
vararg(x4); // expected-error{{cannot pass object of non-trivial type 'X4' through variadic function; call will abort at runtime}}
}
namespace PR11131 {
struct S;
S &getS();
void f(...);
void g() {
(void)sizeof(f(getS()));
}
}
|
// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone -triple %itanium_abi_triple %s -o - | FileCheck %s
// Not trivially copyable because of the explicit destructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "RefDtor",{{.*}}flags: DIFlagTypePassByReference
struct RefDtor {
int i;
~RefDtor() {}
} refDtor;
// Not trivially copyable because of the explicit copy constructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "RefCopy",{{.*}}flags: DIFlagTypePassByReference
struct RefCopy {
int i;
RefCopy() = default;
RefCopy(RefCopy &Copy) {}
} refCopy;
// Not trivially copyable because of the explicit move constructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "RefMove",{{.*}}flags: DIFlagTypePassByReference
struct RefMove {
int i;
RefMove() = default;
RefMove(RefMove &&Move) {}
} refMove;
// POD-like type even though it defines a destructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Podlike", {{.*}}flags: DIFlagTypePassByValue
struct Podlike {
int i;
Podlike() = default;
Podlike(Podlike &&Move) = default;
~Podlike() = default;
} podlike;
// This is a POD type.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Pod",{{.*}}flags: DIFlagTypePassByValue
struct Pod {
int i;
} pod;
// This is definitely not a POD type.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Complex",{{.*}}flags: DIFlagTypePassByReference
struct Complex {
Complex() {}
Complex(Complex &Copy) : i(Copy.i) {};
int i;
} complex;
Remove redundant test
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@321846 91177308-0d34-0410-b5e6-96231b3b80d8
// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone -triple %itanium_abi_triple %s -o - | FileCheck %s
// Not trivially copyable because of the explicit destructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "RefDtor",{{.*}}flags: DIFlagTypePassByReference
struct RefDtor {
int i;
~RefDtor() {}
} refDtor;
// Not trivially copyable because of the explicit copy constructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "RefCopy",{{.*}}flags: DIFlagTypePassByReference
struct RefCopy {
int i;
RefCopy() = default;
RefCopy(RefCopy &Copy) {}
} refCopy;
// POD-like type even though it defines a destructor.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Podlike", {{.*}}flags: DIFlagTypePassByValue
struct Podlike {
int i;
Podlike() = default;
Podlike(Podlike &&Move) = default;
~Podlike() = default;
} podlike;
// This is a POD type.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Pod",{{.*}}flags: DIFlagTypePassByValue
struct Pod {
int i;
} pod;
// This is definitely not a POD type.
// CHECK-DAG: !DICompositeType({{.*}}, name: "Complex",{{.*}}flags: DIFlagTypePassByReference
struct Complex {
Complex() {}
Complex(Complex &Copy) : i(Copy.i) {};
int i;
} complex;
|
#include "orwell/game/Robot.hpp"
#include "orwell/game/Team.hpp"
#include <iostream>
#include <unistd.h>
#include <cstdint>
#include <log4cxx/ndc.h>
#include "orwell/support/GlobalLogger.hpp"
#include "orwell/game/Item.hpp"
#include "orwell/game/Ruleset.hpp"
#include "orwell/game/Game.hpp"
#include "orwell/game/Robot.hpp"
#include "orwell/game/item/Flag.hpp"
#include "orwell/game/item/FlagDetector.hpp"
#include "Common.hpp"
using ::testing::_;
class TestOrwellGameItemFlagDetector : public ::testing::Test
{
protected:
TestOrwellGameItemFlagDetector()
: m_type("flag")
, m_name("FLAG")
, m_colourCode(12)
//, m_timeToCapture(boost::posix_time::milliseconds(30))
//, m_pointsOnCapture(1)
//, m_flag(m_name, m_colourCode, m_timeToCapture, m_pointsOnCapture)
, m_teamName("Team Name")
, m_robotName("Robot Name")
, m_robotId("robot_id")
, m_videoPort(42)
, m_commandPort(43)
, m_team(m_teamName)
, m_robot(std::make_shared< orwell::game::Robot >(
m_fakeSystemProxy,
m_robotName,
m_robotId,
m_team,
m_videoPort,
m_commandPort))
, m_flagDetector(
m_contactHandler,
m_robot)
{
}
virtual void SetUp()
{
orwell::game::Item::CreateItem(
m_type,
m_name,
m_rfids,
m_colourCode,
m_ruleset);
}
virtual void TearDown()
{
}
std::string m_type;
std::string const m_name;
std::set< std::string > m_rfids;
int32_t const m_colourCode;
orwell::game::Ruleset m_ruleset;
//orwell::game::item::Flag m_flag;
FakeSystemProxy m_fakeSystemProxy;
std::string const m_teamName;
std::string const m_robotName;
std::string const m_robotId;
uint16_t const m_videoPort;
uint16_t const m_commandPort;
orwell::game::Team m_team;
std::shared_ptr< orwell::game::Robot > m_robot;
FakeContactHandler m_contactHandler;
orwell::game::item::FlagDetector m_flagDetector;
};
TEST_F(TestOrwellGameItemFlagDetector, Frontier)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(0);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(0);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
}
TEST_F(TestOrwellGameItemFlagDetector, Frontier_Colour_Frontier_Outside)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(1);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(1);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
m_colourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kNoneColourCode,
boost::posix_time::microsec_clock::local_time());
}
TEST_F(TestOrwellGameItemFlagDetector, Frontier_Colour_Frontier)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(1);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(0);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
m_colourCode,
boost::posix_time::microsec_clock::local_time());
}
int main(int argc, char ** argv)
{
orwell::support::GlobalLogger::Create("test_orwell_game_item_FlagDetector", "test_orwell_game_item_FlagDetector.log", true);
log4cxx::NDC ndc("test_orwell_game_item_FlagDetector");
ORWELL_LOG_INFO("Test starts\n");
::testing::InitGoogleTest(&argc, argv);
int aResult = RUN_ALL_TESTS();
orwell::support::GlobalLogger::Clear();
return aResult;
}
Clean-up
#include "orwell/game/Robot.hpp"
#include "orwell/game/Team.hpp"
#include <iostream>
#include <unistd.h>
#include <cstdint>
#include <log4cxx/ndc.h>
#include "orwell/support/GlobalLogger.hpp"
#include "orwell/game/Item.hpp"
#include "orwell/game/Ruleset.hpp"
#include "orwell/game/Game.hpp"
#include "orwell/game/Robot.hpp"
#include "orwell/game/item/Flag.hpp"
#include "orwell/game/item/FlagDetector.hpp"
#include "Common.hpp"
using ::testing::_;
class TestOrwellGameItemFlagDetector : public ::testing::Test
{
protected:
TestOrwellGameItemFlagDetector()
: m_type("flag")
, m_name("FLAG")
, m_colourCode(12)
, m_teamName("Team Name")
, m_robotName("Robot Name")
, m_robotId("robot_id")
, m_videoPort(42)
, m_commandPort(43)
, m_team(m_teamName)
, m_robot(std::make_shared< orwell::game::Robot >(
m_fakeSystemProxy,
m_robotName,
m_robotId,
m_team,
m_videoPort,
m_commandPort))
, m_flagDetector(
m_contactHandler,
m_robot)
{
}
virtual void SetUp()
{
orwell::game::Item::CreateItem(
m_type,
m_name,
m_rfids,
m_colourCode,
m_ruleset);
}
virtual void TearDown()
{
}
std::string m_type;
std::string const m_name;
std::set< std::string > m_rfids;
int32_t const m_colourCode;
orwell::game::Ruleset m_ruleset;
FakeSystemProxy m_fakeSystemProxy;
std::string const m_teamName;
std::string const m_robotName;
std::string const m_robotId;
uint16_t const m_videoPort;
uint16_t const m_commandPort;
orwell::game::Team m_team;
std::shared_ptr< orwell::game::Robot > m_robot;
FakeContactHandler m_contactHandler;
orwell::game::item::FlagDetector m_flagDetector;
};
TEST_F(TestOrwellGameItemFlagDetector, Frontier)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(0);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(0);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
}
TEST_F(TestOrwellGameItemFlagDetector, Frontier_Colour_Frontier_Outside)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(1);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(1);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
m_colourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kNoneColourCode,
boost::posix_time::microsec_clock::local_time());
}
TEST_F(TestOrwellGameItemFlagDetector, Frontier_Colour_Frontier)
{
EXPECT_CALL(m_contactHandler, robotIsInContactWith(_, _)).Times(1);
EXPECT_CALL(m_contactHandler, robotDropsContactWith(_, _)).Times(0);
m_flagDetector.setColour(
orwell::game::item::FlagDetector::kFrontierColourCode,
boost::posix_time::microsec_clock::local_time());
m_flagDetector.setColour(
m_colourCode,
boost::posix_time::microsec_clock::local_time());
}
int main(int argc, char ** argv)
{
std::string const aName = "test_orwell_game_item_FlagDetector";
orwell::support::GlobalLogger::Create(aName, aName, true);
log4cxx::NDC ndc(aName);
ORWELL_LOG_INFO("Test starts\n");
::testing::InitGoogleTest(&argc, argv);
int aResult = RUN_ALL_TESTS();
orwell::support::GlobalLogger::Clear();
return aResult;
}
|
#include <stan/math/mix/scal.hpp>
#include <test/unit/math/rev/scal/fun/util.hpp>
#include <gtest/gtest.h>
#include <vector>
std::vector<double> test_fun(double y) {
using stan::math::std_normal_lpdf;
using stan::math::var;
var y_var = y;
std::vector<var> x;
x.push_back(y_var);
var logp = std_normal_lpdf<false>(y_var);
std::vector<double> grad;
logp.grad(x, grad);
return grad;
}
TEST(ProbAgradDistributionsStdNormal, derivatives) {
using stan::math::fvar;
using stan::math::std_normal_lpdf;
std::vector<double> grad = test_fun(0);
fvar<double> lp = std_normal_lpdf<false>(0);
EXPECT_FLOAT_EQ(grad[2], lp.tangent());
fvar<fvar<double>> y(1.0);
fvar<double> x(1.0, 2.0);
EXPECT_NO_THROW(std_normal_lpdf(y));
EXPECT_FLOAT_EQ(std_normal_lpdf(x).val_, -1.418938533204672669541);
EXPECT_FLOAT_EQ(std_normal_lpdf(x).d_, -2);
}
TEST(ProbAgradDistributionsStdNormal, FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::std_normal_lpdf;
using stan::math::var;
fvar<var> y_(2, 1);
fvar<var> logp = std_normal_lpdf(y_);
AVEC y = createAVEC(y_.val_);
VEC g;
logp.val_.grad(y, g);
EXPECT_FLOAT_EQ(-2, g[0]);
}
Fix test
#include <stan/math/mix/scal.hpp>
#include <test/unit/math/rev/scal/fun/util.hpp>
#include <gtest/gtest.h>
#include <vector>
std::vector<double> test_fun(double y) {
using stan::math::std_normal_lpdf;
using stan::math::var;
var y_var = y;
std::vector<var> x;
x.push_back(y_var);
var logp = std_normal_lpdf<false>(y_var);
std::vector<double> grad;
logp.grad(x, grad);
return grad;
}
TEST(ProbAgradDistributionsStdNormal, derivatives) {
using stan::math::fvar;
using stan::math::std_normal_lpdf;
std::vector<double> grad = test_fun(0);
fvar<double> lp = std_normal_lpdf<false>(fvar<double>(0));
EXPECT_FLOAT_EQ(grad[0], lp.tangent());
fvar<fvar<double>> y(1.0);
fvar<double> x(1.0, 2.0);
EXPECT_NO_THROW(std_normal_lpdf(y));
EXPECT_FLOAT_EQ(std_normal_lpdf(x).val_, -1.418938533204672669541);
EXPECT_FLOAT_EQ(std_normal_lpdf(x).d_, -2);
}
TEST(ProbAgradDistributionsStdNormal, FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::std_normal_lpdf;
using stan::math::var;
fvar<var> y_(2, 1);
fvar<var> logp = std_normal_lpdf(y_);
AVEC y = createAVEC(y_.val_);
VEC g;
logp.val_.grad(y, g);
EXPECT_FLOAT_EQ(-2, g[0]);
}
|
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_offlineapplet.h"
#include <DcpWidgetTypes>
#include <DcpWidget>
#include <MMessageBox>
#include <MDialog>
#include <MApplication>
#include <MInfoBanner>
#include "offlineapplet.h"
#include "offlinebrief.h"
#ifdef HAVE_QMSYSTEM
# include "qmdevicemode_stub.h"
#endif
#include "signalchecker.h"
#define DEBUG
#include "../../src/debug.h"
static const char *signalValuesChanged = SIGNAL (valuesChanged ());
int argc = 1;
char *argv[] = {
(char *) "./ut_offlineapplet",
NULL };
/******************************************************************************
* Stub for MMessageBox
*/
static QString mmessageBoxText;
static int mmessageBoxApereance;
MMessageBox::MMessageBox (
const QString &title,
const QString &text,
M::StandardButtons buttons)
{
SYS_DEBUG ("");
Q_UNUSED (title);
Q_UNUSED (buttons);
mmessageBoxText = text;
}
int
MDialog::result () const
{
return MDialog::Accepted;
}
void
MDialog::appear (MSceneWindow::DeletionPolicy policy)
{
Q_UNUSED (policy);
mmessageBoxApereance = true;
}
/******************************************************************************
* Stub for MNotification
*/
static QString mbannerSubtitle;
MInfoBanner::MInfoBanner (BannerType type)
{
Q_UNUSED (type);
}
MInfoBanner::~MInfoBanner ()
{
}
void
MInfoBanner::setBodyText (const QString &text)
{
mbannerSubtitle = text;
}
/******************************************************************************
* Ut_offlineApplet implementation.
*/
void
Ut_OfflineApplet::init()
{
mmessageBoxText = "";
mmessageBoxApereance = false;
mbannerSubtitle = "";
}
void
Ut_OfflineApplet::cleanup()
{
}
void
Ut_OfflineApplet::initTestCase()
{
m_App = new MApplication(argc, argv);
m_App->setQuitOnLastWindowClosed (false);
m_Applet = new OfflineApplet;
}
void
Ut_OfflineApplet::cleanupTestCase()
{
delete m_Applet;
m_Applet = 0;
m_App->deleteLater ();
m_App = 0;
}
void
Ut_OfflineApplet::testTitle ()
{
QString title = m_Applet->title();
QVERIFY (title.isEmpty());
}
void
Ut_OfflineApplet::testMenu ()
{
QVector<MAction *> menu = m_Applet->viewMenuItems();
QVERIFY (menu.isEmpty());
}
void
Ut_OfflineApplet::testConstructWidget ()
{
DcpWidget* widget = m_Applet->constructWidget(1);
QVERIFY (!widget);
}
void
Ut_OfflineApplet::testBriefConstruct ()
{
#ifdef HAVE_QMSYSTEM
DcpBrief* widget;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
widget = m_Applet->constructBrief(1);
QVERIFY (widget);
QCOMPARE (int(widget->widgetTypeID()), int(DcpWidgetType::Button));
delete widget;
#endif
}
void
Ut_OfflineApplet::testCurrentText ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief brief;
brief.m_LastMode = MeeGo::QmDeviceMode::Normal;
QCOMPARE (brief.currentText(), qtTrId("qtn_offl_activate"));
brief.m_LastMode = MeeGo::QmDeviceMode::Flight;
QCOMPARE (brief.currentText(), qtTrId("qtn_offl_deactivate"));
/*
* Brief never should be empty!
*
brief.m_LastMode = MeeGo::QmDeviceMode::Error;
QVERIFY (brief.currentText().isEmpty());
*/
brief.m_LastMode = MeeGo::QmDeviceMode::Error;
QVERIFY (brief.currentText().isEmpty() == false);
#endif
}
void
Ut_OfflineApplet::testBriefInit ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
delete brief;
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Flight);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
delete brief;
#endif
}
void
Ut_OfflineApplet::testBriefValueText ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Flight);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
m_sChecker.check();
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Normal);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
delete brief;
#endif
}
void
Ut_OfflineApplet::testBriefSetToggle ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
// This should not change the text
brief->setToggle(true);
QCOMPARE (mbannerSubtitle, QString ("<p>") + qtTrId("qtn_offl_entering") + "</p>");
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Flight);
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Flight);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
m_sChecker.check();
// This should not change the text nor the QmDeviceMode
brief->setToggle(true);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Flight);
delete brief;
#endif
}
void
Ut_OfflineApplet::testProcessDialogResult()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Flight);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
brief->setToggle(true);
QCOMPARE(mmessageBoxText, qtTrId("qtn_offl_exiting"));
QVERIFY(mmessageBoxApereance);
brief->processDialogResult();
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Normal);
delete brief;
#endif
}
QTEST_APPLESS_MAIN(Ut_OfflineApplet)
Fixes: failing testcase: ut_offlineapplet
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_offlineapplet.h"
#include <DcpWidgetTypes>
#include <DcpWidget>
#include <MMessageBox>
#include <MDialog>
#include <MApplication>
#include <MBanner>
#include "offlineapplet.h"
#include "offlinebrief.h"
#ifdef HAVE_QMSYSTEM
# include "qmdevicemode_stub.h"
#endif
#include "signalchecker.h"
#define DEBUG
#include "../../src/debug.h"
static const char *signalValuesChanged = SIGNAL (valuesChanged ());
int argc = 1;
char *argv[] = {
(char *) "./ut_offlineapplet",
NULL };
/******************************************************************************
* Stub for MMessageBox
*/
static QString mmessageBoxText;
static int mmessageBoxApereance;
MMessageBox::MMessageBox (
const QString &title,
const QString &text,
M::StandardButtons buttons)
{
SYS_DEBUG ("");
Q_UNUSED (title);
Q_UNUSED (buttons);
mmessageBoxText = text;
}
int
MDialog::result () const
{
return MDialog::Accepted;
}
void
MDialog::appear (MSceneWindow::DeletionPolicy policy)
{
Q_UNUSED (policy);
mmessageBoxApereance = true;
}
/******************************************************************************
* Stub for MNotification
*/
static QString mbannerSubtitle;
MBanner::MBanner ()
{
}
MBanner::~MBanner ()
{
}
void
MBanner::setTitle (const QString &text)
{
mbannerSubtitle = text;
}
/******************************************************************************
* Ut_offlineApplet implementation.
*/
void
Ut_OfflineApplet::init()
{
mmessageBoxText = "";
mmessageBoxApereance = false;
mbannerSubtitle = "";
}
void
Ut_OfflineApplet::cleanup()
{
}
void
Ut_OfflineApplet::initTestCase()
{
m_App = new MApplication(argc, argv);
m_App->setQuitOnLastWindowClosed (false);
m_Applet = new OfflineApplet;
}
void
Ut_OfflineApplet::cleanupTestCase()
{
delete m_Applet;
m_Applet = 0;
m_App->deleteLater ();
m_App = 0;
}
void
Ut_OfflineApplet::testTitle ()
{
QString title = m_Applet->title();
QVERIFY (title.isEmpty());
}
void
Ut_OfflineApplet::testMenu ()
{
QVector<MAction *> menu = m_Applet->viewMenuItems();
QVERIFY (menu.isEmpty());
}
void
Ut_OfflineApplet::testConstructWidget ()
{
DcpWidget* widget = m_Applet->constructWidget(1);
QVERIFY (!widget);
}
void
Ut_OfflineApplet::testBriefConstruct ()
{
#ifdef HAVE_QMSYSTEM
DcpBrief* widget;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
widget = m_Applet->constructBrief(1);
QVERIFY (widget);
QCOMPARE (int(widget->widgetTypeID()), int(DcpWidgetType::Button));
delete widget;
#endif
}
void
Ut_OfflineApplet::testCurrentText ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief brief;
brief.m_LastMode = MeeGo::QmDeviceMode::Normal;
QCOMPARE (brief.currentText(), qtTrId("qtn_offl_activate"));
brief.m_LastMode = MeeGo::QmDeviceMode::Flight;
QCOMPARE (brief.currentText(), qtTrId("qtn_offl_deactivate"));
/*
* Brief never should be empty!
*
brief.m_LastMode = MeeGo::QmDeviceMode::Error;
QVERIFY (brief.currentText().isEmpty());
*/
brief.m_LastMode = MeeGo::QmDeviceMode::Error;
QVERIFY (brief.currentText().isEmpty() == false);
#endif
}
void
Ut_OfflineApplet::testBriefInit ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
delete brief;
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Flight);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
delete brief;
#endif
}
void
Ut_OfflineApplet::testBriefValueText ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Flight);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
m_sChecker.check();
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Normal);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
delete brief;
#endif
}
void
Ut_OfflineApplet::testBriefSetToggle ()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Normal);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
// This should not change the text
brief->setToggle(true);
QCOMPARE (mbannerSubtitle, qtTrId("qtn_offl_entering"));
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_activate"));
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Flight);
m_sChecker.increaseSigCounter(signalValuesChanged);
brief->devModeChanged(MeeGo::QmDeviceMode::Flight);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
m_sChecker.check();
// This should not change the text nor the QmDeviceMode
brief->setToggle(true);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Flight);
delete brief;
#endif
}
void
Ut_OfflineApplet::testProcessDialogResult()
{
#ifdef HAVE_QMSYSTEM
OfflineBrief *brief;
gQmDeviceModeStub->stubReset ();
gQmDeviceModeStub->stubSetReturnValue<MeeGo::QmDeviceMode::DeviceMode> (
"getMode", MeeGo::QmDeviceMode::Flight);
brief = new OfflineBrief();
QVERIFY (brief);
QCOMPARE (brief->valueText(), qtTrId("qtn_offl_deactivate"));
SignalChecker m_sChecker(brief);
m_sChecker.addSignalChecker(signalValuesChanged);
brief->setToggle(true);
QCOMPARE(mmessageBoxText, qtTrId("qtn_offl_exiting"));
QVERIFY(mmessageBoxApereance);
brief->processDialogResult();
QCOMPARE (gQmDeviceModeStub->stubCallCount("setMode"), 1);
QCOMPARE (gQmDeviceModeStub->stubLastParameters<MeeGo::QmDeviceMode::DeviceMode> (0), MeeGo::QmDeviceMode::Normal);
delete brief;
#endif
}
QTEST_APPLESS_MAIN(Ut_OfflineApplet)
|
/*************************************************************************
*
* 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: ctrltool.cxx,v $
* $Revision: 1.18 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define CTRLTOOL_CXX
#include <string.h>
#ifndef TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <i18npool/mslangid.hxx>
#ifndef _VCL_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <svtools/svtools.hrc>
#include <svtools/svtdata.hxx>
#include <ctrltool.hxx>
// =======================================================================
// Standard Fontgroessen fuer scalierbare Fonts
static long aStdSizeAry[] =
{
60,
70,
80,
90,
100,
105,
110,
120,
130,
140,
150,
160,
180,
200,
220,
240,
260,
280,
320,
360,
400,
440,
480,
540,
600,
660,
720,
800,
880,
960,
0
};
// =======================================================================
// -----------------------------
// - class ImplFontListFonInfo -
// -----------------------------
class ImplFontListFontInfo : public FontInfo
{
friend class FontList;
private:
OutputDevice* mpDevice;
ImplFontListFontInfo* mpNext;
public:
ImplFontListFontInfo( const FontInfo& rInfo,
OutputDevice* pDev ) :
FontInfo( rInfo )
{
mpDevice = pDev;
}
OutputDevice* GetDevice() const { return mpDevice; }
};
// ------------------------------
// - class ImplFontListNameInfo -
// ------------------------------
class ImplFontListNameInfo
{
friend class FontList;
private:
XubString maSearchName;
ImplFontListFontInfo* mpFirst;
USHORT mnType;
ImplFontListNameInfo( const XubString& rSearchName ) :
maSearchName( rSearchName )
{}
const XubString& GetSearchName() const { return maSearchName; }
};
// =======================================================================
static StringCompare ImplCompareFontInfo( ImplFontListFontInfo* pInfo1,
ImplFontListFontInfo* pInfo2 )
{
if ( pInfo1->GetWeight() < pInfo2->GetWeight() )
return COMPARE_LESS;
else if ( pInfo1->GetWeight() > pInfo2->GetWeight() )
return COMPARE_GREATER;
if ( pInfo1->GetItalic() < pInfo2->GetItalic() )
return COMPARE_LESS;
else if ( pInfo1->GetItalic() > pInfo2->GetItalic() )
return COMPARE_GREATER;
return pInfo1->GetStyleName().CompareTo( pInfo2->GetStyleName() );
}
// =======================================================================
static void ImplMakeSearchString( XubString& rStr )
{
rStr.ToLowerAscii();
}
// -----------------------------------------------------------------------
static void ImplMakeSearchStringFromName( XubString& rStr )
{
rStr = rStr.GetToken( 0, ';' );
ImplMakeSearchString( rStr );
}
// -----------------------------------------------------------------------
ImplFontListNameInfo* FontList::ImplFind( const XubString& rSearchName, ULONG* pIndex ) const
{
// Wenn kein Eintrag in der Liste oder der Eintrag groesser ist als
// der Letzte, dann hinten dranhaengen. Wir vergleichen erst mit dem
// letzten Eintrag, da die Liste von VCL auch sortiert zurueckkommt
// und somit die Wahrscheinlichkeit das hinten angehaengt werden muss
// sehr gross ist.
StringCompare eComp;
ULONG nCnt = Count();
if ( !nCnt )
{
if ( pIndex )
*pIndex = LIST_APPEND;
return NULL;
}
else
{
ImplFontListNameInfo* pCmpData = (ImplFontListNameInfo*)List::GetObject( nCnt-1 );
eComp = rSearchName.CompareTo( pCmpData->maSearchName );
if ( eComp == COMPARE_GREATER )
{
if ( pIndex )
*pIndex = LIST_APPEND;
return NULL;
}
else if ( eComp == COMPARE_EQUAL )
return pCmpData;
}
// Fonts in der Liste suchen
ImplFontListNameInfo* pCompareData;
ImplFontListNameInfo* pFoundData = NULL;
ULONG nLow = 0;
ULONG nHigh = nCnt-1;
ULONG nMid;
do
{
nMid = (nLow + nHigh) / 2;
pCompareData = (ImplFontListNameInfo*)List::GetObject( nMid );
eComp = rSearchName.CompareTo( pCompareData->maSearchName );
if ( eComp == COMPARE_LESS )
{
if ( !nMid )
break;
nHigh = nMid-1;
}
else
{
if ( eComp == COMPARE_GREATER )
nLow = nMid + 1;
else
{
pFoundData = pCompareData;
break;
}
}
}
while ( nLow <= nHigh );
if ( pIndex )
{
eComp = rSearchName.CompareTo( pCompareData->maSearchName );
if ( eComp == COMPARE_GREATER )
*pIndex = (nMid+1);
else
*pIndex = nMid;
}
return pFoundData;
}
// -----------------------------------------------------------------------
ImplFontListNameInfo* FontList::ImplFindByName( const XubString& rStr ) const
{
XubString aSearchName = rStr;
ImplMakeSearchStringFromName( aSearchName );
return ImplFind( aSearchName, NULL );
}
// -----------------------------------------------------------------------
void FontList::ImplInsertFonts( OutputDevice* pDevice, BOOL bAll,
BOOL bInsertData )
{
rtl_TextEncoding eSystemEncoding = gsl_getSystemTextEncoding();
USHORT nType;
if ( pDevice->GetOutDevType() != OUTDEV_PRINTER )
nType = FONTLIST_FONTNAMETYPE_SCREEN;
else
nType = FONTLIST_FONTNAMETYPE_PRINTER;
// Alle Fonts vom Device abfragen
int n = pDevice->GetDevFontCount();
USHORT i;
for( i = 0; i < n; i++ )
{
FontInfo aFontInfo = pDevice->GetDevFont( i );
// Wenn keine Raster-Schriften angezeigt werden sollen,
// dann diese ignorieren
if ( !bAll && (aFontInfo.GetType() == TYPE_RASTER) )
continue;
XubString aSearchName = aFontInfo.GetName();
ImplFontListNameInfo* pData;
ULONG nIndex;
ImplMakeSearchString( aSearchName );
pData = ImplFind( aSearchName, &nIndex );
if ( !pData )
{
if ( bInsertData )
{
ImplFontListFontInfo* pNewInfo = new ImplFontListFontInfo( aFontInfo, pDevice );
pData = new ImplFontListNameInfo( aSearchName );
pData->mpFirst = pNewInfo;
pNewInfo->mpNext = NULL;
pData->mnType = 0;
Insert( (void*)pData, nIndex );
}
}
else
{
if ( bInsertData )
{
BOOL bInsert = TRUE;
ImplFontListFontInfo* pPrev = NULL;
ImplFontListFontInfo* pTemp = pData->mpFirst;
ImplFontListFontInfo* pNewInfo = new ImplFontListFontInfo( aFontInfo, pDevice );
while ( pTemp )
{
StringCompare eComp = ImplCompareFontInfo( pNewInfo, pTemp );
if ( (eComp == COMPARE_LESS) || (eComp == COMPARE_EQUAL) )
{
if ( eComp == COMPARE_EQUAL )
{
// Overwrite charset, because charset should match
// with the system charset
if ( (pTemp->GetCharSet() != eSystemEncoding) &&
(pNewInfo->GetCharSet() == eSystemEncoding) )
{
ImplFontListFontInfo* pTemp2 = pTemp->mpNext;
*((FontInfo*)pTemp) = *((FontInfo*)pNewInfo);
pTemp->mpNext = pTemp2;
}
delete pNewInfo;
bInsert = FALSE;
}
break;
}
pPrev = pTemp;
pTemp = pTemp->mpNext;
}
if ( bInsert )
{
pNewInfo->mpNext = pTemp;
if ( pPrev )
pPrev->mpNext = pNewInfo;
else
pData->mpFirst = pNewInfo;
}
}
}
if ( pData )
{
pData->mnType |= nType;
if ( aFontInfo.GetType() != TYPE_RASTER )
pData->mnType |= FONTLIST_FONTNAMETYPE_SCALABLE;
}
}
}
// =======================================================================
FontList::FontList( OutputDevice* pDevice, OutputDevice* pDevice2, BOOL bAll ) :
List( 4096, sal::static_int_cast< USHORT >(pDevice->GetDevFontCount()), 32 )
{
// Variablen initialisieren
mpDev = pDevice;
mpDev2 = pDevice2;
mpSizeAry = NULL;
// Stylenamen festlegen
maLight = XubString( SvtResId( STR_SVT_STYLE_LIGHT ) );
maLightItalic = XubString( SvtResId( STR_SVT_STYLE_LIGHT_ITALIC ) );
maNormal = XubString( SvtResId( STR_SVT_STYLE_NORMAL ) );
maNormalItalic = XubString( SvtResId( STR_SVT_STYLE_NORMAL_ITALIC ) );
maBold = XubString( SvtResId( STR_SVT_STYLE_BOLD ) );
maBoldItalic = XubString( SvtResId( STR_SVT_STYLE_BOLD_ITALIC ) );
maBlack = XubString( SvtResId( STR_SVT_STYLE_BLACK ) );
maBlackItalic = XubString( SvtResId( STR_SVT_STYLE_BLACK_ITALIC ) );
ImplInsertFonts( pDevice, bAll, TRUE );
// Gegebenenfalls muessen wir mit den Bildschirmfonts vergleichen,
// damit dort die eigentlich doppelten auf Equal mappen koennen
BOOL bCompareWindow = FALSE;
if ( !pDevice2 && (pDevice->GetOutDevType() == OUTDEV_PRINTER) )
{
bCompareWindow = TRUE;
pDevice2 = Application::GetDefaultDevice();
}
if ( pDevice2 &&
(pDevice2->GetOutDevType() != pDevice->GetOutDevType()) )
ImplInsertFonts( pDevice2, bAll, !bCompareWindow );
}
// -----------------------------------------------------------------------
FontList::~FontList()
{
// Gegebenenfalls SizeArray loeschen
if ( mpSizeAry )
delete[] mpSizeAry;
// FontInfos loeschen
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)First();
while ( pData )
{
ImplFontListFontInfo* pTemp;
ImplFontListFontInfo* pInfo = pData->mpFirst;
while ( pInfo )
{
pTemp = pInfo->mpNext;
delete pInfo;
pInfo = pTemp;
}
ImplFontListNameInfo* pNext = (ImplFontListNameInfo*)Next();
delete pData;
pData = pNext;
}
}
// -----------------------------------------------------------------------
FontList* FontList::Clone() const
{
FontList* pReturn = new FontList(
mpDev, mpDev2, GetFontNameCount() == mpDev->GetDevFontCount());
return pReturn;
}
// -----------------------------------------------------------------------
const XubString& FontList::GetStyleName( FontWeight eWeight, FontItalic eItalic ) const
{
if ( eWeight > WEIGHT_BOLD )
{
if ( eItalic > ITALIC_NONE )
return maBlackItalic;
else
return maBlack;
}
else if ( eWeight > WEIGHT_MEDIUM )
{
if ( eItalic > ITALIC_NONE )
return maBoldItalic;
else
return maBold;
}
else if ( eWeight > WEIGHT_LIGHT )
{
if ( eItalic > ITALIC_NONE )
return maNormalItalic;
else
return maNormal;
}
else if ( eWeight != WEIGHT_DONTKNOW )
{
if ( eItalic > ITALIC_NONE )
return maLightItalic;
else
return maLight;
}
else
{
if ( eItalic > ITALIC_NONE )
return maNormalItalic;
else
return maNormal;
}
}
// -----------------------------------------------------------------------
XubString FontList::GetStyleName( const FontInfo& rInfo ) const
{
XubString aStyleName = rInfo.GetStyleName();
FontWeight eWeight = rInfo.GetWeight();
FontItalic eItalic = rInfo.GetItalic();
// Nur wenn kein StyleName gesetzt ist, geben wir einen syntetischen
// Namen zurueck
if ( !aStyleName.Len() )
aStyleName = GetStyleName( eWeight, eItalic );
else
{
// Translate StyleName to localized name
XubString aCompareStyleName = aStyleName;
aCompareStyleName.ToLowerAscii();
aCompareStyleName.EraseAllChars( ' ' );
if ( aCompareStyleName.EqualsAscii( "bold" ) )
aStyleName = maBold;
else if ( aCompareStyleName.EqualsAscii( "bolditalic" ) )
aStyleName = maBoldItalic;
else if ( aCompareStyleName.EqualsAscii( "italic" ) )
aStyleName = maNormalItalic;
else if ( aCompareStyleName.EqualsAscii( "standard" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "regular" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "medium" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "light" ) )
aStyleName = maLight;
else if ( aCompareStyleName.EqualsAscii( "lightitalic" ) )
aStyleName = maLightItalic;
else if ( aCompareStyleName.EqualsAscii( "black" ) )
aStyleName = maBlack;
else if ( aCompareStyleName.EqualsAscii( "blackitalic" ) )
aStyleName = maBlackItalic;
// fix up StyleName, because the PS Printer driver from
// W2000 returns wrong StyleNames (e.g. Bold instead of Bold Italic
// for Helvetica)
if ( eItalic > ITALIC_NONE )
{
if ( (aStyleName == maNormal) ||
(aStyleName == maBold) ||
(aStyleName == maLight) ||
(aStyleName == maBlack) )
aStyleName = GetStyleName( eWeight, eItalic );
}
}
return aStyleName;
}
// -----------------------------------------------------------------------
XubString FontList::GetFontMapText( const FontInfo& rInfo ) const
{
if ( !rInfo.GetName().Len() )
{
XubString aEmptryStr;
return aEmptryStr;
}
// Search Fontname
ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetName() );
if ( !pData )
{
if ( !maMapNotAvailable.Len() )
((FontList*)this)->maMapNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_NOTAVAILABLE ) );
return maMapNotAvailable;
}
// search for synthetic style
USHORT nType = pData->mnType;
const XubString& rStyleName = rInfo.GetStyleName();
if ( rStyleName.Len() )
{
BOOL bNotSynthetic = FALSE;
BOOL bNoneAvailable = FALSE;
FontWeight eWeight = rInfo.GetWeight();
FontItalic eItalic = rInfo.GetItalic();
ImplFontListFontInfo* pFontInfo = pData->mpFirst;
while ( pFontInfo )
{
if ( (eWeight == pFontInfo->GetWeight()) &&
(eItalic == pFontInfo->GetItalic()) )
{
bNotSynthetic = TRUE;
break;
}
pFontInfo = pFontInfo->mpNext;
}
if ( bNoneAvailable )
{
XubString aEmptryStr;
return aEmptryStr;
}
else if ( !bNotSynthetic )
{
if ( !maMapStyleNotAvailable.Len() )
((FontList*)this)->maMapStyleNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_STYLENOTAVAILABLE ) );
return maMapStyleNotAvailable;
}
}
/* Size not available not implemented yet
if ( !(nType & FONTLIST_FONTNAMETYPE_SCALABLE) )
{
...
{
if ( !maMapSizeNotAvailable.Len() )
((FontList*)this)->maMapSizeNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_SIZENOTAVAILABLE ) );
return maMapSizeNotAvailable;
}
}
*/
// Only Printer-Font?
if ( (nType & (FONTLIST_FONTNAMETYPE_PRINTER | FONTLIST_FONTNAMETYPE_SCREEN)) == FONTLIST_FONTNAMETYPE_PRINTER )
{
if ( !maMapPrinterOnly.Len() )
((FontList*)this)->maMapPrinterOnly = XubString( SvtResId( STR_SVT_FONTMAP_PRINTERONLY ) );
return maMapPrinterOnly;
}
// Only Screen-Font?
else if ( (nType & (FONTLIST_FONTNAMETYPE_PRINTER | FONTLIST_FONTNAMETYPE_SCREEN)) == FONTLIST_FONTNAMETYPE_SCREEN
&& rInfo.GetType() == TYPE_RASTER )
{
if ( !maMapScreenOnly.Len() )
((FontList*)this)->maMapScreenOnly = XubString( SvtResId( STR_SVT_FONTMAP_SCREENONLY ) );
return maMapScreenOnly;
}
else
{
if ( !maMapBoth.Len() )
((FontList*)this)->maMapBoth = XubString( SvtResId( STR_SVT_FONTMAP_BOTH ) );
return maMapBoth;
}
}
// -----------------------------------------------------------------------
USHORT FontList::GetFontNameType( const XubString& rFontName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rFontName );
if ( pData )
return pData->mnType;
else
return 0;
}
// -----------------------------------------------------------------------
FontInfo FontList::Get( const XubString& rName, const XubString& rStyleName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
ImplFontListFontInfo* pFontInfo = NULL;
ImplFontListFontInfo* pFontNameInfo = NULL;
if ( pData )
{
ImplFontListFontInfo* pSearchInfo = pData->mpFirst;
pFontNameInfo = pSearchInfo;
pSearchInfo = pData->mpFirst;
while ( pSearchInfo )
{
if ( rStyleName.EqualsIgnoreCaseAscii( GetStyleName( *pSearchInfo ) ) )
{
pFontInfo = pSearchInfo;
break;
}
pSearchInfo = pSearchInfo->mpNext;
}
}
// Konnten die Daten nicht gefunden werden, dann muessen bestimmte
// Attribute nachgebildet werden
FontInfo aInfo;
if ( !pFontInfo )
{
if ( pFontNameInfo )
aInfo = *pFontNameInfo;
if ( rStyleName == maNormal )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_NORMAL );
}
else if ( rStyleName == maNormalItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_NORMAL );
}
else if ( rStyleName == maBold )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_BOLD );
}
else if ( rStyleName == maBoldItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_BOLD );
}
else if ( rStyleName == maLight )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_LIGHT );
}
else if ( rStyleName == maLightItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_LIGHT );
}
else if ( rStyleName == maBlack )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_BLACK );
}
else if ( rStyleName == maBlackItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_BLACK );
}
else
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_DONTKNOW );
}
}
else
aInfo = *pFontInfo;
// set Fontname to keep FontAlias
aInfo.SetName( rName );
aInfo.SetStyleName( rStyleName );
return aInfo;
}
// -----------------------------------------------------------------------
FontInfo FontList::Get( const XubString& rName,
FontWeight eWeight, FontItalic eItalic ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
ImplFontListFontInfo* pFontInfo = NULL;
ImplFontListFontInfo* pFontNameInfo = NULL;
if ( pData )
{
ImplFontListFontInfo* pSearchInfo = pData->mpFirst;
pFontNameInfo = pSearchInfo;
while ( pSearchInfo )
{
if ( (eWeight == pSearchInfo->GetWeight()) &&
(eItalic == pSearchInfo->GetItalic()) )
{
pFontInfo = pSearchInfo;
break;
}
pSearchInfo = pSearchInfo->mpNext;
}
}
// Konnten die Daten nicht gefunden werden, dann muessen bestimmte
// Attribute nachgebildet werden
FontInfo aInfo;
if ( !pFontInfo )
{
// Falls der Fontname stimmt, uebernehmen wir soviel wie moeglich
if ( pFontNameInfo )
{
aInfo = *pFontNameInfo;
aInfo.SetStyleName( XubString() );
}
aInfo.SetWeight( eWeight );
aInfo.SetItalic( eItalic );
}
else
aInfo = *pFontInfo;
// set Fontname to keep FontAlias
aInfo.SetName( rName );
return aInfo;
}
// -----------------------------------------------------------------------
BOOL FontList::IsAvailable( const XubString& rName ) const
{
return (ImplFindByName( rName ) != 0);
}
// -----------------------------------------------------------------------
const FontInfo& FontList::GetFontName( USHORT nFont ) const
{
DBG_ASSERT( nFont < GetFontNameCount(), "FontList::GetFontName(): nFont >= Count" );
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)List::GetObject( nFont );
return *(pData->mpFirst);
}
// -----------------------------------------------------------------------
USHORT FontList::GetFontNameType( USHORT nFont ) const
{
DBG_ASSERT( nFont < GetFontNameCount(), "FontList::GetFontNameType(): nFont >= Count" );
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)List::GetObject( nFont );
return pData->mnType;
}
// -----------------------------------------------------------------------
sal_Handle FontList::GetFirstFontInfo( const XubString& rName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
if ( !pData )
return (sal_Handle)NULL;
else
return (sal_Handle)pData->mpFirst;
}
// -----------------------------------------------------------------------
sal_Handle FontList::GetNextFontInfo( sal_Handle hFontInfo ) const
{
ImplFontListFontInfo* pInfo = (ImplFontListFontInfo*)(void*)hFontInfo;
return (sal_Handle)(pInfo->mpNext);
}
// -----------------------------------------------------------------------
const FontInfo& FontList::GetFontInfo( sal_Handle hFontInfo ) const
{
ImplFontListFontInfo* pInfo = (ImplFontListFontInfo*)(void*)hFontInfo;
return *pInfo;
}
// -----------------------------------------------------------------------
const long* FontList::GetSizeAry( const FontInfo& rInfo ) const
{
// Size-Array vorher loeschen
if ( mpSizeAry )
{
delete[] ((FontList*)this)->mpSizeAry;
((FontList*)this)->mpSizeAry = NULL;
}
// Falls kein Name, dann Standardgroessen
if ( !rInfo.GetName().Len() )
return aStdSizeAry;
// Zuerst nach dem Fontnamen suchen um das Device dann von dem
// entsprechenden Font zu nehmen
OutputDevice* pDevice = mpDev;
ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetName() );
if ( pData )
pDevice = pData->mpFirst->GetDevice();
int nDevSizeCount = pDevice->GetDevFontSizeCount( rInfo );
if ( !nDevSizeCount ||
(pDevice->GetDevFontSize( rInfo, 0 ).Height() == 0) )
return aStdSizeAry;
MapMode aOldMapMode = pDevice->GetMapMode();
MapMode aMap( MAP_10TH_INCH, Point(), Fraction( 1, 72 ), Fraction( 1, 72 ) );
pDevice->SetMapMode( aMap );
USHORT i;
USHORT nRealCount = 0;
long nOldHeight = 0;
((FontList*)this)->mpSizeAry = new long[nDevSizeCount+1];
for ( i = 0; i < nDevSizeCount; i++ )
{
Size aSize = pDevice->GetDevFontSize( rInfo, i );
if ( aSize.Height() != nOldHeight )
{
nOldHeight = aSize.Height();
((FontList*)this)->mpSizeAry[nRealCount] = nOldHeight;
nRealCount++;
}
}
((FontList*)this)->mpSizeAry[nRealCount] = 0;
pDevice->SetMapMode( aOldMapMode );
return mpSizeAry;
}
// -----------------------------------------------------------------------
const long* FontList::GetStdSizeAry()
{
return aStdSizeAry;
}
// =======================================================================
// ---------------------------------
// - FontSizeNames & FsizeNameItem -
// ---------------------------------
struct ImplFSNameItem
{
long mnSize;
const char* mszUtf8Name;
};
//------------------------------------------------------------------------
static ImplFSNameItem aImplSimplifiedChinese[] =
{
{ 50, "\xe5\x85\xab\xe5\x8f\xb7" },
{ 55, "\xe4\xb8\x83\xe5\x8f\xb7" },
{ 65, "\xe5\xb0\x8f\xe5\x85\xad" },
{ 75, "\xe5\x85\xad\xe5\x8f\xb7" },
{ 90, "\xe5\xb0\x8f\xe4\xba\x94" },
{ 105, "\xe4\xba\x94\xe5\x8f\xb7" },
{ 120, "\xe5\xb0\x8f\xe5\x9b\x9b" },
{ 140, "\xe5\x9b\x9b\xe5\x8f\xb7" },
{ 150, "\xe5\xb0\x8f\xe4\xb8\x89" },
{ 160, "\xe4\xb8\x89\xe5\x8f\xb7" },
{ 180, "\xe5\xb0\x8f\xe4\xba\x8c" },
{ 220, "\xe4\xba\x8c\xe5\x8f\xb7" },
{ 240, "\xe5\xb0\x8f\xe4\xb8\x80" },
{ 260, "\xe4\xb8\x80\xe5\x8f\xb7" },
{ 360, "\xe5\xb0\x8f\xe5\x88\x9d" },
{ 420, "\xe5\x88\x9d\xe5\x8f\xb7" }
};
// -----------------------------------------------------------------------
static ImplFSNameItem aImplTraditionalChinese[] =
{
{ 50, "\xe5\x85\xab\xe8\x99\x9f" },
{ 55, "\xe4\xb8\x83\xe8\x99\x9f" },
{ 65, "\xe5\xb0\x8f\xe5\x85\xad" },
{ 75, "\xe5\x85\xad\xe8\x99\x9f" },
{ 90, "\xe5\xb0\x8f\xe4\xba\x94" },
{ 105, "\xe4\xba\x94\xe8\x99\x9f" },
{ 120, "\xe5\xb0\x8f\xe5\x9b\x9b" },
{ 140, "\xe5\x9b\x9b\xe8\x99\x9f" },
{ 150, "\xe5\xb0\x8f\xe4\xb8\x89" },
{ 160, "\xe4\xb8\x89\xe8\x99\x9f" },
{ 180, "\xe5\xb0\x8f\xe4\xba\x8c" },
{ 220, "\xe4\xba\x8c\xe8\x99\x9f" },
{ 240, "\xe5\xb0\x8f\xe4\xb8\x80" },
{ 260, "\xe4\xb8\x80\xe8\x99\x9f" },
{ 360, "\xe5\xb0\x8f\xe5\x88\x9d" },
{ 420, "\xe5\x88\x9d\xe8\x99\x9f" }
};
//------------------------------------------------------------------------
FontSizeNames::FontSizeNames( LanguageType eLanguage )
{
if ( eLanguage == LANGUAGE_DONTKNOW )
eLanguage = Application::GetSettings().GetUILanguage();
if ( eLanguage == LANGUAGE_SYSTEM )
eLanguage = MsLangId::getSystemUILanguage();
switch( eLanguage )
{
case LANGUAGE_CHINESE:
case LANGUAGE_CHINESE_SIMPLIFIED:
mpArray = aImplSimplifiedChinese;
mnElem = sizeof(aImplSimplifiedChinese) / sizeof(aImplSimplifiedChinese[0]);
break;
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_CHINESE_TRADITIONAL:
mpArray = aImplTraditionalChinese;
mnElem = sizeof(aImplTraditionalChinese) / sizeof(aImplTraditionalChinese[0]);
break;
default:
mpArray = NULL;
mnElem = 0;
break;
};
}
//------------------------------------------------------------------------
long FontSizeNames::Name2Size( const String& rName ) const
{
if ( mnElem )
{
ByteString aName( rName, RTL_TEXTENCODING_UTF8 );
// linear search is sufficient for this rare case
for( long i = mnElem; --i >= 0; )
if ( aName == mpArray[i].mszUtf8Name )
return mpArray[i].mnSize;
}
return 0;
}
//------------------------------------------------------------------------
String FontSizeNames::Size2Name( long nValue ) const
{
String aStr;
// binary search
for( long lower = 0, upper = mnElem - 1; lower <= upper; )
{
long mid = (upper + lower) >> 1;
if ( nValue == mpArray[mid].mnSize )
{
aStr = String( mpArray[mid].mszUtf8Name, RTL_TEXTENCODING_UTF8 );
break;
}
else if ( nValue < mpArray[mid].mnSize )
upper = mid - 1;
else /* ( nValue > mpArray[mid].mnSize ) */
lower = mid + 1;
}
return aStr;
}
//------------------------------------------------------------------------
String FontSizeNames::GetIndexName( ULONG nIndex ) const
{
String aStr;
if ( nIndex < mnElem )
aStr = String( mpArray[nIndex].mszUtf8Name, RTL_TEXTENCODING_UTF8 );
return aStr;
}
//------------------------------------------------------------------------
long FontSizeNames::GetIndexSize( ULONG nIndex ) const
{
if ( nIndex >= mnElem )
return 0;
return mpArray[nIndex].mnSize;
}
INTEGRATION: CWS nofsnames_DEV300 (1.17.228); FILE MERGED
2008/05/08 13:16:58 hdu 1.17.228.2: #i89077# remove unused fontsize names
2008/05/08 13:13:54 hdu 1.17.228.1: #i89077# disable some fontsize names
/*************************************************************************
*
* 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: ctrltool.cxx,v $
* $Revision: 1.19 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define CTRLTOOL_CXX
#include <string.h>
#ifndef TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <i18npool/mslangid.hxx>
#ifndef _VCL_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <svtools/svtools.hrc>
#include <svtools/svtdata.hxx>
#include <ctrltool.hxx>
// =======================================================================
// Standard Fontgroessen fuer scalierbare Fonts
static long aStdSizeAry[] =
{
60,
70,
80,
90,
100,
105,
110,
120,
130,
140,
150,
160,
180,
200,
220,
240,
260,
280,
320,
360,
400,
440,
480,
540,
600,
660,
720,
800,
880,
960,
0
};
// =======================================================================
// -----------------------------
// - class ImplFontListFonInfo -
// -----------------------------
class ImplFontListFontInfo : public FontInfo
{
friend class FontList;
private:
OutputDevice* mpDevice;
ImplFontListFontInfo* mpNext;
public:
ImplFontListFontInfo( const FontInfo& rInfo,
OutputDevice* pDev ) :
FontInfo( rInfo )
{
mpDevice = pDev;
}
OutputDevice* GetDevice() const { return mpDevice; }
};
// ------------------------------
// - class ImplFontListNameInfo -
// ------------------------------
class ImplFontListNameInfo
{
friend class FontList;
private:
XubString maSearchName;
ImplFontListFontInfo* mpFirst;
USHORT mnType;
ImplFontListNameInfo( const XubString& rSearchName ) :
maSearchName( rSearchName )
{}
const XubString& GetSearchName() const { return maSearchName; }
};
// =======================================================================
static StringCompare ImplCompareFontInfo( ImplFontListFontInfo* pInfo1,
ImplFontListFontInfo* pInfo2 )
{
if ( pInfo1->GetWeight() < pInfo2->GetWeight() )
return COMPARE_LESS;
else if ( pInfo1->GetWeight() > pInfo2->GetWeight() )
return COMPARE_GREATER;
if ( pInfo1->GetItalic() < pInfo2->GetItalic() )
return COMPARE_LESS;
else if ( pInfo1->GetItalic() > pInfo2->GetItalic() )
return COMPARE_GREATER;
return pInfo1->GetStyleName().CompareTo( pInfo2->GetStyleName() );
}
// =======================================================================
static void ImplMakeSearchString( XubString& rStr )
{
rStr.ToLowerAscii();
}
// -----------------------------------------------------------------------
static void ImplMakeSearchStringFromName( XubString& rStr )
{
rStr = rStr.GetToken( 0, ';' );
ImplMakeSearchString( rStr );
}
// -----------------------------------------------------------------------
ImplFontListNameInfo* FontList::ImplFind( const XubString& rSearchName, ULONG* pIndex ) const
{
// Wenn kein Eintrag in der Liste oder der Eintrag groesser ist als
// der Letzte, dann hinten dranhaengen. Wir vergleichen erst mit dem
// letzten Eintrag, da die Liste von VCL auch sortiert zurueckkommt
// und somit die Wahrscheinlichkeit das hinten angehaengt werden muss
// sehr gross ist.
StringCompare eComp;
ULONG nCnt = Count();
if ( !nCnt )
{
if ( pIndex )
*pIndex = LIST_APPEND;
return NULL;
}
else
{
ImplFontListNameInfo* pCmpData = (ImplFontListNameInfo*)List::GetObject( nCnt-1 );
eComp = rSearchName.CompareTo( pCmpData->maSearchName );
if ( eComp == COMPARE_GREATER )
{
if ( pIndex )
*pIndex = LIST_APPEND;
return NULL;
}
else if ( eComp == COMPARE_EQUAL )
return pCmpData;
}
// Fonts in der Liste suchen
ImplFontListNameInfo* pCompareData;
ImplFontListNameInfo* pFoundData = NULL;
ULONG nLow = 0;
ULONG nHigh = nCnt-1;
ULONG nMid;
do
{
nMid = (nLow + nHigh) / 2;
pCompareData = (ImplFontListNameInfo*)List::GetObject( nMid );
eComp = rSearchName.CompareTo( pCompareData->maSearchName );
if ( eComp == COMPARE_LESS )
{
if ( !nMid )
break;
nHigh = nMid-1;
}
else
{
if ( eComp == COMPARE_GREATER )
nLow = nMid + 1;
else
{
pFoundData = pCompareData;
break;
}
}
}
while ( nLow <= nHigh );
if ( pIndex )
{
eComp = rSearchName.CompareTo( pCompareData->maSearchName );
if ( eComp == COMPARE_GREATER )
*pIndex = (nMid+1);
else
*pIndex = nMid;
}
return pFoundData;
}
// -----------------------------------------------------------------------
ImplFontListNameInfo* FontList::ImplFindByName( const XubString& rStr ) const
{
XubString aSearchName = rStr;
ImplMakeSearchStringFromName( aSearchName );
return ImplFind( aSearchName, NULL );
}
// -----------------------------------------------------------------------
void FontList::ImplInsertFonts( OutputDevice* pDevice, BOOL bAll,
BOOL bInsertData )
{
rtl_TextEncoding eSystemEncoding = gsl_getSystemTextEncoding();
USHORT nType;
if ( pDevice->GetOutDevType() != OUTDEV_PRINTER )
nType = FONTLIST_FONTNAMETYPE_SCREEN;
else
nType = FONTLIST_FONTNAMETYPE_PRINTER;
// Alle Fonts vom Device abfragen
int n = pDevice->GetDevFontCount();
USHORT i;
for( i = 0; i < n; i++ )
{
FontInfo aFontInfo = pDevice->GetDevFont( i );
// Wenn keine Raster-Schriften angezeigt werden sollen,
// dann diese ignorieren
if ( !bAll && (aFontInfo.GetType() == TYPE_RASTER) )
continue;
XubString aSearchName = aFontInfo.GetName();
ImplFontListNameInfo* pData;
ULONG nIndex;
ImplMakeSearchString( aSearchName );
pData = ImplFind( aSearchName, &nIndex );
if ( !pData )
{
if ( bInsertData )
{
ImplFontListFontInfo* pNewInfo = new ImplFontListFontInfo( aFontInfo, pDevice );
pData = new ImplFontListNameInfo( aSearchName );
pData->mpFirst = pNewInfo;
pNewInfo->mpNext = NULL;
pData->mnType = 0;
Insert( (void*)pData, nIndex );
}
}
else
{
if ( bInsertData )
{
BOOL bInsert = TRUE;
ImplFontListFontInfo* pPrev = NULL;
ImplFontListFontInfo* pTemp = pData->mpFirst;
ImplFontListFontInfo* pNewInfo = new ImplFontListFontInfo( aFontInfo, pDevice );
while ( pTemp )
{
StringCompare eComp = ImplCompareFontInfo( pNewInfo, pTemp );
if ( (eComp == COMPARE_LESS) || (eComp == COMPARE_EQUAL) )
{
if ( eComp == COMPARE_EQUAL )
{
// Overwrite charset, because charset should match
// with the system charset
if ( (pTemp->GetCharSet() != eSystemEncoding) &&
(pNewInfo->GetCharSet() == eSystemEncoding) )
{
ImplFontListFontInfo* pTemp2 = pTemp->mpNext;
*((FontInfo*)pTemp) = *((FontInfo*)pNewInfo);
pTemp->mpNext = pTemp2;
}
delete pNewInfo;
bInsert = FALSE;
}
break;
}
pPrev = pTemp;
pTemp = pTemp->mpNext;
}
if ( bInsert )
{
pNewInfo->mpNext = pTemp;
if ( pPrev )
pPrev->mpNext = pNewInfo;
else
pData->mpFirst = pNewInfo;
}
}
}
if ( pData )
{
pData->mnType |= nType;
if ( aFontInfo.GetType() != TYPE_RASTER )
pData->mnType |= FONTLIST_FONTNAMETYPE_SCALABLE;
}
}
}
// =======================================================================
FontList::FontList( OutputDevice* pDevice, OutputDevice* pDevice2, BOOL bAll ) :
List( 4096, sal::static_int_cast< USHORT >(pDevice->GetDevFontCount()), 32 )
{
// Variablen initialisieren
mpDev = pDevice;
mpDev2 = pDevice2;
mpSizeAry = NULL;
// Stylenamen festlegen
maLight = XubString( SvtResId( STR_SVT_STYLE_LIGHT ) );
maLightItalic = XubString( SvtResId( STR_SVT_STYLE_LIGHT_ITALIC ) );
maNormal = XubString( SvtResId( STR_SVT_STYLE_NORMAL ) );
maNormalItalic = XubString( SvtResId( STR_SVT_STYLE_NORMAL_ITALIC ) );
maBold = XubString( SvtResId( STR_SVT_STYLE_BOLD ) );
maBoldItalic = XubString( SvtResId( STR_SVT_STYLE_BOLD_ITALIC ) );
maBlack = XubString( SvtResId( STR_SVT_STYLE_BLACK ) );
maBlackItalic = XubString( SvtResId( STR_SVT_STYLE_BLACK_ITALIC ) );
ImplInsertFonts( pDevice, bAll, TRUE );
// Gegebenenfalls muessen wir mit den Bildschirmfonts vergleichen,
// damit dort die eigentlich doppelten auf Equal mappen koennen
BOOL bCompareWindow = FALSE;
if ( !pDevice2 && (pDevice->GetOutDevType() == OUTDEV_PRINTER) )
{
bCompareWindow = TRUE;
pDevice2 = Application::GetDefaultDevice();
}
if ( pDevice2 &&
(pDevice2->GetOutDevType() != pDevice->GetOutDevType()) )
ImplInsertFonts( pDevice2, bAll, !bCompareWindow );
}
// -----------------------------------------------------------------------
FontList::~FontList()
{
// Gegebenenfalls SizeArray loeschen
if ( mpSizeAry )
delete[] mpSizeAry;
// FontInfos loeschen
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)First();
while ( pData )
{
ImplFontListFontInfo* pTemp;
ImplFontListFontInfo* pInfo = pData->mpFirst;
while ( pInfo )
{
pTemp = pInfo->mpNext;
delete pInfo;
pInfo = pTemp;
}
ImplFontListNameInfo* pNext = (ImplFontListNameInfo*)Next();
delete pData;
pData = pNext;
}
}
// -----------------------------------------------------------------------
FontList* FontList::Clone() const
{
FontList* pReturn = new FontList(
mpDev, mpDev2, GetFontNameCount() == mpDev->GetDevFontCount());
return pReturn;
}
// -----------------------------------------------------------------------
const XubString& FontList::GetStyleName( FontWeight eWeight, FontItalic eItalic ) const
{
if ( eWeight > WEIGHT_BOLD )
{
if ( eItalic > ITALIC_NONE )
return maBlackItalic;
else
return maBlack;
}
else if ( eWeight > WEIGHT_MEDIUM )
{
if ( eItalic > ITALIC_NONE )
return maBoldItalic;
else
return maBold;
}
else if ( eWeight > WEIGHT_LIGHT )
{
if ( eItalic > ITALIC_NONE )
return maNormalItalic;
else
return maNormal;
}
else if ( eWeight != WEIGHT_DONTKNOW )
{
if ( eItalic > ITALIC_NONE )
return maLightItalic;
else
return maLight;
}
else
{
if ( eItalic > ITALIC_NONE )
return maNormalItalic;
else
return maNormal;
}
}
// -----------------------------------------------------------------------
XubString FontList::GetStyleName( const FontInfo& rInfo ) const
{
XubString aStyleName = rInfo.GetStyleName();
FontWeight eWeight = rInfo.GetWeight();
FontItalic eItalic = rInfo.GetItalic();
// Nur wenn kein StyleName gesetzt ist, geben wir einen syntetischen
// Namen zurueck
if ( !aStyleName.Len() )
aStyleName = GetStyleName( eWeight, eItalic );
else
{
// Translate StyleName to localized name
XubString aCompareStyleName = aStyleName;
aCompareStyleName.ToLowerAscii();
aCompareStyleName.EraseAllChars( ' ' );
if ( aCompareStyleName.EqualsAscii( "bold" ) )
aStyleName = maBold;
else if ( aCompareStyleName.EqualsAscii( "bolditalic" ) )
aStyleName = maBoldItalic;
else if ( aCompareStyleName.EqualsAscii( "italic" ) )
aStyleName = maNormalItalic;
else if ( aCompareStyleName.EqualsAscii( "standard" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "regular" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "medium" ) )
aStyleName = maNormal;
else if ( aCompareStyleName.EqualsAscii( "light" ) )
aStyleName = maLight;
else if ( aCompareStyleName.EqualsAscii( "lightitalic" ) )
aStyleName = maLightItalic;
else if ( aCompareStyleName.EqualsAscii( "black" ) )
aStyleName = maBlack;
else if ( aCompareStyleName.EqualsAscii( "blackitalic" ) )
aStyleName = maBlackItalic;
// fix up StyleName, because the PS Printer driver from
// W2000 returns wrong StyleNames (e.g. Bold instead of Bold Italic
// for Helvetica)
if ( eItalic > ITALIC_NONE )
{
if ( (aStyleName == maNormal) ||
(aStyleName == maBold) ||
(aStyleName == maLight) ||
(aStyleName == maBlack) )
aStyleName = GetStyleName( eWeight, eItalic );
}
}
return aStyleName;
}
// -----------------------------------------------------------------------
XubString FontList::GetFontMapText( const FontInfo& rInfo ) const
{
if ( !rInfo.GetName().Len() )
{
XubString aEmptryStr;
return aEmptryStr;
}
// Search Fontname
ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetName() );
if ( !pData )
{
if ( !maMapNotAvailable.Len() )
((FontList*)this)->maMapNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_NOTAVAILABLE ) );
return maMapNotAvailable;
}
// search for synthetic style
USHORT nType = pData->mnType;
const XubString& rStyleName = rInfo.GetStyleName();
if ( rStyleName.Len() )
{
BOOL bNotSynthetic = FALSE;
BOOL bNoneAvailable = FALSE;
FontWeight eWeight = rInfo.GetWeight();
FontItalic eItalic = rInfo.GetItalic();
ImplFontListFontInfo* pFontInfo = pData->mpFirst;
while ( pFontInfo )
{
if ( (eWeight == pFontInfo->GetWeight()) &&
(eItalic == pFontInfo->GetItalic()) )
{
bNotSynthetic = TRUE;
break;
}
pFontInfo = pFontInfo->mpNext;
}
if ( bNoneAvailable )
{
XubString aEmptryStr;
return aEmptryStr;
}
else if ( !bNotSynthetic )
{
if ( !maMapStyleNotAvailable.Len() )
((FontList*)this)->maMapStyleNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_STYLENOTAVAILABLE ) );
return maMapStyleNotAvailable;
}
}
/* Size not available not implemented yet
if ( !(nType & FONTLIST_FONTNAMETYPE_SCALABLE) )
{
...
{
if ( !maMapSizeNotAvailable.Len() )
((FontList*)this)->maMapSizeNotAvailable = XubString( SvtResId( STR_SVT_FONTMAP_SIZENOTAVAILABLE ) );
return maMapSizeNotAvailable;
}
}
*/
// Only Printer-Font?
if ( (nType & (FONTLIST_FONTNAMETYPE_PRINTER | FONTLIST_FONTNAMETYPE_SCREEN)) == FONTLIST_FONTNAMETYPE_PRINTER )
{
if ( !maMapPrinterOnly.Len() )
((FontList*)this)->maMapPrinterOnly = XubString( SvtResId( STR_SVT_FONTMAP_PRINTERONLY ) );
return maMapPrinterOnly;
}
// Only Screen-Font?
else if ( (nType & (FONTLIST_FONTNAMETYPE_PRINTER | FONTLIST_FONTNAMETYPE_SCREEN)) == FONTLIST_FONTNAMETYPE_SCREEN
&& rInfo.GetType() == TYPE_RASTER )
{
if ( !maMapScreenOnly.Len() )
((FontList*)this)->maMapScreenOnly = XubString( SvtResId( STR_SVT_FONTMAP_SCREENONLY ) );
return maMapScreenOnly;
}
else
{
if ( !maMapBoth.Len() )
((FontList*)this)->maMapBoth = XubString( SvtResId( STR_SVT_FONTMAP_BOTH ) );
return maMapBoth;
}
}
// -----------------------------------------------------------------------
USHORT FontList::GetFontNameType( const XubString& rFontName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rFontName );
if ( pData )
return pData->mnType;
else
return 0;
}
// -----------------------------------------------------------------------
FontInfo FontList::Get( const XubString& rName, const XubString& rStyleName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
ImplFontListFontInfo* pFontInfo = NULL;
ImplFontListFontInfo* pFontNameInfo = NULL;
if ( pData )
{
ImplFontListFontInfo* pSearchInfo = pData->mpFirst;
pFontNameInfo = pSearchInfo;
pSearchInfo = pData->mpFirst;
while ( pSearchInfo )
{
if ( rStyleName.EqualsIgnoreCaseAscii( GetStyleName( *pSearchInfo ) ) )
{
pFontInfo = pSearchInfo;
break;
}
pSearchInfo = pSearchInfo->mpNext;
}
}
// Konnten die Daten nicht gefunden werden, dann muessen bestimmte
// Attribute nachgebildet werden
FontInfo aInfo;
if ( !pFontInfo )
{
if ( pFontNameInfo )
aInfo = *pFontNameInfo;
if ( rStyleName == maNormal )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_NORMAL );
}
else if ( rStyleName == maNormalItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_NORMAL );
}
else if ( rStyleName == maBold )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_BOLD );
}
else if ( rStyleName == maBoldItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_BOLD );
}
else if ( rStyleName == maLight )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_LIGHT );
}
else if ( rStyleName == maLightItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_LIGHT );
}
else if ( rStyleName == maBlack )
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_BLACK );
}
else if ( rStyleName == maBlackItalic )
{
aInfo.SetItalic( ITALIC_NORMAL );
aInfo.SetWeight( WEIGHT_BLACK );
}
else
{
aInfo.SetItalic( ITALIC_NONE );
aInfo.SetWeight( WEIGHT_DONTKNOW );
}
}
else
aInfo = *pFontInfo;
// set Fontname to keep FontAlias
aInfo.SetName( rName );
aInfo.SetStyleName( rStyleName );
return aInfo;
}
// -----------------------------------------------------------------------
FontInfo FontList::Get( const XubString& rName,
FontWeight eWeight, FontItalic eItalic ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
ImplFontListFontInfo* pFontInfo = NULL;
ImplFontListFontInfo* pFontNameInfo = NULL;
if ( pData )
{
ImplFontListFontInfo* pSearchInfo = pData->mpFirst;
pFontNameInfo = pSearchInfo;
while ( pSearchInfo )
{
if ( (eWeight == pSearchInfo->GetWeight()) &&
(eItalic == pSearchInfo->GetItalic()) )
{
pFontInfo = pSearchInfo;
break;
}
pSearchInfo = pSearchInfo->mpNext;
}
}
// Konnten die Daten nicht gefunden werden, dann muessen bestimmte
// Attribute nachgebildet werden
FontInfo aInfo;
if ( !pFontInfo )
{
// Falls der Fontname stimmt, uebernehmen wir soviel wie moeglich
if ( pFontNameInfo )
{
aInfo = *pFontNameInfo;
aInfo.SetStyleName( XubString() );
}
aInfo.SetWeight( eWeight );
aInfo.SetItalic( eItalic );
}
else
aInfo = *pFontInfo;
// set Fontname to keep FontAlias
aInfo.SetName( rName );
return aInfo;
}
// -----------------------------------------------------------------------
BOOL FontList::IsAvailable( const XubString& rName ) const
{
return (ImplFindByName( rName ) != 0);
}
// -----------------------------------------------------------------------
const FontInfo& FontList::GetFontName( USHORT nFont ) const
{
DBG_ASSERT( nFont < GetFontNameCount(), "FontList::GetFontName(): nFont >= Count" );
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)List::GetObject( nFont );
return *(pData->mpFirst);
}
// -----------------------------------------------------------------------
USHORT FontList::GetFontNameType( USHORT nFont ) const
{
DBG_ASSERT( nFont < GetFontNameCount(), "FontList::GetFontNameType(): nFont >= Count" );
ImplFontListNameInfo* pData = (ImplFontListNameInfo*)List::GetObject( nFont );
return pData->mnType;
}
// -----------------------------------------------------------------------
sal_Handle FontList::GetFirstFontInfo( const XubString& rName ) const
{
ImplFontListNameInfo* pData = ImplFindByName( rName );
if ( !pData )
return (sal_Handle)NULL;
else
return (sal_Handle)pData->mpFirst;
}
// -----------------------------------------------------------------------
sal_Handle FontList::GetNextFontInfo( sal_Handle hFontInfo ) const
{
ImplFontListFontInfo* pInfo = (ImplFontListFontInfo*)(void*)hFontInfo;
return (sal_Handle)(pInfo->mpNext);
}
// -----------------------------------------------------------------------
const FontInfo& FontList::GetFontInfo( sal_Handle hFontInfo ) const
{
ImplFontListFontInfo* pInfo = (ImplFontListFontInfo*)(void*)hFontInfo;
return *pInfo;
}
// -----------------------------------------------------------------------
const long* FontList::GetSizeAry( const FontInfo& rInfo ) const
{
// Size-Array vorher loeschen
if ( mpSizeAry )
{
delete[] ((FontList*)this)->mpSizeAry;
((FontList*)this)->mpSizeAry = NULL;
}
// Falls kein Name, dann Standardgroessen
if ( !rInfo.GetName().Len() )
return aStdSizeAry;
// Zuerst nach dem Fontnamen suchen um das Device dann von dem
// entsprechenden Font zu nehmen
OutputDevice* pDevice = mpDev;
ImplFontListNameInfo* pData = ImplFindByName( rInfo.GetName() );
if ( pData )
pDevice = pData->mpFirst->GetDevice();
int nDevSizeCount = pDevice->GetDevFontSizeCount( rInfo );
if ( !nDevSizeCount ||
(pDevice->GetDevFontSize( rInfo, 0 ).Height() == 0) )
return aStdSizeAry;
MapMode aOldMapMode = pDevice->GetMapMode();
MapMode aMap( MAP_10TH_INCH, Point(), Fraction( 1, 72 ), Fraction( 1, 72 ) );
pDevice->SetMapMode( aMap );
USHORT i;
USHORT nRealCount = 0;
long nOldHeight = 0;
((FontList*)this)->mpSizeAry = new long[nDevSizeCount+1];
for ( i = 0; i < nDevSizeCount; i++ )
{
Size aSize = pDevice->GetDevFontSize( rInfo, i );
if ( aSize.Height() != nOldHeight )
{
nOldHeight = aSize.Height();
((FontList*)this)->mpSizeAry[nRealCount] = nOldHeight;
nRealCount++;
}
}
((FontList*)this)->mpSizeAry[nRealCount] = 0;
pDevice->SetMapMode( aOldMapMode );
return mpSizeAry;
}
// -----------------------------------------------------------------------
const long* FontList::GetStdSizeAry()
{
return aStdSizeAry;
}
// =======================================================================
// ---------------------------------
// - FontSizeNames & FsizeNameItem -
// ---------------------------------
struct ImplFSNameItem
{
long mnSize;
const char* mszUtf8Name;
};
//------------------------------------------------------------------------
static ImplFSNameItem aImplSimplifiedChinese[] =
{
{ 50, "\xe5\x85\xab\xe5\x8f\xb7" },
{ 55, "\xe4\xb8\x83\xe5\x8f\xb7" },
{ 65, "\xe5\xb0\x8f\xe5\x85\xad" },
{ 75, "\xe5\x85\xad\xe5\x8f\xb7" },
{ 90, "\xe5\xb0\x8f\xe4\xba\x94" },
{ 105, "\xe4\xba\x94\xe5\x8f\xb7" },
{ 120, "\xe5\xb0\x8f\xe5\x9b\x9b" },
{ 140, "\xe5\x9b\x9b\xe5\x8f\xb7" },
{ 150, "\xe5\xb0\x8f\xe4\xb8\x89" },
{ 160, "\xe4\xb8\x89\xe5\x8f\xb7" },
{ 180, "\xe5\xb0\x8f\xe4\xba\x8c" },
{ 220, "\xe4\xba\x8c\xe5\x8f\xb7" },
{ 240, "\xe5\xb0\x8f\xe4\xb8\x80" },
{ 260, "\xe4\xb8\x80\xe5\x8f\xb7" },
{ 360, "\xe5\xb0\x8f\xe5\x88\x9d" },
{ 420, "\xe5\x88\x9d\xe5\x8f\xb7" }
};
// -----------------------------------------------------------------------
#if 0 // #i89077# disabled by popular request
static ImplFSNameItem aImplTraditionalChinese[] =
{
{ 50, "\xe5\x85\xab\xe8\x99\x9f" },
{ 55, "\xe4\xb8\x83\xe8\x99\x9f" },
{ 65, "\xe5\xb0\x8f\xe5\x85\xad" },
{ 75, "\xe5\x85\xad\xe8\x99\x9f" },
{ 90, "\xe5\xb0\x8f\xe4\xba\x94" },
{ 105, "\xe4\xba\x94\xe8\x99\x9f" },
{ 120, "\xe5\xb0\x8f\xe5\x9b\x9b" },
{ 140, "\xe5\x9b\x9b\xe8\x99\x9f" },
{ 150, "\xe5\xb0\x8f\xe4\xb8\x89" },
{ 160, "\xe4\xb8\x89\xe8\x99\x9f" },
{ 180, "\xe5\xb0\x8f\xe4\xba\x8c" },
{ 220, "\xe4\xba\x8c\xe8\x99\x9f" },
{ 240, "\xe5\xb0\x8f\xe4\xb8\x80" },
{ 260, "\xe4\xb8\x80\xe8\x99\x9f" },
{ 360, "\xe5\xb0\x8f\xe5\x88\x9d" },
{ 420, "\xe5\x88\x9d\xe8\x99\x9f" }
};
#endif
//------------------------------------------------------------------------
FontSizeNames::FontSizeNames( LanguageType eLanguage )
{
if ( eLanguage == LANGUAGE_DONTKNOW )
eLanguage = Application::GetSettings().GetUILanguage();
if ( eLanguage == LANGUAGE_SYSTEM )
eLanguage = MsLangId::getSystemUILanguage();
switch( eLanguage )
{
case LANGUAGE_CHINESE:
case LANGUAGE_CHINESE_SIMPLIFIED:
mpArray = aImplSimplifiedChinese;
mnElem = sizeof(aImplSimplifiedChinese) / sizeof(aImplSimplifiedChinese[0]);
break;
#if 0 // #i89077# disabled by popular request
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_CHINESE_TRADITIONAL:
mpArray = aImplTraditionalChinese;
mnElem = sizeof(aImplTraditionalChinese) / sizeof(aImplTraditionalChinese[0]);
break;
#endif
default:
mpArray = NULL;
mnElem = 0;
break;
};
}
//------------------------------------------------------------------------
long FontSizeNames::Name2Size( const String& rName ) const
{
if ( mnElem )
{
ByteString aName( rName, RTL_TEXTENCODING_UTF8 );
// linear search is sufficient for this rare case
for( long i = mnElem; --i >= 0; )
if ( aName == mpArray[i].mszUtf8Name )
return mpArray[i].mnSize;
}
return 0;
}
//------------------------------------------------------------------------
String FontSizeNames::Size2Name( long nValue ) const
{
String aStr;
// binary search
for( long lower = 0, upper = mnElem - 1; lower <= upper; )
{
long mid = (upper + lower) >> 1;
if ( nValue == mpArray[mid].mnSize )
{
aStr = String( mpArray[mid].mszUtf8Name, RTL_TEXTENCODING_UTF8 );
break;
}
else if ( nValue < mpArray[mid].mnSize )
upper = mid - 1;
else /* ( nValue > mpArray[mid].mnSize ) */
lower = mid + 1;
}
return aStr;
}
//------------------------------------------------------------------------
String FontSizeNames::GetIndexName( ULONG nIndex ) const
{
String aStr;
if ( nIndex < mnElem )
aStr = String( mpArray[nIndex].mszUtf8Name, RTL_TEXTENCODING_UTF8 );
return aStr;
}
//------------------------------------------------------------------------
long FontSizeNames::GetIndexSize( ULONG nIndex ) const
{
if ( nIndex >= mnElem )
return 0;
return mpArray[nIndex].mnSize;
}
|
/*************************************************************************
*
* $RCSfile: fmtfield.cxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: rt $ $Date: 2004-12-03 14:28:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _ZFORMAT_HXX //autogen
#include "zformat.hxx"
#endif
#ifndef _FMTFIELD_HXX_
#include "fmtfield.hxx"
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP_
#include <com/sun/star/util/SearchAlgorithms.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHRESULT_HPP_
#include <com/sun/star/util/SearchResult.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include "syslocale.hxx"
#endif
#ifndef REGEXP_SUPPORT
#include <map>
#endif
#if !defined INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
#ifdef REGEXP_SUPPORT
//==============================================================================
// regular expression to validate complete numbers, plus every fragment which can occur during the input
// of a complete number
// [+/-][{digit}*.]*{digit}*[,{digit}*][e[+/-]{digit}*]
const char __FAR_DATA szNumericInput[] = "_[-+]?([0-9]*\\,)*[0-9]*(\\.[0-9]*)?(e[-+]?[0-9]*)?_";
// (the two _ are for normalizing it: With this, we can ensure that a to-be-checked text is always
// matched as a _whole_)
#else
// hmm. No support for regular expression. Well, I always (not really :) wanted to write a finite automat
// so here comes a finite automat ...
namespace validation
{
// the states of our automat.
enum State
{
START, // at the very start of the string
NUM_START, // the very start of the number
DIGIT_PRE_COMMA, // some pre-comma digits are read, perhaps including some thousand separators
DIGIT_POST_COMMA, // reading digits after the comma
EXPONENT_START, // at the very start of the exponent value
// (means: not including the "e" which denotes the exponent)
EXPONENT_DIGIT, // currently reading the digits of the exponent
END // reached the end of the string
};
// a row in the transition table (means the set of states to be reached from a given state)
typedef ::std::map< sal_Unicode, State > StateTransitions;
// a single transition
typedef StateTransitions::value_type Transition;
// the complete transition table
typedef ::std::map< State, StateTransitions > TransitionTable;
// the validator class
class NumberValidator
{
private:
TransitionTable m_aTransitions;
const sal_Unicode m_cThSep;
const sal_Unicode m_cDecSep;
public:
NumberValidator( const sal_Unicode _cThSep, const sal_Unicode _cDecSep );
sal_Bool isValidNumericFragment( const String& _rText );
private:
sal_Bool implValidateNormalized( const String& _rText );
};
//--------------------------------------------------------------------------
//..........................................................................
static void lcl_insertStopTransition( StateTransitions& _rRow )
{
_rRow.insert( Transition( '_', END ) );
}
//..........................................................................
static void lcl_insertStartExponentTransition( StateTransitions& _rRow )
{
_rRow.insert( Transition( 'e', EXPONENT_START ) );
}
//..........................................................................
static void lcl_insertSignTransitions( StateTransitions& _rRow, const State eNextState )
{
_rRow.insert( Transition( '-', eNextState ) );
_rRow.insert( Transition( '+', eNextState ) );
}
//..........................................................................
static void lcl_insertDigitTransitions( StateTransitions& _rRow, const State eNextState )
{
for ( sal_Unicode aChar = '0'; aChar <= '9'; ++aChar )
_rRow.insert( Transition( aChar, eNextState ) );
}
//..........................................................................
static void lcl_insertCommonPreCommaTransitions( StateTransitions& _rRow, const sal_Unicode _cThSep, const sal_Unicode _cDecSep )
{
// digits are allowed
lcl_insertDigitTransitions( _rRow, DIGIT_PRE_COMMA );
// the thousand separator is allowed
_rRow.insert( Transition( _cThSep, DIGIT_PRE_COMMA ) );
// a comma is allowed
_rRow.insert( Transition( _cDecSep, DIGIT_POST_COMMA ) );
}
//--------------------------------------------------------------------------
NumberValidator::NumberValidator( const sal_Unicode _cThSep, const sal_Unicode _cDecSep )
:m_cThSep( _cThSep )
,m_cDecSep( _cDecSep )
{
// build up our transition table
// how to procede from START
{
StateTransitions& rRow = m_aTransitions[ START ];
rRow.insert( Transition( '_', NUM_START ) );
// if we encounter the normalizing character, we want to procede with the number
}
// how to procede from NUM_START
{
StateTransitions& rRow = m_aTransitions[ NUM_START ];
// a sign is allowed
lcl_insertSignTransitions( rRow, DIGIT_PRE_COMMA );
// common transitions for the two pre-comma states
lcl_insertCommonPreCommaTransitions( rRow, m_cThSep, m_cDecSep );
// the exponent may start here
// (this would mean string like "_+e10_", but this is a valid fragment, though no valid number)
lcl_insertStartExponentTransition( rRow );
}
// how to procede from DIGIT_PRE_COMMA
{
StateTransitions& rRow = m_aTransitions[ DIGIT_PRE_COMMA ];
// common transitions for the two pre-comma states
lcl_insertCommonPreCommaTransitions( rRow, m_cThSep, m_cDecSep );
// the exponent may start here
lcl_insertStartExponentTransition( rRow );
// the final transition indicating the end of the string
// (if there is no comma and no post-comma, then the string may end here)
lcl_insertStopTransition( rRow );
}
// how to procede from DIGIT_POST_COMMA
{
StateTransitions& rRow = m_aTransitions[ DIGIT_POST_COMMA ];
// there might be digits, which would keep the state at DIGIT_POST_COMMA
lcl_insertDigitTransitions( rRow, DIGIT_POST_COMMA );
// the exponent may start here
lcl_insertStartExponentTransition( rRow );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from EXPONENT_START
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_START ];
// there may be a sign
lcl_insertSignTransitions( rRow, EXPONENT_DIGIT );
// there may be digits
lcl_insertDigitTransitions( rRow, EXPONENT_DIGIT );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from EXPONENT_DIGIT
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_DIGIT ];
// there may be digits
lcl_insertDigitTransitions( rRow, EXPONENT_DIGIT );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from END
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_DIGIT ];
// no valid transition to leave this state
// (note that we, for consistency, nevertheless want to have a row in the table)
}
}
//--------------------------------------------------------------------------
sal_Bool NumberValidator::implValidateNormalized( const String& _rText )
{
const sal_Unicode* pCheckPos = _rText.GetBuffer();
State eCurrentState = START;
while ( END != eCurrentState )
{
// look up the transition row for the current state
TransitionTable::const_iterator aRow = m_aTransitions.find( eCurrentState );
DBG_ASSERT( m_aTransitions.end() != aRow,
"NumberValidator::implValidateNormalized: invalid transition table (row not found)!" );
if ( m_aTransitions.end() != aRow )
{
// look up the current character in this row
StateTransitions::const_iterator aTransition = aRow->second.find( *pCheckPos );
if ( aRow->second.end() != aTransition )
{
// there is a valid transition for this character
eCurrentState = aTransition->second;
++pCheckPos;
continue;
}
}
// if we're here, there is no valid transition
break;
}
DBG_ASSERT( ( END != eCurrentState ) || ( 0 == *pCheckPos ),
"NumberValidator::implValidateNormalized: inconsistency!" );
// if we're at END, then the string should be done, too - the string should be normalized, means ending
// a "_" and not containing any other "_" (except at the start), and "_" is the only possibility
// to reach the END state
// the string is valid if and only if we reached the final state
return ( END == eCurrentState );
}
//--------------------------------------------------------------------------
sal_Bool NumberValidator::isValidNumericFragment( const String& _rText )
{
if ( !_rText.Len() )
// empty strings are always allowed
return sal_True;
// normalize the string
String sNormalized( RTL_CONSTASCII_STRINGPARAM( "_") );
sNormalized.Append( _rText );
sNormalized.AppendAscii( "_" );
return implValidateNormalized( sNormalized );
}
}
#endif
//==============================================================================
SvNumberFormatter* FormattedField::StaticFormatter::s_cFormatter = NULL;
ULONG FormattedField::StaticFormatter::s_nReferences = 0;
//------------------------------------------------------------------------------
SvNumberFormatter* FormattedField::StaticFormatter::GetFormatter()
{
if (!s_cFormatter)
{
// get the Office's UI locale
SvtSysLocale aSysLocale;
const Locale& rSysLocale = aSysLocale.GetLocaleData().getLocale();
// translate
LanguageType eSysLanguage = ConvertIsoNamesToLanguage( rSysLocale.Language, rSysLocale.Country );
s_cFormatter = new SvNumberFormatter(
::comphelper::getProcessServiceFactory(),
eSysLanguage);
}
return s_cFormatter;
}
//------------------------------------------------------------------------------
FormattedField::StaticFormatter::StaticFormatter()
{
++s_nReferences;
}
//------------------------------------------------------------------------------
FormattedField::StaticFormatter::~StaticFormatter()
{
if (--s_nReferences == 0)
{
delete s_cFormatter;
s_cFormatter = NULL;
}
}
//==============================================================================
DBG_NAME(FormattedField);
#define INIT_MEMBERS() \
m_aLastSelection(0,0) \
,m_dMinValue(0) \
,m_dMaxValue(0) \
,m_bHasMin(FALSE) \
,m_bHasMax(FALSE) \
,m_bStrictFormat(TRUE) \
,m_bValueDirty(TRUE) \
,m_bEnableEmptyField(TRUE) \
,m_bAutoColor(FALSE) \
,m_dCurrentValue(0) \
,m_dDefaultValue(0) \
,m_nFormatKey(0) \
,m_pFormatter(NULL) \
,m_dSpinSize(1) \
,m_dSpinFirst(-1000000) \
,m_dSpinLast(1000000) \
,m_bTreatAsNumber(TRUE) \
,m_pLastOutputColor(NULL)
//------------------------------------------------------------------------------
FormattedField::FormattedField(Window* pParent, WinBits nStyle, SvNumberFormatter* pInitialFormatter, INT32 nFormatKey)
:SpinField(pParent, nStyle)
,INIT_MEMBERS()
{
DBG_CTOR(FormattedField, NULL);
if (pInitialFormatter)
{
m_pFormatter = pInitialFormatter;
m_nFormatKey = nFormatKey;
}
}
//------------------------------------------------------------------------------
FormattedField::FormattedField(Window* pParent, const ResId& rResId, SvNumberFormatter* pInitialFormatter, INT32 nFormatKey)
:SpinField(pParent, rResId)
,INIT_MEMBERS()
{
DBG_CTOR(FormattedField, NULL);
if (pInitialFormatter)
{
m_pFormatter = pInitialFormatter;
m_nFormatKey = nFormatKey;
}
}
//------------------------------------------------------------------------------
FormattedField::~FormattedField()
{
DBG_DTOR(FormattedField, NULL);
}
//------------------------------------------------------------------------------
void FormattedField::SetValidateText(const XubString& rText, const String* pErrorText)
{
DBG_CHKTHIS(FormattedField, NULL);
if (CheckText(rText))
SetText(rText);
else
if (pErrorText)
ImplSetText(*pErrorText, NULL);
else
ImplSetValue(m_dDefaultValue, TRUE);
}
//------------------------------------------------------------------------------
void FormattedField::SetText(const XubString& rStr)
{
DBG_CHKTHIS(FormattedField, NULL);
SpinField::SetText(rStr);
m_bValueDirty = TRUE;
}
//------------------------------------------------------------------------------
void FormattedField::SetTextFormatted(const XubString& rStr)
{
DBG_CHKTHIS(FormattedField, NULL);
#if DBG_UTIL
if (ImplGetFormatter()->IsTextFormat(m_nFormatKey))
DBG_WARNING("FormattedField::SetTextFormatted : valid only with text formats !");
#endif
m_sCurrentTextValue = rStr;
String sFormatted;
ImplGetFormatter()->GetOutputString(m_sCurrentTextValue, m_nFormatKey, sFormatted, &m_pLastOutputColor);
// calculate the new selection
Selection aSel(GetSelection());
Selection aNewSel(aSel);
aNewSel.Justify();
USHORT nNewLen = sFormatted.Len();
USHORT nCurrentLen = GetText().Len();
if ((nNewLen > nCurrentLen) && (aNewSel.Max() == nCurrentLen))
{ // the new text is longer and the cursor was behind the last char (of the old text)
if (aNewSel.Min() == 0)
{ // the whole text was selected -> select the new text on the whole, too
aNewSel.Max() = nNewLen;
if (!nCurrentLen)
{ // there wasn't really a previous selection (as there was no previous text), we're setting a new one -> check the selection options
ULONG nSelOptions = GetSettings().GetStyleSettings().GetSelectionOptions();
if (nSelOptions & SELECTION_OPTION_SHOWFIRST)
{ // selection should be from right to left -> swap min and max
aNewSel.Min() = aNewSel.Max();
aNewSel.Max() = 0;
}
}
}
else if (aNewSel.Max() == aNewSel.Min())
{ // there was no selection -> set the cursor behind the new last char
aNewSel.Max() = nNewLen;
aNewSel.Min() = nNewLen;
}
}
else if (aNewSel.Max() > nNewLen)
aNewSel.Max() = nNewLen;
else
aNewSel = aSel; // don't use the justified version
SpinField::SetText(sFormatted, aNewSel);
m_bValueDirty = FALSE;
}
//------------------------------------------------------------------------------
String FormattedField::GetTextValue() const
{
if (m_bValueDirty)
{
((FormattedField*)this)->m_sCurrentTextValue = GetText();
((FormattedField*)this)->m_bValueDirty = FALSE;
}
return m_sCurrentTextValue;
}
//------------------------------------------------------------------------------
void FormattedField::EnableNotANumber( BOOL _bEnable )
{
if ( m_bEnableNaN == _bEnable )
return;
m_bEnableNaN = _bEnable;
}
//------------------------------------------------------------------------------
void FormattedField::SetAutoColor(BOOL _bAutomatic)
{
if (_bAutomatic == m_bAutoColor)
return;
m_bAutoColor = _bAutomatic;
if (m_bAutoColor)
{ // if auto color is switched on, adjust the current text color, too
if (m_pLastOutputColor)
SetControlForeground(*m_pLastOutputColor);
else
SetControlForeground();
}
}
//------------------------------------------------------------------------------
void FormattedField::Modify()
{
DBG_CHKTHIS(FormattedField, NULL);
if (!IsStrictFormat())
{
m_bValueDirty = TRUE;
SpinField::Modify();
return;
}
String sCheck = GetText();
if (CheckText(sCheck))
{
m_sLastValidText = sCheck;
m_aLastSelection = GetSelection();
m_bValueDirty = TRUE;
}
else
{
ImplSetText(m_sLastValidText, &m_aLastSelection);
}
SpinField::Modify();
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetText(const XubString& rNew, Selection* pNewSel)
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bAutoColor)
{
if (m_pLastOutputColor)
SetControlForeground(*m_pLastOutputColor);
else
SetControlForeground();
}
if (pNewSel)
SpinField::SetText(rNew, *pNewSel);
else
{
Selection aSel(GetSelection());
aSel.Justify();
USHORT nNewLen = rNew.Len();
USHORT nCurrentLen = GetText().Len();
if ((nNewLen > nCurrentLen) && (aSel.Max() == nCurrentLen))
{ // new new text is longer and the cursor is behind the last char
if (aSel.Min() == 0)
{ // the whole text was selected -> select the new text on the whole, too
aSel.Max() = nNewLen;
if (!nCurrentLen)
{ // there wasn't really a previous selection (as there was no previous text), we're setting a new one -> check the selection options
ULONG nSelOptions = GetSettings().GetStyleSettings().GetSelectionOptions();
if (nSelOptions & SELECTION_OPTION_SHOWFIRST)
{ // selection should be from right to left -> swap min and max
aSel.Min() = aSel.Max();
aSel.Max() = 0;
}
}
}
else if (aSel.Max() == aSel.Min())
{ // there was no selection -> set the cursor behind the new last char
aSel.Max() = nNewLen;
aSel.Min() = nNewLen;
}
}
else if (aSel.Max() > nNewLen)
aSel.Max() = nNewLen;
SpinField::SetText(rNew, aSel);
}
m_bValueDirty = TRUE;
// muss nicht stimmen, aber sicherheitshalber ...
}
//------------------------------------------------------------------------------
long FormattedField::PreNotify(NotifyEvent& rNEvt)
{
DBG_CHKTHIS(FormattedField, NULL);
if (rNEvt.GetType() == EVENT_KEYINPUT)
m_aLastSelection = GetSelection();
return SpinField::PreNotify(rNEvt);
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetFormatKey(ULONG nFormatKey)
{
DBG_CHKTHIS(FormattedField, NULL);
m_nFormatKey = nFormatKey;
BOOL bNeedFormatter = (m_pFormatter == NULL) && (nFormatKey != 0);
if (bNeedFormatter)
{
ImplGetFormatter(); // damit wird ein Standard-Formatter angelegt
m_nFormatKey = nFormatKey;
// kann sein, dass das in dem Standard-Formatter keinen Sinn macht, aber der nimmt dann ein Default-Format an.
// Auf diese Weise kann ich einfach einen der - formatteruebergreifended gleichen - Standard-Keys setzen.
DBG_ASSERT(m_pFormatter->GetEntry(nFormatKey) != NULL, "FormattedField::ImplSetFormatKey : invalid format key !");
// Wenn SetFormatKey aufgerufen wird, ohne dass ein Formatter existiert, muss der Key einer der Standard-Werte
// sein, der in allen Formattern (also auch in meinem neu angelegten) vorhanden ist.
}
}
//------------------------------------------------------------------------------
void FormattedField::SetFormatKey(ULONG nFormatKey)
{
DBG_CHKTHIS(FormattedField, NULL);
BOOL bNoFormatter = (m_pFormatter == NULL);
ImplSetFormatKey(nFormatKey);
FormatChanged((bNoFormatter && (m_pFormatter != NULL)) ? FCT_FORMATTER : FCT_KEYONLY);
}
//------------------------------------------------------------------------------
void FormattedField::SetFormatter(SvNumberFormatter* pFormatter, BOOL bResetFormat)
{
DBG_CHKTHIS(FormattedField, NULL);
if (bResetFormat)
{
m_pFormatter = pFormatter;
// calc the default format key from the Office's UI locale
if ( m_pFormatter )
{
// get the Office's UI locale
SvtSysLocale aSysLocale;
const Locale& rSysLocale = aSysLocale.GetLocaleData().getLocale();
// translate
LanguageType eSysLanguage = ConvertIsoNamesToLanguage( rSysLocale.Language, rSysLocale.Country );
// get the standard numeric format for this language
m_nFormatKey = m_pFormatter->GetStandardFormat( NUMBERFORMAT_NUMBER, eSysLanguage );
}
else
m_nFormatKey = 0;
}
else
{
XubString sOldFormat;
LanguageType aOldLang;
GetFormat(sOldFormat, aOldLang);
ULONG nDestKey = pFormatter->TestNewString(sOldFormat);
if (nDestKey == NUMBERFORMAT_ENTRY_NOT_FOUND)
{
// die Sprache des neuen Formatters
const SvNumberformat* pDefaultEntry = pFormatter->GetEntry(0);
LanguageType aNewLang = pDefaultEntry ? pDefaultEntry->GetLanguage() : LANGUAGE_DONTKNOW;
// den alten Format-String in die neue Sprache konvertieren
USHORT nCheckPos;
short nType;
pFormatter->PutandConvertEntry(sOldFormat, nCheckPos, nType, nDestKey, aOldLang, aNewLang);
m_nFormatKey = nDestKey;
}
m_pFormatter = pFormatter;
}
FormatChanged(FCT_FORMATTER);
}
//------------------------------------------------------------------------------
void FormattedField::GetFormat(XubString& rFormatString, LanguageType& eLang) const
{
DBG_CHKTHIS(FormattedField, NULL);
const SvNumberformat* pFormatEntry = ImplGetFormatter()->GetEntry(m_nFormatKey);
DBG_ASSERT(pFormatEntry != NULL, "FormattedField::GetFormat: no number format for the given format key.");
rFormatString = pFormatEntry ? pFormatEntry->GetFormatstring() : XubString();
eLang = pFormatEntry ? pFormatEntry->GetLanguage() : LANGUAGE_DONTKNOW;
}
//------------------------------------------------------------------------------
BOOL FormattedField::SetFormat(const XubString& rFormatString, LanguageType eLang)
{
DBG_CHKTHIS(FormattedField, NULL);
ULONG nNewKey = ImplGetFormatter()->TestNewString(rFormatString, eLang);
if (nNewKey == NUMBERFORMAT_ENTRY_NOT_FOUND)
{
USHORT nCheckPos;
short nType;
XubString rFormat(rFormatString);
if (!ImplGetFormatter()->PutEntry(rFormat, nCheckPos, nType, nNewKey, eLang))
return FALSE;
DBG_ASSERT(nNewKey != NUMBERFORMAT_ENTRY_NOT_FOUND, "FormattedField::SetFormatString : PutEntry returned an invalid key !");
}
if (nNewKey != m_nFormatKey)
SetFormatKey(nNewKey);
return TRUE;
}
//------------------------------------------------------------------------------
BOOL FormattedField::GetThousandsSep() const
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::GetThousandsSep : your'e sure what your'e doing when setting the precision of a text format ?");
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
return bThousand;
}
//------------------------------------------------------------------------------
void FormattedField::SetThousandsSep(BOOL _bUseSeparator)
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::SetThousandsSep : your'e sure what your'e doing when setting the precision of a text format ?");
// get the current settings
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
if (bThousand == _bUseSeparator)
return;
// we need the language for the following
LanguageType eLang;
String sFmtDescription;
GetFormat(sFmtDescription, eLang);
// generate a new format ...
ImplGetFormatter()->GenerateFormat(sFmtDescription, m_nFormatKey, eLang, _bUseSeparator, IsRed, nPrecision, nAnzLeading);
// ... and introduce it to the formatter
USHORT nCheckPos;
ULONG nNewKey;
short nType;
ImplGetFormatter()->PutEntry(sFmtDescription, nCheckPos, nType, nNewKey, eLang);
// set the new key
ImplSetFormatKey(nNewKey);
FormatChanged(FCT_THOUSANDSSEP);
}
//------------------------------------------------------------------------------
USHORT FormattedField::GetDecimalDigits() const
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::GetDecimalDigits : your'e sure what your'e doing when setting the precision of a text format ?");
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
return nPrecision;
}
//------------------------------------------------------------------------------
void FormattedField::SetDecimalDigits(USHORT _nPrecision)
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::SetDecimalDigits : your'e sure what your'e doing when setting the precision of a text format ?");
// get the current settings
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
if (nPrecision == _nPrecision)
return;
// we need the language for the following
LanguageType eLang;
String sFmtDescription;
GetFormat(sFmtDescription, eLang);
// generate a new format ...
ImplGetFormatter()->GenerateFormat(sFmtDescription, m_nFormatKey, eLang, bThousand, IsRed, _nPrecision, nAnzLeading);
// ... and introduce it to the formatter
USHORT nCheckPos;
ULONG nNewKey;
short nType;
ImplGetFormatter()->PutEntry(sFmtDescription, nCheckPos, nType, nNewKey, eLang);
// set the new key
ImplSetFormatKey(nNewKey);
FormatChanged(FCT_PRECISION);
}
//------------------------------------------------------------------------------
void FormattedField::FormatChanged( FORMAT_CHANGE_TYPE _nWhat )
{
DBG_CHKTHIS(FormattedField, NULL);
m_pLastOutputColor = NULL;
if ( ( 0 != ( _nWhat & FCT_FORMATTER ) ) && m_pFormatter )
m_pFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_INTL_FORMAT );
// 95845 - 03.04.2002 - fs@openoffice.org
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::Commit()
{
// remember the old text
String sOld( GetText() );
// do the reformat
ReFormat();
// did the text change?
if ( GetText() != sOld )
{ // consider the field as modified
Modify();
// but we have the most recent value now
m_bValueDirty = FALSE;
}
}
//------------------------------------------------------------------------------
void FormattedField::ReFormat()
{
if (!IsEmptyFieldEnabled() || GetText().Len())
if (TreatingAsNumber())
{
double dValue = GetValue();
if ( m_bEnableNaN && ::rtl::math::isNan( dValue ) )
return;
ImplSetValue( dValue, TRUE );
}
else
SetTextFormatted(GetTextValue());
}
//------------------------------------------------------------------------------
long FormattedField::Notify(NotifyEvent& rNEvt)
{
DBG_CHKTHIS(FormattedField, NULL);
if ((rNEvt.GetType() == EVENT_KEYINPUT) && !IsReadOnly())
{
const KeyEvent& rKEvt = *rNEvt.GetKeyEvent();
USHORT nMod = rKEvt.GetKeyCode().GetModifier();
switch ( rKEvt.GetKeyCode().GetCode() )
{
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN:
if (!nMod && ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// the base class would translate this into calls to Up/Down/First/Last,
// but we don't want this if we are text-formatted
return 1;
}
}
}
if ((rNEvt.GetType() == EVENT_COMMAND) && !IsReadOnly())
{
const CommandEvent* pCommand = rNEvt.GetCommandEvent();
if (pCommand->GetCommand() == COMMAND_WHEEL)
{
const CommandWheelData* pData = rNEvt.GetCommandEvent()->GetWheelData();
if ((pData->GetMode() == COMMAND_WHEEL_SCROLL) && ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// same as above : prevent the base class from doing Up/Down-calls
// (normally I should put this test into the Up/Down methods itself, shouldn't I ?)
// FS - 71553 - 19.01.00
return 1;
}
}
}
if (rNEvt.GetType() == EVENT_LOSEFOCUS)
{
// Sonderbehandlung fuer leere Texte
if (GetText().Len() == 0)
{
if (!IsEmptyFieldEnabled())
{
if (TreatingAsNumber())
{
ImplSetValue(m_dCurrentValue, TRUE);
Modify();
}
else
{
String sNew = GetTextValue();
if (sNew.Len())
SetTextFormatted(sNew);
else
SetTextFormatted(m_sDefaultText);
}
m_bValueDirty = FALSE;
}
}
else
{
Commit();
}
}
return SpinField::Notify( rNEvt );
}
//------------------------------------------------------------------------------
void FormattedField::SetMinValue(double dMin)
{
DBG_CHKTHIS(FormattedField, NULL);
DBG_ASSERT(m_bTreatAsNumber, "FormattedField::SetMinValue : only to be used in numeric mode !");
m_dMinValue = dMin;
m_bHasMin = TRUE;
// fuer die Ueberpruefung des aktuellen Wertes an der neuen Grenze -> ImplSetValue
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::SetMaxValue(double dMax)
{
DBG_CHKTHIS(FormattedField, NULL);
DBG_ASSERT(m_bTreatAsNumber, "FormattedField::SetMaxValue : only to be used in numeric mode !");
m_dMaxValue = dMax;
m_bHasMax = TRUE;
// fuer die Ueberpruefung des aktuellen Wertes an der neuen Grenze -> ImplSetValue
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::SetTextValue(const XubString& rText)
{
DBG_CHKTHIS(FormattedField, NULL);
SetText(rText);
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::EnableEmptyField(BOOL bEnable)
{
DBG_CHKTHIS(FormattedField, NULL);
if (bEnable == m_bEnableEmptyField)
return;
m_bEnableEmptyField = bEnable;
if (!m_bEnableEmptyField && GetText().Len()==0)
ImplSetValue(m_dCurrentValue, TRUE);
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetValue(double dVal, BOOL bForce)
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMin && (dVal<m_dMinValue))
dVal = m_dMinValue;
if (m_bHasMax && (dVal>m_dMaxValue))
dVal = m_dMaxValue;
if (!bForce && (dVal == GetValue()))
return;
DBG_ASSERT(ImplGetFormatter() != NULL, "FormattedField::ImplSetValue : can't set a value without a formatter !");
m_bValueDirty = FALSE;
m_dCurrentValue = dVal;
String sNewText;
if (ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// zuerst die Zahl als String im Standard-Format
String sTemp;
ImplGetFormatter()->GetOutputString(dVal, 0, sTemp, &m_pLastOutputColor);
// dann den String entsprechend dem Text-Format
ImplGetFormatter()->GetOutputString(sTemp, m_nFormatKey, sNewText, &m_pLastOutputColor);
}
else
{
ImplGetFormatter()->GetOutputString(dVal, m_nFormatKey, sNewText, &m_pLastOutputColor);
}
ImplSetText(sNewText, NULL);
m_bValueDirty = FALSE;
DBG_ASSERT(CheckText(sNewText), "FormattedField::ImplSetValue : formatted string doesn't match the criteria !");
}
//------------------------------------------------------------------------------
BOOL FormattedField::ImplGetValue(double& dNewVal)
{
DBG_CHKTHIS(FormattedField, NULL);
dNewVal = m_dCurrentValue;
if (!m_bValueDirty)
return TRUE;
dNewVal = m_dDefaultValue;
String sText(GetText());
if (!sText.Len())
return TRUE;
DBG_ASSERT(ImplGetFormatter() != NULL, "FormattedField::ImplGetValue : can't give you a current value without a formatter !");
ULONG nFormatKey = m_nFormatKey; // IsNumberFormat veraendert den FormatKey ...
if (ImplGetFormatter()->IsTextFormat(nFormatKey) && m_bTreatAsNumber)
// damit wir in einem als Text formatierten Feld trotzdem eine Eingabe wie '1,1' erkennen ...
nFormatKey = 0;
// Sonderbehandlung fuer %-Formatierung
if (ImplGetFormatter()->GetType(m_nFormatKey) == NUMBERFORMAT_PERCENT)
{
// the language of our format
LanguageType eLanguage = m_pFormatter->GetEntry(m_nFormatKey)->GetLanguage();
// the default number format for this language
ULONG nStandardNumericFormat = m_pFormatter->GetStandardFormat(NUMBERFORMAT_NUMBER, eLanguage);
ULONG nTempFormat = nStandardNumericFormat;
double dTemp;
if (m_pFormatter->IsNumberFormat(sText, nTempFormat, dTemp) &&
NUMBERFORMAT_NUMBER == m_pFormatter->GetType(nTempFormat))
// der String entspricht einer Number-Formatierung, hat also nur kein %
// -> append it
sText += '%';
// (with this, a input of '3' becomes '3%', which then by the formatter is translated
// into 0.03. Without this, the formatter would give us the double 3 for an input '3',
// which equals 300 percent.
}
if (!ImplGetFormatter()->IsNumberFormat(sText, nFormatKey, dNewVal))
return FALSE;
if (m_bHasMin && (dNewVal<m_dMinValue))
dNewVal = m_dMinValue;
if (m_bHasMax && (dNewVal>m_dMaxValue))
dNewVal = m_dMaxValue;
return TRUE;
}
//------------------------------------------------------------------------------
void FormattedField::SetValue(double dVal)
{
DBG_CHKTHIS(FormattedField, NULL);
ImplSetValue(dVal, m_bValueDirty);
}
//------------------------------------------------------------------------------
double FormattedField::GetValue()
{
DBG_CHKTHIS(FormattedField, NULL);
if ( !ImplGetValue( m_dCurrentValue ) )
if ( m_bEnableNaN )
::rtl::math::setNan( &m_dCurrentValue );
else
m_dCurrentValue = m_dDefaultValue;
m_bValueDirty = FALSE;
return m_dCurrentValue;
}
//------------------------------------------------------------------------------
void FormattedField::Up()
{
DBG_CHKTHIS(FormattedField, NULL);
SetValue(GetValue() + m_dSpinSize);
// das setValue handelt Bereichsueberschreitungen (min/max) automatisch
SetModifyFlag();
Modify();
SpinField::Up();
}
//------------------------------------------------------------------------------
void FormattedField::Down()
{
DBG_CHKTHIS(FormattedField, NULL);
SetValue(GetValue() - m_dSpinSize);
SetModifyFlag();
Modify();
SpinField::Down();
}
//------------------------------------------------------------------------------
void FormattedField::First()
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMin)
{
SetValue(m_dMinValue);
SetModifyFlag();
Modify();
}
SpinField::First();
}
//------------------------------------------------------------------------------
void FormattedField::Last()
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMax)
{
SetValue(m_dMaxValue);
SetModifyFlag();
Modify();
}
SpinField::Last();
}
//==============================================================================
//------------------------------------------------------------------------------
DoubleNumericField::~DoubleNumericField()
{
#ifdef REGEXP_SUPPORT
delete m_pConformanceTester;
#else
delete m_pNumberValidator;
#endif
}
//------------------------------------------------------------------------------
void DoubleNumericField::FormatChanged(FORMAT_CHANGE_TYPE nWhat)
{
ResetConformanceTester();
FormattedField::FormatChanged(nWhat);
}
//------------------------------------------------------------------------------
BOOL DoubleNumericField::CheckText(const XubString& sText) const
{
// We'd like to implement this using the NumberFormatter::IsNumberFormat, but unfortunately, this doesn't
// recognize fragments of numbers (like, for instance "1e", which happens during entering e.g. "1e10")
// Thus, the roundabout way via a regular expression
#ifdef REGEXP_SUPPORT
if (!sText.Len())
return TRUE;
String sForceComplete = '_';
sForceComplete += sText;
sForceComplete += '_';
USHORT nStart = 0, nEnd = sForceComplete.Len();
BOOL bFound = m_pConformanceTester->SearchFrwrd(sForceComplete, &nStart, &nEnd);
if (bFound && (nStart == 0) && (nEnd == sForceComplete.Len()))
return TRUE;
return FALSE;
#else
return m_pNumberValidator->isValidNumericFragment( sText );
#endif
}
//------------------------------------------------------------------------------
void DoubleNumericField::ResetConformanceTester()
{
// the thousands and the decimal separator are language dependent
const SvNumberformat* pFormatEntry = ImplGetFormatter()->GetEntry(m_nFormatKey);
sal_Unicode cSeparatorThousand = ',';
sal_Unicode cSeparatorDecimal = '.';
if (pFormatEntry)
{
String aLanguage, aCountry, aVariant;
ConvertLanguageToIsoNames( pFormatEntry->GetLanguage(), aLanguage, aCountry );
LocaleDataWrapper aLocaleInfo(::comphelper::getProcessServiceFactory(), Locale( aLanguage, aCountry, aVariant ));
String sSeparator = aLocaleInfo.getNumThousandSep();
if (sSeparator.Len())
cSeparatorThousand = sSeparator.GetBuffer()[0];
sSeparator = aLocaleInfo.getNumDecimalSep();
if (sSeparator.Len())
cSeparatorDecimal = sSeparator.GetBuffer()[0];
}
#ifdef REGEXP_SUPPORT
String sDescription = String::CreateFromAscii(szNumericInput);
String sReplaceWith((sal_Unicode)'\\');
sReplaceWith += cSeparatorThousand;
sDescription.SearchAndReplaceAscii("\\,", sReplaceWith);
sReplaceWith = (sal_Unicode)'\\';
sReplaceWith += cSeparatorDecimal;
sDescription.SearchAndReplaceAscii("\\.", sReplaceWith);
delete m_pConformanceTester;
SearchOptions aParam;
aParam.algorithmType = SearchAlgorithms_REGEXP;
aParam.searchFlag = SearchFlags::ALL_IGNORE_CASE;
aParam.searchString = sDescription;
aParam.transliterateFlags = 0;
String sLanguage, sCountry;
ConvertLanguageToIsoNames( pFormatEntry ? pFormatEntry->GetLanguage() : LANGUAGE_ENGLISH_US, sLanguage, sCountry );
aParam.Locale.Language = sLanguage;
aParam.Locale.Country = sCountry;
m_pConformanceTester = new ::utl::TextSearch(aParam);
#else
delete m_pNumberValidator;
m_pNumberValidator = new validation::NumberValidator( cSeparatorThousand, cSeparatorDecimal );
#endif
}
//==============================================================================
//------------------------------------------------------------------------------
DoubleCurrencyField::DoubleCurrencyField(Window* pParent, WinBits nStyle)
:FormattedField(pParent, nStyle)
,m_bChangingFormat(FALSE)
{
m_bPrependCurrSym = FALSE;
// initialize with a system currency format
m_sCurrencySymbol = SvtSysLocale().GetLocaleData().getCurrSymbol();
UpdateCurrencyFormat();
}
//------------------------------------------------------------------------------
DoubleCurrencyField::DoubleCurrencyField(Window* pParent, const ResId& rResId)
:FormattedField(pParent, rResId)
,m_bChangingFormat(FALSE)
{
m_bPrependCurrSym = FALSE;
// initialize with a system currency format
m_sCurrencySymbol = SvtSysLocale().GetLocaleData().getCurrSymbol();
UpdateCurrencyFormat();
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::FormatChanged(FORMAT_CHANGE_TYPE nWhat)
{
if (m_bChangingFormat)
{
FormattedField::FormatChanged(nWhat);
return;
}
switch (nWhat)
{
case FCT_FORMATTER:
case FCT_PRECISION:
case FCT_THOUSANDSSEP:
// the aspects which changed don't take our currency settings into account (in fact, they most probably
// destroyed them)
UpdateCurrencyFormat();
break;
case FCT_KEYONLY:
DBG_ERROR("DoubleCurrencyField::FormatChanged : somebody modified my key !");
// We always build our own format from the settings we get via special methods (setCurrencySymbol etc.).
// Nobody but ourself should modifiy the format key directly !
break;
}
FormattedField::FormatChanged(nWhat);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::setCurrencySymbol(const String& _sSymbol)
{
if (m_sCurrencySymbol == _sSymbol)
return;
m_sCurrencySymbol = _sSymbol;
UpdateCurrencyFormat();
FormatChanged(FCT_CURRENCY_SYMBOL);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::setPrependCurrSym(BOOL _bPrepend)
{
if (m_bPrependCurrSym == _bPrepend)
return;
m_bPrependCurrSym = _bPrepend;
UpdateCurrencyFormat();
FormatChanged(FCT_CURRSYM_POSITION);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::UpdateCurrencyFormat()
{
// the old settings
XubString sOldFormat;
LanguageType eLanguage;
GetFormat(sOldFormat, eLanguage);
BOOL bThSep = GetThousandsSep();
USHORT nDigits = GetDecimalDigits();
// build a new format string with the base class' and my own settings
String aLanguage, aCountry, aVariant;
ConvertLanguageToIsoNames( eLanguage, aLanguage, aCountry );
LocaleDataWrapper aLocaleInfo(::comphelper::getProcessServiceFactory(), Locale( aLanguage, aCountry, aVariant ));
XubString sNewFormat;
if (bThSep)
{
sNewFormat = '#';
sNewFormat += aLocaleInfo.getNumThousandSep();
sNewFormat.AppendAscii("##0");
}
else
sNewFormat = '0';
if (nDigits)
{
sNewFormat += aLocaleInfo.getNumDecimalSep();
XubString sTemp;
sTemp.Fill(nDigits, '0');
sNewFormat += sTemp;
}
if (getPrependCurrSym())
{
XubString sSymbol = getCurrencySymbol();
sSymbol.EraseLeadingChars(' ');
sSymbol.EraseTrailingChars(' ');
XubString sTemp = String::CreateFromAscii("[$");
sTemp += sSymbol;
sTemp.AppendAscii("] ");
sTemp += sNewFormat;
// for negative values : $ -0.00, not -$ 0.00 ...
// (the real solution would be a possibility to choose a "positive currency format" and a "negative currency format" ...
// But not now ... (and hey, you could take a formatted field for this ....))
// FS - 31.03.00 74642
sTemp.AppendAscii(";[$");
sTemp += sSymbol;
sTemp.AppendAscii("] -");
sTemp += sNewFormat;
sNewFormat = sTemp;
}
else
{
XubString sTemp = getCurrencySymbol();
sTemp.EraseLeadingChars(' ');
sTemp.EraseTrailingChars(' ');
sNewFormat += String::CreateFromAscii(" [$");
sNewFormat += sTemp;
sNewFormat += ']';
}
// set this new basic format
m_bChangingFormat = TRUE;
SetFormat(sNewFormat, eLanguage);
m_bChangingFormat = FALSE;
}
INTEGRATION: CWS ooo19126 (1.29.276); FILE MERGED
2005/09/05 14:52:26 rt 1.29.276.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtfield.cxx,v $
*
* $Revision: 1.30 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:02:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _ZFORMAT_HXX //autogen
#include "zformat.hxx"
#endif
#ifndef _FMTFIELD_HXX_
#include "fmtfield.hxx"
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP_
#include <com/sun/star/util/SearchAlgorithms.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHRESULT_HPP_
#include <com/sun/star/util/SearchResult.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include "syslocale.hxx"
#endif
#ifndef REGEXP_SUPPORT
#include <map>
#endif
#if !defined INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
#ifdef REGEXP_SUPPORT
//==============================================================================
// regular expression to validate complete numbers, plus every fragment which can occur during the input
// of a complete number
// [+/-][{digit}*.]*{digit}*[,{digit}*][e[+/-]{digit}*]
const char __FAR_DATA szNumericInput[] = "_[-+]?([0-9]*\\,)*[0-9]*(\\.[0-9]*)?(e[-+]?[0-9]*)?_";
// (the two _ are for normalizing it: With this, we can ensure that a to-be-checked text is always
// matched as a _whole_)
#else
// hmm. No support for regular expression. Well, I always (not really :) wanted to write a finite automat
// so here comes a finite automat ...
namespace validation
{
// the states of our automat.
enum State
{
START, // at the very start of the string
NUM_START, // the very start of the number
DIGIT_PRE_COMMA, // some pre-comma digits are read, perhaps including some thousand separators
DIGIT_POST_COMMA, // reading digits after the comma
EXPONENT_START, // at the very start of the exponent value
// (means: not including the "e" which denotes the exponent)
EXPONENT_DIGIT, // currently reading the digits of the exponent
END // reached the end of the string
};
// a row in the transition table (means the set of states to be reached from a given state)
typedef ::std::map< sal_Unicode, State > StateTransitions;
// a single transition
typedef StateTransitions::value_type Transition;
// the complete transition table
typedef ::std::map< State, StateTransitions > TransitionTable;
// the validator class
class NumberValidator
{
private:
TransitionTable m_aTransitions;
const sal_Unicode m_cThSep;
const sal_Unicode m_cDecSep;
public:
NumberValidator( const sal_Unicode _cThSep, const sal_Unicode _cDecSep );
sal_Bool isValidNumericFragment( const String& _rText );
private:
sal_Bool implValidateNormalized( const String& _rText );
};
//--------------------------------------------------------------------------
//..........................................................................
static void lcl_insertStopTransition( StateTransitions& _rRow )
{
_rRow.insert( Transition( '_', END ) );
}
//..........................................................................
static void lcl_insertStartExponentTransition( StateTransitions& _rRow )
{
_rRow.insert( Transition( 'e', EXPONENT_START ) );
}
//..........................................................................
static void lcl_insertSignTransitions( StateTransitions& _rRow, const State eNextState )
{
_rRow.insert( Transition( '-', eNextState ) );
_rRow.insert( Transition( '+', eNextState ) );
}
//..........................................................................
static void lcl_insertDigitTransitions( StateTransitions& _rRow, const State eNextState )
{
for ( sal_Unicode aChar = '0'; aChar <= '9'; ++aChar )
_rRow.insert( Transition( aChar, eNextState ) );
}
//..........................................................................
static void lcl_insertCommonPreCommaTransitions( StateTransitions& _rRow, const sal_Unicode _cThSep, const sal_Unicode _cDecSep )
{
// digits are allowed
lcl_insertDigitTransitions( _rRow, DIGIT_PRE_COMMA );
// the thousand separator is allowed
_rRow.insert( Transition( _cThSep, DIGIT_PRE_COMMA ) );
// a comma is allowed
_rRow.insert( Transition( _cDecSep, DIGIT_POST_COMMA ) );
}
//--------------------------------------------------------------------------
NumberValidator::NumberValidator( const sal_Unicode _cThSep, const sal_Unicode _cDecSep )
:m_cThSep( _cThSep )
,m_cDecSep( _cDecSep )
{
// build up our transition table
// how to procede from START
{
StateTransitions& rRow = m_aTransitions[ START ];
rRow.insert( Transition( '_', NUM_START ) );
// if we encounter the normalizing character, we want to procede with the number
}
// how to procede from NUM_START
{
StateTransitions& rRow = m_aTransitions[ NUM_START ];
// a sign is allowed
lcl_insertSignTransitions( rRow, DIGIT_PRE_COMMA );
// common transitions for the two pre-comma states
lcl_insertCommonPreCommaTransitions( rRow, m_cThSep, m_cDecSep );
// the exponent may start here
// (this would mean string like "_+e10_", but this is a valid fragment, though no valid number)
lcl_insertStartExponentTransition( rRow );
}
// how to procede from DIGIT_PRE_COMMA
{
StateTransitions& rRow = m_aTransitions[ DIGIT_PRE_COMMA ];
// common transitions for the two pre-comma states
lcl_insertCommonPreCommaTransitions( rRow, m_cThSep, m_cDecSep );
// the exponent may start here
lcl_insertStartExponentTransition( rRow );
// the final transition indicating the end of the string
// (if there is no comma and no post-comma, then the string may end here)
lcl_insertStopTransition( rRow );
}
// how to procede from DIGIT_POST_COMMA
{
StateTransitions& rRow = m_aTransitions[ DIGIT_POST_COMMA ];
// there might be digits, which would keep the state at DIGIT_POST_COMMA
lcl_insertDigitTransitions( rRow, DIGIT_POST_COMMA );
// the exponent may start here
lcl_insertStartExponentTransition( rRow );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from EXPONENT_START
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_START ];
// there may be a sign
lcl_insertSignTransitions( rRow, EXPONENT_DIGIT );
// there may be digits
lcl_insertDigitTransitions( rRow, EXPONENT_DIGIT );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from EXPONENT_DIGIT
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_DIGIT ];
// there may be digits
lcl_insertDigitTransitions( rRow, EXPONENT_DIGIT );
// the string may end here
lcl_insertStopTransition( rRow );
}
// how to procede from END
{
StateTransitions& rRow = m_aTransitions[ EXPONENT_DIGIT ];
// no valid transition to leave this state
// (note that we, for consistency, nevertheless want to have a row in the table)
}
}
//--------------------------------------------------------------------------
sal_Bool NumberValidator::implValidateNormalized( const String& _rText )
{
const sal_Unicode* pCheckPos = _rText.GetBuffer();
State eCurrentState = START;
while ( END != eCurrentState )
{
// look up the transition row for the current state
TransitionTable::const_iterator aRow = m_aTransitions.find( eCurrentState );
DBG_ASSERT( m_aTransitions.end() != aRow,
"NumberValidator::implValidateNormalized: invalid transition table (row not found)!" );
if ( m_aTransitions.end() != aRow )
{
// look up the current character in this row
StateTransitions::const_iterator aTransition = aRow->second.find( *pCheckPos );
if ( aRow->second.end() != aTransition )
{
// there is a valid transition for this character
eCurrentState = aTransition->second;
++pCheckPos;
continue;
}
}
// if we're here, there is no valid transition
break;
}
DBG_ASSERT( ( END != eCurrentState ) || ( 0 == *pCheckPos ),
"NumberValidator::implValidateNormalized: inconsistency!" );
// if we're at END, then the string should be done, too - the string should be normalized, means ending
// a "_" and not containing any other "_" (except at the start), and "_" is the only possibility
// to reach the END state
// the string is valid if and only if we reached the final state
return ( END == eCurrentState );
}
//--------------------------------------------------------------------------
sal_Bool NumberValidator::isValidNumericFragment( const String& _rText )
{
if ( !_rText.Len() )
// empty strings are always allowed
return sal_True;
// normalize the string
String sNormalized( RTL_CONSTASCII_STRINGPARAM( "_") );
sNormalized.Append( _rText );
sNormalized.AppendAscii( "_" );
return implValidateNormalized( sNormalized );
}
}
#endif
//==============================================================================
SvNumberFormatter* FormattedField::StaticFormatter::s_cFormatter = NULL;
ULONG FormattedField::StaticFormatter::s_nReferences = 0;
//------------------------------------------------------------------------------
SvNumberFormatter* FormattedField::StaticFormatter::GetFormatter()
{
if (!s_cFormatter)
{
// get the Office's UI locale
SvtSysLocale aSysLocale;
const Locale& rSysLocale = aSysLocale.GetLocaleData().getLocale();
// translate
LanguageType eSysLanguage = ConvertIsoNamesToLanguage( rSysLocale.Language, rSysLocale.Country );
s_cFormatter = new SvNumberFormatter(
::comphelper::getProcessServiceFactory(),
eSysLanguage);
}
return s_cFormatter;
}
//------------------------------------------------------------------------------
FormattedField::StaticFormatter::StaticFormatter()
{
++s_nReferences;
}
//------------------------------------------------------------------------------
FormattedField::StaticFormatter::~StaticFormatter()
{
if (--s_nReferences == 0)
{
delete s_cFormatter;
s_cFormatter = NULL;
}
}
//==============================================================================
DBG_NAME(FormattedField);
#define INIT_MEMBERS() \
m_aLastSelection(0,0) \
,m_dMinValue(0) \
,m_dMaxValue(0) \
,m_bHasMin(FALSE) \
,m_bHasMax(FALSE) \
,m_bStrictFormat(TRUE) \
,m_bValueDirty(TRUE) \
,m_bEnableEmptyField(TRUE) \
,m_bAutoColor(FALSE) \
,m_dCurrentValue(0) \
,m_dDefaultValue(0) \
,m_nFormatKey(0) \
,m_pFormatter(NULL) \
,m_dSpinSize(1) \
,m_dSpinFirst(-1000000) \
,m_dSpinLast(1000000) \
,m_bTreatAsNumber(TRUE) \
,m_pLastOutputColor(NULL)
//------------------------------------------------------------------------------
FormattedField::FormattedField(Window* pParent, WinBits nStyle, SvNumberFormatter* pInitialFormatter, INT32 nFormatKey)
:SpinField(pParent, nStyle)
,INIT_MEMBERS()
{
DBG_CTOR(FormattedField, NULL);
if (pInitialFormatter)
{
m_pFormatter = pInitialFormatter;
m_nFormatKey = nFormatKey;
}
}
//------------------------------------------------------------------------------
FormattedField::FormattedField(Window* pParent, const ResId& rResId, SvNumberFormatter* pInitialFormatter, INT32 nFormatKey)
:SpinField(pParent, rResId)
,INIT_MEMBERS()
{
DBG_CTOR(FormattedField, NULL);
if (pInitialFormatter)
{
m_pFormatter = pInitialFormatter;
m_nFormatKey = nFormatKey;
}
}
//------------------------------------------------------------------------------
FormattedField::~FormattedField()
{
DBG_DTOR(FormattedField, NULL);
}
//------------------------------------------------------------------------------
void FormattedField::SetValidateText(const XubString& rText, const String* pErrorText)
{
DBG_CHKTHIS(FormattedField, NULL);
if (CheckText(rText))
SetText(rText);
else
if (pErrorText)
ImplSetText(*pErrorText, NULL);
else
ImplSetValue(m_dDefaultValue, TRUE);
}
//------------------------------------------------------------------------------
void FormattedField::SetText(const XubString& rStr)
{
DBG_CHKTHIS(FormattedField, NULL);
SpinField::SetText(rStr);
m_bValueDirty = TRUE;
}
//------------------------------------------------------------------------------
void FormattedField::SetTextFormatted(const XubString& rStr)
{
DBG_CHKTHIS(FormattedField, NULL);
#if DBG_UTIL
if (ImplGetFormatter()->IsTextFormat(m_nFormatKey))
DBG_WARNING("FormattedField::SetTextFormatted : valid only with text formats !");
#endif
m_sCurrentTextValue = rStr;
String sFormatted;
ImplGetFormatter()->GetOutputString(m_sCurrentTextValue, m_nFormatKey, sFormatted, &m_pLastOutputColor);
// calculate the new selection
Selection aSel(GetSelection());
Selection aNewSel(aSel);
aNewSel.Justify();
USHORT nNewLen = sFormatted.Len();
USHORT nCurrentLen = GetText().Len();
if ((nNewLen > nCurrentLen) && (aNewSel.Max() == nCurrentLen))
{ // the new text is longer and the cursor was behind the last char (of the old text)
if (aNewSel.Min() == 0)
{ // the whole text was selected -> select the new text on the whole, too
aNewSel.Max() = nNewLen;
if (!nCurrentLen)
{ // there wasn't really a previous selection (as there was no previous text), we're setting a new one -> check the selection options
ULONG nSelOptions = GetSettings().GetStyleSettings().GetSelectionOptions();
if (nSelOptions & SELECTION_OPTION_SHOWFIRST)
{ // selection should be from right to left -> swap min and max
aNewSel.Min() = aNewSel.Max();
aNewSel.Max() = 0;
}
}
}
else if (aNewSel.Max() == aNewSel.Min())
{ // there was no selection -> set the cursor behind the new last char
aNewSel.Max() = nNewLen;
aNewSel.Min() = nNewLen;
}
}
else if (aNewSel.Max() > nNewLen)
aNewSel.Max() = nNewLen;
else
aNewSel = aSel; // don't use the justified version
SpinField::SetText(sFormatted, aNewSel);
m_bValueDirty = FALSE;
}
//------------------------------------------------------------------------------
String FormattedField::GetTextValue() const
{
if (m_bValueDirty)
{
((FormattedField*)this)->m_sCurrentTextValue = GetText();
((FormattedField*)this)->m_bValueDirty = FALSE;
}
return m_sCurrentTextValue;
}
//------------------------------------------------------------------------------
void FormattedField::EnableNotANumber( BOOL _bEnable )
{
if ( m_bEnableNaN == _bEnable )
return;
m_bEnableNaN = _bEnable;
}
//------------------------------------------------------------------------------
void FormattedField::SetAutoColor(BOOL _bAutomatic)
{
if (_bAutomatic == m_bAutoColor)
return;
m_bAutoColor = _bAutomatic;
if (m_bAutoColor)
{ // if auto color is switched on, adjust the current text color, too
if (m_pLastOutputColor)
SetControlForeground(*m_pLastOutputColor);
else
SetControlForeground();
}
}
//------------------------------------------------------------------------------
void FormattedField::Modify()
{
DBG_CHKTHIS(FormattedField, NULL);
if (!IsStrictFormat())
{
m_bValueDirty = TRUE;
SpinField::Modify();
return;
}
String sCheck = GetText();
if (CheckText(sCheck))
{
m_sLastValidText = sCheck;
m_aLastSelection = GetSelection();
m_bValueDirty = TRUE;
}
else
{
ImplSetText(m_sLastValidText, &m_aLastSelection);
}
SpinField::Modify();
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetText(const XubString& rNew, Selection* pNewSel)
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bAutoColor)
{
if (m_pLastOutputColor)
SetControlForeground(*m_pLastOutputColor);
else
SetControlForeground();
}
if (pNewSel)
SpinField::SetText(rNew, *pNewSel);
else
{
Selection aSel(GetSelection());
aSel.Justify();
USHORT nNewLen = rNew.Len();
USHORT nCurrentLen = GetText().Len();
if ((nNewLen > nCurrentLen) && (aSel.Max() == nCurrentLen))
{ // new new text is longer and the cursor is behind the last char
if (aSel.Min() == 0)
{ // the whole text was selected -> select the new text on the whole, too
aSel.Max() = nNewLen;
if (!nCurrentLen)
{ // there wasn't really a previous selection (as there was no previous text), we're setting a new one -> check the selection options
ULONG nSelOptions = GetSettings().GetStyleSettings().GetSelectionOptions();
if (nSelOptions & SELECTION_OPTION_SHOWFIRST)
{ // selection should be from right to left -> swap min and max
aSel.Min() = aSel.Max();
aSel.Max() = 0;
}
}
}
else if (aSel.Max() == aSel.Min())
{ // there was no selection -> set the cursor behind the new last char
aSel.Max() = nNewLen;
aSel.Min() = nNewLen;
}
}
else if (aSel.Max() > nNewLen)
aSel.Max() = nNewLen;
SpinField::SetText(rNew, aSel);
}
m_bValueDirty = TRUE;
// muss nicht stimmen, aber sicherheitshalber ...
}
//------------------------------------------------------------------------------
long FormattedField::PreNotify(NotifyEvent& rNEvt)
{
DBG_CHKTHIS(FormattedField, NULL);
if (rNEvt.GetType() == EVENT_KEYINPUT)
m_aLastSelection = GetSelection();
return SpinField::PreNotify(rNEvt);
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetFormatKey(ULONG nFormatKey)
{
DBG_CHKTHIS(FormattedField, NULL);
m_nFormatKey = nFormatKey;
BOOL bNeedFormatter = (m_pFormatter == NULL) && (nFormatKey != 0);
if (bNeedFormatter)
{
ImplGetFormatter(); // damit wird ein Standard-Formatter angelegt
m_nFormatKey = nFormatKey;
// kann sein, dass das in dem Standard-Formatter keinen Sinn macht, aber der nimmt dann ein Default-Format an.
// Auf diese Weise kann ich einfach einen der - formatteruebergreifended gleichen - Standard-Keys setzen.
DBG_ASSERT(m_pFormatter->GetEntry(nFormatKey) != NULL, "FormattedField::ImplSetFormatKey : invalid format key !");
// Wenn SetFormatKey aufgerufen wird, ohne dass ein Formatter existiert, muss der Key einer der Standard-Werte
// sein, der in allen Formattern (also auch in meinem neu angelegten) vorhanden ist.
}
}
//------------------------------------------------------------------------------
void FormattedField::SetFormatKey(ULONG nFormatKey)
{
DBG_CHKTHIS(FormattedField, NULL);
BOOL bNoFormatter = (m_pFormatter == NULL);
ImplSetFormatKey(nFormatKey);
FormatChanged((bNoFormatter && (m_pFormatter != NULL)) ? FCT_FORMATTER : FCT_KEYONLY);
}
//------------------------------------------------------------------------------
void FormattedField::SetFormatter(SvNumberFormatter* pFormatter, BOOL bResetFormat)
{
DBG_CHKTHIS(FormattedField, NULL);
if (bResetFormat)
{
m_pFormatter = pFormatter;
// calc the default format key from the Office's UI locale
if ( m_pFormatter )
{
// get the Office's UI locale
SvtSysLocale aSysLocale;
const Locale& rSysLocale = aSysLocale.GetLocaleData().getLocale();
// translate
LanguageType eSysLanguage = ConvertIsoNamesToLanguage( rSysLocale.Language, rSysLocale.Country );
// get the standard numeric format for this language
m_nFormatKey = m_pFormatter->GetStandardFormat( NUMBERFORMAT_NUMBER, eSysLanguage );
}
else
m_nFormatKey = 0;
}
else
{
XubString sOldFormat;
LanguageType aOldLang;
GetFormat(sOldFormat, aOldLang);
ULONG nDestKey = pFormatter->TestNewString(sOldFormat);
if (nDestKey == NUMBERFORMAT_ENTRY_NOT_FOUND)
{
// die Sprache des neuen Formatters
const SvNumberformat* pDefaultEntry = pFormatter->GetEntry(0);
LanguageType aNewLang = pDefaultEntry ? pDefaultEntry->GetLanguage() : LANGUAGE_DONTKNOW;
// den alten Format-String in die neue Sprache konvertieren
USHORT nCheckPos;
short nType;
pFormatter->PutandConvertEntry(sOldFormat, nCheckPos, nType, nDestKey, aOldLang, aNewLang);
m_nFormatKey = nDestKey;
}
m_pFormatter = pFormatter;
}
FormatChanged(FCT_FORMATTER);
}
//------------------------------------------------------------------------------
void FormattedField::GetFormat(XubString& rFormatString, LanguageType& eLang) const
{
DBG_CHKTHIS(FormattedField, NULL);
const SvNumberformat* pFormatEntry = ImplGetFormatter()->GetEntry(m_nFormatKey);
DBG_ASSERT(pFormatEntry != NULL, "FormattedField::GetFormat: no number format for the given format key.");
rFormatString = pFormatEntry ? pFormatEntry->GetFormatstring() : XubString();
eLang = pFormatEntry ? pFormatEntry->GetLanguage() : LANGUAGE_DONTKNOW;
}
//------------------------------------------------------------------------------
BOOL FormattedField::SetFormat(const XubString& rFormatString, LanguageType eLang)
{
DBG_CHKTHIS(FormattedField, NULL);
ULONG nNewKey = ImplGetFormatter()->TestNewString(rFormatString, eLang);
if (nNewKey == NUMBERFORMAT_ENTRY_NOT_FOUND)
{
USHORT nCheckPos;
short nType;
XubString rFormat(rFormatString);
if (!ImplGetFormatter()->PutEntry(rFormat, nCheckPos, nType, nNewKey, eLang))
return FALSE;
DBG_ASSERT(nNewKey != NUMBERFORMAT_ENTRY_NOT_FOUND, "FormattedField::SetFormatString : PutEntry returned an invalid key !");
}
if (nNewKey != m_nFormatKey)
SetFormatKey(nNewKey);
return TRUE;
}
//------------------------------------------------------------------------------
BOOL FormattedField::GetThousandsSep() const
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::GetThousandsSep : your'e sure what your'e doing when setting the precision of a text format ?");
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
return bThousand;
}
//------------------------------------------------------------------------------
void FormattedField::SetThousandsSep(BOOL _bUseSeparator)
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::SetThousandsSep : your'e sure what your'e doing when setting the precision of a text format ?");
// get the current settings
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
if (bThousand == _bUseSeparator)
return;
// we need the language for the following
LanguageType eLang;
String sFmtDescription;
GetFormat(sFmtDescription, eLang);
// generate a new format ...
ImplGetFormatter()->GenerateFormat(sFmtDescription, m_nFormatKey, eLang, _bUseSeparator, IsRed, nPrecision, nAnzLeading);
// ... and introduce it to the formatter
USHORT nCheckPos;
ULONG nNewKey;
short nType;
ImplGetFormatter()->PutEntry(sFmtDescription, nCheckPos, nType, nNewKey, eLang);
// set the new key
ImplSetFormatKey(nNewKey);
FormatChanged(FCT_THOUSANDSSEP);
}
//------------------------------------------------------------------------------
USHORT FormattedField::GetDecimalDigits() const
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::GetDecimalDigits : your'e sure what your'e doing when setting the precision of a text format ?");
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
return nPrecision;
}
//------------------------------------------------------------------------------
void FormattedField::SetDecimalDigits(USHORT _nPrecision)
{
DBG_ASSERT(!ImplGetFormatter()->IsTextFormat(m_nFormatKey),
"FormattedField::SetDecimalDigits : your'e sure what your'e doing when setting the precision of a text format ?");
// get the current settings
BOOL bThousand, IsRed;
USHORT nPrecision, nAnzLeading;
ImplGetFormatter()->GetFormatSpecialInfo(m_nFormatKey, bThousand, IsRed, nPrecision, nAnzLeading);
if (nPrecision == _nPrecision)
return;
// we need the language for the following
LanguageType eLang;
String sFmtDescription;
GetFormat(sFmtDescription, eLang);
// generate a new format ...
ImplGetFormatter()->GenerateFormat(sFmtDescription, m_nFormatKey, eLang, bThousand, IsRed, _nPrecision, nAnzLeading);
// ... and introduce it to the formatter
USHORT nCheckPos;
ULONG nNewKey;
short nType;
ImplGetFormatter()->PutEntry(sFmtDescription, nCheckPos, nType, nNewKey, eLang);
// set the new key
ImplSetFormatKey(nNewKey);
FormatChanged(FCT_PRECISION);
}
//------------------------------------------------------------------------------
void FormattedField::FormatChanged( FORMAT_CHANGE_TYPE _nWhat )
{
DBG_CHKTHIS(FormattedField, NULL);
m_pLastOutputColor = NULL;
if ( ( 0 != ( _nWhat & FCT_FORMATTER ) ) && m_pFormatter )
m_pFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_INTL_FORMAT );
// 95845 - 03.04.2002 - fs@openoffice.org
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::Commit()
{
// remember the old text
String sOld( GetText() );
// do the reformat
ReFormat();
// did the text change?
if ( GetText() != sOld )
{ // consider the field as modified
Modify();
// but we have the most recent value now
m_bValueDirty = FALSE;
}
}
//------------------------------------------------------------------------------
void FormattedField::ReFormat()
{
if (!IsEmptyFieldEnabled() || GetText().Len())
if (TreatingAsNumber())
{
double dValue = GetValue();
if ( m_bEnableNaN && ::rtl::math::isNan( dValue ) )
return;
ImplSetValue( dValue, TRUE );
}
else
SetTextFormatted(GetTextValue());
}
//------------------------------------------------------------------------------
long FormattedField::Notify(NotifyEvent& rNEvt)
{
DBG_CHKTHIS(FormattedField, NULL);
if ((rNEvt.GetType() == EVENT_KEYINPUT) && !IsReadOnly())
{
const KeyEvent& rKEvt = *rNEvt.GetKeyEvent();
USHORT nMod = rKEvt.GetKeyCode().GetModifier();
switch ( rKEvt.GetKeyCode().GetCode() )
{
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN:
if (!nMod && ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// the base class would translate this into calls to Up/Down/First/Last,
// but we don't want this if we are text-formatted
return 1;
}
}
}
if ((rNEvt.GetType() == EVENT_COMMAND) && !IsReadOnly())
{
const CommandEvent* pCommand = rNEvt.GetCommandEvent();
if (pCommand->GetCommand() == COMMAND_WHEEL)
{
const CommandWheelData* pData = rNEvt.GetCommandEvent()->GetWheelData();
if ((pData->GetMode() == COMMAND_WHEEL_SCROLL) && ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// same as above : prevent the base class from doing Up/Down-calls
// (normally I should put this test into the Up/Down methods itself, shouldn't I ?)
// FS - 71553 - 19.01.00
return 1;
}
}
}
if (rNEvt.GetType() == EVENT_LOSEFOCUS)
{
// Sonderbehandlung fuer leere Texte
if (GetText().Len() == 0)
{
if (!IsEmptyFieldEnabled())
{
if (TreatingAsNumber())
{
ImplSetValue(m_dCurrentValue, TRUE);
Modify();
}
else
{
String sNew = GetTextValue();
if (sNew.Len())
SetTextFormatted(sNew);
else
SetTextFormatted(m_sDefaultText);
}
m_bValueDirty = FALSE;
}
}
else
{
Commit();
}
}
return SpinField::Notify( rNEvt );
}
//------------------------------------------------------------------------------
void FormattedField::SetMinValue(double dMin)
{
DBG_CHKTHIS(FormattedField, NULL);
DBG_ASSERT(m_bTreatAsNumber, "FormattedField::SetMinValue : only to be used in numeric mode !");
m_dMinValue = dMin;
m_bHasMin = TRUE;
// fuer die Ueberpruefung des aktuellen Wertes an der neuen Grenze -> ImplSetValue
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::SetMaxValue(double dMax)
{
DBG_CHKTHIS(FormattedField, NULL);
DBG_ASSERT(m_bTreatAsNumber, "FormattedField::SetMaxValue : only to be used in numeric mode !");
m_dMaxValue = dMax;
m_bHasMax = TRUE;
// fuer die Ueberpruefung des aktuellen Wertes an der neuen Grenze -> ImplSetValue
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::SetTextValue(const XubString& rText)
{
DBG_CHKTHIS(FormattedField, NULL);
SetText(rText);
ReFormat();
}
//------------------------------------------------------------------------------
void FormattedField::EnableEmptyField(BOOL bEnable)
{
DBG_CHKTHIS(FormattedField, NULL);
if (bEnable == m_bEnableEmptyField)
return;
m_bEnableEmptyField = bEnable;
if (!m_bEnableEmptyField && GetText().Len()==0)
ImplSetValue(m_dCurrentValue, TRUE);
}
//------------------------------------------------------------------------------
void FormattedField::ImplSetValue(double dVal, BOOL bForce)
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMin && (dVal<m_dMinValue))
dVal = m_dMinValue;
if (m_bHasMax && (dVal>m_dMaxValue))
dVal = m_dMaxValue;
if (!bForce && (dVal == GetValue()))
return;
DBG_ASSERT(ImplGetFormatter() != NULL, "FormattedField::ImplSetValue : can't set a value without a formatter !");
m_bValueDirty = FALSE;
m_dCurrentValue = dVal;
String sNewText;
if (ImplGetFormatter()->IsTextFormat(m_nFormatKey))
{
// zuerst die Zahl als String im Standard-Format
String sTemp;
ImplGetFormatter()->GetOutputString(dVal, 0, sTemp, &m_pLastOutputColor);
// dann den String entsprechend dem Text-Format
ImplGetFormatter()->GetOutputString(sTemp, m_nFormatKey, sNewText, &m_pLastOutputColor);
}
else
{
ImplGetFormatter()->GetOutputString(dVal, m_nFormatKey, sNewText, &m_pLastOutputColor);
}
ImplSetText(sNewText, NULL);
m_bValueDirty = FALSE;
DBG_ASSERT(CheckText(sNewText), "FormattedField::ImplSetValue : formatted string doesn't match the criteria !");
}
//------------------------------------------------------------------------------
BOOL FormattedField::ImplGetValue(double& dNewVal)
{
DBG_CHKTHIS(FormattedField, NULL);
dNewVal = m_dCurrentValue;
if (!m_bValueDirty)
return TRUE;
dNewVal = m_dDefaultValue;
String sText(GetText());
if (!sText.Len())
return TRUE;
DBG_ASSERT(ImplGetFormatter() != NULL, "FormattedField::ImplGetValue : can't give you a current value without a formatter !");
ULONG nFormatKey = m_nFormatKey; // IsNumberFormat veraendert den FormatKey ...
if (ImplGetFormatter()->IsTextFormat(nFormatKey) && m_bTreatAsNumber)
// damit wir in einem als Text formatierten Feld trotzdem eine Eingabe wie '1,1' erkennen ...
nFormatKey = 0;
// Sonderbehandlung fuer %-Formatierung
if (ImplGetFormatter()->GetType(m_nFormatKey) == NUMBERFORMAT_PERCENT)
{
// the language of our format
LanguageType eLanguage = m_pFormatter->GetEntry(m_nFormatKey)->GetLanguage();
// the default number format for this language
ULONG nStandardNumericFormat = m_pFormatter->GetStandardFormat(NUMBERFORMAT_NUMBER, eLanguage);
ULONG nTempFormat = nStandardNumericFormat;
double dTemp;
if (m_pFormatter->IsNumberFormat(sText, nTempFormat, dTemp) &&
NUMBERFORMAT_NUMBER == m_pFormatter->GetType(nTempFormat))
// der String entspricht einer Number-Formatierung, hat also nur kein %
// -> append it
sText += '%';
// (with this, a input of '3' becomes '3%', which then by the formatter is translated
// into 0.03. Without this, the formatter would give us the double 3 for an input '3',
// which equals 300 percent.
}
if (!ImplGetFormatter()->IsNumberFormat(sText, nFormatKey, dNewVal))
return FALSE;
if (m_bHasMin && (dNewVal<m_dMinValue))
dNewVal = m_dMinValue;
if (m_bHasMax && (dNewVal>m_dMaxValue))
dNewVal = m_dMaxValue;
return TRUE;
}
//------------------------------------------------------------------------------
void FormattedField::SetValue(double dVal)
{
DBG_CHKTHIS(FormattedField, NULL);
ImplSetValue(dVal, m_bValueDirty);
}
//------------------------------------------------------------------------------
double FormattedField::GetValue()
{
DBG_CHKTHIS(FormattedField, NULL);
if ( !ImplGetValue( m_dCurrentValue ) )
if ( m_bEnableNaN )
::rtl::math::setNan( &m_dCurrentValue );
else
m_dCurrentValue = m_dDefaultValue;
m_bValueDirty = FALSE;
return m_dCurrentValue;
}
//------------------------------------------------------------------------------
void FormattedField::Up()
{
DBG_CHKTHIS(FormattedField, NULL);
SetValue(GetValue() + m_dSpinSize);
// das setValue handelt Bereichsueberschreitungen (min/max) automatisch
SetModifyFlag();
Modify();
SpinField::Up();
}
//------------------------------------------------------------------------------
void FormattedField::Down()
{
DBG_CHKTHIS(FormattedField, NULL);
SetValue(GetValue() - m_dSpinSize);
SetModifyFlag();
Modify();
SpinField::Down();
}
//------------------------------------------------------------------------------
void FormattedField::First()
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMin)
{
SetValue(m_dMinValue);
SetModifyFlag();
Modify();
}
SpinField::First();
}
//------------------------------------------------------------------------------
void FormattedField::Last()
{
DBG_CHKTHIS(FormattedField, NULL);
if (m_bHasMax)
{
SetValue(m_dMaxValue);
SetModifyFlag();
Modify();
}
SpinField::Last();
}
//==============================================================================
//------------------------------------------------------------------------------
DoubleNumericField::~DoubleNumericField()
{
#ifdef REGEXP_SUPPORT
delete m_pConformanceTester;
#else
delete m_pNumberValidator;
#endif
}
//------------------------------------------------------------------------------
void DoubleNumericField::FormatChanged(FORMAT_CHANGE_TYPE nWhat)
{
ResetConformanceTester();
FormattedField::FormatChanged(nWhat);
}
//------------------------------------------------------------------------------
BOOL DoubleNumericField::CheckText(const XubString& sText) const
{
// We'd like to implement this using the NumberFormatter::IsNumberFormat, but unfortunately, this doesn't
// recognize fragments of numbers (like, for instance "1e", which happens during entering e.g. "1e10")
// Thus, the roundabout way via a regular expression
#ifdef REGEXP_SUPPORT
if (!sText.Len())
return TRUE;
String sForceComplete = '_';
sForceComplete += sText;
sForceComplete += '_';
USHORT nStart = 0, nEnd = sForceComplete.Len();
BOOL bFound = m_pConformanceTester->SearchFrwrd(sForceComplete, &nStart, &nEnd);
if (bFound && (nStart == 0) && (nEnd == sForceComplete.Len()))
return TRUE;
return FALSE;
#else
return m_pNumberValidator->isValidNumericFragment( sText );
#endif
}
//------------------------------------------------------------------------------
void DoubleNumericField::ResetConformanceTester()
{
// the thousands and the decimal separator are language dependent
const SvNumberformat* pFormatEntry = ImplGetFormatter()->GetEntry(m_nFormatKey);
sal_Unicode cSeparatorThousand = ',';
sal_Unicode cSeparatorDecimal = '.';
if (pFormatEntry)
{
String aLanguage, aCountry, aVariant;
ConvertLanguageToIsoNames( pFormatEntry->GetLanguage(), aLanguage, aCountry );
LocaleDataWrapper aLocaleInfo(::comphelper::getProcessServiceFactory(), Locale( aLanguage, aCountry, aVariant ));
String sSeparator = aLocaleInfo.getNumThousandSep();
if (sSeparator.Len())
cSeparatorThousand = sSeparator.GetBuffer()[0];
sSeparator = aLocaleInfo.getNumDecimalSep();
if (sSeparator.Len())
cSeparatorDecimal = sSeparator.GetBuffer()[0];
}
#ifdef REGEXP_SUPPORT
String sDescription = String::CreateFromAscii(szNumericInput);
String sReplaceWith((sal_Unicode)'\\');
sReplaceWith += cSeparatorThousand;
sDescription.SearchAndReplaceAscii("\\,", sReplaceWith);
sReplaceWith = (sal_Unicode)'\\';
sReplaceWith += cSeparatorDecimal;
sDescription.SearchAndReplaceAscii("\\.", sReplaceWith);
delete m_pConformanceTester;
SearchOptions aParam;
aParam.algorithmType = SearchAlgorithms_REGEXP;
aParam.searchFlag = SearchFlags::ALL_IGNORE_CASE;
aParam.searchString = sDescription;
aParam.transliterateFlags = 0;
String sLanguage, sCountry;
ConvertLanguageToIsoNames( pFormatEntry ? pFormatEntry->GetLanguage() : LANGUAGE_ENGLISH_US, sLanguage, sCountry );
aParam.Locale.Language = sLanguage;
aParam.Locale.Country = sCountry;
m_pConformanceTester = new ::utl::TextSearch(aParam);
#else
delete m_pNumberValidator;
m_pNumberValidator = new validation::NumberValidator( cSeparatorThousand, cSeparatorDecimal );
#endif
}
//==============================================================================
//------------------------------------------------------------------------------
DoubleCurrencyField::DoubleCurrencyField(Window* pParent, WinBits nStyle)
:FormattedField(pParent, nStyle)
,m_bChangingFormat(FALSE)
{
m_bPrependCurrSym = FALSE;
// initialize with a system currency format
m_sCurrencySymbol = SvtSysLocale().GetLocaleData().getCurrSymbol();
UpdateCurrencyFormat();
}
//------------------------------------------------------------------------------
DoubleCurrencyField::DoubleCurrencyField(Window* pParent, const ResId& rResId)
:FormattedField(pParent, rResId)
,m_bChangingFormat(FALSE)
{
m_bPrependCurrSym = FALSE;
// initialize with a system currency format
m_sCurrencySymbol = SvtSysLocale().GetLocaleData().getCurrSymbol();
UpdateCurrencyFormat();
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::FormatChanged(FORMAT_CHANGE_TYPE nWhat)
{
if (m_bChangingFormat)
{
FormattedField::FormatChanged(nWhat);
return;
}
switch (nWhat)
{
case FCT_FORMATTER:
case FCT_PRECISION:
case FCT_THOUSANDSSEP:
// the aspects which changed don't take our currency settings into account (in fact, they most probably
// destroyed them)
UpdateCurrencyFormat();
break;
case FCT_KEYONLY:
DBG_ERROR("DoubleCurrencyField::FormatChanged : somebody modified my key !");
// We always build our own format from the settings we get via special methods (setCurrencySymbol etc.).
// Nobody but ourself should modifiy the format key directly !
break;
}
FormattedField::FormatChanged(nWhat);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::setCurrencySymbol(const String& _sSymbol)
{
if (m_sCurrencySymbol == _sSymbol)
return;
m_sCurrencySymbol = _sSymbol;
UpdateCurrencyFormat();
FormatChanged(FCT_CURRENCY_SYMBOL);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::setPrependCurrSym(BOOL _bPrepend)
{
if (m_bPrependCurrSym == _bPrepend)
return;
m_bPrependCurrSym = _bPrepend;
UpdateCurrencyFormat();
FormatChanged(FCT_CURRSYM_POSITION);
}
//------------------------------------------------------------------------------
void DoubleCurrencyField::UpdateCurrencyFormat()
{
// the old settings
XubString sOldFormat;
LanguageType eLanguage;
GetFormat(sOldFormat, eLanguage);
BOOL bThSep = GetThousandsSep();
USHORT nDigits = GetDecimalDigits();
// build a new format string with the base class' and my own settings
String aLanguage, aCountry, aVariant;
ConvertLanguageToIsoNames( eLanguage, aLanguage, aCountry );
LocaleDataWrapper aLocaleInfo(::comphelper::getProcessServiceFactory(), Locale( aLanguage, aCountry, aVariant ));
XubString sNewFormat;
if (bThSep)
{
sNewFormat = '#';
sNewFormat += aLocaleInfo.getNumThousandSep();
sNewFormat.AppendAscii("##0");
}
else
sNewFormat = '0';
if (nDigits)
{
sNewFormat += aLocaleInfo.getNumDecimalSep();
XubString sTemp;
sTemp.Fill(nDigits, '0');
sNewFormat += sTemp;
}
if (getPrependCurrSym())
{
XubString sSymbol = getCurrencySymbol();
sSymbol.EraseLeadingChars(' ');
sSymbol.EraseTrailingChars(' ');
XubString sTemp = String::CreateFromAscii("[$");
sTemp += sSymbol;
sTemp.AppendAscii("] ");
sTemp += sNewFormat;
// for negative values : $ -0.00, not -$ 0.00 ...
// (the real solution would be a possibility to choose a "positive currency format" and a "negative currency format" ...
// But not now ... (and hey, you could take a formatted field for this ....))
// FS - 31.03.00 74642
sTemp.AppendAscii(";[$");
sTemp += sSymbol;
sTemp.AppendAscii("] -");
sTemp += sNewFormat;
sNewFormat = sTemp;
}
else
{
XubString sTemp = getCurrencySymbol();
sTemp.EraseLeadingChars(' ');
sTemp.EraseTrailingChars(' ');
sNewFormat += String::CreateFromAscii(" [$");
sNewFormat += sTemp;
sNewFormat += ']';
}
// set this new basic format
m_bChangingFormat = TRUE;
SetFormat(sNewFormat, eLanguage);
m_bChangingFormat = FALSE;
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svarray.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2007-07-18 08:55:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_BOOLS
#define _SVSTDARR_BYTES
#define _SVSTDARR_ULONGS
#define _SVSTDARR_ULONGSSORT
#define _SVSTDARR_USHORTS
#define _SVSTDARR_LONGS
#define _SVSTDARR_LONGSSORT
#define _SVSTDARR_SHORTS
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_USHORTSSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#define _SVSTDARR_XUB_STRLENSORT
#include <svtools/svstdarr.hxx>
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
SV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)
USHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
USHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvBools, BOOL )
SV_IMPL_VARARR( SvBytes, BYTE )
SV_IMPL_VARARR( SvULongs, ULONG )
SV_IMPL_VARARR( SvUShorts, USHORT )
SV_IMPL_VARARR( SvLongs, long)
SV_IMPL_VARARR( SvShorts, short )
SV_IMPL_VARARR_SORT( SvULongsSort, ULONG )
SV_IMPL_VARARR_SORT( SvLongsSort, long )
SV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )
SV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
BOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const
{
register USHORT nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
USHORT nP;
const USHORT * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
BOOL SvUShortsSort::Insert( const USHORT aE )
{
USHORT nP;
BOOL bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
BOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )
{
BOOL bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const USHORT* pE, USHORT nL)
{
USHORT nP;
for( USHORT n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const USHORT aE, USHORT nL )
{
USHORT nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
INTEGRATION: CWS changefileheader (1.7.222); FILE MERGED
2008/04/01 15:45:16 thb 1.7.222.2: #i85898# Stripping all external header guards
2008/03/31 13:02:15 rt 1.7.222.1: #i87441# Change license header to LPGL v3.
/*************************************************************************
*
* 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: svarray.cxx,v $
* $Revision: 1.8 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_BOOLS
#define _SVSTDARR_BYTES
#define _SVSTDARR_ULONGS
#define _SVSTDARR_ULONGSSORT
#define _SVSTDARR_USHORTS
#define _SVSTDARR_LONGS
#define _SVSTDARR_LONGSSORT
#define _SVSTDARR_SHORTS
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_USHORTSSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#define _SVSTDARR_XUB_STRLENSORT
#include <svtools/svstdarr.hxx>
#include <tools/string.hxx>
#include <tools/debug.hxx>
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
SV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)
USHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
USHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvBools, BOOL )
SV_IMPL_VARARR( SvBytes, BYTE )
SV_IMPL_VARARR( SvULongs, ULONG )
SV_IMPL_VARARR( SvUShorts, USHORT )
SV_IMPL_VARARR( SvLongs, long)
SV_IMPL_VARARR( SvShorts, short )
SV_IMPL_VARARR_SORT( SvULongsSort, ULONG )
SV_IMPL_VARARR_SORT( SvLongsSort, long )
SV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )
SV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
BOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const
{
register USHORT nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
USHORT nP;
const USHORT * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
BOOL SvUShortsSort::Insert( const USHORT aE )
{
USHORT nP;
BOOL bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
BOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )
{
BOOL bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const USHORT* pE, USHORT nL)
{
USHORT nP;
for( USHORT n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const USHORT aE, USHORT nL )
{
USHORT nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
|
/*************************************************************************
*
* $RCSfile: numfmuno.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-05-24 12:19:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _NUMFMUNO_HXX
#define _NUMFMUNO_HXX
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATPREVIEWER_HPP_
#include <com/sun/star/util/XNumberFormatPreviewer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATS_HPP_
#include <com/sun/star/util/XNumberFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTYPES_HPP_
#include <com/sun/star/util/XNumberFormatTypes.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_
#include <com/sun/star/beans/XPropertyAccess.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
class SvNumberformat;
class SvNumberFormatter;
class SvNumberFormatsSupplierObj;
// SvNumberFormatterServiceObj wird global als Service angemeldet
class SvNumberFormatterServiceObj : public cppu::WeakImplHelper3<
com::sun::star::util::XNumberFormatter,
com::sun::star::util::XNumberFormatPreviewer,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatterServiceObj();
virtual ~SvNumberFormatterServiceObj();
// XNumberFormatter
virtual void SAL_CALL attachNumberFormatsSupplier(
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& xSupplier )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >
SAL_CALL getNumberFormatsSupplier()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL detectNumberFormat( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::util::NotNumericException,
::com::sun::star::uno::RuntimeException);
virtual double SAL_CALL convertStringToNumber( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::util::NotNumericException,
::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL convertNumberToString( sal_Int32 nKey, double fValue )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryColorForNumber( sal_Int32 nKey,
double fValue, ::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL formatString( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryColorForString( sal_Int32 nKey,
const ::rtl::OUString& aString,
::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getInputString( sal_Int32 nKey, double fValue )
throw(::com::sun::star::uno::RuntimeException);
// XNumberFormatPreviewer
virtual ::rtl::OUString SAL_CALL convertNumberToPreviewString(
const ::rtl::OUString& aFormat, double fValue,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bAllowEnglish )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryPreviewColorForNumber(
const ::rtl::OUString& aFormat, double fValue,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bAllowEnglish,
::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatsObj : public cppu::WeakImplHelper3<
com::sun::star::util::XNumberFormats,
com::sun::star::util::XNumberFormatTypes,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatsObj();
SvNumberFormatsObj(SvNumberFormatsSupplierObj* pParent);
virtual ~SvNumberFormatsObj();
// XNumberFormats
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SAL_CALL
getByKey( sal_Int32 nKey ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL queryKeys( sal_Int16 nType,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bCreate )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL queryKey( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bScan )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL addNew( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL addNewConverted( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale,
const ::com::sun::star::lang::Locale& nNewLocale )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeByKey( sal_Int32 nKey ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL generateFormat( sal_Int32 nBaseKey,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bThousands,
sal_Bool bRed, sal_Int16 nDecimals, sal_Int16 nLeading )
throw(::com::sun::star::uno::RuntimeException);
// XNumberFormatTypes
virtual sal_Int32 SAL_CALL getStandardIndex( const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getStandardFormat( sal_Int16 nType,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getFormatIndex( sal_Int16 nIndex,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isTypeCompatible( sal_Int16 nOldType, sal_Int16 nNewType )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getFormatForLocale( sal_Int32 nKey,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatObj : public cppu::WeakImplHelper3<
com::sun::star::beans::XPropertySet,
com::sun::star::beans::XPropertyAccess,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
ULONG nKey;
public:
SvNumberFormatObj(SvNumberFormatsSupplierObj* pParent, ULONG nK);
virtual ~SvNumberFormatObj();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(
const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& xListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XPropertyAccess
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL
getPropertyValues() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& aProps )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatSettingsObj : public cppu::WeakImplHelper2<
com::sun::star::beans::XPropertySet,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatSettingsObj(SvNumberFormatsSupplierObj* pParent);
virtual ~SvNumberFormatSettingsObj();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(
const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& xListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
#endif
INTEGRATION: CWS ooo19126 (1.2.492); FILE MERGED
2005/09/05 14:53:55 rt 1.2.492.1: #i54170# Change license header: remove SISSL
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: numfmuno.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:33:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _NUMFMUNO_HXX
#define _NUMFMUNO_HXX
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATPREVIEWER_HPP_
#include <com/sun/star/util/XNumberFormatPreviewer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATS_HPP_
#include <com/sun/star/util/XNumberFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTYPES_HPP_
#include <com/sun/star/util/XNumberFormatTypes.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_
#include <com/sun/star/beans/XPropertyAccess.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
class SvNumberformat;
class SvNumberFormatter;
class SvNumberFormatsSupplierObj;
// SvNumberFormatterServiceObj wird global als Service angemeldet
class SvNumberFormatterServiceObj : public cppu::WeakImplHelper3<
com::sun::star::util::XNumberFormatter,
com::sun::star::util::XNumberFormatPreviewer,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatterServiceObj();
virtual ~SvNumberFormatterServiceObj();
// XNumberFormatter
virtual void SAL_CALL attachNumberFormatsSupplier(
const ::com::sun::star::uno::Reference<
::com::sun::star::util::XNumberFormatsSupplier >& xSupplier )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >
SAL_CALL getNumberFormatsSupplier()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL detectNumberFormat( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::util::NotNumericException,
::com::sun::star::uno::RuntimeException);
virtual double SAL_CALL convertStringToNumber( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::util::NotNumericException,
::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL convertNumberToString( sal_Int32 nKey, double fValue )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryColorForNumber( sal_Int32 nKey,
double fValue, ::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL formatString( sal_Int32 nKey, const ::rtl::OUString& aString )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryColorForString( sal_Int32 nKey,
const ::rtl::OUString& aString,
::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getInputString( sal_Int32 nKey, double fValue )
throw(::com::sun::star::uno::RuntimeException);
// XNumberFormatPreviewer
virtual ::rtl::OUString SAL_CALL convertNumberToPreviewString(
const ::rtl::OUString& aFormat, double fValue,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bAllowEnglish )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::util::Color SAL_CALL queryPreviewColorForNumber(
const ::rtl::OUString& aFormat, double fValue,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bAllowEnglish,
::com::sun::star::util::Color aDefaultColor )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatsObj : public cppu::WeakImplHelper3<
com::sun::star::util::XNumberFormats,
com::sun::star::util::XNumberFormatTypes,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatsObj();
SvNumberFormatsObj(SvNumberFormatsSupplierObj* pParent);
virtual ~SvNumberFormatsObj();
// XNumberFormats
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SAL_CALL
getByKey( sal_Int32 nKey ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL queryKeys( sal_Int16 nType,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bCreate )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL queryKey( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bScan )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL addNew( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL addNewConverted( const ::rtl::OUString& aFormat,
const ::com::sun::star::lang::Locale& nLocale,
const ::com::sun::star::lang::Locale& nNewLocale )
throw(::com::sun::star::util::MalformedNumberFormatException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeByKey( sal_Int32 nKey ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL generateFormat( sal_Int32 nBaseKey,
const ::com::sun::star::lang::Locale& nLocale, sal_Bool bThousands,
sal_Bool bRed, sal_Int16 nDecimals, sal_Int16 nLeading )
throw(::com::sun::star::uno::RuntimeException);
// XNumberFormatTypes
virtual sal_Int32 SAL_CALL getStandardIndex( const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getStandardFormat( sal_Int16 nType,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getFormatIndex( sal_Int16 nIndex,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isTypeCompatible( sal_Int16 nOldType, sal_Int16 nNewType )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getFormatForLocale( sal_Int32 nKey,
const ::com::sun::star::lang::Locale& nLocale )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatObj : public cppu::WeakImplHelper3<
com::sun::star::beans::XPropertySet,
com::sun::star::beans::XPropertyAccess,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
ULONG nKey;
public:
SvNumberFormatObj(SvNumberFormatsSupplierObj* pParent, ULONG nK);
virtual ~SvNumberFormatObj();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(
const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& xListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XPropertyAccess
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL
getPropertyValues() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& aProps )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
class SvNumberFormatSettingsObj : public cppu::WeakImplHelper2<
com::sun::star::beans::XPropertySet,
com::sun::star::lang::XServiceInfo>
{
private:
SvNumberFormatsSupplierObj* pSupplier;
public:
SvNumberFormatSettingsObj(SvNumberFormatsSupplierObj* pParent);
virtual ~SvNumberFormatSettingsObj();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >
SAL_CALL getPropertySetInfo( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Any& aValue )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(
const ::rtl::OUString& PropertyName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& xListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertyChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName,
const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XVetoableChangeListener >& aListener )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
#endif
|
/*************************************************************************
*
* $RCSfile: zforfind.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: er $ $Date: 2001-08-06 10:04:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <ctype.h>
#include <stdlib.h>
#include <float.h>
#include <errno.h>
#ifndef _INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _TOOLS_SOLMATH_HXX
#include <tools/solmath.hxx>
#endif
#ifndef _SYSTEM_HXX //autogen
#include <vcl/system.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX
#include <unotools/calendarwrapper.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_CALENDARFIELDINDEX_HPP_
#include <com/sun/star/i18n/CalendarFieldIndex.hpp>
#endif
#include "zforlist.hxx" // NUMBERFORMAT_XXX
#include "zforscan.hxx"
#include "zformat.hxx"
#define _ZFORFIND_CXX
#include "zforfind.hxx"
#undef _ZFORFIND_CXX
// use faster isdigit() if possible
//#define MyIsdigit(c) (pFormatter->GetCharClass()->isDigit(c))
#define MyIsdigit(c) ((c) < 256 && isdigit((unsigned char)(c)))
//---------------------------------------------------------------------------
// Konstruktor
ImpSvNumberInputScan::ImpSvNumberInputScan( SvNumberFormatter* pFormatterP )
:
pUpperMonthText( NULL ),
pUpperAbbrevMonthText( NULL ),
pUpperDayText( NULL ),
pUpperAbbrevDayText( NULL )
{
pFormatter = pFormatterP;
pNullDate = new Date(30,12,1899);
nYear2000 = SvNumberFormatter::GetYear2000Default();
Reset();
ChangeIntl();
}
//---------------------------------------------------------------------------
// Destruktor
ImpSvNumberInputScan::~ImpSvNumberInputScan()
{
Reset();
delete pNullDate;
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
}
//---------------------------------------------------------------------------
// Reset
void ImpSvNumberInputScan::Reset()
{
#if 0
// ER 16.06.97 18:56 Vorbelegung erfolgt jetzt in NumberStringDivision,
// wozu immer alles loeschen wenn einiges wieder benutzt oder gar nicht
// gebraucht wird..
for (USHORT i = 0; i < SV_MAX_ANZ_INPUT_STRINGS; i++)
{
sStrArray[i].Erase();
nNums[i] = SV_MAX_ANZ_INPUT_STRINGS-1;
IsNum[i] = FALSE;
}
#endif
nMonth = 0;
nMonthPos = 0;
nTimePos = 0;
nSign = 0;
nESign = 0;
nDecPos = 0;
nNegCheck = 0;
nAnzStrings = 0;
nAnzNums = 0;
nThousand = 0;
eScannedType = NUMBERFORMAT_UNDEFINED;
nAmPm = 0;
nPosThousandString = 0;
nLogical = 0;
nStringScanNumFor = 0;
nStringScanSign = 0;
}
//---------------------------------------------------------------------------
// StringToDouble
//
// Only simple unsigned floating point values without any error detection,
// decimal separator has to be '.'
double ImpSvNumberInputScan::StringToDouble( const String& rStr, BOOL bForceFraction )
{
double fNum = 0.0;
double fFrac = 0.0;
int nExp = 0;
xub_StrLen nPos = 0;
xub_StrLen nLen = rStr.Len();
BOOL bPreSep = !bForceFraction;
while (nPos < nLen)
{
if (rStr.GetChar(nPos) == '.')
bPreSep = FALSE;
else if (bPreSep)
fNum = fNum * 10.0 + (double) (rStr.GetChar(nPos) - '0');
else
{
fFrac = fFrac * 10.0 + (double) (rStr.GetChar(nPos) - '0');
--nExp;
}
nPos++;
}
if ( fFrac )
return fNum + SolarMath::Pow10Exp( fFrac, nExp );
return fNum;
}
//---------------------------------------------------------------------------
// NextNumberStringSymbol
//
// Zerlegt die Eingabe in Zahlen und Strings fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = GetChar
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// GetChar | Ziffer | Symbol=Zeichen | GetValue
// | Sonst | Symbol=Zeichen | GetString
//---------------|-------------------+-----------------------+---------------
// GetValue | Ziffer | Symbol=Symbol+Zeichen | GetValue
// | Sonst | Dec(CharPos) | Stop
//---------------+-------------------+-----------------------+---------------
// GetString | Ziffer | Dec(CharPos) | Stop
// | Sonst | Symbol=Symbol+Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
enum ScanState // States der Turing-Maschine
{
SsStop = 0,
SsStart = 1,
SsGetValue = 2,
SsGetString = 3
};
BOOL ImpSvNumberInputScan::NextNumberStringSymbol(
const sal_Unicode*& pStr,
String& rSymbol )
{
BOOL isNumber = FALSE;
sal_Unicode cToken;
ScanState eState = SsStart;
register const sal_Unicode* pHere = pStr;
register xub_StrLen nChars = 0;
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( MyIsdigit( cToken ) )
{
eState = SsGetValue;
isNumber = TRUE;
}
else
eState = SsGetString;
nChars++;
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetString:
if ( !MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if ( nChars )
rSymbol.Assign( pStr, nChars );
else
rSymbol.Erase();
pStr = pHere;
return isNumber;
}
//---------------------------------------------------------------------------
// SkipThousands
BOOL ImpSvNumberInputScan::SkipThousands(
const sal_Unicode*& pStr,
String& rSymbol )
{
BOOL res = FALSE;
sal_Unicode cToken;
const String& rThSep = pFormatter->GetLocaleData()->getNumThousandSep();
register const sal_Unicode* pHere = pStr;
ScanState eState = SsStart;
xub_StrLen nCounter; // counts 3 digits
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( StringPtrContains( rThSep, pHere-1, 0 ) )
{
nCounter = 0;
eState = SsGetValue;
pHere += rThSep.Len()-1;
}
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
{
rSymbol += cToken;
nCounter++;
if (nCounter == 3)
{
eState = SsStart;
res = TRUE; // .000 combination found
}
}
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if (eState == SsGetValue) // break witth less than 3 digits
{
if ( nCounter )
rSymbol.Erase( rSymbol.Len() - nCounter, nCounter );
pHere -= nCounter + rThSep.Len(); // put back ThSep also
}
pStr = pHere;
return res;
}
//---------------------------------------------------------------------------
// NumberStringDivision
void ImpSvNumberInputScan::NumberStringDivision( const String& rString )
{
register const sal_Unicode* pStr = rString.GetBuffer();
register const sal_Unicode* const pEnd = pStr + rString.Len();
while ( pStr < pEnd && nAnzStrings < SV_MAX_ANZ_INPUT_STRINGS )
{
if ( NextNumberStringSymbol( pStr, sStrArray[nAnzStrings] ) )
{ // Zahl
IsNum[nAnzStrings] = TRUE;
nNums[nAnzNums] = nAnzStrings;
nAnzNums++;
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS - 7 &&
nPosThousandString == 0) // nur einmal
if ( SkipThousands( pStr, sStrArray[nAnzStrings] ) )
nPosThousandString = nAnzStrings;
}
else
{
IsNum[nAnzStrings] = FALSE;
}
nAnzStrings++;
}
}
//---------------------------------------------------------------------------
// Whether rString contains rWhat at nPos
BOOL ImpSvNumberInputScan::StringContainsImpl( const String& rWhat,
const String& rString, xub_StrLen nPos )
{
if ( nPos + rWhat.Len() <= rString.Len() )
return StringPtrContainsImpl( rWhat, rString.GetBuffer(), nPos );
return FALSE;
}
//---------------------------------------------------------------------------
// Whether pString contains rWhat at nPos
BOOL ImpSvNumberInputScan::StringPtrContainsImpl( const String& rWhat,
const sal_Unicode* pString, xub_StrLen nPos )
{
if ( rWhat.Len() == 0 )
return FALSE;
register const sal_Unicode* pWhat = rWhat.GetBuffer();
register const sal_Unicode* const pEnd = pWhat + rWhat.Len();
register const sal_Unicode* pStr = pString + nPos;
while ( pWhat < pEnd )
{
if ( *pWhat != *pStr )
return FALSE;
pWhat++;
pStr++;
}
return TRUE;
}
//---------------------------------------------------------------------------
// SkipChar
//
// ueberspringt genau das angegebene Zeichen
inline BOOL ImpSvNumberInputScan::SkipChar( sal_Unicode c, const String& rString,
xub_StrLen& nPos )
{
if ((nPos < rString.Len()) && (rString.GetChar(nPos) == c))
{
nPos++;
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// SkipBlanks
//
// Ueberspringt Leerzeichen
inline void ImpSvNumberInputScan::SkipBlanks( const String& rString,
xub_StrLen& nPos )
{
if ( nPos < rString.Len() )
{
register const sal_Unicode* p = rString.GetBuffer() + nPos;
while ( *p == ' ' )
{
nPos++;
p++;
}
}
}
//---------------------------------------------------------------------------
// SkipString
//
// jump over rWhat in rString at nPos
inline BOOL ImpSvNumberInputScan::SkipString( const String& rWhat,
const String& rString, xub_StrLen& nPos )
{
if ( StringContains( rWhat, rString, nPos ) )
{
nPos += rWhat.Len();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetThousandSep
//
// erkennt genau .111 als Tausenderpunkt
inline BOOL ImpSvNumberInputScan::GetThousandSep(
const String& rString,
xub_StrLen& nPos,
USHORT nStringPos )
{
const String& rSep = pFormatter->GetLocaleData()->getNumThousandSep();
if ( rString == rSep // nothing else
&& nStringPos < nAnzStrings - 1 // safety first!
&& IsNum[nStringPos+1] // number follows
&& ( sStrArray[nStringPos+1].Len() == 3 // with 3 digits
|| nPosThousandString == nStringPos+1 ) ) // or concatenated
{
nPos += rSep.Len();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetLogical
//
// Umwandlung Text in logischen Wert
// "TRUE" => 1:
// "FALSE"=> -1:
// sonst => 0:
short ImpSvNumberInputScan::GetLogical( const String& rString )
{
short res;
if (rString.Len() < 4) // kein Platz fuer mind 4 Buch.
res = 0;
else
{
const ImpSvNumberformatScan* pFS = pFormatter->GetFormatScanner();
if ( rString == pFS->GetTrueString() )
res = 1;
else if ( rString == pFS->GetFalseString() )
res = -1;
else
res = 0;
}
return res;
}
//---------------------------------------------------------------------------
// GetMonth
//
// Converts a string containing a month name (JAN, January) at nPos into the
// month number (negative if abbreviated), returns 0 if nothing found
short ImpSvNumberInputScan::GetMonth( const String& rString, xub_StrLen& nPos )
{
short res = 0; // no month found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nMonths = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
for ( sal_Int16 i = 0; i < nMonths; i++ )
{
if ( StringContains( pUpperMonthText[i], rString, nPos ) )
{ // full names first
nPos += pUpperMonthText[i].Len();
res = i+1;
break; // for
}
else if ( StringContains( pUpperAbbrevMonthText[i], rString, nPos ) )
{ // abbreviated
nPos += pUpperAbbrevMonthText[i].Len();
res = -(i+1); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetDayOfWeek
//
// Converts a string containing a DayOfWeek name (Mon, Monday) at nPos into the
// DayOfWeek number + 1 (negative if abbreviated), returns 0 if nothing found
short ImpSvNumberInputScan::GetDayOfWeek( const String& rString, xub_StrLen& nPos )
{
short res = 0; // no day found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nDays = pFormatter->GetCalendar()->getNumberOfDaysInWeek();
for ( sal_Int16 i = 0; i < nDays; i++ )
{
if ( StringContains( pUpperDayText[i], rString, nPos ) )
{ // full names first
nPos += pUpperDayText[i].Len();
res = i + 1;
break; // for
}
if ( StringContains( pUpperAbbrevDayText[i], rString, nPos ) )
{ // abbreviated
nPos += pUpperAbbrevDayText[i].Len();
res = -(i + 1); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetCurrency
//
// Lesen eines Waehrungssysmbols
// '$' => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::GetCurrency( const String& rString, xub_StrLen& nPos,
const SvNumberformat* pFormat )
{
if ( rString.Len() > nPos )
{
if ( !aUpperCurrSymbol.Len() )
{ // if no format specified the currency of the initialized formatter
LanguageType eLang = (pFormat ? pFormat->GetLanguage() :
pFormatter->GetLanguage());
aUpperCurrSymbol = pFormatter->GetCharClass()->upper(
SvNumberFormatter::GetCurrencyEntry( eLang ).GetSymbol() );
}
if ( StringContains( aUpperCurrSymbol, rString, nPos ) )
{
nPos += aUpperCurrSymbol.Len();
return TRUE;
}
if ( pFormat )
{
String aSymbol, aExtension;
if ( pFormat->GetNewCurrencySymbol( aSymbol, aExtension ) )
{
if ( aSymbol.Len() <= rString.Len() - nPos )
{
pFormatter->GetCharClass()->toUpper( aSymbol );
if ( StringContains( aSymbol, rString, nPos ) )
{
nPos += aSymbol.Len();
return TRUE;
}
}
}
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetTimeAmPm
//
// Lesen des Zeitsymbols (AM od. PM) f. kurze Zeitangabe
//
// Rueckgabe:
// "AM" od. "PM" => TRUE
// sonst => FALSE
//
// nAmPos:
// "AM" => 1
// "PM" => -1
// sonst => 0
BOOL ImpSvNumberInputScan::GetTimeAmPm( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const CharClass* pChr = pFormatter->GetCharClass();
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
if ( StringContains( pChr->upper( pLoc->getTimeAM() ), rString, nPos ) )
{
nAmPm = 1;
nPos += pLoc->getTimeAM().Len();
return TRUE;
}
else if ( StringContains( pChr->upper( pLoc->getTimePM() ), rString, nPos ) )
{
nAmPm = -1;
nPos += pLoc->getTimePM().Len();
return TRUE;
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetDecSep
//
// Lesen eines Dezimaltrenners (',')
// ',' => TRUE
// sonst => FALSE
inline BOOL ImpSvNumberInputScan::GetDecSep( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const String& rSep = pFormatter->GetLocaleData()->getNumDecimalSep();
if ( rString.Equals( rSep, nPos, rSep.Len() ) )
{
nPos += rSep.Len();
return TRUE;
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetSign
//
// Lesen eines Vorzeichens, auch Klammer !?!
// '+' => 1
// '-' => -1
// '(' => -1, nNegCheck = 1
// sonst => 0
short ImpSvNumberInputScan::GetSign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
break;
case '(': // '(' aehnlich wie '-' ?!?
nNegCheck = 1;
//! fallthru
case '-':
nPos++;
return -1;
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetESign
//
// Lesen eines Vorzeichens, gedacht fuer Exponent ?!?
// '+' => 1
// '-' => -1
// sonst => 0
short ImpSvNumberInputScan::GetESign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
break;
case '-':
nPos++;
return -1;
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetNextNumber
//
// i zaehlt Strings, j zaehlt Numbers, eigentlich sollte das SkipNumber heissen
inline BOOL ImpSvNumberInputScan::GetNextNumber( USHORT& i, USHORT& j )
{
if ( IsNum[i] )
{
j++;
i++;
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetTimeRef
void ImpSvNumberInputScan::GetTimeRef(
double& fOutNumber,
USHORT nIndex, // j-Wert fuer den ersten Zeitstring der Eingabe (default 0)
USHORT nAnz ) // Anzahl der Zeitstrings
{
sal_Unicode* pChar = NULL;
USHORT nHour;
USHORT nMinute = 0;
USHORT nSecond = 0;
double fSecond100 = 0.0;
USHORT nStartIndex = nIndex;
if (nDecPos == 2 && nAnz == 3) // 20:45,5
nHour = 0;
else
nHour = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
nMinute = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
nSecond = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
fSecond100 = StringToDouble( sStrArray[nNums[nIndex]], TRUE );
if (nAmPm == -1 && nHour != 12) // PM
nHour += 12;
else if (nAmPm == 1 && nHour == 12) // 12 AM
nHour = 0;
fOutNumber = ((double)nHour*3600 +
(double)nMinute*60 +
(double)nSecond +
fSecond100)/86400.0;
}
//---------------------------------------------------------------------------
// ImplGetDay
USHORT ImpSvNumberInputScan::ImplGetDay( USHORT nIndex )
{
USHORT nRes = 0;
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
USHORT nNum = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
if (nNum <= 31)
nRes = nNum;
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetMonth
USHORT ImpSvNumberInputScan::ImplGetMonth( USHORT nIndex )
{
// preset invalid month number
USHORT nRes = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
USHORT nNum = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
if ( 0 < nNum && nNum <= nRes )
nRes = nNum - 1; // zero based for CalendarFieldIndex::MONTH
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetYear
//
// 30 -> 1930, 29 -> 2029, oder 56 -> 1756, 55 -> 1855, ...
USHORT ImpSvNumberInputScan::ImplGetYear( USHORT nIndex )
{
USHORT nYear = 0;
if (sStrArray[nNums[nIndex]].Len() <= 4)
{
nYear = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
nYear = SvNumberFormatter::ExpandTwoDigitYear( nYear, nYear2000 );
}
return nYear;
}
//---------------------------------------------------------------------------
// GetDateRef
BOOL ImpSvNumberInputScan::GetDateRef( Date& aDt, USHORT& nCounter,
const SvNumberformat* pFormat )
{
using namespace ::com::sun::star::i18n;
NfEvalDateFormat eEDF;
int nFormatOrder;
if ( pFormat && ((pFormat->GetType() & NUMBERFORMAT_DATE) == NUMBERFORMAT_DATE) )
{
eEDF = pFormat->ImpGetScan().GetNumberformatter()->GetEvalDateFormat();
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
case NF_EVALDATEFORMAT_FORMAT :
nFormatOrder = 1; // only one loop
break;
default:
nFormatOrder = 2;
}
}
else
{
eEDF = NF_EVALDATEFORMAT_INTL;
nFormatOrder = 1;
}
BOOL res = TRUE;
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
CalendarWrapper* pCal = pFormatter->GetCalendar();
for ( int nTryOrder = 1; nTryOrder <= nFormatOrder; nTryOrder++ )
{
pCal->setGregorianDateTime( aDt );
DateFormat DateFmt;
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
DateFmt = pLoc->getDateFormat();
break;
case NF_EVALDATEFORMAT_FORMAT :
DateFmt = pFormat->GetDateOrder();
break;
case NF_EVALDATEFORMAT_INTL_FORMAT :
if ( nTryOrder == 1 )
DateFmt = pLoc->getDateFormat();
else
DateFmt = pFormat->GetDateOrder();
break;
case NF_EVALDATEFORMAT_FORMAT_INTL :
if ( nTryOrder == 2 )
DateFmt = pLoc->getDateFormat();
else
DateFmt = pFormat->GetDateOrder();
break;
default:
DBG_ERROR( "ImpSvNumberInputScan::GetDateRef: unknown NfEvalDateFormat" );
}
res = TRUE;
nCounter = 0;
switch (nAnzNums) // count of numbers in string
{
case 0: // none
if (nMonthPos) // only month (Jan)
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
}
else
res = FALSE;
break;
case 1: // only one number
nCounter = 1;
switch (nMonthPos) // where is the month
{
case 0: // not found => only day entered
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case 1: // month at the beginning (Jan 01)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case MDY:
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
case 3: // month at the end (10 Jan)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
default:
res = FALSE;
break;
} // switch (nMonthPos)
break;
case 2: // 2 numbers
nCounter = 2;
switch (nMonthPos) // where is the month
{
case 0: // not found
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( !pCal->isValid() ) // 2nd try
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
}
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( !pCal->isValid() ) // 2nd try
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
}
break;
default:
res = FALSE;
break;
}
break;
case 1: // month at the beginning (Jan 01 01)
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
default:
res = FALSE;
break;
}
break;
case 2: // month in the middle (10 Jan 94)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan)
res = FALSE;
break;
} // switch (nMonthPos)
break;
default: // more than two numbers (31.12.94 8:23) (31.12. 8:23)
switch (nMonthPos) // where is the month
{
case 0: // not found
nCounter = 3;
if ( nTimePos > 1 )
{ // find first time number index (should only be 3 or 2 anyway)
for ( USHORT j = 0; j < nAnzNums; j++ )
{
if ( nNums[j] == nTimePos - 2 )
{
nCounter = j;
break; // for
}
}
}
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case YMD:
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(2) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
case 1: // month at the beginning (Jan 01 01 8:23)
nCounter = 2;
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
default:
res = FALSE;
break;
}
break;
case 2: // month in the middle (10 Jan 94 8:23)
nCounter = 2;
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
default:
res = FALSE;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan 8:23)
nCounter = 2;
res = FALSE;
break;
} // switch (nMonthPos)
break;
} // switch (nAnzNums)
if ( res && pCal->isValid() )
{
aDt = pCal->getGregorianDateTime();
nTryOrder = nFormatOrder; // break for
}
else
{
res = FALSE;
aDt = Date(); // next try
}
}
return res;
}
//---------------------------------------------------------------------------
// ScanStartString
//
// ersten String analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanStartString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
short nDayOfWeek;
SkipBlanks(rString, nPos);
if ( nSign = GetSign(rString, nPos) ) // Vorzeichen?
SkipBlanks(rString, nPos);
if ( GetDecSep(rString, nPos) ) // Dezimaltrenner (,) im Startstring
{
nDecPos = 1;
SkipBlanks(rString, nPos);
}
else if ( GetCurrency(rString, nPos, pFormat) ) // Waehrung (DM 1)?
{
eScannedType = NUMBERFORMAT_CURRENCY; // !!! es ist Geld !!!
SkipBlanks(rString, nPos);
if (nSign == 0) // noch kein Vorzeichen
if ( nSign = GetSign(rString, nPos) ) // DM -1
SkipBlanks(rString, nPos);
}
else if ( nMonth = GetMonth(rString, nPos) ) // month (Jan 1)?
{
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
nMonthPos = 1; // month at the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
else if ( nDayOfWeek = GetDayOfWeek( rString, nPos ) )
{ // day of week is just parsed away
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // abbreviated
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
else
{ // full long name
SkipBlanks(rString, nPos);
SkipString( pFormatter->GetLocaleData()->getLongDateDayOfWeekSep(), rString, nPos );
}
SkipBlanks(rString, nPos);
if ( nMonth = GetMonth(rString, nPos) ) // month (Jan 1)?
{
nMonthPos = 1; // month a the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
}
if (nPos < rString.Len()) // noch nicht alles weg
{
// eingegebener StartString gleich StartString im Format?
if ( !ScanStringNumFor( rString, nPos, pFormat, 0 ) )
return FALSE;
}
return TRUE;
}
//---------------------------------------------------------------------------
// ScanMidString
//
// String in der Mitte analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanMidString(
const String& rString,
USHORT nStringPos )
{
xub_StrLen nPos = 0;
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // ,12,4 or 1,E2,1
return FALSE;
else if (nDecPos == 2) // , dup: 12,4,
{
if (bDecSepInDateSeps) // , also date separator
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
else
{
nDecPos = 2; // , in mid string
SkipBlanks(rString, nPos);
}
}
if (SkipChar('/', rString, nPos)) // fraction?
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE; // => jan/31/1994
else if ( eScannedType != NUMBERFORMAT_DATE // analyzed date until now
&& ( eSetType == NUMBERFORMAT_FRACTION // and preset was fraction
|| (nAnzNums == 3 // or 3 numbers
&& nStringPos > 2) ) ) // and what ???
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_FRACTION; // !!! it IS a fraction
}
else
nPos--; // put '/' back
}
if (GetThousandSep(rString, nPos, nStringPos)) // 1,000
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_CURRENCY) // except currency
return FALSE;
nThousand++;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
sal_Unicode cTime = rTime.GetChar(0);
SkipBlanks(rString, nPos);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE;
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan 94
if (nMonth && nTmpMonth) // month dup
return FALSE;
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 2; // month in the middle
// Short month may be abbreviated Jan. or
// #79632# recognize 17-Jan-2001 to be a date
if ( !(nMonth < 0 && (SkipChar( '.', rString, nPos ) ||
SkipChar( '-', rString, nPos ))) )
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // month in the middle (10 Jan 94)
if (nTempMonth)
{
if (nMonth != 0) // month dup
return FALSE;
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
nMonth = nTempMonth;
nMonthPos = 2; // month in the middle
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
if ( SkipChar('E', rString, nPos) // 10E, 10e, 10,Ee
|| SkipChar('e', rString, nPos) )
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_SCIENTIFIC; // !!! it IS scientific
if ( nThousand+2 == nAnzNums // special case 1.E2
&& nDecPos == 2 )
nDecPos = 3; // 1,100.E2 1,100,100.E3
}
nESign = GetESign(rString, nPos); // signed exponent?
SkipBlanks(rString, nPos);
}
if ( SkipString(rTime, rString, nPos) ) // time separator?
{
if (nDecPos) // already , => error
return FALSE;
if ( ( eScannedType == NUMBERFORMAT_DATE // already date type
|| eScannedType == NUMBERFORMAT_DATETIME) // or date time
&& nAnzNums > 3) // and more than 3 numbers? (31.Dez.94 8:23)
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME; // !!! it IS date with time
}
else if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_TIME) // except time
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME; // !!! it IS a time
}
if ( !nTimePos )
nTimePos = nStringPos + 1;
}
// #68232# recognize long date separators like ", " in "September 5, 1999"
if ( nPos < rString.Len() && eScannedType == NUMBERFORMAT_DATE
&& nMonthPos == 1 && pLoc->getLongDateFormat() == MDY )
{
if ( SkipString( pLoc->getLongDateDaySep(), rString, nPos ) )
SkipBlanks( rString, nPos );
}
if (nPos < rString.Len()) // not everything consumed?
return FALSE;
return TRUE;
}
//---------------------------------------------------------------------------
// ScanEndString
//
// Schlussteil analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanEndString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // ,12,4 or 12,E4,
return FALSE;
else if (nDecPos == 2) // , dup: 12,4,
{
if (bDecSepInDateSeps) // , also date sep
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
else
{
nDecPos = 3; // , in end string
SkipBlanks(rString, nPos);
}
}
if ( nSign == 0 // conflict - not signed
&& eScannedType != NUMBERFORMAT_DATE) // and not date
//!? catch time too?
{ // not signed yet
nSign = GetSign(rString, nPos); // 1- DM
if (nNegCheck) // '(' as sign
return FALSE;
}
SkipBlanks(rString, nPos);
if (nNegCheck && SkipChar(')', rString, nPos)) // skip ')' if appropriate
{
nNegCheck = 0;
SkipBlanks(rString, nPos);
}
if ( GetCurrency(rString, nPos, pFormat) ) // currency symbol?
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // currency dup
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_CURRENCY;
} // behind currency a '-' is allowed
if (nSign == 0) // not signed yet
{
nSign = GetSign(rString, nPos); // DM -
SkipBlanks(rString, nPos);
if (nNegCheck) // 3 DM (
return FALSE;
}
if ( nNegCheck && eScannedType == NUMBERFORMAT_CURRENCY
&& SkipChar(')', rString, nPos) )
{
nNegCheck = 0; // ')' skipped
SkipBlanks(rString, nPos); // only if currency
}
}
if ( SkipChar('%', rString, nPos) ) // 1 %
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return FALSE;
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_PERCENT;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
if ( SkipString(rTime, rString, nPos) ) // 10:
{
if (nDecPos) // already , => error
return FALSE;
if (eScannedType == NUMBERFORMAT_DATE && nAnzNums > 2) // 31.Dez.94 8:
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME;
}
else if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME;
}
}
sal_Unicode cTime = rTime.GetChar(0);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE;
}
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan
if (nMonth && nTmpMonth) // month dup
return FALSE;
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // 10 Jan
if (nTempMonth)
{
if (nMonth) // month dup
return FALSE;
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE;
nMonth = nTempMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
if (GetTimeAmPm(rString, nPos))
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME &&
eScannedType != NUMBERFORMAT_DATETIME) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
if ( eScannedType != NUMBERFORMAT_DATETIME )
eScannedType = NUMBERFORMAT_TIME;
}
}
if ( nNegCheck && SkipChar(')', rString, nPos) )
{
if (eScannedType == NUMBERFORMAT_CURRENCY) // only if currency
{
nNegCheck = 0; // skip ')'
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
if ( nPos < rString.Len() &&
(eScannedType == NUMBERFORMAT_DATE
|| eScannedType == NUMBERFORMAT_DATETIME) )
{ // day of week is just parsed away
xub_StrLen nOldPos = nPos;
const String& rSep = pFormatter->GetLocaleData()->getLongDateDayOfWeekSep();
if ( StringContains( rSep, rString, nPos ) )
{
nPos += rSep.Len();
SkipBlanks(rString, nPos);
}
short nDayOfWeek;
if ( nDayOfWeek = GetDayOfWeek( rString, nPos ) )
{
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // short
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
SkipBlanks(rString, nPos);
}
}
else
nPos = nOldPos;
}
if (nPos < rString.Len()) // everything consumed?
{
// does input EndString equal EndString in Format?
if ( !ScanStringNumFor( rString, nPos, pFormat, 0xFFFF ) )
return FALSE;
}
return TRUE;
}
BOOL ImpSvNumberInputScan::ScanStringNumFor(
const String& rString, // zu scannender String
xub_StrLen nPos, // Position bis zu der abgearbeitet war
const SvNumberformat* pFormat, // das zu matchende Format
USHORT nString ) // TeilString des TeilFormats
// normalerweise 0 oder 0xFFFF
{
if ( !pFormat )
return FALSE;
const ::utl::TransliterationWrapper* pTransliteration = pFormatter->GetTransliteration();
const String* pStr;
String aString( rString );
BOOL bFound = FALSE;
BOOL bFirst = TRUE;
BOOL bContinue = TRUE;
USHORT nSub;
do
{
// wenn am Anfang das zweite/dritte Teilformat gefunden wurde darunter
// nicht mehr suchen
nSub = nStringScanNumFor;
do
{ // TeilFormate durchprobieren, erst positiv, dann negativ, dann anderes,
// letztes (Text) nicht
pStr = pFormat->GetNumForString( nSub, nString, TRUE );
if ( pStr && pTransliteration->isEqual( aString, *pStr ) )
{
bFound = TRUE;
bContinue = FALSE;
}
else if ( nSub < 2 )
++nSub;
else
bContinue = FALSE;
} while ( bContinue );
if ( !bFound && bFirst && nPos )
{ // uebriggelassenen SubString probieren
bFirst = FALSE;
aString.Erase( 0, nPos );
bContinue = TRUE;
}
} while ( bContinue );
if ( !bFound )
{
if ( (nString == 0) && !bFirst && (nSign < 0)
&& pFormat->IsNegativeRealNegative() )
{ // simpel doppelt negiert? --1
aString.EraseAllChars( ' ' );
if ( (aString.Len() == 1) && (aString.GetChar(0) == '-') )
{
bFound = TRUE;
nStringScanSign = -1;
nSub = 0; //! nicht 1
}
}
if ( !bFound )
return FALSE;
}
else if ( (nSub == 1) && pFormat->IsNegativeRealNegative() )
{ // negativ
if ( nStringScanSign < 0 )
{
if ( (nSign < 0) && (nStringScanNumFor != 1) )
nStringScanSign = 1; // dreifach negiert --1 yyy
}
else if ( nStringScanSign == 0 )
{
if ( nSign < 0 )
{ // nSign und nStringScanSign werden spaeter verknuepft,
// Vorzeichen umkehren wenn doppelt negiert
if ( (nString == 0) && !bFirst
&& SvNumberformat::HasStringNegativeSign( aString ) )
nStringScanSign = -1; // direkte doppelte Negierung
else if ( pFormat->IsNegativeWithoutSign() )
nStringScanSign = -1; // indirekte doppelte Negierung
}
else
nStringScanSign = -1;
}
else // > 0
nStringScanSign = -1;
}
nStringScanNumFor = nSub;
return TRUE;
}
//---------------------------------------------------------------------------
// IsNumberFormatMain
//
// erkennt folgende Typen: Zahl Z, Exp.darst. E, Bruch B, Prozent P
// Waehrung W, Datum D, Uhrzeit U
// sonst Text T <=> return FALSE; )
BOOL ImpSvNumberInputScan::IsNumberFormatMain(
const String& rString, // zu analysierender String
double& fOutNumber, // OUT: Ergebnis als Zahl, wenn moeglich
const SvNumberformat* pFormat ) // evtl. gesetztes Zahlenformat
{
Reset(); // Anfangszustand
// NoMoreUpperNeeded, alle Vergleiche auf UpperCase
String aString( pFormatter->GetCharClass()->upper( rString ) );
NumberStringDivision(aString); // Zerlegung in Zahlen/Strings
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS) // zuviele Einzelteile
return FALSE; // Njet, Nope, ...
if (nAnzNums == 0) // keine Zahl in der Eingabe
{
if ( nAnzStrings > 0 )
{
// hier kann das Original geaendert werden, wird nicht mehr
// gebraucht, das erspart Kopiererei und ToUpper in GetLogical
// und ist im Zusammenspiel schneller
String& rStrArray = sStrArray[0];
rStrArray.EraseTrailingChars( ' ' );
rStrArray.EraseLeadingChars( ' ' );
if ( nLogical = GetLogical( rStrArray ) )
{
eScannedType = NUMBERFORMAT_LOGICAL;// !!! es ist ein BOOL
return TRUE;
}
else
return FALSE; // simple Text
}
else
return FALSE; // simple Text
}
USHORT i = 0; // markiert Symbole
USHORT j = 0; // markiert nur Zahlen
switch ( nAnzNums )
{
case 1 : // Genau 1 Zahl in der Eingabe
{ // nAnzStrings >= 1
if (GetNextNumber(i,j)) // i=1,0
{ // Zahl am Anfang
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall Bruch 1 = 1/1
{
if (i >= nAnzStrings || // kein Endstring oder ,
sStrArray[i] == pFormatter->GetLocaleData()->getNumDecimalSep())
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
}
else
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat )) // i=0
return FALSE; // schon fehlerhaft
i++; // naechstes Symbol, i=1
}
GetNextNumber(i,j); // i=1,2
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall Bruch -1 = -1/1
{
if (nSign && !nNegCheck && // Vorzeichen +, -
eScannedType == NUMBERFORMAT_UNDEFINED && // nicht D oder C
nDecPos == 0 && // kein Dezimalkomma vorher
(i >= nAnzStrings || // kein Endstring oder ,
sStrArray[i] == pFormatter->GetLocaleData()->getNumDecimalSep())
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
}
break;
case 2 : // Genau 2 Zahlen in Eingabe
{ // nAnzStrings >= 3
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // naechstes Symbol, i=2,3
GetNextNumber(i,j); // i=3,4
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall -1.200, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
}
break;
case 3 : // Genau 3 Zahlen in Eingabe
{ // nAnzStrings >= 5
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
if (nDecPos == 1) // , am Anfang => Fehler
return FALSE;
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=2,3
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j); // i=3,4
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=4,5
GetNextNumber(i,j); // i=5,6
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION)// Sonderfall -1.200.100, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return FALSE; // #36857# kein echter Bruch
}
break;
default: // Mehr als 3 Zahlen in Eingabe
{ // nAnzStrings >= 7
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
if (nDecPos == 1) // , am Anfang => Fehler
return FALSE;
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=2,3
USHORT nThOld = 10; // != 0 oder 1
while (nThOld != nThousand && j < nAnzNums-1)
// mindestens ein Mal
// aber eine Zahl noch lassen
{ // Abarbeitung Tausenderpkte.
nThOld = nThousand;
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanMidString(sStrArray[i], i))
return FALSE;
i++;
}
if (eScannedType == NUMBERFORMAT_DATE || // Abarbeitung langes Datum
eScannedType == NUMBERFORMAT_TIME || // lange Uhrzeit
eScannedType == NUMBERFORMAT_UNDEFINED) // oder lange Zahl
{
for (USHORT k = j; k < nAnzNums-1; k++)
{
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanMidString(sStrArray[i], i))
return FALSE;
i++;
}
}
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION)// Sonderfall -1.200.100, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return FALSE; // #36857# kein echter Bruch
}
}
if (eScannedType == NUMBERFORMAT_UNDEFINED) // alles andere sollte bereits
eScannedType = NUMBERFORMAT_NUMBER; // erkannt sein
return TRUE;
}
//---------------------------------------------------------------------------
// Initialize uppercase months and weekdays
void ImpSvNumberInputScan::InitText()
{
sal_Int32 j, nElems;
const CharClass* pChrCls = pFormatter->GetCharClass();
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const CalendarWrapper* pCal = pFormatter->GetCalendar();
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > xElems
= pCal->getMonths();
nElems = xElems.getLength();
pUpperMonthText = new String[nElems];
pUpperAbbrevMonthText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperMonthText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevMonthText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
xElems = pCal->getDays();
nElems = xElems.getLength();
pUpperDayText = new String[nElems];
pUpperAbbrevDayText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperDayText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevDayText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
bTextInitialized = TRUE;
}
//===========================================================================
// P U B L I C
//---------------------------------------------------------------------------
// ChangeIntl
//
// MUST be called if International/Locale is changed
void ImpSvNumberInputScan::ChangeIntl()
{
sal_Unicode cDecSep = pFormatter->GetNumDecimalSep().GetChar(0);
bDecSepInDateSeps = ( cDecSep == '-' ||
cDecSep == '/' ||
cDecSep == '.' ||
cDecSep == pFormatter->GetDateSep().GetChar(0) );
bTextInitialized = FALSE;
aUpperCurrSymbol.Erase();
}
//---------------------------------------------------------------------------
// ChangeNullDate
void ImpSvNumberInputScan::ChangeNullDate(
const USHORT nDay,
const USHORT nMonth,
const USHORT nYear )
{
if ( pNullDate )
*pNullDate = Date(nDay, nMonth, nYear);
else
pNullDate = new Date(nDay, nMonth, nYear);
}
//---------------------------------------------------------------------------
// IsNumberFormat
//
// => String als Zahl darstellbar
BOOL ImpSvNumberInputScan::IsNumberFormat(
const String& rString, // zu analysierender String
short& F_Type, // IN: alter Typ, OUT: neuer Typ
double& fOutNumber, // OUT: Zahl, wenn Umwandlung moeglich
const SvNumberformat* pFormat ) // evtl. gesetztes Zahlenformat
{
// in den zerlegten Strings gibt es keine Null-Laengen Strings mehr!
String sResString; // die Eingabe fuer atof
BOOL res; // Rueckgabewert
eSetType = F_Type; // Typ der Zelle
if ( !rString.Len() )
res = FALSE;
else if (rString.Len() > 308) // frueher 100
res = FALSE;
else
res = IsNumberFormatMain(rString, fOutNumber, pFormat);
if (res)
{
if ( nNegCheck // ')' nicht gefunden
|| (eScannedType == NUMBERFORMAT_TIME // Zeit mit Vorzeichen
&& nSign) )
res = FALSE;
else // Check der Zahlanzahlen
{
switch (eScannedType) // Analyseergebnis pruefen
{
case NUMBERFORMAT_PERCENT: // alle Zahlen
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
if (nDecPos == 1) // ,05
{
if (nAnzNums != 1)
res = FALSE;
}
else if (nDecPos == 2) // 1,05
{
if (nAnzNums != nThousand+2)
res = FALSE;
}
else // 1.100 oder 1.100,
{
if (nAnzNums != nThousand+1)
res = FALSE;
}
break;
case NUMBERFORMAT_SCIENTIFIC: // wissenschaftl. Format 1,0e-2
if (nDecPos == 1) // ,05
{
if (nAnzNums != 2)
res = FALSE;
}
else if (nDecPos == 2) // 1,05
{
if (nAnzNums != nThousand+3)
res = FALSE;
}
else // 1.100 oder 1.100,
{
if (nAnzNums != nThousand+2)
res = FALSE;
}
break;
case NUMBERFORMAT_DATE: // Datum
if (nMonth)
{
if (nAnzNums > 2)
res = FALSE;
}
else
{
if (nAnzNums > 3)
res = FALSE;
}
break;
case NUMBERFORMAT_TIME: // Uhrzeit
if (nDecPos)
{
if (nAnzNums > 4)
res = FALSE;
}
else
{
if (nAnzNums > 3)
res = FALSE;
}
break;
case NUMBERFORMAT_DATETIME: // Datum + Uhrzeit
if (nMonth)
{
if (nAnzNums > 5)
res = FALSE;
}
else
{
if (nAnzNums > 6)
res = FALSE;
}
break;
default:
break;
} // switch
} // else
} // if (res)
if (res) // Bestimmung der Zahl:
{
switch (eScannedType)
{
case NUMBERFORMAT_LOGICAL: // Logisch
if (nLogical == 1)
fOutNumber = 1.0; // True
else if (nLogical == -1)
fOutNumber = 0.0; // False
else
res = FALSE; // Oops
break;
case NUMBERFORMAT_PERCENT: // Zahlen
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_SCIENTIFIC: // erstmal Zahlanteil
if (nDecPos == 1) // , am Anfang
{
sResString.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "0." ) );
sResString += sStrArray[nNums[0]];
}
else
{ USHORT k;
sResString = sStrArray[nNums[0]];
for ( k = 1; k <= nThousand; k++)
sResString += sStrArray[nNums[k]]; // Vorkommateil
if (nDecPos == 2) // in der Mitte
{
sResString += '.';
sResString += sStrArray[nNums[k]];
}
}
if (eScannedType != NUMBERFORMAT_SCIENTIFIC)
fOutNumber = StringToDouble(sResString);
else // Nachbehandlung Exponent
{
sResString += 'E';
if ( nESign == -1 )
sResString += '-';
if (nDecPos == 2)
sResString += sStrArray[nNums[nThousand+2]];
else
sResString += sStrArray[nNums[nThousand+1]];
int nErrno = 0;
fOutNumber = SolarMath::StringToDouble(
sResString.GetBuffer(), ',', '.', nErrno );
if ( nErrno == ERANGE )
{
F_Type = NUMBERFORMAT_TEXT; // overflow/underflow -> Text
if (nESign == -1)
fOutNumber = 0.0;
else
fOutNumber = DBL_MAX;
/*!*/ return TRUE;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 ) // Vorzeichen dazu
fOutNumber = -fOutNumber;
if (eScannedType == NUMBERFORMAT_PERCENT) // durch 100 dividieren
fOutNumber/= 100.0;
break;
case NUMBERFORMAT_FRACTION: // Bruch
if (nAnzNums == 1)
fOutNumber = StringToDouble(sStrArray[nNums[0]]);
else if (nAnzNums == 2)
{
if (nThousand == 1)
{
sResString = sStrArray[nNums[0]];
sResString += sStrArray[nNums[1]]; // Vorkommateil
fOutNumber = StringToDouble(sResString);
}
else
{
double fZaehler = StringToDouble(sStrArray[nNums[0]]);
double fNenner = StringToDouble(sStrArray[nNums[1]]);
if (fNenner != 0.0)
fOutNumber = fZaehler/fNenner;
else
res = FALSE;
}
}
else // nAnzNums > 2
{
USHORT k = 1;
sResString = sStrArray[nNums[0]];
if (nThousand > 0)
for (k = 1; k <= nThousand; k++)
sResString += sStrArray[nNums[k]];
fOutNumber = StringToDouble(sResString);
if (k == nAnzNums-2)
{
double fZaehler = StringToDouble(sStrArray[nNums[k]]);
double fNenner = StringToDouble(sStrArray[nNums[k+1]]);
if (fNenner != 0.0)
fOutNumber += fZaehler/fNenner;
else
res = FALSE;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 ) // Vorzeichen dazu
fOutNumber = -fOutNumber;
break;
case NUMBERFORMAT_TIME: // Uhrzeit
GetTimeRef(fOutNumber, 0, nAnzNums);
break;
case NUMBERFORMAT_DATE: // Datum
{
Date aDt; // heute
USHORT nCounter = 0; // hier dummy
res = GetDateRef(aDt, nCounter, pFormat); // Datum->aDt
if ( res )
{
long nDate = (long) (aDt - *pNullDate); // erst nach long!!
fOutNumber = (double) nDate; // vorsichtshalber
}
}
break;
case NUMBERFORMAT_DATETIME: // Datum mit Uhrzeit
{
Date aDt; // heute
USHORT nCounter; // hier wichtig
res = GetDateRef(aDt, nCounter, pFormat); // Datum->aDt
double fTime;
GetTimeRef(fTime, nCounter, nAnzNums-nCounter);
if ( res )
{
long nDate = (long) (aDt - *pNullDate);
fOutNumber = (double) nDate + fTime;
}
}
break;
default:
break;
}
}
if (res) // Ueberlauf -> Text
{
if (fOutNumber < -DBL_MAX) // -1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = -DBL_MAX;
return TRUE;
}
else if (fOutNumber > DBL_MAX) // 1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = DBL_MAX;
return TRUE;
}
}
if (res == FALSE)
{
eScannedType = NUMBERFORMAT_TEXT;
fOutNumber = 0.0;
}
F_Type = eScannedType;
return res;
}
#90415# 10-Jan-94 is a valid date even if date order is MDY
/*************************************************************************
*
* $RCSfile: zforfind.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: er $ $Date: 2001-08-22 15:25:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <ctype.h>
#include <stdlib.h>
#include <float.h>
#include <errno.h>
#ifndef _INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _TOOLS_SOLMATH_HXX
#include <tools/solmath.hxx>
#endif
#ifndef _SYSTEM_HXX //autogen
#include <vcl/system.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX
#include <unotools/calendarwrapper.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_CALENDARFIELDINDEX_HPP_
#include <com/sun/star/i18n/CalendarFieldIndex.hpp>
#endif
#include "zforlist.hxx" // NUMBERFORMAT_XXX
#include "zforscan.hxx"
#include "zformat.hxx"
#define _ZFORFIND_CXX
#include "zforfind.hxx"
#undef _ZFORFIND_CXX
// use faster isdigit() if possible
//#define MyIsdigit(c) (pFormatter->GetCharClass()->isDigit(c))
#define MyIsdigit(c) ((c) < 256 && isdigit((unsigned char)(c)))
//---------------------------------------------------------------------------
// Konstruktor
ImpSvNumberInputScan::ImpSvNumberInputScan( SvNumberFormatter* pFormatterP )
:
pUpperMonthText( NULL ),
pUpperAbbrevMonthText( NULL ),
pUpperDayText( NULL ),
pUpperAbbrevDayText( NULL )
{
pFormatter = pFormatterP;
pNullDate = new Date(30,12,1899);
nYear2000 = SvNumberFormatter::GetYear2000Default();
Reset();
ChangeIntl();
}
//---------------------------------------------------------------------------
// Destruktor
ImpSvNumberInputScan::~ImpSvNumberInputScan()
{
Reset();
delete pNullDate;
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
}
//---------------------------------------------------------------------------
// Reset
void ImpSvNumberInputScan::Reset()
{
#if 0
// ER 16.06.97 18:56 Vorbelegung erfolgt jetzt in NumberStringDivision,
// wozu immer alles loeschen wenn einiges wieder benutzt oder gar nicht
// gebraucht wird..
for (USHORT i = 0; i < SV_MAX_ANZ_INPUT_STRINGS; i++)
{
sStrArray[i].Erase();
nNums[i] = SV_MAX_ANZ_INPUT_STRINGS-1;
IsNum[i] = FALSE;
}
#endif
nMonth = 0;
nMonthPos = 0;
nTimePos = 0;
nSign = 0;
nESign = 0;
nDecPos = 0;
nNegCheck = 0;
nAnzStrings = 0;
nAnzNums = 0;
nThousand = 0;
eScannedType = NUMBERFORMAT_UNDEFINED;
nAmPm = 0;
nPosThousandString = 0;
nLogical = 0;
nStringScanNumFor = 0;
nStringScanSign = 0;
}
//---------------------------------------------------------------------------
// StringToDouble
//
// Only simple unsigned floating point values without any error detection,
// decimal separator has to be '.'
double ImpSvNumberInputScan::StringToDouble( const String& rStr, BOOL bForceFraction )
{
double fNum = 0.0;
double fFrac = 0.0;
int nExp = 0;
xub_StrLen nPos = 0;
xub_StrLen nLen = rStr.Len();
BOOL bPreSep = !bForceFraction;
while (nPos < nLen)
{
if (rStr.GetChar(nPos) == '.')
bPreSep = FALSE;
else if (bPreSep)
fNum = fNum * 10.0 + (double) (rStr.GetChar(nPos) - '0');
else
{
fFrac = fFrac * 10.0 + (double) (rStr.GetChar(nPos) - '0');
--nExp;
}
nPos++;
}
if ( fFrac )
return fNum + SolarMath::Pow10Exp( fFrac, nExp );
return fNum;
}
//---------------------------------------------------------------------------
// NextNumberStringSymbol
//
// Zerlegt die Eingabe in Zahlen und Strings fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = GetChar
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// GetChar | Ziffer | Symbol=Zeichen | GetValue
// | Sonst | Symbol=Zeichen | GetString
//---------------|-------------------+-----------------------+---------------
// GetValue | Ziffer | Symbol=Symbol+Zeichen | GetValue
// | Sonst | Dec(CharPos) | Stop
//---------------+-------------------+-----------------------+---------------
// GetString | Ziffer | Dec(CharPos) | Stop
// | Sonst | Symbol=Symbol+Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
enum ScanState // States der Turing-Maschine
{
SsStop = 0,
SsStart = 1,
SsGetValue = 2,
SsGetString = 3
};
BOOL ImpSvNumberInputScan::NextNumberStringSymbol(
const sal_Unicode*& pStr,
String& rSymbol )
{
BOOL isNumber = FALSE;
sal_Unicode cToken;
ScanState eState = SsStart;
register const sal_Unicode* pHere = pStr;
register xub_StrLen nChars = 0;
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( MyIsdigit( cToken ) )
{
eState = SsGetValue;
isNumber = TRUE;
}
else
eState = SsGetString;
nChars++;
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetString:
if ( !MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if ( nChars )
rSymbol.Assign( pStr, nChars );
else
rSymbol.Erase();
pStr = pHere;
return isNumber;
}
//---------------------------------------------------------------------------
// SkipThousands
BOOL ImpSvNumberInputScan::SkipThousands(
const sal_Unicode*& pStr,
String& rSymbol )
{
BOOL res = FALSE;
sal_Unicode cToken;
const String& rThSep = pFormatter->GetLocaleData()->getNumThousandSep();
register const sal_Unicode* pHere = pStr;
ScanState eState = SsStart;
xub_StrLen nCounter; // counts 3 digits
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( StringPtrContains( rThSep, pHere-1, 0 ) )
{
nCounter = 0;
eState = SsGetValue;
pHere += rThSep.Len()-1;
}
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
{
rSymbol += cToken;
nCounter++;
if (nCounter == 3)
{
eState = SsStart;
res = TRUE; // .000 combination found
}
}
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if (eState == SsGetValue) // break witth less than 3 digits
{
if ( nCounter )
rSymbol.Erase( rSymbol.Len() - nCounter, nCounter );
pHere -= nCounter + rThSep.Len(); // put back ThSep also
}
pStr = pHere;
return res;
}
//---------------------------------------------------------------------------
// NumberStringDivision
void ImpSvNumberInputScan::NumberStringDivision( const String& rString )
{
register const sal_Unicode* pStr = rString.GetBuffer();
register const sal_Unicode* const pEnd = pStr + rString.Len();
while ( pStr < pEnd && nAnzStrings < SV_MAX_ANZ_INPUT_STRINGS )
{
if ( NextNumberStringSymbol( pStr, sStrArray[nAnzStrings] ) )
{ // Zahl
IsNum[nAnzStrings] = TRUE;
nNums[nAnzNums] = nAnzStrings;
nAnzNums++;
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS - 7 &&
nPosThousandString == 0) // nur einmal
if ( SkipThousands( pStr, sStrArray[nAnzStrings] ) )
nPosThousandString = nAnzStrings;
}
else
{
IsNum[nAnzStrings] = FALSE;
}
nAnzStrings++;
}
}
//---------------------------------------------------------------------------
// Whether rString contains rWhat at nPos
BOOL ImpSvNumberInputScan::StringContainsImpl( const String& rWhat,
const String& rString, xub_StrLen nPos )
{
if ( nPos + rWhat.Len() <= rString.Len() )
return StringPtrContainsImpl( rWhat, rString.GetBuffer(), nPos );
return FALSE;
}
//---------------------------------------------------------------------------
// Whether pString contains rWhat at nPos
BOOL ImpSvNumberInputScan::StringPtrContainsImpl( const String& rWhat,
const sal_Unicode* pString, xub_StrLen nPos )
{
if ( rWhat.Len() == 0 )
return FALSE;
register const sal_Unicode* pWhat = rWhat.GetBuffer();
register const sal_Unicode* const pEnd = pWhat + rWhat.Len();
register const sal_Unicode* pStr = pString + nPos;
while ( pWhat < pEnd )
{
if ( *pWhat != *pStr )
return FALSE;
pWhat++;
pStr++;
}
return TRUE;
}
//---------------------------------------------------------------------------
// SkipChar
//
// ueberspringt genau das angegebene Zeichen
inline BOOL ImpSvNumberInputScan::SkipChar( sal_Unicode c, const String& rString,
xub_StrLen& nPos )
{
if ((nPos < rString.Len()) && (rString.GetChar(nPos) == c))
{
nPos++;
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// SkipBlanks
//
// Ueberspringt Leerzeichen
inline void ImpSvNumberInputScan::SkipBlanks( const String& rString,
xub_StrLen& nPos )
{
if ( nPos < rString.Len() )
{
register const sal_Unicode* p = rString.GetBuffer() + nPos;
while ( *p == ' ' )
{
nPos++;
p++;
}
}
}
//---------------------------------------------------------------------------
// SkipString
//
// jump over rWhat in rString at nPos
inline BOOL ImpSvNumberInputScan::SkipString( const String& rWhat,
const String& rString, xub_StrLen& nPos )
{
if ( StringContains( rWhat, rString, nPos ) )
{
nPos += rWhat.Len();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetThousandSep
//
// erkennt genau .111 als Tausenderpunkt
inline BOOL ImpSvNumberInputScan::GetThousandSep(
const String& rString,
xub_StrLen& nPos,
USHORT nStringPos )
{
const String& rSep = pFormatter->GetLocaleData()->getNumThousandSep();
if ( rString == rSep // nothing else
&& nStringPos < nAnzStrings - 1 // safety first!
&& IsNum[nStringPos+1] // number follows
&& ( sStrArray[nStringPos+1].Len() == 3 // with 3 digits
|| nPosThousandString == nStringPos+1 ) ) // or concatenated
{
nPos += rSep.Len();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetLogical
//
// Umwandlung Text in logischen Wert
// "TRUE" => 1:
// "FALSE"=> -1:
// sonst => 0:
short ImpSvNumberInputScan::GetLogical( const String& rString )
{
short res;
if (rString.Len() < 4) // kein Platz fuer mind 4 Buch.
res = 0;
else
{
const ImpSvNumberformatScan* pFS = pFormatter->GetFormatScanner();
if ( rString == pFS->GetTrueString() )
res = 1;
else if ( rString == pFS->GetFalseString() )
res = -1;
else
res = 0;
}
return res;
}
//---------------------------------------------------------------------------
// GetMonth
//
// Converts a string containing a month name (JAN, January) at nPos into the
// month number (negative if abbreviated), returns 0 if nothing found
short ImpSvNumberInputScan::GetMonth( const String& rString, xub_StrLen& nPos )
{
short res = 0; // no month found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nMonths = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
for ( sal_Int16 i = 0; i < nMonths; i++ )
{
if ( StringContains( pUpperMonthText[i], rString, nPos ) )
{ // full names first
nPos += pUpperMonthText[i].Len();
res = i+1;
break; // for
}
else if ( StringContains( pUpperAbbrevMonthText[i], rString, nPos ) )
{ // abbreviated
nPos += pUpperAbbrevMonthText[i].Len();
res = -(i+1); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetDayOfWeek
//
// Converts a string containing a DayOfWeek name (Mon, Monday) at nPos into the
// DayOfWeek number + 1 (negative if abbreviated), returns 0 if nothing found
short ImpSvNumberInputScan::GetDayOfWeek( const String& rString, xub_StrLen& nPos )
{
short res = 0; // no day found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nDays = pFormatter->GetCalendar()->getNumberOfDaysInWeek();
for ( sal_Int16 i = 0; i < nDays; i++ )
{
if ( StringContains( pUpperDayText[i], rString, nPos ) )
{ // full names first
nPos += pUpperDayText[i].Len();
res = i + 1;
break; // for
}
if ( StringContains( pUpperAbbrevDayText[i], rString, nPos ) )
{ // abbreviated
nPos += pUpperAbbrevDayText[i].Len();
res = -(i + 1); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetCurrency
//
// Lesen eines Waehrungssysmbols
// '$' => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::GetCurrency( const String& rString, xub_StrLen& nPos,
const SvNumberformat* pFormat )
{
if ( rString.Len() > nPos )
{
if ( !aUpperCurrSymbol.Len() )
{ // if no format specified the currency of the initialized formatter
LanguageType eLang = (pFormat ? pFormat->GetLanguage() :
pFormatter->GetLanguage());
aUpperCurrSymbol = pFormatter->GetCharClass()->upper(
SvNumberFormatter::GetCurrencyEntry( eLang ).GetSymbol() );
}
if ( StringContains( aUpperCurrSymbol, rString, nPos ) )
{
nPos += aUpperCurrSymbol.Len();
return TRUE;
}
if ( pFormat )
{
String aSymbol, aExtension;
if ( pFormat->GetNewCurrencySymbol( aSymbol, aExtension ) )
{
if ( aSymbol.Len() <= rString.Len() - nPos )
{
pFormatter->GetCharClass()->toUpper( aSymbol );
if ( StringContains( aSymbol, rString, nPos ) )
{
nPos += aSymbol.Len();
return TRUE;
}
}
}
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetTimeAmPm
//
// Lesen des Zeitsymbols (AM od. PM) f. kurze Zeitangabe
//
// Rueckgabe:
// "AM" od. "PM" => TRUE
// sonst => FALSE
//
// nAmPos:
// "AM" => 1
// "PM" => -1
// sonst => 0
BOOL ImpSvNumberInputScan::GetTimeAmPm( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const CharClass* pChr = pFormatter->GetCharClass();
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
if ( StringContains( pChr->upper( pLoc->getTimeAM() ), rString, nPos ) )
{
nAmPm = 1;
nPos += pLoc->getTimeAM().Len();
return TRUE;
}
else if ( StringContains( pChr->upper( pLoc->getTimePM() ), rString, nPos ) )
{
nAmPm = -1;
nPos += pLoc->getTimePM().Len();
return TRUE;
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetDecSep
//
// Lesen eines Dezimaltrenners (',')
// ',' => TRUE
// sonst => FALSE
inline BOOL ImpSvNumberInputScan::GetDecSep( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const String& rSep = pFormatter->GetLocaleData()->getNumDecimalSep();
if ( rString.Equals( rSep, nPos, rSep.Len() ) )
{
nPos += rSep.Len();
return TRUE;
}
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetSign
//
// Lesen eines Vorzeichens, auch Klammer !?!
// '+' => 1
// '-' => -1
// '(' => -1, nNegCheck = 1
// sonst => 0
short ImpSvNumberInputScan::GetSign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
break;
case '(': // '(' aehnlich wie '-' ?!?
nNegCheck = 1;
//! fallthru
case '-':
nPos++;
return -1;
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetESign
//
// Lesen eines Vorzeichens, gedacht fuer Exponent ?!?
// '+' => 1
// '-' => -1
// sonst => 0
short ImpSvNumberInputScan::GetESign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
break;
case '-':
nPos++;
return -1;
break;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetNextNumber
//
// i zaehlt Strings, j zaehlt Numbers, eigentlich sollte das SkipNumber heissen
inline BOOL ImpSvNumberInputScan::GetNextNumber( USHORT& i, USHORT& j )
{
if ( IsNum[i] )
{
j++;
i++;
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// GetTimeRef
void ImpSvNumberInputScan::GetTimeRef(
double& fOutNumber,
USHORT nIndex, // j-Wert fuer den ersten Zeitstring der Eingabe (default 0)
USHORT nAnz ) // Anzahl der Zeitstrings
{
sal_Unicode* pChar = NULL;
USHORT nHour;
USHORT nMinute = 0;
USHORT nSecond = 0;
double fSecond100 = 0.0;
USHORT nStartIndex = nIndex;
if (nDecPos == 2 && nAnz == 3) // 20:45,5
nHour = 0;
else
nHour = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
nMinute = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
nSecond = (USHORT) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
fSecond100 = StringToDouble( sStrArray[nNums[nIndex]], TRUE );
if (nAmPm == -1 && nHour != 12) // PM
nHour += 12;
else if (nAmPm == 1 && nHour == 12) // 12 AM
nHour = 0;
fOutNumber = ((double)nHour*3600 +
(double)nMinute*60 +
(double)nSecond +
fSecond100)/86400.0;
}
//---------------------------------------------------------------------------
// ImplGetDay
USHORT ImpSvNumberInputScan::ImplGetDay( USHORT nIndex )
{
USHORT nRes = 0;
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
USHORT nNum = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
if (nNum <= 31)
nRes = nNum;
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetMonth
USHORT ImpSvNumberInputScan::ImplGetMonth( USHORT nIndex )
{
// preset invalid month number
USHORT nRes = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
USHORT nNum = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
if ( 0 < nNum && nNum <= nRes )
nRes = nNum - 1; // zero based for CalendarFieldIndex::MONTH
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetYear
//
// 30 -> 1930, 29 -> 2029, oder 56 -> 1756, 55 -> 1855, ...
USHORT ImpSvNumberInputScan::ImplGetYear( USHORT nIndex )
{
USHORT nYear = 0;
if (sStrArray[nNums[nIndex]].Len() <= 4)
{
nYear = (USHORT) sStrArray[nNums[nIndex]].ToInt32();
nYear = SvNumberFormatter::ExpandTwoDigitYear( nYear, nYear2000 );
}
return nYear;
}
//---------------------------------------------------------------------------
// GetDateRef
BOOL ImpSvNumberInputScan::GetDateRef( Date& aDt, USHORT& nCounter,
const SvNumberformat* pFormat )
{
using namespace ::com::sun::star::i18n;
NfEvalDateFormat eEDF;
int nFormatOrder;
if ( pFormat && ((pFormat->GetType() & NUMBERFORMAT_DATE) == NUMBERFORMAT_DATE) )
{
eEDF = pFormat->ImpGetScan().GetNumberformatter()->GetEvalDateFormat();
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
case NF_EVALDATEFORMAT_FORMAT :
nFormatOrder = 1; // only one loop
break;
default:
nFormatOrder = 2;
}
}
else
{
eEDF = NF_EVALDATEFORMAT_INTL;
nFormatOrder = 1;
}
BOOL res = TRUE;
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
CalendarWrapper* pCal = pFormatter->GetCalendar();
for ( int nTryOrder = 1; nTryOrder <= nFormatOrder; nTryOrder++ )
{
pCal->setGregorianDateTime( aDt );
DateFormat DateFmt;
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
DateFmt = pLoc->getDateFormat();
break;
case NF_EVALDATEFORMAT_FORMAT :
DateFmt = pFormat->GetDateOrder();
break;
case NF_EVALDATEFORMAT_INTL_FORMAT :
if ( nTryOrder == 1 )
DateFmt = pLoc->getDateFormat();
else
DateFmt = pFormat->GetDateOrder();
break;
case NF_EVALDATEFORMAT_FORMAT_INTL :
if ( nTryOrder == 2 )
DateFmt = pLoc->getDateFormat();
else
DateFmt = pFormat->GetDateOrder();
break;
default:
DBG_ERROR( "ImpSvNumberInputScan::GetDateRef: unknown NfEvalDateFormat" );
}
res = TRUE;
nCounter = 0;
switch (nAnzNums) // count of numbers in string
{
case 0: // none
if (nMonthPos) // only month (Jan)
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
}
else
res = FALSE;
break;
case 1: // only one number
nCounter = 1;
switch (nMonthPos) // where is the month
{
case 0: // not found => only day entered
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case 1: // month at the beginning (Jan 01)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case MDY:
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
case 3: // month at the end (10 Jan)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
default:
res = FALSE;
break;
} // switch (nMonthPos)
break;
case 2: // 2 numbers
nCounter = 2;
switch (nMonthPos) // where is the month
{
case 0: // not found
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( !pCal->isValid() ) // 2nd try
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
}
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( !pCal->isValid() ) // 2nd try
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
}
break;
default:
res = FALSE;
break;
}
break;
case 1: // month at the beginning (Jan 01 01)
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
default:
res = FALSE;
break;
}
break;
case 2: // month in the middle (10 Jan 94)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case MDY: // yes, "10-Jan-94" is valid
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan)
res = FALSE;
break;
} // switch (nMonthPos)
break;
default: // more than two numbers (31.12.94 8:23) (31.12. 8:23)
switch (nMonthPos) // where is the month
{
case 0: // not found
nCounter = 3;
if ( nTimePos > 1 )
{ // find first time number index (should only be 3 or 2 anyway)
for ( USHORT j = 0; j < nAnzNums; j++ )
{
if ( nNums[j] == nTimePos - 2 )
{
nCounter = j;
break; // for
}
}
}
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case YMD:
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(2) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = FALSE;
break;
}
break;
case 1: // month at the beginning (Jan 01 01 8:23)
nCounter = 2;
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
default:
res = FALSE;
break;
}
break;
case 2: // month in the middle (10 Jan 94 8:23)
nCounter = 2;
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
default:
res = FALSE;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan 8:23)
nCounter = 2;
res = FALSE;
break;
} // switch (nMonthPos)
break;
} // switch (nAnzNums)
if ( res && pCal->isValid() )
{
aDt = pCal->getGregorianDateTime();
nTryOrder = nFormatOrder; // break for
}
else
{
res = FALSE;
aDt = Date(); // next try
}
}
return res;
}
//---------------------------------------------------------------------------
// ScanStartString
//
// ersten String analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanStartString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
short nDayOfWeek;
SkipBlanks(rString, nPos);
if ( nSign = GetSign(rString, nPos) ) // Vorzeichen?
SkipBlanks(rString, nPos);
if ( GetDecSep(rString, nPos) ) // Dezimaltrenner (,) im Startstring
{
nDecPos = 1;
SkipBlanks(rString, nPos);
}
else if ( GetCurrency(rString, nPos, pFormat) ) // Waehrung (DM 1)?
{
eScannedType = NUMBERFORMAT_CURRENCY; // !!! es ist Geld !!!
SkipBlanks(rString, nPos);
if (nSign == 0) // noch kein Vorzeichen
if ( nSign = GetSign(rString, nPos) ) // DM -1
SkipBlanks(rString, nPos);
}
else if ( nMonth = GetMonth(rString, nPos) ) // month (Jan 1)?
{
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
nMonthPos = 1; // month at the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
else if ( nDayOfWeek = GetDayOfWeek( rString, nPos ) )
{ // day of week is just parsed away
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // abbreviated
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
else
{ // full long name
SkipBlanks(rString, nPos);
SkipString( pFormatter->GetLocaleData()->getLongDateDayOfWeekSep(), rString, nPos );
}
SkipBlanks(rString, nPos);
if ( nMonth = GetMonth(rString, nPos) ) // month (Jan 1)?
{
nMonthPos = 1; // month a the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
}
if (nPos < rString.Len()) // noch nicht alles weg
{
// eingegebener StartString gleich StartString im Format?
if ( !ScanStringNumFor( rString, nPos, pFormat, 0 ) )
return FALSE;
}
return TRUE;
}
//---------------------------------------------------------------------------
// ScanMidString
//
// String in der Mitte analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanMidString(
const String& rString,
USHORT nStringPos )
{
xub_StrLen nPos = 0;
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // ,12,4 or 1,E2,1
return FALSE;
else if (nDecPos == 2) // , dup: 12,4,
{
if (bDecSepInDateSeps) // , also date separator
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
else
{
nDecPos = 2; // , in mid string
SkipBlanks(rString, nPos);
}
}
if (SkipChar('/', rString, nPos)) // fraction?
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE; // => jan/31/1994
else if ( eScannedType != NUMBERFORMAT_DATE // analyzed date until now
&& ( eSetType == NUMBERFORMAT_FRACTION // and preset was fraction
|| (nAnzNums == 3 // or 3 numbers
&& nStringPos > 2) ) ) // and what ???
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_FRACTION; // !!! it IS a fraction
}
else
nPos--; // put '/' back
}
if (GetThousandSep(rString, nPos, nStringPos)) // 1,000
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_CURRENCY) // except currency
return FALSE;
nThousand++;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
sal_Unicode cTime = rTime.GetChar(0);
SkipBlanks(rString, nPos);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE;
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan 94
if (nMonth && nTmpMonth) // month dup
return FALSE;
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 2; // month in the middle
// Short month may be abbreviated Jan. or
// #79632# recognize 17-Jan-2001 to be a date
if ( !(nMonth < 0 && (SkipChar( '.', rString, nPos ) ||
SkipChar( '-', rString, nPos ))) )
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // month in the middle (10 Jan 94)
if (nTempMonth)
{
if (nMonth != 0) // month dup
return FALSE;
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
nMonth = nTempMonth;
nMonthPos = 2; // month in the middle
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
if ( SkipChar('E', rString, nPos) // 10E, 10e, 10,Ee
|| SkipChar('e', rString, nPos) )
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_SCIENTIFIC; // !!! it IS scientific
if ( nThousand+2 == nAnzNums // special case 1.E2
&& nDecPos == 2 )
nDecPos = 3; // 1,100.E2 1,100,100.E3
}
nESign = GetESign(rString, nPos); // signed exponent?
SkipBlanks(rString, nPos);
}
if ( SkipString(rTime, rString, nPos) ) // time separator?
{
if (nDecPos) // already , => error
return FALSE;
if ( ( eScannedType == NUMBERFORMAT_DATE // already date type
|| eScannedType == NUMBERFORMAT_DATETIME) // or date time
&& nAnzNums > 3) // and more than 3 numbers? (31.Dez.94 8:23)
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME; // !!! it IS date with time
}
else if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_TIME) // except time
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME; // !!! it IS a time
}
if ( !nTimePos )
nTimePos = nStringPos + 1;
}
// #68232# recognize long date separators like ", " in "September 5, 1999"
if ( nPos < rString.Len() && eScannedType == NUMBERFORMAT_DATE
&& nMonthPos == 1 && pLoc->getLongDateFormat() == MDY )
{
if ( SkipString( pLoc->getLongDateDaySep(), rString, nPos ) )
SkipBlanks( rString, nPos );
}
if (nPos < rString.Len()) // not everything consumed?
return FALSE;
return TRUE;
}
//---------------------------------------------------------------------------
// ScanEndString
//
// Schlussteil analysieren
// Alles weg => TRUE
// sonst => FALSE
BOOL ImpSvNumberInputScan::ScanEndString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // ,12,4 or 12,E4,
return FALSE;
else if (nDecPos == 2) // , dup: 12,4,
{
if (bDecSepInDateSeps) // , also date sep
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
else
{
nDecPos = 3; // , in end string
SkipBlanks(rString, nPos);
}
}
if ( nSign == 0 // conflict - not signed
&& eScannedType != NUMBERFORMAT_DATE) // and not date
//!? catch time too?
{ // not signed yet
nSign = GetSign(rString, nPos); // 1- DM
if (nNegCheck) // '(' as sign
return FALSE;
}
SkipBlanks(rString, nPos);
if (nNegCheck && SkipChar(')', rString, nPos)) // skip ')' if appropriate
{
nNegCheck = 0;
SkipBlanks(rString, nPos);
}
if ( GetCurrency(rString, nPos, pFormat) ) // currency symbol?
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // currency dup
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_CURRENCY;
} // behind currency a '-' is allowed
if (nSign == 0) // not signed yet
{
nSign = GetSign(rString, nPos); // DM -
SkipBlanks(rString, nPos);
if (nNegCheck) // 3 DM (
return FALSE;
}
if ( nNegCheck && eScannedType == NUMBERFORMAT_CURRENCY
&& SkipChar(')', rString, nPos) )
{
nNegCheck = 0; // ')' skipped
SkipBlanks(rString, nPos); // only if currency
}
}
if ( SkipChar('%', rString, nPos) ) // 1 %
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return FALSE;
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_PERCENT;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
if ( SkipString(rTime, rString, nPos) ) // 10:
{
if (nDecPos) // already , => error
return FALSE;
if (eScannedType == NUMBERFORMAT_DATE && nAnzNums > 2) // 31.Dez.94 8:
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME;
}
else if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME;
}
}
sal_Unicode cTime = rTime.GetChar(0);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE;
}
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan
if (nMonth && nTmpMonth) // month dup
return FALSE;
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // 10 Jan
if (nTempMonth)
{
if (nMonth) // month dup
return FALSE;
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return FALSE;
eScannedType = NUMBERFORMAT_DATE;
nMonth = nTempMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
if (GetTimeAmPm(rString, nPos))
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME &&
eScannedType != NUMBERFORMAT_DATETIME) // already another type
return FALSE;
else
{
SkipBlanks(rString, nPos);
if ( eScannedType != NUMBERFORMAT_DATETIME )
eScannedType = NUMBERFORMAT_TIME;
}
}
if ( nNegCheck && SkipChar(')', rString, nPos) )
{
if (eScannedType == NUMBERFORMAT_CURRENCY) // only if currency
{
nNegCheck = 0; // skip ')'
SkipBlanks(rString, nPos);
}
else
return FALSE;
}
if ( nPos < rString.Len() &&
(eScannedType == NUMBERFORMAT_DATE
|| eScannedType == NUMBERFORMAT_DATETIME) )
{ // day of week is just parsed away
xub_StrLen nOldPos = nPos;
const String& rSep = pFormatter->GetLocaleData()->getLongDateDayOfWeekSep();
if ( StringContains( rSep, rString, nPos ) )
{
nPos += rSep.Len();
SkipBlanks(rString, nPos);
}
short nDayOfWeek;
if ( nDayOfWeek = GetDayOfWeek( rString, nPos ) )
{
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // short
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
SkipBlanks(rString, nPos);
}
}
else
nPos = nOldPos;
}
if (nPos < rString.Len()) // everything consumed?
{
// does input EndString equal EndString in Format?
if ( !ScanStringNumFor( rString, nPos, pFormat, 0xFFFF ) )
return FALSE;
}
return TRUE;
}
BOOL ImpSvNumberInputScan::ScanStringNumFor(
const String& rString, // zu scannender String
xub_StrLen nPos, // Position bis zu der abgearbeitet war
const SvNumberformat* pFormat, // das zu matchende Format
USHORT nString ) // TeilString des TeilFormats
// normalerweise 0 oder 0xFFFF
{
if ( !pFormat )
return FALSE;
const ::utl::TransliterationWrapper* pTransliteration = pFormatter->GetTransliteration();
const String* pStr;
String aString( rString );
BOOL bFound = FALSE;
BOOL bFirst = TRUE;
BOOL bContinue = TRUE;
USHORT nSub;
do
{
// wenn am Anfang das zweite/dritte Teilformat gefunden wurde darunter
// nicht mehr suchen
nSub = nStringScanNumFor;
do
{ // TeilFormate durchprobieren, erst positiv, dann negativ, dann anderes,
// letztes (Text) nicht
pStr = pFormat->GetNumForString( nSub, nString, TRUE );
if ( pStr && pTransliteration->isEqual( aString, *pStr ) )
{
bFound = TRUE;
bContinue = FALSE;
}
else if ( nSub < 2 )
++nSub;
else
bContinue = FALSE;
} while ( bContinue );
if ( !bFound && bFirst && nPos )
{ // uebriggelassenen SubString probieren
bFirst = FALSE;
aString.Erase( 0, nPos );
bContinue = TRUE;
}
} while ( bContinue );
if ( !bFound )
{
if ( (nString == 0) && !bFirst && (nSign < 0)
&& pFormat->IsNegativeRealNegative() )
{ // simpel doppelt negiert? --1
aString.EraseAllChars( ' ' );
if ( (aString.Len() == 1) && (aString.GetChar(0) == '-') )
{
bFound = TRUE;
nStringScanSign = -1;
nSub = 0; //! nicht 1
}
}
if ( !bFound )
return FALSE;
}
else if ( (nSub == 1) && pFormat->IsNegativeRealNegative() )
{ // negativ
if ( nStringScanSign < 0 )
{
if ( (nSign < 0) && (nStringScanNumFor != 1) )
nStringScanSign = 1; // dreifach negiert --1 yyy
}
else if ( nStringScanSign == 0 )
{
if ( nSign < 0 )
{ // nSign und nStringScanSign werden spaeter verknuepft,
// Vorzeichen umkehren wenn doppelt negiert
if ( (nString == 0) && !bFirst
&& SvNumberformat::HasStringNegativeSign( aString ) )
nStringScanSign = -1; // direkte doppelte Negierung
else if ( pFormat->IsNegativeWithoutSign() )
nStringScanSign = -1; // indirekte doppelte Negierung
}
else
nStringScanSign = -1;
}
else // > 0
nStringScanSign = -1;
}
nStringScanNumFor = nSub;
return TRUE;
}
//---------------------------------------------------------------------------
// IsNumberFormatMain
//
// erkennt folgende Typen: Zahl Z, Exp.darst. E, Bruch B, Prozent P
// Waehrung W, Datum D, Uhrzeit U
// sonst Text T <=> return FALSE; )
BOOL ImpSvNumberInputScan::IsNumberFormatMain(
const String& rString, // zu analysierender String
double& fOutNumber, // OUT: Ergebnis als Zahl, wenn moeglich
const SvNumberformat* pFormat ) // evtl. gesetztes Zahlenformat
{
Reset(); // Anfangszustand
// NoMoreUpperNeeded, alle Vergleiche auf UpperCase
String aString( pFormatter->GetCharClass()->upper( rString ) );
NumberStringDivision(aString); // Zerlegung in Zahlen/Strings
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS) // zuviele Einzelteile
return FALSE; // Njet, Nope, ...
if (nAnzNums == 0) // keine Zahl in der Eingabe
{
if ( nAnzStrings > 0 )
{
// hier kann das Original geaendert werden, wird nicht mehr
// gebraucht, das erspart Kopiererei und ToUpper in GetLogical
// und ist im Zusammenspiel schneller
String& rStrArray = sStrArray[0];
rStrArray.EraseTrailingChars( ' ' );
rStrArray.EraseLeadingChars( ' ' );
if ( nLogical = GetLogical( rStrArray ) )
{
eScannedType = NUMBERFORMAT_LOGICAL;// !!! es ist ein BOOL
return TRUE;
}
else
return FALSE; // simple Text
}
else
return FALSE; // simple Text
}
USHORT i = 0; // markiert Symbole
USHORT j = 0; // markiert nur Zahlen
switch ( nAnzNums )
{
case 1 : // Genau 1 Zahl in der Eingabe
{ // nAnzStrings >= 1
if (GetNextNumber(i,j)) // i=1,0
{ // Zahl am Anfang
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall Bruch 1 = 1/1
{
if (i >= nAnzStrings || // kein Endstring oder ,
sStrArray[i] == pFormatter->GetLocaleData()->getNumDecimalSep())
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
}
else
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat )) // i=0
return FALSE; // schon fehlerhaft
i++; // naechstes Symbol, i=1
}
GetNextNumber(i,j); // i=1,2
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall Bruch -1 = -1/1
{
if (nSign && !nNegCheck && // Vorzeichen +, -
eScannedType == NUMBERFORMAT_UNDEFINED && // nicht D oder C
nDecPos == 0 && // kein Dezimalkomma vorher
(i >= nAnzStrings || // kein Endstring oder ,
sStrArray[i] == pFormatter->GetLocaleData()->getNumDecimalSep())
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
}
break;
case 2 : // Genau 2 Zahlen in Eingabe
{ // nAnzStrings >= 3
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // naechstes Symbol, i=2,3
GetNextNumber(i,j); // i=3,4
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION) // Sonderfall -1.200, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
}
break;
case 3 : // Genau 3 Zahlen in Eingabe
{ // nAnzStrings >= 5
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
if (nDecPos == 1) // , am Anfang => Fehler
return FALSE;
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=2,3
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j); // i=3,4
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=4,5
GetNextNumber(i,j); // i=5,6
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION)// Sonderfall -1.200.100, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return FALSE; // #36857# kein echter Bruch
}
break;
default: // Mehr als 3 Zahlen in Eingabe
{ // nAnzStrings >= 7
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyse des Anfangsstrings
if (!ScanStartString( sStrArray[i], pFormat ))
return FALSE; // schon fehlerhaft
i++; // i=1
if (nDecPos == 1) // , am Anfang => Fehler
return FALSE;
}
GetNextNumber(i,j); // i=1,2
if (!ScanMidString(sStrArray[i], i))
return FALSE;
i++; // i=2,3
USHORT nThOld = 10; // != 0 oder 1
while (nThOld != nThousand && j < nAnzNums-1)
// mindestens ein Mal
// aber eine Zahl noch lassen
{ // Abarbeitung Tausenderpkte.
nThOld = nThousand;
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanMidString(sStrArray[i], i))
return FALSE;
i++;
}
if (eScannedType == NUMBERFORMAT_DATE || // Abarbeitung langes Datum
eScannedType == NUMBERFORMAT_TIME || // lange Uhrzeit
eScannedType == NUMBERFORMAT_UNDEFINED) // oder lange Zahl
{
for (USHORT k = j; k < nAnzNums-1; k++)
{
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E nur am Ende
return FALSE;
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanMidString(sStrArray[i], i))
return FALSE;
i++;
}
}
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return FALSE;
if (eSetType == NUMBERFORMAT_FRACTION)// Sonderfall -1.200.100, als Bruch
{
if (!nNegCheck && // kein Vorzeichen '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // kein Dezimalz. oder hinten
)
{
eScannedType = NUMBERFORMAT_FRACTION;
return TRUE;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return FALSE; // #36857# kein echter Bruch
}
}
if (eScannedType == NUMBERFORMAT_UNDEFINED) // alles andere sollte bereits
eScannedType = NUMBERFORMAT_NUMBER; // erkannt sein
return TRUE;
}
//---------------------------------------------------------------------------
// Initialize uppercase months and weekdays
void ImpSvNumberInputScan::InitText()
{
sal_Int32 j, nElems;
const CharClass* pChrCls = pFormatter->GetCharClass();
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const CalendarWrapper* pCal = pFormatter->GetCalendar();
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > xElems
= pCal->getMonths();
nElems = xElems.getLength();
pUpperMonthText = new String[nElems];
pUpperAbbrevMonthText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperMonthText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevMonthText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
xElems = pCal->getDays();
nElems = xElems.getLength();
pUpperDayText = new String[nElems];
pUpperAbbrevDayText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperDayText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevDayText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
bTextInitialized = TRUE;
}
//===========================================================================
// P U B L I C
//---------------------------------------------------------------------------
// ChangeIntl
//
// MUST be called if International/Locale is changed
void ImpSvNumberInputScan::ChangeIntl()
{
sal_Unicode cDecSep = pFormatter->GetNumDecimalSep().GetChar(0);
bDecSepInDateSeps = ( cDecSep == '-' ||
cDecSep == '/' ||
cDecSep == '.' ||
cDecSep == pFormatter->GetDateSep().GetChar(0) );
bTextInitialized = FALSE;
aUpperCurrSymbol.Erase();
}
//---------------------------------------------------------------------------
// ChangeNullDate
void ImpSvNumberInputScan::ChangeNullDate(
const USHORT nDay,
const USHORT nMonth,
const USHORT nYear )
{
if ( pNullDate )
*pNullDate = Date(nDay, nMonth, nYear);
else
pNullDate = new Date(nDay, nMonth, nYear);
}
//---------------------------------------------------------------------------
// IsNumberFormat
//
// => String als Zahl darstellbar
BOOL ImpSvNumberInputScan::IsNumberFormat(
const String& rString, // zu analysierender String
short& F_Type, // IN: alter Typ, OUT: neuer Typ
double& fOutNumber, // OUT: Zahl, wenn Umwandlung moeglich
const SvNumberformat* pFormat ) // evtl. gesetztes Zahlenformat
{
// in den zerlegten Strings gibt es keine Null-Laengen Strings mehr!
String sResString; // die Eingabe fuer atof
BOOL res; // Rueckgabewert
eSetType = F_Type; // Typ der Zelle
if ( !rString.Len() )
res = FALSE;
else if (rString.Len() > 308) // frueher 100
res = FALSE;
else
res = IsNumberFormatMain(rString, fOutNumber, pFormat);
if (res)
{
if ( nNegCheck // ')' nicht gefunden
|| (eScannedType == NUMBERFORMAT_TIME // Zeit mit Vorzeichen
&& nSign) )
res = FALSE;
else // Check der Zahlanzahlen
{
switch (eScannedType) // Analyseergebnis pruefen
{
case NUMBERFORMAT_PERCENT: // alle Zahlen
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
if (nDecPos == 1) // ,05
{
if (nAnzNums != 1)
res = FALSE;
}
else if (nDecPos == 2) // 1,05
{
if (nAnzNums != nThousand+2)
res = FALSE;
}
else // 1.100 oder 1.100,
{
if (nAnzNums != nThousand+1)
res = FALSE;
}
break;
case NUMBERFORMAT_SCIENTIFIC: // wissenschaftl. Format 1,0e-2
if (nDecPos == 1) // ,05
{
if (nAnzNums != 2)
res = FALSE;
}
else if (nDecPos == 2) // 1,05
{
if (nAnzNums != nThousand+3)
res = FALSE;
}
else // 1.100 oder 1.100,
{
if (nAnzNums != nThousand+2)
res = FALSE;
}
break;
case NUMBERFORMAT_DATE: // Datum
if (nMonth)
{
if (nAnzNums > 2)
res = FALSE;
}
else
{
if (nAnzNums > 3)
res = FALSE;
}
break;
case NUMBERFORMAT_TIME: // Uhrzeit
if (nDecPos)
{
if (nAnzNums > 4)
res = FALSE;
}
else
{
if (nAnzNums > 3)
res = FALSE;
}
break;
case NUMBERFORMAT_DATETIME: // Datum + Uhrzeit
if (nMonth)
{
if (nAnzNums > 5)
res = FALSE;
}
else
{
if (nAnzNums > 6)
res = FALSE;
}
break;
default:
break;
} // switch
} // else
} // if (res)
if (res) // Bestimmung der Zahl:
{
switch (eScannedType)
{
case NUMBERFORMAT_LOGICAL: // Logisch
if (nLogical == 1)
fOutNumber = 1.0; // True
else if (nLogical == -1)
fOutNumber = 0.0; // False
else
res = FALSE; // Oops
break;
case NUMBERFORMAT_PERCENT: // Zahlen
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_SCIENTIFIC: // erstmal Zahlanteil
if (nDecPos == 1) // , am Anfang
{
sResString.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "0." ) );
sResString += sStrArray[nNums[0]];
}
else
{ USHORT k;
sResString = sStrArray[nNums[0]];
for ( k = 1; k <= nThousand; k++)
sResString += sStrArray[nNums[k]]; // Vorkommateil
if (nDecPos == 2) // in der Mitte
{
sResString += '.';
sResString += sStrArray[nNums[k]];
}
}
if (eScannedType != NUMBERFORMAT_SCIENTIFIC)
fOutNumber = StringToDouble(sResString);
else // Nachbehandlung Exponent
{
sResString += 'E';
if ( nESign == -1 )
sResString += '-';
if (nDecPos == 2)
sResString += sStrArray[nNums[nThousand+2]];
else
sResString += sStrArray[nNums[nThousand+1]];
int nErrno = 0;
fOutNumber = SolarMath::StringToDouble(
sResString.GetBuffer(), ',', '.', nErrno );
if ( nErrno == ERANGE )
{
F_Type = NUMBERFORMAT_TEXT; // overflow/underflow -> Text
if (nESign == -1)
fOutNumber = 0.0;
else
fOutNumber = DBL_MAX;
/*!*/ return TRUE;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 ) // Vorzeichen dazu
fOutNumber = -fOutNumber;
if (eScannedType == NUMBERFORMAT_PERCENT) // durch 100 dividieren
fOutNumber/= 100.0;
break;
case NUMBERFORMAT_FRACTION: // Bruch
if (nAnzNums == 1)
fOutNumber = StringToDouble(sStrArray[nNums[0]]);
else if (nAnzNums == 2)
{
if (nThousand == 1)
{
sResString = sStrArray[nNums[0]];
sResString += sStrArray[nNums[1]]; // Vorkommateil
fOutNumber = StringToDouble(sResString);
}
else
{
double fZaehler = StringToDouble(sStrArray[nNums[0]]);
double fNenner = StringToDouble(sStrArray[nNums[1]]);
if (fNenner != 0.0)
fOutNumber = fZaehler/fNenner;
else
res = FALSE;
}
}
else // nAnzNums > 2
{
USHORT k = 1;
sResString = sStrArray[nNums[0]];
if (nThousand > 0)
for (k = 1; k <= nThousand; k++)
sResString += sStrArray[nNums[k]];
fOutNumber = StringToDouble(sResString);
if (k == nAnzNums-2)
{
double fZaehler = StringToDouble(sStrArray[nNums[k]]);
double fNenner = StringToDouble(sStrArray[nNums[k+1]]);
if (fNenner != 0.0)
fOutNumber += fZaehler/fNenner;
else
res = FALSE;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 ) // Vorzeichen dazu
fOutNumber = -fOutNumber;
break;
case NUMBERFORMAT_TIME: // Uhrzeit
GetTimeRef(fOutNumber, 0, nAnzNums);
break;
case NUMBERFORMAT_DATE: // Datum
{
Date aDt; // heute
USHORT nCounter = 0; // hier dummy
res = GetDateRef(aDt, nCounter, pFormat); // Datum->aDt
if ( res )
{
long nDate = (long) (aDt - *pNullDate); // erst nach long!!
fOutNumber = (double) nDate; // vorsichtshalber
}
}
break;
case NUMBERFORMAT_DATETIME: // Datum mit Uhrzeit
{
Date aDt; // heute
USHORT nCounter; // hier wichtig
res = GetDateRef(aDt, nCounter, pFormat); // Datum->aDt
double fTime;
GetTimeRef(fTime, nCounter, nAnzNums-nCounter);
if ( res )
{
long nDate = (long) (aDt - *pNullDate);
fOutNumber = (double) nDate + fTime;
}
}
break;
default:
break;
}
}
if (res) // Ueberlauf -> Text
{
if (fOutNumber < -DBL_MAX) // -1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = -DBL_MAX;
return TRUE;
}
else if (fOutNumber > DBL_MAX) // 1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = DBL_MAX;
return TRUE;
}
}
if (res == FALSE)
{
eScannedType = NUMBERFORMAT_TEXT;
fOutNumber = 0.0;
}
F_Type = eScannedType;
return res;
}
|
/*************************************************************************
*
* $RCSfile: zforscan.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: mba $ $Date: 2001-06-11 09:23:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <stdlib.h>
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _SYSTEM_HXX //autogen
#include <vcl/system.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _UNOTOOLS_NUMBERFORMATCODEWRAPPER_HXX
#include <unotools/numberformatcodewrapper.hxx>
#endif
//#include "iniman.hxx"
#include "zforlist.hxx"
#include "zformat.hxx"
#define _ZFORSCAN_CXX
#include "zforscan.hxx"
#undef _ZFORSCAN_CXX
String ImpSvNumberformatScan::theEnglishColors[SC_MAX_ANZ_STANDARD_FARBEN] =
{
String( RTL_CONSTASCII_USTRINGPARAM( "BLACK" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "BLUE" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "GREEN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "CYAN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "RED" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "MAGENTA" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "BROWN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "GREY" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "YELLOW" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "WHITE" ) )
};
ImpSvNumberformatScan::ImpSvNumberformatScan( SvNumberFormatter* pFormatterP )
{
pFormatter = pFormatterP;
bConvertMode = FALSE;
//! All keywords MUST be UPPERCASE!
sKeyword[NF_KEY_E].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "E" ) ); // Exponent
sKeyword[NF_KEY_AMPM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AM/PM" ) ); // AM/PM
sKeyword[NF_KEY_AP].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "A/P" ) ); // AM/PM short
sKeyword[NF_KEY_MI].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) ); // Minute
sKeyword[NF_KEY_MMI].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) ); // Minute 02
sKeyword[NF_KEY_S].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "S" ) ); // Second
sKeyword[NF_KEY_SS].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "SS" ) ); // Second 02
sKeyword[NF_KEY_Q].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Q" ) ); // Quarter short 'Q'
sKeyword[NF_KEY_QQ].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "QQ" ) ); // Quarter long
sKeyword[NF_KEY_NN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NN" ) ); // Day of week short
sKeyword[NF_KEY_NNN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NNN" ) ); // Day of week long
sKeyword[NF_KEY_NNNN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NNNN" ) ); // Day of week long incl. separator
sKeyword[NF_KEY_WW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WW" ) ); // Week of year
sKeyword[NF_KEY_CCC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CCC" ) ); // Currency abbreviation
SetDependentKeywords();
StandardColor[0] = Color(COL_BLACK);
StandardColor[1] = Color(COL_LIGHTBLUE);
StandardColor[2] = Color(COL_LIGHTGREEN);
StandardColor[3] = Color(COL_LIGHTCYAN);
StandardColor[4] = Color(COL_LIGHTRED);
StandardColor[5] = Color(COL_LIGHTMAGENTA);
StandardColor[6] = Color(COL_BROWN);
StandardColor[7] = Color(COL_GRAY);
StandardColor[8] = Color(COL_YELLOW);
StandardColor[9] = Color(COL_WHITE);
pNullDate = new Date(30,12,1899);
nStandardPrec = 2;
sErrStr.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "###" ) );
Reset();
}
ImpSvNumberformatScan::~ImpSvNumberformatScan()
{
delete pNullDate;
Reset();
}
void ImpSvNumberformatScan::SetDependentKeywords()
{
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
const CharClass* pCharClass = pFormatter->GetCharClass();
const LocaleDataWrapper* pLocaleData = pFormatter->GetLocaleData();
// #80023# be sure to generate keywords for the loaded Locale, not for the
// requested Locale, otherwise number format codes might not match
lang::Locale aLoadedLocale = pLocaleData->getLoadedLocale();
LanguageType eLang = ConvertIsoNamesToLanguage( aLoadedLocale.Language, aLoadedLocale.Country );
NumberFormatCodeWrapper aNumberFormatCode( pFormatter->GetServiceManager(), aLoadedLocale );
i18n::NumberFormatCode aFormat = aNumberFormatCode.getFormatCode( NF_NUMBER_STANDARD );
sNameStandardFormat = aFormat.Code;
sKeyword[NF_KEY_GENERAL] = pCharClass->upper( sNameStandardFormat );
// preset new calendar keywords
sKeyword[NF_KEY_AAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAA" ) );
sKeyword[NF_KEY_AAAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAAA" ) );
sKeyword[NF_KEY_EC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "E" ) );
sKeyword[NF_KEY_EEC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "EE" ) );
sKeyword[NF_KEY_G].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "G" ) );
sKeyword[NF_KEY_GG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GG" ) );
sKeyword[NF_KEY_GGG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGG" ) );
sKeyword[NF_KEY_R].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "R" ) );
sKeyword[NF_KEY_RR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "RR" ) );
switch ( eLang )
{
case LANGUAGE_GERMAN:
case LANGUAGE_GERMAN_SWISS:
case LANGUAGE_GERMAN_AUSTRIAN:
case LANGUAGE_GERMAN_LUXEMBOURG:
case LANGUAGE_GERMAN_LIECHTENSTEIN:
{
//! all capital letters
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) ); // month 1
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) ); // month 01
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMM" ) ); // month Jan
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMM" ) ); // month Januar
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMMM" ) );// month J
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "H" ) ); // hour 2
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "HH" ) ); // hour 02
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "T" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TT" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TTT" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TTTT" ) );
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
sKeyword[NF_KEY_BOOLEAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "LOGISCH" ) );
sKeyword[NF_KEY_COLOR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "FARBE" ) );
sKeyword[NF_KEY_BLACK].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "SCHWARZ" ) );
sKeyword[NF_KEY_BLUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLAU" ) );
sKeyword[NF_KEY_GREEN] = UniString( "GR" "\xDC" "N", RTL_TEXTENCODING_ISO_8859_1 );
sKeyword[NF_KEY_CYAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CYAN" ) );
sKeyword[NF_KEY_RED].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "ROT" ) );
sKeyword[NF_KEY_MAGENTA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MAGENTA" ) );
sKeyword[NF_KEY_BROWN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BRAUN" ) );
sKeyword[NF_KEY_GREY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GRAU" ) );
sKeyword[NF_KEY_YELLOW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GELB" ) );
sKeyword[NF_KEY_WHITE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WEISS" ) );
}
break;
default:
{
// day
switch ( eLang )
{
case LANGUAGE_ITALIAN :
case LANGUAGE_ITALIAN_SWISS :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "G" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GG" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGG" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGGG" ) );
// must exchange the era code, same as Xcl
sKeyword[NF_KEY_G].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "X" ) );
sKeyword[NF_KEY_GG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "XX" ) );
sKeyword[NF_KEY_GGG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "XXX" ) );
break;
case LANGUAGE_FRENCH :
case LANGUAGE_FRENCH_BELGIAN :
case LANGUAGE_FRENCH_CANADIAN :
case LANGUAGE_FRENCH_SWISS :
case LANGUAGE_FRENCH_LUXEMBOURG :
case LANGUAGE_FRENCH_MONACO :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "J" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJ" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
break;
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "P" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PP" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PPP" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PPPP" ) );
break;
default:
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "D" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DD" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DDD" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DDDD" ) );
}
// month
switch ( eLang )
{
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "K" ) );
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KK" ) );
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKK" ) );
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKKK" ) );
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKKKK" ) );
break;
default:
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) );
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) );
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMM" ) );
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMM" ) );
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMMM" ) );
}
// year
switch ( eLang )
{
case LANGUAGE_ITALIAN :
case LANGUAGE_ITALIAN_SWISS :
case LANGUAGE_FRENCH :
case LANGUAGE_FRENCH_BELGIAN :
case LANGUAGE_FRENCH_CANADIAN :
case LANGUAGE_FRENCH_SWISS :
case LANGUAGE_FRENCH_LUXEMBOURG :
case LANGUAGE_FRENCH_MONACO :
case LANGUAGE_PORTUGUESE :
case LANGUAGE_PORTUGUESE_BRAZILIAN :
case LANGUAGE_SPANISH :
case LANGUAGE_SPANISH_MEXICAN :
case LANGUAGE_SPANISH_MODERN :
case LANGUAGE_SPANISH_GUATEMALA :
case LANGUAGE_SPANISH_COSTARICA :
case LANGUAGE_SPANISH_PANAMA :
case LANGUAGE_SPANISH_DOMINICAN_REPUBLIC :
case LANGUAGE_SPANISH_VENEZUELA :
case LANGUAGE_SPANISH_COLOMBIA :
case LANGUAGE_SPANISH_PERU :
case LANGUAGE_SPANISH_ARGENTINA :
case LANGUAGE_SPANISH_ECUADOR :
case LANGUAGE_SPANISH_CHILE :
case LANGUAGE_SPANISH_URUGUAY :
case LANGUAGE_SPANISH_PARAGUAY :
case LANGUAGE_SPANISH_BOLIVIA :
case LANGUAGE_SPANISH_EL_SALVADOR :
case LANGUAGE_SPANISH_HONDURAS :
case LANGUAGE_SPANISH_NICARAGUA :
case LANGUAGE_SPANISH_PUERTO_RICO :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AA" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAAA" ) );
// must exchange the day of week name code, same as Xcl
sKeyword[NF_KEY_AAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "OOO" ) );
sKeyword[NF_KEY_AAAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "OOOO" ) );
break;
case LANGUAGE_DUTCH :
case LANGUAGE_DUTCH_BELGIAN :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
break;
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "VV" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "VVVV" ) );
break;
default:
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YY" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YYYY" ) );
}
// hour
switch ( eLang )
{
case LANGUAGE_DUTCH :
case LANGUAGE_DUTCH_BELGIAN :
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "U" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "UU" ) );
break;
case LANGUAGE_FINNISH :
case LANGUAGE_SWEDISH :
case LANGUAGE_SWEDISH_FINLAND :
case LANGUAGE_DANISH :
case LANGUAGE_NORWEGIAN :
case LANGUAGE_NORWEGIAN_BOKMAL :
case LANGUAGE_NORWEGIAN_NYNORSK :
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "T" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TT" ) );
break;
default:
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "H" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "HH" ) );
}
// boolean
sKeyword[NF_KEY_BOOLEAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BOOLEAN" ) );
// colours
sKeyword[NF_KEY_COLOR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "COLOR" ) );
sKeyword[NF_KEY_BLACK].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLACK" ) );
sKeyword[NF_KEY_BLUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLUE" ) );
sKeyword[NF_KEY_GREEN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GREEN" ) );
sKeyword[NF_KEY_CYAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CYAN" ) );
sKeyword[NF_KEY_RED].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "RED" ) );
sKeyword[NF_KEY_MAGENTA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MAGENTA" ) );
sKeyword[NF_KEY_BROWN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BROWN" ) );
sKeyword[NF_KEY_GREY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GREY" ) );
sKeyword[NF_KEY_YELLOW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YELLOW" ) );
sKeyword[NF_KEY_WHITE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WHITE" ) );
}
break;
}
// boolean keyords
sKeyword[NF_KEY_TRUE] = pCharClass->upper( pLocaleData->getTrueWord() );
if ( !sKeyword[NF_KEY_TRUE].Len() )
{
DBG_ERRORFILE( "SetDependentKeywords: TRUE_WORD?" );
sKeyword[NF_KEY_TRUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TRUE" ) );
}
sKeyword[NF_KEY_FALSE] = pCharClass->upper( pLocaleData->getFalseWord() );
if ( !sKeyword[NF_KEY_FALSE].Len() )
{
DBG_ERRORFILE( "SetDependentKeywords: FALSE_WORD?" );
sKeyword[NF_KEY_FALSE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "FALSE" ) );
}
// currency symbol for old style ("automatic") compatibility format codes
pFormatter->GetCompatibilityCurrency( sCurSymbol, sCurAbbrev );
// currency symbol upper case
sCurString = pCharClass->upper( sCurSymbol );
}
void ImpSvNumberformatScan::ChangeNullDate(USHORT nDay, USHORT nMonth, USHORT nYear)
{
if ( pNullDate )
*pNullDate = Date(nDay, nMonth, nYear);
else
pNullDate = new Date(nDay, nMonth, nYear);
}
void ImpSvNumberformatScan::ChangeStandardPrec(short nPrec)
{
nStandardPrec = nPrec;
}
Color* ImpSvNumberformatScan::GetColor(String& sStr)
{
String sString = pFormatter->GetCharClass()->upper(sStr);
USHORT i = 0;
while (i < SC_MAX_ANZ_STANDARD_FARBEN &&
sString != sKeyword[NF_KEY_FIRSTCOLOR+i] )
i++;
if ( i >= SC_MAX_ANZ_STANDARD_FARBEN )
{
USHORT j = 0;
while ( j < SC_MAX_ANZ_STANDARD_FARBEN &&
sString != theEnglishColors[j] )
++j;
if ( j < SC_MAX_ANZ_STANDARD_FARBEN )
i = j;
}
if (i >= SC_MAX_ANZ_STANDARD_FARBEN)
{
const String& rColorWord = sKeyword[NF_KEY_COLOR];
xub_StrLen nPos = sString.Match(rColorWord);
if (nPos > 0)
{
sStr.Erase(0, nPos);
sStr.EraseLeadingChars();
sStr.EraseTrailingChars();
if (bConvertMode)
{
pFormatter->ChangeIntl(eNewLnge);
sStr.Insert(rColorWord,0); // Color -> FARBE
pFormatter->ChangeIntl(eTmpLnge);
}
else
sStr.Insert(rColorWord,0);
sString.Erase(0, nPos);
sString.EraseLeadingChars();
sString.EraseTrailingChars();
if ( CharClass::isAsciiNumeric( sString ) )
{
long nIndex = sString.ToInt32();
if (nIndex > 0 && nIndex <= 64)
return pFormatter->GetUserDefColor((USHORT)nIndex-1);
else
return NULL;
}
else
return NULL;
}
else
return NULL;
}
else
{
sStr.Erase();
if (bConvertMode)
{
pFormatter->ChangeIntl(eNewLnge);
sStr = sKeyword[NF_KEY_FIRSTCOLOR+i]; // red -> rot
pFormatter->ChangeIntl(eTmpLnge);
}
else
sStr = sKeyword[NF_KEY_FIRSTCOLOR+i];
return &(StandardColor[i]);
}
}
void ImpSvNumberformatScan::ChangeIntl()
{
SetDependentKeywords();
}
short ImpSvNumberformatScan::GetKeyWord( const String& sSymbol, xub_StrLen nPos )
{
String sString = pFormatter->GetCharClass()->toUpper( sSymbol, nPos, sSymbol.Len() - nPos );
// #77026# for the Xcl perverts: the GENERAL keyword is recognized anywhere
if ( sString.Search( sKeyword[NF_KEY_GENERAL] ) == 0 )
return NF_KEY_GENERAL;
//! MUST be a reverse search to find longer strings first
short i = NF_KEYWORD_ENTRIES_COUNT-1;
BOOL bFound;
while ( i > NF_KEY_LASTKEYWORD_SO5 && !(bFound = (sString.Search(sKeyword[i]) == 0)) )
i--;
// new keywords take precedence over old keywords
if ( !bFound )
{ // skip the gap of colors et al between new and old keywords and search on
i = NF_KEY_LASTKEYWORD;
while ( i > 0 && sString.Search(sKeyword[i]) != 0 )
i--;
if ( i > NF_KEY_LASTOLDKEYWORD && sString != sKeyword[i] )
{ // found something, but maybe it's something else?
// e.g. new NNN is found in NNNN, for NNNN we must search on
short j = i - 1;
while ( j > 0 && sString.Search(sKeyword[j]) != 0 )
j--;
if ( j && sKeyword[j].Len() > sKeyword[i].Len() )
return j;
}
}
return i; // 0 => not found
}
//---------------------------------------------------------------------------
// Next_Symbol
//---------------------------------------------------------------------------
// Zerlegt die Eingabe in Symbole fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = SsStart
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// SsStart | Buchstabe | Symbol=Zeichen | SsGetWord
// | " | Typ = String | SsGetString
// | \ | Typ = String | SsGetChar
// | * | Typ = Star | SsGetStar
// | _ | Typ = Blank | SsGetBlank
// | @ # 0 ? / . , % [ | Symbol = Zeichen; |
// | ] ' Blank | Typ = Steuerzeichen | SsStop
// | $ - + ( ) : | Typ = String; |
// | | | Typ = Comment | SsStop
// | Sonst | Symbol = Zeichen | SsStop
//---------------|-------------------+-----------------------+---------------
// SsGetChar | Sonst | Symbol=Zeichen | SsStop
//---------------+-------------------+-----------------------+---------------
// GetString | " | | SsStop
// | Sonst | Symbol+=Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
// SsGetWord | Buchstabe | Symbol += Zeichen |
// | + - (E+ E-)| Symbol += Zeichen | SsStop
// | / (AM/PM)| Symbol += Zeichen |
// | Sonst | Pos--, if Key Typ=Word| SsStop
//---------------+-------------------+-----------------------+---------------
// SsGetStar | Sonst | Symbol+=Zeichen | SsStop
// | | markiere Sonderfall * |
//---------------+-------------------+-----------------------+---------------
// SsGetBlank | Sonst | Symbol+=Zeichen | SsStop
// | | markiere Sonderfall _ |
//---------------+-------------------+-----------------------+---------------
// Wurde im State SsGetWord ein Schluesselwort erkannt (auch als
// Anfangsteilwort des Symbols)
// so werden die restlichen Buchstaben zurueckgeschrieben !!
enum ScanState
{
SsStop = 0,
SsStart = 1,
SsGetChar = 2,
SsGetString = 3,
SsGetWord = 4,
SsGetStar = 5,
SsGetBlank = 6
};
short ImpSvNumberformatScan::Next_Symbol( const String& rStr,
xub_StrLen& nPos, String& sSymbol )
{
const CharClass* pChrCls = pFormatter->GetCharClass();
const xub_StrLen nStart = nPos;
short eType;
ScanState eState = SsStart;
sSymbol.Erase();
while ( nPos < rStr.Len() && eState != SsStop )
{
sal_Unicode cToken = rStr.GetChar( nPos++ );
switch (eState)
{
case SsStart:
{
// Fetch any currency longer than one character and don't get
// confused later on by "E/" or other combinations of letters
// and meaningful symbols.
if ( nCurrPos != STRING_NOTFOUND && sCurString.Len() > 1 &&
nPos-1 + sCurString.Len() <= rStr.Len() )
{
String aTest( rStr.Copy( nPos-1, sCurString.Len() ) );
pChrCls->toUpper( aTest );
if ( aTest == sCurString )
{
sSymbol = rStr.Copy( --nPos, sCurString.Len() );
nPos += sSymbol.Len();
eState = SsStop;
eType = SYMBOLTYPE_STRING;
return eType;
}
}
switch (cToken)
{
case '#':
case '0':
case '?':
case '%':
case '@':
case '[':
case ']':
case ',':
case '.':
case '/':
case '\'':
case ' ':
case ':':
case '-':
{
eType = SYMBOLTYPE_DEL;
sSymbol += cToken;
eState = SsStop;
}
break;
case '*':
{
eType = SYMBOLTYPE_STAR;
sSymbol += cToken;
eState = SsGetStar;
}
break;
case '_':
{
eType = SYMBOLTYPE_BLANK;
sSymbol += cToken;
eState = SsGetBlank;
}
break;
#if NF_COMMENT_IN_FORMATSTRING
case '{':
eType = SYMBOLTYPE_COMMENT;
eState = SsStop;
sSymbol.Append( rStr.GetBuffer() + (nPos-1), rStr.Len() - (nPos-1) );
nPos = rStr.Len();
break;
#endif
case '"':
eType = SYMBOLTYPE_STRING;
eState = SsGetString;
sSymbol += cToken;
break;
case '\\':
eType = SYMBOLTYPE_STRING;
eState = SsGetChar;
sSymbol += cToken;
break;
case '$':
case '+':
case '(':
case ')':
eType = SYMBOLTYPE_STRING;
eState = SsStop;
sSymbol += cToken;
break;
default :
{
if ( pChrCls->isLetter( rStr, nPos-1 ) )
{
short nTmpType = GetKeyWord( rStr, nPos-1 );
if ( nTmpType )
{
BOOL bCurrency = FALSE;
// "Automatic" currency may start with keyword,
// like "R" (Rand) and 'R' (era)
if ( nCurrPos != STRING_NOTFOUND &&
nPos-1 + sCurString.Len() <= rStr.Len() &&
sCurString.Search( sKeyword[nTmpType] ) == 0 )
{
String aTest( rStr.Copy( nPos-1, sCurString.Len() ) );
pChrCls->toUpper( aTest );
if ( aTest == sCurString )
bCurrency = TRUE;
}
if ( bCurrency )
{
eState = SsGetWord;
sSymbol += cToken;
}
else
{
eType = nTmpType;
xub_StrLen nLen = sKeyword[eType].Len();
sSymbol = rStr.Copy( nPos-1, nLen );
if ( eType == NF_KEY_E || IsAmbiguousE( eType ) )
{
sal_Unicode cNext = rStr.GetChar(nPos);
switch ( cNext )
{
case '+' :
case '-' : // E+ E- combine to one symbol
sSymbol += cNext;
eType = NF_KEY_E;
nPos++;
break;
case '0' :
case '#' : // scientific E without sign
eType = NF_KEY_E;
break;
}
}
nPos--;
nPos += nLen;
eState = SsStop;
}
}
else
{
eState = SsGetWord;
sSymbol += cToken;
}
}
else
{
eType = SYMBOLTYPE_STRING;
eState = SsStop;
sSymbol += cToken;
}
}
break;
}
}
break;
case SsGetChar:
{
sSymbol += cToken;
eState = SsStop;
}
break;
case SsGetString:
{
if (cToken == '"')
eState = SsStop;
sSymbol += cToken;
}
break;
case SsGetWord:
{
if ( pChrCls->isLetter( rStr, nPos-1 ) )
{
short nTmpType = GetKeyWord( rStr, nPos-1 );
if ( nTmpType )
{ // beginning of keyword, stop scan and put back
eType = SYMBOLTYPE_STRING;
eState = SsStop;
nPos--;
}
else
sSymbol += cToken;
}
else
{
BOOL bDontStop = FALSE;
switch (cToken)
{
case '/': // AM/PM, A/P
{
sal_Unicode cNext = rStr.GetChar(nPos);
if ( cNext == 'P' || cNext == 'p' )
{
xub_StrLen nLen = sSymbol.Len();
if ( 1 <= nLen
&& (sSymbol.GetChar(0) == 'A' || sSymbol.GetChar(0) == 'a')
&& (nLen == 1 || (nLen == 2
&& (sSymbol.GetChar(1) == 'M' || sSymbol.GetChar(1) == 'm')
&& (rStr.GetChar(nPos+1) == 'M' || rStr.GetChar(nPos+1) == 'm'))) )
{
sSymbol += cToken;
bDontStop = TRUE;
}
}
}
break;
}
// anything not recognized will stop the scan
if ( eState != SsStop && !bDontStop )
{
eState = SsStop;
nPos--;
eType = SYMBOLTYPE_STRING;
}
}
}
break;
case SsGetStar:
{
eState = SsStop;
sSymbol += cToken;
nRepPos = (nPos - nStart) - 1; // everytime > 0!!
}
break;
case SsGetBlank:
{
eState = SsStop;
sSymbol += cToken;
}
break;
default:
break;
} // of switch
} // of while
if (eState == SsGetWord)
eType = SYMBOLTYPE_STRING;
return eType;
}
xub_StrLen ImpSvNumberformatScan::Symbol_Division(const String& rString)
{
nCurrPos = STRING_NOTFOUND;
// Ist Waehrung im Spiel?
String sString = pFormatter->GetCharClass()->upper(rString);
xub_StrLen nCPos = 0;
while (nCPos != STRING_NOTFOUND)
{
nCPos = sString.Search(sCurString,nCPos);
if (nCPos != STRING_NOTFOUND)
{
// in Quotes?
xub_StrLen nQ = SvNumberformat::GetQuoteEnd( sString, nCPos );
if ( nQ == STRING_NOTFOUND )
{
sal_Unicode c;
if ( nCPos == 0 ||
((c = sString.GetChar(xub_StrLen(nCPos-1))) != '"'
&& c != '\\') ) // dm kann durch "dm
{ // \d geschuetzt werden
nCurrPos = nCPos;
nCPos = STRING_NOTFOUND; // Abbruch
}
else
nCPos++; // weitersuchen
}
else
nCPos = nQ + 1; // weitersuchen
}
}
nAnzStrings = 0;
BOOL bStar = FALSE; // wird bei '*'Detektion gesetzt
Reset();
xub_StrLen nPos = 0;
const xub_StrLen nLen = rString.Len();
while (nPos < nLen && nAnzStrings < SC_MAX_ANZ_FORMAT_STRINGS)
{
nTypeArray[nAnzStrings] = Next_Symbol(rString, nPos, sStrArray[nAnzStrings]);
if (nTypeArray[nAnzStrings] == SYMBOLTYPE_STAR)
{ // Ueberwachung des '*'
if (bStar)
return nPos; // Fehler: doppelter '*'
else
bStar = TRUE;
}
nAnzStrings++;
}
return 0; // 0 => ok
}
void ImpSvNumberformatScan::SkipStrings(USHORT& i, xub_StrLen& nPos)
{
while (i < nAnzStrings && ( nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_BLANK
|| nTypeArray[i] == SYMBOLTYPE_STAR) )
{
nPos += sStrArray[i].Len();
i++;
}
}
USHORT ImpSvNumberformatScan::PreviousKeyword(USHORT i)
{
short res = 0;
if (i > 0 && i < nAnzStrings)
{
i--;
while (i > 0 && nTypeArray[i] <= 0)
i--;
if (nTypeArray[i] > 0)
res = nTypeArray[i];
}
return res;
}
USHORT ImpSvNumberformatScan::NextKeyword(USHORT i)
{
short res = 0;
if (i < nAnzStrings-1)
{
i++;
while (i < nAnzStrings-1 && nTypeArray[i] <= 0)
i++;
if (nTypeArray[i] > 0)
res = nTypeArray[i];
}
return res;
}
short ImpSvNumberformatScan::PreviousType( USHORT i )
{
if ( i > 0 && i < nAnzStrings )
{
do
{
i--;
} while ( i > 0 && nTypeArray[i] == SYMBOLTYPE_EMPTY );
return nTypeArray[i];
}
return 0;
}
sal_Unicode ImpSvNumberformatScan::PreviousChar(USHORT i)
{
sal_Unicode res = ' ';
if (i > 0 && i < nAnzStrings)
{
i--;
while (i > 0 && ( nTypeArray[i] == SYMBOLTYPE_EMPTY
|| nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_STAR
|| nTypeArray[i] == SYMBOLTYPE_BLANK ) )
i--;
if (sStrArray[i].Len() > 0)
res = sStrArray[i].GetChar(xub_StrLen(sStrArray[i].Len()-1));
}
return res;
}
sal_Unicode ImpSvNumberformatScan::NextChar(USHORT i)
{
sal_Unicode res = ' ';
if (i < nAnzStrings-1)
{
i++;
while (i < nAnzStrings-1 &&
( nTypeArray[i] == SYMBOLTYPE_EMPTY
|| nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_STAR
|| nTypeArray[i] == SYMBOLTYPE_BLANK))
i++;
if (sStrArray[i].Len() > 0)
res = sStrArray[i].GetChar(0);
}
return res;
}
BOOL ImpSvNumberformatScan::IsLastBlankBeforeFrac(USHORT i)
{
BOOL res = TRUE;
if (i < nAnzStrings-1)
{
BOOL bStop = FALSE;
i++;
while (i < nAnzStrings-1 && !bStop)
{
i++;
if ( nTypeArray[i] == SYMBOLTYPE_DEL &&
sStrArray[i].GetChar(0) == '/')
bStop = TRUE;
else if ( nTypeArray[i] == SYMBOLTYPE_DEL &&
sStrArray[i].GetChar(0) == ' ')
res = FALSE;
}
if (!bStop) // kein '/'
res = FALSE;
}
else
res = FALSE; // kein '/' mehr
return res;
}
void ImpSvNumberformatScan::Reset()
{
nAnzStrings = 0;
nAnzResStrings = 0;
#if 0
// ER 20.06.97 14:05 nicht noetig, wenn nAnzStrings beachtet wird
for (USHORT i = 0; i < SC_MAX_ANZ_FORMAT_STRINGS; i++)
{
sStrArray[i].Erase();
nTypeArray[i] = 0;
}
#endif
eScannedType = NUMBERFORMAT_UNDEFINED;
nRepPos = 0;
bExp = FALSE;
bThousand = FALSE;
nThousand = 0;
bDecSep = FALSE;
nDecPos = -1;
nExpPos = (USHORT) -1;
nBlankPos = (USHORT) -1;
nCntPre = 0;
nCntPost = 0;
nCntExp = 0;
bFrac = FALSE;
bBlank = FALSE;
}
xub_StrLen ImpSvNumberformatScan::ScanType(const String& rString)
{
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
xub_StrLen nPos = 0;
USHORT i = 0; // durchlaeuft die Symbole
short eNewType; // neu erkannter Typ
SkipStrings(i, nPos); // Ausgabestrings ueberlesen
while (i < nAnzStrings)
{
if (nTypeArray[i] > 0) // Schluesselwort
{
switch (nTypeArray[i])
{
case NF_KEY_E: // E
eNewType = NUMBERFORMAT_SCIENTIFIC;
break;
case NF_KEY_AMPM: // AM,A,PM,P
case NF_KEY_AP:
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
eNewType = NUMBERFORMAT_TIME;
break;
case NF_KEY_M: // M
case NF_KEY_MM: // MM
{ // Sonderfall: Minute oder Monat
USHORT nIndexPre = PreviousKeyword(i);
USHORT nIndexNex = NextKeyword(i);
sal_Unicode cChar = PreviousChar(i);
if (nIndexPre == NF_KEY_H || // H
nIndexPre == NF_KEY_HH || // HH
nIndexNex == NF_KEY_S || // S
nIndexNex == NF_KEY_SS || // SS
cChar == '[' ) // [M
{
eNewType = NUMBERFORMAT_TIME;
nTypeArray[i] -= 2; // 6 -> 4, 7 -> 5
}
else
eNewType = NUMBERFORMAT_DATE;
}
break;
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
eNewType = NUMBERFORMAT_DATE;
break;
case NF_KEY_CCC: // CCC
eNewType = NUMBERFORMAT_CURRENCY;
break;
case NF_KEY_GENERAL: // Standard
eNewType = NUMBERFORMAT_NUMBER;
break;
default:
eNewType = NUMBERFORMAT_UNDEFINED;
break;
}
}
else // Steuerzeichen
{
switch ( sStrArray[i].GetChar(0) )
{
case '#':
case '?':
eNewType = NUMBERFORMAT_NUMBER;
break;
case '0':
{
if (eScannedType == NUMBERFORMAT_TIME)
{
USHORT nIndexPre = PreviousKeyword(i);
if ((nIndexPre == NF_KEY_S || nIndexPre == NF_KEY_SS)
&& bDecSep) // S, SS ','
eNewType = NUMBERFORMAT_TIME;
else
return nPos; // Fehler
}
else
eNewType = NUMBERFORMAT_NUMBER;
}
break;
case ',':
case '.':
{
bDecSep = TRUE; // fuer SS,0
eNewType = NUMBERFORMAT_UNDEFINED;
}
break;
case '%':
eNewType = NUMBERFORMAT_PERCENT;
break;
case '/':
eNewType = NUMBERFORMAT_FRACTION;
break;
case '[':
{
if ( i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '$' )
{ // as of SV_NUMBERFORMATTER_VERSION_NEW_CURR
eNewType = NUMBERFORMAT_CURRENCY;
}
else if ( i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '~' )
{ // as of SV_NUMBERFORMATTER_VERSION_CALENDAR
eNewType = NUMBERFORMAT_DATE;
}
else
{
USHORT nIndexNex = NextKeyword(i);
if (nIndexNex == NF_KEY_H || // H
nIndexNex == NF_KEY_HH || // HH
nIndexNex == NF_KEY_M || // M
nIndexNex == NF_KEY_MM || // MM
nIndexNex == NF_KEY_S || // S
nIndexNex == NF_KEY_SS ) // SS
eNewType = NUMBERFORMAT_TIME;
else
return nPos; // Fehler
}
}
break;
case '@':
eNewType = NUMBERFORMAT_TEXT;
break;
default:
eNewType = NUMBERFORMAT_UNDEFINED;
break;
}
}
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = eNewType;
else if (eScannedType == NUMBERFORMAT_TEXT || eNewType == NUMBERFORMAT_TEXT)
eScannedType = NUMBERFORMAT_TEXT; // Text bleibt immer Text
else if (eNewType == NUMBERFORMAT_UNDEFINED)
{ // bleibt wie bisher
}
else if (eScannedType != eNewType)
{
switch (eScannedType)
{
case NUMBERFORMAT_DATE:
{
switch (eNewType)
{
case NUMBERFORMAT_TIME:
eScannedType = NUMBERFORMAT_DATETIME;
break;
case NUMBERFORMAT_FRACTION: // DD/MM
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getDateSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_TIME:
{
switch (eNewType)
{
case NUMBERFORMAT_DATE:
eScannedType = NUMBERFORMAT_DATETIME;
break;
case NUMBERFORMAT_FRACTION: // MM/SS
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getTimeSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_DATETIME:
{
switch (eNewType)
{
case NUMBERFORMAT_TIME:
case NUMBERFORMAT_DATE:
break;
case NUMBERFORMAT_FRACTION: // DD/MM
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getDateSep()
&& sStrArray[i] != pLoc->getTimeSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_PERCENT:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach Prozent
break;
default:
return nPos;
}
}
break;
case NUMBERFORMAT_SCIENTIFIC:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach E
break;
default:
return nPos;
}
}
break;
case NUMBERFORMAT_NUMBER:
{
switch (eNewType)
{
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_FRACTION:
case NUMBERFORMAT_CURRENCY:
eScannedType = eNewType;
break;
default:
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else
return nPos;
}
}
break;
case NUMBERFORMAT_FRACTION:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach Bruch
break;
default:
return nPos;
}
}
break;
default:
break;
}
}
nPos += sStrArray[i].Len(); // Korrekturposition
i++;
SkipStrings(i, nPos);
}
if ((eScannedType == NUMBERFORMAT_NUMBER || eScannedType == NUMBERFORMAT_UNDEFINED)
&& nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_CURRENCY; // old "automatic" currency
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = NUMBERFORMAT_DEFINED;
return 0; // Alles ok
}
int ImpSvNumberformatScan::FinalScanGetCalendar( xub_StrLen& nPos, USHORT& i,
USHORT& nAnzResStrings )
{
if ( sStrArray[i].GetChar(0) == '[' &&
i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '~' )
{ // [~calendarID]
// as of SV_NUMBERFORMATTER_VERSION_CALENDAR
nPos += sStrArray[i].Len(); // [
nTypeArray[i] = SYMBOLTYPE_CALDEL;
nPos += sStrArray[++i].Len(); // ~
sStrArray[i-1] += sStrArray[i]; // [~
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
if ( ++i >= nAnzStrings )
return -1; // error
nPos += sStrArray[i].Len(); // calendarID
String& rStr = sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CALENDAR; // convert
i++;
while ( i < nAnzStrings &&
sStrArray[i].GetChar(0) != ']' )
{
nPos += sStrArray[i].Len();
rStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
if ( rStr.Len() && i < nAnzStrings &&
sStrArray[i].GetChar(0) == ']' )
{
nTypeArray[i] = SYMBOLTYPE_CALDEL;
nPos += sStrArray[i].Len();
i++;
}
else
return -1; // error
return 1;
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::FinalScan( String& rString, String& rComment )
{
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const CharClass* pChrCls = pFormatter->GetCharClass();
// save values for convert mode
String sOldDecSep = pLoc->getNumDecimalSep();
String sOldThousandSep = pLoc->getNumThousandSep();
String sOldDateSep = pLoc->getDateSep();
String sOldTimeSep = pLoc->getTimeSep();
String sOldCurSymbol = sCurSymbol;
String sOldCurString = sCurString;
// If the group separator is a Non-Breaking Space (French) continue with a
// normal space instead so queries on space work correctly.
// The format string is adjusted to allow both.
// For output of the format code string the LocaleData characters are used.
if ( sOldThousandSep.GetChar(0) == 0xA0 && sOldThousandSep.Len() == 1 )
sOldThousandSep = ' ';
// change locale data et al
if (bConvertMode)
pFormatter->ChangeIntl(eNewLnge);
xub_StrLen nPos = 0; // Korrekturposition
USHORT i = 0; // durchlaeuft die Symbole
USHORT nCounter = 0; // Zaehlt Ziffern
nAnzResStrings = nAnzStrings; // Zaehlt uebrigbleibende Symbole
bDecSep = FALSE; // falls schon in TypeCeck benutzt
switch (eScannedType)
{
case NUMBERFORMAT_TEXT:
case NUMBERFORMAT_DEFINED:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
break;
case NF_KEY_GENERAL : // #77026# "General" is the same as "@"
break;
default:
{
if ( nTypeArray[i] != SYMBOLTYPE_DEL ||
sStrArray[i].GetChar(0) != '@' )
nTypeArray[i] = SYMBOLTYPE_STRING;
}
break;
}
nPos += sStrArray[i].Len();
i++;
} // of while
}
break;
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_FRACTION:
{
sal_Unicode cThousandFill = ' ';
while (i < nAnzStrings)
{
if (eScannedType == NUMBERFORMAT_FRACTION && // special case
nTypeArray[i] == SYMBOLTYPE_DEL && // # ### #/#
StringEqualsChar( sOldThousandSep, ' ' ) && // e.g. France or Sweden
StringEqualsChar( sStrArray[i], ' ' ) &&
!bFrac &&
IsLastBlankBeforeFrac(i) )
{
nTypeArray[i] = SYMBOLTYPE_STRING; // del->string
} // kein Taus.p.
if (nTypeArray[i] == SYMBOLTYPE_BLANK ||
nTypeArray[i] == SYMBOLTYPE_STAR ||
nTypeArray[i] == NF_KEY_CCC || // CCC
nTypeArray[i] == NF_KEY_GENERAL ) // Standard
{
if (nTypeArray[i] == NF_KEY_GENERAL)
{
nThousand = FLAG_STANDARD_IN_FORMAT;
if ( bConvertMode )
sStrArray[i] = sNameStandardFormat;
}
nPos += sStrArray[i].Len();
i++;
}
else if (nTypeArray[i] == SYMBOLTYPE_STRING || // Strings oder
nTypeArray[i] > 0) // Keywords
{
if (eScannedType == NUMBERFORMAT_SCIENTIFIC &&
nTypeArray[i] == NF_KEY_E) // E+
{
if (bExp) // doppelt
return nPos;
bExp = TRUE;
nExpPos = i;
if (bDecSep)
nCntPost = nCounter;
else
nCntPre = nCounter;
nCounter = 0;
nTypeArray[i] = SYMBOLTYPE_EXP;
}
else if (eScannedType == NUMBERFORMAT_FRACTION &&
sStrArray[i].GetChar(0) == ' ')
{
if (!bBlank && !bFrac) // nicht doppelt oder hinter /
{
if (bDecSep && nCounter > 0) // Nachkommastellen
return nPos; // Fehler
bBlank = TRUE;
nBlankPos = i;
nCntPre = nCounter;
nCounter = 0;
}
nTypeArray[i] = SYMBOLTYPE_FRACBLANK;
}
else
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if (nTypeArray[i] == SYMBOLTYPE_DEL)
{
sal_Unicode cHere = sStrArray[i].GetChar(0);
switch ( cHere )
{
case '#':
case '0':
case '?':
{
if (nThousand > 0) // #... #
return nPos; // Fehler
else if (bFrac && cHere == '0')
return nPos; // 0 im Nenner
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nCounter++;
while (i < nAnzStrings &&
(sStrArray[i].GetChar(0) == '#' ||
sStrArray[i].GetChar(0) == '0' ||
sStrArray[i].GetChar(0) == '?')
)
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
break;
case '-':
{
if ( bDecSep && nDecPos < i &&
nTypeArray[nDecPos] == SYMBOLTYPE_DECSEP )
{ // "0,--"
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nCounter++;
while (i < nAnzStrings &&
(sStrArray[i].GetChar(0) == '-') )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case '.':
case ',':
case '\'':
case ' ':
{
sal_Unicode cSep = cHere; // remember
if ( StringEqualsChar( sOldThousandSep, cSep ) )
{
if (bConvertMode)
sStrArray[i] = pLoc->getNumThousandSep();
// previous char with skip empty
sal_Unicode cPre = PreviousChar(i);
sal_Unicode cNext;
if (bExp || bBlank || bFrac)
{ // after E, / or ' '
if ( !StringEqualsChar( sOldThousandSep, ' ' ) )
{
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++; // eat it
}
else
nTypeArray[i] = SYMBOLTYPE_STRING;
}
else if (i > 0 && i < nAnzStrings-1 &&
(cPre == '#' || cPre == '0') &&
((cNext = NextChar(i)) == '#' || cNext == '0')
) // #,#
{
nPos += sStrArray[i].Len();
if (!bThousand) // only once
{ // set hard, in case of Non-Breaking Space
sStrArray[i] = pLoc->getNumThousandSep();
nTypeArray[i] = SYMBOLTYPE_THSEP;
bThousand = TRUE;
cThousandFill = sStrArray[i+1].GetChar(0);
}
else // eat it
{
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i++;
}
else if (i > 0 && (cPre == '#' || cPre == '0')
&& PreviousType(i) == SYMBOLTYPE_DIGIT
&& nThousand < FLAG_STANDARD_IN_FORMAT )
{ // #,,,,
if ( StringEqualsChar( sOldThousandSep, ' ' ) )
{ // strange, those French..
BOOL bFirst = TRUE;
String& rStr = sStrArray[i];
// set a hard Non-Breaking Space
const String& rSepF = pLoc->getNumThousandSep();
while ( i < nAnzStrings
&& sStrArray[i] == sOldThousandSep
&& StringEqualsChar( sOldThousandSep, NextChar(i) ) )
{ // last was a space or another space
// is following => separator
nPos += sStrArray[i].Len();
if ( bFirst )
{
bFirst = FALSE;
rStr = rSepF;
nTypeArray[i] = SYMBOLTYPE_THSEP;
}
else
{
rStr += rSepF;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
nThousand++;
i++;
}
if ( i < nAnzStrings-1
&& sStrArray[i] == sOldThousandSep )
{ // something following last space
// => space if currency contained,
// else separator
nPos += sStrArray[i].Len();
if ( (nPos <= nCurrPos &&
nCurrPos < nPos + sStrArray[i+1].Len())
|| nTypeArray[i+1] == NF_KEY_CCC
|| (i < nAnzStrings-2 &&
sStrArray[i+1].GetChar(0) == '[' &&
sStrArray[i+2].GetChar(0) == '$') )
{
nTypeArray[i] = SYMBOLTYPE_STRING;
}
else
{
if ( bFirst )
{
bFirst = FALSE;
rStr = rSepF;
nTypeArray[i] = SYMBOLTYPE_THSEP;
}
else
{
rStr += rSepF;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
nThousand++;
}
i++;
}
}
else
{
nTypeArray[i] = SYMBOLTYPE_THSEP;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nThousand++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldThousandSep )
{
nThousand++;
rStr += pLoc->getNumThousandSep();
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
else // any grsep
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldThousandSep )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
else if ( StringEqualsChar( sOldDecSep, cSep ) )
{
if (bConvertMode)
sStrArray[i] = pLoc->getNumDecimalSep();
if (bBlank || bFrac) // . behind / or ' '
return nPos; // error
else if (bExp) // behind E
{
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++; // eat it
}
else if (bDecSep) // any .
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldDecSep )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
else
{
nTypeArray[i] = SYMBOLTYPE_DECSEP;
bDecSep = TRUE;
nDecPos = i;
nCntPre = nCounter;
nCounter = 0;
nPos += sStrArray[i].Len();
i++;
}
} // of else = DecSep
else // . without meaning
{
if (cSep == ' ' &&
eScannedType == NUMBERFORMAT_FRACTION &&
StringEqualsChar( sStrArray[i], ' ' ) )
{
if (!bBlank && !bFrac) // no dups
{ // or behind /
if (bDecSep && nCounter > 0)// dec.
return nPos; // error
bBlank = TRUE;
nBlankPos = i;
nCntPre = nCounter;
nCounter = 0;
}
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while (i < nAnzStrings &&
StringEqualsChar( sStrArray[i], cSep ) )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
}
break;
case '/':
{
if (eScannedType == NUMBERFORMAT_FRACTION)
{
if ( i == 0 ||
(nTypeArray[i-1] != SYMBOLTYPE_DIGIT &&
nTypeArray[i-1] != SYMBOLTYPE_EMPTY) )
return nPos ? nPos : 1; // /? not allowed
else if (!bFrac || (bDecSep && nCounter > 0))
{
bFrac = TRUE;
nCntPost = nCounter;
nCounter = 0;
nTypeArray[i] = SYMBOLTYPE_FRAC;
nPos += sStrArray[i].Len();
i++;
}
else // / doppelt od. , imZaehl
return nPos; // Fehler
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case '[' :
{
if ( eScannedType == NUMBERFORMAT_CURRENCY &&
i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '$' )
{ // [$DM-xxx]
// ab SV_NUMBERFORMATTER_VERSION_NEW_CURR
nPos += sStrArray[i].Len(); // [
nTypeArray[i] = SYMBOLTYPE_CURRDEL;
nPos += sStrArray[++i].Len(); // $
sStrArray[i-1] += sStrArray[i]; // [$
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
if ( ++i >= nAnzStrings )
return nPos; // Fehler
nPos += sStrArray[i].Len(); // DM
String& rStr = sStrArray[i];
String* pStr = &sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CURRENCY; // wandeln
BOOL bHadDash = FALSE;
i++;
while ( i < nAnzStrings &&
sStrArray[i].GetChar(0) != ']' )
{
nPos += sStrArray[i].Len();
if ( bHadDash )
{
*pStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
else
{
if ( sStrArray[i].GetChar(0) == '-' )
{
bHadDash = TRUE;
pStr = &sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CURREXT;
}
else
{
*pStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
}
i++;
}
if ( rStr.Len() && i < nAnzStrings &&
sStrArray[i].GetChar(0) == ']' )
{
nTypeArray[i] = SYMBOLTYPE_CURRDEL;
nPos += sStrArray[i].Len();
i++;
}
else
return nPos; // Fehler
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
default: // andere Dels
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
} // of switch (Del)
} // of else Del
else if ( nTypeArray[i] == SYMBOLTYPE_COMMENT )
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
else
{
DBG_ERRORFILE( "unknown SYMBOLTYPE_..." );
nPos += sStrArray[i].Len();
i++;
}
} // of while
if (eScannedType == NUMBERFORMAT_FRACTION)
{
if (bFrac)
nCntExp = nCounter;
else if (bBlank)
nCntPost = nCounter;
else
nCntPre = nCounter;
}
else
{
if (bExp)
nCntExp = nCounter;
else if (bDecSep)
nCntPost = nCounter;
else
nCntPre = nCounter;
}
if (nThousand == 0 && bThousand) // Expansion Tausenderpunkt:
{
USHORT nMaxPos;
if (bFrac)
{
if (bBlank)
nMaxPos = nBlankPos;
else
nMaxPos = 0; // keine Expansion
}
else if (bDecSep) // , vorhanden
nMaxPos = nDecPos;
else if (bExp) // E vorhanden
nMaxPos = nExpPos;
else // sonst bis Ende
nMaxPos = i;
i = 0;
long nCount = nCntPre;
while (i < nMaxPos && nTypeArray[i] != SYMBOLTYPE_THSEP) // nur bis zum ,
{
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
nCount -= sStrArray[i].Len();
i++;
}
USHORT nPosThSep = i; // Position merken
i++; // Ziffern hinter .
xub_StrLen nFill = 0;
if (nCount > 0) // muesste immer sein
nFill = xub_StrLen(nCount % 3);
if (nFill)
{
nFill = 3 - nFill;
if (i < nMaxPos)
for (xub_StrLen k = 0; k < nFill; k++)
sStrArray[i].Insert(cThousandFill,0);
nCntPre += USHORT(nFill);
}
nCount = 0; // Aufuellen mit .
while (i < nMaxPos) // nach hinten
{
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
{
xub_StrLen nLen = sStrArray[i].Len();
if (nCount+nLen > 3)
{ // hier muss . dazwischen
xub_StrLen nAnz = (nLen+nCount-4)/3+1;
xub_StrLen InPos = 3-nCount;
for (xub_StrLen k = 0; k < nAnz; k++)
{
sStrArray[i].Insert(
pLoc->getNumThousandSep(),InPos);
InPos += 4;
}
nCount = sStrArray[i].Len() - InPos + 3;
}
else
nCount += sStrArray[i].Len();
}
i++;
}
nCount = 0; // Aufuellen mit .
i = nPosThSep; // nach vorn
while (i > 0)
{
i--;
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
{
xub_StrLen nLen = sStrArray[i].Len();
if (nCount+nLen > 3)
{ // hier muss . dazwischen
xub_StrLen nAnz = (nLen+nCount-4)/3+1;
xub_StrLen InPos = nLen + nCount - 3;
for (xub_StrLen k = 0; k < nAnz; k++)
{
sStrArray[i].Insert(
pLoc->getNumThousandSep(),InPos);
InPos -= 3;
}
nCount = InPos + 3;
}
else
nCount += sStrArray[i].Len();
}
}
}
}
break; // of NUMBERFORMAT_NUMBER
case NUMBERFORMAT_DATE:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
case SYMBOLTYPE_STRING:
nPos += sStrArray[i].Len();
i++;
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case SYMBOLTYPE_DEL:
{
int nCalRet;
if (bConvertMode && sStrArray[i] == sOldDateSep)
{
sStrArray[i] = pLoc->getDateSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if ( (nCalRet = FinalScanGetCalendar( nPos, i, nAnzResStrings )) != 0 )
{
if ( nCalRet < 0 )
return nPos; // error
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case NF_KEY_M: // M
case NF_KEY_MM: // MM
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
break;
default: // andere Keywords
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
break;
}
} // of while
}
break; // of NUMBERFORMAT_DATE
case NUMBERFORMAT_TIME:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
{
nPos += sStrArray[i].Len();
i++;
}
break;
case SYMBOLTYPE_DEL:
{
switch( sStrArray[i].GetChar(0) )
{
case '0':
{
if (bDecSep)
{
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
i++;
nPos += sStrArray[i].Len();
nCounter++;
while (i < nAnzStrings &&
sStrArray[i].GetChar(0) == '0')
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
else
return nPos;
}
break;
case '#':
case '?':
return nPos;
break;
case '.':
case ',':
{
bDecSep = TRUE;
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
case '[':
{
if (bThousand) // doppelt
return nPos;
bThousand = TRUE; // bei Time frei
sal_Unicode cChar = pChrCls->upper( NextChar(i) ).GetChar(0);
if ( cChar == sKeyword[NF_KEY_H].GetChar(0) )
nThousand = 1; // H
else if ( cChar == sKeyword[NF_KEY_MI].GetChar(0) )
nThousand = 2; // M
else if ( cChar == sKeyword[NF_KEY_S].GetChar(0) )
nThousand = 3; // S
else
return nPos;
nPos += sStrArray[i].Len();
i++;
}
case ']':
{
if (!bThousand) // kein [ vorher
return nPos;
nPos += sStrArray[i].Len();
i++;
}
break;
default:
{
if (bConvertMode && sStrArray[i] == sOldTimeSep)
sStrArray[i] = pLoc->getTimeSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
}
}
break;
case SYMBOLTYPE_STRING:
{
nPos += sStrArray[i].Len();
i++;
}
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case NF_KEY_AMPM: // AM/PM
case NF_KEY_AP: // A/P
{
bExp = TRUE; // missbraucht fuer A/P
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
}
break;
case NF_KEY_MI: // M
case NF_KEY_MMI: // MM
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
{
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
}
break;
default: // andere Keywords
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
}
} // of while
nCntPost = nCounter; // Zaehler der Nullen
if (bExp)
nCntExp = 1; // merkt AM/PM
}
break; // of NUMBERFORMAT_TIME
case NUMBERFORMAT_DATETIME:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
case SYMBOLTYPE_STRING:
nPos += sStrArray[i].Len();
i++;
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case SYMBOLTYPE_DEL:
{
int nCalRet;
if (bConvertMode && sStrArray[i] == sOldDateSep)
{
sStrArray[i] = pLoc->getDateSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if (bConvertMode && sStrArray[i] == sOldTimeSep)
{
sStrArray[i] = pLoc->getTimeSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if ( (nCalRet = FinalScanGetCalendar( nPos, i, nAnzResStrings )) != 0 )
{
if ( nCalRet < 0 )
return nPos; // error
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case NF_KEY_AMPM: // AM/PM
case NF_KEY_AP: // A/P
{
bExp = TRUE; // missbraucht fuer A/P
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
case NF_KEY_MI: // M
case NF_KEY_MMI: // MM
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
case NF_KEY_M: // M
case NF_KEY_MM: // MM
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
break;
default: // andere Keywords
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
break;
}
} // of while
if (bExp)
nCntExp = 1; // merkt AM/PM
}
break; // of NUMBERFORMAT_DATETIME
default:
break;
}
if (eScannedType == NUMBERFORMAT_SCIENTIFIC &&
(nCntPre + nCntPost == 0 || nCntExp == 0))
return nPos;
else if (eScannedType == NUMBERFORMAT_FRACTION && (nCntExp > 8 || nCntExp == 0))
return nPos;
if ( bConvertMode )
{ // strings containing keywords of the target locale must be quoted, so
// the user sees the difference and is able to edit the format string
for ( i=0; i < nAnzStrings; i++ )
{
if ( nTypeArray[i] == SYMBOLTYPE_STRING &&
sStrArray[i].GetChar(0) != '\"' )
{
if ( bConvertSystemToSystem && eScannedType == NUMBERFORMAT_CURRENCY )
{ // don't stringize automatic currency, will be converted
if ( sStrArray[i] == sOldCurSymbol )
continue; // for
// DM might be splitted into D and M
if ( sStrArray[i].Len() < sOldCurSymbol.Len() &&
pChrCls->toUpper( sStrArray[i], 0, 1 ).GetChar(0) ==
sOldCurString.GetChar(0) )
{
String aTmp( sStrArray[i] );
USHORT j = i + 1;
while ( aTmp.Len() < sOldCurSymbol.Len() &&
j < nAnzStrings &&
nTypeArray[j] == SYMBOLTYPE_STRING )
{
aTmp += sStrArray[j++];
}
if ( pChrCls->upper( aTmp ) == sOldCurString )
{
sStrArray[i++] = aTmp;
for ( ; i<j; i++ )
{
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i = j - 1;
continue; // for
}
}
}
String& rStr = sStrArray[i];
xub_StrLen nLen = rStr.Len();
for ( xub_StrLen j=0; j<nLen; j++ )
{
if ( (j == 0 || rStr.GetChar(j-1) != '\\') && GetKeyWord( rStr, j ) )
{
rStr.Insert( '\"', 0 );
rStr += '\"';
break; // for
}
}
}
}
}
// concatenate strings, remove quotes for output, and rebuild the format string
rString.Erase();
i = 0;
while (i < nAnzStrings)
{
switch ( nTypeArray[i] )
{
case SYMBOLTYPE_STRING :
{
xub_StrLen nStringPos = rString.Len();
xub_StrLen nArrPos = 0;
USHORT iPos = i;
do
{
rString += sStrArray[i];
if ( RemoveQuotes( sStrArray[i] ) > 0 )
{ // update currency up to quoted string
if ( eScannedType == NUMBERFORMAT_CURRENCY )
{ // dM -> DM or DM -> $ in old automatic
// currency formats, oh my ..., why did we ever
// introduce them?
String aTmp( pChrCls->toUpper(
sStrArray[iPos], nArrPos,
sStrArray[iPos].Len()-nArrPos ) );
xub_StrLen nCPos = aTmp.Search( sOldCurString );
if ( nCPos != STRING_NOTFOUND )
{
const String& rCur =
bConvertMode && bConvertSystemToSystem ?
sCurSymbol : sOldCurSymbol;
sStrArray[iPos].Replace( nArrPos+nCPos,
sOldCurString.Len(), rCur );
rString.Replace( nStringPos+nCPos,
sOldCurString.Len(), rCur );
}
nStringPos = rString.Len();
if ( iPos == i )
nArrPos = sStrArray[iPos].Len();
else
nArrPos = sStrArray[iPos].Len() + sStrArray[i].Len();
}
}
if ( iPos != i )
{
sStrArray[iPos] += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i++;
} while ( i < nAnzStrings && nTypeArray[i] == SYMBOLTYPE_STRING );
if ( i < nAnzStrings )
i--; // enter switch on next symbol again
if ( eScannedType == NUMBERFORMAT_CURRENCY && nStringPos < rString.Len() )
{ // same as above, since last RemoveQuotes
String aTmp( pChrCls->toUpper(
sStrArray[iPos], nArrPos,
sStrArray[iPos].Len()-nArrPos ) );
xub_StrLen nCPos = aTmp.Search( sOldCurString );
if ( nCPos != STRING_NOTFOUND )
{
const String& rCur =
bConvertMode && bConvertSystemToSystem ?
sCurSymbol : sOldCurSymbol;
sStrArray[iPos].Replace( nArrPos+nCPos,
sOldCurString.Len(), rCur );
rString.Replace( nStringPos+nCPos,
sOldCurString.Len(), rCur );
}
}
}
break;
case SYMBOLTYPE_CURRENCY :
{
rString += sStrArray[i];
RemoveQuotes( sStrArray[i] );
}
break;
case SYMBOLTYPE_EMPTY :
// nothing
break;
default:
rString += sStrArray[i];
}
i++;
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::RemoveQuotes( String& rStr )
{
if ( rStr.Len() > 1 )
{
sal_Unicode c = rStr.GetChar(0);
xub_StrLen n;
if ( c == '"' && rStr.GetChar( (n = xub_StrLen(rStr.Len()-1)) ) == '"' )
{
rStr.Erase(n,1);
rStr.Erase(0,1);
return 2;
}
else if ( c == '\\' )
{
rStr.Erase(0,1);
return 1;
}
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::ScanFormat( String& rString, String& rComment )
{
xub_StrLen res = Symbol_Division(rString); //lexikalische Analyse
if (!res)
res = ScanType(rString); // Erkennung des Formattyps
if (!res)
res = FinalScan( rString, rComment ); // Typabhaengige Endanalyse
return res; // res = Kontrollposition
// res = 0 => Format ok
}
void ImpSvNumberformatScan::CopyInfo(ImpSvNumberformatInfo* pInfo, USHORT nAnz)
{
USHORT i,j;
j = 0;
i = 0;
while (i < nAnz && j < SC_MAX_ANZ_FORMAT_STRINGS)
{
if (nTypeArray[j] != SYMBOLTYPE_EMPTY)
{
pInfo->sStrArray[i] = sStrArray[j];
pInfo->nTypeArray[i] = nTypeArray[j];
i++;
}
j++;
}
pInfo->eScannedType = eScannedType;
pInfo->bThousand = bThousand;
pInfo->nThousand = nThousand;
pInfo->nCntPre = nCntPre;
pInfo->nCntPost = nCntPost;
pInfo->nCntExp = nCntExp;
}
#89253# don't get confused by space as group separator on convert mode
/*************************************************************************
*
* $RCSfile: zforscan.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: er $ $Date: 2001-07-04 17:33:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <stdlib.h>
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _SYSTEM_HXX //autogen
#include <vcl/system.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _UNOTOOLS_NUMBERFORMATCODEWRAPPER_HXX
#include <unotools/numberformatcodewrapper.hxx>
#endif
//#include "iniman.hxx"
#include "zforlist.hxx"
#include "zformat.hxx"
#define _ZFORSCAN_CXX
#include "zforscan.hxx"
#undef _ZFORSCAN_CXX
String ImpSvNumberformatScan::theEnglishColors[SC_MAX_ANZ_STANDARD_FARBEN] =
{
String( RTL_CONSTASCII_USTRINGPARAM( "BLACK" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "BLUE" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "GREEN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "CYAN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "RED" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "MAGENTA" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "BROWN" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "GREY" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "YELLOW" ) ),
String( RTL_CONSTASCII_USTRINGPARAM( "WHITE" ) )
};
ImpSvNumberformatScan::ImpSvNumberformatScan( SvNumberFormatter* pFormatterP )
{
pFormatter = pFormatterP;
bConvertMode = FALSE;
//! All keywords MUST be UPPERCASE!
sKeyword[NF_KEY_E].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "E" ) ); // Exponent
sKeyword[NF_KEY_AMPM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AM/PM" ) ); // AM/PM
sKeyword[NF_KEY_AP].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "A/P" ) ); // AM/PM short
sKeyword[NF_KEY_MI].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) ); // Minute
sKeyword[NF_KEY_MMI].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) ); // Minute 02
sKeyword[NF_KEY_S].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "S" ) ); // Second
sKeyword[NF_KEY_SS].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "SS" ) ); // Second 02
sKeyword[NF_KEY_Q].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Q" ) ); // Quarter short 'Q'
sKeyword[NF_KEY_QQ].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "QQ" ) ); // Quarter long
sKeyword[NF_KEY_NN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NN" ) ); // Day of week short
sKeyword[NF_KEY_NNN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NNN" ) ); // Day of week long
sKeyword[NF_KEY_NNNN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "NNNN" ) ); // Day of week long incl. separator
sKeyword[NF_KEY_WW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WW" ) ); // Week of year
sKeyword[NF_KEY_CCC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CCC" ) ); // Currency abbreviation
SetDependentKeywords();
StandardColor[0] = Color(COL_BLACK);
StandardColor[1] = Color(COL_LIGHTBLUE);
StandardColor[2] = Color(COL_LIGHTGREEN);
StandardColor[3] = Color(COL_LIGHTCYAN);
StandardColor[4] = Color(COL_LIGHTRED);
StandardColor[5] = Color(COL_LIGHTMAGENTA);
StandardColor[6] = Color(COL_BROWN);
StandardColor[7] = Color(COL_GRAY);
StandardColor[8] = Color(COL_YELLOW);
StandardColor[9] = Color(COL_WHITE);
pNullDate = new Date(30,12,1899);
nStandardPrec = 2;
sErrStr.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "###" ) );
Reset();
}
ImpSvNumberformatScan::~ImpSvNumberformatScan()
{
delete pNullDate;
Reset();
}
void ImpSvNumberformatScan::SetDependentKeywords()
{
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
const CharClass* pCharClass = pFormatter->GetCharClass();
const LocaleDataWrapper* pLocaleData = pFormatter->GetLocaleData();
// #80023# be sure to generate keywords for the loaded Locale, not for the
// requested Locale, otherwise number format codes might not match
lang::Locale aLoadedLocale = pLocaleData->getLoadedLocale();
LanguageType eLang = ConvertIsoNamesToLanguage( aLoadedLocale.Language, aLoadedLocale.Country );
NumberFormatCodeWrapper aNumberFormatCode( pFormatter->GetServiceManager(), aLoadedLocale );
i18n::NumberFormatCode aFormat = aNumberFormatCode.getFormatCode( NF_NUMBER_STANDARD );
sNameStandardFormat = aFormat.Code;
sKeyword[NF_KEY_GENERAL] = pCharClass->upper( sNameStandardFormat );
// preset new calendar keywords
sKeyword[NF_KEY_AAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAA" ) );
sKeyword[NF_KEY_AAAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAAA" ) );
sKeyword[NF_KEY_EC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "E" ) );
sKeyword[NF_KEY_EEC].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "EE" ) );
sKeyword[NF_KEY_G].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "G" ) );
sKeyword[NF_KEY_GG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GG" ) );
sKeyword[NF_KEY_GGG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGG" ) );
sKeyword[NF_KEY_R].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "R" ) );
sKeyword[NF_KEY_RR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "RR" ) );
switch ( eLang )
{
case LANGUAGE_GERMAN:
case LANGUAGE_GERMAN_SWISS:
case LANGUAGE_GERMAN_AUSTRIAN:
case LANGUAGE_GERMAN_LUXEMBOURG:
case LANGUAGE_GERMAN_LIECHTENSTEIN:
{
//! all capital letters
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) ); // month 1
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) ); // month 01
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMM" ) ); // month Jan
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMM" ) ); // month Januar
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMMM" ) );// month J
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "H" ) ); // hour 2
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "HH" ) ); // hour 02
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "T" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TT" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TTT" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TTTT" ) );
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
sKeyword[NF_KEY_BOOLEAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "LOGISCH" ) );
sKeyword[NF_KEY_COLOR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "FARBE" ) );
sKeyword[NF_KEY_BLACK].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "SCHWARZ" ) );
sKeyword[NF_KEY_BLUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLAU" ) );
sKeyword[NF_KEY_GREEN] = UniString( "GR" "\xDC" "N", RTL_TEXTENCODING_ISO_8859_1 );
sKeyword[NF_KEY_CYAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CYAN" ) );
sKeyword[NF_KEY_RED].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "ROT" ) );
sKeyword[NF_KEY_MAGENTA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MAGENTA" ) );
sKeyword[NF_KEY_BROWN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BRAUN" ) );
sKeyword[NF_KEY_GREY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GRAU" ) );
sKeyword[NF_KEY_YELLOW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GELB" ) );
sKeyword[NF_KEY_WHITE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WEISS" ) );
}
break;
default:
{
// day
switch ( eLang )
{
case LANGUAGE_ITALIAN :
case LANGUAGE_ITALIAN_SWISS :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "G" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GG" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGG" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GGGG" ) );
// must exchange the era code, same as Xcl
sKeyword[NF_KEY_G].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "X" ) );
sKeyword[NF_KEY_GG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "XX" ) );
sKeyword[NF_KEY_GGG].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "XXX" ) );
break;
case LANGUAGE_FRENCH :
case LANGUAGE_FRENCH_BELGIAN :
case LANGUAGE_FRENCH_CANADIAN :
case LANGUAGE_FRENCH_SWISS :
case LANGUAGE_FRENCH_LUXEMBOURG :
case LANGUAGE_FRENCH_MONACO :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "J" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJ" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
break;
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "P" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PP" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PPP" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "PPPP" ) );
break;
default:
sKeyword[NF_KEY_D].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "D" ) );
sKeyword[NF_KEY_DD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DD" ) );
sKeyword[NF_KEY_DDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DDD" ) );
sKeyword[NF_KEY_DDDD].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "DDDD" ) );
}
// month
switch ( eLang )
{
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "K" ) );
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KK" ) );
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKK" ) );
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKKK" ) );
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "KKKKK" ) );
break;
default:
sKeyword[NF_KEY_M].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "M" ) );
sKeyword[NF_KEY_MM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MM" ) );
sKeyword[NF_KEY_MMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMM" ) );
sKeyword[NF_KEY_MMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMM" ) );
sKeyword[NF_KEY_MMMMM].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MMMMM" ) );
}
// year
switch ( eLang )
{
case LANGUAGE_ITALIAN :
case LANGUAGE_ITALIAN_SWISS :
case LANGUAGE_FRENCH :
case LANGUAGE_FRENCH_BELGIAN :
case LANGUAGE_FRENCH_CANADIAN :
case LANGUAGE_FRENCH_SWISS :
case LANGUAGE_FRENCH_LUXEMBOURG :
case LANGUAGE_FRENCH_MONACO :
case LANGUAGE_PORTUGUESE :
case LANGUAGE_PORTUGUESE_BRAZILIAN :
case LANGUAGE_SPANISH :
case LANGUAGE_SPANISH_MEXICAN :
case LANGUAGE_SPANISH_MODERN :
case LANGUAGE_SPANISH_GUATEMALA :
case LANGUAGE_SPANISH_COSTARICA :
case LANGUAGE_SPANISH_PANAMA :
case LANGUAGE_SPANISH_DOMINICAN_REPUBLIC :
case LANGUAGE_SPANISH_VENEZUELA :
case LANGUAGE_SPANISH_COLOMBIA :
case LANGUAGE_SPANISH_PERU :
case LANGUAGE_SPANISH_ARGENTINA :
case LANGUAGE_SPANISH_ECUADOR :
case LANGUAGE_SPANISH_CHILE :
case LANGUAGE_SPANISH_URUGUAY :
case LANGUAGE_SPANISH_PARAGUAY :
case LANGUAGE_SPANISH_BOLIVIA :
case LANGUAGE_SPANISH_EL_SALVADOR :
case LANGUAGE_SPANISH_HONDURAS :
case LANGUAGE_SPANISH_NICARAGUA :
case LANGUAGE_SPANISH_PUERTO_RICO :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AA" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "AAAA" ) );
// must exchange the day of week name code, same as Xcl
sKeyword[NF_KEY_AAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "OOO" ) );
sKeyword[NF_KEY_AAAA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "OOOO" ) );
break;
case LANGUAGE_DUTCH :
case LANGUAGE_DUTCH_BELGIAN :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJ" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "JJJJ" ) );
break;
case LANGUAGE_FINNISH :
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "VV" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "VVVV" ) );
break;
default:
sKeyword[NF_KEY_YY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YY" ) );
sKeyword[NF_KEY_YYYY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YYYY" ) );
}
// hour
switch ( eLang )
{
case LANGUAGE_DUTCH :
case LANGUAGE_DUTCH_BELGIAN :
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "U" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "UU" ) );
break;
case LANGUAGE_FINNISH :
case LANGUAGE_SWEDISH :
case LANGUAGE_SWEDISH_FINLAND :
case LANGUAGE_DANISH :
case LANGUAGE_NORWEGIAN :
case LANGUAGE_NORWEGIAN_BOKMAL :
case LANGUAGE_NORWEGIAN_NYNORSK :
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "T" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TT" ) );
break;
default:
sKeyword[NF_KEY_H].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "H" ) );
sKeyword[NF_KEY_HH].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "HH" ) );
}
// boolean
sKeyword[NF_KEY_BOOLEAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BOOLEAN" ) );
// colours
sKeyword[NF_KEY_COLOR].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "COLOR" ) );
sKeyword[NF_KEY_BLACK].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLACK" ) );
sKeyword[NF_KEY_BLUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BLUE" ) );
sKeyword[NF_KEY_GREEN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GREEN" ) );
sKeyword[NF_KEY_CYAN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "CYAN" ) );
sKeyword[NF_KEY_RED].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "RED" ) );
sKeyword[NF_KEY_MAGENTA].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "MAGENTA" ) );
sKeyword[NF_KEY_BROWN].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "BROWN" ) );
sKeyword[NF_KEY_GREY].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "GREY" ) );
sKeyword[NF_KEY_YELLOW].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "YELLOW" ) );
sKeyword[NF_KEY_WHITE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "WHITE" ) );
}
break;
}
// boolean keyords
sKeyword[NF_KEY_TRUE] = pCharClass->upper( pLocaleData->getTrueWord() );
if ( !sKeyword[NF_KEY_TRUE].Len() )
{
DBG_ERRORFILE( "SetDependentKeywords: TRUE_WORD?" );
sKeyword[NF_KEY_TRUE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "TRUE" ) );
}
sKeyword[NF_KEY_FALSE] = pCharClass->upper( pLocaleData->getFalseWord() );
if ( !sKeyword[NF_KEY_FALSE].Len() )
{
DBG_ERRORFILE( "SetDependentKeywords: FALSE_WORD?" );
sKeyword[NF_KEY_FALSE].AssignAscii( RTL_CONSTASCII_STRINGPARAM( "FALSE" ) );
}
// currency symbol for old style ("automatic") compatibility format codes
pFormatter->GetCompatibilityCurrency( sCurSymbol, sCurAbbrev );
// currency symbol upper case
sCurString = pCharClass->upper( sCurSymbol );
}
void ImpSvNumberformatScan::ChangeNullDate(USHORT nDay, USHORT nMonth, USHORT nYear)
{
if ( pNullDate )
*pNullDate = Date(nDay, nMonth, nYear);
else
pNullDate = new Date(nDay, nMonth, nYear);
}
void ImpSvNumberformatScan::ChangeStandardPrec(short nPrec)
{
nStandardPrec = nPrec;
}
Color* ImpSvNumberformatScan::GetColor(String& sStr)
{
String sString = pFormatter->GetCharClass()->upper(sStr);
USHORT i = 0;
while (i < SC_MAX_ANZ_STANDARD_FARBEN &&
sString != sKeyword[NF_KEY_FIRSTCOLOR+i] )
i++;
if ( i >= SC_MAX_ANZ_STANDARD_FARBEN )
{
USHORT j = 0;
while ( j < SC_MAX_ANZ_STANDARD_FARBEN &&
sString != theEnglishColors[j] )
++j;
if ( j < SC_MAX_ANZ_STANDARD_FARBEN )
i = j;
}
if (i >= SC_MAX_ANZ_STANDARD_FARBEN)
{
const String& rColorWord = sKeyword[NF_KEY_COLOR];
xub_StrLen nPos = sString.Match(rColorWord);
if (nPos > 0)
{
sStr.Erase(0, nPos);
sStr.EraseLeadingChars();
sStr.EraseTrailingChars();
if (bConvertMode)
{
pFormatter->ChangeIntl(eNewLnge);
sStr.Insert(rColorWord,0); // Color -> FARBE
pFormatter->ChangeIntl(eTmpLnge);
}
else
sStr.Insert(rColorWord,0);
sString.Erase(0, nPos);
sString.EraseLeadingChars();
sString.EraseTrailingChars();
if ( CharClass::isAsciiNumeric( sString ) )
{
long nIndex = sString.ToInt32();
if (nIndex > 0 && nIndex <= 64)
return pFormatter->GetUserDefColor((USHORT)nIndex-1);
else
return NULL;
}
else
return NULL;
}
else
return NULL;
}
else
{
sStr.Erase();
if (bConvertMode)
{
pFormatter->ChangeIntl(eNewLnge);
sStr = sKeyword[NF_KEY_FIRSTCOLOR+i]; // red -> rot
pFormatter->ChangeIntl(eTmpLnge);
}
else
sStr = sKeyword[NF_KEY_FIRSTCOLOR+i];
return &(StandardColor[i]);
}
}
void ImpSvNumberformatScan::ChangeIntl()
{
SetDependentKeywords();
}
short ImpSvNumberformatScan::GetKeyWord( const String& sSymbol, xub_StrLen nPos )
{
String sString = pFormatter->GetCharClass()->toUpper( sSymbol, nPos, sSymbol.Len() - nPos );
// #77026# for the Xcl perverts: the GENERAL keyword is recognized anywhere
if ( sString.Search( sKeyword[NF_KEY_GENERAL] ) == 0 )
return NF_KEY_GENERAL;
//! MUST be a reverse search to find longer strings first
short i = NF_KEYWORD_ENTRIES_COUNT-1;
BOOL bFound;
while ( i > NF_KEY_LASTKEYWORD_SO5 && !(bFound = (sString.Search(sKeyword[i]) == 0)) )
i--;
// new keywords take precedence over old keywords
if ( !bFound )
{ // skip the gap of colors et al between new and old keywords and search on
i = NF_KEY_LASTKEYWORD;
while ( i > 0 && sString.Search(sKeyword[i]) != 0 )
i--;
if ( i > NF_KEY_LASTOLDKEYWORD && sString != sKeyword[i] )
{ // found something, but maybe it's something else?
// e.g. new NNN is found in NNNN, for NNNN we must search on
short j = i - 1;
while ( j > 0 && sString.Search(sKeyword[j]) != 0 )
j--;
if ( j && sKeyword[j].Len() > sKeyword[i].Len() )
return j;
}
}
return i; // 0 => not found
}
//---------------------------------------------------------------------------
// Next_Symbol
//---------------------------------------------------------------------------
// Zerlegt die Eingabe in Symbole fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = SsStart
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// SsStart | Buchstabe | Symbol=Zeichen | SsGetWord
// | " | Typ = String | SsGetString
// | \ | Typ = String | SsGetChar
// | * | Typ = Star | SsGetStar
// | _ | Typ = Blank | SsGetBlank
// | @ # 0 ? / . , % [ | Symbol = Zeichen; |
// | ] ' Blank | Typ = Steuerzeichen | SsStop
// | $ - + ( ) : | Typ = String; |
// | | | Typ = Comment | SsStop
// | Sonst | Symbol = Zeichen | SsStop
//---------------|-------------------+-----------------------+---------------
// SsGetChar | Sonst | Symbol=Zeichen | SsStop
//---------------+-------------------+-----------------------+---------------
// GetString | " | | SsStop
// | Sonst | Symbol+=Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
// SsGetWord | Buchstabe | Symbol += Zeichen |
// | + - (E+ E-)| Symbol += Zeichen | SsStop
// | / (AM/PM)| Symbol += Zeichen |
// | Sonst | Pos--, if Key Typ=Word| SsStop
//---------------+-------------------+-----------------------+---------------
// SsGetStar | Sonst | Symbol+=Zeichen | SsStop
// | | markiere Sonderfall * |
//---------------+-------------------+-----------------------+---------------
// SsGetBlank | Sonst | Symbol+=Zeichen | SsStop
// | | markiere Sonderfall _ |
//---------------+-------------------+-----------------------+---------------
// Wurde im State SsGetWord ein Schluesselwort erkannt (auch als
// Anfangsteilwort des Symbols)
// so werden die restlichen Buchstaben zurueckgeschrieben !!
enum ScanState
{
SsStop = 0,
SsStart = 1,
SsGetChar = 2,
SsGetString = 3,
SsGetWord = 4,
SsGetStar = 5,
SsGetBlank = 6
};
short ImpSvNumberformatScan::Next_Symbol( const String& rStr,
xub_StrLen& nPos, String& sSymbol )
{
const CharClass* pChrCls = pFormatter->GetCharClass();
const xub_StrLen nStart = nPos;
short eType;
ScanState eState = SsStart;
sSymbol.Erase();
while ( nPos < rStr.Len() && eState != SsStop )
{
sal_Unicode cToken = rStr.GetChar( nPos++ );
switch (eState)
{
case SsStart:
{
// Fetch any currency longer than one character and don't get
// confused later on by "E/" or other combinations of letters
// and meaningful symbols.
if ( nCurrPos != STRING_NOTFOUND && sCurString.Len() > 1 &&
nPos-1 + sCurString.Len() <= rStr.Len() )
{
String aTest( rStr.Copy( nPos-1, sCurString.Len() ) );
pChrCls->toUpper( aTest );
if ( aTest == sCurString )
{
sSymbol = rStr.Copy( --nPos, sCurString.Len() );
nPos += sSymbol.Len();
eState = SsStop;
eType = SYMBOLTYPE_STRING;
return eType;
}
}
switch (cToken)
{
case '#':
case '0':
case '?':
case '%':
case '@':
case '[':
case ']':
case ',':
case '.':
case '/':
case '\'':
case ' ':
case ':':
case '-':
{
eType = SYMBOLTYPE_DEL;
sSymbol += cToken;
eState = SsStop;
}
break;
case '*':
{
eType = SYMBOLTYPE_STAR;
sSymbol += cToken;
eState = SsGetStar;
}
break;
case '_':
{
eType = SYMBOLTYPE_BLANK;
sSymbol += cToken;
eState = SsGetBlank;
}
break;
#if NF_COMMENT_IN_FORMATSTRING
case '{':
eType = SYMBOLTYPE_COMMENT;
eState = SsStop;
sSymbol.Append( rStr.GetBuffer() + (nPos-1), rStr.Len() - (nPos-1) );
nPos = rStr.Len();
break;
#endif
case '"':
eType = SYMBOLTYPE_STRING;
eState = SsGetString;
sSymbol += cToken;
break;
case '\\':
eType = SYMBOLTYPE_STRING;
eState = SsGetChar;
sSymbol += cToken;
break;
case '$':
case '+':
case '(':
case ')':
eType = SYMBOLTYPE_STRING;
eState = SsStop;
sSymbol += cToken;
break;
default :
{
if ( pChrCls->isLetter( rStr, nPos-1 ) )
{
short nTmpType = GetKeyWord( rStr, nPos-1 );
if ( nTmpType )
{
BOOL bCurrency = FALSE;
// "Automatic" currency may start with keyword,
// like "R" (Rand) and 'R' (era)
if ( nCurrPos != STRING_NOTFOUND &&
nPos-1 + sCurString.Len() <= rStr.Len() &&
sCurString.Search( sKeyword[nTmpType] ) == 0 )
{
String aTest( rStr.Copy( nPos-1, sCurString.Len() ) );
pChrCls->toUpper( aTest );
if ( aTest == sCurString )
bCurrency = TRUE;
}
if ( bCurrency )
{
eState = SsGetWord;
sSymbol += cToken;
}
else
{
eType = nTmpType;
xub_StrLen nLen = sKeyword[eType].Len();
sSymbol = rStr.Copy( nPos-1, nLen );
if ( eType == NF_KEY_E || IsAmbiguousE( eType ) )
{
sal_Unicode cNext = rStr.GetChar(nPos);
switch ( cNext )
{
case '+' :
case '-' : // E+ E- combine to one symbol
sSymbol += cNext;
eType = NF_KEY_E;
nPos++;
break;
case '0' :
case '#' : // scientific E without sign
eType = NF_KEY_E;
break;
}
}
nPos--;
nPos += nLen;
eState = SsStop;
}
}
else
{
eState = SsGetWord;
sSymbol += cToken;
}
}
else
{
eType = SYMBOLTYPE_STRING;
eState = SsStop;
sSymbol += cToken;
}
}
break;
}
}
break;
case SsGetChar:
{
sSymbol += cToken;
eState = SsStop;
}
break;
case SsGetString:
{
if (cToken == '"')
eState = SsStop;
sSymbol += cToken;
}
break;
case SsGetWord:
{
if ( pChrCls->isLetter( rStr, nPos-1 ) )
{
short nTmpType = GetKeyWord( rStr, nPos-1 );
if ( nTmpType )
{ // beginning of keyword, stop scan and put back
eType = SYMBOLTYPE_STRING;
eState = SsStop;
nPos--;
}
else
sSymbol += cToken;
}
else
{
BOOL bDontStop = FALSE;
switch (cToken)
{
case '/': // AM/PM, A/P
{
sal_Unicode cNext = rStr.GetChar(nPos);
if ( cNext == 'P' || cNext == 'p' )
{
xub_StrLen nLen = sSymbol.Len();
if ( 1 <= nLen
&& (sSymbol.GetChar(0) == 'A' || sSymbol.GetChar(0) == 'a')
&& (nLen == 1 || (nLen == 2
&& (sSymbol.GetChar(1) == 'M' || sSymbol.GetChar(1) == 'm')
&& (rStr.GetChar(nPos+1) == 'M' || rStr.GetChar(nPos+1) == 'm'))) )
{
sSymbol += cToken;
bDontStop = TRUE;
}
}
}
break;
}
// anything not recognized will stop the scan
if ( eState != SsStop && !bDontStop )
{
eState = SsStop;
nPos--;
eType = SYMBOLTYPE_STRING;
}
}
}
break;
case SsGetStar:
{
eState = SsStop;
sSymbol += cToken;
nRepPos = (nPos - nStart) - 1; // everytime > 0!!
}
break;
case SsGetBlank:
{
eState = SsStop;
sSymbol += cToken;
}
break;
default:
break;
} // of switch
} // of while
if (eState == SsGetWord)
eType = SYMBOLTYPE_STRING;
return eType;
}
xub_StrLen ImpSvNumberformatScan::Symbol_Division(const String& rString)
{
nCurrPos = STRING_NOTFOUND;
// Ist Waehrung im Spiel?
String sString = pFormatter->GetCharClass()->upper(rString);
xub_StrLen nCPos = 0;
while (nCPos != STRING_NOTFOUND)
{
nCPos = sString.Search(sCurString,nCPos);
if (nCPos != STRING_NOTFOUND)
{
// in Quotes?
xub_StrLen nQ = SvNumberformat::GetQuoteEnd( sString, nCPos );
if ( nQ == STRING_NOTFOUND )
{
sal_Unicode c;
if ( nCPos == 0 ||
((c = sString.GetChar(xub_StrLen(nCPos-1))) != '"'
&& c != '\\') ) // dm kann durch "dm
{ // \d geschuetzt werden
nCurrPos = nCPos;
nCPos = STRING_NOTFOUND; // Abbruch
}
else
nCPos++; // weitersuchen
}
else
nCPos = nQ + 1; // weitersuchen
}
}
nAnzStrings = 0;
BOOL bStar = FALSE; // wird bei '*'Detektion gesetzt
Reset();
xub_StrLen nPos = 0;
const xub_StrLen nLen = rString.Len();
while (nPos < nLen && nAnzStrings < SC_MAX_ANZ_FORMAT_STRINGS)
{
nTypeArray[nAnzStrings] = Next_Symbol(rString, nPos, sStrArray[nAnzStrings]);
if (nTypeArray[nAnzStrings] == SYMBOLTYPE_STAR)
{ // Ueberwachung des '*'
if (bStar)
return nPos; // Fehler: doppelter '*'
else
bStar = TRUE;
}
nAnzStrings++;
}
return 0; // 0 => ok
}
void ImpSvNumberformatScan::SkipStrings(USHORT& i, xub_StrLen& nPos)
{
while (i < nAnzStrings && ( nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_BLANK
|| nTypeArray[i] == SYMBOLTYPE_STAR) )
{
nPos += sStrArray[i].Len();
i++;
}
}
USHORT ImpSvNumberformatScan::PreviousKeyword(USHORT i)
{
short res = 0;
if (i > 0 && i < nAnzStrings)
{
i--;
while (i > 0 && nTypeArray[i] <= 0)
i--;
if (nTypeArray[i] > 0)
res = nTypeArray[i];
}
return res;
}
USHORT ImpSvNumberformatScan::NextKeyword(USHORT i)
{
short res = 0;
if (i < nAnzStrings-1)
{
i++;
while (i < nAnzStrings-1 && nTypeArray[i] <= 0)
i++;
if (nTypeArray[i] > 0)
res = nTypeArray[i];
}
return res;
}
short ImpSvNumberformatScan::PreviousType( USHORT i )
{
if ( i > 0 && i < nAnzStrings )
{
do
{
i--;
} while ( i > 0 && nTypeArray[i] == SYMBOLTYPE_EMPTY );
return nTypeArray[i];
}
return 0;
}
sal_Unicode ImpSvNumberformatScan::PreviousChar(USHORT i)
{
sal_Unicode res = ' ';
if (i > 0 && i < nAnzStrings)
{
i--;
while (i > 0 && ( nTypeArray[i] == SYMBOLTYPE_EMPTY
|| nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_STAR
|| nTypeArray[i] == SYMBOLTYPE_BLANK ) )
i--;
if (sStrArray[i].Len() > 0)
res = sStrArray[i].GetChar(xub_StrLen(sStrArray[i].Len()-1));
}
return res;
}
sal_Unicode ImpSvNumberformatScan::NextChar(USHORT i)
{
sal_Unicode res = ' ';
if (i < nAnzStrings-1)
{
i++;
while (i < nAnzStrings-1 &&
( nTypeArray[i] == SYMBOLTYPE_EMPTY
|| nTypeArray[i] == SYMBOLTYPE_STRING
|| nTypeArray[i] == SYMBOLTYPE_STAR
|| nTypeArray[i] == SYMBOLTYPE_BLANK))
i++;
if (sStrArray[i].Len() > 0)
res = sStrArray[i].GetChar(0);
}
return res;
}
BOOL ImpSvNumberformatScan::IsLastBlankBeforeFrac(USHORT i)
{
BOOL res = TRUE;
if (i < nAnzStrings-1)
{
BOOL bStop = FALSE;
i++;
while (i < nAnzStrings-1 && !bStop)
{
i++;
if ( nTypeArray[i] == SYMBOLTYPE_DEL &&
sStrArray[i].GetChar(0) == '/')
bStop = TRUE;
else if ( nTypeArray[i] == SYMBOLTYPE_DEL &&
sStrArray[i].GetChar(0) == ' ')
res = FALSE;
}
if (!bStop) // kein '/'
res = FALSE;
}
else
res = FALSE; // kein '/' mehr
return res;
}
void ImpSvNumberformatScan::Reset()
{
nAnzStrings = 0;
nAnzResStrings = 0;
#if 0
// ER 20.06.97 14:05 nicht noetig, wenn nAnzStrings beachtet wird
for (USHORT i = 0; i < SC_MAX_ANZ_FORMAT_STRINGS; i++)
{
sStrArray[i].Erase();
nTypeArray[i] = 0;
}
#endif
eScannedType = NUMBERFORMAT_UNDEFINED;
nRepPos = 0;
bExp = FALSE;
bThousand = FALSE;
nThousand = 0;
bDecSep = FALSE;
nDecPos = -1;
nExpPos = (USHORT) -1;
nBlankPos = (USHORT) -1;
nCntPre = 0;
nCntPost = 0;
nCntExp = 0;
bFrac = FALSE;
bBlank = FALSE;
}
xub_StrLen ImpSvNumberformatScan::ScanType(const String& rString)
{
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
xub_StrLen nPos = 0;
USHORT i = 0; // durchlaeuft die Symbole
short eNewType; // neu erkannter Typ
SkipStrings(i, nPos); // Ausgabestrings ueberlesen
while (i < nAnzStrings)
{
if (nTypeArray[i] > 0) // Schluesselwort
{
switch (nTypeArray[i])
{
case NF_KEY_E: // E
eNewType = NUMBERFORMAT_SCIENTIFIC;
break;
case NF_KEY_AMPM: // AM,A,PM,P
case NF_KEY_AP:
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
eNewType = NUMBERFORMAT_TIME;
break;
case NF_KEY_M: // M
case NF_KEY_MM: // MM
{ // Sonderfall: Minute oder Monat
USHORT nIndexPre = PreviousKeyword(i);
USHORT nIndexNex = NextKeyword(i);
sal_Unicode cChar = PreviousChar(i);
if (nIndexPre == NF_KEY_H || // H
nIndexPre == NF_KEY_HH || // HH
nIndexNex == NF_KEY_S || // S
nIndexNex == NF_KEY_SS || // SS
cChar == '[' ) // [M
{
eNewType = NUMBERFORMAT_TIME;
nTypeArray[i] -= 2; // 6 -> 4, 7 -> 5
}
else
eNewType = NUMBERFORMAT_DATE;
}
break;
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
eNewType = NUMBERFORMAT_DATE;
break;
case NF_KEY_CCC: // CCC
eNewType = NUMBERFORMAT_CURRENCY;
break;
case NF_KEY_GENERAL: // Standard
eNewType = NUMBERFORMAT_NUMBER;
break;
default:
eNewType = NUMBERFORMAT_UNDEFINED;
break;
}
}
else // Steuerzeichen
{
switch ( sStrArray[i].GetChar(0) )
{
case '#':
case '?':
eNewType = NUMBERFORMAT_NUMBER;
break;
case '0':
{
if (eScannedType == NUMBERFORMAT_TIME)
{
USHORT nIndexPre = PreviousKeyword(i);
if ((nIndexPre == NF_KEY_S || nIndexPre == NF_KEY_SS)
&& bDecSep) // S, SS ','
eNewType = NUMBERFORMAT_TIME;
else
return nPos; // Fehler
}
else
eNewType = NUMBERFORMAT_NUMBER;
}
break;
case ',':
case '.':
{
bDecSep = TRUE; // fuer SS,0
eNewType = NUMBERFORMAT_UNDEFINED;
}
break;
case '%':
eNewType = NUMBERFORMAT_PERCENT;
break;
case '/':
eNewType = NUMBERFORMAT_FRACTION;
break;
case '[':
{
if ( i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '$' )
{ // as of SV_NUMBERFORMATTER_VERSION_NEW_CURR
eNewType = NUMBERFORMAT_CURRENCY;
}
else if ( i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '~' )
{ // as of SV_NUMBERFORMATTER_VERSION_CALENDAR
eNewType = NUMBERFORMAT_DATE;
}
else
{
USHORT nIndexNex = NextKeyword(i);
if (nIndexNex == NF_KEY_H || // H
nIndexNex == NF_KEY_HH || // HH
nIndexNex == NF_KEY_M || // M
nIndexNex == NF_KEY_MM || // MM
nIndexNex == NF_KEY_S || // S
nIndexNex == NF_KEY_SS ) // SS
eNewType = NUMBERFORMAT_TIME;
else
return nPos; // Fehler
}
}
break;
case '@':
eNewType = NUMBERFORMAT_TEXT;
break;
default:
eNewType = NUMBERFORMAT_UNDEFINED;
break;
}
}
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = eNewType;
else if (eScannedType == NUMBERFORMAT_TEXT || eNewType == NUMBERFORMAT_TEXT)
eScannedType = NUMBERFORMAT_TEXT; // Text bleibt immer Text
else if (eNewType == NUMBERFORMAT_UNDEFINED)
{ // bleibt wie bisher
}
else if (eScannedType != eNewType)
{
switch (eScannedType)
{
case NUMBERFORMAT_DATE:
{
switch (eNewType)
{
case NUMBERFORMAT_TIME:
eScannedType = NUMBERFORMAT_DATETIME;
break;
case NUMBERFORMAT_FRACTION: // DD/MM
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getDateSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_TIME:
{
switch (eNewType)
{
case NUMBERFORMAT_DATE:
eScannedType = NUMBERFORMAT_DATETIME;
break;
case NUMBERFORMAT_FRACTION: // MM/SS
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getTimeSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_DATETIME:
{
switch (eNewType)
{
case NUMBERFORMAT_TIME:
case NUMBERFORMAT_DATE:
break;
case NUMBERFORMAT_FRACTION: // DD/MM
break;
default:
{
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else if ( sStrArray[i] != pLoc->getDateSep()
&& sStrArray[i] != pLoc->getTimeSep() )
return nPos;
}
}
}
break;
case NUMBERFORMAT_PERCENT:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach Prozent
break;
default:
return nPos;
}
}
break;
case NUMBERFORMAT_SCIENTIFIC:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach E
break;
default:
return nPos;
}
}
break;
case NUMBERFORMAT_NUMBER:
{
switch (eNewType)
{
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_FRACTION:
case NUMBERFORMAT_CURRENCY:
eScannedType = eNewType;
break;
default:
if (nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_UNDEFINED;
else
return nPos;
}
}
break;
case NUMBERFORMAT_FRACTION:
{
switch (eNewType)
{
case NUMBERFORMAT_NUMBER: // nur Zahl nach Bruch
break;
default:
return nPos;
}
}
break;
default:
break;
}
}
nPos += sStrArray[i].Len(); // Korrekturposition
i++;
SkipStrings(i, nPos);
}
if ((eScannedType == NUMBERFORMAT_NUMBER || eScannedType == NUMBERFORMAT_UNDEFINED)
&& nCurrPos != STRING_NOTFOUND)
eScannedType = NUMBERFORMAT_CURRENCY; // old "automatic" currency
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = NUMBERFORMAT_DEFINED;
return 0; // Alles ok
}
int ImpSvNumberformatScan::FinalScanGetCalendar( xub_StrLen& nPos, USHORT& i,
USHORT& nAnzResStrings )
{
if ( sStrArray[i].GetChar(0) == '[' &&
i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '~' )
{ // [~calendarID]
// as of SV_NUMBERFORMATTER_VERSION_CALENDAR
nPos += sStrArray[i].Len(); // [
nTypeArray[i] = SYMBOLTYPE_CALDEL;
nPos += sStrArray[++i].Len(); // ~
sStrArray[i-1] += sStrArray[i]; // [~
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
if ( ++i >= nAnzStrings )
return -1; // error
nPos += sStrArray[i].Len(); // calendarID
String& rStr = sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CALENDAR; // convert
i++;
while ( i < nAnzStrings &&
sStrArray[i].GetChar(0) != ']' )
{
nPos += sStrArray[i].Len();
rStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
if ( rStr.Len() && i < nAnzStrings &&
sStrArray[i].GetChar(0) == ']' )
{
nTypeArray[i] = SYMBOLTYPE_CALDEL;
nPos += sStrArray[i].Len();
i++;
}
else
return -1; // error
return 1;
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::FinalScan( String& rString, String& rComment )
{
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const CharClass* pChrCls = pFormatter->GetCharClass();
// save values for convert mode
String sOldDecSep = pLoc->getNumDecimalSep();
String sOldThousandSep = pLoc->getNumThousandSep();
String sOldDateSep = pLoc->getDateSep();
String sOldTimeSep = pLoc->getTimeSep();
String sOldCurSymbol = sCurSymbol;
String sOldCurString = sCurString;
// If the group separator is a Non-Breaking Space (French) continue with a
// normal space instead so queries on space work correctly.
// The format string is adjusted to allow both.
// For output of the format code string the LocaleData characters are used.
if ( sOldThousandSep.GetChar(0) == 0xA0 && sOldThousandSep.Len() == 1 )
sOldThousandSep = ' ';
// change locale data et al
if (bConvertMode)
pFormatter->ChangeIntl(eNewLnge);
xub_StrLen nPos = 0; // Korrekturposition
USHORT i = 0; // durchlaeuft die Symbole
USHORT nCounter = 0; // Zaehlt Ziffern
nAnzResStrings = nAnzStrings; // Zaehlt uebrigbleibende Symbole
bDecSep = FALSE; // falls schon in TypeCeck benutzt
switch (eScannedType)
{
case NUMBERFORMAT_TEXT:
case NUMBERFORMAT_DEFINED:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
break;
case NF_KEY_GENERAL : // #77026# "General" is the same as "@"
break;
default:
{
if ( nTypeArray[i] != SYMBOLTYPE_DEL ||
sStrArray[i].GetChar(0) != '@' )
nTypeArray[i] = SYMBOLTYPE_STRING;
}
break;
}
nPos += sStrArray[i].Len();
i++;
} // of while
}
break;
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_FRACTION:
{
sal_Unicode cThousandFill = ' ';
while (i < nAnzStrings)
{
if (eScannedType == NUMBERFORMAT_FRACTION && // special case
nTypeArray[i] == SYMBOLTYPE_DEL && // # ### #/#
StringEqualsChar( sOldThousandSep, ' ' ) && // e.g. France or Sweden
StringEqualsChar( sStrArray[i], ' ' ) &&
!bFrac &&
IsLastBlankBeforeFrac(i) )
{
nTypeArray[i] = SYMBOLTYPE_STRING; // del->string
} // kein Taus.p.
if (nTypeArray[i] == SYMBOLTYPE_BLANK ||
nTypeArray[i] == SYMBOLTYPE_STAR ||
nTypeArray[i] == NF_KEY_CCC || // CCC
nTypeArray[i] == NF_KEY_GENERAL ) // Standard
{
if (nTypeArray[i] == NF_KEY_GENERAL)
{
nThousand = FLAG_STANDARD_IN_FORMAT;
if ( bConvertMode )
sStrArray[i] = sNameStandardFormat;
}
nPos += sStrArray[i].Len();
i++;
}
else if (nTypeArray[i] == SYMBOLTYPE_STRING || // Strings oder
nTypeArray[i] > 0) // Keywords
{
if (eScannedType == NUMBERFORMAT_SCIENTIFIC &&
nTypeArray[i] == NF_KEY_E) // E+
{
if (bExp) // doppelt
return nPos;
bExp = TRUE;
nExpPos = i;
if (bDecSep)
nCntPost = nCounter;
else
nCntPre = nCounter;
nCounter = 0;
nTypeArray[i] = SYMBOLTYPE_EXP;
}
else if (eScannedType == NUMBERFORMAT_FRACTION &&
sStrArray[i].GetChar(0) == ' ')
{
if (!bBlank && !bFrac) // nicht doppelt oder hinter /
{
if (bDecSep && nCounter > 0) // Nachkommastellen
return nPos; // Fehler
bBlank = TRUE;
nBlankPos = i;
nCntPre = nCounter;
nCounter = 0;
}
nTypeArray[i] = SYMBOLTYPE_FRACBLANK;
}
else
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if (nTypeArray[i] == SYMBOLTYPE_DEL)
{
sal_Unicode cHere = sStrArray[i].GetChar(0);
switch ( cHere )
{
case '#':
case '0':
case '?':
{
if (nThousand > 0) // #... #
return nPos; // Fehler
else if (bFrac && cHere == '0')
return nPos; // 0 im Nenner
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nCounter++;
while (i < nAnzStrings &&
(sStrArray[i].GetChar(0) == '#' ||
sStrArray[i].GetChar(0) == '0' ||
sStrArray[i].GetChar(0) == '?')
)
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
break;
case '-':
{
if ( bDecSep && nDecPos < i &&
nTypeArray[nDecPos] == SYMBOLTYPE_DECSEP )
{ // "0,--"
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nCounter++;
while (i < nAnzStrings &&
(sStrArray[i].GetChar(0) == '-') )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case '.':
case ',':
case '\'':
case ' ':
{
sal_Unicode cSep = cHere; // remember
if ( StringEqualsChar( sOldThousandSep, cSep ) )
{
// previous char with skip empty
sal_Unicode cPre = PreviousChar(i);
sal_Unicode cNext;
if (bExp || bBlank || bFrac)
{ // after E, / or ' '
if ( !StringEqualsChar( sOldThousandSep, ' ' ) )
{
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++; // eat it
}
else
nTypeArray[i] = SYMBOLTYPE_STRING;
}
else if (i > 0 && i < nAnzStrings-1 &&
(cPre == '#' || cPre == '0') &&
((cNext = NextChar(i)) == '#' || cNext == '0')
) // #,#
{
nPos += sStrArray[i].Len();
if (!bThousand) // only once
{ // set hard, in case of Non-Breaking Space or ConvertMode
sStrArray[i] = pLoc->getNumThousandSep();
nTypeArray[i] = SYMBOLTYPE_THSEP;
bThousand = TRUE;
cThousandFill = sStrArray[i+1].GetChar(0);
}
else // eat it
{
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i++;
}
else if (i > 0 && (cPre == '#' || cPre == '0')
&& PreviousType(i) == SYMBOLTYPE_DIGIT
&& nThousand < FLAG_STANDARD_IN_FORMAT )
{ // #,,,,
if ( StringEqualsChar( sOldThousandSep, ' ' ) )
{ // strange, those French..
BOOL bFirst = TRUE;
String& rStr = sStrArray[i];
// set a hard Non-Breaking Space or ConvertMode
const String& rSepF = pLoc->getNumThousandSep();
while ( i < nAnzStrings
&& sStrArray[i] == sOldThousandSep
&& StringEqualsChar( sOldThousandSep, NextChar(i) ) )
{ // last was a space or another space
// is following => separator
nPos += sStrArray[i].Len();
if ( bFirst )
{
bFirst = FALSE;
rStr = rSepF;
nTypeArray[i] = SYMBOLTYPE_THSEP;
}
else
{
rStr += rSepF;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
nThousand++;
i++;
}
if ( i < nAnzStrings-1
&& sStrArray[i] == sOldThousandSep )
{ // something following last space
// => space if currency contained,
// else separator
nPos += sStrArray[i].Len();
if ( (nPos <= nCurrPos &&
nCurrPos < nPos + sStrArray[i+1].Len())
|| nTypeArray[i+1] == NF_KEY_CCC
|| (i < nAnzStrings-2 &&
sStrArray[i+1].GetChar(0) == '[' &&
sStrArray[i+2].GetChar(0) == '$') )
{
nTypeArray[i] = SYMBOLTYPE_STRING;
}
else
{
if ( bFirst )
{
bFirst = FALSE;
rStr = rSepF;
nTypeArray[i] = SYMBOLTYPE_THSEP;
}
else
{
rStr += rSepF;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
nThousand++;
}
i++;
}
}
else
{
nTypeArray[i] = SYMBOLTYPE_THSEP;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
nThousand++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldThousandSep )
{
nThousand++;
rStr += pLoc->getNumThousandSep();
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
else // any grsep
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldThousandSep )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
else if ( StringEqualsChar( sOldDecSep, cSep ) )
{
if (bBlank || bFrac) // . behind / or ' '
return nPos; // error
else if (bExp) // behind E
{
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++; // eat it
}
else if (bDecSep) // any .
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while ( i < nAnzStrings &&
sStrArray[i] == sOldDecSep )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
else
{
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_DECSEP;
sStrArray[i] = pLoc->getNumDecimalSep();
bDecSep = TRUE;
nDecPos = i;
nCntPre = nCounter;
nCounter = 0;
i++;
}
} // of else = DecSep
else // . without meaning
{
if (cSep == ' ' &&
eScannedType == NUMBERFORMAT_FRACTION &&
StringEqualsChar( sStrArray[i], ' ' ) )
{
if (!bBlank && !bFrac) // no dups
{ // or behind /
if (bDecSep && nCounter > 0)// dec.
return nPos; // error
bBlank = TRUE;
nBlankPos = i;
nCntPre = nCounter;
nCounter = 0;
}
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
String& rStr = sStrArray[i];
nPos += rStr.Len();
i++;
while (i < nAnzStrings &&
StringEqualsChar( sStrArray[i], cSep ) )
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
}
}
}
break;
case '/':
{
if (eScannedType == NUMBERFORMAT_FRACTION)
{
if ( i == 0 ||
(nTypeArray[i-1] != SYMBOLTYPE_DIGIT &&
nTypeArray[i-1] != SYMBOLTYPE_EMPTY) )
return nPos ? nPos : 1; // /? not allowed
else if (!bFrac || (bDecSep && nCounter > 0))
{
bFrac = TRUE;
nCntPost = nCounter;
nCounter = 0;
nTypeArray[i] = SYMBOLTYPE_FRAC;
nPos += sStrArray[i].Len();
i++;
}
else // / doppelt od. , imZaehl
return nPos; // Fehler
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case '[' :
{
if ( eScannedType == NUMBERFORMAT_CURRENCY &&
i < nAnzStrings-1 &&
nTypeArray[i+1] == SYMBOLTYPE_STRING &&
sStrArray[i+1].GetChar(0) == '$' )
{ // [$DM-xxx]
// ab SV_NUMBERFORMATTER_VERSION_NEW_CURR
nPos += sStrArray[i].Len(); // [
nTypeArray[i] = SYMBOLTYPE_CURRDEL;
nPos += sStrArray[++i].Len(); // $
sStrArray[i-1] += sStrArray[i]; // [$
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
if ( ++i >= nAnzStrings )
return nPos; // Fehler
nPos += sStrArray[i].Len(); // DM
String& rStr = sStrArray[i];
String* pStr = &sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CURRENCY; // wandeln
BOOL bHadDash = FALSE;
i++;
while ( i < nAnzStrings &&
sStrArray[i].GetChar(0) != ']' )
{
nPos += sStrArray[i].Len();
if ( bHadDash )
{
*pStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
else
{
if ( sStrArray[i].GetChar(0) == '-' )
{
bHadDash = TRUE;
pStr = &sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_CURREXT;
}
else
{
*pStr += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
}
i++;
}
if ( rStr.Len() && i < nAnzStrings &&
sStrArray[i].GetChar(0) == ']' )
{
nTypeArray[i] = SYMBOLTYPE_CURRDEL;
nPos += sStrArray[i].Len();
i++;
}
else
return nPos; // Fehler
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
default: // andere Dels
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
} // of switch (Del)
} // of else Del
else if ( nTypeArray[i] == SYMBOLTYPE_COMMENT )
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
else
{
DBG_ERRORFILE( "unknown SYMBOLTYPE_..." );
nPos += sStrArray[i].Len();
i++;
}
} // of while
if (eScannedType == NUMBERFORMAT_FRACTION)
{
if (bFrac)
nCntExp = nCounter;
else if (bBlank)
nCntPost = nCounter;
else
nCntPre = nCounter;
}
else
{
if (bExp)
nCntExp = nCounter;
else if (bDecSep)
nCntPost = nCounter;
else
nCntPre = nCounter;
}
if (nThousand == 0 && bThousand) // Expansion Tausenderpunkt:
{
USHORT nMaxPos;
if (bFrac)
{
if (bBlank)
nMaxPos = nBlankPos;
else
nMaxPos = 0; // keine Expansion
}
else if (bDecSep) // , vorhanden
nMaxPos = nDecPos;
else if (bExp) // E vorhanden
nMaxPos = nExpPos;
else // sonst bis Ende
nMaxPos = i;
i = 0;
long nCount = nCntPre;
while (i < nMaxPos && nTypeArray[i] != SYMBOLTYPE_THSEP) // nur bis zum ,
{
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
nCount -= sStrArray[i].Len();
i++;
}
USHORT nPosThSep = i; // Position merken
i++; // Ziffern hinter .
xub_StrLen nFill = 0;
if (nCount > 0) // muesste immer sein
nFill = xub_StrLen(nCount % 3);
if (nFill)
{
nFill = 3 - nFill;
if (i < nMaxPos)
for (xub_StrLen k = 0; k < nFill; k++)
sStrArray[i].Insert(cThousandFill,0);
nCntPre += USHORT(nFill);
}
nCount = 0; // Aufuellen mit .
while (i < nMaxPos) // nach hinten
{
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
{
xub_StrLen nLen = sStrArray[i].Len();
if (nCount+nLen > 3)
{ // hier muss . dazwischen
xub_StrLen nAnz = (nLen+nCount-4)/3+1;
xub_StrLen InPos = 3-nCount;
for (xub_StrLen k = 0; k < nAnz; k++)
{
sStrArray[i].Insert(
pLoc->getNumThousandSep(),InPos);
InPos += 4;
}
nCount = sStrArray[i].Len() - InPos + 3;
}
else
nCount += sStrArray[i].Len();
}
i++;
}
nCount = 0; // Aufuellen mit .
i = nPosThSep; // nach vorn
while (i > 0)
{
i--;
if (nTypeArray[i] == SYMBOLTYPE_DIGIT)
{
xub_StrLen nLen = sStrArray[i].Len();
if (nCount+nLen > 3)
{ // hier muss . dazwischen
xub_StrLen nAnz = (nLen+nCount-4)/3+1;
xub_StrLen InPos = nLen + nCount - 3;
for (xub_StrLen k = 0; k < nAnz; k++)
{
sStrArray[i].Insert(
pLoc->getNumThousandSep(),InPos);
InPos -= 3;
}
nCount = InPos + 3;
}
else
nCount += sStrArray[i].Len();
}
}
}
}
break; // of NUMBERFORMAT_NUMBER
case NUMBERFORMAT_DATE:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
case SYMBOLTYPE_STRING:
nPos += sStrArray[i].Len();
i++;
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case SYMBOLTYPE_DEL:
{
int nCalRet;
if (bConvertMode && sStrArray[i] == sOldDateSep)
{
sStrArray[i] = pLoc->getDateSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if ( (nCalRet = FinalScanGetCalendar( nPos, i, nAnzResStrings )) != 0 )
{
if ( nCalRet < 0 )
return nPos; // error
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case NF_KEY_M: // M
case NF_KEY_MM: // MM
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
break;
default: // andere Keywords
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
break;
}
} // of while
}
break; // of NUMBERFORMAT_DATE
case NUMBERFORMAT_TIME:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
{
nPos += sStrArray[i].Len();
i++;
}
break;
case SYMBOLTYPE_DEL:
{
switch( sStrArray[i].GetChar(0) )
{
case '0':
{
if (bDecSep)
{
nTypeArray[i] = SYMBOLTYPE_DIGIT;
String& rStr = sStrArray[i];
i++;
nPos += sStrArray[i].Len();
nCounter++;
while (i < nAnzStrings &&
sStrArray[i].GetChar(0) == '0')
{
rStr += sStrArray[i];
nPos += sStrArray[i].Len();
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
nCounter++;
i++;
}
}
else
return nPos;
}
break;
case '#':
case '?':
return nPos;
break;
case '.':
case ',':
{
bDecSep = TRUE;
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
case '[':
{
if (bThousand) // doppelt
return nPos;
bThousand = TRUE; // bei Time frei
sal_Unicode cChar = pChrCls->upper( NextChar(i) ).GetChar(0);
if ( cChar == sKeyword[NF_KEY_H].GetChar(0) )
nThousand = 1; // H
else if ( cChar == sKeyword[NF_KEY_MI].GetChar(0) )
nThousand = 2; // M
else if ( cChar == sKeyword[NF_KEY_S].GetChar(0) )
nThousand = 3; // S
else
return nPos;
nPos += sStrArray[i].Len();
i++;
}
case ']':
{
if (!bThousand) // kein [ vorher
return nPos;
nPos += sStrArray[i].Len();
i++;
}
break;
default:
{
if (bConvertMode && sStrArray[i] == sOldTimeSep)
sStrArray[i] = pLoc->getTimeSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
}
}
break;
case SYMBOLTYPE_STRING:
{
nPos += sStrArray[i].Len();
i++;
}
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case NF_KEY_AMPM: // AM/PM
case NF_KEY_AP: // A/P
{
bExp = TRUE; // missbraucht fuer A/P
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
}
break;
case NF_KEY_MI: // M
case NF_KEY_MMI: // MM
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
{
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
}
break;
default: // andere Keywords
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
}
} // of while
nCntPost = nCounter; // Zaehler der Nullen
if (bExp)
nCntExp = 1; // merkt AM/PM
}
break; // of NUMBERFORMAT_TIME
case NUMBERFORMAT_DATETIME:
{
while (i < nAnzStrings)
{
switch (nTypeArray[i])
{
case SYMBOLTYPE_BLANK:
case SYMBOLTYPE_STAR:
case SYMBOLTYPE_STRING:
nPos += sStrArray[i].Len();
i++;
break;
case SYMBOLTYPE_COMMENT:
{
String& rStr = sStrArray[i];
nPos += rStr.Len();
SvNumberformat::EraseCommentBraces( rStr );
rComment += rStr;
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
i++;
}
break;
case SYMBOLTYPE_DEL:
{
int nCalRet;
if (bConvertMode && sStrArray[i] == sOldDateSep)
{
sStrArray[i] = pLoc->getDateSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if (bConvertMode && sStrArray[i] == sOldTimeSep)
{
sStrArray[i] = pLoc->getTimeSep();
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
else if ( (nCalRet = FinalScanGetCalendar( nPos, i, nAnzResStrings )) != 0 )
{
if ( nCalRet < 0 )
return nPos; // error
}
else
{
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
}
break;
case NF_KEY_AMPM: // AM/PM
case NF_KEY_AP: // A/P
{
bExp = TRUE; // missbraucht fuer A/P
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
}
break;
case NF_KEY_MI: // M
case NF_KEY_MMI: // MM
case NF_KEY_H: // H
case NF_KEY_HH: // HH
case NF_KEY_S: // S
case NF_KEY_SS: // SS
case NF_KEY_M: // M
case NF_KEY_MM: // MM
case NF_KEY_MMM: // MMM
case NF_KEY_MMMM: // MMMM
case NF_KEY_MMMMM: // MMMMM
case NF_KEY_Q: // Q
case NF_KEY_QQ: // QQ
case NF_KEY_D: // D
case NF_KEY_DD: // DD
case NF_KEY_DDD: // DDD
case NF_KEY_DDDD: // DDDD
case NF_KEY_YY: // YY
case NF_KEY_YYYY: // YYYY
case NF_KEY_NN: // NN
case NF_KEY_NNN: // NNN
case NF_KEY_NNNN: // NNNN
case NF_KEY_WW : // WW
case NF_KEY_AAA : // AAA
case NF_KEY_AAAA : // AAAA
case NF_KEY_EC : // E
case NF_KEY_EEC : // EE
case NF_KEY_G : // G
case NF_KEY_GG : // GG
case NF_KEY_GGG : // GGG
case NF_KEY_R : // R
case NF_KEY_RR : // RR
sStrArray[i] = sKeyword[nTypeArray[i]]; // tTtT -> TTTT
nPos += sStrArray[i].Len();
i++;
break;
default: // andere Keywords
nTypeArray[i] = SYMBOLTYPE_STRING;
nPos += sStrArray[i].Len();
i++;
break;
}
} // of while
if (bExp)
nCntExp = 1; // merkt AM/PM
}
break; // of NUMBERFORMAT_DATETIME
default:
break;
}
if (eScannedType == NUMBERFORMAT_SCIENTIFIC &&
(nCntPre + nCntPost == 0 || nCntExp == 0))
return nPos;
else if (eScannedType == NUMBERFORMAT_FRACTION && (nCntExp > 8 || nCntExp == 0))
return nPos;
if ( bConvertMode )
{ // strings containing keywords of the target locale must be quoted, so
// the user sees the difference and is able to edit the format string
for ( i=0; i < nAnzStrings; i++ )
{
if ( nTypeArray[i] == SYMBOLTYPE_STRING &&
sStrArray[i].GetChar(0) != '\"' )
{
if ( bConvertSystemToSystem && eScannedType == NUMBERFORMAT_CURRENCY )
{ // don't stringize automatic currency, will be converted
if ( sStrArray[i] == sOldCurSymbol )
continue; // for
// DM might be splitted into D and M
if ( sStrArray[i].Len() < sOldCurSymbol.Len() &&
pChrCls->toUpper( sStrArray[i], 0, 1 ).GetChar(0) ==
sOldCurString.GetChar(0) )
{
String aTmp( sStrArray[i] );
USHORT j = i + 1;
while ( aTmp.Len() < sOldCurSymbol.Len() &&
j < nAnzStrings &&
nTypeArray[j] == SYMBOLTYPE_STRING )
{
aTmp += sStrArray[j++];
}
if ( pChrCls->upper( aTmp ) == sOldCurString )
{
sStrArray[i++] = aTmp;
for ( ; i<j; i++ )
{
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i = j - 1;
continue; // for
}
}
}
String& rStr = sStrArray[i];
xub_StrLen nLen = rStr.Len();
for ( xub_StrLen j=0; j<nLen; j++ )
{
if ( (j == 0 || rStr.GetChar(j-1) != '\\') && GetKeyWord( rStr, j ) )
{
rStr.Insert( '\"', 0 );
rStr += '\"';
break; // for
}
}
}
}
}
// concatenate strings, remove quotes for output, and rebuild the format string
rString.Erase();
i = 0;
while (i < nAnzStrings)
{
switch ( nTypeArray[i] )
{
case SYMBOLTYPE_STRING :
{
xub_StrLen nStringPos = rString.Len();
xub_StrLen nArrPos = 0;
USHORT iPos = i;
do
{
rString += sStrArray[i];
if ( RemoveQuotes( sStrArray[i] ) > 0 )
{ // update currency up to quoted string
if ( eScannedType == NUMBERFORMAT_CURRENCY )
{ // dM -> DM or DM -> $ in old automatic
// currency formats, oh my ..., why did we ever
// introduce them?
String aTmp( pChrCls->toUpper(
sStrArray[iPos], nArrPos,
sStrArray[iPos].Len()-nArrPos ) );
xub_StrLen nCPos = aTmp.Search( sOldCurString );
if ( nCPos != STRING_NOTFOUND )
{
const String& rCur =
bConvertMode && bConvertSystemToSystem ?
sCurSymbol : sOldCurSymbol;
sStrArray[iPos].Replace( nArrPos+nCPos,
sOldCurString.Len(), rCur );
rString.Replace( nStringPos+nCPos,
sOldCurString.Len(), rCur );
}
nStringPos = rString.Len();
if ( iPos == i )
nArrPos = sStrArray[iPos].Len();
else
nArrPos = sStrArray[iPos].Len() + sStrArray[i].Len();
}
}
if ( iPos != i )
{
sStrArray[iPos] += sStrArray[i];
nTypeArray[i] = SYMBOLTYPE_EMPTY;
nAnzResStrings--;
}
i++;
} while ( i < nAnzStrings && nTypeArray[i] == SYMBOLTYPE_STRING );
if ( i < nAnzStrings )
i--; // enter switch on next symbol again
if ( eScannedType == NUMBERFORMAT_CURRENCY && nStringPos < rString.Len() )
{ // same as above, since last RemoveQuotes
String aTmp( pChrCls->toUpper(
sStrArray[iPos], nArrPos,
sStrArray[iPos].Len()-nArrPos ) );
xub_StrLen nCPos = aTmp.Search( sOldCurString );
if ( nCPos != STRING_NOTFOUND )
{
const String& rCur =
bConvertMode && bConvertSystemToSystem ?
sCurSymbol : sOldCurSymbol;
sStrArray[iPos].Replace( nArrPos+nCPos,
sOldCurString.Len(), rCur );
rString.Replace( nStringPos+nCPos,
sOldCurString.Len(), rCur );
}
}
}
break;
case SYMBOLTYPE_CURRENCY :
{
rString += sStrArray[i];
RemoveQuotes( sStrArray[i] );
}
break;
case SYMBOLTYPE_EMPTY :
// nothing
break;
default:
rString += sStrArray[i];
}
i++;
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::RemoveQuotes( String& rStr )
{
if ( rStr.Len() > 1 )
{
sal_Unicode c = rStr.GetChar(0);
xub_StrLen n;
if ( c == '"' && rStr.GetChar( (n = xub_StrLen(rStr.Len()-1)) ) == '"' )
{
rStr.Erase(n,1);
rStr.Erase(0,1);
return 2;
}
else if ( c == '\\' )
{
rStr.Erase(0,1);
return 1;
}
}
return 0;
}
xub_StrLen ImpSvNumberformatScan::ScanFormat( String& rString, String& rComment )
{
xub_StrLen res = Symbol_Division(rString); //lexikalische Analyse
if (!res)
res = ScanType(rString); // Erkennung des Formattyps
if (!res)
res = FinalScan( rString, rComment ); // Typabhaengige Endanalyse
return res; // res = Kontrollposition
// res = 0 => Format ok
}
void ImpSvNumberformatScan::CopyInfo(ImpSvNumberformatInfo* pInfo, USHORT nAnz)
{
USHORT i,j;
j = 0;
i = 0;
while (i < nAnz && j < SC_MAX_ANZ_FORMAT_STRINGS)
{
if (nTypeArray[j] != SYMBOLTYPE_EMPTY)
{
pInfo->sStrArray[i] = sStrArray[j];
pInfo->nTypeArray[i] = nTypeArray[j];
i++;
}
j++;
}
pInfo->eScannedType = eScannedType;
pInfo->bThousand = bThousand;
pInfo->nThousand = nThousand;
pInfo->nCntPre = nCntPre;
pInfo->nCntPost = nCntPost;
pInfo->nCntExp = nCntExp;
}
|
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "sidebar/PanelFactory.hxx"
#include "text/TextPropertyPanel.hxx"
#include "paragraph/ParaPropertyPanel.hxx"
#include "area/AreaPropertyPanel.hxx"
#include "graphic/GraphicPropertyPanel.hxx"
#include "line/LinePropertyPanel.hxx"
#include "possize/PosSizePropertyPanel.hxx"
#include "insert/InsertPropertyPanel.hxx"
#include "GalleryControl.hxx"
#include "debug/ColorPanel.hxx"
#include "debug/ContextPanel.hxx"
#include "debug/NotYetImplementedPanel.hxx"
#include "EmptyPanel.hxx"
#include <sfx2/sidebar/SidebarPanelBase.hxx>
#include <sfx2/sfxbasecontroller.hxx>
#include <sfx2/templdlg.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/window.hxx>
#include <rtl/ref.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <com/sun/star/ui/XSidebar.hpp>
#include <boost/bind.hpp>
using namespace css;
using namespace cssu;
using ::rtl::OUString;
namespace svx { namespace sidebar {
#define IMPLEMENTATION_NAME "org.apache.openoffice.comp.svx.sidebar.PanelFactory"
#define SERVICE_NAME "com.sun.star.ui.UIElementFactory"
::rtl::OUString SAL_CALL PanelFactory::getImplementationName (void)
{
return A2S(IMPLEMENTATION_NAME);
}
cssu::Reference<cssu::XInterface> SAL_CALL PanelFactory::createInstance (
const uno::Reference<lang::XMultiServiceFactory>& rxFactory)
{
(void)rxFactory;
::rtl::Reference<PanelFactory> pPanelFactory (new PanelFactory());
cssu::Reference<cssu::XInterface> xService (static_cast<XWeak*>(pPanelFactory.get()), cssu::UNO_QUERY);
return xService;
}
cssu::Sequence<OUString> SAL_CALL PanelFactory::getSupportedServiceNames (void)
{
cssu::Sequence<OUString> aServiceNames (1);
aServiceNames[0] = A2S(SERVICE_NAME);
return aServiceNames;
}
PanelFactory::PanelFactory (void)
: PanelFactoryInterfaceBase(m_aMutex)
{
}
PanelFactory::~PanelFactory (void)
{
}
Reference<ui::XUIElement> SAL_CALL PanelFactory::createUIElement (
const ::rtl::OUString& rsResourceURL,
const ::cssu::Sequence<css::beans::PropertyValue>& rArguments)
throw(
container::NoSuchElementException,
lang::IllegalArgumentException,
RuntimeException)
{
const ::comphelper::NamedValueCollection aArguments (rArguments);
Reference<frame::XFrame> xFrame (aArguments.getOrDefault("Frame", Reference<frame::XFrame>()));
Reference<awt::XWindow> xParentWindow (aArguments.getOrDefault("ParentWindow", Reference<awt::XWindow>()));
Reference<ui::XSidebar> xSidebar (aArguments.getOrDefault("Sidebar", Reference<ui::XSidebar>()));
const sal_uInt64 nBindingsValue (aArguments.getOrDefault("SfxBindings", sal_uInt64(0)));
SfxBindings* pBindings = reinterpret_cast<SfxBindings*>(nBindingsValue);
::sfx2::sidebar::EnumContext aContext (
aArguments.getOrDefault("ApplicationName", OUString()),
aArguments.getOrDefault("ContextName", OUString()));
::Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if ( ! xParentWindow.is() || pParentWindow==NULL)
throw RuntimeException(
A2S("PanelFactory::createUIElement called without ParentWindow"),
NULL);
if ( ! xFrame.is())
throw RuntimeException(
A2S("PanelFactory::createUIElement called without Frame"),
NULL);
if (pBindings == NULL)
throw RuntimeException(
A2S("PanelFactory::createUIElement called without SfxBindings"),
NULL);
Window* pControl = NULL;
ui::LayoutSize aLayoutSize (-1,-1,-1);
#define DoesResourceEndWith(s) rsResourceURL.endsWithAsciiL(s,strlen(s))
if (DoesResourceEndWith("/TextPropertyPanel"))
{
pControl = TextPropertyPanel::Create(pParentWindow, xFrame, pBindings, aContext);
}
else if (DoesResourceEndWith("/ParaPropertyPanel"))
{
pControl = ParaPropertyPanel::Create(pParentWindow, xFrame, pBindings, xSidebar);
}
else if (DoesResourceEndWith("/AreaPropertyPanel"))
{
pControl = AreaPropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/GraphicPropertyPanel"))
{
pControl = GraphicPropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/LinePropertyPanel"))
{
pControl = LinePropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/PosSizePropertyPanel"))
{
pControl = PosSizePropertyPanel::Create(pParentWindow, xFrame, pBindings, xSidebar);
}
else if (DoesResourceEndWith("/InsertPropertyPanel"))
{
pControl = new InsertPropertyPanel(pParentWindow, xFrame);
}
else if (DoesResourceEndWith("/GalleryPanel"))
{
pControl = new GalleryControl(pBindings, pParentWindow);
aLayoutSize = ui::LayoutSize(300,-1,400);
}
else if (DoesResourceEndWith("/StyleListPanel"))
{
pControl = new SfxTemplatePanelControl(pBindings, pParentWindow);
aLayoutSize = ui::LayoutSize(0,-1,-1);
}
else if (DoesResourceEndWith("/Debug_ColorPanel"))
{
pControl = new ColorPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(300,-1,400);
}
else if (DoesResourceEndWith("/Debug_ContextPanel"))
{
pControl = new ContextPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(45,45,45);
}
else if (DoesResourceEndWith("/Debug_NotYetImplementedPanel"))
{
pControl = new NotYetImplementedPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(20,25,25);
}
else if (DoesResourceEndWith("/EmptyPanel"))
{
pControl = new EmptyPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(20,-1, 50);
}
#undef DoesResourceEndWith
if (pControl != NULL)
{
return sfx2::sidebar::SidebarPanelBase::Create(
rsResourceURL,
xFrame,
pControl,
aLayoutSize);
}
else
return Reference<ui::XUIElement>();
}
} } // end of namespace svx::sidebar
// eof
Include <sfx2/sidebar/Tools.hxx> for A2S
It is included in the precompiled svx header, so have to include it
explicitly too for A2S to be visible in the non-pch case.
Change-Id: Ic90272699979001645b42eebba9bb27dce2b7022
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "sidebar/PanelFactory.hxx"
#include "text/TextPropertyPanel.hxx"
#include "paragraph/ParaPropertyPanel.hxx"
#include "area/AreaPropertyPanel.hxx"
#include "graphic/GraphicPropertyPanel.hxx"
#include "line/LinePropertyPanel.hxx"
#include "possize/PosSizePropertyPanel.hxx"
#include "insert/InsertPropertyPanel.hxx"
#include "GalleryControl.hxx"
#include "debug/ColorPanel.hxx"
#include "debug/ContextPanel.hxx"
#include "debug/NotYetImplementedPanel.hxx"
#include "EmptyPanel.hxx"
#include <sfx2/sidebar/SidebarPanelBase.hxx>
#include <sfx2/sidebar/Tools.hxx>
#include <sfx2/sfxbasecontroller.hxx>
#include <sfx2/templdlg.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/window.hxx>
#include <rtl/ref.hxx>
#include <comphelper/namedvaluecollection.hxx>
#include <com/sun/star/ui/XSidebar.hpp>
#include <boost/bind.hpp>
using namespace css;
using namespace cssu;
using ::rtl::OUString;
namespace svx { namespace sidebar {
#define IMPLEMENTATION_NAME "org.apache.openoffice.comp.svx.sidebar.PanelFactory"
#define SERVICE_NAME "com.sun.star.ui.UIElementFactory"
::rtl::OUString SAL_CALL PanelFactory::getImplementationName (void)
{
return A2S(IMPLEMENTATION_NAME);
}
cssu::Reference<cssu::XInterface> SAL_CALL PanelFactory::createInstance (
const uno::Reference<lang::XMultiServiceFactory>& rxFactory)
{
(void)rxFactory;
::rtl::Reference<PanelFactory> pPanelFactory (new PanelFactory());
cssu::Reference<cssu::XInterface> xService (static_cast<XWeak*>(pPanelFactory.get()), cssu::UNO_QUERY);
return xService;
}
cssu::Sequence<OUString> SAL_CALL PanelFactory::getSupportedServiceNames (void)
{
cssu::Sequence<OUString> aServiceNames (1);
aServiceNames[0] = A2S(SERVICE_NAME);
return aServiceNames;
}
PanelFactory::PanelFactory (void)
: PanelFactoryInterfaceBase(m_aMutex)
{
}
PanelFactory::~PanelFactory (void)
{
}
Reference<ui::XUIElement> SAL_CALL PanelFactory::createUIElement (
const ::rtl::OUString& rsResourceURL,
const ::cssu::Sequence<css::beans::PropertyValue>& rArguments)
throw(
container::NoSuchElementException,
lang::IllegalArgumentException,
RuntimeException)
{
const ::comphelper::NamedValueCollection aArguments (rArguments);
Reference<frame::XFrame> xFrame (aArguments.getOrDefault("Frame", Reference<frame::XFrame>()));
Reference<awt::XWindow> xParentWindow (aArguments.getOrDefault("ParentWindow", Reference<awt::XWindow>()));
Reference<ui::XSidebar> xSidebar (aArguments.getOrDefault("Sidebar", Reference<ui::XSidebar>()));
const sal_uInt64 nBindingsValue (aArguments.getOrDefault("SfxBindings", sal_uInt64(0)));
SfxBindings* pBindings = reinterpret_cast<SfxBindings*>(nBindingsValue);
::sfx2::sidebar::EnumContext aContext (
aArguments.getOrDefault("ApplicationName", OUString()),
aArguments.getOrDefault("ContextName", OUString()));
::Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if ( ! xParentWindow.is() || pParentWindow==NULL)
throw RuntimeException(
A2S("PanelFactory::createUIElement called without ParentWindow"),
NULL);
if ( ! xFrame.is())
throw RuntimeException(
A2S("PanelFactory::createUIElement called without Frame"),
NULL);
if (pBindings == NULL)
throw RuntimeException(
A2S("PanelFactory::createUIElement called without SfxBindings"),
NULL);
Window* pControl = NULL;
ui::LayoutSize aLayoutSize (-1,-1,-1);
#define DoesResourceEndWith(s) rsResourceURL.endsWithAsciiL(s,strlen(s))
if (DoesResourceEndWith("/TextPropertyPanel"))
{
pControl = TextPropertyPanel::Create(pParentWindow, xFrame, pBindings, aContext);
}
else if (DoesResourceEndWith("/ParaPropertyPanel"))
{
pControl = ParaPropertyPanel::Create(pParentWindow, xFrame, pBindings, xSidebar);
}
else if (DoesResourceEndWith("/AreaPropertyPanel"))
{
pControl = AreaPropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/GraphicPropertyPanel"))
{
pControl = GraphicPropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/LinePropertyPanel"))
{
pControl = LinePropertyPanel::Create(pParentWindow, xFrame, pBindings);
}
else if (DoesResourceEndWith("/PosSizePropertyPanel"))
{
pControl = PosSizePropertyPanel::Create(pParentWindow, xFrame, pBindings, xSidebar);
}
else if (DoesResourceEndWith("/InsertPropertyPanel"))
{
pControl = new InsertPropertyPanel(pParentWindow, xFrame);
}
else if (DoesResourceEndWith("/GalleryPanel"))
{
pControl = new GalleryControl(pBindings, pParentWindow);
aLayoutSize = ui::LayoutSize(300,-1,400);
}
else if (DoesResourceEndWith("/StyleListPanel"))
{
pControl = new SfxTemplatePanelControl(pBindings, pParentWindow);
aLayoutSize = ui::LayoutSize(0,-1,-1);
}
else if (DoesResourceEndWith("/Debug_ColorPanel"))
{
pControl = new ColorPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(300,-1,400);
}
else if (DoesResourceEndWith("/Debug_ContextPanel"))
{
pControl = new ContextPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(45,45,45);
}
else if (DoesResourceEndWith("/Debug_NotYetImplementedPanel"))
{
pControl = new NotYetImplementedPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(20,25,25);
}
else if (DoesResourceEndWith("/EmptyPanel"))
{
pControl = new EmptyPanel(pParentWindow);
aLayoutSize = ui::LayoutSize(20,-1, 50);
}
#undef DoesResourceEndWith
if (pControl != NULL)
{
return sfx2::sidebar::SidebarPanelBase::Create(
rsResourceURL,
xFrame,
pControl,
aLayoutSize);
}
else
return Reference<ui::XUIElement>();
}
} } // end of namespace svx::sidebar
// eof
|
/*************************************************************************
*
* $RCSfile: unoclbck.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: jp $ $Date: 2001-11-06 08:34:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _UNOIDX_HXX
#include <unoidx.hxx>
#endif
#ifndef _TOX_HXX
#include <tox.hxx>
#endif
#ifndef _UNOCLBCK_HXX
#include <unoclbck.hxx>
#endif
#ifndef _TXTFTN_HXX
#include <txtftn.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FMTRFMRK_HXX
#include <fmtrfmrk.hxx>
#endif
#ifndef _TXTRFMRK_HXX
#include <txtrfmrk.hxx>
#endif
/* -----------------------------06.01.00 13:51--------------------------------
---------------------------------------------------------------------------*/
SwUnoCallBack::SwUnoCallBack(SwModify *pToRegisterIn) :
SwModify(pToRegisterIn)
{
}
/* -----------------------------06.01.00 13:51--------------------------------
---------------------------------------------------------------------------*/
SwUnoCallBack::~SwUnoCallBack()
{
}
/* -----------------------------01.09.00 12:03--------------------------------
---------------------------------------------------------------------------*/
SwXReferenceMark* SwUnoCallBack::GetRefMark(const SwFmtRefMark& rMark)
{
SwClientIter aIter( *this );
SwXReferenceMark* pxRefMark = (SwXReferenceMark*)aIter.First( TYPE( SwXReferenceMark ));
while(pxRefMark)
{
SwDoc* pDoc = pxRefMark->GetDoc();
if(pDoc)
{
const SwFmtRefMark* pFmt = pDoc->GetRefMark(pxRefMark->GetMarkName());
if(pFmt == &rMark)
return pxRefMark;
}
pxRefMark = (SwXReferenceMark*)aIter.Next( );
}
return 0;
}
/* -----------------------------05.09.00 12:38--------------------------------
---------------------------------------------------------------------------*/
SwXFootnote* SwUnoCallBack::GetFootnote(const SwFmtFtn& rMark)
{
SwClientIter aIter( *this );
SwXFootnote* pxFootnote = (SwXFootnote*)aIter.First( TYPE( SwXFootnote ));
while(pxFootnote)
{
SwDoc* pDoc = pxFootnote->GetDoc();
if(pDoc)
{
const SwFmtFtn* pFtn = pxFootnote->FindFmt();
if(pFtn == &rMark)
return pxFootnote;
}
pxFootnote = (SwXFootnote*)aIter.Next( );
}
return 0;
}
/* -----------------------------27.11.00 17:15--------------------------------
---------------------------------------------------------------------------*/
SwXDocumentIndexMark* SwUnoCallBack::GetTOXMark(const SwTOXMark& rMark)
{
SwClientIter aIter( *this );
SwXDocumentIndexMark* pxIndexMark = (SwXDocumentIndexMark*)aIter.First( TYPE( SwXDocumentIndexMark ));
while(pxIndexMark)
{
const SwTOXMark* pMark = pxIndexMark->GetTOXMark();
if(pMark == &rMark)
return pxIndexMark;
pxIndexMark = (SwXDocumentIndexMark*)aIter.Next( );
}
return 0;
}
INTEGRATION: CWS os8 (1.6.158); FILE MERGED
2003/04/03 07:12:14 os 1.6.158.1: #108583# precompiled headers removed
/*************************************************************************
*
* $RCSfile: unoclbck.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:41:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _UNOIDX_HXX
#include <unoidx.hxx>
#endif
#ifndef _TOX_HXX
#include <tox.hxx>
#endif
#ifndef _UNOCLBCK_HXX
#include <unoclbck.hxx>
#endif
#ifndef _TXTFTN_HXX
#include <txtftn.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FMTRFMRK_HXX
#include <fmtrfmrk.hxx>
#endif
#ifndef _TXTRFMRK_HXX
#include <txtrfmrk.hxx>
#endif
/* -----------------------------06.01.00 13:51--------------------------------
---------------------------------------------------------------------------*/
SwUnoCallBack::SwUnoCallBack(SwModify *pToRegisterIn) :
SwModify(pToRegisterIn)
{
}
/* -----------------------------06.01.00 13:51--------------------------------
---------------------------------------------------------------------------*/
SwUnoCallBack::~SwUnoCallBack()
{
}
/* -----------------------------01.09.00 12:03--------------------------------
---------------------------------------------------------------------------*/
SwXReferenceMark* SwUnoCallBack::GetRefMark(const SwFmtRefMark& rMark)
{
SwClientIter aIter( *this );
SwXReferenceMark* pxRefMark = (SwXReferenceMark*)aIter.First( TYPE( SwXReferenceMark ));
while(pxRefMark)
{
SwDoc* pDoc = pxRefMark->GetDoc();
if(pDoc)
{
const SwFmtRefMark* pFmt = pDoc->GetRefMark(pxRefMark->GetMarkName());
if(pFmt == &rMark)
return pxRefMark;
}
pxRefMark = (SwXReferenceMark*)aIter.Next( );
}
return 0;
}
/* -----------------------------05.09.00 12:38--------------------------------
---------------------------------------------------------------------------*/
SwXFootnote* SwUnoCallBack::GetFootnote(const SwFmtFtn& rMark)
{
SwClientIter aIter( *this );
SwXFootnote* pxFootnote = (SwXFootnote*)aIter.First( TYPE( SwXFootnote ));
while(pxFootnote)
{
SwDoc* pDoc = pxFootnote->GetDoc();
if(pDoc)
{
const SwFmtFtn* pFtn = pxFootnote->FindFmt();
if(pFtn == &rMark)
return pxFootnote;
}
pxFootnote = (SwXFootnote*)aIter.Next( );
}
return 0;
}
/* -----------------------------27.11.00 17:15--------------------------------
---------------------------------------------------------------------------*/
SwXDocumentIndexMark* SwUnoCallBack::GetTOXMark(const SwTOXMark& rMark)
{
SwClientIter aIter( *this );
SwXDocumentIndexMark* pxIndexMark = (SwXDocumentIndexMark*)aIter.First( TYPE( SwXDocumentIndexMark ));
while(pxIndexMark)
{
const SwTOXMark* pMark = pxIndexMark->GetTOXMark();
if(pMark == &rMark)
return pxIndexMark;
pxIndexMark = (SwXDocumentIndexMark*)aIter.Next( );
}
return 0;
}
|
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unofield.cxx,v $
*
* $Revision: 1.101 $
*
* last change: $Author: ihi $ $Date: 2007-11-26 15:29:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <swtypes.hxx>
#include <cmdid.h>
#ifndef _DOC_HXX //autogen
#include <doc.hxx>
#endif
#ifndef _HINTS_HXX //autogen
#include <hints.hxx>
#endif
#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#ifndef _NDTXT_HXX //autogen
#include <ndtxt.hxx>
#endif
#ifndef _UNOMAP_HXX
#include <unomap.hxx>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _UNOCOLL_HXX
#include <unocoll.hxx>
#endif
#ifndef _SVXLINKMGR_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _DOCSTAT_HXX //autogen
#include <docstat.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_TIME_HPP_
#include <com/sun/star/util/Time.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIMERANGE_HPP_
#include <com/sun/star/util/DateTimeRange.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSET_HPP_
#include <com/sun/star/beans/XFastPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATECHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyStateChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCONTAINER_HPP_
#include <com/sun/star/beans/XPropertyContainer.hpp>
#endif
//undef to prevent error (from sfx2/docfile.cxx)
#undef SEQUENCE
#ifndef _COM_SUN_STAR_TEXT_SETVARIABLETYPE_HPP_
#include <com/sun/star/text/SetVariableType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_
#include <com/sun/star/text/WrapTextMode.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP_
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_PAGENUMBERTYPE_HPP_
#include <com/sun/star/text/PageNumberType.hpp>
#endif
#ifndef _UNOFIELD_HXX
#include <unofield.hxx>
#endif
#ifndef _UNOCRSR_HXX
#include <unocrsr.hxx>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _FLDDAT_HXX
#include <flddat.hxx>
#endif
#ifndef _DBFLD_HXX
#include <dbfld.hxx>
#endif
#ifndef _USRFLD_HXX
#include <usrfld.hxx>
#endif
#ifndef _DOCUFLD_HXX
#include <docufld.hxx>
#endif
#ifndef _EXPFLD_HXX
#include <expfld.hxx>
#endif
#ifndef _CHPFLD_HXX
#include <chpfld.hxx>
#endif
#ifndef _FLDDROPDOWN_HXX
#include <flddropdown.hxx>
#endif
#ifndef _POOLFMT_HXX
#include <poolfmt.hxx>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif
#ifndef _PAGEDESC_HXX //autogen
#include <pagedesc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _REFFLD_HXX
#include <reffld.hxx>
#endif
#ifndef _DDEFLD_HXX
#include <ddefld.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
#ifndef _SWUNOHELPER_HXX
#include <swunohelper.hxx>
#endif
#ifndef SW_UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _SCRIPTINFO_HXX
#include <scriptinfo.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace nsSwDocInfoSubType;
#define COM_TEXT_FLDMASTER "com.sun.star.text.FieldMaster."
// case-corrected version of the first part for the service names (see #i67811)
#define COM_TEXT_FLDMASTER_CC "com.sun.star.text.fieldmaster."
static const sal_uInt16 aDocInfoSubTypeFromService[] =
{
DI_CHANGE | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_CHANGE_AUTHOR
DI_CHANGE | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_CHANGE_DATE_TIME
DI_EDIT | DI_SUB_TIME, //PROPERTY_MAP_FLDTYP_DOCINFO_EDIT_TIME
DI_COMMENT, //PROPERTY_MAP_FLDTYP_DOCINFO_DESCRIPTION
DI_CREATE | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_CREATE_AUTHOR
DI_CREATE | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_CREATE_DATE_TIME
DI_INFO1, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_0
DI_INFO2, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_1
DI_INFO3, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_2
DI_INFO4, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_3
DI_CUSTOM, //PROPERTY_MAP_FLDTYP_DOCINFO_CUSTOM
DI_PRINT | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_PRINT_AUTHOR
DI_PRINT | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_PRINT_DATE_TIME
DI_KEYS, //PROPERTY_MAP_FLDTYP_DOCINFO_KEY_WORDS
DI_THEMA, //PROPERTY_MAP_FLDTYP_DOCINFO_SUBJECT
DI_TITEL, //PROPERTY_MAP_FLDTYP_DOCINFO_TITLE
DI_DOCNO //PROPERTY_MAP_FLDTYP_DOCINFO_REVISION
};
struct ServiceIdResId
{
USHORT nResId;
USHORT nServiceId;
};
static const ServiceIdResId aServiceToRes[] =
{
{RES_DATETIMEFLD, SW_SERVICE_FIELDTYPE_DATETIME },
{RES_USERFLD, SW_SERVICE_FIELDTYPE_USER },
{RES_SETEXPFLD, SW_SERVICE_FIELDTYPE_SET_EXP } ,
{RES_GETEXPFLD, SW_SERVICE_FIELDTYPE_GET_EXP } ,
{RES_FILENAMEFLD, SW_SERVICE_FIELDTYPE_FILE_NAME },
{RES_PAGENUMBERFLD, SW_SERVICE_FIELDTYPE_PAGE_NUM } ,
{RES_AUTHORFLD, SW_SERVICE_FIELDTYPE_AUTHOR } ,
{RES_CHAPTERFLD, SW_SERVICE_FIELDTYPE_CHAPTER },
{RES_GETREFFLD, SW_SERVICE_FIELDTYPE_GET_REFERENCE } ,
{RES_HIDDENTXTFLD, SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT },
{RES_POSTITFLD, SW_SERVICE_FIELDTYPE_ANNOTATION } ,
{RES_INPUTFLD, SW_SERVICE_FIELDTYPE_INPUT },
{RES_MACROFLD, SW_SERVICE_FIELDTYPE_MACRO },
{RES_DDEFLD, SW_SERVICE_FIELDTYPE_DDE },
{RES_HIDDENPARAFLD, SW_SERVICE_FIELDTYPE_HIDDEN_PARA } ,
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOC_INFO },
{RES_TEMPLNAMEFLD, SW_SERVICE_FIELDTYPE_TEMPLATE_NAME },
{RES_EXTUSERFLD, SW_SERVICE_FIELDTYPE_USER_EXT },
{RES_REFPAGESETFLD, SW_SERVICE_FIELDTYPE_REF_PAGE_SET } ,
{RES_REFPAGEGETFLD, SW_SERVICE_FIELDTYPE_REF_PAGE_GET } ,
{RES_JUMPEDITFLD, SW_SERVICE_FIELDTYPE_JUMP_EDIT },
{RES_SCRIPTFLD, SW_SERVICE_FIELDTYPE_SCRIPT } ,
{RES_DBNEXTSETFLD, SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET },
{RES_DBNUMSETFLD, SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET },
{RES_DBSETNUMBERFLD, SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM } ,
{RES_DBFLD, SW_SERVICE_FIELDTYPE_DATABASE } ,
{RES_DBNAMEFLD, SW_SERVICE_FIELDTYPE_DATABASE_NAME },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_PAGE_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_WORD_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_CHARACTER_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_TABLE_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME},
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME},
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_TITLE },
{RES_INPUTFLD, SW_SERVICE_FIELDTYPE_INPUT_USER },
{RES_HIDDENTXTFLD, SW_SERVICE_FIELDTYPE_HIDDEN_TEXT },
{RES_AUTHORITY, SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY },
{RES_COMBINED_CHARS, SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS },
{RES_DROPDOWN, SW_SERVICE_FIELDTYPE_DROPDOWN },
{RES_TABLEFLD, SW_SERVICE_FIELDTYPE_TABLE_FORMULA },
{USHRT_MAX, USHRT_MAX }
};
//-----------------------------------------------------------------
sal_uInt16 lcl_ServiceIdToResId(sal_uInt16 nServiceId)
{
const ServiceIdResId* pMap = aServiceToRes;
while( USHRT_MAX != pMap->nServiceId && nServiceId != pMap->nServiceId )
++pMap;
#ifdef DBG_UTIL
if( USHRT_MAX == pMap->nServiceId )
DBG_ERROR("service id not found");
#endif
return pMap->nResId;
}
//-----------------------------------------------------------------
sal_uInt16 lcl_GetServiceForField( const SwField& rFld )
{
sal_uInt16 nWhich = rFld.Which(), nSrvId = USHRT_MAX;
//special handling for some fields
switch( nWhich )
{
case RES_INPUTFLD:
if( INP_USR == (rFld.GetSubType() & 0x00ff) )
nSrvId = SW_SERVICE_FIELDTYPE_INPUT_USER;
break;
case RES_DOCINFOFLD:
{
USHORT nSubType = rFld.GetSubType();
switch( (nSubType & 0xff))
{
case DI_CHANGE:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME;
break;
case DI_CREATE:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME;
break;
case DI_PRINT:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME;
break;
case DI_EDIT: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME;break;
case DI_COMMENT:nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION;break;
case DI_INFO1: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0; break;
case DI_INFO2: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1; break;
case DI_INFO3: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2; break;
case DI_INFO4: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3; break;
case DI_KEYS: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS;break;
case DI_THEMA: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT; break;
case DI_TITEL: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_TITLE; break;
case DI_DOCNO: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_REVISION; break;
case DI_CUSTOM: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM; break;
}
}
break;
case RES_HIDDENTXTFLD:
nSrvId = TYP_CONDTXTFLD == rFld.GetSubType()
? SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT
: SW_SERVICE_FIELDTYPE_HIDDEN_TEXT;
break;
case RES_DOCSTATFLD:
{
switch( rFld.GetSubType() )
{
case DS_PAGE: nSrvId = SW_SERVICE_FIELDTYPE_PAGE_COUNT; break;
case DS_PARA: nSrvId = SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT; break;
case DS_WORD: nSrvId = SW_SERVICE_FIELDTYPE_WORD_COUNT ; break;
case DS_CHAR: nSrvId = SW_SERVICE_FIELDTYPE_CHARACTER_COUNT; break;
case DS_TBL: nSrvId = SW_SERVICE_FIELDTYPE_TABLE_COUNT ; break;
case DS_GRF: nSrvId = SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT; break;
case DS_OLE: nSrvId = SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT; break;
}
}
break;
}
if( USHRT_MAX == nSrvId )
{
for( const ServiceIdResId* pMap = aServiceToRes;
USHRT_MAX != pMap->nResId; ++pMap )
if( nWhich == pMap->nResId )
{
nSrvId = pMap->nServiceId;
break;
}
}
#ifdef DBG_UTIL
if( USHRT_MAX == nSrvId )
DBG_ERROR("resid not found");
#endif
return nSrvId;
}
sal_uInt16 lcl_GetPropMapIdForFieldType( USHORT nWhich )
{
sal_uInt16 nId;
switch( nWhich )
{
case RES_USERFLD: nId = PROPERTY_MAP_FLDMSTR_USER; break;
case RES_DBFLD: nId = PROPERTY_MAP_FLDMSTR_DATABASE; break;
case RES_SETEXPFLD: nId = PROPERTY_MAP_FLDMSTR_SET_EXP; break;
case RES_DDEFLD: nId = PROPERTY_MAP_FLDMSTR_DDE; break;
case RES_AUTHORITY: nId = PROPERTY_MAP_FLDMSTR_BIBLIOGRAPHY; break;
default: nId = PROPERTY_MAP_FLDMSTR_DUMMY0;
}
return nId;
}
BYTE GetFieldTypeMId( const OUString& rProperty, const SwFieldType& rTyp )
{
USHORT nId = lcl_GetPropMapIdForFieldType( rTyp.Which() );
const SfxItemPropertyMap* pMap = aSwMapProvider.GetPropertyMap( nId );
if( !pMap )
nId = USHRT_MAX;
else
{
nId = USHRT_MAX; // in case of property not found
for( ; pMap->pName; ++pMap )
if( rProperty.equalsAsciiL( pMap->pName, pMap->nNameLen ) )
{
nId = pMap->nWID;
break;
}
}
return (BYTE)nId;
}
USHORT lcl_GetPropertyMapOfService( USHORT nServiceId )
{
USHORT nRet;
switch ( nServiceId)
{
case SW_SERVICE_FIELDTYPE_DATETIME: nRet = PROPERTY_MAP_FLDTYP_DATETIME; break;
case SW_SERVICE_FIELDTYPE_USER: nRet = PROPERTY_MAP_FLDTYP_USER; break;
case SW_SERVICE_FIELDTYPE_SET_EXP: nRet = PROPERTY_MAP_FLDTYP_SET_EXP; break;
case SW_SERVICE_FIELDTYPE_GET_EXP: nRet = PROPERTY_MAP_FLDTYP_GET_EXP; break;
case SW_SERVICE_FIELDTYPE_FILE_NAME: nRet = PROPERTY_MAP_FLDTYP_FILE_NAME; break;
case SW_SERVICE_FIELDTYPE_PAGE_NUM: nRet = PROPERTY_MAP_FLDTYP_PAGE_NUM; break;
case SW_SERVICE_FIELDTYPE_AUTHOR: nRet = PROPERTY_MAP_FLDTYP_AUTHOR; break;
case SW_SERVICE_FIELDTYPE_CHAPTER: nRet = PROPERTY_MAP_FLDTYP_CHAPTER; break;
case SW_SERVICE_FIELDTYPE_GET_REFERENCE: nRet = PROPERTY_MAP_FLDTYP_GET_REFERENCE; break;
case SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT: nRet = PROPERTY_MAP_FLDTYP_CONDITIONED_TEXT; break;
case SW_SERVICE_FIELDTYPE_ANNOTATION: nRet = PROPERTY_MAP_FLDTYP_ANNOTATION; break;
case SW_SERVICE_FIELDTYPE_INPUT_USER:
case SW_SERVICE_FIELDTYPE_INPUT: nRet = PROPERTY_MAP_FLDTYP_INPUT; break;
case SW_SERVICE_FIELDTYPE_MACRO: nRet = PROPERTY_MAP_FLDTYP_MACRO; break;
case SW_SERVICE_FIELDTYPE_DDE: nRet = PROPERTY_MAP_FLDTYP_DDE; break;
case SW_SERVICE_FIELDTYPE_HIDDEN_PARA: nRet = PROPERTY_MAP_FLDTYP_HIDDEN_PARA; break;
case SW_SERVICE_FIELDTYPE_DOC_INFO: nRet = PROPERTY_MAP_FLDTYP_DOC_INFO; break;
case SW_SERVICE_FIELDTYPE_TEMPLATE_NAME: nRet = PROPERTY_MAP_FLDTYP_TEMPLATE_NAME; break;
case SW_SERVICE_FIELDTYPE_USER_EXT: nRet = PROPERTY_MAP_FLDTYP_USER_EXT; break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_SET: nRet = PROPERTY_MAP_FLDTYP_REF_PAGE_SET; break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_GET: nRet = PROPERTY_MAP_FLDTYP_REF_PAGE_GET; break;
case SW_SERVICE_FIELDTYPE_JUMP_EDIT: nRet = PROPERTY_MAP_FLDTYP_JUMP_EDIT; break;
case SW_SERVICE_FIELDTYPE_SCRIPT: nRet = PROPERTY_MAP_FLDTYP_SCRIPT; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NEXT_SET; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NUM_SET; break;
case SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM: nRet = PROPERTY_MAP_FLDTYP_DATABASE_SET_NUM; break;
case SW_SERVICE_FIELDTYPE_DATABASE: nRet = PROPERTY_MAP_FLDTYP_DATABASE; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NAME: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NAME; break;
case SW_SERVICE_FIELDTYPE_TABLE_FORMULA: nRet = PROPERTY_MAP_FLDTYP_TABLE_FORMULA; break;
case SW_SERVICE_FIELDTYPE_PAGE_COUNT:
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT:
case SW_SERVICE_FIELDTYPE_WORD_COUNT:
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT:
case SW_SERVICE_FIELDTYPE_TABLE_COUNT:
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT:
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT: nRet = PROPERTY_MAP_FLDTYP_DOCSTAT; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR:
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR:
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_AUTHOR; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME:
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME:
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_DATE_TIME; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_EDIT_TIME; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_CUSTOM; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3:
case SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS:
case SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT:
case SW_SERVICE_FIELDTYPE_DOCINFO_TITLE: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_MISC; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_REVISION: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_REVISION; break;
case SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY: nRet = PROPERTY_MAP_FLDTYP_BIBLIOGRAPHY; break;
case SW_SERVICE_FIELDTYPE_DUMMY_0:
case SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS: nRet = PROPERTY_MAP_FLDTYP_COMBINED_CHARACTERS; break;
case SW_SERVICE_FIELDTYPE_DROPDOWN: nRet = PROPERTY_MAP_FLDTYP_DROPDOWN; break;
case SW_SERVICE_FIELDTYPE_DUMMY_4:
case SW_SERVICE_FIELDTYPE_DUMMY_5:
case SW_SERVICE_FIELDTYPE_DUMMY_6:
case SW_SERVICE_FIELDTYPE_DUMMY_7:
case SW_SERVICE_FIELDTYPE_DUMMY_8: nRet = PROPERTY_MAP_FLDTYP_DUMMY_0; break;
case SW_SERVICE_FIELDMASTER_USER: nRet = PROPERTY_MAP_FLDMSTR_USER; break;
case SW_SERVICE_FIELDMASTER_DDE: nRet = PROPERTY_MAP_FLDMSTR_DDE; break;
case SW_SERVICE_FIELDMASTER_SET_EXP: nRet = PROPERTY_MAP_FLDMSTR_SET_EXP; break;
case SW_SERVICE_FIELDMASTER_DATABASE: nRet = PROPERTY_MAP_FLDMSTR_DATABASE; break;
case SW_SERVICE_FIELDMASTER_BIBLIOGRAPHY: nRet = PROPERTY_MAP_FLDMSTR_BIBLIOGRAPHY; break;
case SW_SERVICE_FIELDMASTER_DUMMY2:
case SW_SERVICE_FIELDMASTER_DUMMY3:
case SW_SERVICE_FIELDMASTER_DUMMY4:
case SW_SERVICE_FIELDMASTER_DUMMY5: nRet = PROPERTY_MAP_FLDMSTR_DUMMY0; break;
case SW_SERVICE_FIELDTYPE_HIDDEN_TEXT: nRet = PROPERTY_MAP_FLDTYP_HIDDEN_TEXT; break;
default:
DBG_ERROR( "wrong service id" );
nRet = USHRT_MAX;
}
return nRet;
}
/******************************************************************
* SwXFieldMaster
******************************************************************/
TYPEINIT1(SwXFieldMaster, SwClient);
/* -----------------------------13.03.00 12:15--------------------------------
---------------------------------------------------------------------------*/
const uno::Sequence< sal_Int8 > & SwXFieldMaster::getUnoTunnelId()
{
static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId();
return aSeq;
}
/* -----------------------------10.03.00 18:04--------------------------------
---------------------------------------------------------------------------*/
sal_Int64 SAL_CALL SwXFieldMaster::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw(uno::RuntimeException)
{
if( rId.getLength() == 16
&& 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return sal::static_int_cast< sal_Int64 >( reinterpret_cast< sal_IntPtr >(this) );
}
return 0;
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXFieldMaster");
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXFieldMaster::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
sal_Bool bRet = sal_False;
if(rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("com.sun.star.text.TextFieldMaster")))
bRet = sal_True;
else
{
const sal_Char* pEntry;
switch( nResTypeId )
{
case RES_USERFLD: pEntry = "User"; break;
case RES_DBFLD: pEntry = "Database"; break;
case RES_SETEXPFLD: pEntry = "SetExpression"; break;
case RES_DDEFLD: pEntry = "DDE"; break;
case RES_AUTHORITY: pEntry = "Bibliography"; break;
default: pEntry = 0;
}
if( pEntry )
{
ByteString aTmp( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.fieldmaster."));
aTmp.Append( pEntry );
bRet = rServiceName.equalsAsciiL(aTmp.GetBuffer(), aTmp.Len());
}
}
return bRet;
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXFieldMaster::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFieldMaster");
const sal_Char* pEntry1;
switch( nResTypeId )
{
case RES_USERFLD: pEntry1 = "User"; break;
case RES_DBFLD: pEntry1 = "Database"; break;
case RES_SETEXPFLD: pEntry1 = "SetExpression"; break;
case RES_DDEFLD: pEntry1 = "DDE"; break;
case RES_AUTHORITY: pEntry1 = "Bibliography"; break;
default: pEntry1 = 0;
}
if( pEntry1 )
{
String s;
s.AppendAscii( "com.sun.star.text.fieldmaster." ).AppendAscii( pEntry1 );
pArray[1] = s;
}
return aRet;
}
/*-- 14.12.98 11:08:33---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::SwXFieldMaster(SwDoc* pDoc, sal_uInt16 nResId) :
aLstnrCntnr( (XPropertySet*)this),
nResTypeId(nResId),
m_pDoc(pDoc),
m_bIsDescriptor(sal_True),
fParam1(0.),
nParam1(-1),
bParam1(FALSE),
nParam2(0)
{
pDoc->GetPageDescFromPool(RES_POOLPAGE_STANDARD)->Add(this);
}
/*-- 14.12.98 11:08:33---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::SwXFieldMaster(SwFieldType& rType, SwDoc* pDoc) :
SwClient(&rType),
aLstnrCntnr( (XPropertySet*)this),
nResTypeId(rType.Which()),
m_pDoc(pDoc),
m_bIsDescriptor(sal_False),
fParam1(0.),
nParam1(-1),
bParam1(FALSE)
{
}
/*-- 14.12.98 11:08:34---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::~SwXFieldMaster()
{
}
/*-- 14.12.98 11:08:35---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySetInfo > SwXFieldMaster::getPropertySetInfo(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Reference< beans::XPropertySetInfo > aRef = new SfxItemPropertySetInfo(
aSwMapProvider.GetPropertyMap(
lcl_GetPropMapIdForFieldType( nResTypeId ) ));
return aRef;
}
/*-- 14.12.98 11:08:35---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::setPropertyValue( const OUString& rPropertyName,
const uno::Any& rValue)
throw( beans::UnknownPropertyException, beans::PropertyVetoException,
lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pType = GetFldType(sal_True);
if(pType)
{
sal_Bool bSetValue = sal_True;
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_SUB_TYPE)))
{
const SvStringsDtor& rExtraArr = SwStyleNameMapper::GetExtraUINameArray();
String sTypeName = pType->GetName();
static sal_uInt16 nIds[] =
{
RES_POOLCOLL_LABEL_DRAWING - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_ABB - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_TABLE - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_FRAME- RES_POOLCOLL_EXTRA_BEGIN,
0
};
for(const sal_uInt16 * pIds = nIds; *pIds; ++pIds)
{
if(sTypeName == *rExtraArr[ *pIds ] )
{
bSetValue = sal_False;
break;
}
}
}
if( bSetValue )
{
// nothing special to be done here for the properties
// UNO_NAME_DATA_BASE_NAME and UNO_NAME_DATA_BASE_URL.
// We just call PutValue (empty string is allowed).
// Thus the last property set will be used as Data Source.
BYTE nMId = GetFieldTypeMId( rPropertyName, *pType );
if( UCHAR_MAX != nMId )
pType->PutValue( rValue, nMId );
else
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
}
else if(!pType && m_pDoc &&
( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NAME))) )
{
OUString uTmp;
rValue >>= uTmp;
String sTypeName(uTmp);
SwFieldType* pType2 = m_pDoc->GetFldType(nResTypeId, sTypeName, sal_False);
String sTable(SW_RES(STR_POOLCOLL_LABEL_TABLE));
String sDrawing(SW_RES(STR_POOLCOLL_LABEL_DRAWING));
String sFrame(SW_RES(STR_POOLCOLL_LABEL_FRAME));
String sIllustration(SW_RES(STR_POOLCOLL_LABEL_ABB));
if(pType2 ||
(RES_SETEXPFLD == nResTypeId &&
( sTypeName == sTable || sTypeName == sDrawing ||
sTypeName == sFrame || sTypeName == sIllustration )))
{
throw lang::IllegalArgumentException();
}
else
{
switch(nResTypeId)
{
case RES_USERFLD :
{
SwUserFieldType aType(m_pDoc, sTypeName);
pType2 = m_pDoc->InsertFldType(aType);
((SwUserFieldType*)pType2)->SetContent(sParam1);
((SwUserFieldType*)pType2)->SetValue(fParam1);
((SwUserFieldType*)pType2)->SetType(bParam1 ? nsSwGetSetExpType::GSE_EXPR : nsSwGetSetExpType::GSE_STRING);
}
break;
case RES_DDEFLD :
{
SwDDEFieldType aType(sTypeName, sParam1,
sal::static_int_cast< USHORT >(bParam1 ? sfx2::LINKUPDATE_ALWAYS : sfx2::LINKUPDATE_ONCALL));
pType2 = m_pDoc->InsertFldType(aType);
}
break;
case RES_SETEXPFLD :
{
SwSetExpFieldType aType(m_pDoc, sTypeName);
if(sParam1.Len())
aType.SetDelimiter( sParam1.GetChar(0));
if(nParam1 > -1 && nParam1 < MAXLEVEL)
aType.SetOutlineLvl(nParam1);
pType2 = m_pDoc->InsertFldType(aType);
}
break;
case RES_DBFLD :
{
::GetString( rValue, sParam3 );
pType = GetFldType();
}
break;
}
if(pType2)
{
pType2->Add(this);
m_bIsDescriptor = sal_False;
}
else
throw uno::RuntimeException();
}
DBG_ASSERT(pType2, "kein FieldType gefunden!" );
}
else
{
switch( nResTypeId )
{
case RES_USERFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CONTENT)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_VALUE )))
{
if(rValue.getValueType() != ::getCppuType(static_cast<const double*>(0)))
throw lang::IllegalArgumentException();
fParam1 = *(double*)rValue.getValue();
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_EXPRESSION )))
{
if(rValue.getValueType() != ::getBooleanCppuType())
throw lang::IllegalArgumentException();
bParam1 = *(sal_Bool*)rValue.getValue();
}
break;
case RES_DBFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME)))
::GetString( rValue, sParam2 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME)))
::GetString( rValue, sParam3 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)))
rValue >>= nParam2;
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
::GetString( rValue, sParam5 );
if((sParam1.Len() || sParam5.Len())
&& sParam2.Len() && sParam3.Len())
GetFldType();
break;
case RES_SETEXPFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NUMBERING_SEPARATOR)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CHAPTER_NUMBERING_LEVEL)))
rValue >>= nParam1;
break;
case RES_DDEFLD:
{
USHORT nPart = rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_TYPE)) ? 0 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_FILE)) ? 1 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_ELEMENT)) ? 2 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_AUTOMATIC_UPDATE)) ? 3 : USHRT_MAX;
if(nPart < 3 )
{
String sTmp;
if(!sParam1.Len())
(sParam1 = sfx2::cTokenSeperator)
+= sfx2::cTokenSeperator;
sParam1.SetToken( nPart, sfx2::cTokenSeperator,
::GetString( rValue, sTmp ));
}
else if(3 == nPart)
bParam1 = *(sal_Bool*)rValue.getValue();
}
break;
default:
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
}
}
/* -----------------------------30.03.01 14:40--------------------------------
---------------------------------------------------------------------------*/
SwFieldType* SwXFieldMaster::GetFldType(sal_Bool bDontCreate) const
{
if(!bDontCreate && RES_DBFLD == nResTypeId && m_bIsDescriptor && m_pDoc)
{
SwDBData aData;
// set DataSource
svx::ODataAccessDescriptor aAcc;
if( sParam1.Len() > 0 )
aAcc[ svx::daDataSource ] <<= OUString(sParam1); // DataBaseName
else if( sParam5.Len() > 0 )
aAcc[ svx::daDatabaseLocation] <<= OUString(sParam5); // DataBaseURL
aData.sDataSource = aAcc.getDataSource();
aData.sCommand = sParam2;
aData.nCommandType = nParam2;
SwDBFieldType aType(m_pDoc, sParam3, aData);
SwFieldType* pType = m_pDoc->InsertFldType(aType);
SwXFieldMaster* pThis = ((SwXFieldMaster*)this);
pType->Add(pThis);
pThis->m_bIsDescriptor = sal_False;
}
if(m_bIsDescriptor)
return 0;
else
return (SwFieldType*)GetRegisteredIn();
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
typedef SwFmtFld* SwFmtFldPtr;
SV_DECL_PTRARR(SwDependentFields, SwFmtFldPtr, 5, 5)
SV_IMPL_PTRARR(SwDependentFields, SwFmtFldPtr)
uno::Any SwXFieldMaster::getPropertyValue(const OUString& rPropertyName)
throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Any aRet;
SwFieldType* pType = GetFldType(sal_True);
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_INSTANCE_NAME)) )
{
String sName;
if(pType)
SwXTextFieldMasters::getInstanceName(*pType, sName);
aRet <<= OUString(sName);
}
else if(pType)
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NAME) ))
{
aRet <<= SwXFieldMaster::GetProgrammaticName(*pType, *GetDoc());
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DEPENDENT_TEXT_FIELDS)) )
{
//fill all text fields into a sequence
SwClientIter aIter( *pType );
SwDependentFields aFldArr;
SwFmtFldPtr pFld = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while(pFld)
{
if(pFld->IsFldInDoc())
aFldArr.Insert(pFld, aFldArr.Count());
pFld = (SwFmtFld*)aIter.Next();
}
uno::Sequence<uno::Reference <text::XDependentTextField> > aRetSeq(aFldArr.Count());
uno::Reference<text::XDependentTextField>* pRetSeq = aRetSeq.getArray();
SwXTextField* pInsert = 0;
for(USHORT i = 0; i < aFldArr.Count(); i++)
{
pFld = aFldArr.GetObject(i);
SwXTextField* pTemp = (SwXTextField*)aIter.First(TYPE(SwXTextField));
while(pTemp)
{
if(pTemp->GetFldFmt() == pFld)
{
pInsert = pTemp;
break;
}
pTemp = (SwXTextField*)aIter.Next();
}
if(!pInsert)
pInsert = new SwXTextField( *pFld, GetDoc());
pRetSeq[i] = uno::Reference<text::XDependentTextField>(pInsert);
pInsert = 0;
}
aRet <<= aRetSeq;
}
else if(pType)
{
//TODO: Properties fuer die uebrigen Feldtypen einbauen
BYTE nMId = GetFieldTypeMId( rPropertyName, *pType );
if( UCHAR_MAX != nMId )
{
pType->QueryValue( aRet, nMId );
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
{
OUString aDataSource;
aRet >>= aDataSource;
aRet <<= OUString();
OUString *pStr = 0; // only one of this properties will return
// a non-empty string.
INetURLObject aObj;
aObj.SetURL( aDataSource );
BOOL bIsURL = aObj.GetProtocol() != INET_PROT_NOT_VALID;
if (bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
pStr = &aDataSource; // DataBaseURL
else if (!bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
pStr = &aDataSource; // DataBaseName
if (pStr)
aRet <<= *pStr;
}
}
else
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
else
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)) )
aRet <<= nParam2;
}
}
else
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)) )
aRet <<= nParam2;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DEPENDENT_TEXT_FIELDS)) )
{
uno::Sequence<uno::Reference <text::XDependentTextField> > aRetSeq(0);
aRet <<= aRetSeq;
}
else
{
const String* pStr = 0;
String sStr;
switch ( nResTypeId )
{
case RES_USERFLD:
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CONTENT)) )
pStr = &sParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_VALUE )))
aRet <<= fParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_EXPRESSION )))
aRet.setValue(&bParam1, ::getBooleanCppuType());
break;
case RES_DBFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
{
pStr = 0; // only one of this properties will return
// a non-empty string.
INetURLObject aObj;
aObj.SetURL( sParam5 ); // SetSmartURL
BOOL bIsURL = aObj.GetProtocol() != INET_PROT_NOT_VALID;
if (bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
pStr = &sParam5; // DataBaseURL
else if ( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
pStr = &sParam1; // DataBaseName
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME)))
pStr = &sParam2;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME)))
pStr = &sParam3;
break;
case RES_SETEXPFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NUMBERING_SEPARATOR)))
pStr = &sParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CHAPTER_NUMBERING_LEVEL)))
aRet <<= nParam1;
break;
case RES_DDEFLD:
{
USHORT nPart = rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_TYPE)) ? 0 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_FILE)) ? 1 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_ELEMENT)) ? 2 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_AUTOMATIC_UPDATE)) ? 3 : USHRT_MAX;
if(nPart < 3 )
pStr = &(sStr = sParam1.GetToken(nPart, sfx2::cTokenSeperator));
else if(3 == nPart)
aRet.setValue(&bParam1, ::getBooleanCppuType());
}
break;
default:
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
if( pStr )
aRet <<= OUString( *pStr );
}
}
return aRet;
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addPropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removePropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:37---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:37---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removeVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 25.02.99 11:01:57---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::dispose(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pFldType = GetFldType(sal_True);
if(pFldType)
{
sal_uInt16 nTypeIdx = USHRT_MAX;
const SwFldTypes* pTypes = GetDoc()->GetFldTypes();
for( sal_uInt16 i = 0; i < pTypes->Count(); i++ )
{
if((*pTypes)[i] == pFldType)
nTypeIdx = i;
}
// zuerst alle Felder loeschen
SwClientIter aIter( *pFldType );
SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while(pFld)
{
// Feld im Undo?
SwTxtFld *pTxtFld = pFld->GetTxtFld();
if(pTxtFld && pTxtFld->GetTxtNode().GetNodes().IsDocNodes() )
{
SwTxtNode& rTxtNode = (SwTxtNode&)*pTxtFld->GetpTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart());
aPam.SetMark();
aPam.Move();
GetDoc()->DeleteAndJoin(aPam);
}
pFld = (SwFmtFld*)aIter.Next();
}
// dann den FieldType loeschen
GetDoc()->RemoveFldType(nTypeIdx);
}
else
throw uno::RuntimeException();
}
/*-- 25.02.99 11:02:00---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addEventListener(const uno::Reference< lang::XEventListener > & aListener)
throw( uno::RuntimeException )
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
aLstnrCntnr.AddListener(aListener);
}
/*-- 25.02.99 11:02:02---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removeEventListener(const uno::Reference< lang::XEventListener > & aListener)
throw( uno::RuntimeException )
{
if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener))
throw uno::RuntimeException();
}
/*-- 14.12.98 11:08:38---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
ClientModify(this, pOld, pNew);
if(!GetRegisteredIn())
{
aLstnrCntnr.Disposing();
m_pDoc = 0;
}
}
/* -----------------------------06.11.00 09:44--------------------------------
const Programmatic2UIName_Impl* lcl_GetFieldNameTable()
{
static BOOL bInitialized = FALSE;
static Programmatic2UIName_Impl aFieldNames[5];
if(!bInitialized)
{
bInitialized = TRUE;
int nName = 0;
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_ABB ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_ABB));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_TABLE ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_TABLE));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_FRAME));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_FRAME));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_DRAWING ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_DRAWING));
}
return &aFieldNames[0];
}
---------------------------------------------------------------------------*/
/* -----------------------------06.11.00 10:26--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::GetProgrammaticName(const SwFieldType& rType, SwDoc& rDoc)
{
OUString sRet(rType.GetName());
if(RES_SETEXPFLD == rType.Which())
{
const SwFldTypes* pTypes = rDoc.GetFldTypes();
for( sal_uInt16 i = 0; i <= INIT_FLDTYPES; i++ )
{
if((*pTypes)[i] == &rType)
{
sRet = SwStyleNameMapper::GetProgName ( sRet, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL );
break;
}
}
}
return sRet;
}
/* -----------------------------06.11.00 14:12--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::LocalizeFormula(
const SwSetExpField& rFld,
const OUString& rFormula,
sal_Bool bQuery)
{
const OUString sTypeName(rFld.GetTyp()->GetName());
OUString sProgName = SwStyleNameMapper::GetProgName(sTypeName, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL );
if(sProgName != sTypeName)
{
OUString sSource = bQuery ? sTypeName : sProgName;
OUString sDest = bQuery ? sProgName : sTypeName;
if(!rFormula.compareTo(sSource, sSource.getLength()))
{
OUString sTmpFormula = sDest;
sTmpFormula += rFormula.copy(sSource.getLength());
return sTmpFormula;
}
}
return rFormula;
}
/******************************************************************
*
******************************************************************/
struct SwFieldProperties_Impl
{
String sPar1;
String sPar2;
String sPar3;
String sPar4;
String sPar5;
String sPar6;
Date aDate;
double fDouble;
uno::Sequence<beans::PropertyValue> aPropSeq;
uno::Sequence<OUString> aStrings;
util::DateTime* pDateTime;
sal_Int32 nSubType;
sal_Int32 nFormat;
sal_uInt16 nUSHORT1;
sal_uInt16 nUSHORT2;
sal_Int16 nSHORT1;
sal_Int8 nByte1;
sal_Bool bFormatIsDefault;
sal_Bool bBool1;
sal_Bool bBool2;
sal_Bool bBool3;
sal_Bool bBool4;
SwFieldProperties_Impl():
fDouble(0.),
pDateTime(0),
nSubType(0),
nFormat(0),
nUSHORT1(0),
nUSHORT2(0),
nSHORT1(0),
nByte1(0),
bFormatIsDefault(sal_True),
bBool1(sal_False),
bBool2(sal_False),
bBool3(sal_False),
bBool4(sal_True) //Automatic language
{}
~SwFieldProperties_Impl()
{delete pDateTime;}
};
TYPEINIT1(SwXTextField, SwClient);
/* -----------------------------13.03.00 12:15--------------------------------
---------------------------------------------------------------------------*/
const uno::Sequence< sal_Int8 > & SwXTextField::getUnoTunnelId()
{
static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId();
return aSeq;
}
/* -----------------------------10.03.00 18:04--------------------------------
---------------------------------------------------------------------------*/
sal_Int64 SAL_CALL SwXTextField::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw(uno::RuntimeException)
{
if( rId.getLength() == 16
&& 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return sal::static_int_cast< sal_Int64 >( reinterpret_cast< sal_IntPtr >(this) );
}
return 0;
}
/*-- 14.12.98 11:37:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::SwXTextField(sal_uInt16 nServiceId) :
aLstnrCntnr( (XTextContent*)this),
pFmtFld(0),
m_pDoc(0),
m_bIsDescriptor(nServiceId != USHRT_MAX),
m_bCallUpdate(sal_False),
m_nServiceId(nServiceId),
m_pProps(new SwFieldProperties_Impl)
{
//Set visible as default!
if(SW_SERVICE_FIELDTYPE_SET_EXP == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE_NAME == nServiceId )
m_pProps->bBool2 = sal_True;
else if(SW_SERVICE_FIELDTYPE_TABLE_FORMULA == nServiceId)
m_pProps->bBool1 = sal_True;
if(SW_SERVICE_FIELDTYPE_SET_EXP == nServiceId)
m_pProps->nUSHORT2 = USHRT_MAX;
}
/*-- 14.12.98 11:37:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::SwXTextField(const SwFmtFld& rFmt, SwDoc* pDc) :
aLstnrCntnr( (XTextContent*)this),
pFmtFld(&rFmt),
m_pDoc(pDc),
m_bIsDescriptor(sal_False),
m_bCallUpdate(sal_False),
m_nServiceId( lcl_GetServiceForField( *pFmtFld->GetFld() ) ),
m_pProps(0)
{
pDc->GetUnoCallBack()->Add(this);
}
/*-- 14.12.98 11:37:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::~SwXTextField()
{
delete m_pProps;
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::attachTextFieldMaster(const uno::Reference< beans::XPropertySet > & xFieldMaster)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!m_bIsDescriptor)
throw uno::RuntimeException();
uno::Reference< lang::XUnoTunnel > xMasterTunnel(xFieldMaster, uno::UNO_QUERY);
if (!xMasterTunnel.is())
throw lang::IllegalArgumentException();
SwXFieldMaster* pMaster = reinterpret_cast< SwXFieldMaster * >(
sal::static_int_cast< sal_IntPtr >( xMasterTunnel->getSomething( SwXFieldMaster::getUnoTunnelId()) ));
SwFieldType* pFieldType = pMaster ? pMaster->GetFldType() : 0;
if(pFieldType && pFieldType->Which() == lcl_ServiceIdToResId(m_nServiceId))
{
m_sTypeName = pFieldType->GetName();
pFieldType->Add( &m_aFieldTypeClient );
}
else
throw lang::IllegalArgumentException();
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySet > SwXTextField::getTextFieldMaster(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pType = 0;
if( m_bIsDescriptor && m_aFieldTypeClient.GetRegisteredIn() )
{
pType = (SwFieldType*)m_aFieldTypeClient.GetRegisteredIn();
}
else
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
pType = pFmtFld->GetFld()->GetTyp();
}
SwXFieldMaster* pMaster = (SwXFieldMaster*)
SwClientIter(*pType).First(TYPE(SwXFieldMaster));
if(!pMaster)
pMaster = new SwXFieldMaster(*pType, GetDoc());
return pMaster;
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
OUString SwXTextField::getPresentation(sal_Bool bShowCommand) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
OUString sRet;
const SwField* pField = GetField();
if(pField)
sRet = pField->GetCntnt(bShowCommand);
else
throw uno::RuntimeException();
return sRet;
}
/* -----------------18.02.99 13:39-------------------
*
* --------------------------------------------------*/
void SwXTextField::attachToRange(
const uno::Reference< text::XTextRange > & xTextRange)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!m_bIsDescriptor)
throw uno::RuntimeException();
uno::Reference<lang::XUnoTunnel> xRangeTunnel( xTextRange, uno::UNO_QUERY);
SwXTextRange* pRange = 0;
OTextCursorHelper* pCursor = 0;
if(xRangeTunnel.is())
{
pRange = reinterpret_cast< SwXTextRange * >(
sal::static_int_cast< sal_IntPtr >( xRangeTunnel->getSomething( SwXTextRange::getUnoTunnelId()) ));
pCursor = reinterpret_cast< OTextCursorHelper * >(
sal::static_int_cast< sal_IntPtr >( xRangeTunnel->getSomething( OTextCursorHelper::getUnoTunnelId()) ));
}
SwDoc* pDoc = pRange ? (SwDoc*)pRange->GetDoc() : pCursor ? (SwDoc*)pCursor->GetDoc() : 0;
//wurde ein FieldMaster attached, dann ist das Dokument schon festgelegt!
if(pDoc && (!m_pDoc || m_pDoc == pDoc))
{
SwUnoInternalPaM aPam(*pDoc);
//das muss jetzt sal_True liefern
SwXTextRange::XTextRangeToSwPaM(aPam, xTextRange);
SwField* pFld = 0;
switch(m_nServiceId)
{
case SW_SERVICE_FIELDTYPE_ANNOTATION:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_POSTITFLD);
pFld = new SwPostItField((SwPostItFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,
m_pProps->aDate);
}
break;
case SW_SERVICE_FIELDTYPE_SCRIPT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_SCRIPTFLD);
pFld = new SwScriptField((SwScriptFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,
m_pProps->bBool1);
}
break;
case SW_SERVICE_FIELDTYPE_DATETIME:
{
sal_uInt16 nSub = 0;
if(m_pProps->bBool1)
nSub |= FIXEDFLD;
if(m_pProps->bBool2)
nSub |= DATEFLD;
else
nSub |= TIMEFLD;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DATETIMEFLD);
pFld = new SwDateTimeField((SwDateTimeFieldType*)pFldType,
nSub, m_pProps->nFormat);
if(m_pProps->fDouble > 0.)
((SwDateTimeField*)pFld)->SetValue( m_pProps->fDouble );
if(m_pProps->pDateTime)
{
uno::Any aVal; aVal <<= *m_pProps->pDateTime;
pFld->PutValue( aVal, FIELD_PROP_DATE_TIME );
}
((SwDateTimeField*)pFld)->SetOffset(m_pProps->nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_FILE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_FILENAMEFLD);
sal_Int32 nFormat = m_pProps->nFormat;
if(m_pProps->bBool2)
nFormat |= FF_FIXED;
pFld = new SwFileNameField((SwFileNameFieldType*)pFldType, nFormat);
if(m_pProps->sPar3.Len())
((SwFileNameField*)pFld)->SetExpansion(m_pProps->sPar3);
uno::Any aFormat(&m_pProps->nFormat, ::getCppuType(&m_pProps->nFormat));
pFld->PutValue( aFormat, FIELD_PROP_FORMAT );
}
break;
case SW_SERVICE_FIELDTYPE_TEMPLATE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_TEMPLNAMEFLD);
pFld = new SwTemplNameField((SwTemplNameFieldType*)pFldType,
m_pProps->nFormat);
uno::Any aFormat(&m_pProps->nFormat, ::getCppuType(&m_pProps->nFormat));
pFld->PutValue(aFormat, FIELD_PROP_FORMAT);
}
break;
case SW_SERVICE_FIELDTYPE_CHAPTER:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_CHAPTERFLD);
pFld = new SwChapterField((SwChapterFieldType*)pFldType, m_pProps->nUSHORT1);
((SwChapterField*)pFld)->SetLevel(m_pProps->nByte1);
uno::Any aVal; aVal <<= (sal_Int16)m_pProps->nUSHORT1;
pFld->PutValue(aVal, FIELD_PROP_USHORT1 );
}
break;
case SW_SERVICE_FIELDTYPE_AUTHOR:
{
long nFormat = m_pProps->bBool1 ? AF_NAME : AF_SHORTCUT;
if(m_pProps->bBool2)
nFormat |= AF_FIXED;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_AUTHORFLD);
pFld = new SwAuthorField((SwAuthorFieldType*)pFldType, nFormat);
((SwAuthorField*)pFld)->SetExpansion(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT:
case SW_SERVICE_FIELDTYPE_HIDDEN_TEXT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_HIDDENTXTFLD);
pFld = new SwHiddenTxtField(((SwHiddenTxtFieldType*)pFldType),
m_pProps->sPar1,
m_pProps->sPar2, m_pProps->sPar3,
static_cast< USHORT >(SW_SERVICE_FIELDTYPE_HIDDEN_TEXT == m_nServiceId ?
TYP_HIDDENTXTFLD : TYP_CONDTXTFLD));
((SwHiddenTxtField*)pFld)->SetValue(m_pProps->bBool1);
uno::Any aVal; aVal <<= (OUString)m_pProps->sPar4;
pFld->PutValue(aVal, FIELD_PROP_PAR4 );
}
break;
case SW_SERVICE_FIELDTYPE_HIDDEN_PARA:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_HIDDENPARAFLD);
pFld = new SwHiddenParaField((SwHiddenParaFieldType*)pFldType,
m_pProps->sPar1);
((SwHiddenParaField*)pFld)->SetHidden(m_pProps->bBool1);
}
break;
case SW_SERVICE_FIELDTYPE_GET_REFERENCE:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_GETREFFLD);
pFld = new SwGetRefField((SwGetRefFieldType*)pFldType,
m_pProps->sPar1,
0,
0,
0);
if(m_pProps->sPar3.Len())
((SwGetRefField*)pFld)->SetExpand(m_pProps->sPar3);
uno::Any aVal; aVal <<=(sal_Int16)m_pProps->nUSHORT1;
pFld->PutValue(aVal, FIELD_PROP_USHORT1 );
aVal <<=(sal_Int16)m_pProps->nUSHORT2;
pFld->PutValue(aVal, FIELD_PROP_USHORT2 );
aVal <<=(sal_Int16)m_pProps->nSHORT1;
pFld->PutValue(aVal, FIELD_PROP_SHORT1 );
}
break;
case SW_SERVICE_FIELDTYPE_JUMP_EDIT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_JUMPEDITFLD);
pFld = new SwJumpEditField((SwJumpEditFieldType*)pFldType,
m_pProps->nUSHORT1, m_pProps->sPar2, m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION :
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3 :
case SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM :
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS :
case SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT :
case SW_SERVICE_FIELDTYPE_DOCINFO_TITLE :
case SW_SERVICE_FIELDTYPE_DOCINFO_REVISION :
case SW_SERVICE_FIELDTYPE_DOC_INFO:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DOCINFOFLD);
sal_uInt16 nSubType = aDocInfoSubTypeFromService[
m_nServiceId - SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR];
if( SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME == m_nServiceId )
{
if(m_pProps->bBool2) //IsDate
{
nSubType &= 0xf0ff;
nSubType |= DI_SUB_DATE;
}
else
{
nSubType &= 0xf0ff;
nSubType |= DI_SUB_TIME;
}
}
if(m_pProps->bBool1)
nSubType |= DI_SUB_FIXED;
pFld = new SwDocInfoField((SwDocInfoFieldType*)pFldType, nSubType, m_pProps->sPar4, m_pProps->nFormat);
if(m_pProps->sPar3.Len())
((SwDocInfoField*)pFld)->SetExpansion(m_pProps->sPar3);
}
break;
case SW_SERVICE_FIELDTYPE_USER_EXT:
{
sal_Int32 nFormat = 0;
if(m_pProps->bBool1)
nFormat = AF_FIXED;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_EXTUSERFLD);
pFld = new SwExtUserField((SwExtUserFieldType*)pFldType, m_pProps->nUSHORT1, nFormat);
((SwExtUserField*)pFld)->SetExpansion(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_USER:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_USERFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
USHORT nUserSubType = m_pProps->bBool1 ? nsSwExtendedSubType::SUB_INVISIBLE : 0;
if(m_pProps->bBool2)
nUserSubType |= nsSwExtendedSubType::SUB_CMD;
if(m_pProps->bFormatIsDefault &&
nsSwGetSetExpType::GSE_STRING == ((SwUserFieldType*)pFldType)->GetType())
m_pProps->nFormat = -1;
pFld = new SwUserField((SwUserFieldType*)pFldType,
nUserSubType,
m_pProps->nFormat);
}
break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_SET:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_REFPAGESETFLD);
pFld = new SwRefPageSetField( (SwRefPageSetFieldType*)pFldType,
m_pProps->nUSHORT1,
m_pProps->bBool1 );
}
break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_GET:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_REFPAGEGETFLD);
pFld = new SwRefPageGetField( (SwRefPageGetFieldType*)pFldType,
m_pProps->nUSHORT1 );
((SwRefPageGetField*)pFld)->SetText(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_PAGE_NUM:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_PAGENUMBERFLD);
pFld = new SwPageNumberField((SwPageNumberFieldType*)pFldType,
PG_RANDOM,
m_pProps->nFormat,
m_pProps->nUSHORT1);
((SwPageNumberField*)pFld)->SetUserString(m_pProps->sPar1);
uno::Any aVal; aVal <<= m_pProps->nSubType;
pFld->PutValue( aVal, FIELD_PROP_SUBTYPE );
}
break;
case SW_SERVICE_FIELDTYPE_DDE:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_DDEFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
pFld = new SwDDEField( (SwDDEFieldType*)pFldType );
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DBNAMEFLD);
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBNameField((SwDBNameFieldType*)pFldType, aData);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DBNEXTSETFLD);
pFld = new SwDBNextSetField((SwDBNextSetFieldType*)pFldType,
m_pProps->sPar3, aEmptyStr,
aData);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBNumSetField( (SwDBNumSetFieldType*)
pDoc->GetSysFldType(RES_DBNUMSETFLD),
m_pProps->sPar3,
String::CreateFromInt32(m_pProps->nFormat),
aData );
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBSetNumberField((SwDBSetNumberFieldType*)
pDoc->GetSysFldType(RES_DBSETNUMBERFLD),
aData,
m_pProps->nUSHORT1);
((SwDBSetNumberField*)pFld)->SetSetNumber(m_pProps->nFormat);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_DBFLD, m_sTypeName, sal_False);
if(!pFldType)
throw uno::RuntimeException();
pFld = new SwDBField((SwDBFieldType*)pFldType, m_pProps->nFormat);
((SwDBField*)pFld)->InitContent(m_pProps->sPar1);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_SET_EXP:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_SETEXPFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
//#93192# detect the field type's sub type and set an appropriate number format
if(m_pProps->bFormatIsDefault &&
nsSwGetSetExpType::GSE_STRING == ((SwSetExpFieldType*)pFldType)->GetType())
m_pProps->nFormat = -1;
pFld = new SwSetExpField((SwSetExpFieldType*)pFldType,
m_pProps->sPar2,
m_pProps->nUSHORT2 != USHRT_MAX ? //#i79471# the field can have a number format or a number_ing_ format
m_pProps->nUSHORT2 : m_pProps->nFormat);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
if(m_pProps->bBool3)
nSubType |= nsSwExtendedSubType::SUB_CMD;
else
nSubType &= ~nsSwExtendedSubType::SUB_CMD;
pFld->SetSubType(nSubType);
((SwSetExpField*)pFld)->SetSeqNumber( m_pProps->nUSHORT1 );
((SwSetExpField*)pFld)->SetInputFlag(m_pProps->bBool1);
((SwSetExpField*)pFld)->SetPromptText(m_pProps->sPar3);
if(m_pProps->sPar4.Len())
((SwSetExpField*)pFld)->ChgExpStr(m_pProps->sPar4);
}
break;
case SW_SERVICE_FIELDTYPE_GET_EXP:
{
sal_uInt16 nSubType;
switch(m_pProps->nSubType)
{
case text::SetVariableType::STRING: nSubType = nsSwGetSetExpType::GSE_STRING; break;
case text::SetVariableType::VAR: nSubType = nsSwGetSetExpType::GSE_EXPR; break;
case text::SetVariableType::SEQUENCE: nSubType = nsSwGetSetExpType::GSE_SEQ; break;
case text::SetVariableType::FORMULA: nSubType = nsSwGetSetExpType::GSE_FORMULA; break;
default:
DBG_ERROR("wrong value");
nSubType = nsSwGetSetExpType::GSE_EXPR;
}
//make sure the SubType matches the field type
SwFieldType* pSetExpFld = pDoc->GetFldType(RES_SETEXPFLD, m_pProps->sPar1, sal_False);
if( pSetExpFld && nSubType != nsSwGetSetExpType::GSE_STRING &&
static_cast< SwSetExpFieldType* >(pSetExpFld)->GetType() == nsSwGetSetExpType::GSE_STRING
)
nSubType = nsSwGetSetExpType::GSE_STRING;
if(m_pProps->bBool2)
nSubType |= nsSwExtendedSubType::SUB_CMD;
else
nSubType &= ~nsSwExtendedSubType::SUB_CMD;
pFld = new SwGetExpField((SwGetExpFieldType*)
pDoc->GetSysFldType(RES_GETEXPFLD),
m_pProps->sPar1, nSubType, m_pProps->nFormat);
//TODO: SubType auswerten!
if(m_pProps->sPar4.Len())
((SwGetExpField*)pFld)->ChgExpStr(m_pProps->sPar4);
}
break;
case SW_SERVICE_FIELDTYPE_INPUT_USER:
case SW_SERVICE_FIELDTYPE_INPUT:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_INPUTFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
USHORT nInpSubType = sal::static_int_cast< USHORT >(SW_SERVICE_FIELDTYPE_INPUT_USER == m_nServiceId ? INP_USR : INP_TXT);
SwInputField * pTxtField =
new SwInputField((SwInputFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,
nInpSubType);
pTxtField->SetHelp(m_pProps->sPar3);
pTxtField->SetToolTip(m_pProps->sPar4);
pFld = pTxtField;
}
break;
case SW_SERVICE_FIELDTYPE_MACRO:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_MACROFLD);
String aName;
// support for Scripting Framework macros
if (m_pProps->sPar4.Len() != 0)
{
aName = m_pProps->sPar4;
}
else
{
SwMacroField::CreateMacroString(
aName, m_pProps->sPar1, m_pProps->sPar3 );
}
pFld = new SwMacroField((SwMacroFieldType*)pFldType, aName,
m_pProps->sPar2);
}
break;
case SW_SERVICE_FIELDTYPE_PAGE_COUNT :
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT :
case SW_SERVICE_FIELDTYPE_WORD_COUNT :
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT :
case SW_SERVICE_FIELDTYPE_TABLE_COUNT :
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT :
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT :
{
sal_uInt16 nSubType = DS_PAGE;
switch(m_nServiceId)
{
// case SW_SERVICE_FIELDTYPE_PAGE_COUNT : break;
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT : nSubType = DS_PARA;break;
case SW_SERVICE_FIELDTYPE_WORD_COUNT : nSubType = DS_WORD;break;
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT : nSubType = DS_CHAR;break;
case SW_SERVICE_FIELDTYPE_TABLE_COUNT : nSubType = DS_TBL;break;
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT : nSubType = DS_GRF;break;
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT : nSubType = DS_OLE;break;
}
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DOCSTATFLD);
pFld = new SwDocStatField((SwDocStatFieldType*)pFldType, nSubType, m_pProps->nUSHORT2);
}
break;
case SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY:
pFld = new SwAuthorityField( (SwAuthorityFieldType*)
pDoc->InsertFldType(SwAuthorityFieldType(pDoc)),
aEmptyStr );
if(m_pProps->aPropSeq.getLength())
{
uno::Any aVal; aVal <<= m_pProps->aPropSeq;
pFld->PutValue( aVal, FIELD_PROP_PROP_SEQ );
}
break;
case SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS:
// create field
pFld = new SwCombinedCharField( (SwCombinedCharFieldType*)
pDoc->GetSysFldType(RES_COMBINED_CHARS),
m_pProps->sPar1);
break;
case SW_SERVICE_FIELDTYPE_DROPDOWN:
pFld = new SwDropDownField
((SwDropDownFieldType *)
pDoc->GetSysFldType(RES_DROPDOWN));
((SwDropDownField *) pFld)->SetItems(m_pProps->aStrings);
((SwDropDownField *) pFld)->SetSelectedItem(m_pProps->sPar1);
((SwDropDownField *) pFld)->SetName(m_pProps->sPar2);
((SwDropDownField *) pFld)->SetHelp(m_pProps->sPar3);
((SwDropDownField *) pFld)->SetToolTip(m_pProps->sPar4);
break;
case SW_SERVICE_FIELDTYPE_TABLE_FORMULA :
{
// create field
USHORT nType = nsSwGetSetExpType::GSE_FORMULA;
if(m_pProps->bBool1)
{
nType |= nsSwExtendedSubType::SUB_CMD;
if(m_pProps->bFormatIsDefault)
m_pProps->nFormat = -1;
}
pFld = new SwTblField( (SwTblFieldType*)
pDoc->GetSysFldType(RES_TABLEFLD),
m_pProps->sPar2,
nType,
m_pProps->nFormat);
((SwTblField*)pFld)->ChgExpStr(m_pProps->sPar1);
}
break;
default: DBG_ERROR("was ist das fuer ein Typ?");
}
if(pFld)
{
pFld->SetAutomaticLanguage(!m_pProps->bBool4);
SwFmtFld aFmt( *pFld );
UnoActionContext aCont(pDoc);
SwTxtAttr* pTxtAttr = 0;
if(aPam.HasMark())
pDoc->DeleteAndJoin(aPam);
pDoc->Insert(aPam, aFmt, 0);
pTxtAttr = aPam.GetNode()->GetTxtNode()->GetTxtAttr(
aPam.GetPoint()->nContent.GetIndex()-1, RES_TXTATR_FIELD);
// was passiert mit dem Update der Felder ? (siehe fldmgr.cxx)
if(pTxtAttr)
{
const SwFmtFld& rFld = pTxtAttr->GetFld();
pFmtFld = &rFld;
}
}
delete pFld;
m_pDoc = pDoc;
m_pDoc->GetUnoCallBack()->Add(this);
m_bIsDescriptor = sal_False;
if(m_aFieldTypeClient.GetRegisteredIn())
const_cast<SwModify*>(m_aFieldTypeClient.GetRegisteredIn())->Remove(&m_aFieldTypeClient);
DELETEZ(m_pProps);
if(m_bCallUpdate)
update();
}
else
throw lang::IllegalArgumentException();
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::attach(const uno::Reference< text::XTextRange > & xTextRange)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
attachToRange( xTextRange );
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< text::XTextRange > SwXTextField::getAnchor(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Reference< text::XTextRange > aRef;
SwField* pField = (SwField*)GetField();
if(pField)
{
const SwTxtFld* pTxtFld = pFmtFld->GetTxtFld();
if(!pTxtFld)
throw uno::RuntimeException();
const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart() + 1, rTxtNode, *pTxtFld->GetStart());
aRef = SwXTextRange::CreateTextRangeFromPosition(m_pDoc,
*aPam.GetPoint(), aPam.GetMark());
}
return aRef;
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::dispose(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwField* pField = (SwField*)GetField();
if(pField)
{
UnoActionContext aContext(GetDoc());
const SwTxtFld* pTxtFld = pFmtFld->GetTxtFld();
SwTxtNode& rTxtNode = (SwTxtNode&)*pTxtFld->GetpTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart());
aPam.SetMark();
aPam.Move();
GetDoc()->DeleteAndJoin(aPam);
}
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException )
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
aLstnrCntnr.AddListener(aListener);
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException )
{
if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener))
throw uno::RuntimeException();
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySetInfo > SwXTextField::getPropertySetInfo(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
//kein static
uno::Reference< beans::XPropertySetInfo > aRef;
if(m_nServiceId != USHRT_MAX)
{
const SfxItemPropertyMap* pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId ));
uno::Reference< beans::XPropertySetInfo > xInfo = new SfxItemPropertySetInfo(pMap);
// extend PropertySetInfo!
const uno::Sequence<beans::Property> aPropSeq = xInfo->getProperties();
aRef = new SfxExtItemPropertySetInfo(
aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH_EXTENSIONS),
aPropSeq );
}
else
throw uno::RuntimeException();
return aRef;
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::setPropertyValue(const OUString& rPropertyName, const uno::Any& rValue)
throw( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,
lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwField* pField = (SwField*)GetField();
const SfxItemPropertyMap* _pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId));
const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
if (!pMap)
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & beans::PropertyAttribute::READONLY)
throw beans::PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if(pField)
{
// Sonderbehandlung Serienbrieffeld
sal_uInt16 nWhich = pField->Which();
if( RES_DBFLD == nWhich &&
(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL))||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME))||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME))))
{
// hier muss ein neuer Feldtyp angelegt werden und
// das Feld an den neuen Typ umgehaengt werden
DBG_WARNING("not implemented")
}
else
{
// -> #111840#
SwDoc * pDoc = GetDoc();
if (NULL != pDoc)
{
SwPosition * pPos = GetPosition();
ASSERT(pPos, "no position");
pDoc->PutValueToField( *pPos, rValue, pMap->nWID);
delete pPos;
}
// <- #111840#
}
pField->PutValue( rValue, pMap->nWID );
//#114571# changes of the expanded string have to be notified
//#to the SwTxtFld
if(RES_DBFLD == nWhich && pFmtFld->GetTxtFld())
{
pFmtFld->GetTxtFld()->Expand();
}
}
else if(m_pProps)
{
String* pStr = 0;
BOOL* pBool = 0;
switch(pMap->nWID)
{
case FIELD_PROP_PAR1:
pStr = &m_pProps->sPar1;
break;
case FIELD_PROP_PAR2:
pStr = &m_pProps->sPar2;
break;
case FIELD_PROP_PAR3:
pStr = &m_pProps->sPar3;
break;
case FIELD_PROP_PAR4:
pStr = &m_pProps->sPar4;
break;
case FIELD_PROP_FORMAT:
rValue >>= m_pProps->nFormat;
m_pProps->bFormatIsDefault = sal_False;
break;
case FIELD_PROP_SUBTYPE:
m_pProps->nSubType = SWUnoHelper::GetEnumAsInt32( rValue );
break;
case FIELD_PROP_BYTE1 :
rValue >>= m_pProps->nByte1;
break;
case FIELD_PROP_BOOL1 :
pBool = &m_pProps->bBool1;
break;
case FIELD_PROP_BOOL2 :
pBool = &m_pProps->bBool2;
break;
case FIELD_PROP_BOOL3 :
pBool = &m_pProps->bBool3;
break;
case FIELD_PROP_BOOL4:
pBool = &m_pProps->bBool4;
break;
case FIELD_PROP_DATE :
{
if(rValue.getValueType() != ::getCppuType(static_cast<const util::Date*>(0)))
throw lang::IllegalArgumentException();
util::Date aTemp = *(const util::Date*)rValue.getValue();
m_pProps->aDate = Date(aTemp.Day, aTemp.Month, aTemp.Year);
}
break;
case FIELD_PROP_USHORT1:
case FIELD_PROP_USHORT2:
{
sal_Int16 nVal = 0;
rValue >>= nVal;
if( FIELD_PROP_USHORT1 == pMap->nWID)
m_pProps->nUSHORT1 = nVal;
else
m_pProps->nUSHORT2 = nVal;
}
break;
case FIELD_PROP_SHORT1:
rValue >>= m_pProps->nSHORT1;
break;
case FIELD_PROP_DOUBLE:
if(rValue.getValueType() != ::getCppuType(static_cast<const double*>(0)))
throw lang::IllegalArgumentException();
m_pProps->fDouble = *(double*)rValue.getValue();
break;
case FIELD_PROP_DATE_TIME :
if(!m_pProps->pDateTime)
m_pProps->pDateTime = new util::DateTime;
rValue >>= (*m_pProps->pDateTime);
break;
case FIELD_PROP_PROP_SEQ:
rValue >>= m_pProps->aPropSeq;
break;
case FIELD_PROP_STRINGS:
rValue >>= m_pProps->aStrings;
break;
}
if( pStr )
::GetString( rValue, *pStr );
else if( pBool )
{
if( rValue.getValueType() == getCppuBooleanType() )
*pBool = *(sal_Bool*)rValue.getValue();
else
throw lang::IllegalArgumentException();
}
}
else
throw uno::RuntimeException();
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Any SwXTextField::getPropertyValue(const OUString& rPropertyName)
throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Any aRet;
const SwField* pField = GetField();
const SfxItemPropertyMap* _pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId));
const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
if(!pMap )
{
_pMap = aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH_EXTENSIONS);
pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
}
if (!pMap)
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
switch( pMap->nWID )
{
case FN_UNO_TEXT_WRAP:
aRet <<= text::WrapTextMode_NONE;
break;
case FN_UNO_ANCHOR_TYPE:
aRet <<= text::TextContentAnchorType_AS_CHARACTER;
break;
case FN_UNO_ANCHOR_TYPES:
{
uno::Sequence<text::TextContentAnchorType> aTypes(1);
text::TextContentAnchorType* pArray = aTypes.getArray();
pArray[0] = text::TextContentAnchorType_AS_CHARACTER;
aRet.setValue(&aTypes, ::getCppuType(static_cast<uno::Sequence<text::TextContentAnchorType>*>(0)));
}
break;
default:
if( pField )
{
if (FIELD_PROP_IS_FIELD_USED == pMap->nWID ||
FIELD_PROP_IS_FIELD_DISPLAYED == pMap->nWID)
{
sal_Bool bIsFieldUsed = sal_False;
sal_Bool bIsFieldDisplayed = sal_False;
// in order to have the information about fields
// correctly evaluated the document needs a layout
// (has to be already formatted)
SwDoc *pDoc = GetDoc();
ViewShell *pViewShell = 0;
SwEditShell *pEditShell = pDoc ? pDoc->GetEditShell( &pViewShell ) : 0;
if (pEditShell)
pEditShell->CalcLayout();
else if (pViewShell) // a page preview has no SwEditShell it should only have a view shell
pViewShell->CalcLayout();
else
throw uno::RuntimeException();
// get text node for the text field
const SwFmtFld *pFldFmt = GetFldFmt();
const SwTxtFld* pTxtFld = pFldFmt ? pFmtFld->GetTxtFld() : 0;
if(!pTxtFld)
throw uno::RuntimeException();
const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();
// skip fields that are currently not in the document
// e.g. fields in undo or redo array
if (rTxtNode.GetNodes().IsDocNodes())
{
sal_Bool bFrame = 0 != rTxtNode.FindLayoutRect().Width(); // oder so
sal_Bool bHidden = rTxtNode.IsHidden();
if ( !bHidden )
{
xub_StrLen nHiddenStart;
xub_StrLen nHiddenEnd;
SwPosition *pPos = pTxtFld->GetPosition();
if (!pPos)
throw uno::RuntimeException();
bHidden = SwScriptInfo::GetBoundsOfHiddenRange( rTxtNode,
pPos->nContent.GetIndex(),
nHiddenStart, nHiddenEnd );
}
// !bFrame && !bHidden: aller Wahrscheinlichkeit handelt es
// sich um ein Feld in einem unbenutzten Seitenstyle
//
// bHidden: Feld ist versteckt
// FME: Problem: Verstecktes Feld in unbenutzter Seitenvorlage =>
// bIsFieldUsed = true
// bIsFieldDisplayed = false
bIsFieldUsed = bFrame || bHidden;
bIsFieldDisplayed = bIsFieldUsed && !bHidden;
}
sal_Bool bRetVal = (FIELD_PROP_IS_FIELD_USED == pMap->nWID) ?
bIsFieldUsed : bIsFieldDisplayed;
aRet.setValue( &bRetVal, ::getCppuBooleanType() );
}
else
pField->QueryValue( aRet, pMap->nWID );
}
else if( m_pProps ) // currently just a descriptor...
{
switch(pMap->nWID)
{
case FIELD_PROP_PAR1:
aRet <<= OUString(m_pProps->sPar1);
break;
case FIELD_PROP_PAR2:
aRet <<= OUString(m_pProps->sPar2);
break;
case FIELD_PROP_PAR3:
aRet <<= OUString(m_pProps->sPar3);
break;
case FIELD_PROP_PAR4:
aRet <<= OUString(m_pProps->sPar4);
break;
case FIELD_PROP_FORMAT:
aRet <<= m_pProps->nFormat;
break;
case FIELD_PROP_SUBTYPE:
aRet <<= m_pProps->nSubType;
break;
case FIELD_PROP_BYTE1 :
aRet <<= m_pProps->nByte1;
break;
case FIELD_PROP_BOOL1 :
aRet.setValue(&m_pProps->bBool1, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL2 :
aRet.setValue(&m_pProps->bBool2, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL3 :
aRet.setValue(&m_pProps->bBool3, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL4 :
aRet.setValue(&m_pProps->bBool4, ::getCppuBooleanType());
break;
case FIELD_PROP_DATE :
aRet.setValue(&m_pProps->aDate, ::getCppuType(static_cast<const util::Date*>(0)));
break;
case FIELD_PROP_USHORT1:
aRet <<= (sal_Int16)m_pProps->nUSHORT1;
break;
case FIELD_PROP_USHORT2:
aRet <<= (sal_Int16)m_pProps->nUSHORT2;
break;
case FIELD_PROP_SHORT1:
aRet <<= m_pProps->nSHORT1;
break;
case FIELD_PROP_DOUBLE:
aRet <<= m_pProps->fDouble;
break;
case FIELD_PROP_DATE_TIME :
if(m_pProps->pDateTime)
aRet <<= (*m_pProps->pDateTime);
break;
case FIELD_PROP_PROP_SEQ:
aRet <<= m_pProps->aPropSeq;
break;
case FIELD_PROP_STRINGS:
aRet <<= m_pProps->aStrings;
break;
case FIELD_PROP_IS_FIELD_USED:
case FIELD_PROP_IS_FIELD_DISPLAYED:
aRet.setValue( sal_False, ::getCppuBooleanType() );
break;
}
}
else
throw uno::RuntimeException();
}
return aRet;
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addPropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removePropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removeVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/* -----------------------------23.03.01 13:15--------------------------------
---------------------------------------------------------------------------*/
void SwXTextField::update( ) throw (uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
const SwField* pFld = GetField();
if(pFld)
{
switch(pFld->Which())
{
case RES_DATETIMEFLD:
((SwDateTimeField*)pFld)->SetDateTime( ::DateTime() );
break;
case RES_EXTUSERFLD:
{
SwExtUserField* pExtUserFld = (SwExtUserField*)pFld;
pExtUserFld->SetExpansion( ((SwExtUserFieldType*)pFld->GetTyp())->Expand(
pExtUserFld->GetSubType(),
pExtUserFld->GetFormat() ) );
}
break;
case RES_AUTHORFLD:
{
SwAuthorField* pAuthorFld = (SwAuthorField*)pFld;
pAuthorFld->SetExpansion( ((SwAuthorFieldType*)pFld->GetTyp())->Expand(
pAuthorFld->GetFormat() ) );
}
break;
case RES_FILENAMEFLD:
{
SwFileNameField* pFileNameFld = (SwFileNameField*)pFld;
pFileNameFld->SetExpansion( ((SwFileNameFieldType*)pFld->GetTyp())->Expand(
pFileNameFld->GetFormat() ) );
}
break;
case RES_DOCINFOFLD:
{
SwDocInfoField* pDocInfFld = (SwDocInfoField*)pFld;
pDocInfFld->SetExpansion( ((SwDocInfoFieldType*)pFld->GetTyp())->Expand(
pDocInfFld->GetSubType(),
pDocInfFld->GetFormat(),
pDocInfFld->GetLanguage(),
pDocInfFld->GetName() ) );
}
break;
}
// --> FME 2004-10-06 #116480#
// Text formatting has to be triggered.
const_cast<SwFmtFld*>(pFmtFld)->Modify( 0, 0 );
// <--
}
else
m_bCallUpdate = sal_True;
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
OUString SwXTextField::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextField");
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
static OUString OldNameToNewName_Impl( const OUString &rOld )
{
static OUString aOldNamePart1( OUString::createFromAscii(".TextField.DocInfo.") );
static OUString aOldNamePart2( OUString::createFromAscii(".TextField.") );
static OUString aNewNamePart1( OUString::createFromAscii(".textfield.docinfo.") );
static OUString aNewNamePart2( OUString::createFromAscii(".textfield.") );
OUString sServiceNameCC( rOld );
sal_Int32 nIdx = sServiceNameCC.indexOf( aOldNamePart1 );
if (nIdx >= 0)
sServiceNameCC = sServiceNameCC.replaceAt( nIdx, aOldNamePart1.getLength(), aNewNamePart1 );
nIdx = sServiceNameCC.indexOf( aOldNamePart2 );
if (nIdx >= 0)
sServiceNameCC = sServiceNameCC.replaceAt( nIdx, aOldNamePart2.getLength(), aNewNamePart2 );
return sServiceNameCC;
}
sal_Bool SwXTextField::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
OUString sServiceName = SwXServiceProvider::GetProviderName(m_nServiceId);
// case-corected version of service-name (see #i67811)
// (need to supply both because of compatibility to older versions)
OUString sServiceNameCC( OldNameToNewName_Impl( sServiceName ) );
return sServiceName == rServiceName || sServiceNameCC == rServiceName ||
rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("com.sun.star.text.TextContent"));
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
uno::Sequence< OUString > SwXTextField::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
OUString sServiceName = SwXServiceProvider::GetProviderName(m_nServiceId);
// case-corected version of service-name (see #i67811)
// (need to supply both because of compatibility to older versions)
OUString sServiceNameCC( OldNameToNewName_Impl( sServiceName ) );
sal_Int32 nLen = sServiceName == sServiceNameCC ? 2 : 3;
uno::Sequence< OUString > aRet( nLen );
OUString* pArray = aRet.getArray();
*pArray++ = sServiceName;
if (nLen == 3)
*pArray++ = sServiceNameCC;
*pArray++ = C2U("com.sun.star.text.TextContent");
return aRet;
}
void SwXTextField::Invalidate()
{
if (GetRegisteredIn())
{
((SwModify*)GetRegisteredIn())->Remove(this);
aLstnrCntnr.Disposing();
pFmtFld = 0;
m_pDoc = 0;
}
}
/* -----------------14.12.98 12:00-------------------
*
* --------------------------------------------------*/
void SwXTextField::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
switch( pOld ? pOld->Which() : 0 )
{
case RES_REMOVE_UNO_OBJECT:
case RES_OBJECTDYING:
if( (void*)GetRegisteredIn() == ((SwPtrMsgPoolItem *)pOld)->pObject )
Invalidate();
break;
case RES_FMT_CHG:
// wurden wir an das neue umgehaengt und wird das alte geloscht?
if( ((SwFmtChg*)pNew)->pChangedFmt == GetRegisteredIn() &&
((SwFmtChg*)pOld)->pChangedFmt->IsFmtInDTOR() )
Invalidate();
break;
case RES_FIELD_DELETED:
if( (void*)pFmtFld == ((SwPtrMsgPoolItem *)pOld)->pObject )
Invalidate();
break;
}
}
/*-- 14.12.98 11:37:21---------------------------------------------------
-----------------------------------------------------------------------*/
const SwField* SwXTextField::GetField() const
{
if(GetRegisteredIn() && pFmtFld)
return pFmtFld->GetFld();
return 0;
}
// #111840#
SwPosition * SwXTextField::GetPosition()
{
SwPosition * pResult = NULL;
const SwFmtFld * pFmtFld2 = GetFldFmt();
if (pFmtFld2)
{
const SwTxtFld * pTxtFld = pFmtFld2->GetTxtFld();
if (pTxtFld)
pResult = pTxtFld->GetPosition();
}
return pResult;
}
/******************************************************************
*
******************************************************************/
/******************************************************************
* SwXTextFieldMasters
******************************************************************/
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
OUString SwXTextFieldMasters::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextFieldMasters");
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXTextFieldMasters::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.TextFieldMasters" ));
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldMasters::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFieldMasters");
return aRet;
}
/*-- 21.12.98 10:37:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldMasters::SwXTextFieldMasters(SwDoc* _pDoc) :
SwUnoCollection(_pDoc)
{
}
/*-- 21.12.98 10:37:32---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldMasters::~SwXTextFieldMasters()
{
}
/*-- 21.12.98 10:37:33---------------------------------------------------
Iteration ueber nicht-Standard Feldtypen
USER/SETEXP/DDE/DATABASE
Der Name ist demnach:
"com.sun.star.text.fieldmaster.User" + <Feltypname>
"com.sun.star.text.fieldmaster.DDE" + <Feltypname>
"com.sun.star.text.fieldmaster.SetExpression" + <Feltypname>
"com.sun.star.text.fieldmaster.DataBase" + <Feltypname>
Falls wir grosszuegig werden wollen, dann koennte man com.sun.star.text
auch optional weglassen
-----------------------------------------------------------------------*/
sal_uInt16 lcl_GetIdByName( String& rName, String& rTypeName )
{
if( rName.EqualsAscii( COM_TEXT_FLDMASTER, 0, RTL_CONSTASCII_LENGTH(COM_TEXT_FLDMASTER ))
|| rName.EqualsAscii( COM_TEXT_FLDMASTER_CC, 0, RTL_CONSTASCII_LENGTH(COM_TEXT_FLDMASTER_CC )))
rName.Erase(0, 30);
sal_uInt16 nResId = USHRT_MAX;
xub_StrLen nFound = 0;
rTypeName = rName.GetToken( 0, '.', nFound );
if(rTypeName.EqualsAscii("User"))
nResId = RES_USERFLD;
else if(rTypeName.EqualsAscii("DDE"))
nResId = RES_DDEFLD;
else if(rTypeName.EqualsAscii("SetExpression"))
{
nResId = RES_SETEXPFLD;
String sFldTypName( rName.GetToken( 1, '.' ));
String sUIName( SwStyleNameMapper::GetSpecialExtraUIName( sFldTypName ) );
if( sUIName != sFldTypName )
rName.SetToken( 1, '.', sUIName );
}
else if(rTypeName.EqualsAscii("DataBase"))
{
rName.Erase( 0, RTL_CONSTASCII_LENGTH( "DataBase." ));
USHORT nDotCount = rName.GetTokenCount('.');
if( 2 <= nDotCount )
{
// #i51815#
//rName.SearchAndReplace('.', DB_DELIM);
//rName.SetChar( rName.SearchBackward( '.' ), DB_DELIM );
rName.InsertAscii( "DataBase.", 0 );
nResId = RES_DBFLD;
}
}
else if( rTypeName.EqualsAscii("Bibliography"))
nResId = RES_AUTHORITY;
return nResId;
}
//-----------------------------------------------------------------------------
uno::Any SwXTextFieldMasters::getByName(const OUString& rName)
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
String sName(rName), sTypeName;
sal_uInt16 nResId = lcl_GetIdByName( sName, sTypeName );
if( USHRT_MAX == nResId )
throw container::NoSuchElementException();
sName.Erase(0, sTypeName.Len()+1);
SwFieldType* pType = GetDoc()->GetFldType(nResId, sName, sal_True);
if(!pType)
throw container::NoSuchElementException();
SwXFieldMaster* pMaster = (SwXFieldMaster*)
SwClientIter(*pType).First(TYPE(SwXFieldMaster));
if(!pMaster)
pMaster = new SwXFieldMaster(*pType, GetDoc());
uno::Reference< beans::XPropertySet > aRef = pMaster;
uno::Any aRet(&aRef, ::getCppuType( static_cast<const uno::Reference<beans::XPropertySet>* >(0)));
return aRet;
}
/*-- 06.03.2001 11:29:34,5-------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::getInstanceName(
const SwFieldType& rFldType, String& rName)
{
sal_Bool bRet = sal_True;
switch( rFldType.Which() )
{
case RES_USERFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "User."));
rName += rFldType.GetName();
break;
case RES_DDEFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "DDE."));
rName += rFldType.GetName();
break;
case RES_SETEXPFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "SetExpression."));
rName += String( SwStyleNameMapper::GetSpecialExtraProgName( rFldType.GetName() ) );
break;
case RES_DBFLD:
{
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "DataBase."));
String sDBName(rFldType.GetName());
sDBName.SearchAndReplaceAll(DB_DELIM, '.');
rName += sDBName;
}
break;
case RES_AUTHORITY:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "Bibliography"));
break;
default:
bRet = sal_False;
}
return bRet;
}
/*-- 21.12.98 10:37:33---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldMasters::getElementNames(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
const SwFldTypes* pFldTypes = GetDoc()->GetFldTypes();
sal_uInt16 nCount = pFldTypes->Count();
SvStrings aFldNames;
String* pString = new String();
sal_uInt16 i;
for( i = 0; i < nCount; i++)
{
SwFieldType& rFldType = *((*pFldTypes)[i]);
if (SwXTextFieldMasters::getInstanceName(rFldType, *pString))
{
aFldNames.Insert(pString, aFldNames.Count());
pString = new String();
}
}
delete pString;
uno::Sequence< OUString > aSeq(aFldNames.Count());
OUString* pArray = aSeq.getArray();
for(i = 0; i < aFldNames.Count();i++)
{
pArray[i] = *aFldNames.GetObject(i);
}
aFldNames.DeleteAndDestroy(0, aFldNames.Count());
return aSeq;
}
/*-- 21.12.98 10:37:33---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::hasByName(const OUString& rName) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
String sName(rName), sTypeName;
sal_uInt16 nResId = lcl_GetIdByName( sName, sTypeName );
sal_Bool bRet = sal_False;
if( USHRT_MAX != nResId )
{
sName.Erase(0, sTypeName.Len()+1);
bRet = USHRT_MAX != nResId && 0 != GetDoc()->GetFldType(nResId, sName, sal_True);
}
return bRet;
}
/*-- 21.12.98 10:37:34---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Type SwXTextFieldMasters::getElementType(void) throw( uno::RuntimeException )
{
return ::getCppuType(static_cast<const uno::Reference<beans::XPropertySet>*>(0));
}
/*-- 21.12.98 10:37:34---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::hasElements(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
return sal_True;
}
/******************************************************************
*
******************************************************************/
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
OUString SwXTextFieldTypes::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextFieldTypes");
}
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXTextFieldTypes::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.TextFields" ));
}
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldTypes::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFields");
return aRet;
}
/*-- 21.12.98 10:35:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldTypes::SwXTextFieldTypes(SwDoc* _pDoc) :
SwUnoCollection (_pDoc),
aRefreshCont ( static_cast< XEnumerationAccess * >(this) )
{
}
/*-- 21.12.98 10:35:16---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldTypes::~SwXTextFieldTypes()
{
}
/*-- 11.07.02 14:25:00---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextFieldTypes::Invalidate()
{
SwUnoCollection::Invalidate();
aRefreshCont.Disposing();
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< container::XEnumeration > SwXTextFieldTypes::createEnumeration(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
return new SwXFieldEnumeration(GetDoc());
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Type SwXTextFieldTypes::getElementType(void) throw( uno::RuntimeException )
{
return ::getCppuType(static_cast<const uno::Reference<text::XDependentTextField>*>(0));
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldTypes::hasElements(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
//es gibt sie immer
return sal_True;
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::refresh(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
UnoActionContext aContext(GetDoc());
SwDocStat aDocStat;
GetDoc()->UpdateDocStat(aDocStat);
GetDoc()->UpdateFlds(0, sal_False);
// call refresh listeners
aRefreshCont.Refreshed();
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::addRefreshListener(const uno::Reference< util::XRefreshListener > & l)
throw( uno::RuntimeException )
{
::vos::OGuard aGuard(Application::GetSolarMutex());
if ( !IsValid() )
throw uno::RuntimeException();
aRefreshCont.AddListener ( reinterpret_cast < const uno::Reference < lang::XEventListener > &> ( l ));
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::removeRefreshListener(const uno::Reference< util::XRefreshListener > & l)
throw( uno::RuntimeException )
{
::vos::OGuard aGuard(Application::GetSolarMutex());
if ( !IsValid() || !aRefreshCont.RemoveListener ( reinterpret_cast < const uno::Reference < lang::XEventListener > &> ( l ) ) )
throw uno::RuntimeException();
}
/******************************************************************
* SwXFieldEnumeration
******************************************************************/
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldEnumeration::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXFieldEnumeration");
}
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXFieldEnumeration::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.FieldEnumeration" ));
}
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXFieldEnumeration::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.FieldEnumeration");
return aRet;
}
/* -----------------21.12.98 14:57-------------------
*
* --------------------------------------------------*/
SwXFieldEnumeration::SwXFieldEnumeration(SwDoc* pDc) :
nNextIndex(0),
pDoc(pDc)
{
pDoc->GetPageDescFromPool(RES_POOLPAGE_STANDARD)->Add(this);
// build sequence
sal_Int32 nSize = 32;
aItems.realloc( nSize );
uno::Reference< text::XTextField > *pItems = aItems.getArray();
sal_Int32 nFillPos = 0;
//
const SwFldTypes* pFldTypes = pDoc->GetFldTypes();
sal_uInt16 nCount = pFldTypes->Count();
for(sal_uInt16 nType = 0; nType < nCount; ++nType)
{
const SwFieldType *pCurType = pFldTypes->GetObject(nType);
SwClientIter aIter( *(SwFieldType*)pCurType );
const SwFmtFld* pCurFldFmt = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while (pCurFldFmt)
{
const SwTxtFld *pTxtFld = pCurFldFmt->GetTxtFld();
// skip fields that are currently not in the document
// e.g. fields in undo or redo array
BOOL bSkip = !pTxtFld ||
!pTxtFld->GetpTxtNode()->GetNodes().IsDocNodes();
if (!bSkip)
pItems[ nFillPos++ ] = new SwXTextField(*pCurFldFmt, pDoc);
pCurFldFmt = (SwFmtFld*)aIter.Next();
// enlarge sequence if necessary
if (aItems.getLength() == nFillPos)
{
aItems.realloc( 2 * aItems.getLength() );
pItems = aItems.getArray();
}
}
}
// resize sequence to actual used size
aItems.realloc( nFillPos );
}
/*-- 21.12.98 14:57:23---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldEnumeration::~SwXFieldEnumeration()
{
}
/*-- 21.12.98 14:57:42---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXFieldEnumeration::hasMoreElements(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
return nNextIndex < aItems.getLength();
}
/*-- 21.12.98 14:57:42---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Any SwXFieldEnumeration::nextElement(void)
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if (!(nNextIndex < aItems.getLength()))
throw container::NoSuchElementException();
#if OSL_DEBUG_LEVEL > 1
uno::Reference< text::XTextField > *pItems = aItems.getArray();
(void)pItems;
#endif
uno::Reference< text::XTextField > &rxFld = aItems.getArray()[ nNextIndex++ ];
uno::Any aRet(&rxFld, ::getCppuType(static_cast<const uno::Reference<text::XTextField>*>(0)));
rxFld = 0; // free memory for item that is not longer used
return aRet;
}
/* -----------------21.12.98 15:08-------------------
*
* --------------------------------------------------*/
void SwXFieldEnumeration::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
ClientModify(this, pOld, pNew);
if(!GetRegisteredIn())
pDoc = 0;
}
String& GetString( const uno::Any& rAny, String& rStr )
{
OUString aStr;
rAny >>= aStr;
rStr = String( aStr );
return rStr;
}
INTEGRATION: CWS notes2 (1.95.82); FILE MERGED
2007/12/19 08:56:18 mba 1.95.82.11: #i6193#: access text in TextApiObject as string; make copy ctor of EditSource warning free
2007/12/15 16:15:33 mod 1.95.82.10: RESYNC: (1.99-1.101); FILE MERGED
2007/11/29 10:49:32 mba 1.95.82.9: #i84074#: store text of annotations with rich formatting
2007/09/28 16:32:24 mod 1.95.82.8: RESYNC: (1.98-1.99); FILE MERGED
2007/09/24 13:49:50 mod 1.95.82.7: notes are now collected inside SwTxtFld::SwTxtFld, IsInVisibleArea added to PostItMg, new colors for change tracking
2007/09/14 15:52:37 mod 1.95.82.6: cleanup, annotation have date and time now
2007/09/14 15:49:58 mod 1.95.82.5: remove unneccessary code from SwTextShell::ExecField
2007/09/01 14:01:44 mod 1.95.82.4: RESYNC: (1.96-1.98); FILE MERGED
2007/07/04 11:33:48 mod 1.95.82.3: RESYNC: (1.95-1.96); FILE MERGED
2007/05/31 07:54:58 mod 1.95.82.2: #i6193# Use of overlayobject for ankor
2007/05/24 04:34:44 mod 1.95.82.1: Initial checking, do not use
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unofield.cxx,v $
*
* $Revision: 1.102 $
*
* last change: $Author: rt $ $Date: 2008-02-19 13:49:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <swtypes.hxx>
#include <cmdid.h>
#ifndef _DOC_HXX //autogen
#include <doc.hxx>
#endif
#ifndef _HINTS_HXX //autogen
#include <hints.hxx>
#endif
#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#ifndef _NDTXT_HXX //autogen
#include <ndtxt.hxx>
#endif
#ifndef _UNOMAP_HXX
#include <unomap.hxx>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _UNOCOLL_HXX
#include <unocoll.hxx>
#endif
#ifndef _SVXLINKMGR_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _DOCSTAT_HXX //autogen
#include <docstat.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_TIME_HPP_
#include <com/sun/star/util/Time.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIMERANGE_HPP_
#include <com/sun/star/util/DateTimeRange.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSET_HPP_
#include <com/sun/star/beans/XFastPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATECHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyStateChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCONTAINER_HPP_
#include <com/sun/star/beans/XPropertyContainer.hpp>
#endif
//undef to prevent error (from sfx2/docfile.cxx)
#undef SEQUENCE
#ifndef _COM_SUN_STAR_TEXT_SETVARIABLETYPE_HPP_
#include <com/sun/star/text/SetVariableType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_WRAPTEXTMODE_HPP_
#include <com/sun/star/text/WrapTextMode.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP_
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_PAGENUMBERTYPE_HPP_
#include <com/sun/star/text/PageNumberType.hpp>
#endif
#ifndef _UNOFIELD_HXX
#include <unofield.hxx>
#endif
#ifndef _UNOCRSR_HXX
#include <unocrsr.hxx>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _FLDDAT_HXX
#include <flddat.hxx>
#endif
#ifndef _DBFLD_HXX
#include <dbfld.hxx>
#endif
#ifndef _USRFLD_HXX
#include <usrfld.hxx>
#endif
#ifndef _DOCUFLD_HXX
#include <docufld.hxx>
#endif
#ifndef _EXPFLD_HXX
#include <expfld.hxx>
#endif
#ifndef _CHPFLD_HXX
#include <chpfld.hxx>
#endif
#ifndef _FLDDROPDOWN_HXX
#include <flddropdown.hxx>
#endif
#ifndef _POOLFMT_HXX
#include <poolfmt.hxx>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif
#ifndef _PAGEDESC_HXX //autogen
#include <pagedesc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _REFFLD_HXX
#include <reffld.hxx>
#endif
#ifndef _DDEFLD_HXX
#include <ddefld.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
#ifndef _SWUNOHELPER_HXX
#include <swunohelper.hxx>
#endif
#ifndef SW_UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _SCRIPTINFO_HXX
#include <scriptinfo.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SVX_DATACCESSDESCRIPTOR_HXX_
#include <svx/dataaccessdescriptor.hxx>
#endif
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#include <textapi.hxx>
#include <svx/outliner.hxx>
#include <docsh.hxx>
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace nsSwDocInfoSubType;
#define COM_TEXT_FLDMASTER "com.sun.star.text.FieldMaster."
// case-corrected version of the first part for the service names (see #i67811)
#define COM_TEXT_FLDMASTER_CC "com.sun.star.text.fieldmaster."
static const sal_uInt16 aDocInfoSubTypeFromService[] =
{
DI_CHANGE | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_CHANGE_AUTHOR
DI_CHANGE | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_CHANGE_DATE_TIME
DI_EDIT | DI_SUB_TIME, //PROPERTY_MAP_FLDTYP_DOCINFO_EDIT_TIME
DI_COMMENT, //PROPERTY_MAP_FLDTYP_DOCINFO_DESCRIPTION
DI_CREATE | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_CREATE_AUTHOR
DI_CREATE | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_CREATE_DATE_TIME
DI_INFO1, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_0
DI_INFO2, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_1
DI_INFO3, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_2
DI_INFO4, //PROPERTY_MAP_FLDTYP_DOCINFO_INFO_3
DI_CUSTOM, //PROPERTY_MAP_FLDTYP_DOCINFO_CUSTOM
DI_PRINT | DI_SUB_AUTHOR, //PROPERTY_MAP_FLDTYP_DOCINFO_PRINT_AUTHOR
DI_PRINT | DI_SUB_DATE, //PROPERTY_MAP_FLDTYP_DOCINFO_PRINT_DATE_TIME
DI_KEYS, //PROPERTY_MAP_FLDTYP_DOCINFO_KEY_WORDS
DI_THEMA, //PROPERTY_MAP_FLDTYP_DOCINFO_SUBJECT
DI_TITEL, //PROPERTY_MAP_FLDTYP_DOCINFO_TITLE
DI_DOCNO //PROPERTY_MAP_FLDTYP_DOCINFO_REVISION
};
struct ServiceIdResId
{
USHORT nResId;
USHORT nServiceId;
};
static const ServiceIdResId aServiceToRes[] =
{
{RES_DATETIMEFLD, SW_SERVICE_FIELDTYPE_DATETIME },
{RES_USERFLD, SW_SERVICE_FIELDTYPE_USER },
{RES_SETEXPFLD, SW_SERVICE_FIELDTYPE_SET_EXP } ,
{RES_GETEXPFLD, SW_SERVICE_FIELDTYPE_GET_EXP } ,
{RES_FILENAMEFLD, SW_SERVICE_FIELDTYPE_FILE_NAME },
{RES_PAGENUMBERFLD, SW_SERVICE_FIELDTYPE_PAGE_NUM } ,
{RES_AUTHORFLD, SW_SERVICE_FIELDTYPE_AUTHOR } ,
{RES_CHAPTERFLD, SW_SERVICE_FIELDTYPE_CHAPTER },
{RES_GETREFFLD, SW_SERVICE_FIELDTYPE_GET_REFERENCE } ,
{RES_HIDDENTXTFLD, SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT },
{RES_POSTITFLD, SW_SERVICE_FIELDTYPE_ANNOTATION } ,
{RES_INPUTFLD, SW_SERVICE_FIELDTYPE_INPUT },
{RES_MACROFLD, SW_SERVICE_FIELDTYPE_MACRO },
{RES_DDEFLD, SW_SERVICE_FIELDTYPE_DDE },
{RES_HIDDENPARAFLD, SW_SERVICE_FIELDTYPE_HIDDEN_PARA } ,
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOC_INFO },
{RES_TEMPLNAMEFLD, SW_SERVICE_FIELDTYPE_TEMPLATE_NAME },
{RES_EXTUSERFLD, SW_SERVICE_FIELDTYPE_USER_EXT },
{RES_REFPAGESETFLD, SW_SERVICE_FIELDTYPE_REF_PAGE_SET } ,
{RES_REFPAGEGETFLD, SW_SERVICE_FIELDTYPE_REF_PAGE_GET } ,
{RES_JUMPEDITFLD, SW_SERVICE_FIELDTYPE_JUMP_EDIT },
{RES_SCRIPTFLD, SW_SERVICE_FIELDTYPE_SCRIPT } ,
{RES_DBNEXTSETFLD, SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET },
{RES_DBNUMSETFLD, SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET },
{RES_DBSETNUMBERFLD, SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM } ,
{RES_DBFLD, SW_SERVICE_FIELDTYPE_DATABASE } ,
{RES_DBNAMEFLD, SW_SERVICE_FIELDTYPE_DATABASE_NAME },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_PAGE_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_WORD_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_CHARACTER_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_TABLE_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT },
{RES_DOCSTATFLD, SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME},
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME},
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3 },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT },
{RES_DOCINFOFLD, SW_SERVICE_FIELDTYPE_DOCINFO_TITLE },
{RES_INPUTFLD, SW_SERVICE_FIELDTYPE_INPUT_USER },
{RES_HIDDENTXTFLD, SW_SERVICE_FIELDTYPE_HIDDEN_TEXT },
{RES_AUTHORITY, SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY },
{RES_COMBINED_CHARS, SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS },
{RES_DROPDOWN, SW_SERVICE_FIELDTYPE_DROPDOWN },
{RES_TABLEFLD, SW_SERVICE_FIELDTYPE_TABLE_FORMULA },
{USHRT_MAX, USHRT_MAX }
};
//-----------------------------------------------------------------
sal_uInt16 lcl_ServiceIdToResId(sal_uInt16 nServiceId)
{
const ServiceIdResId* pMap = aServiceToRes;
while( USHRT_MAX != pMap->nServiceId && nServiceId != pMap->nServiceId )
++pMap;
#ifdef DBG_UTIL
if( USHRT_MAX == pMap->nServiceId )
DBG_ERROR("service id not found");
#endif
return pMap->nResId;
}
//-----------------------------------------------------------------
sal_uInt16 lcl_GetServiceForField( const SwField& rFld )
{
sal_uInt16 nWhich = rFld.Which(), nSrvId = USHRT_MAX;
//special handling for some fields
switch( nWhich )
{
case RES_INPUTFLD:
if( INP_USR == (rFld.GetSubType() & 0x00ff) )
nSrvId = SW_SERVICE_FIELDTYPE_INPUT_USER;
break;
case RES_DOCINFOFLD:
{
USHORT nSubType = rFld.GetSubType();
switch( (nSubType & 0xff))
{
case DI_CHANGE:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME;
break;
case DI_CREATE:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME;
break;
case DI_PRINT:
nSrvId = ((nSubType&0x300) == DI_SUB_AUTHOR)
? SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR
: SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME;
break;
case DI_EDIT: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME;break;
case DI_COMMENT:nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION;break;
case DI_INFO1: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0; break;
case DI_INFO2: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1; break;
case DI_INFO3: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2; break;
case DI_INFO4: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3; break;
case DI_KEYS: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS;break;
case DI_THEMA: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT; break;
case DI_TITEL: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_TITLE; break;
case DI_DOCNO: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_REVISION; break;
case DI_CUSTOM: nSrvId = SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM; break;
}
}
break;
case RES_HIDDENTXTFLD:
nSrvId = TYP_CONDTXTFLD == rFld.GetSubType()
? SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT
: SW_SERVICE_FIELDTYPE_HIDDEN_TEXT;
break;
case RES_DOCSTATFLD:
{
switch( rFld.GetSubType() )
{
case DS_PAGE: nSrvId = SW_SERVICE_FIELDTYPE_PAGE_COUNT; break;
case DS_PARA: nSrvId = SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT; break;
case DS_WORD: nSrvId = SW_SERVICE_FIELDTYPE_WORD_COUNT ; break;
case DS_CHAR: nSrvId = SW_SERVICE_FIELDTYPE_CHARACTER_COUNT; break;
case DS_TBL: nSrvId = SW_SERVICE_FIELDTYPE_TABLE_COUNT ; break;
case DS_GRF: nSrvId = SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT; break;
case DS_OLE: nSrvId = SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT; break;
}
}
break;
}
if( USHRT_MAX == nSrvId )
{
for( const ServiceIdResId* pMap = aServiceToRes;
USHRT_MAX != pMap->nResId; ++pMap )
if( nWhich == pMap->nResId )
{
nSrvId = pMap->nServiceId;
break;
}
}
#ifdef DBG_UTIL
if( USHRT_MAX == nSrvId )
DBG_ERROR("resid not found");
#endif
return nSrvId;
}
sal_uInt16 lcl_GetPropMapIdForFieldType( USHORT nWhich )
{
sal_uInt16 nId;
switch( nWhich )
{
case RES_USERFLD: nId = PROPERTY_MAP_FLDMSTR_USER; break;
case RES_DBFLD: nId = PROPERTY_MAP_FLDMSTR_DATABASE; break;
case RES_SETEXPFLD: nId = PROPERTY_MAP_FLDMSTR_SET_EXP; break;
case RES_DDEFLD: nId = PROPERTY_MAP_FLDMSTR_DDE; break;
case RES_AUTHORITY: nId = PROPERTY_MAP_FLDMSTR_BIBLIOGRAPHY; break;
default: nId = PROPERTY_MAP_FLDMSTR_DUMMY0;
}
return nId;
}
BYTE GetFieldTypeMId( const OUString& rProperty, const SwFieldType& rTyp )
{
USHORT nId = lcl_GetPropMapIdForFieldType( rTyp.Which() );
const SfxItemPropertyMap* pMap = aSwMapProvider.GetPropertyMap( nId );
if( !pMap )
nId = USHRT_MAX;
else
{
nId = USHRT_MAX; // in case of property not found
for( ; pMap->pName; ++pMap )
if( rProperty.equalsAsciiL( pMap->pName, pMap->nNameLen ) )
{
nId = pMap->nWID;
break;
}
}
return (BYTE)nId;
}
USHORT lcl_GetPropertyMapOfService( USHORT nServiceId )
{
USHORT nRet;
switch ( nServiceId)
{
case SW_SERVICE_FIELDTYPE_DATETIME: nRet = PROPERTY_MAP_FLDTYP_DATETIME; break;
case SW_SERVICE_FIELDTYPE_USER: nRet = PROPERTY_MAP_FLDTYP_USER; break;
case SW_SERVICE_FIELDTYPE_SET_EXP: nRet = PROPERTY_MAP_FLDTYP_SET_EXP; break;
case SW_SERVICE_FIELDTYPE_GET_EXP: nRet = PROPERTY_MAP_FLDTYP_GET_EXP; break;
case SW_SERVICE_FIELDTYPE_FILE_NAME: nRet = PROPERTY_MAP_FLDTYP_FILE_NAME; break;
case SW_SERVICE_FIELDTYPE_PAGE_NUM: nRet = PROPERTY_MAP_FLDTYP_PAGE_NUM; break;
case SW_SERVICE_FIELDTYPE_AUTHOR: nRet = PROPERTY_MAP_FLDTYP_AUTHOR; break;
case SW_SERVICE_FIELDTYPE_CHAPTER: nRet = PROPERTY_MAP_FLDTYP_CHAPTER; break;
case SW_SERVICE_FIELDTYPE_GET_REFERENCE: nRet = PROPERTY_MAP_FLDTYP_GET_REFERENCE; break;
case SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT: nRet = PROPERTY_MAP_FLDTYP_CONDITIONED_TEXT; break;
case SW_SERVICE_FIELDTYPE_ANNOTATION: nRet = PROPERTY_MAP_FLDTYP_ANNOTATION; break;
case SW_SERVICE_FIELDTYPE_INPUT_USER:
case SW_SERVICE_FIELDTYPE_INPUT: nRet = PROPERTY_MAP_FLDTYP_INPUT; break;
case SW_SERVICE_FIELDTYPE_MACRO: nRet = PROPERTY_MAP_FLDTYP_MACRO; break;
case SW_SERVICE_FIELDTYPE_DDE: nRet = PROPERTY_MAP_FLDTYP_DDE; break;
case SW_SERVICE_FIELDTYPE_HIDDEN_PARA: nRet = PROPERTY_MAP_FLDTYP_HIDDEN_PARA; break;
case SW_SERVICE_FIELDTYPE_DOC_INFO: nRet = PROPERTY_MAP_FLDTYP_DOC_INFO; break;
case SW_SERVICE_FIELDTYPE_TEMPLATE_NAME: nRet = PROPERTY_MAP_FLDTYP_TEMPLATE_NAME; break;
case SW_SERVICE_FIELDTYPE_USER_EXT: nRet = PROPERTY_MAP_FLDTYP_USER_EXT; break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_SET: nRet = PROPERTY_MAP_FLDTYP_REF_PAGE_SET; break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_GET: nRet = PROPERTY_MAP_FLDTYP_REF_PAGE_GET; break;
case SW_SERVICE_FIELDTYPE_JUMP_EDIT: nRet = PROPERTY_MAP_FLDTYP_JUMP_EDIT; break;
case SW_SERVICE_FIELDTYPE_SCRIPT: nRet = PROPERTY_MAP_FLDTYP_SCRIPT; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NEXT_SET; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NUM_SET; break;
case SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM: nRet = PROPERTY_MAP_FLDTYP_DATABASE_SET_NUM; break;
case SW_SERVICE_FIELDTYPE_DATABASE: nRet = PROPERTY_MAP_FLDTYP_DATABASE; break;
case SW_SERVICE_FIELDTYPE_DATABASE_NAME: nRet = PROPERTY_MAP_FLDTYP_DATABASE_NAME; break;
case SW_SERVICE_FIELDTYPE_TABLE_FORMULA: nRet = PROPERTY_MAP_FLDTYP_TABLE_FORMULA; break;
case SW_SERVICE_FIELDTYPE_PAGE_COUNT:
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT:
case SW_SERVICE_FIELDTYPE_WORD_COUNT:
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT:
case SW_SERVICE_FIELDTYPE_TABLE_COUNT:
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT:
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT: nRet = PROPERTY_MAP_FLDTYP_DOCSTAT; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR:
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR:
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_AUTHOR; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME:
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME:
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_DATE_TIME; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_EDIT_TIME; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_CUSTOM; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2:
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3:
case SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS:
case SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT:
case SW_SERVICE_FIELDTYPE_DOCINFO_TITLE: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_MISC; break;
case SW_SERVICE_FIELDTYPE_DOCINFO_REVISION: nRet = PROPERTY_MAP_FLDTYP_DOCINFO_REVISION; break;
case SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY: nRet = PROPERTY_MAP_FLDTYP_BIBLIOGRAPHY; break;
case SW_SERVICE_FIELDTYPE_DUMMY_0:
case SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS: nRet = PROPERTY_MAP_FLDTYP_COMBINED_CHARACTERS; break;
case SW_SERVICE_FIELDTYPE_DROPDOWN: nRet = PROPERTY_MAP_FLDTYP_DROPDOWN; break;
case SW_SERVICE_FIELDTYPE_DUMMY_4:
case SW_SERVICE_FIELDTYPE_DUMMY_5:
case SW_SERVICE_FIELDTYPE_DUMMY_6:
case SW_SERVICE_FIELDTYPE_DUMMY_7:
case SW_SERVICE_FIELDTYPE_DUMMY_8: nRet = PROPERTY_MAP_FLDTYP_DUMMY_0; break;
case SW_SERVICE_FIELDMASTER_USER: nRet = PROPERTY_MAP_FLDMSTR_USER; break;
case SW_SERVICE_FIELDMASTER_DDE: nRet = PROPERTY_MAP_FLDMSTR_DDE; break;
case SW_SERVICE_FIELDMASTER_SET_EXP: nRet = PROPERTY_MAP_FLDMSTR_SET_EXP; break;
case SW_SERVICE_FIELDMASTER_DATABASE: nRet = PROPERTY_MAP_FLDMSTR_DATABASE; break;
case SW_SERVICE_FIELDMASTER_BIBLIOGRAPHY: nRet = PROPERTY_MAP_FLDMSTR_BIBLIOGRAPHY; break;
case SW_SERVICE_FIELDMASTER_DUMMY2:
case SW_SERVICE_FIELDMASTER_DUMMY3:
case SW_SERVICE_FIELDMASTER_DUMMY4:
case SW_SERVICE_FIELDMASTER_DUMMY5: nRet = PROPERTY_MAP_FLDMSTR_DUMMY0; break;
case SW_SERVICE_FIELDTYPE_HIDDEN_TEXT: nRet = PROPERTY_MAP_FLDTYP_HIDDEN_TEXT; break;
default:
DBG_ERROR( "wrong service id" );
nRet = USHRT_MAX;
}
return nRet;
}
/******************************************************************
* SwXFieldMaster
******************************************************************/
TYPEINIT1(SwXFieldMaster, SwClient);
/* -----------------------------13.03.00 12:15--------------------------------
---------------------------------------------------------------------------*/
const uno::Sequence< sal_Int8 > & SwXFieldMaster::getUnoTunnelId()
{
static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId();
return aSeq;
}
/* -----------------------------10.03.00 18:04--------------------------------
---------------------------------------------------------------------------*/
sal_Int64 SAL_CALL SwXFieldMaster::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw(uno::RuntimeException)
{
if( rId.getLength() == 16
&& 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return sal::static_int_cast< sal_Int64 >( reinterpret_cast< sal_IntPtr >(this) );
}
return 0;
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXFieldMaster");
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXFieldMaster::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
sal_Bool bRet = sal_False;
if(rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("com.sun.star.text.TextFieldMaster")))
bRet = sal_True;
else
{
const sal_Char* pEntry;
switch( nResTypeId )
{
case RES_USERFLD: pEntry = "User"; break;
case RES_DBFLD: pEntry = "Database"; break;
case RES_SETEXPFLD: pEntry = "SetExpression"; break;
case RES_DDEFLD: pEntry = "DDE"; break;
case RES_AUTHORITY: pEntry = "Bibliography"; break;
default: pEntry = 0;
}
if( pEntry )
{
ByteString aTmp( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.fieldmaster."));
aTmp.Append( pEntry );
bRet = rServiceName.equalsAsciiL(aTmp.GetBuffer(), aTmp.Len());
}
}
return bRet;
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXFieldMaster::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFieldMaster");
const sal_Char* pEntry1;
switch( nResTypeId )
{
case RES_USERFLD: pEntry1 = "User"; break;
case RES_DBFLD: pEntry1 = "Database"; break;
case RES_SETEXPFLD: pEntry1 = "SetExpression"; break;
case RES_DDEFLD: pEntry1 = "DDE"; break;
case RES_AUTHORITY: pEntry1 = "Bibliography"; break;
default: pEntry1 = 0;
}
if( pEntry1 )
{
String s;
s.AppendAscii( "com.sun.star.text.fieldmaster." ).AppendAscii( pEntry1 );
pArray[1] = s;
}
return aRet;
}
/*-- 14.12.98 11:08:33---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::SwXFieldMaster(SwDoc* pDoc, sal_uInt16 nResId) :
aLstnrCntnr( (XPropertySet*)this),
nResTypeId(nResId),
m_pDoc(pDoc),
m_bIsDescriptor(sal_True),
fParam1(0.),
nParam1(-1),
bParam1(FALSE),
nParam2(0)
{
pDoc->GetPageDescFromPool(RES_POOLPAGE_STANDARD)->Add(this);
}
/*-- 14.12.98 11:08:33---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::SwXFieldMaster(SwFieldType& rType, SwDoc* pDoc) :
SwClient(&rType),
aLstnrCntnr( (XPropertySet*)this),
nResTypeId(rType.Which()),
m_pDoc(pDoc),
m_bIsDescriptor(sal_False),
fParam1(0.),
nParam1(-1),
bParam1(FALSE)
{
}
/*-- 14.12.98 11:08:34---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldMaster::~SwXFieldMaster()
{
}
/*-- 14.12.98 11:08:35---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySetInfo > SwXFieldMaster::getPropertySetInfo(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Reference< beans::XPropertySetInfo > aRef = new SfxItemPropertySetInfo(
aSwMapProvider.GetPropertyMap(
lcl_GetPropMapIdForFieldType( nResTypeId ) ));
return aRef;
}
/*-- 14.12.98 11:08:35---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::setPropertyValue( const OUString& rPropertyName,
const uno::Any& rValue)
throw( beans::UnknownPropertyException, beans::PropertyVetoException,
lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pType = GetFldType(sal_True);
if(pType)
{
sal_Bool bSetValue = sal_True;
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_SUB_TYPE)))
{
const SvStringsDtor& rExtraArr = SwStyleNameMapper::GetExtraUINameArray();
String sTypeName = pType->GetName();
static sal_uInt16 nIds[] =
{
RES_POOLCOLL_LABEL_DRAWING - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_ABB - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_TABLE - RES_POOLCOLL_EXTRA_BEGIN,
RES_POOLCOLL_LABEL_FRAME- RES_POOLCOLL_EXTRA_BEGIN,
0
};
for(const sal_uInt16 * pIds = nIds; *pIds; ++pIds)
{
if(sTypeName == *rExtraArr[ *pIds ] )
{
bSetValue = sal_False;
break;
}
}
}
if( bSetValue )
{
// nothing special to be done here for the properties
// UNO_NAME_DATA_BASE_NAME and UNO_NAME_DATA_BASE_URL.
// We just call PutValue (empty string is allowed).
// Thus the last property set will be used as Data Source.
BYTE nMId = GetFieldTypeMId( rPropertyName, *pType );
if( UCHAR_MAX != nMId )
pType->PutValue( rValue, nMId );
else
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
}
else if(!pType && m_pDoc &&
( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NAME))) )
{
OUString uTmp;
rValue >>= uTmp;
String sTypeName(uTmp);
SwFieldType* pType2 = m_pDoc->GetFldType(nResTypeId, sTypeName, sal_False);
String sTable(SW_RES(STR_POOLCOLL_LABEL_TABLE));
String sDrawing(SW_RES(STR_POOLCOLL_LABEL_DRAWING));
String sFrame(SW_RES(STR_POOLCOLL_LABEL_FRAME));
String sIllustration(SW_RES(STR_POOLCOLL_LABEL_ABB));
if(pType2 ||
(RES_SETEXPFLD == nResTypeId &&
( sTypeName == sTable || sTypeName == sDrawing ||
sTypeName == sFrame || sTypeName == sIllustration )))
{
throw lang::IllegalArgumentException();
}
else
{
switch(nResTypeId)
{
case RES_USERFLD :
{
SwUserFieldType aType(m_pDoc, sTypeName);
pType2 = m_pDoc->InsertFldType(aType);
((SwUserFieldType*)pType2)->SetContent(sParam1);
((SwUserFieldType*)pType2)->SetValue(fParam1);
((SwUserFieldType*)pType2)->SetType(bParam1 ? nsSwGetSetExpType::GSE_EXPR : nsSwGetSetExpType::GSE_STRING);
}
break;
case RES_DDEFLD :
{
SwDDEFieldType aType(sTypeName, sParam1,
sal::static_int_cast< USHORT >(bParam1 ? sfx2::LINKUPDATE_ALWAYS : sfx2::LINKUPDATE_ONCALL));
pType2 = m_pDoc->InsertFldType(aType);
}
break;
case RES_SETEXPFLD :
{
SwSetExpFieldType aType(m_pDoc, sTypeName);
if(sParam1.Len())
aType.SetDelimiter( sParam1.GetChar(0));
if(nParam1 > -1 && nParam1 < MAXLEVEL)
aType.SetOutlineLvl(nParam1);
pType2 = m_pDoc->InsertFldType(aType);
}
break;
case RES_DBFLD :
{
::GetString( rValue, sParam3 );
pType = GetFldType();
}
break;
}
if(pType2)
{
pType2->Add(this);
m_bIsDescriptor = sal_False;
}
else
throw uno::RuntimeException();
}
DBG_ASSERT(pType2, "kein FieldType gefunden!" );
}
else
{
switch( nResTypeId )
{
case RES_USERFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CONTENT)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_VALUE )))
{
if(rValue.getValueType() != ::getCppuType(static_cast<const double*>(0)))
throw lang::IllegalArgumentException();
fParam1 = *(double*)rValue.getValue();
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_EXPRESSION )))
{
if(rValue.getValueType() != ::getBooleanCppuType())
throw lang::IllegalArgumentException();
bParam1 = *(sal_Bool*)rValue.getValue();
}
break;
case RES_DBFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME)))
::GetString( rValue, sParam2 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME)))
::GetString( rValue, sParam3 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)))
rValue >>= nParam2;
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
::GetString( rValue, sParam5 );
if((sParam1.Len() || sParam5.Len())
&& sParam2.Len() && sParam3.Len())
GetFldType();
break;
case RES_SETEXPFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NUMBERING_SEPARATOR)))
::GetString( rValue, sParam1 );
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CHAPTER_NUMBERING_LEVEL)))
rValue >>= nParam1;
break;
case RES_DDEFLD:
{
USHORT nPart = rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_TYPE)) ? 0 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_FILE)) ? 1 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_ELEMENT)) ? 2 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_AUTOMATIC_UPDATE)) ? 3 : USHRT_MAX;
if(nPart < 3 )
{
String sTmp;
if(!sParam1.Len())
(sParam1 = sfx2::cTokenSeperator)
+= sfx2::cTokenSeperator;
sParam1.SetToken( nPart, sfx2::cTokenSeperator,
::GetString( rValue, sTmp ));
}
else if(3 == nPart)
bParam1 = *(sal_Bool*)rValue.getValue();
}
break;
default:
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
}
}
/* -----------------------------30.03.01 14:40--------------------------------
---------------------------------------------------------------------------*/
SwFieldType* SwXFieldMaster::GetFldType(sal_Bool bDontCreate) const
{
if(!bDontCreate && RES_DBFLD == nResTypeId && m_bIsDescriptor && m_pDoc)
{
SwDBData aData;
// set DataSource
svx::ODataAccessDescriptor aAcc;
if( sParam1.Len() > 0 )
aAcc[ svx::daDataSource ] <<= OUString(sParam1); // DataBaseName
else if( sParam5.Len() > 0 )
aAcc[ svx::daDatabaseLocation] <<= OUString(sParam5); // DataBaseURL
aData.sDataSource = aAcc.getDataSource();
aData.sCommand = sParam2;
aData.nCommandType = nParam2;
SwDBFieldType aType(m_pDoc, sParam3, aData);
SwFieldType* pType = m_pDoc->InsertFldType(aType);
SwXFieldMaster* pThis = ((SwXFieldMaster*)this);
pType->Add(pThis);
pThis->m_bIsDescriptor = sal_False;
}
if(m_bIsDescriptor)
return 0;
else
return (SwFieldType*)GetRegisteredIn();
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
typedef SwFmtFld* SwFmtFldPtr;
SV_DECL_PTRARR(SwDependentFields, SwFmtFldPtr, 5, 5)
SV_IMPL_PTRARR(SwDependentFields, SwFmtFldPtr)
uno::Any SwXFieldMaster::getPropertyValue(const OUString& rPropertyName)
throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Any aRet;
SwFieldType* pType = GetFldType(sal_True);
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_INSTANCE_NAME)) )
{
String sName;
if(pType)
SwXTextFieldMasters::getInstanceName(*pType, sName);
aRet <<= OUString(sName);
}
else if(pType)
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NAME) ))
{
aRet <<= SwXFieldMaster::GetProgrammaticName(*pType, *GetDoc());
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DEPENDENT_TEXT_FIELDS)) )
{
//fill all text fields into a sequence
SwClientIter aIter( *pType );
SwDependentFields aFldArr;
SwFmtFldPtr pFld = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while(pFld)
{
if(pFld->IsFldInDoc())
aFldArr.Insert(pFld, aFldArr.Count());
pFld = (SwFmtFld*)aIter.Next();
}
uno::Sequence<uno::Reference <text::XDependentTextField> > aRetSeq(aFldArr.Count());
uno::Reference<text::XDependentTextField>* pRetSeq = aRetSeq.getArray();
SwXTextField* pInsert = 0;
for(USHORT i = 0; i < aFldArr.Count(); i++)
{
pFld = aFldArr.GetObject(i);
SwXTextField* pTemp = (SwXTextField*)aIter.First(TYPE(SwXTextField));
while(pTemp)
{
if(pTemp->GetFldFmt() == pFld)
{
pInsert = pTemp;
break;
}
pTemp = (SwXTextField*)aIter.Next();
}
if(!pInsert)
pInsert = new SwXTextField( *pFld, GetDoc());
pRetSeq[i] = uno::Reference<text::XDependentTextField>(pInsert);
pInsert = 0;
}
aRet <<= aRetSeq;
}
else if(pType)
{
//TODO: Properties fuer die uebrigen Feldtypen einbauen
BYTE nMId = GetFieldTypeMId( rPropertyName, *pType );
if( UCHAR_MAX != nMId )
{
pType->QueryValue( aRet, nMId );
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
{
OUString aDataSource;
aRet >>= aDataSource;
aRet <<= OUString();
OUString *pStr = 0; // only one of this properties will return
// a non-empty string.
INetURLObject aObj;
aObj.SetURL( aDataSource );
BOOL bIsURL = aObj.GetProtocol() != INET_PROT_NOT_VALID;
if (bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
pStr = &aDataSource; // DataBaseURL
else if (!bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
pStr = &aDataSource; // DataBaseName
if (pStr)
aRet <<= *pStr;
}
}
else
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
else
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)) )
aRet <<= nParam2;
}
}
else
{
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COMMAND_TYPE)) )
aRet <<= nParam2;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DEPENDENT_TEXT_FIELDS)) )
{
uno::Sequence<uno::Reference <text::XDependentTextField> > aRetSeq(0);
aRet <<= aRetSeq;
}
else
{
const String* pStr = 0;
String sStr;
switch ( nResTypeId )
{
case RES_USERFLD:
if( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CONTENT)) )
pStr = &sParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_VALUE )))
aRet <<= fParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_EXPRESSION )))
aRet.setValue(&bParam1, ::getBooleanCppuType());
break;
case RES_DBFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
{
pStr = 0; // only one of this properties will return
// a non-empty string.
INetURLObject aObj;
aObj.SetURL( sParam5 ); // SetSmartURL
BOOL bIsURL = aObj.GetProtocol() != INET_PROT_NOT_VALID;
if (bIsURL && rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL)))
pStr = &sParam5; // DataBaseURL
else if ( rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)))
pStr = &sParam1; // DataBaseName
}
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME)))
pStr = &sParam2;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME)))
pStr = &sParam3;
break;
case RES_SETEXPFLD:
if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_NUMBERING_SEPARATOR)))
pStr = &sParam1;
else if(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_CHAPTER_NUMBERING_LEVEL)))
aRet <<= nParam1;
break;
case RES_DDEFLD:
{
USHORT nPart = rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_TYPE)) ? 0 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_FILE)) ? 1 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DDE_COMMAND_ELEMENT)) ? 2 :
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_IS_AUTOMATIC_UPDATE)) ? 3 : USHRT_MAX;
if(nPart < 3 )
pStr = &(sStr = sParam1.GetToken(nPart, sfx2::cTokenSeperator));
else if(3 == nPart)
aRet.setValue(&bParam1, ::getBooleanCppuType());
}
break;
default:
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
}
if( pStr )
aRet <<= OUString( *pStr );
}
}
return aRet;
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addPropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:36---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removePropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:37---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:08:37---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removeVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 25.02.99 11:01:57---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::dispose(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pFldType = GetFldType(sal_True);
if(pFldType)
{
sal_uInt16 nTypeIdx = USHRT_MAX;
const SwFldTypes* pTypes = GetDoc()->GetFldTypes();
for( sal_uInt16 i = 0; i < pTypes->Count(); i++ )
{
if((*pTypes)[i] == pFldType)
nTypeIdx = i;
}
// zuerst alle Felder loeschen
SwClientIter aIter( *pFldType );
SwFmtFld* pFld = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while(pFld)
{
// Feld im Undo?
SwTxtFld *pTxtFld = pFld->GetTxtFld();
if(pTxtFld && pTxtFld->GetTxtNode().GetNodes().IsDocNodes() )
{
SwTxtNode& rTxtNode = (SwTxtNode&)*pTxtFld->GetpTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart());
aPam.SetMark();
aPam.Move();
GetDoc()->DeleteAndJoin(aPam);
}
pFld = (SwFmtFld*)aIter.Next();
}
// dann den FieldType loeschen
GetDoc()->RemoveFldType(nTypeIdx);
}
else
throw uno::RuntimeException();
}
/*-- 25.02.99 11:02:00---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::addEventListener(const uno::Reference< lang::XEventListener > & aListener)
throw( uno::RuntimeException )
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
aLstnrCntnr.AddListener(aListener);
}
/*-- 25.02.99 11:02:02---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::removeEventListener(const uno::Reference< lang::XEventListener > & aListener)
throw( uno::RuntimeException )
{
if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener))
throw uno::RuntimeException();
}
/*-- 14.12.98 11:08:38---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXFieldMaster::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
ClientModify(this, pOld, pNew);
if(!GetRegisteredIn())
{
aLstnrCntnr.Disposing();
m_pDoc = 0;
}
}
/* -----------------------------06.11.00 09:44--------------------------------
const Programmatic2UIName_Impl* lcl_GetFieldNameTable()
{
static BOOL bInitialized = FALSE;
static Programmatic2UIName_Impl aFieldNames[5];
if(!bInitialized)
{
bInitialized = TRUE;
int nName = 0;
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_ABB ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_ABB));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_TABLE ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_TABLE));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_FRAME));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_FRAME));
aFieldNames[nName].sUIName = String (SW_RES(STR_POOLCOLL_LABEL_DRAWING ));
aFieldNames[nName++].sProgrammaticName = String (SW_RES(STR_POCO_PRGM_LABEL_DRAWING));
}
return &aFieldNames[0];
}
---------------------------------------------------------------------------*/
/* -----------------------------06.11.00 10:26--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::GetProgrammaticName(const SwFieldType& rType, SwDoc& rDoc)
{
OUString sRet(rType.GetName());
if(RES_SETEXPFLD == rType.Which())
{
const SwFldTypes* pTypes = rDoc.GetFldTypes();
for( sal_uInt16 i = 0; i <= INIT_FLDTYPES; i++ )
{
if((*pTypes)[i] == &rType)
{
sRet = SwStyleNameMapper::GetProgName ( sRet, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL );
break;
}
}
}
return sRet;
}
/* -----------------------------06.11.00 14:12--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldMaster::LocalizeFormula(
const SwSetExpField& rFld,
const OUString& rFormula,
sal_Bool bQuery)
{
const OUString sTypeName(rFld.GetTyp()->GetName());
OUString sProgName = SwStyleNameMapper::GetProgName(sTypeName, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL );
if(sProgName != sTypeName)
{
OUString sSource = bQuery ? sTypeName : sProgName;
OUString sDest = bQuery ? sProgName : sTypeName;
if(!rFormula.compareTo(sSource, sSource.getLength()))
{
OUString sTmpFormula = sDest;
sTmpFormula += rFormula.copy(sSource.getLength());
return sTmpFormula;
}
}
return rFormula;
}
/******************************************************************
*
******************************************************************/
struct SwFieldProperties_Impl
{
String sPar1;
String sPar2;
String sPar3;
String sPar4;
String sPar5;
String sPar6;
Date aDate;
double fDouble;
uno::Sequence<beans::PropertyValue> aPropSeq;
uno::Sequence<OUString> aStrings;
util::DateTime* pDateTime;
sal_Int32 nSubType;
sal_Int32 nFormat;
sal_uInt16 nUSHORT1;
sal_uInt16 nUSHORT2;
sal_Int16 nSHORT1;
sal_Int8 nByte1;
sal_Bool bFormatIsDefault;
sal_Bool bBool1;
sal_Bool bBool2;
sal_Bool bBool3;
sal_Bool bBool4;
SwFieldProperties_Impl():
fDouble(0.),
pDateTime(0),
nSubType(0),
nFormat(0),
nUSHORT1(0),
nUSHORT2(0),
nSHORT1(0),
nByte1(0),
bFormatIsDefault(sal_True),
bBool1(sal_False),
bBool2(sal_False),
bBool3(sal_False),
bBool4(sal_True) //Automatic language
{}
~SwFieldProperties_Impl()
{delete pDateTime;}
};
TYPEINIT1(SwXTextField, SwClient);
/* -----------------------------13.03.00 12:15--------------------------------
---------------------------------------------------------------------------*/
const uno::Sequence< sal_Int8 > & SwXTextField::getUnoTunnelId()
{
static uno::Sequence< sal_Int8 > aSeq = ::CreateUnoTunnelId();
return aSeq;
}
/* -----------------------------10.03.00 18:04--------------------------------
---------------------------------------------------------------------------*/
sal_Int64 SAL_CALL SwXTextField::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw(uno::RuntimeException)
{
if( rId.getLength() == 16
&& 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return sal::static_int_cast< sal_Int64 >( reinterpret_cast< sal_IntPtr >(this) );
}
return 0;
}
/*-- 14.12.98 11:37:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::SwXTextField(sal_uInt16 nServiceId, SwDoc* pDoc) :
aLstnrCntnr( (XTextContent*)this),
pFmtFld(0),
m_pDoc(pDoc),
m_pTextObject(0),
m_bIsDescriptor(nServiceId != USHRT_MAX),
m_bCallUpdate(sal_False),
m_nServiceId(nServiceId),
m_pProps(new SwFieldProperties_Impl)
{
//Set visible as default!
if(SW_SERVICE_FIELDTYPE_SET_EXP == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE == nServiceId ||
SW_SERVICE_FIELDTYPE_DATABASE_NAME == nServiceId )
m_pProps->bBool2 = sal_True;
else if(SW_SERVICE_FIELDTYPE_TABLE_FORMULA == nServiceId)
m_pProps->bBool1 = sal_True;
if(SW_SERVICE_FIELDTYPE_SET_EXP == nServiceId)
m_pProps->nUSHORT2 = USHRT_MAX;
}
/*-- 14.12.98 11:37:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::SwXTextField(const SwFmtFld& rFmt, SwDoc* pDc) :
aLstnrCntnr( (XTextContent*)this),
pFmtFld(&rFmt),
m_pDoc(pDc),
m_pTextObject(0),
m_bIsDescriptor(sal_False),
m_bCallUpdate(sal_False),
m_nServiceId( lcl_GetServiceForField( *pFmtFld->GetFld() ) ),
m_pProps(0)
{
pDc->GetUnoCallBack()->Add(this);
}
/*-- 14.12.98 11:37:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextField::~SwXTextField()
{
if ( m_pTextObject )
{
m_pTextObject->DisposeEditSource();
m_pTextObject->release();
}
delete m_pProps;
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::attachTextFieldMaster(const uno::Reference< beans::XPropertySet > & xFieldMaster)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!m_bIsDescriptor)
throw uno::RuntimeException();
uno::Reference< lang::XUnoTunnel > xMasterTunnel(xFieldMaster, uno::UNO_QUERY);
if (!xMasterTunnel.is())
throw lang::IllegalArgumentException();
SwXFieldMaster* pMaster = reinterpret_cast< SwXFieldMaster * >(
sal::static_int_cast< sal_IntPtr >( xMasterTunnel->getSomething( SwXFieldMaster::getUnoTunnelId()) ));
SwFieldType* pFieldType = pMaster ? pMaster->GetFldType() : 0;
if(pFieldType && pFieldType->Which() == lcl_ServiceIdToResId(m_nServiceId))
{
m_sTypeName = pFieldType->GetName();
pFieldType->Add( &m_aFieldTypeClient );
}
else
throw lang::IllegalArgumentException();
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySet > SwXTextField::getTextFieldMaster(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwFieldType* pType = 0;
if( m_bIsDescriptor && m_aFieldTypeClient.GetRegisteredIn() )
{
pType = (SwFieldType*)m_aFieldTypeClient.GetRegisteredIn();
}
else
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
pType = pFmtFld->GetFld()->GetTyp();
}
SwXFieldMaster* pMaster = (SwXFieldMaster*)
SwClientIter(*pType).First(TYPE(SwXFieldMaster));
if(!pMaster)
pMaster = new SwXFieldMaster(*pType, GetDoc());
return pMaster;
}
/*-- 14.12.98 11:37:16---------------------------------------------------
-----------------------------------------------------------------------*/
OUString SwXTextField::getPresentation(sal_Bool bShowCommand) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
OUString sRet;
const SwField* pField = GetField();
if(pField)
sRet = pField->GetCntnt(bShowCommand);
else
throw uno::RuntimeException();
return sRet;
}
/* -----------------18.02.99 13:39-------------------
*
* --------------------------------------------------*/
void SwXTextField::attachToRange(
const uno::Reference< text::XTextRange > & xTextRange)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!m_bIsDescriptor)
throw uno::RuntimeException();
uno::Reference<lang::XUnoTunnel> xRangeTunnel( xTextRange, uno::UNO_QUERY);
SwXTextRange* pRange = 0;
OTextCursorHelper* pCursor = 0;
if(xRangeTunnel.is())
{
pRange = reinterpret_cast< SwXTextRange * >(
sal::static_int_cast< sal_IntPtr >( xRangeTunnel->getSomething( SwXTextRange::getUnoTunnelId()) ));
pCursor = reinterpret_cast< OTextCursorHelper * >(
sal::static_int_cast< sal_IntPtr >( xRangeTunnel->getSomething( OTextCursorHelper::getUnoTunnelId()) ));
}
SwDoc* pDoc = pRange ? (SwDoc*)pRange->GetDoc() : pCursor ? (SwDoc*)pCursor->GetDoc() : 0;
//wurde ein FieldMaster attached, dann ist das Dokument schon festgelegt!
if(pDoc && (!m_pDoc || m_pDoc == pDoc))
{
SwUnoInternalPaM aPam(*pDoc);
//das muss jetzt sal_True liefern
SwXTextRange::XTextRangeToSwPaM(aPam, xTextRange);
SwField* pFld = 0;
switch(m_nServiceId)
{
case SW_SERVICE_FIELDTYPE_ANNOTATION:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_POSTITFLD);
DateTime aDateTime;
aDateTime.SetYear(m_pProps->pDateTime->Year);
aDateTime.SetMonth(m_pProps->pDateTime->Month);
aDateTime.SetDay(m_pProps->pDateTime->Day);
aDateTime.SetHour(m_pProps->pDateTime->Hours);
aDateTime.SetMin(m_pProps->pDateTime->Minutes);
aDateTime.SetSec(m_pProps->pDateTime->Seconds);
pFld = new SwPostItField((SwPostItFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,aDateTime);
if ( m_pTextObject )
{
((SwPostItField*)pFld)->SetTextObject( m_pTextObject->CreateText() );
((SwPostItField*)pFld)->SetPar2(m_pTextObject->GetText());
}
}
break;
case SW_SERVICE_FIELDTYPE_SCRIPT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_SCRIPTFLD);
pFld = new SwScriptField((SwScriptFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,
m_pProps->bBool1);
}
break;
case SW_SERVICE_FIELDTYPE_DATETIME:
{
sal_uInt16 nSub = 0;
if(m_pProps->bBool1)
nSub |= FIXEDFLD;
if(m_pProps->bBool2)
nSub |= DATEFLD;
else
nSub |= TIMEFLD;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DATETIMEFLD);
pFld = new SwDateTimeField((SwDateTimeFieldType*)pFldType,
nSub, m_pProps->nFormat);
if(m_pProps->fDouble > 0.)
((SwDateTimeField*)pFld)->SetValue( m_pProps->fDouble );
if(m_pProps->pDateTime)
{
uno::Any aVal; aVal <<= *m_pProps->pDateTime;
pFld->PutValue( aVal, FIELD_PROP_DATE_TIME );
}
((SwDateTimeField*)pFld)->SetOffset(m_pProps->nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_FILE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_FILENAMEFLD);
sal_Int32 nFormat = m_pProps->nFormat;
if(m_pProps->bBool2)
nFormat |= FF_FIXED;
pFld = new SwFileNameField((SwFileNameFieldType*)pFldType, nFormat);
if(m_pProps->sPar3.Len())
((SwFileNameField*)pFld)->SetExpansion(m_pProps->sPar3);
uno::Any aFormat(&m_pProps->nFormat, ::getCppuType(&m_pProps->nFormat));
pFld->PutValue( aFormat, FIELD_PROP_FORMAT );
}
break;
case SW_SERVICE_FIELDTYPE_TEMPLATE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_TEMPLNAMEFLD);
pFld = new SwTemplNameField((SwTemplNameFieldType*)pFldType,
m_pProps->nFormat);
uno::Any aFormat(&m_pProps->nFormat, ::getCppuType(&m_pProps->nFormat));
pFld->PutValue(aFormat, FIELD_PROP_FORMAT);
}
break;
case SW_SERVICE_FIELDTYPE_CHAPTER:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_CHAPTERFLD);
pFld = new SwChapterField((SwChapterFieldType*)pFldType, m_pProps->nUSHORT1);
((SwChapterField*)pFld)->SetLevel(m_pProps->nByte1);
uno::Any aVal; aVal <<= (sal_Int16)m_pProps->nUSHORT1;
pFld->PutValue(aVal, FIELD_PROP_USHORT1 );
}
break;
case SW_SERVICE_FIELDTYPE_AUTHOR:
{
long nFormat = m_pProps->bBool1 ? AF_NAME : AF_SHORTCUT;
if(m_pProps->bBool2)
nFormat |= AF_FIXED;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_AUTHORFLD);
pFld = new SwAuthorField((SwAuthorFieldType*)pFldType, nFormat);
((SwAuthorField*)pFld)->SetExpansion(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_CONDITIONED_TEXT:
case SW_SERVICE_FIELDTYPE_HIDDEN_TEXT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_HIDDENTXTFLD);
pFld = new SwHiddenTxtField(((SwHiddenTxtFieldType*)pFldType),
m_pProps->sPar1,
m_pProps->sPar2, m_pProps->sPar3,
static_cast< USHORT >(SW_SERVICE_FIELDTYPE_HIDDEN_TEXT == m_nServiceId ?
TYP_HIDDENTXTFLD : TYP_CONDTXTFLD));
((SwHiddenTxtField*)pFld)->SetValue(m_pProps->bBool1);
uno::Any aVal; aVal <<= (OUString)m_pProps->sPar4;
pFld->PutValue(aVal, FIELD_PROP_PAR4 );
}
break;
case SW_SERVICE_FIELDTYPE_HIDDEN_PARA:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_HIDDENPARAFLD);
pFld = new SwHiddenParaField((SwHiddenParaFieldType*)pFldType,
m_pProps->sPar1);
((SwHiddenParaField*)pFld)->SetHidden(m_pProps->bBool1);
}
break;
case SW_SERVICE_FIELDTYPE_GET_REFERENCE:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_GETREFFLD);
pFld = new SwGetRefField((SwGetRefFieldType*)pFldType,
m_pProps->sPar1,
0,
0,
0);
if(m_pProps->sPar3.Len())
((SwGetRefField*)pFld)->SetExpand(m_pProps->sPar3);
uno::Any aVal; aVal <<=(sal_Int16)m_pProps->nUSHORT1;
pFld->PutValue(aVal, FIELD_PROP_USHORT1 );
aVal <<=(sal_Int16)m_pProps->nUSHORT2;
pFld->PutValue(aVal, FIELD_PROP_USHORT2 );
aVal <<=(sal_Int16)m_pProps->nSHORT1;
pFld->PutValue(aVal, FIELD_PROP_SHORT1 );
}
break;
case SW_SERVICE_FIELDTYPE_JUMP_EDIT:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_JUMPEDITFLD);
pFld = new SwJumpEditField((SwJumpEditFieldType*)pFldType,
m_pProps->nUSHORT1, m_pProps->sPar2, m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_DESCRIPTION :
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_0 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_1 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_2 :
case SW_SERVICE_FIELDTYPE_DOCINFO_INFO_3 :
case SW_SERVICE_FIELDTYPE_DOCINFO_CUSTOM :
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_AUTHOR :
case SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME :
case SW_SERVICE_FIELDTYPE_DOCINFO_KEY_WORDS :
case SW_SERVICE_FIELDTYPE_DOCINFO_SUBJECT :
case SW_SERVICE_FIELDTYPE_DOCINFO_TITLE :
case SW_SERVICE_FIELDTYPE_DOCINFO_REVISION :
case SW_SERVICE_FIELDTYPE_DOC_INFO:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DOCINFOFLD);
sal_uInt16 nSubType = aDocInfoSubTypeFromService[
m_nServiceId - SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_AUTHOR];
if( SW_SERVICE_FIELDTYPE_DOCINFO_CHANGE_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_CREATE_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_PRINT_DATE_TIME == m_nServiceId ||
SW_SERVICE_FIELDTYPE_DOCINFO_EDIT_TIME == m_nServiceId )
{
if(m_pProps->bBool2) //IsDate
{
nSubType &= 0xf0ff;
nSubType |= DI_SUB_DATE;
}
else
{
nSubType &= 0xf0ff;
nSubType |= DI_SUB_TIME;
}
}
if(m_pProps->bBool1)
nSubType |= DI_SUB_FIXED;
pFld = new SwDocInfoField((SwDocInfoFieldType*)pFldType, nSubType, m_pProps->sPar4, m_pProps->nFormat);
if(m_pProps->sPar3.Len())
((SwDocInfoField*)pFld)->SetExpansion(m_pProps->sPar3);
}
break;
case SW_SERVICE_FIELDTYPE_USER_EXT:
{
sal_Int32 nFormat = 0;
if(m_pProps->bBool1)
nFormat = AF_FIXED;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_EXTUSERFLD);
pFld = new SwExtUserField((SwExtUserFieldType*)pFldType, m_pProps->nUSHORT1, nFormat);
((SwExtUserField*)pFld)->SetExpansion(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_USER:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_USERFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
USHORT nUserSubType = m_pProps->bBool1 ? nsSwExtendedSubType::SUB_INVISIBLE : 0;
if(m_pProps->bBool2)
nUserSubType |= nsSwExtendedSubType::SUB_CMD;
if(m_pProps->bFormatIsDefault &&
nsSwGetSetExpType::GSE_STRING == ((SwUserFieldType*)pFldType)->GetType())
m_pProps->nFormat = -1;
pFld = new SwUserField((SwUserFieldType*)pFldType,
nUserSubType,
m_pProps->nFormat);
}
break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_SET:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_REFPAGESETFLD);
pFld = new SwRefPageSetField( (SwRefPageSetFieldType*)pFldType,
m_pProps->nUSHORT1,
m_pProps->bBool1 );
}
break;
case SW_SERVICE_FIELDTYPE_REF_PAGE_GET:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_REFPAGEGETFLD);
pFld = new SwRefPageGetField( (SwRefPageGetFieldType*)pFldType,
m_pProps->nUSHORT1 );
((SwRefPageGetField*)pFld)->SetText(m_pProps->sPar1);
}
break;
case SW_SERVICE_FIELDTYPE_PAGE_NUM:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_PAGENUMBERFLD);
pFld = new SwPageNumberField((SwPageNumberFieldType*)pFldType,
PG_RANDOM,
m_pProps->nFormat,
m_pProps->nUSHORT1);
((SwPageNumberField*)pFld)->SetUserString(m_pProps->sPar1);
uno::Any aVal; aVal <<= m_pProps->nSubType;
pFld->PutValue( aVal, FIELD_PROP_SUBTYPE );
}
break;
case SW_SERVICE_FIELDTYPE_DDE:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_DDEFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
pFld = new SwDDEField( (SwDDEFieldType*)pFldType );
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NAME:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DBNAMEFLD);
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBNameField((SwDBNameFieldType*)pFldType, aData);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NEXT_SET:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DBNEXTSETFLD);
pFld = new SwDBNextSetField((SwDBNextSetFieldType*)pFldType,
m_pProps->sPar3, aEmptyStr,
aData);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_NUM_SET:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBNumSetField( (SwDBNumSetFieldType*)
pDoc->GetSysFldType(RES_DBNUMSETFLD),
m_pProps->sPar3,
String::CreateFromInt32(m_pProps->nFormat),
aData );
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE_SET_NUM:
{
SwDBData aData;
aData.sDataSource = m_pProps->sPar1;
aData.sCommand = m_pProps->sPar2;
aData.nCommandType = m_pProps->nSHORT1;
pFld = new SwDBSetNumberField((SwDBSetNumberFieldType*)
pDoc->GetSysFldType(RES_DBSETNUMBERFLD),
aData,
m_pProps->nUSHORT1);
((SwDBSetNumberField*)pFld)->SetSetNumber(m_pProps->nFormat);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_DATABASE:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_DBFLD, m_sTypeName, sal_False);
if(!pFldType)
throw uno::RuntimeException();
pFld = new SwDBField((SwDBFieldType*)pFldType, m_pProps->nFormat);
((SwDBField*)pFld)->InitContent(m_pProps->sPar1);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
pFld->SetSubType(nSubType);
}
break;
case SW_SERVICE_FIELDTYPE_SET_EXP:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_SETEXPFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
//#93192# detect the field type's sub type and set an appropriate number format
if(m_pProps->bFormatIsDefault &&
nsSwGetSetExpType::GSE_STRING == ((SwSetExpFieldType*)pFldType)->GetType())
m_pProps->nFormat = -1;
pFld = new SwSetExpField((SwSetExpFieldType*)pFldType,
m_pProps->sPar2,
m_pProps->nUSHORT2 != USHRT_MAX ? //#i79471# the field can have a number format or a number_ing_ format
m_pProps->nUSHORT2 : m_pProps->nFormat);
sal_uInt16 nSubType = pFld->GetSubType();
if(m_pProps->bBool2)
nSubType &= ~nsSwExtendedSubType::SUB_INVISIBLE;
else
nSubType |= nsSwExtendedSubType::SUB_INVISIBLE;
if(m_pProps->bBool3)
nSubType |= nsSwExtendedSubType::SUB_CMD;
else
nSubType &= ~nsSwExtendedSubType::SUB_CMD;
pFld->SetSubType(nSubType);
((SwSetExpField*)pFld)->SetSeqNumber( m_pProps->nUSHORT1 );
((SwSetExpField*)pFld)->SetInputFlag(m_pProps->bBool1);
((SwSetExpField*)pFld)->SetPromptText(m_pProps->sPar3);
if(m_pProps->sPar4.Len())
((SwSetExpField*)pFld)->ChgExpStr(m_pProps->sPar4);
}
break;
case SW_SERVICE_FIELDTYPE_GET_EXP:
{
sal_uInt16 nSubType;
switch(m_pProps->nSubType)
{
case text::SetVariableType::STRING: nSubType = nsSwGetSetExpType::GSE_STRING; break;
case text::SetVariableType::VAR: nSubType = nsSwGetSetExpType::GSE_EXPR; break;
//case text::SetVariableType::SEQUENCE: nSubType = nsSwGetSetExpType::GSE_SEQ; break;
case text::SetVariableType::FORMULA: nSubType = nsSwGetSetExpType::GSE_FORMULA; break;
default:
DBG_ERROR("wrong value");
nSubType = nsSwGetSetExpType::GSE_EXPR;
}
//make sure the SubType matches the field type
SwFieldType* pSetExpFld = pDoc->GetFldType(RES_SETEXPFLD, m_pProps->sPar1, sal_False);
if( pSetExpFld && nSubType != nsSwGetSetExpType::GSE_STRING &&
static_cast< SwSetExpFieldType* >(pSetExpFld)->GetType() == nsSwGetSetExpType::GSE_STRING
)
nSubType = nsSwGetSetExpType::GSE_STRING;
if(m_pProps->bBool2)
nSubType |= nsSwExtendedSubType::SUB_CMD;
else
nSubType &= ~nsSwExtendedSubType::SUB_CMD;
pFld = new SwGetExpField((SwGetExpFieldType*)
pDoc->GetSysFldType(RES_GETEXPFLD),
m_pProps->sPar1, nSubType, m_pProps->nFormat);
//TODO: SubType auswerten!
if(m_pProps->sPar4.Len())
((SwGetExpField*)pFld)->ChgExpStr(m_pProps->sPar4);
}
break;
case SW_SERVICE_FIELDTYPE_INPUT_USER:
case SW_SERVICE_FIELDTYPE_INPUT:
{
SwFieldType* pFldType = pDoc->GetFldType(RES_INPUTFLD, m_sTypeName, sal_True);
if(!pFldType)
throw uno::RuntimeException();
USHORT nInpSubType = sal::static_int_cast< USHORT >(SW_SERVICE_FIELDTYPE_INPUT_USER == m_nServiceId ? INP_USR : INP_TXT);
SwInputField * pTxtField =
new SwInputField((SwInputFieldType*)pFldType,
m_pProps->sPar1, m_pProps->sPar2,
nInpSubType);
pTxtField->SetHelp(m_pProps->sPar3);
pTxtField->SetToolTip(m_pProps->sPar4);
pFld = pTxtField;
}
break;
case SW_SERVICE_FIELDTYPE_MACRO:
{
SwFieldType* pFldType = pDoc->GetSysFldType(RES_MACROFLD);
String aName;
// support for Scripting Framework macros
if (m_pProps->sPar4.Len() != 0)
{
aName = m_pProps->sPar4;
}
else
{
SwMacroField::CreateMacroString(
aName, m_pProps->sPar1, m_pProps->sPar3 );
}
pFld = new SwMacroField((SwMacroFieldType*)pFldType, aName,
m_pProps->sPar2);
}
break;
case SW_SERVICE_FIELDTYPE_PAGE_COUNT :
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT :
case SW_SERVICE_FIELDTYPE_WORD_COUNT :
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT :
case SW_SERVICE_FIELDTYPE_TABLE_COUNT :
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT :
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT :
{
sal_uInt16 nSubType = DS_PAGE;
switch(m_nServiceId)
{
// case SW_SERVICE_FIELDTYPE_PAGE_COUNT : break;
case SW_SERVICE_FIELDTYPE_PARAGRAPH_COUNT : nSubType = DS_PARA;break;
case SW_SERVICE_FIELDTYPE_WORD_COUNT : nSubType = DS_WORD;break;
case SW_SERVICE_FIELDTYPE_CHARACTER_COUNT : nSubType = DS_CHAR;break;
case SW_SERVICE_FIELDTYPE_TABLE_COUNT : nSubType = DS_TBL;break;
case SW_SERVICE_FIELDTYPE_GRAPHIC_OBJECT_COUNT : nSubType = DS_GRF;break;
case SW_SERVICE_FIELDTYPE_EMBEDDED_OBJECT_COUNT : nSubType = DS_OLE;break;
}
SwFieldType* pFldType = pDoc->GetSysFldType(RES_DOCSTATFLD);
pFld = new SwDocStatField((SwDocStatFieldType*)pFldType, nSubType, m_pProps->nUSHORT2);
}
break;
case SW_SERVICE_FIELDTYPE_BIBLIOGRAPHY:
pFld = new SwAuthorityField( (SwAuthorityFieldType*)
pDoc->InsertFldType(SwAuthorityFieldType(pDoc)),
aEmptyStr );
if(m_pProps->aPropSeq.getLength())
{
uno::Any aVal; aVal <<= m_pProps->aPropSeq;
pFld->PutValue( aVal, FIELD_PROP_PROP_SEQ );
}
break;
case SW_SERVICE_FIELDTYPE_COMBINED_CHARACTERS:
// create field
pFld = new SwCombinedCharField( (SwCombinedCharFieldType*)
pDoc->GetSysFldType(RES_COMBINED_CHARS),
m_pProps->sPar1);
break;
case SW_SERVICE_FIELDTYPE_DROPDOWN:
pFld = new SwDropDownField
((SwDropDownFieldType *)
pDoc->GetSysFldType(RES_DROPDOWN));
((SwDropDownField *) pFld)->SetItems(m_pProps->aStrings);
((SwDropDownField *) pFld)->SetSelectedItem(m_pProps->sPar1);
((SwDropDownField *) pFld)->SetName(m_pProps->sPar2);
((SwDropDownField *) pFld)->SetHelp(m_pProps->sPar3);
((SwDropDownField *) pFld)->SetToolTip(m_pProps->sPar4);
break;
case SW_SERVICE_FIELDTYPE_TABLE_FORMULA :
{
// create field
USHORT nType = nsSwGetSetExpType::GSE_FORMULA;
if(m_pProps->bBool1)
{
nType |= nsSwExtendedSubType::SUB_CMD;
if(m_pProps->bFormatIsDefault)
m_pProps->nFormat = -1;
}
pFld = new SwTblField( (SwTblFieldType*)
pDoc->GetSysFldType(RES_TABLEFLD),
m_pProps->sPar2,
nType,
m_pProps->nFormat);
((SwTblField*)pFld)->ChgExpStr(m_pProps->sPar1);
}
break;
default: DBG_ERROR("was ist das fuer ein Typ?");
}
if(pFld)
{
pFld->SetAutomaticLanguage(!m_pProps->bBool4);
SwFmtFld aFmt( *pFld );
UnoActionContext aCont(pDoc);
SwTxtAttr* pTxtAttr = 0;
if(aPam.HasMark())
pDoc->DeleteAndJoin(aPam);
pDoc->Insert(aPam, aFmt, 10000);
pTxtAttr = aPam.GetNode()->GetTxtNode()->GetTxtAttr(
aPam.GetPoint()->nContent.GetIndex()-1, RES_TXTATR_FIELD);
// was passiert mit dem Update der Felder ? (siehe fldmgr.cxx)
if(pTxtAttr)
{
const SwFmtFld& rFld = pTxtAttr->GetFld();
pFmtFld = &rFld;
}
}
delete pFld;
m_pDoc = pDoc;
m_pDoc->GetUnoCallBack()->Add(this);
m_bIsDescriptor = sal_False;
if(m_aFieldTypeClient.GetRegisteredIn())
const_cast<SwModify*>(m_aFieldTypeClient.GetRegisteredIn())->Remove(&m_aFieldTypeClient);
DELETEZ(m_pProps);
if(m_bCallUpdate)
update();
}
else
throw lang::IllegalArgumentException();
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::attach(const uno::Reference< text::XTextRange > & xTextRange)
throw( lang::IllegalArgumentException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
attachToRange( xTextRange );
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< text::XTextRange > SwXTextField::getAnchor(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Reference< text::XTextRange > aRef;
SwField* pField = (SwField*)GetField();
if(pField)
{
const SwTxtFld* pTxtFld = pFmtFld->GetTxtFld();
if(!pTxtFld)
throw uno::RuntimeException();
const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart() + 1, rTxtNode, *pTxtFld->GetStart());
aRef = SwXTextRange::CreateTextRangeFromPosition(m_pDoc,
*aPam.GetPoint(), aPam.GetMark());
}
return aRef;
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::dispose(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwField* pField = (SwField*)GetField();
if(pField)
{
UnoActionContext aContext(GetDoc());
const SwTxtFld* pTxtFld = pFmtFld->GetTxtFld();
SwTxtNode& rTxtNode = (SwTxtNode&)*pTxtFld->GetpTxtNode();
SwPaM aPam(rTxtNode, *pTxtFld->GetStart());
aPam.SetMark();
aPam.Move();
GetDoc()->DeleteAndJoin(aPam);
}
if ( m_pTextObject )
{
m_pTextObject->DisposeEditSource();
m_pTextObject->release();
m_pTextObject = 0;
}
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException )
{
if(!GetRegisteredIn())
throw uno::RuntimeException();
aLstnrCntnr.AddListener(aListener);
}
/*-- 14.12.98 11:37:18---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw( uno::RuntimeException )
{
if(!GetRegisteredIn() || !aLstnrCntnr.RemoveListener(aListener))
throw uno::RuntimeException();
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< beans::XPropertySetInfo > SwXTextField::getPropertySetInfo(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
//kein static
uno::Reference< beans::XPropertySetInfo > aRef;
if(m_nServiceId != USHRT_MAX)
{
const SfxItemPropertyMap* pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId ));
uno::Reference< beans::XPropertySetInfo > xInfo = new SfxItemPropertySetInfo(pMap);
// extend PropertySetInfo!
const uno::Sequence<beans::Property> aPropSeq = xInfo->getProperties();
aRef = new SfxExtItemPropertySetInfo(
aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH_EXTENSIONS),
aPropSeq );
}
else
throw uno::RuntimeException();
return aRef;
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::setPropertyValue(const OUString& rPropertyName, const uno::Any& rValue)
throw( beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException,
lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
SwField* pField = (SwField*)GetField();
const SfxItemPropertyMap* _pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId));
const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
if (!pMap)
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & beans::PropertyAttribute::READONLY)
throw beans::PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if(pField)
{
// Sonderbehandlung Serienbrieffeld
sal_uInt16 nWhich = pField->Which();
if( RES_DBFLD == nWhich &&
(rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_NAME)) ||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_BASE_URL))||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_TABLE_NAME))||
rPropertyName.equalsAsciiL( SW_PROP_NAME(UNO_NAME_DATA_COLUMN_NAME))))
{
// hier muss ein neuer Feldtyp angelegt werden und
// das Feld an den neuen Typ umgehaengt werden
DBG_WARNING("not implemented")
}
else
{
// -> #111840#
SwDoc * pDoc = GetDoc();
if (NULL != pDoc)
{
SwPosition * pPos = GetPosition();
ASSERT(pPos, "no position");
pDoc->PutValueToField( *pPos, rValue, pMap->nWID);
delete pPos;
}
// <- #111840#
}
pField->PutValue( rValue, pMap->nWID );
//#114571# changes of the expanded string have to be notified
//#to the SwTxtFld
if(RES_DBFLD == nWhich && pFmtFld->GetTxtFld())
{
pFmtFld->GetTxtFld()->Expand();
}
}
else if(m_pProps)
{
String* pStr = 0;
BOOL* pBool = 0;
switch(pMap->nWID)
{
case FIELD_PROP_PAR1:
pStr = &m_pProps->sPar1;
break;
case FIELD_PROP_PAR2:
pStr = &m_pProps->sPar2;
break;
case FIELD_PROP_PAR3:
pStr = &m_pProps->sPar3;
break;
case FIELD_PROP_PAR4:
pStr = &m_pProps->sPar4;
break;
case FIELD_PROP_FORMAT:
rValue >>= m_pProps->nFormat;
m_pProps->bFormatIsDefault = sal_False;
break;
case FIELD_PROP_SUBTYPE:
m_pProps->nSubType = SWUnoHelper::GetEnumAsInt32( rValue );
break;
case FIELD_PROP_BYTE1 :
rValue >>= m_pProps->nByte1;
break;
case FIELD_PROP_BOOL1 :
pBool = &m_pProps->bBool1;
break;
case FIELD_PROP_BOOL2 :
pBool = &m_pProps->bBool2;
break;
case FIELD_PROP_BOOL3 :
pBool = &m_pProps->bBool3;
break;
case FIELD_PROP_BOOL4:
pBool = &m_pProps->bBool4;
break;
case FIELD_PROP_DATE :
{
if(rValue.getValueType() != ::getCppuType(static_cast<const util::Date*>(0)))
throw lang::IllegalArgumentException();
util::Date aTemp = *(const util::Date*)rValue.getValue();
m_pProps->aDate = Date(aTemp.Day, aTemp.Month, aTemp.Year);
}
break;
case FIELD_PROP_USHORT1:
case FIELD_PROP_USHORT2:
{
sal_Int16 nVal = 0;
rValue >>= nVal;
if( FIELD_PROP_USHORT1 == pMap->nWID)
m_pProps->nUSHORT1 = nVal;
else
m_pProps->nUSHORT2 = nVal;
}
break;
case FIELD_PROP_SHORT1:
rValue >>= m_pProps->nSHORT1;
break;
case FIELD_PROP_DOUBLE:
if(rValue.getValueType() != ::getCppuType(static_cast<const double*>(0)))
throw lang::IllegalArgumentException();
m_pProps->fDouble = *(double*)rValue.getValue();
break;
case FIELD_PROP_DATE_TIME :
if(!m_pProps->pDateTime)
m_pProps->pDateTime = new util::DateTime;
rValue >>= (*m_pProps->pDateTime);
break;
case FIELD_PROP_PROP_SEQ:
rValue >>= m_pProps->aPropSeq;
break;
case FIELD_PROP_STRINGS:
rValue >>= m_pProps->aStrings;
break;
}
if( pStr )
::GetString( rValue, *pStr );
else if( pBool )
{
if( rValue.getValueType() == getCppuBooleanType() )
*pBool = *(sal_Bool*)rValue.getValue();
else
throw lang::IllegalArgumentException();
}
}
else
throw uno::RuntimeException();
}
/*-- 14.12.98 11:37:19---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Any SwXTextField::getPropertyValue(const OUString& rPropertyName)
throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
uno::Any aRet;
const SwField* pField = GetField();
const SfxItemPropertyMap* _pMap = aSwMapProvider.GetPropertyMap(
lcl_GetPropertyMapOfService( m_nServiceId));
const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
if(!pMap )
{
_pMap = aSwMapProvider.GetPropertyMap(PROPERTY_MAP_PARAGRAPH_EXTENSIONS);
pMap = SfxItemPropertyMap::GetByName(_pMap, rPropertyName);
}
if (!pMap)
throw beans::UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
switch( pMap->nWID )
{
case FN_UNO_TEXT_WRAP:
aRet <<= text::WrapTextMode_NONE;
break;
case FN_UNO_ANCHOR_TYPE:
aRet <<= text::TextContentAnchorType_AS_CHARACTER;
break;
case FN_UNO_ANCHOR_TYPES:
{
uno::Sequence<text::TextContentAnchorType> aTypes(1);
text::TextContentAnchorType* pArray = aTypes.getArray();
pArray[0] = text::TextContentAnchorType_AS_CHARACTER;
aRet.setValue(&aTypes, ::getCppuType(static_cast<uno::Sequence<text::TextContentAnchorType>*>(0)));
}
break;
default:
if( pField )
{
if (FIELD_PROP_IS_FIELD_USED == pMap->nWID ||
FIELD_PROP_IS_FIELD_DISPLAYED == pMap->nWID)
{
sal_Bool bIsFieldUsed = sal_False;
sal_Bool bIsFieldDisplayed = sal_False;
// in order to have the information about fields
// correctly evaluated the document needs a layout
// (has to be already formatted)
SwDoc *pDoc = GetDoc();
ViewShell *pViewShell = 0;
SwEditShell *pEditShell = pDoc ? pDoc->GetEditShell( &pViewShell ) : 0;
if (pEditShell)
pEditShell->CalcLayout();
else if (pViewShell) // a page preview has no SwEditShell it should only have a view shell
pViewShell->CalcLayout();
else
throw uno::RuntimeException();
// get text node for the text field
const SwFmtFld *pFldFmt = GetFldFmt();
const SwTxtFld* pTxtFld = pFldFmt ? pFmtFld->GetTxtFld() : 0;
if(!pTxtFld)
throw uno::RuntimeException();
const SwTxtNode& rTxtNode = pTxtFld->GetTxtNode();
// skip fields that are currently not in the document
// e.g. fields in undo or redo array
if (rTxtNode.GetNodes().IsDocNodes())
{
sal_Bool bFrame = 0 != rTxtNode.FindLayoutRect().Width(); // oder so
sal_Bool bHidden = rTxtNode.IsHidden();
if ( !bHidden )
{
xub_StrLen nHiddenStart;
xub_StrLen nHiddenEnd;
SwPosition *pPos = pTxtFld->GetPosition();
if (!pPos)
throw uno::RuntimeException();
bHidden = SwScriptInfo::GetBoundsOfHiddenRange( rTxtNode,
pPos->nContent.GetIndex(),
nHiddenStart, nHiddenEnd );
}
// !bFrame && !bHidden: aller Wahrscheinlichkeit handelt es
// sich um ein Feld in einem unbenutzten Seitenstyle
//
// bHidden: Feld ist versteckt
// FME: Problem: Verstecktes Feld in unbenutzter Seitenvorlage =>
// bIsFieldUsed = true
// bIsFieldDisplayed = false
bIsFieldUsed = bFrame || bHidden;
bIsFieldDisplayed = bIsFieldUsed && !bHidden;
}
sal_Bool bRetVal = (FIELD_PROP_IS_FIELD_USED == pMap->nWID) ?
bIsFieldUsed : bIsFieldDisplayed;
aRet.setValue( &bRetVal, ::getCppuBooleanType() );
}
else
pField->QueryValue( aRet, pMap->nWID );
}
else if( m_pProps ) // currently just a descriptor...
{
switch(pMap->nWID)
{
case FIELD_PROP_TEXT:
{
if (!m_pTextObject)
{
SwTextAPIEditSource* pObj = new SwTextAPIEditSource( &m_pDoc->GetDocShell()->GetPool() );
m_pTextObject = new SwTextAPIObject( pObj );
m_pTextObject->acquire();
}
uno::Reference < text::XText > xText( m_pTextObject );
aRet <<= xText;
break;
}
case FIELD_PROP_PAR1:
aRet <<= OUString(m_pProps->sPar1);
break;
case FIELD_PROP_PAR2:
aRet <<= OUString(m_pProps->sPar2);
break;
case FIELD_PROP_PAR3:
aRet <<= OUString(m_pProps->sPar3);
break;
case FIELD_PROP_PAR4:
aRet <<= OUString(m_pProps->sPar4);
break;
case FIELD_PROP_FORMAT:
aRet <<= m_pProps->nFormat;
break;
case FIELD_PROP_SUBTYPE:
aRet <<= m_pProps->nSubType;
break;
case FIELD_PROP_BYTE1 :
aRet <<= m_pProps->nByte1;
break;
case FIELD_PROP_BOOL1 :
aRet.setValue(&m_pProps->bBool1, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL2 :
aRet.setValue(&m_pProps->bBool2, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL3 :
aRet.setValue(&m_pProps->bBool3, ::getCppuBooleanType());
break;
case FIELD_PROP_BOOL4 :
aRet.setValue(&m_pProps->bBool4, ::getCppuBooleanType());
break;
case FIELD_PROP_DATE :
aRet.setValue(&m_pProps->aDate, ::getCppuType(static_cast<const util::Date*>(0)));
break;
case FIELD_PROP_USHORT1:
aRet <<= (sal_Int16)m_pProps->nUSHORT1;
break;
case FIELD_PROP_USHORT2:
aRet <<= (sal_Int16)m_pProps->nUSHORT2;
break;
case FIELD_PROP_SHORT1:
aRet <<= m_pProps->nSHORT1;
break;
case FIELD_PROP_DOUBLE:
aRet <<= m_pProps->fDouble;
break;
case FIELD_PROP_DATE_TIME :
if(m_pProps->pDateTime)
aRet <<= (*m_pProps->pDateTime);
break;
case FIELD_PROP_PROP_SEQ:
aRet <<= m_pProps->aPropSeq;
break;
case FIELD_PROP_STRINGS:
aRet <<= m_pProps->aStrings;
break;
case FIELD_PROP_IS_FIELD_USED:
case FIELD_PROP_IS_FIELD_DISPLAYED:
aRet.setValue( sal_False, ::getCppuBooleanType() );
break;
}
}
else
throw uno::RuntimeException();
}
return aRet;
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addPropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removePropertyChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XPropertyChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::addVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/*-- 14.12.98 11:37:20---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextField::removeVetoableChangeListener(const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener > & /*aListener*/) throw( beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException )
{
DBG_WARNING("not implemented")
}
/* -----------------------------23.03.01 13:15--------------------------------
---------------------------------------------------------------------------*/
void SwXTextField::update( ) throw (uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
const SwField* pFld = GetField();
if(pFld)
{
switch(pFld->Which())
{
case RES_DATETIMEFLD:
((SwDateTimeField*)pFld)->SetDateTime( ::DateTime() );
break;
case RES_EXTUSERFLD:
{
SwExtUserField* pExtUserFld = (SwExtUserField*)pFld;
pExtUserFld->SetExpansion( ((SwExtUserFieldType*)pFld->GetTyp())->Expand(
pExtUserFld->GetSubType(),
pExtUserFld->GetFormat() ) );
}
break;
case RES_AUTHORFLD:
{
SwAuthorField* pAuthorFld = (SwAuthorField*)pFld;
pAuthorFld->SetExpansion( ((SwAuthorFieldType*)pFld->GetTyp())->Expand(
pAuthorFld->GetFormat() ) );
}
break;
case RES_FILENAMEFLD:
{
SwFileNameField* pFileNameFld = (SwFileNameField*)pFld;
pFileNameFld->SetExpansion( ((SwFileNameFieldType*)pFld->GetTyp())->Expand(
pFileNameFld->GetFormat() ) );
}
break;
case RES_DOCINFOFLD:
{
SwDocInfoField* pDocInfFld = (SwDocInfoField*)pFld;
pDocInfFld->SetExpansion( ((SwDocInfoFieldType*)pFld->GetTyp())->Expand(
pDocInfFld->GetSubType(),
pDocInfFld->GetFormat(),
pDocInfFld->GetLanguage(),
pDocInfFld->GetName() ) );
}
break;
}
// --> FME 2004-10-06 #116480#
// Text formatting has to be triggered.
const_cast<SwFmtFld*>(pFmtFld)->Modify( 0, 0 );
// <--
}
else
m_bCallUpdate = sal_True;
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
OUString SwXTextField::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextField");
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
static OUString OldNameToNewName_Impl( const OUString &rOld )
{
static OUString aOldNamePart1( OUString::createFromAscii(".TextField.DocInfo.") );
static OUString aOldNamePart2( OUString::createFromAscii(".TextField.") );
static OUString aNewNamePart1( OUString::createFromAscii(".textfield.docinfo.") );
static OUString aNewNamePart2( OUString::createFromAscii(".textfield.") );
OUString sServiceNameCC( rOld );
sal_Int32 nIdx = sServiceNameCC.indexOf( aOldNamePart1 );
if (nIdx >= 0)
sServiceNameCC = sServiceNameCC.replaceAt( nIdx, aOldNamePart1.getLength(), aNewNamePart1 );
nIdx = sServiceNameCC.indexOf( aOldNamePart2 );
if (nIdx >= 0)
sServiceNameCC = sServiceNameCC.replaceAt( nIdx, aOldNamePart2.getLength(), aNewNamePart2 );
return sServiceNameCC;
}
sal_Bool SwXTextField::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
OUString sServiceName = SwXServiceProvider::GetProviderName(m_nServiceId);
// case-corected version of service-name (see #i67811)
// (need to supply both because of compatibility to older versions)
OUString sServiceNameCC( OldNameToNewName_Impl( sServiceName ) );
return sServiceName == rServiceName || sServiceNameCC == rServiceName ||
rServiceName.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM("com.sun.star.text.TextContent"));
}
/* -----------------19.03.99 14:11-------------------
*
* --------------------------------------------------*/
uno::Sequence< OUString > SwXTextField::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
OUString sServiceName = SwXServiceProvider::GetProviderName(m_nServiceId);
// case-corected version of service-name (see #i67811)
// (need to supply both because of compatibility to older versions)
OUString sServiceNameCC( OldNameToNewName_Impl( sServiceName ) );
sal_Int32 nLen = sServiceName == sServiceNameCC ? 2 : 3;
uno::Sequence< OUString > aRet( nLen );
OUString* pArray = aRet.getArray();
*pArray++ = sServiceName;
if (nLen == 3)
*pArray++ = sServiceNameCC;
*pArray++ = C2U("com.sun.star.text.TextContent");
return aRet;
}
void SwXTextField::Invalidate()
{
if (GetRegisteredIn())
{
((SwModify*)GetRegisteredIn())->Remove(this);
aLstnrCntnr.Disposing();
pFmtFld = 0;
m_pDoc = 0;
}
}
/* -----------------14.12.98 12:00-------------------
*
* --------------------------------------------------*/
void SwXTextField::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
switch( pOld ? pOld->Which() : 0 )
{
case RES_REMOVE_UNO_OBJECT:
case RES_OBJECTDYING:
if( (void*)GetRegisteredIn() == ((SwPtrMsgPoolItem *)pOld)->pObject )
Invalidate();
break;
case RES_FMT_CHG:
// wurden wir an das neue umgehaengt und wird das alte geloscht?
if( ((SwFmtChg*)pNew)->pChangedFmt == GetRegisteredIn() &&
((SwFmtChg*)pOld)->pChangedFmt->IsFmtInDTOR() )
Invalidate();
break;
case RES_FIELD_DELETED:
if( (void*)pFmtFld == ((SwPtrMsgPoolItem *)pOld)->pObject )
Invalidate();
break;
}
}
/*-- 14.12.98 11:37:21---------------------------------------------------
-----------------------------------------------------------------------*/
const SwField* SwXTextField::GetField() const
{
if(GetRegisteredIn() && pFmtFld)
return pFmtFld->GetFld();
return 0;
}
// #111840#
SwPosition * SwXTextField::GetPosition()
{
SwPosition * pResult = NULL;
const SwFmtFld * pFmtFld2 = GetFldFmt();
if (pFmtFld2)
{
const SwTxtFld * pTxtFld = pFmtFld2->GetTxtFld();
if (pTxtFld)
pResult = pTxtFld->GetPosition();
}
return pResult;
}
/******************************************************************
*
******************************************************************/
/******************************************************************
* SwXTextFieldMasters
******************************************************************/
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
OUString SwXTextFieldMasters::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextFieldMasters");
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXTextFieldMasters::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.TextFieldMasters" ));
}
/* -----------------------------06.04.00 13:22--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldMasters::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFieldMasters");
return aRet;
}
/*-- 21.12.98 10:37:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldMasters::SwXTextFieldMasters(SwDoc* _pDoc) :
SwUnoCollection(_pDoc)
{
}
/*-- 21.12.98 10:37:32---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldMasters::~SwXTextFieldMasters()
{
}
/*-- 21.12.98 10:37:33---------------------------------------------------
Iteration ueber nicht-Standard Feldtypen
USER/SETEXP/DDE/DATABASE
Der Name ist demnach:
"com.sun.star.text.fieldmaster.User" + <Feltypname>
"com.sun.star.text.fieldmaster.DDE" + <Feltypname>
"com.sun.star.text.fieldmaster.SetExpression" + <Feltypname>
"com.sun.star.text.fieldmaster.DataBase" + <Feltypname>
Falls wir grosszuegig werden wollen, dann koennte man com.sun.star.text
auch optional weglassen
-----------------------------------------------------------------------*/
sal_uInt16 lcl_GetIdByName( String& rName, String& rTypeName )
{
if( rName.EqualsAscii( COM_TEXT_FLDMASTER, 0, RTL_CONSTASCII_LENGTH(COM_TEXT_FLDMASTER ))
|| rName.EqualsAscii( COM_TEXT_FLDMASTER_CC, 0, RTL_CONSTASCII_LENGTH(COM_TEXT_FLDMASTER_CC )))
rName.Erase(0, 30);
sal_uInt16 nResId = USHRT_MAX;
xub_StrLen nFound = 0;
rTypeName = rName.GetToken( 0, '.', nFound );
if(rTypeName.EqualsAscii("User"))
nResId = RES_USERFLD;
else if(rTypeName.EqualsAscii("DDE"))
nResId = RES_DDEFLD;
else if(rTypeName.EqualsAscii("SetExpression"))
{
nResId = RES_SETEXPFLD;
String sFldTypName( rName.GetToken( 1, '.' ));
String sUIName( SwStyleNameMapper::GetSpecialExtraUIName( sFldTypName ) );
if( sUIName != sFldTypName )
rName.SetToken( 1, '.', sUIName );
}
else if(rTypeName.EqualsAscii("DataBase"))
{
rName.Erase( 0, RTL_CONSTASCII_LENGTH( "DataBase." ));
USHORT nDotCount = rName.GetTokenCount('.');
if( 2 <= nDotCount )
{
// #i51815#
//rName.SearchAndReplace('.', DB_DELIM);
//rName.SetChar( rName.SearchBackward( '.' ), DB_DELIM );
rName.InsertAscii( "DataBase.", 0 );
nResId = RES_DBFLD;
}
}
else if( rTypeName.EqualsAscii("Bibliography"))
nResId = RES_AUTHORITY;
return nResId;
}
//-----------------------------------------------------------------------------
uno::Any SwXTextFieldMasters::getByName(const OUString& rName)
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
String sName(rName), sTypeName;
sal_uInt16 nResId = lcl_GetIdByName( sName, sTypeName );
if( USHRT_MAX == nResId )
throw container::NoSuchElementException();
sName.Erase(0, sTypeName.Len()+1);
SwFieldType* pType = GetDoc()->GetFldType(nResId, sName, sal_True);
if(!pType)
throw container::NoSuchElementException();
SwXFieldMaster* pMaster = (SwXFieldMaster*)
SwClientIter(*pType).First(TYPE(SwXFieldMaster));
if(!pMaster)
pMaster = new SwXFieldMaster(*pType, GetDoc());
uno::Reference< beans::XPropertySet > aRef = pMaster;
uno::Any aRet(&aRef, ::getCppuType( static_cast<const uno::Reference<beans::XPropertySet>* >(0)));
return aRet;
}
/*-- 06.03.2001 11:29:34,5-------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::getInstanceName(
const SwFieldType& rFldType, String& rName)
{
sal_Bool bRet = sal_True;
switch( rFldType.Which() )
{
case RES_USERFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "User."));
rName += rFldType.GetName();
break;
case RES_DDEFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "DDE."));
rName += rFldType.GetName();
break;
case RES_SETEXPFLD:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "SetExpression."));
rName += String( SwStyleNameMapper::GetSpecialExtraProgName( rFldType.GetName() ) );
break;
case RES_DBFLD:
{
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "DataBase."));
String sDBName(rFldType.GetName());
sDBName.SearchAndReplaceAll(DB_DELIM, '.');
rName += sDBName;
}
break;
case RES_AUTHORITY:
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( COM_TEXT_FLDMASTER_CC ));
rName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( "Bibliography"));
break;
default:
bRet = sal_False;
}
return bRet;
}
/*-- 21.12.98 10:37:33---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldMasters::getElementNames(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
const SwFldTypes* pFldTypes = GetDoc()->GetFldTypes();
sal_uInt16 nCount = pFldTypes->Count();
SvStrings aFldNames;
String* pString = new String();
sal_uInt16 i;
for( i = 0; i < nCount; i++)
{
SwFieldType& rFldType = *((*pFldTypes)[i]);
if (SwXTextFieldMasters::getInstanceName(rFldType, *pString))
{
aFldNames.Insert(pString, aFldNames.Count());
pString = new String();
}
}
delete pString;
uno::Sequence< OUString > aSeq(aFldNames.Count());
OUString* pArray = aSeq.getArray();
for(i = 0; i < aFldNames.Count();i++)
{
pArray[i] = *aFldNames.GetObject(i);
}
aFldNames.DeleteAndDestroy(0, aFldNames.Count());
return aSeq;
}
/*-- 21.12.98 10:37:33---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::hasByName(const OUString& rName) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!GetDoc())
throw uno::RuntimeException();
String sName(rName), sTypeName;
sal_uInt16 nResId = lcl_GetIdByName( sName, sTypeName );
sal_Bool bRet = sal_False;
if( USHRT_MAX != nResId )
{
sName.Erase(0, sTypeName.Len()+1);
bRet = USHRT_MAX != nResId && 0 != GetDoc()->GetFldType(nResId, sName, sal_True);
}
return bRet;
}
/*-- 21.12.98 10:37:34---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Type SwXTextFieldMasters::getElementType(void) throw( uno::RuntimeException )
{
return ::getCppuType(static_cast<const uno::Reference<beans::XPropertySet>*>(0));
}
/*-- 21.12.98 10:37:34---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldMasters::hasElements(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
return sal_True;
}
/******************************************************************
*
******************************************************************/
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
OUString SwXTextFieldTypes::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXTextFieldTypes");
}
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXTextFieldTypes::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.TextFields" ));
}
/* -----------------------------06.04.00 13:24--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXTextFieldTypes::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.TextFields");
return aRet;
}
/*-- 21.12.98 10:35:15---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldTypes::SwXTextFieldTypes(SwDoc* _pDoc) :
SwUnoCollection (_pDoc),
aRefreshCont ( static_cast< XEnumerationAccess * >(this) )
{
}
/*-- 21.12.98 10:35:16---------------------------------------------------
-----------------------------------------------------------------------*/
SwXTextFieldTypes::~SwXTextFieldTypes()
{
}
/*-- 11.07.02 14:25:00---------------------------------------------------
-----------------------------------------------------------------------*/
void SwXTextFieldTypes::Invalidate()
{
SwUnoCollection::Invalidate();
aRefreshCont.Disposing();
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Reference< container::XEnumeration > SwXTextFieldTypes::createEnumeration(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
return new SwXFieldEnumeration(GetDoc());
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Type SwXTextFieldTypes::getElementType(void) throw( uno::RuntimeException )
{
return ::getCppuType(static_cast<const uno::Reference<text::XDependentTextField>*>(0));
}
/*-- 21.12.98 10:35:17---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXTextFieldTypes::hasElements(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
//es gibt sie immer
return sal_True;
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::refresh(void) throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if(!IsValid())
throw uno::RuntimeException();
UnoActionContext aContext(GetDoc());
SwDocStat aDocStat;
GetDoc()->UpdateDocStat(aDocStat);
GetDoc()->UpdateFlds(0, sal_False);
// call refresh listeners
aRefreshCont.Refreshed();
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::addRefreshListener(const uno::Reference< util::XRefreshListener > & l)
throw( uno::RuntimeException )
{
::vos::OGuard aGuard(Application::GetSolarMutex());
if ( !IsValid() )
throw uno::RuntimeException();
aRefreshCont.AddListener ( reinterpret_cast < const uno::Reference < lang::XEventListener > &> ( l ));
}
/* -----------------24.02.99 16:19-------------------
*
* --------------------------------------------------*/
void SwXTextFieldTypes::removeRefreshListener(const uno::Reference< util::XRefreshListener > & l)
throw( uno::RuntimeException )
{
::vos::OGuard aGuard(Application::GetSolarMutex());
if ( !IsValid() || !aRefreshCont.RemoveListener ( reinterpret_cast < const uno::Reference < lang::XEventListener > &> ( l ) ) )
throw uno::RuntimeException();
}
/******************************************************************
* SwXFieldEnumeration
******************************************************************/
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
OUString SwXFieldEnumeration::getImplementationName(void) throw( uno::RuntimeException )
{
return C2U("SwXFieldEnumeration");
}
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
BOOL SwXFieldEnumeration::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
"com.sun.star.text.FieldEnumeration" ));
}
/* -----------------------------06.04.00 13:25--------------------------------
---------------------------------------------------------------------------*/
uno::Sequence< OUString > SwXFieldEnumeration::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = C2U("com.sun.star.text.FieldEnumeration");
return aRet;
}
/* -----------------21.12.98 14:57-------------------
*
* --------------------------------------------------*/
SwXFieldEnumeration::SwXFieldEnumeration(SwDoc* pDc) :
nNextIndex(0),
pDoc(pDc)
{
pDoc->GetPageDescFromPool(RES_POOLPAGE_STANDARD)->Add(this);
// build sequence
sal_Int32 nSize = 32;
aItems.realloc( nSize );
uno::Reference< text::XTextField > *pItems = aItems.getArray();
sal_Int32 nFillPos = 0;
//
const SwFldTypes* pFldTypes = pDoc->GetFldTypes();
sal_uInt16 nCount = pFldTypes->Count();
for(sal_uInt16 nType = 0; nType < nCount; ++nType)
{
const SwFieldType *pCurType = pFldTypes->GetObject(nType);
SwClientIter aIter( *(SwFieldType*)pCurType );
const SwFmtFld* pCurFldFmt = (SwFmtFld*)aIter.First( TYPE( SwFmtFld ));
while (pCurFldFmt)
{
const SwTxtFld *pTxtFld = pCurFldFmt->GetTxtFld();
// skip fields that are currently not in the document
// e.g. fields in undo or redo array
BOOL bSkip = !pTxtFld ||
!pTxtFld->GetpTxtNode()->GetNodes().IsDocNodes();
if (!bSkip)
pItems[ nFillPos++ ] = new SwXTextField(*pCurFldFmt, pDoc);
pCurFldFmt = (SwFmtFld*)aIter.Next();
// enlarge sequence if necessary
if (aItems.getLength() == nFillPos)
{
aItems.realloc( 2 * aItems.getLength() );
pItems = aItems.getArray();
}
}
}
// resize sequence to actual used size
aItems.realloc( nFillPos );
}
/*-- 21.12.98 14:57:23---------------------------------------------------
-----------------------------------------------------------------------*/
SwXFieldEnumeration::~SwXFieldEnumeration()
{
}
/*-- 21.12.98 14:57:42---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwXFieldEnumeration::hasMoreElements(void)
throw( uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
return nNextIndex < aItems.getLength();
}
/*-- 21.12.98 14:57:42---------------------------------------------------
-----------------------------------------------------------------------*/
uno::Any SwXFieldEnumeration::nextElement(void)
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
vos::OGuard aGuard(Application::GetSolarMutex());
if (!(nNextIndex < aItems.getLength()))
throw container::NoSuchElementException();
#if OSL_DEBUG_LEVEL > 1
uno::Reference< text::XTextField > *pItems = aItems.getArray();
(void)pItems;
#endif
uno::Reference< text::XTextField > &rxFld = aItems.getArray()[ nNextIndex++ ];
uno::Any aRet(&rxFld, ::getCppuType(static_cast<const uno::Reference<text::XTextField>*>(0)));
rxFld = 0; // free memory for item that is not longer used
return aRet;
}
/* -----------------21.12.98 15:08-------------------
*
* --------------------------------------------------*/
void SwXFieldEnumeration::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew)
{
ClientModify(this, pOld, pNew);
if(!GetRegisteredIn())
pDoc = 0;
}
String& GetString( const uno::Any& rAny, String& rStr )
{
OUString aStr;
rAny >>= aStr;
rStr = String( aStr );
return rStr;
}
|
/*************************************************************************
*
* $RCSfile: unoprnms.cxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: dvo $ $Date: 2000-12-11 20:00:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
//#define MAP_CHAR_LEN(cchar) cchar, sizeof(cchar) - 1
//struct SwPropNameLen
//{
// const char* pName;
// USHORT nNameLen;
//};
//extern const SwPropNameLen UNO_NAME_FOLLOW_STYLE;
const SwPropNameLen __FAR_DATA UNO_NAME_FOLLOW_STYLE(MAP_CHAR_LEN("FollowStyle"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_PHYSICAL (MAP_CHAR_LEN("IsPhysical"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTO_UPDATE (MAP_CHAR_LEN("IsAutoUpdate"));
const SwPropNameLen __FAR_DATA UNO_NAME_DISPLAY_NAME (MAP_CHAR_LEN("DisplayName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_URL (MAP_CHAR_LEN("ParaBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_FILTER (MAP_CHAR_LEN("ParaBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_URL (MAP_CHAR_LEN("HeaderBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_FILTER (MAP_CHAR_LEN("HeaderBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_URL (MAP_CHAR_LEN("FooterBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_FILTER (MAP_CHAR_LEN("FooterBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_URL (MAP_CHAR_LEN("BackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_FILTER (MAP_CHAR_LEN("BackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_LOCATION (MAP_CHAR_LEN("BackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_BITMAP (MAP_CHAR_LEN("BackGraphicBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_URL (MAP_CHAR_LEN("GraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_FILTER (MAP_CHAR_LEN("GraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_LOCATION (MAP_CHAR_LEN("GraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_SIZE (MAP_CHAR_LEN("GraphicSize"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_BITMAP (MAP_CHAR_LEN("GraphicBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_FONT (MAP_CHAR_LEN("BulletFont"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_LOCATION (MAP_CHAR_LEN("ParaBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_LOCATION (MAP_CHAR_LEN("HeaderBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_LOCATION (MAP_CHAR_LEN("FooterBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_PARA_MARGIN (MAP_CHAR_LEN("ParaLeftParaMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_PARA_MARGIN (MAP_CHAR_LEN("ParaRightParaMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_MARGIN (MAP_CHAR_LEN("ParaLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_MARGIN (MAP_CHAR_LEN("ParaRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaLeftMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaRightMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_FIRST_LINE_INDENT (MAP_CHAR_LEN("ParaFirstLineIndent"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_FIRST_LINE_INDENT_RELATIVE (MAP_CHAR_LEN("ParaFirstLineIndentRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_HYPHENATION (MAP_CHAR_LEN("ParaIsHyphenation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_LEADING_CHARS (MAP_CHAR_LEN("HyphenationMaxLeadingChars"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_TRAILING_CHARS (MAP_CHAR_LEN("HyphenationMaxTrailingChars"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_HYPHENS (MAP_CHAR_LEN("HyphenationMaxHyphens"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_MARGIN (MAP_CHAR_LEN("LeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_MARGIN (MAP_CHAR_LEN("RightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_MARGIN (MAP_CHAR_LEN("HeaderLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_MARGIN (MAP_CHAR_LEN("HeaderRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_MARGIN (MAP_CHAR_LEN("FooterLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_MARGIN (MAP_CHAR_LEN("FooterRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_RANGE (MAP_CHAR_LEN("TextRange"));
const SwPropNameLen __FAR_DATA UNO_NAME_NAME (MAP_CHAR_LEN("Name"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_ALIGNMENT (MAP_CHAR_LEN("NumberingAlignment"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_FONT_NAME (MAP_CHAR_LEN("BulletFontName"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_ID (MAP_CHAR_LEN("BulletId"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_STYLE_NAME (MAP_CHAR_LEN("CharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_CHAR_STYLE_NAME (MAP_CHAR_LEN("AnchorCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_SUFFIX (MAP_CHAR_LEN("Suffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_PREFIX (MAP_CHAR_LEN("Prefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARENT_NUMBERING (MAP_CHAR_LEN("ParentNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_START_WITH (MAP_CHAR_LEN("StartWith"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT (MAP_CHAR_LEN("CharHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME (MAP_CHAR_LEN("CharFontName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME (MAP_CHAR_LEN("CharFontStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY (MAP_CHAR_LEN("CharFontFamily"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET (MAP_CHAR_LEN("CharFontCharSet"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH (MAP_CHAR_LEN("CharFontPitch"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE (MAP_CHAR_LEN("CharPosture"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT (MAP_CHAR_LEN("CharWeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE (MAP_CHAR_LEN("CharLocale"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT_ASIAN (MAP_CHAR_LEN("CharHeightAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME_ASIAN (MAP_CHAR_LEN("CharFontNameAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME_ASIAN (MAP_CHAR_LEN("CharFontStyleNameAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY_ASIAN (MAP_CHAR_LEN("CharFontFamilyAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET_ASIAN (MAP_CHAR_LEN("CharFontCharSetAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH_ASIAN (MAP_CHAR_LEN("CharFontPitchAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE_ASIAN (MAP_CHAR_LEN("CharPostureAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT_ASIAN (MAP_CHAR_LEN("CharWeightAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE_ASIAN (MAP_CHAR_LEN("CharLocaleAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT_COMPLEX (MAP_CHAR_LEN("CharHeightComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME_COMPLEX (MAP_CHAR_LEN("CharFontNameComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME_COMPLEX (MAP_CHAR_LEN("CharFontStyleNameComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY_COMPLEX (MAP_CHAR_LEN("CharFontFamilyComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET_COMPLEX (MAP_CHAR_LEN("CharFontCharSetComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH_COMPLEX (MAP_CHAR_LEN("CharFontPitchComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE_COMPLEX (MAP_CHAR_LEN("CharPostureComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT_COMPLEX (MAP_CHAR_LEN("CharWeightComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE_COMPLEX (MAP_CHAR_LEN("CharLocaleComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_AUTO_KERNING (MAP_CHAR_LEN("CharAutoKerning"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE (MAP_CHAR_LEN("CharUnderline"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE_COLOR (MAP_CHAR_LEN("CharUnderlineColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE_HAS_COLOR (MAP_CHAR_LEN("CharUnderlineHasColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_ESCAPEMENT (MAP_CHAR_LEN("CharEscapement"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CASE_MAP (MAP_CHAR_LEN("CharCaseMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_SHADOWED (MAP_CHAR_LEN("CharShadowed"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_STRIKEOUT (MAP_CHAR_LEN("CharStrikeout"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CROSSED_OUT (MAP_CHAR_LEN("CharCrossedOut"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_NO_HYPHENATION (MAP_CHAR_LEN("CharNoHyphenation"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_AUTO_ESCAPEMENT (MAP_CHAR_LEN("CharAutoEscapement"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_PROP_FONT_HEIGHT (MAP_CHAR_LEN("CharPropFontHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_DIFF_FONT_HEIGHT (MAP_CHAR_LEN("CharDiffFontHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_ESCAPEMENT_HEIGHT (MAP_CHAR_LEN("CharEscapementHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COLOR (MAP_CHAR_LEN("CharColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FLASH (MAP_CHAR_LEN("CharFlash"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_KERNING (MAP_CHAR_LEN("CharKerning"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_BACK_COLOR (MAP_CHAR_LEN("CharBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_BACK_TRANSPARENT (MAP_CHAR_LEN("CharBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_IS_ON (MAP_CHAR_LEN("CharCombineIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_PREFIX (MAP_CHAR_LEN("CharCombinePrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_SUFFIX (MAP_CHAR_LEN("CharCombineSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_EMPHASIZE (MAP_CHAR_LEN("CharEmphasize"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_SPACING (MAP_CHAR_LEN("ParaLineSpacing"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_TOP_MARGIN (MAP_CHAR_LEN("ParaTopMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BOTTOM_MARGIN (MAP_CHAR_LEN("ParaBottomMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_TOP_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaTopMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BOTTOM_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaBottomMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_EXPAND_SINGLE_WORD (MAP_CHAR_LEN("ParaExpandSingleWord"));
const SwPropNameLen __FAR_DATA UNO_NAME_END_NOTICE (MAP_CHAR_LEN("EndNotice"));
const SwPropNameLen __FAR_DATA UNO_NAME_EMBEDDED_OBJECTS (MAP_CHAR_LEN("EmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_ALPHABETICAL_SEPARATORS (MAP_CHAR_LEN("AlphabeticalSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACKGROUND_COLOR (MAP_CHAR_LEN("BackgroundColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_BEGIN_NOTICE (MAP_CHAR_LEN("BeginNotice"));
const SwPropNameLen __FAR_DATA UNO_NAME_CASE_SENSITIVE (MAP_CHAR_LEN("CaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_FRAME_STYLE_NAME (MAP_CHAR_LEN("FrameStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_STYLE_NAME (MAP_CHAR_LEN("NumberingStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_LEVEL (MAP_CHAR_LEN("NumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_START_VALUE (MAP_CHAR_LEN("NumberingStartValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_IS_NUMBER (MAP_CHAR_LEN("NumberingIsNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_COMBINE_ENTRIES (MAP_CHAR_LEN("CombineEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_COUNT_LINES_IN_FRAMES (MAP_CHAR_LEN("CountLinesInFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_TYPE (MAP_CHAR_LEN("DDECommandType"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_FILE (MAP_CHAR_LEN("DDECommandFile"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_ELEMENT (MAP_CHAR_LEN("DDECommandElement"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTOMATIC_UPDATE (MAP_CHAR_LEN("IsAutomaticUpdate"));
const SwPropNameLen __FAR_DATA UNO_NAME_DEFAULT_TABSTOP_DISTANCE (MAP_CHAR_LEN("DefaultTabstopDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_DISTANCE (MAP_CHAR_LEN("Distance"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_FORMAT (MAP_CHAR_LEN("DropCapFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_WHOLE_WORD (MAP_CHAR_LEN("DropCapWholeWord"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_CHAR_STYLE_NAME (MAP_CHAR_LEN("DropCapCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_LINK (MAP_CHAR_LEN("FileLink"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC (MAP_CHAR_LEN("Graphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHICS (MAP_CHAR_LEN("Graphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_PROTECTED (MAP_CHAR_LEN("IsProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_KEY_AS_ENTRY (MAP_CHAR_LEN("KeyAsEntry"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_KEEP_TOGETHER (MAP_CHAR_LEN("ParaKeepTogether"));
const SwPropNameLen __FAR_DATA UNO_NAME_KEEP_TOGETHER (MAP_CHAR_LEN("KeepTogether"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_LANDSCAPE (MAP_CHAR_LEN("IsLandscape"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_TEXT (MAP_CHAR_LEN("SeparatorText"));
const SwPropNameLen __FAR_DATA UNO_NAME_MARKS (MAP_CHAR_LEN("Marks"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBER_POSITION (MAP_CHAR_LEN("NumberPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_OUTLINES (MAP_CHAR_LEN("Outlines"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_STYLE_NAME (MAP_CHAR_LEN("PageStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_STYLE_LAYOUT (MAP_CHAR_LEN("PageStyleLayout"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_STYLES (MAP_CHAR_LEN("ParaStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_ADJUST (MAP_CHAR_LEN("ParaAdjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_REGISTER_MODE_ACTIVE (MAP_CHAR_LEN("ParaRegisterModeActive"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_STYLE_NAME (MAP_CHAR_LEN("ParaStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LAST_LINE_ADJUST (MAP_CHAR_LEN("ParaLastLineAdjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_NUMBER_COUNT (MAP_CHAR_LEN("ParaLineNumberCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_NUMBER_START_VALUE (MAP_CHAR_LEN("ParaLineNumberStartValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_COLOR (MAP_CHAR_LEN("BackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BACK_COLOR (MAP_CHAR_LEN("ParaBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_WIDOWS (MAP_CHAR_LEN("ParaWidows"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_ORPHANS (MAP_CHAR_LEN("ParaOrphans"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BACK_TRANSPARENT (MAP_CHAR_LEN("ParaBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_POSITION_END_OF_DOC (MAP_CHAR_LEN("PositionEndOfDoc"));
const SwPropNameLen __FAR_DATA UNO_NAME_POSITION_PROTECTED (MAP_CHAR_LEN("PositionProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_ALTERNATIVE_TEXT (MAP_CHAR_LEN("AlternativeText"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRIMARY_KEY (MAP_CHAR_LEN("PrimaryKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_TABLES (MAP_CHAR_LEN("PrintTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_GRAPHICS (MAP_CHAR_LEN("PrintGraphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_REVERSED (MAP_CHAR_LEN("PrintReversed"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_PROSPECT (MAP_CHAR_LEN("PrintProspect"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_CONTROLS (MAP_CHAR_LEN("PrintControls"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_DRAWINGS (MAP_CHAR_LEN("PrintDrawings"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRING_RIGHT_PAGES (MAP_CHAR_LEN("PrintRightPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_BLACK_FONTS (MAP_CHAR_LEN("PrintBlackFonts"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINTER_PAPER_TRAY (MAP_CHAR_LEN("PrinterPaperTray"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_PAGE_BACKGROUND (MAP_CHAR_LEN("PrintPageBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_ANNOTATION_MODE (MAP_CHAR_LEN("PrintAnnotationMode"));
const SwPropNameLen __FAR_DATA UNO_NAME_REGISTER_MODE_ACTIVE (MAP_CHAR_LEN("RegisterModeActive"));
const SwPropNameLen __FAR_DATA UNO_NAME_RELATIVE_WIDTH (MAP_CHAR_LEN("RelativeWidth"));
const SwPropNameLen __FAR_DATA UNO_NAME_RELATIVE_HEIGHT (MAP_CHAR_LEN("RelativeHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_REPEAT_HEADLINE (MAP_CHAR_LEN("RepeatHeadline"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_STYLES (MAP_CHAR_LEN("SearchStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_BACKWARDS (MAP_CHAR_LEN("SearchBackwards"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY (MAP_CHAR_LEN("SearchSimilarity"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_IN_SELECTION (MAP_CHAR_LEN("SearchInSelection"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_CASE_SENSITIVE (MAP_CHAR_LEN("SearchCaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_ADD (MAP_CHAR_LEN("SearchSimilarityAdd"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_RELAX (MAP_CHAR_LEN("SearchSimilarityRelax"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_REMOVE (MAP_CHAR_LEN("SearchSimilarityRemove"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_REGULAR_EXPRESSION (MAP_CHAR_LEN("SearchRegularExpression"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_EXCHANGE (MAP_CHAR_LEN("SearchSimilarityExchange"));
const SwPropNameLen __FAR_DATA UNO_NAME_SECONDARY_KEY (MAP_CHAR_LEN("SecondaryKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_INTERVAL (MAP_CHAR_LEN("SeparatorInterval"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_BREAKS (MAP_CHAR_LEN("ShowBreaks"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_SPACES (MAP_CHAR_LEN("ShowSpaces"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABLES (MAP_CHAR_LEN("ShowTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_GRAPHICS (MAP_CHAR_LEN("ShowGraphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_DRAWINGS (MAP_CHAR_LEN("ShowDrawings"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABSTOPS (MAP_CHAR_LEN("ShowTabstops"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_VERT_RULER (MAP_CHAR_LEN("ShowVertRuler"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_PARA_BREAKS (MAP_CHAR_LEN("ShowParaBreaks"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HIDDEN_TEXT (MAP_CHAR_LEN("ShowHiddenText"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_ANNOTATIONS (MAP_CHAR_LEN("ShowAnnotations"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_SOFT_HYPHENS (MAP_CHAR_LEN("ShowSoftHyphens"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_VERT_SCROLL_BAR (MAP_CHAR_LEN("ShowVertScrollBar"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HORI_SCROLL_BAR (MAP_CHAR_LEN("ShowHoriScrollBar"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_FIELD_COMMANDS (MAP_CHAR_LEN("ShowFieldCommands"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TEXT_BOUNDARIES (MAP_CHAR_LEN("ShowTextBoundaries"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_PROTECTED_SPACES (MAP_CHAR_LEN("ShowProtectedSpaces"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABLE_BOUNDARIES (MAP_CHAR_LEN("ShowTableBoundaries"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HIDDEN_PARAGRAPHS (MAP_CHAR_LEN("ShowHiddenParagraphs"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_INDEX_MARK_BACKGROUND (MAP_CHAR_LEN("ShowIndexMarkBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_FOOTNOTE_BACKGROUND (MAP_CHAR_LEN("ShowFootnoteBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TEXT_FIELD_BACKGROUND (MAP_CHAR_LEN("ShowTextFieldBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_RELATIVE (MAP_CHAR_LEN("SizeRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_PROTECTED (MAP_CHAR_LEN("SizeProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_SMOOTH_SCROLLING (MAP_CHAR_LEN("SmoothScrolling"));
const SwPropNameLen __FAR_DATA UNO_NAME_SOLID_MARK_HANDLES (MAP_CHAR_LEN("SolidMarkHandles"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLES (MAP_CHAR_LEN("Tables"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FRAMES (MAP_CHAR_LEN("TextFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_COLUMNS (MAP_CHAR_LEN("TextColumns"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_TRANSPARENT (MAP_CHAR_LEN("BackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_PP (MAP_CHAR_LEN("UsePP"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_METRIC (MAP_CHAR_LEN("UserMetric"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_TYPE (MAP_CHAR_LEN("AnchorType"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_TYPES (MAP_CHAR_LEN("AnchorTypes"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_PAGE_NO (MAP_CHAR_LEN("AnchorPageNo"));
const SwPropNameLen __FAR_DATA UNO_NAME_AUTHOR (MAP_CHAR_LEN("Author"));
const SwPropNameLen __FAR_DATA UNO_NAME_BREAK_TYPE (MAP_CHAR_LEN("BreakType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAIN_NEXT_NAME (MAP_CHAR_LEN("ChainNextName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAIN_PREV_NAME (MAP_CHAR_LEN("ChainPrevName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAPTER_FORMAT (MAP_CHAR_LEN("ChapterFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_CLIENT_MAP (MAP_CHAR_LEN("ClientMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONDITION (MAP_CHAR_LEN("Condition"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT (MAP_CHAR_LEN("Content"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CONTOURED (MAP_CHAR_LEN("CharContoured"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTOUR_OUTSIDE (MAP_CHAR_LEN("ContourOutside"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT_PROTECTED (MAP_CHAR_LEN("ContentProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_COUNT_EMPTY_LINES (MAP_CHAR_LEN("CountEmptyLines"));
const SwPropNameLen __FAR_DATA UNO_NAME_RESTART_AT_EACH_PAGE (MAP_CHAR_LEN("RestartAtEachPage"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_BASE_NAME (MAP_CHAR_LEN("DataBaseName"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_TABLE_NAME (MAP_CHAR_LEN("DataTableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_COLUMN_NAME (MAP_CHAR_LEN("DataColumnName"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_DATA_BASE_FORMAT (MAP_CHAR_LEN("DataBaseFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATE (MAP_CHAR_LEN("Date"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_DATE (MAP_CHAR_LEN("IsDate"));
const SwPropNameLen __FAR_DATA UNO_NAME_EDIT_IN_READONLY (MAP_CHAR_LEN("EditInReadonly"));
const SwPropNameLen __FAR_DATA UNO_NAME_FALSE_CONTENT (MAP_CHAR_LEN("FalseContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_FORMAT (MAP_CHAR_LEN("FileFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_FIXED (MAP_CHAR_LEN("IsFixed"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_COUNTING (MAP_CHAR_LEN("FootnoteCounting"));
const SwPropNameLen __FAR_DATA UNO_NAME_FORMULA (MAP_CHAR_LEN("Formula"));
const SwPropNameLen __FAR_DATA UNO_NAME_FRAME_NAME (MAP_CHAR_LEN("FrameName"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_NAME (MAP_CHAR_LEN("GraphicName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FULL_NAME (MAP_CHAR_LEN("FullName"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEIGHT (MAP_CHAR_LEN("Height"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTO_HEIGHT (MAP_CHAR_LEN("IsAutoHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_TYPE (MAP_CHAR_LEN("SizeType"));
const SwPropNameLen __FAR_DATA UNO_NAME_HINT (MAP_CHAR_LEN("Hint"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT (MAP_CHAR_LEN("HoriOrient"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_MIRRORED_ON_EVEN_PAGES (MAP_CHAR_LEN("HoriMirroredOnEvenPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_MIRRORED_ON_ODD_PAGES (MAP_CHAR_LEN("HoriMirroredOnOddPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT_RELATION (MAP_CHAR_LEN("HoriOrientRelation"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT_POSITION (MAP_CHAR_LEN("HoriOrientPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_U_R_L (MAP_CHAR_LEN("HyperLinkURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_TARGET (MAP_CHAR_LEN("HyperLinkTarget"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_NAME (MAP_CHAR_LEN("HyperLinkName"));
const SwPropNameLen __FAR_DATA UNO_NAME_INFO_TYPE (MAP_CHAR_LEN("InfoType"));
const SwPropNameLen __FAR_DATA UNO_NAME_INFO_FORMAT (MAP_CHAR_LEN("InfoFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_INPUT (MAP_CHAR_LEN("Input"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL (MAP_CHAR_LEN("Level"));
const SwPropNameLen __FAR_DATA UNO_NAME_INTERVAL (MAP_CHAR_LEN("Interval"));
const SwPropNameLen __FAR_DATA UNO_NAME_LINK_REGION (MAP_CHAR_LEN("LinkRegion"));
const SwPropNameLen __FAR_DATA UNO_NAME_MACRO (MAP_CHAR_LEN("Macro"));
const SwPropNameLen __FAR_DATA UNO_NAME_SPLIT (MAP_CHAR_LEN("Split"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_SPLIT (MAP_CHAR_LEN("ParaSplit"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBER_FORMAT (MAP_CHAR_LEN("NumberFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_TYPE (MAP_CHAR_LEN("NumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_RULES (MAP_CHAR_LEN("NumberingRules"));
const SwPropNameLen __FAR_DATA UNO_NAME_OFFSET (MAP_CHAR_LEN("Offset"));
const SwPropNameLen __FAR_DATA UNO_NAME_ON (MAP_CHAR_LEN("On"));
const SwPropNameLen __FAR_DATA UNO_NAME_OPAQUE (MAP_CHAR_LEN("Opaque"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_TOGGLE (MAP_CHAR_LEN("PageToggle"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_DESC_NAME (MAP_CHAR_LEN("PageDescName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_NUMBER_OFFSET (MAP_CHAR_LEN("PageNumberOffset"));
const SwPropNameLen __FAR_DATA UNO_NAME_PLACEHOLDER (MAP_CHAR_LEN("PlaceHolder"));
const SwPropNameLen __FAR_DATA UNO_NAME_PLACEHOLDER_TYPE (MAP_CHAR_LEN("PlaceHolderType"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT (MAP_CHAR_LEN("Print"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_LEFT_PAGES (MAP_CHAR_LEN("PrintLeftPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_FIELD_PART (MAP_CHAR_LEN("ReferenceFieldPart"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_FIELD_SOURCE (MAP_CHAR_LEN("ReferenceFieldSource"));
const SwPropNameLen __FAR_DATA UNO_NAME_REGISTER_PARAGRAPH_STYLE (MAP_CHAR_LEN("RegisterParagraphStyle"));
const SwPropNameLen __FAR_DATA UNO_NAME_SCRIPT_TYPE (MAP_CHAR_LEN("ScriptType"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_ALL (MAP_CHAR_LEN("SearchAll"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_WORDS (MAP_CHAR_LEN("SearchWords"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEQUENCE_VALUE (MAP_CHAR_LEN("SequenceValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_SERVER_MAP (MAP_CHAR_LEN("ServerMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_SET_NUMBER (MAP_CHAR_LEN("SetNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHADOW_FORMAT (MAP_CHAR_LEN("ShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HORI_RULER (MAP_CHAR_LEN("ShowHoriRuler"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE (MAP_CHAR_LEN("Size"));
const SwPropNameLen __FAR_DATA UNO_NAME_ACTUAL_SIZE (MAP_CHAR_LEN("ActualSize"));
const SwPropNameLen __FAR_DATA UNO_NAME_SOURCE_NAME (MAP_CHAR_LEN("SourceName"));
const SwPropNameLen __FAR_DATA UNO_NAME_START_AT (MAP_CHAR_LEN("StartAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_STATISTIC_TYPE_ID (MAP_CHAR_LEN("StatisticTypeId"));
const SwPropNameLen __FAR_DATA UNO_NAME_SUB_TYPE (MAP_CHAR_LEN("SubType"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND (MAP_CHAR_LEN("Surround"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_EXPRESSION (MAP_CHAR_LEN("IsExpression"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SHOW_FORMULA (MAP_CHAR_LEN("IsShowFormula"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_WRAP (MAP_CHAR_LEN("TextWrap"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND_CONTOUR (MAP_CHAR_LEN("SurroundContour"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND_ANCHORONLY (MAP_CHAR_LEN("SurroundAnchorOnly"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_NAME (MAP_CHAR_LEN("TableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABSTOPS (MAP_CHAR_LEN("ParaTabStops"));
const SwPropNameLen __FAR_DATA UNO_NAME_TITLE (MAP_CHAR_LEN("Title"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_MARGIN (MAP_CHAR_LEN("TopMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_MARGIN (MAP_CHAR_LEN("BottomMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_TRUE_CONTENT (MAP_CHAR_LEN("TrueContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_URL_CONTENT (MAP_CHAR_LEN("URLContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_USERTEXT (MAP_CHAR_LEN("UserText"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_DATA_TYPE (MAP_CHAR_LEN("UserDataType"));
const SwPropNameLen __FAR_DATA UNO_NAME_VALUE (MAP_CHAR_LEN("Value"));
const SwPropNameLen __FAR_DATA UNO_NAME_VARIABLE_NAME (MAP_CHAR_LEN("VariableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_VARIABLE_SUBTYPE (MAP_CHAR_LEN("VariableSubtype"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT (MAP_CHAR_LEN("VertOrient"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_MIRRORED (MAP_CHAR_LEN("VertMirrored"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT_POSITION (MAP_CHAR_LEN("VertOrientPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT_RELATION (MAP_CHAR_LEN("VertOrientRelation"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_VISIBLE (MAP_CHAR_LEN("IsVisible"));
const SwPropNameLen __FAR_DATA UNO_NAME_WIDTH (MAP_CHAR_LEN("Width"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_MODE (MAP_CHAR_LEN("CharWordMode"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_CROP (MAP_CHAR_LEN("GraphicCrop"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHARACTER_FORMAT_NONE (MAP_CHAR_LEN("CharacterFormatNone"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_POSITION (MAP_CHAR_LEN("TextPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX_MARK (MAP_CHAR_LEN("DocumentIndexMark"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX (MAP_CHAR_LEN("DocumentIndex"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FIELD (MAP_CHAR_LEN("TextField"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOOKMARK (MAP_CHAR_LEN("Bookmark"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_TABLE (MAP_CHAR_LEN("TextTable"));
const SwPropNameLen __FAR_DATA UNO_NAME_CELL (MAP_CHAR_LEN("Cell"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FRAME (MAP_CHAR_LEN("TextFrame"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_MARK (MAP_CHAR_LEN("ReferenceMark"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_SECTION (MAP_CHAR_LEN("TextSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE (MAP_CHAR_LEN("Footnote"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE (MAP_CHAR_LEN("Endnote"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHART_ROW_AS_LABEL (MAP_CHAR_LEN("ChartRowAsLabel"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHART_COLUMN_AS_LABEL (MAP_CHAR_LEN("ChartColumnAsLabel"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMS (MAP_CHAR_LEN("TableColumns"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_BORDER (MAP_CHAR_LEN("LeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_BORDER (MAP_CHAR_LEN("RightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_BORDER (MAP_CHAR_LEN("TopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_BORDER (MAP_CHAR_LEN("BottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_BORDER_DISTANCE (MAP_CHAR_LEN("BorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("LeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("RightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("TopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("BottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_BORDER (MAP_CHAR_LEN("TableBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMN_SEPARATORS (MAP_CHAR_LEN("TableColumnSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMN_RELATIVE_SUM (MAP_CHAR_LEN("TableColumnRelativeSum"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT (MAP_CHAR_LEN("HeaderText"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT_LEFT (MAP_CHAR_LEN("HeaderTextLeft"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT_RIGHT (MAP_CHAR_LEN("HeaderTextRight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT (MAP_CHAR_LEN("FooterText"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT_LEFT (MAP_CHAR_LEN("FooterTextLeft"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT_RIGHT (MAP_CHAR_LEN("FooterTextRight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BACK_COLOR (MAP_CHAR_LEN("HeaderBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC (MAP_CHAR_LEN("HeaderBackGraphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BACK_TRANSPARENT (MAP_CHAR_LEN("HeaderBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_BORDER (MAP_CHAR_LEN("HeaderLeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_BORDER (MAP_CHAR_LEN("HeaderRightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TOP_BORDER (MAP_CHAR_LEN("HeaderTopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BOTTOM_BORDER (MAP_CHAR_LEN("HeaderBottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_SHADOW_FORMAT (MAP_CHAR_LEN("HeaderShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BODY_DISTANCE (MAP_CHAR_LEN("HeaderBodyDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_DYNAMIC_HEIGHT (MAP_CHAR_LEN("HeaderIsDynamicHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_SHARED (MAP_CHAR_LEN("HeaderIsShared"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_HEIGHT (MAP_CHAR_LEN("HeaderHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_ON (MAP_CHAR_LEN("HeaderIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BACK_COLOR (MAP_CHAR_LEN("FooterBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC (MAP_CHAR_LEN("FooterBackGraphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BACK_TRANSPARENT (MAP_CHAR_LEN("FooterBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_BORDER (MAP_CHAR_LEN("FooterLeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_BORDER (MAP_CHAR_LEN("FooterRightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TOP_BORDER (MAP_CHAR_LEN("FooterTopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BOTTOM_BORDER (MAP_CHAR_LEN("FooterBottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BORDER_DISTANCE (MAP_CHAR_LEN("FooterBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_SHADOW_FORMAT (MAP_CHAR_LEN("FooterShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BODY_DISTANCE (MAP_CHAR_LEN("FooterBodyDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_DYNAMIC_HEIGHT (MAP_CHAR_LEN("FooterIsDynamicHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_SHARED (MAP_CHAR_LEN("FooterIsShared"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_HEIGHT (MAP_CHAR_LEN("FooterHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_ON (MAP_CHAR_LEN("FooterIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_OVERWRITE_STYLES (MAP_CHAR_LEN("OverwriteStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_NUMBERING_STYLES (MAP_CHAR_LEN("LoadNumberingStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_PAGE_STYLES (MAP_CHAR_LEN("LoadPageStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_FRAME_STYLES (MAP_CHAR_LEN("LoadFrameStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_TEXT_STYLES (MAP_CHAR_LEN("LoadTextStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_NAME (MAP_CHAR_LEN("FileName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILTER_NAME (MAP_CHAR_LEN("FilterName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILTER_OPTION (MAP_CHAR_LEN("FilterOption"));
const SwPropNameLen __FAR_DATA UNO_NAME_PASSWORD (MAP_CHAR_LEN("Password"));
const SwPropNameLen __FAR_DATA UNO_NAME_COPY_COUNT (MAP_CHAR_LEN("CopyCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_COLLATE (MAP_CHAR_LEN("Collate"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT (MAP_CHAR_LEN("Sort"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGES (MAP_CHAR_LEN("Pages"));
const SwPropNameLen __FAR_DATA UNO_NAME_FIRST_LINE_OFFSET (MAP_CHAR_LEN("FirstLineOffset"));
const SwPropNameLen __FAR_DATA UNO_NAME_SYMBOL_TEXT_DISTANCE (MAP_CHAR_LEN("SymbolTextDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_INDEX_NAME (MAP_CHAR_LEN("UserIndexName"));
const SwPropNameLen __FAR_DATA UNO_NAME_REVISION (MAP_CHAR_LEN("Revision"));
const SwPropNameLen __FAR_DATA UNO_NAME_UNVISITED_CHAR_STYLE_NAME (MAP_CHAR_LEN("UnvisitedCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_VISITED_CHAR_STYLE_NAME (MAP_CHAR_LEN("VisitedCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARAGRAPH_COUNT (MAP_CHAR_LEN("ParagraphCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_COUNT (MAP_CHAR_LEN("WordCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_SEPARATOR (MAP_CHAR_LEN("WordSeparator"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHARACTER_COUNT (MAP_CHAR_LEN("CharacterCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_ZOOM_VALUE (MAP_CHAR_LEN("ZoomValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_ZOOM_TYPE (MAP_CHAR_LEN("ZoomType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_MARKS (MAP_CHAR_LEN("CreateFromMarks"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_OUTLINE (MAP_CHAR_LEN("CreateFromOutline"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARAGRAPH_STYLE_NAMES (MAP_CHAR_LEN("ParagraphStyleNames"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_CHAPTER (MAP_CHAR_LEN("CreateFromChapter"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_LABELS (MAP_CHAR_LEN("CreateFromLabels"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_ALPHABETICAL_SEPARATORS (MAP_CHAR_LEN("UseAlphabeticalSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_KEY_AS_ENTRY (MAP_CHAR_LEN("UseKeyAsEntry"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_COMBINED_ENTRIES (MAP_CHAR_LEN("UseCombinedEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_CASE_SENSITIVE (MAP_CHAR_LEN("IsCaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_P_P (MAP_CHAR_LEN("UsePP"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_DASH (MAP_CHAR_LEN("UseDash"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_UPPER_CASE (MAP_CHAR_LEN("UseUpperCase"));
const SwPropNameLen __FAR_DATA UNO_NAME_LABEL_CATEGORY (MAP_CHAR_LEN("LabelCategory"));
const SwPropNameLen __FAR_DATA UNO_NAME_LABEL_DISPLAY_TYPE (MAP_CHAR_LEN("LabelDisplayType"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_LEVEL_FROM_SOURCE (MAP_CHAR_LEN("UseLevelFromSource"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL_FORMAT (MAP_CHAR_LEN("LevelFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL_PARAGRAPH_STYLES (MAP_CHAR_LEN("LevelParagraphStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_RECALC_TAB_STOPS (MAP_CHAR_LEN("RecalcTabStops"));
const SwPropNameLen __FAR_DATA UNO_NAME_MAIN_ENTRY_CHARACTER_STYLE_NAME (MAP_CHAR_LEN("MainEntryCharacterStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_TABLES (MAP_CHAR_LEN("CreateFromTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_TEXT_FRAMES (MAP_CHAR_LEN("CreateFromTextFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_GRAPHIC_OBJECTS (MAP_CHAR_LEN("CreateFromGraphicObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_EMBEDDED_OBJECTS (MAP_CHAR_LEN("CreateFromEmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_MATH (MAP_CHAR_LEN("CreateFromStarMath"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_CHART (MAP_CHAR_LEN("CreateFromStarChart"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_CALC (MAP_CHAR_LEN("CreateFromStarCalc"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_DRAW (MAP_CHAR_LEN("CreateFromStarDraw"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_OTHER_EMBEDDED_OBJECTS (MAP_CHAR_LEN("CreateFromOtherEmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_INDEX_AUTO_MARK_FILE_U_R_L (MAP_CHAR_LEN("IndexAutoMarkFileURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_COMMA_SEPARATED (MAP_CHAR_LEN("IsCommaSeparated"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_RELATIVE_TABSTOPS (MAP_CHAR_LEN("IsRelativeTabstops"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_LEVEL_PARAGRAPH_STYLES (MAP_CHAR_LEN("CreateFromLevelParagraphStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_CHANGES (MAP_CHAR_LEN("ShowChanges"));
const SwPropNameLen __FAR_DATA UNO_NAME_RECORD_CHANGES (MAP_CHAR_LEN("RecordChanges"));
const SwPropNameLen __FAR_DATA UNO_LINK_DISPLAY_NAME (MAP_CHAR_LEN("LinkDisplayName"));
const SwPropNameLen __FAR_DATA UNO_LINK_DISPLAY_BITMAP (MAP_CHAR_LEN("LinkDisplayBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADING_STYLE_NAME (MAP_CHAR_LEN("HeadingStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_ONLINE_LAYOUT (MAP_CHAR_LEN("ShowOnlineLayout"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("UserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("TextUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_PATH (MAP_CHAR_LEN("FilePath"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_CHAPTER_NUMBERING_LEVEL (MAP_CHAR_LEN("ParaChapterNumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_CONDITIONAL_STYLE_NAME (MAP_CHAR_LEN("ParaConditionalStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAPTER_NUMBERING_LEVEL (MAP_CHAR_LEN("ChapterNumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_SEPARATOR (MAP_CHAR_LEN("NumberingSeparator"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_CONTINUOUS_NUMBERING (MAP_CHAR_LEN("IsContinuousNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTOMATIC (MAP_CHAR_LEN("IsAutomatic"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_ABSOLUTE_MARGINS (MAP_CHAR_LEN("IsAbsoluteMargins"));
const SwPropNameLen __FAR_DATA UNO_NAME_CATEGORY (MAP_CHAR_LEN("Category"));
const SwPropNameLen __FAR_DATA UNO_NAME_DEPENDENT_TEXT_FIELDS (MAP_CHAR_LEN("DependentTextFields"));
const SwPropNameLen __FAR_DATA UNO_NAME_CURRENT_PRESENTATION (MAP_CHAR_LEN("CurrentPresentation"));
const SwPropNameLen __FAR_DATA UNO_NAME_ADJUST (MAP_CHAR_LEN("Adjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_PORTION_TYPE (MAP_CHAR_LEN("TextPortionType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTROL_CHARACTER (MAP_CHAR_LEN("ControlCharacter"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_COLLAPSED (MAP_CHAR_LEN("IsCollapsed"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_START (MAP_CHAR_LEN("IsStart"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEQUENCE_NUMBER (MAP_CHAR_LEN("SequenceNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_ID (MAP_CHAR_LEN("ReferenceId"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderLeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderRightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderTopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderBottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("HeaderUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("FooterLeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("FooterRightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("FooterTopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("FooterBottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("FooterUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_NUMBERING_RESTART (MAP_CHAR_LEN("ParaIsNumberingRestart"));
const SwPropNameLen __FAR_DATA UNO_NAME_HIDE_FIELD_TIPS (MAP_CHAR_LEN("HideFieldTips"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_SHADOW_FORMAT (MAP_CHAR_LEN("ParaShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTOUR_POLY_POLYGON (MAP_CHAR_LEN("ContourPolyPolygon"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_WIDTH (MAP_CHAR_LEN("SeparatorLineWidth"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_COLOR (MAP_CHAR_LEN("SeparatorLineColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_RELATIVE_HEIGHT (MAP_CHAR_LEN("SeparatorLineRelativeHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_VERTIVAL_ALIGNMENT (MAP_CHAR_LEN("SeparatorLineVerticalAlignment"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_IS_ON (MAP_CHAR_LEN("SeparatorLineIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SKIP_HIDDEN_TEXT (MAP_CHAR_LEN("IsSkipHiddenText"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SKIP_PROTECTED_TEXT (MAP_CHAR_LEN("IsSkipProtectedText"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX_MARKS (MAP_CHAR_LEN("DocumentIndexMarks"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_COLLECT_AT_TEXT_END (MAP_CHAR_LEN("FootnoteIsCollectAtTextEnd"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_RESTART_NUMBERING (MAP_CHAR_LEN("FootnoteIsRestartNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_RESTART_NUMBERING_AT (MAP_CHAR_LEN("FootnoteRestartNumberingAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_OWN_NUMBERING (MAP_CHAR_LEN("FootnoteIsOwnNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_TYPE (MAP_CHAR_LEN("FootnoteNumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_PREFIX (MAP_CHAR_LEN("FootnoteNumberingPrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_SUFFIX (MAP_CHAR_LEN("FootnoteNumberingSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_COLLECT_AT_TEXT_END (MAP_CHAR_LEN("EndnoteIsCollectAtTextEnd"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_RESTART_NUMBERING (MAP_CHAR_LEN("EndnoteIsRestartNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_RESTART_NUMBERING_AT (MAP_CHAR_LEN("EndnoteRestartNumberingAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_OWN_NUMBERING (MAP_CHAR_LEN("EndnoteIsOwnNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_TYPE (MAP_CHAR_LEN("EndnoteNumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_PREFIX (MAP_CHAR_LEN("EndnoteNumberingPrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_SUFFIX (MAP_CHAR_LEN("EndnoteNumberingSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_BRACKET_BEFORE (MAP_CHAR_LEN("BracketBefore"));
const SwPropNameLen __FAR_DATA UNO_NAME_BRACKET_AFTER (MAP_CHAR_LEN("BracketAfter"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_NUMBER_ENTRIES (MAP_CHAR_LEN("IsNumberEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SORT_BY_POSITION (MAP_CHAR_LEN("IsSortByPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT_KEYS (MAP_CHAR_LEN("SortKeys"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SORT_ASCENDING (MAP_CHAR_LEN("IsSortAscending"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT_KEY (MAP_CHAR_LEN("SortKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_FIELDS (MAP_CHAR_LEN("Fields"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATE_TIME_VALUE (MAP_CHAR_LEN("DateTimeValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_ON (MAP_CHAR_LEN("IsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_Z_ORDER (MAP_CHAR_LEN("ZOrder"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT_SECTION (MAP_CHAR_LEN("ContentSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_SECTION (MAP_CHAR_LEN("HeaderSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_HANGING_PUNCTUATION (MAP_CHAR_LEN("ParaIsHangingPunctuation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_CHARACTER_DISTANCE (MAP_CHAR_LEN("ParaIsCharacterDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_FORBIDDEN_RULES (MAP_CHAR_LEN("ParaIsForbiddenRules"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_MAIN_ENTRY (MAP_CHAR_LEN("IsMainEntry"));
#82036# graphic attributes added to the API
/*************************************************************************
*
* $RCSfile: unoprnms.cxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: os $ $Date: 2000-12-14 10:05:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
//#define MAP_CHAR_LEN(cchar) cchar, sizeof(cchar) - 1
//struct SwPropNameLen
//{
// const char* pName;
// USHORT nNameLen;
//};
//extern const SwPropNameLen UNO_NAME_FOLLOW_STYLE;
const SwPropNameLen __FAR_DATA UNO_NAME_FOLLOW_STYLE(MAP_CHAR_LEN("FollowStyle"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_PHYSICAL (MAP_CHAR_LEN("IsPhysical"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTO_UPDATE (MAP_CHAR_LEN("IsAutoUpdate"));
const SwPropNameLen __FAR_DATA UNO_NAME_DISPLAY_NAME (MAP_CHAR_LEN("DisplayName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_URL (MAP_CHAR_LEN("ParaBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_FILTER (MAP_CHAR_LEN("ParaBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_URL (MAP_CHAR_LEN("HeaderBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_FILTER (MAP_CHAR_LEN("HeaderBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_URL (MAP_CHAR_LEN("FooterBackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_FILTER (MAP_CHAR_LEN("FooterBackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_URL (MAP_CHAR_LEN("BackGraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_FILTER (MAP_CHAR_LEN("BackGraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_LOCATION (MAP_CHAR_LEN("BackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_GRAPHIC_BITMAP (MAP_CHAR_LEN("BackGraphicBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_URL (MAP_CHAR_LEN("GraphicURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_FILTER (MAP_CHAR_LEN("GraphicFilter"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_LOCATION (MAP_CHAR_LEN("GraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_SIZE (MAP_CHAR_LEN("GraphicSize"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_BITMAP (MAP_CHAR_LEN("GraphicBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_FONT (MAP_CHAR_LEN("BulletFont"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_GRAPHIC_LOCATION (MAP_CHAR_LEN("ParaBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC_LOCATION (MAP_CHAR_LEN("HeaderBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC_LOCATION (MAP_CHAR_LEN("FooterBackGraphicLocation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_PARA_MARGIN (MAP_CHAR_LEN("ParaLeftParaMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_PARA_MARGIN (MAP_CHAR_LEN("ParaRightParaMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_MARGIN (MAP_CHAR_LEN("ParaLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_MARGIN (MAP_CHAR_LEN("ParaRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LEFT_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaLeftMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_RIGHT_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaRightMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_FIRST_LINE_INDENT (MAP_CHAR_LEN("ParaFirstLineIndent"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_FIRST_LINE_INDENT_RELATIVE (MAP_CHAR_LEN("ParaFirstLineIndentRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_HYPHENATION (MAP_CHAR_LEN("ParaIsHyphenation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_LEADING_CHARS (MAP_CHAR_LEN("HyphenationMaxLeadingChars"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_TRAILING_CHARS (MAP_CHAR_LEN("HyphenationMaxTrailingChars"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_HYPHENATION_MAX_HYPHENS (MAP_CHAR_LEN("HyphenationMaxHyphens"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_MARGIN (MAP_CHAR_LEN("LeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_MARGIN (MAP_CHAR_LEN("RightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_MARGIN (MAP_CHAR_LEN("HeaderLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_MARGIN (MAP_CHAR_LEN("HeaderRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_MARGIN (MAP_CHAR_LEN("FooterLeftMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_MARGIN (MAP_CHAR_LEN("FooterRightMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_RANGE (MAP_CHAR_LEN("TextRange"));
const SwPropNameLen __FAR_DATA UNO_NAME_NAME (MAP_CHAR_LEN("Name"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_ALIGNMENT (MAP_CHAR_LEN("NumberingAlignment"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_FONT_NAME (MAP_CHAR_LEN("BulletFontName"));
const SwPropNameLen __FAR_DATA UNO_NAME_BULLET_ID (MAP_CHAR_LEN("BulletId"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_STYLE_NAME (MAP_CHAR_LEN("CharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_CHAR_STYLE_NAME (MAP_CHAR_LEN("AnchorCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_SUFFIX (MAP_CHAR_LEN("Suffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_PREFIX (MAP_CHAR_LEN("Prefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARENT_NUMBERING (MAP_CHAR_LEN("ParentNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_START_WITH (MAP_CHAR_LEN("StartWith"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT (MAP_CHAR_LEN("CharHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME (MAP_CHAR_LEN("CharFontName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME (MAP_CHAR_LEN("CharFontStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY (MAP_CHAR_LEN("CharFontFamily"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET (MAP_CHAR_LEN("CharFontCharSet"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH (MAP_CHAR_LEN("CharFontPitch"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE (MAP_CHAR_LEN("CharPosture"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT (MAP_CHAR_LEN("CharWeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE (MAP_CHAR_LEN("CharLocale"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT_ASIAN (MAP_CHAR_LEN("CharHeightAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME_ASIAN (MAP_CHAR_LEN("CharFontNameAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME_ASIAN (MAP_CHAR_LEN("CharFontStyleNameAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY_ASIAN (MAP_CHAR_LEN("CharFontFamilyAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET_ASIAN (MAP_CHAR_LEN("CharFontCharSetAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH_ASIAN (MAP_CHAR_LEN("CharFontPitchAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE_ASIAN (MAP_CHAR_LEN("CharPostureAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT_ASIAN (MAP_CHAR_LEN("CharWeightAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE_ASIAN (MAP_CHAR_LEN("CharLocaleAsian"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_HEIGHT_COMPLEX (MAP_CHAR_LEN("CharHeightComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_NAME_COMPLEX (MAP_CHAR_LEN("CharFontNameComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_STYLE_NAME_COMPLEX (MAP_CHAR_LEN("CharFontStyleNameComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_FAMILY_COMPLEX (MAP_CHAR_LEN("CharFontFamilyComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_CHAR_SET_COMPLEX (MAP_CHAR_LEN("CharFontCharSetComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FONT_PITCH_COMPLEX (MAP_CHAR_LEN("CharFontPitchComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_POSTURE_COMPLEX (MAP_CHAR_LEN("CharPostureComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_WEIGHT_COMPLEX (MAP_CHAR_LEN("CharWeightComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_LOCALE_COMPLEX (MAP_CHAR_LEN("CharLocaleComplex"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_AUTO_KERNING (MAP_CHAR_LEN("CharAutoKerning"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE (MAP_CHAR_LEN("CharUnderline"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE_COLOR (MAP_CHAR_LEN("CharUnderlineColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_UNDERLINE_HAS_COLOR (MAP_CHAR_LEN("CharUnderlineHasColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_ESCAPEMENT (MAP_CHAR_LEN("CharEscapement"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CASE_MAP (MAP_CHAR_LEN("CharCaseMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_SHADOWED (MAP_CHAR_LEN("CharShadowed"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_STRIKEOUT (MAP_CHAR_LEN("CharStrikeout"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CROSSED_OUT (MAP_CHAR_LEN("CharCrossedOut"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_NO_HYPHENATION (MAP_CHAR_LEN("CharNoHyphenation"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_AUTO_ESCAPEMENT (MAP_CHAR_LEN("CharAutoEscapement"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_PROP_FONT_HEIGHT (MAP_CHAR_LEN("CharPropFontHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_DIFF_FONT_HEIGHT (MAP_CHAR_LEN("CharDiffFontHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_ESCAPEMENT_HEIGHT (MAP_CHAR_LEN("CharEscapementHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COLOR (MAP_CHAR_LEN("CharColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_FLASH (MAP_CHAR_LEN("CharFlash"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_KERNING (MAP_CHAR_LEN("CharKerning"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_BACK_COLOR (MAP_CHAR_LEN("CharBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_BACK_TRANSPARENT (MAP_CHAR_LEN("CharBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_IS_ON (MAP_CHAR_LEN("CharCombineIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_PREFIX (MAP_CHAR_LEN("CharCombinePrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_COMBINE_SUFFIX (MAP_CHAR_LEN("CharCombineSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_EMPHASIZE (MAP_CHAR_LEN("CharEmphasize"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_SPACING (MAP_CHAR_LEN("ParaLineSpacing"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_TOP_MARGIN (MAP_CHAR_LEN("ParaTopMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BOTTOM_MARGIN (MAP_CHAR_LEN("ParaBottomMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_TOP_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaTopMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BOTTOM_MARGIN_RELATIVE (MAP_CHAR_LEN("ParaBottomMarginRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_EXPAND_SINGLE_WORD (MAP_CHAR_LEN("ParaExpandSingleWord"));
const SwPropNameLen __FAR_DATA UNO_NAME_END_NOTICE (MAP_CHAR_LEN("EndNotice"));
const SwPropNameLen __FAR_DATA UNO_NAME_EMBEDDED_OBJECTS (MAP_CHAR_LEN("EmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_ALPHABETICAL_SEPARATORS (MAP_CHAR_LEN("AlphabeticalSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACKGROUND_COLOR (MAP_CHAR_LEN("BackgroundColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_BEGIN_NOTICE (MAP_CHAR_LEN("BeginNotice"));
const SwPropNameLen __FAR_DATA UNO_NAME_CASE_SENSITIVE (MAP_CHAR_LEN("CaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_FRAME_STYLE_NAME (MAP_CHAR_LEN("FrameStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_STYLE_NAME (MAP_CHAR_LEN("NumberingStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_LEVEL (MAP_CHAR_LEN("NumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_START_VALUE (MAP_CHAR_LEN("NumberingStartValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_IS_NUMBER (MAP_CHAR_LEN("NumberingIsNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_COMBINE_ENTRIES (MAP_CHAR_LEN("CombineEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_COUNT_LINES_IN_FRAMES (MAP_CHAR_LEN("CountLinesInFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_TYPE (MAP_CHAR_LEN("DDECommandType"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_FILE (MAP_CHAR_LEN("DDECommandFile"));
const SwPropNameLen __FAR_DATA UNO_NAME_DDE_COMMAND_ELEMENT (MAP_CHAR_LEN("DDECommandElement"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTOMATIC_UPDATE (MAP_CHAR_LEN("IsAutomaticUpdate"));
const SwPropNameLen __FAR_DATA UNO_NAME_DEFAULT_TABSTOP_DISTANCE (MAP_CHAR_LEN("DefaultTabstopDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_DISTANCE (MAP_CHAR_LEN("Distance"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_FORMAT (MAP_CHAR_LEN("DropCapFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_WHOLE_WORD (MAP_CHAR_LEN("DropCapWholeWord"));
const SwPropNameLen __FAR_DATA UNO_NAME_DROP_CAP_CHAR_STYLE_NAME (MAP_CHAR_LEN("DropCapCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_LINK (MAP_CHAR_LEN("FileLink"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC (MAP_CHAR_LEN("Graphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHICS (MAP_CHAR_LEN("Graphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_PROTECTED (MAP_CHAR_LEN("IsProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_KEY_AS_ENTRY (MAP_CHAR_LEN("KeyAsEntry"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_KEEP_TOGETHER (MAP_CHAR_LEN("ParaKeepTogether"));
const SwPropNameLen __FAR_DATA UNO_NAME_KEEP_TOGETHER (MAP_CHAR_LEN("KeepTogether"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_LANDSCAPE (MAP_CHAR_LEN("IsLandscape"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_TEXT (MAP_CHAR_LEN("SeparatorText"));
const SwPropNameLen __FAR_DATA UNO_NAME_MARKS (MAP_CHAR_LEN("Marks"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBER_POSITION (MAP_CHAR_LEN("NumberPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_OUTLINES (MAP_CHAR_LEN("Outlines"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_STYLE_NAME (MAP_CHAR_LEN("PageStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_STYLE_LAYOUT (MAP_CHAR_LEN("PageStyleLayout"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_STYLES (MAP_CHAR_LEN("ParaStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_ADJUST (MAP_CHAR_LEN("ParaAdjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_REGISTER_MODE_ACTIVE (MAP_CHAR_LEN("ParaRegisterModeActive"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_STYLE_NAME (MAP_CHAR_LEN("ParaStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LAST_LINE_ADJUST (MAP_CHAR_LEN("ParaLastLineAdjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_NUMBER_COUNT (MAP_CHAR_LEN("ParaLineNumberCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_LINE_NUMBER_START_VALUE (MAP_CHAR_LEN("ParaLineNumberStartValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_COLOR (MAP_CHAR_LEN("BackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BACK_COLOR (MAP_CHAR_LEN("ParaBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_WIDOWS (MAP_CHAR_LEN("ParaWidows"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_ORPHANS (MAP_CHAR_LEN("ParaOrphans"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_BACK_TRANSPARENT (MAP_CHAR_LEN("ParaBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_POSITION_END_OF_DOC (MAP_CHAR_LEN("PositionEndOfDoc"));
const SwPropNameLen __FAR_DATA UNO_NAME_POSITION_PROTECTED (MAP_CHAR_LEN("PositionProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_ALTERNATIVE_TEXT (MAP_CHAR_LEN("AlternativeText"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRIMARY_KEY (MAP_CHAR_LEN("PrimaryKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_TABLES (MAP_CHAR_LEN("PrintTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_GRAPHICS (MAP_CHAR_LEN("PrintGraphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_REVERSED (MAP_CHAR_LEN("PrintReversed"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_PROSPECT (MAP_CHAR_LEN("PrintProspect"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_CONTROLS (MAP_CHAR_LEN("PrintControls"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_DRAWINGS (MAP_CHAR_LEN("PrintDrawings"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRING_RIGHT_PAGES (MAP_CHAR_LEN("PrintRightPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_BLACK_FONTS (MAP_CHAR_LEN("PrintBlackFonts"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINTER_PAPER_TRAY (MAP_CHAR_LEN("PrinterPaperTray"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_PAGE_BACKGROUND (MAP_CHAR_LEN("PrintPageBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_ANNOTATION_MODE (MAP_CHAR_LEN("PrintAnnotationMode"));
const SwPropNameLen __FAR_DATA UNO_NAME_REGISTER_MODE_ACTIVE (MAP_CHAR_LEN("RegisterModeActive"));
const SwPropNameLen __FAR_DATA UNO_NAME_RELATIVE_WIDTH (MAP_CHAR_LEN("RelativeWidth"));
const SwPropNameLen __FAR_DATA UNO_NAME_RELATIVE_HEIGHT (MAP_CHAR_LEN("RelativeHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_REPEAT_HEADLINE (MAP_CHAR_LEN("RepeatHeadline"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_STYLES (MAP_CHAR_LEN("SearchStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_BACKWARDS (MAP_CHAR_LEN("SearchBackwards"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY (MAP_CHAR_LEN("SearchSimilarity"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_IN_SELECTION (MAP_CHAR_LEN("SearchInSelection"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_CASE_SENSITIVE (MAP_CHAR_LEN("SearchCaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_ADD (MAP_CHAR_LEN("SearchSimilarityAdd"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_RELAX (MAP_CHAR_LEN("SearchSimilarityRelax"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_REMOVE (MAP_CHAR_LEN("SearchSimilarityRemove"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_REGULAR_EXPRESSION (MAP_CHAR_LEN("SearchRegularExpression"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_SIMILARITY_EXCHANGE (MAP_CHAR_LEN("SearchSimilarityExchange"));
const SwPropNameLen __FAR_DATA UNO_NAME_SECONDARY_KEY (MAP_CHAR_LEN("SecondaryKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_INTERVAL (MAP_CHAR_LEN("SeparatorInterval"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_BREAKS (MAP_CHAR_LEN("ShowBreaks"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_SPACES (MAP_CHAR_LEN("ShowSpaces"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABLES (MAP_CHAR_LEN("ShowTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_GRAPHICS (MAP_CHAR_LEN("ShowGraphics"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_DRAWINGS (MAP_CHAR_LEN("ShowDrawings"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABSTOPS (MAP_CHAR_LEN("ShowTabstops"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_VERT_RULER (MAP_CHAR_LEN("ShowVertRuler"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_PARA_BREAKS (MAP_CHAR_LEN("ShowParaBreaks"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HIDDEN_TEXT (MAP_CHAR_LEN("ShowHiddenText"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_ANNOTATIONS (MAP_CHAR_LEN("ShowAnnotations"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_SOFT_HYPHENS (MAP_CHAR_LEN("ShowSoftHyphens"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_VERT_SCROLL_BAR (MAP_CHAR_LEN("ShowVertScrollBar"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HORI_SCROLL_BAR (MAP_CHAR_LEN("ShowHoriScrollBar"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_FIELD_COMMANDS (MAP_CHAR_LEN("ShowFieldCommands"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TEXT_BOUNDARIES (MAP_CHAR_LEN("ShowTextBoundaries"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_PROTECTED_SPACES (MAP_CHAR_LEN("ShowProtectedSpaces"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TABLE_BOUNDARIES (MAP_CHAR_LEN("ShowTableBoundaries"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HIDDEN_PARAGRAPHS (MAP_CHAR_LEN("ShowHiddenParagraphs"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_INDEX_MARK_BACKGROUND (MAP_CHAR_LEN("ShowIndexMarkBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_FOOTNOTE_BACKGROUND (MAP_CHAR_LEN("ShowFootnoteBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_TEXT_FIELD_BACKGROUND (MAP_CHAR_LEN("ShowTextFieldBackground"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_RELATIVE (MAP_CHAR_LEN("SizeRelative"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_PROTECTED (MAP_CHAR_LEN("SizeProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_SMOOTH_SCROLLING (MAP_CHAR_LEN("SmoothScrolling"));
const SwPropNameLen __FAR_DATA UNO_NAME_SOLID_MARK_HANDLES (MAP_CHAR_LEN("SolidMarkHandles"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLES (MAP_CHAR_LEN("Tables"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FRAMES (MAP_CHAR_LEN("TextFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_COLUMNS (MAP_CHAR_LEN("TextColumns"));
const SwPropNameLen __FAR_DATA UNO_NAME_BACK_TRANSPARENT (MAP_CHAR_LEN("BackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_PP (MAP_CHAR_LEN("UsePP"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_METRIC (MAP_CHAR_LEN("UserMetric"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_TYPE (MAP_CHAR_LEN("AnchorType"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_TYPES (MAP_CHAR_LEN("AnchorTypes"));
const SwPropNameLen __FAR_DATA UNO_NAME_ANCHOR_PAGE_NO (MAP_CHAR_LEN("AnchorPageNo"));
const SwPropNameLen __FAR_DATA UNO_NAME_AUTHOR (MAP_CHAR_LEN("Author"));
const SwPropNameLen __FAR_DATA UNO_NAME_BREAK_TYPE (MAP_CHAR_LEN("BreakType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAIN_NEXT_NAME (MAP_CHAR_LEN("ChainNextName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAIN_PREV_NAME (MAP_CHAR_LEN("ChainPrevName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAPTER_FORMAT (MAP_CHAR_LEN("ChapterFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_CLIENT_MAP (MAP_CHAR_LEN("ClientMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONDITION (MAP_CHAR_LEN("Condition"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT (MAP_CHAR_LEN("Content"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAR_CONTOURED (MAP_CHAR_LEN("CharContoured"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTOUR_OUTSIDE (MAP_CHAR_LEN("ContourOutside"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT_PROTECTED (MAP_CHAR_LEN("ContentProtected"));
const SwPropNameLen __FAR_DATA UNO_NAME_COUNT_EMPTY_LINES (MAP_CHAR_LEN("CountEmptyLines"));
const SwPropNameLen __FAR_DATA UNO_NAME_RESTART_AT_EACH_PAGE (MAP_CHAR_LEN("RestartAtEachPage"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_BASE_NAME (MAP_CHAR_LEN("DataBaseName"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_TABLE_NAME (MAP_CHAR_LEN("DataTableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATA_COLUMN_NAME (MAP_CHAR_LEN("DataColumnName"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_DATA_BASE_FORMAT (MAP_CHAR_LEN("DataBaseFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATE (MAP_CHAR_LEN("Date"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_DATE (MAP_CHAR_LEN("IsDate"));
const SwPropNameLen __FAR_DATA UNO_NAME_EDIT_IN_READONLY (MAP_CHAR_LEN("EditInReadonly"));
const SwPropNameLen __FAR_DATA UNO_NAME_FALSE_CONTENT (MAP_CHAR_LEN("FalseContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_FORMAT (MAP_CHAR_LEN("FileFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_FIXED (MAP_CHAR_LEN("IsFixed"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_COUNTING (MAP_CHAR_LEN("FootnoteCounting"));
const SwPropNameLen __FAR_DATA UNO_NAME_FORMULA (MAP_CHAR_LEN("Formula"));
const SwPropNameLen __FAR_DATA UNO_NAME_FRAME_NAME (MAP_CHAR_LEN("FrameName"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_NAME (MAP_CHAR_LEN("GraphicName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FULL_NAME (MAP_CHAR_LEN("FullName"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEIGHT (MAP_CHAR_LEN("Height"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTO_HEIGHT (MAP_CHAR_LEN("IsAutoHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE_TYPE (MAP_CHAR_LEN("SizeType"));
const SwPropNameLen __FAR_DATA UNO_NAME_HINT (MAP_CHAR_LEN("Hint"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT (MAP_CHAR_LEN("HoriOrient"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_MIRRORED_ON_EVEN_PAGES (MAP_CHAR_LEN("HoriMirroredOnEvenPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_MIRRORED_ON_ODD_PAGES (MAP_CHAR_LEN("HoriMirroredOnOddPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT_RELATION (MAP_CHAR_LEN("HoriOrientRelation"));
const SwPropNameLen __FAR_DATA UNO_NAME_HORI_ORIENT_POSITION (MAP_CHAR_LEN("HoriOrientPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_U_R_L (MAP_CHAR_LEN("HyperLinkURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_TARGET (MAP_CHAR_LEN("HyperLinkTarget"));
const SwPropNameLen __FAR_DATA UNO_NAME_HYPER_LINK_NAME (MAP_CHAR_LEN("HyperLinkName"));
const SwPropNameLen __FAR_DATA UNO_NAME_INFO_TYPE (MAP_CHAR_LEN("InfoType"));
const SwPropNameLen __FAR_DATA UNO_NAME_INFO_FORMAT (MAP_CHAR_LEN("InfoFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_INPUT (MAP_CHAR_LEN("Input"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL (MAP_CHAR_LEN("Level"));
const SwPropNameLen __FAR_DATA UNO_NAME_INTERVAL (MAP_CHAR_LEN("Interval"));
const SwPropNameLen __FAR_DATA UNO_NAME_LINK_REGION (MAP_CHAR_LEN("LinkRegion"));
const SwPropNameLen __FAR_DATA UNO_NAME_MACRO (MAP_CHAR_LEN("Macro"));
const SwPropNameLen __FAR_DATA UNO_NAME_SPLIT (MAP_CHAR_LEN("Split"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_SPLIT (MAP_CHAR_LEN("ParaSplit"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBER_FORMAT (MAP_CHAR_LEN("NumberFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_TYPE (MAP_CHAR_LEN("NumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_RULES (MAP_CHAR_LEN("NumberingRules"));
const SwPropNameLen __FAR_DATA UNO_NAME_OFFSET (MAP_CHAR_LEN("Offset"));
const SwPropNameLen __FAR_DATA UNO_NAME_ON (MAP_CHAR_LEN("On"));
const SwPropNameLen __FAR_DATA UNO_NAME_OPAQUE (MAP_CHAR_LEN("Opaque"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_TOGGLE (MAP_CHAR_LEN("PageToggle"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_DESC_NAME (MAP_CHAR_LEN("PageDescName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGE_NUMBER_OFFSET (MAP_CHAR_LEN("PageNumberOffset"));
const SwPropNameLen __FAR_DATA UNO_NAME_PLACEHOLDER (MAP_CHAR_LEN("PlaceHolder"));
const SwPropNameLen __FAR_DATA UNO_NAME_PLACEHOLDER_TYPE (MAP_CHAR_LEN("PlaceHolderType"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT (MAP_CHAR_LEN("Print"));
const SwPropNameLen __FAR_DATA UNO_NAME_PRINT_LEFT_PAGES (MAP_CHAR_LEN("PrintLeftPages"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_FIELD_PART (MAP_CHAR_LEN("ReferenceFieldPart"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_FIELD_SOURCE (MAP_CHAR_LEN("ReferenceFieldSource"));
const SwPropNameLen __FAR_DATA UNO_NAME_REGISTER_PARAGRAPH_STYLE (MAP_CHAR_LEN("RegisterParagraphStyle"));
const SwPropNameLen __FAR_DATA UNO_NAME_SCRIPT_TYPE (MAP_CHAR_LEN("ScriptType"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_ALL (MAP_CHAR_LEN("SearchAll"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEARCH_WORDS (MAP_CHAR_LEN("SearchWords"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEQUENCE_VALUE (MAP_CHAR_LEN("SequenceValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_SERVER_MAP (MAP_CHAR_LEN("ServerMap"));
const SwPropNameLen __FAR_DATA UNO_NAME_SET_NUMBER (MAP_CHAR_LEN("SetNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHADOW_FORMAT (MAP_CHAR_LEN("ShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_HORI_RULER (MAP_CHAR_LEN("ShowHoriRuler"));
const SwPropNameLen __FAR_DATA UNO_NAME_SIZE (MAP_CHAR_LEN("Size"));
const SwPropNameLen __FAR_DATA UNO_NAME_ACTUAL_SIZE (MAP_CHAR_LEN("ActualSize"));
const SwPropNameLen __FAR_DATA UNO_NAME_SOURCE_NAME (MAP_CHAR_LEN("SourceName"));
const SwPropNameLen __FAR_DATA UNO_NAME_START_AT (MAP_CHAR_LEN("StartAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_STATISTIC_TYPE_ID (MAP_CHAR_LEN("StatisticTypeId"));
const SwPropNameLen __FAR_DATA UNO_NAME_SUB_TYPE (MAP_CHAR_LEN("SubType"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND (MAP_CHAR_LEN("Surround"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_EXPRESSION (MAP_CHAR_LEN("IsExpression"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SHOW_FORMULA (MAP_CHAR_LEN("IsShowFormula"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_WRAP (MAP_CHAR_LEN("TextWrap"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND_CONTOUR (MAP_CHAR_LEN("SurroundContour"));
const SwPropNameLen __FAR_DATA UNO_NAME_SURROUND_ANCHORONLY (MAP_CHAR_LEN("SurroundAnchorOnly"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_NAME (MAP_CHAR_LEN("TableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABSTOPS (MAP_CHAR_LEN("ParaTabStops"));
const SwPropNameLen __FAR_DATA UNO_NAME_TITLE (MAP_CHAR_LEN("Title"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_MARGIN (MAP_CHAR_LEN("TopMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_MARGIN (MAP_CHAR_LEN("BottomMargin"));
const SwPropNameLen __FAR_DATA UNO_NAME_TRUE_CONTENT (MAP_CHAR_LEN("TrueContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_URL_CONTENT (MAP_CHAR_LEN("URLContent"));
const SwPropNameLen __FAR_DATA UNO_NAME_USERTEXT (MAP_CHAR_LEN("UserText"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_DATA_TYPE (MAP_CHAR_LEN("UserDataType"));
const SwPropNameLen __FAR_DATA UNO_NAME_VALUE (MAP_CHAR_LEN("Value"));
const SwPropNameLen __FAR_DATA UNO_NAME_VARIABLE_NAME (MAP_CHAR_LEN("VariableName"));
const SwPropNameLen __FAR_DATA UNO_NAME_VARIABLE_SUBTYPE (MAP_CHAR_LEN("VariableSubtype"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT (MAP_CHAR_LEN("VertOrient"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_MIRRORED (MAP_CHAR_LEN("VertMirrored"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT_POSITION (MAP_CHAR_LEN("VertOrientPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_VERT_ORIENT_RELATION (MAP_CHAR_LEN("VertOrientRelation"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_VISIBLE (MAP_CHAR_LEN("IsVisible"));
const SwPropNameLen __FAR_DATA UNO_NAME_WIDTH (MAP_CHAR_LEN("Width"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_MODE (MAP_CHAR_LEN("CharWordMode"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_CROP (MAP_CHAR_LEN("GraphicCrop"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHARACTER_FORMAT_NONE (MAP_CHAR_LEN("CharacterFormatNone"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_POSITION (MAP_CHAR_LEN("TextPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX_MARK (MAP_CHAR_LEN("DocumentIndexMark"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX (MAP_CHAR_LEN("DocumentIndex"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FIELD (MAP_CHAR_LEN("TextField"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOOKMARK (MAP_CHAR_LEN("Bookmark"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_TABLE (MAP_CHAR_LEN("TextTable"));
const SwPropNameLen __FAR_DATA UNO_NAME_CELL (MAP_CHAR_LEN("Cell"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_FRAME (MAP_CHAR_LEN("TextFrame"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_MARK (MAP_CHAR_LEN("ReferenceMark"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_SECTION (MAP_CHAR_LEN("TextSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE (MAP_CHAR_LEN("Footnote"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE (MAP_CHAR_LEN("Endnote"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHART_ROW_AS_LABEL (MAP_CHAR_LEN("ChartRowAsLabel"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHART_COLUMN_AS_LABEL (MAP_CHAR_LEN("ChartColumnAsLabel"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMS (MAP_CHAR_LEN("TableColumns"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_BORDER (MAP_CHAR_LEN("LeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_BORDER (MAP_CHAR_LEN("RightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_BORDER (MAP_CHAR_LEN("TopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_BORDER (MAP_CHAR_LEN("BottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_BORDER_DISTANCE (MAP_CHAR_LEN("BorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("LeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("RightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("TopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("BottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_BORDER (MAP_CHAR_LEN("TableBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMN_SEPARATORS (MAP_CHAR_LEN("TableColumnSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_TABLE_COLUMN_RELATIVE_SUM (MAP_CHAR_LEN("TableColumnRelativeSum"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT (MAP_CHAR_LEN("HeaderText"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT_LEFT (MAP_CHAR_LEN("HeaderTextLeft"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TEXT_RIGHT (MAP_CHAR_LEN("HeaderTextRight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT (MAP_CHAR_LEN("FooterText"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT_LEFT (MAP_CHAR_LEN("FooterTextLeft"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TEXT_RIGHT (MAP_CHAR_LEN("FooterTextRight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BACK_COLOR (MAP_CHAR_LEN("HeaderBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_GRAPHIC (MAP_CHAR_LEN("HeaderBackGraphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BACK_TRANSPARENT (MAP_CHAR_LEN("HeaderBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_BORDER (MAP_CHAR_LEN("HeaderLeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_BORDER (MAP_CHAR_LEN("HeaderRightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TOP_BORDER (MAP_CHAR_LEN("HeaderTopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BOTTOM_BORDER (MAP_CHAR_LEN("HeaderBottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_SHADOW_FORMAT (MAP_CHAR_LEN("HeaderShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BODY_DISTANCE (MAP_CHAR_LEN("HeaderBodyDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_DYNAMIC_HEIGHT (MAP_CHAR_LEN("HeaderIsDynamicHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_SHARED (MAP_CHAR_LEN("HeaderIsShared"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_HEIGHT (MAP_CHAR_LEN("HeaderHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_IS_ON (MAP_CHAR_LEN("HeaderIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BACK_COLOR (MAP_CHAR_LEN("FooterBackColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_GRAPHIC (MAP_CHAR_LEN("FooterBackGraphic"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BACK_TRANSPARENT (MAP_CHAR_LEN("FooterBackTransparent"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_BORDER (MAP_CHAR_LEN("FooterLeftBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_BORDER (MAP_CHAR_LEN("FooterRightBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TOP_BORDER (MAP_CHAR_LEN("FooterTopBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BOTTOM_BORDER (MAP_CHAR_LEN("FooterBottomBorder"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BORDER_DISTANCE (MAP_CHAR_LEN("FooterBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_SHADOW_FORMAT (MAP_CHAR_LEN("FooterShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BODY_DISTANCE (MAP_CHAR_LEN("FooterBodyDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_DYNAMIC_HEIGHT (MAP_CHAR_LEN("FooterIsDynamicHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_SHARED (MAP_CHAR_LEN("FooterIsShared"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_HEIGHT (MAP_CHAR_LEN("FooterHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_IS_ON (MAP_CHAR_LEN("FooterIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_OVERWRITE_STYLES (MAP_CHAR_LEN("OverwriteStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_NUMBERING_STYLES (MAP_CHAR_LEN("LoadNumberingStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_PAGE_STYLES (MAP_CHAR_LEN("LoadPageStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_FRAME_STYLES (MAP_CHAR_LEN("LoadFrameStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_LOAD_TEXT_STYLES (MAP_CHAR_LEN("LoadTextStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_NAME (MAP_CHAR_LEN("FileName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILTER_NAME (MAP_CHAR_LEN("FilterName"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILTER_OPTION (MAP_CHAR_LEN("FilterOption"));
const SwPropNameLen __FAR_DATA UNO_NAME_PASSWORD (MAP_CHAR_LEN("Password"));
const SwPropNameLen __FAR_DATA UNO_NAME_COPY_COUNT (MAP_CHAR_LEN("CopyCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_COLLATE (MAP_CHAR_LEN("Collate"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT (MAP_CHAR_LEN("Sort"));
const SwPropNameLen __FAR_DATA UNO_NAME_PAGES (MAP_CHAR_LEN("Pages"));
const SwPropNameLen __FAR_DATA UNO_NAME_FIRST_LINE_OFFSET (MAP_CHAR_LEN("FirstLineOffset"));
const SwPropNameLen __FAR_DATA UNO_NAME_SYMBOL_TEXT_DISTANCE (MAP_CHAR_LEN("SymbolTextDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_INDEX_NAME (MAP_CHAR_LEN("UserIndexName"));
const SwPropNameLen __FAR_DATA UNO_NAME_REVISION (MAP_CHAR_LEN("Revision"));
const SwPropNameLen __FAR_DATA UNO_NAME_UNVISITED_CHAR_STYLE_NAME (MAP_CHAR_LEN("UnvisitedCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_VISITED_CHAR_STYLE_NAME (MAP_CHAR_LEN("VisitedCharStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARAGRAPH_COUNT (MAP_CHAR_LEN("ParagraphCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_COUNT (MAP_CHAR_LEN("WordCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_WORD_SEPARATOR (MAP_CHAR_LEN("WordSeparator"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHARACTER_COUNT (MAP_CHAR_LEN("CharacterCount"));
const SwPropNameLen __FAR_DATA UNO_NAME_ZOOM_VALUE (MAP_CHAR_LEN("ZoomValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_ZOOM_TYPE (MAP_CHAR_LEN("ZoomType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_MARKS (MAP_CHAR_LEN("CreateFromMarks"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_OUTLINE (MAP_CHAR_LEN("CreateFromOutline"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARAGRAPH_STYLE_NAMES (MAP_CHAR_LEN("ParagraphStyleNames"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_CHAPTER (MAP_CHAR_LEN("CreateFromChapter"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_LABELS (MAP_CHAR_LEN("CreateFromLabels"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_ALPHABETICAL_SEPARATORS (MAP_CHAR_LEN("UseAlphabeticalSeparators"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_KEY_AS_ENTRY (MAP_CHAR_LEN("UseKeyAsEntry"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_COMBINED_ENTRIES (MAP_CHAR_LEN("UseCombinedEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_CASE_SENSITIVE (MAP_CHAR_LEN("IsCaseSensitive"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_P_P (MAP_CHAR_LEN("UsePP"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_DASH (MAP_CHAR_LEN("UseDash"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_UPPER_CASE (MAP_CHAR_LEN("UseUpperCase"));
const SwPropNameLen __FAR_DATA UNO_NAME_LABEL_CATEGORY (MAP_CHAR_LEN("LabelCategory"));
const SwPropNameLen __FAR_DATA UNO_NAME_LABEL_DISPLAY_TYPE (MAP_CHAR_LEN("LabelDisplayType"));
const SwPropNameLen __FAR_DATA UNO_NAME_USE_LEVEL_FROM_SOURCE (MAP_CHAR_LEN("UseLevelFromSource"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL_FORMAT (MAP_CHAR_LEN("LevelFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_LEVEL_PARAGRAPH_STYLES (MAP_CHAR_LEN("LevelParagraphStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_RECALC_TAB_STOPS (MAP_CHAR_LEN("RecalcTabStops"));
const SwPropNameLen __FAR_DATA UNO_NAME_MAIN_ENTRY_CHARACTER_STYLE_NAME (MAP_CHAR_LEN("MainEntryCharacterStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_TABLES (MAP_CHAR_LEN("CreateFromTables"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_TEXT_FRAMES (MAP_CHAR_LEN("CreateFromTextFrames"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_GRAPHIC_OBJECTS (MAP_CHAR_LEN("CreateFromGraphicObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_EMBEDDED_OBJECTS (MAP_CHAR_LEN("CreateFromEmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_MATH (MAP_CHAR_LEN("CreateFromStarMath"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_CHART (MAP_CHAR_LEN("CreateFromStarChart"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_CALC (MAP_CHAR_LEN("CreateFromStarCalc"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_STAR_DRAW (MAP_CHAR_LEN("CreateFromStarDraw"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_OTHER_EMBEDDED_OBJECTS (MAP_CHAR_LEN("CreateFromOtherEmbeddedObjects"));
const SwPropNameLen __FAR_DATA UNO_NAME_INDEX_AUTO_MARK_FILE_U_R_L (MAP_CHAR_LEN("IndexAutoMarkFileURL"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_COMMA_SEPARATED (MAP_CHAR_LEN("IsCommaSeparated"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_RELATIVE_TABSTOPS (MAP_CHAR_LEN("IsRelativeTabstops"));
const SwPropNameLen __FAR_DATA UNO_NAME_CREATE_FROM_LEVEL_PARAGRAPH_STYLES (MAP_CHAR_LEN("CreateFromLevelParagraphStyles"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_CHANGES (MAP_CHAR_LEN("ShowChanges"));
const SwPropNameLen __FAR_DATA UNO_NAME_RECORD_CHANGES (MAP_CHAR_LEN("RecordChanges"));
const SwPropNameLen __FAR_DATA UNO_LINK_DISPLAY_NAME (MAP_CHAR_LEN("LinkDisplayName"));
const SwPropNameLen __FAR_DATA UNO_LINK_DISPLAY_BITMAP (MAP_CHAR_LEN("LinkDisplayBitmap"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADING_STYLE_NAME (MAP_CHAR_LEN("HeadingStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_SHOW_ONLINE_LAYOUT (MAP_CHAR_LEN("ShowOnlineLayout"));
const SwPropNameLen __FAR_DATA UNO_NAME_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("UserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("TextUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_FILE_PATH (MAP_CHAR_LEN("FilePath"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_CHAPTER_NUMBERING_LEVEL (MAP_CHAR_LEN("ParaChapterNumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_CONDITIONAL_STYLE_NAME (MAP_CHAR_LEN("ParaConditionalStyleName"));
const SwPropNameLen __FAR_DATA UNO_NAME_CHAPTER_NUMBERING_LEVEL (MAP_CHAR_LEN("ChapterNumberingLevel"));
const SwPropNameLen __FAR_DATA UNO_NAME_NUMBERING_SEPARATOR (MAP_CHAR_LEN("NumberingSeparator"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_CONTINUOUS_NUMBERING (MAP_CHAR_LEN("IsContinuousNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_AUTOMATIC (MAP_CHAR_LEN("IsAutomatic"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_ABSOLUTE_MARGINS (MAP_CHAR_LEN("IsAbsoluteMargins"));
const SwPropNameLen __FAR_DATA UNO_NAME_CATEGORY (MAP_CHAR_LEN("Category"));
const SwPropNameLen __FAR_DATA UNO_NAME_DEPENDENT_TEXT_FIELDS (MAP_CHAR_LEN("DependentTextFields"));
const SwPropNameLen __FAR_DATA UNO_NAME_CURRENT_PRESENTATION (MAP_CHAR_LEN("CurrentPresentation"));
const SwPropNameLen __FAR_DATA UNO_NAME_ADJUST (MAP_CHAR_LEN("Adjust"));
const SwPropNameLen __FAR_DATA UNO_NAME_TEXT_PORTION_TYPE (MAP_CHAR_LEN("TextPortionType"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTROL_CHARACTER (MAP_CHAR_LEN("ControlCharacter"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_COLLAPSED (MAP_CHAR_LEN("IsCollapsed"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_START (MAP_CHAR_LEN("IsStart"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEQUENCE_NUMBER (MAP_CHAR_LEN("SequenceNumber"));
const SwPropNameLen __FAR_DATA UNO_NAME_REFERENCE_ID (MAP_CHAR_LEN("ReferenceId"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderLeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderRightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderTopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("HeaderBottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("HeaderUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_LEFT_BORDER_DISTANCE (MAP_CHAR_LEN("FooterLeftBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_RIGHT_BORDER_DISTANCE (MAP_CHAR_LEN("FooterRightBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_TOP_BORDER_DISTANCE (MAP_CHAR_LEN("FooterTopBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_BOTTOM_BORDER_DISTANCE (MAP_CHAR_LEN("FooterBottomBorderDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTER_USER_DEFINED_ATTRIBUTES (MAP_CHAR_LEN("FooterUserDefinedAttributes"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_NUMBERING_RESTART (MAP_CHAR_LEN("ParaIsNumberingRestart"));
const SwPropNameLen __FAR_DATA UNO_NAME_HIDE_FIELD_TIPS (MAP_CHAR_LEN("HideFieldTips"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_SHADOW_FORMAT (MAP_CHAR_LEN("ParaShadowFormat"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTOUR_POLY_POLYGON (MAP_CHAR_LEN("ContourPolyPolygon"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_WIDTH (MAP_CHAR_LEN("SeparatorLineWidth"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_COLOR (MAP_CHAR_LEN("SeparatorLineColor"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_RELATIVE_HEIGHT (MAP_CHAR_LEN("SeparatorLineRelativeHeight"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_VERTIVAL_ALIGNMENT (MAP_CHAR_LEN("SeparatorLineVerticalAlignment"));
const SwPropNameLen __FAR_DATA UNO_NAME_SEPARATOR_LINE_IS_ON (MAP_CHAR_LEN("SeparatorLineIsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SKIP_HIDDEN_TEXT (MAP_CHAR_LEN("IsSkipHiddenText"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SKIP_PROTECTED_TEXT (MAP_CHAR_LEN("IsSkipProtectedText"));
const SwPropNameLen __FAR_DATA UNO_NAME_DOCUMENT_INDEX_MARKS (MAP_CHAR_LEN("DocumentIndexMarks"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_COLLECT_AT_TEXT_END (MAP_CHAR_LEN("FootnoteIsCollectAtTextEnd"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_RESTART_NUMBERING (MAP_CHAR_LEN("FootnoteIsRestartNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_RESTART_NUMBERING_AT (MAP_CHAR_LEN("FootnoteRestartNumberingAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_IS_OWN_NUMBERING (MAP_CHAR_LEN("FootnoteIsOwnNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_TYPE (MAP_CHAR_LEN("FootnoteNumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_PREFIX (MAP_CHAR_LEN("FootnoteNumberingPrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_FOOTNOTE_NUMBERING_SUFFIX (MAP_CHAR_LEN("FootnoteNumberingSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_COLLECT_AT_TEXT_END (MAP_CHAR_LEN("EndnoteIsCollectAtTextEnd"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_RESTART_NUMBERING (MAP_CHAR_LEN("EndnoteIsRestartNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_RESTART_NUMBERING_AT (MAP_CHAR_LEN("EndnoteRestartNumberingAt"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_IS_OWN_NUMBERING (MAP_CHAR_LEN("EndnoteIsOwnNumbering"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_TYPE (MAP_CHAR_LEN("EndnoteNumberingType"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_PREFIX (MAP_CHAR_LEN("EndnoteNumberingPrefix"));
const SwPropNameLen __FAR_DATA UNO_NAME_ENDNOTE_NUMBERING_SUFFIX (MAP_CHAR_LEN("EndnoteNumberingSuffix"));
const SwPropNameLen __FAR_DATA UNO_NAME_BRACKET_BEFORE (MAP_CHAR_LEN("BracketBefore"));
const SwPropNameLen __FAR_DATA UNO_NAME_BRACKET_AFTER (MAP_CHAR_LEN("BracketAfter"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_NUMBER_ENTRIES (MAP_CHAR_LEN("IsNumberEntries"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SORT_BY_POSITION (MAP_CHAR_LEN("IsSortByPosition"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT_KEYS (MAP_CHAR_LEN("SortKeys"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_SORT_ASCENDING (MAP_CHAR_LEN("IsSortAscending"));
const SwPropNameLen __FAR_DATA UNO_NAME_SORT_KEY (MAP_CHAR_LEN("SortKey"));
const SwPropNameLen __FAR_DATA UNO_NAME_FIELDS (MAP_CHAR_LEN("Fields"));
const SwPropNameLen __FAR_DATA UNO_NAME_DATE_TIME_VALUE (MAP_CHAR_LEN("DateTimeValue"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_ON (MAP_CHAR_LEN("IsOn"));
const SwPropNameLen __FAR_DATA UNO_NAME_Z_ORDER (MAP_CHAR_LEN("ZOrder"));
const SwPropNameLen __FAR_DATA UNO_NAME_CONTENT_SECTION (MAP_CHAR_LEN("ContentSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_HEADER_SECTION (MAP_CHAR_LEN("HeaderSection"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_HANGING_PUNCTUATION (MAP_CHAR_LEN("ParaIsHangingPunctuation"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_CHARACTER_DISTANCE (MAP_CHAR_LEN("ParaIsCharacterDistance"));
const SwPropNameLen __FAR_DATA UNO_NAME_PARA_IS_FORBIDDEN_RULES (MAP_CHAR_LEN("ParaIsForbiddenRules"));
const SwPropNameLen __FAR_DATA UNO_NAME_IS_MAIN_ENTRY (MAP_CHAR_LEN("IsMainEntry"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_ROTATION (MAP_CHAR_LEN("GraphicRotation"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_LUMINANCE (MAP_CHAR_LEN("GraphicLuminance"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_CONTRAST (MAP_CHAR_LEN("GraphicContrast"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_RED (MAP_CHAR_LEN("GraphicRed"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_GREEN (MAP_CHAR_LEN("GraphicGreen"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_BLUE (MAP_CHAR_LEN("GraphicBlue"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_GAMMA (MAP_CHAR_LEN("GraphicGamma"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_INVERSION (MAP_CHAR_LEN("GraphicInversion"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_TRANSPARENCY (MAP_CHAR_LEN("GraphicTransparency"));
const SwPropNameLen __FAR_DATA UNO_NAME_GRAPHIC_COLOR_MODE (MAP_CHAR_LEN("GraphicColorMode"));
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <shellio.hxx>
#include <doc.hxx>
#include <node.hxx>
#include <cmdid.h>
/******************************************************************************
* Methode : SwDocFac::SwDocFac( SwDoc *pDoc )
******************************************************************************/
SwDocFac::SwDocFac( SwDoc *pDc )
: pDoc( pDc )
{
if( pDoc )
pDoc->acquire();
}
/******************************************************************************
* Methode : SwDocFac::~SwDocFac()
******************************************************************************/
SwDocFac::~SwDocFac()
{
if( pDoc && !pDoc->release() )
delete pDoc;
}
/******************************************************************************
* Methode : SwDoc *SwDocFac::GetDoc()
* Beschreibung: Diese Methode legt immer einen Drucker an.
******************************************************************************/
SwDoc *SwDocFac::GetDoc()
{
if( !pDoc )
{
pDoc = new SwDoc;
pDoc->acquire();
}
return pDoc;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fdo#39468 Translate German Comments - docfact.cxx
Change-Id: Ib9ca82b1b5f19dff439cd3119781a5f025b45231
Reviewed-on: https://gerrit.libreoffice.org/8663
Reviewed-by: Miklos Vajna <16f13092e03e3d9e997de904d0f86cc803fb6ef7@collabora.co.uk>
Tested-by: Miklos Vajna <16f13092e03e3d9e997de904d0f86cc803fb6ef7@collabora.co.uk>
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <shellio.hxx>
#include <doc.hxx>
#include <node.hxx>
#include <cmdid.h>
SwDocFac::SwDocFac( SwDoc *pDc )
: pDoc( pDc )
{
if( pDoc )
pDoc->acquire();
}
SwDocFac::~SwDocFac()
{
if( pDoc && !pDoc->release() )
delete pDoc;
}
SwDoc *SwDocFac::GetDoc()
{
if( !pDoc )
{
pDoc = new SwDoc;
pDoc->acquire();
}
return pDoc;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/*************************************************************************
*
* $RCSfile: shellio.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: jp $ $Date: 2001-10-30 14:38:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif
#pragma hdrstop
#define ITEMID_BOXINFO SID_ATTR_BORDER_INNER
#include <hintids.hxx>
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _TIME_HXX
#include <tools/time.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef SVTOOLS_FSTATHELPER_HXX
#include <svtools/fstathelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_ULSPITEM_HXX //autogen
#include <svx/ulspitem.hxx>
#endif
#ifndef _SVX_BOXITEM_HXX //autogen
#include <svx/boxitem.hxx>
#endif
#ifndef _SVXLINKMGR_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _SVX_PAPERINF_HXX //autogen
#include <svx/paperinf.hxx>
#endif
#ifndef _NODE_HXX //autogen
#include <node.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen
#include <fmtanchr.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _CRSRSH_HXX
#include <crsrsh.hxx>
#endif
#ifndef _UNDOBJ_HXX
#include <undobj.hxx> // fuer Undo Insert-Dokument
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo Insert-Dokument
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx>
#endif
#ifndef _TBLSEL_HXX
#include <tblsel.hxx>
#endif
#ifndef _PAGEDESC_HXX
#include <pagedesc.hxx>
#endif
#ifndef _POOLFMT_HXX
#include <poolfmt.hxx>
#endif
#ifndef _FLTINI_HXX
#include <fltini.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SW3IO_HXX
#include <sw3io.hxx>
#endif
#ifndef _REDLINE_HXX
#include <redline.hxx>
#endif
#ifndef _LINKENUM_HXX
#include <linkenum.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
//////////////////////////////////////////////////////////////////////////
ULONG SwReader::Read( const Reader& rOptions )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = 0 != pCrsr;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
if( 0 != (po->pMedium = pMedium ) &&
!po->SetStrmStgPtr() )
{
po->SetReadUTF8( FALSE );
po->SetBlockMode( FALSE );
po->SetOrganizerMode( FALSE );
return ERR_SWG_FILE_FORMAT_ERROR;
}
ULONG nError = 0L;
GetDoc();
// am Sw3-Reader noch den pIo-Pointer "loeschen"
if( po == ReadSw3 && pDoc->GetDocShell() &&
((Sw3Reader*)po)->GetSw3Io() != pDoc->GetDocShell()->GetIoSystem() )
((Sw3Reader*)po)->SetSw3Io( pDoc->GetDocShell()->GetIoSystem() );
// waehrend des einlesens kein OLE-Modified rufen
Link aOLELink( pDoc->GetOle2Link() );
pDoc->SetOle2Link( Link() );
pDoc->bInReading = TRUE;
SwPaM *pPam;
if( pCrsr )
pPam = pCrsr;
else
{
// Wenn der Reader nicht mit einem Shell konstruiert wurde,
// selber einen Pam machen.
SwNodeIndex nNode( pDoc->GetNodes().GetEndOfContent(), -1 );
pPam = new SwPaM( nNode );
// Bei Web-Dokumenten wird die Default-Vorlage schon im InitNew
// gesetzt und braucht deshalb nicht nochmal gesetzt zu werden.
// Das gilt natuerlich nicht, wenn der Filter nicht der HTML-Filter
// ist oder im ConvertFrom zuvor ein SetTemplateName gerufen
// wurde.
if( !pDoc->IsHTMLMode() || ReadHTML != po || !po->pTemplate )
po->SetTemplate( *pDoc );
}
// Pams sind ringfoermig verkettet. Aufhoeren, wenn man wieder beim
// ersten ist.
SwPaM *pEnd = pPam;
SwUndoInsDoc* pUndo = 0L;
BOOL bReadPageDescs = FALSE;
BOOL bDocUndo = pDoc->DoesUndo();
BOOL bSaveUndo = bDocUndo && pCrsr;
if( bSaveUndo )
{
// das Einlesen von Seitenvorlagen ist nicht Undofaehig!
if( 0 != ( bReadPageDescs = po->aOpt.IsPageDescs() ) )
{
bSaveUndo = FALSE;
pDoc->DelAllUndoObj();
}
else
{
pDoc->ClearRedo();
pDoc->StartUndo( UNDO_INSDOKUMENT );
}
}
pDoc->DoUndo( FALSE );
SwNodeIndex aSplitIdx( pDoc->GetNodes() );
SwRedlineMode eOld = pDoc->GetRedlineMode();
pDoc->SetRedlineMode_intern( REDLINE_IGNORE );
// Array von FlyFormaten
SwSpzFrmFmts aFlyFrmArr;
// only read templates? then ignore multi selection!
BOOL bFmtsOnly = po->aOpt.IsFmtsOnly();
while( TRUE )
{
if( bSaveUndo )
pUndo = new SwUndoInsDoc( *pPam );
SwPaM* pUndoPam = 0L;
if( bDocUndo || pCrsr )
{
// Pam auf den Node davor setzen damit er nicht mit verschoben wird
const SwNodeIndex& rTmp = pPam->GetPoint()->nNode;
pUndoPam = new SwPaM( rTmp, rTmp, 0, -1 );
}
// Speicher mal alle Fly's
if( pCrsr )
aFlyFrmArr.Insert( pDoc->GetSpzFrmFmts(), 0L );
xub_StrLen nSttCntnt = pPam->GetPoint()->nContent.GetIndex();
// damit fuer alle Reader die Ende-Position immer stimmt, hier
// pflegen.
SwCntntNode* pCNd = pPam->GetCntntNode();
xub_StrLen nEndCntnt = pCNd ? pCNd->Len() - nSttCntnt : 0;
SwNodeIndex aEndPos( pPam->GetPoint()->nNode, 1 );
nError = po->Read( *pDoc, *pPam, aFileName );
if( !IsError( nError )) // dann setzen wir das Ende mal richtig
{
aEndPos--;
pCNd = aEndPos.GetNode().GetCntntNode();
if( !pCNd && 0 == ( pCNd = pDoc->GetNodes().GoPrevious( &aEndPos ) ))
pCNd = pDoc->GetNodes().GoNext( &aEndPos );
pPam->GetPoint()->nNode = aEndPos;
xub_StrLen nLen = pCNd->Len();
if( nLen < nEndCntnt )
nEndCntnt = 0;
else
nEndCntnt = nLen - nEndCntnt;
pPam->GetPoint()->nContent.Assign( pCNd, nEndCntnt );
}
if( pCrsr )
{
*pUndoPam->GetMark() = *pPam->GetPoint();
pUndoPam->GetPoint()->nNode++;
SwNode* pNd = pUndoPam->GetNode();
if( pNd->IsCntntNode() )
pUndoPam->GetPoint()->nContent.Assign(
(SwCntntNode*)pNd, nSttCntnt );
else
pUndoPam->GetPoint()->nContent.Assign( 0, 0 );
int bChkHeaderFooter = pNd->FindHeaderStartNode() ||
pNd->FindFooterStartNode();
// Suche alle neuen Fly's und speicher sie als einzelne Undo
// Objecte
for( USHORT n = 0; n < pDoc->GetSpzFrmFmts()->Count(); ++n )
{
SwFrmFmt* pFrmFmt = (*pDoc->GetSpzFrmFmts())[ n ];
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
if( USHRT_MAX == aFlyFrmArr.GetPos( pFrmFmt) )
{
if( FLY_PAGE == rAnchor.GetAnchorId() ||
( FLY_AT_CNTNT == rAnchor.GetAnchorId() &&
rAnchor.GetCntntAnchor() &&
( pUndoPam->GetPoint()->nNode ==
rAnchor.GetCntntAnchor()->nNode ||
pUndoPam->GetMark()->nNode ==
rAnchor.GetCntntAnchor()->nNode ) ) )
{
if( bChkHeaderFooter &&
FLY_AT_CNTNT == rAnchor.GetAnchorId() &&
RES_DRAWFRMFMT == pFrmFmt->Which() )
{
// DrawObjecte in Kopf-/Fusszeilen ist nicht
// erlaubt!
pFrmFmt->DelFrms();
pDoc->DelFrmFmt( pFrmFmt );
--n;
}
else
{
if( bSaveUndo )
pDoc->AppendUndo( new SwUndoInsLayFmt( pFrmFmt ) );
if( pFrmFmt->GetDepends() )
{
// beim Insert legen Draw-Objecte einen Frame an
// also weg damit.
pFrmFmt->DelFrms();
}
if( FLY_PAGE == rAnchor.GetAnchorId() )
{
if( !rAnchor.GetCntntAnchor() )
pFrmFmt->MakeFrms();
else if( pCrsr )
// seitengebundene Flys eingefuegt, dann schalte
// die Optimierungs-Flags vom SwDoc ab. Sonst
// werden die Flys nicht an der Position erzeugt.
pDoc->SetLoaded( FALSE );
}
else
pFrmFmt->MakeFrms();
}
}
}
}
if( aFlyFrmArr.Count() )
aFlyFrmArr.Remove( 0, aFlyFrmArr.Count() );
pDoc->SetRedlineMode_intern( eOld );
if( pDoc->IsRedlineOn() )
pDoc->AppendRedline( new SwRedline( REDLINE_INSERT, *pUndoPam ));
else
pDoc->SplitRedline( *pUndoPam );
pDoc->SetRedlineMode_intern( REDLINE_IGNORE );
}
if( bSaveUndo )
{
pUndo->SetInsertRange( *pUndoPam, FALSE );
pDoc->AppendUndo( pUndo );
}
delete pUndoPam;
pPam = (SwPaM *) pPam->GetNext();
if( pPam == pEnd )
break;
// only read templates? then ignore multi selection! Bug 68593
if( bFmtsOnly )
break;
/*
* !!! man muss selbst den Status vom Stream zuruecksetzen. !!!
* Beim seekg wird der akt. Status, eof- und bad-Bit
* gesetzt, warum weiss keiner
*/
if( pStrm )
{
pStrm->Seek(0);
pStrm->ResetError();
}
}
pDoc->bInReading = FALSE;
pDoc->SetAllUniqueFlyNames();
if( bReadPageDescs )
pDoc->DoUndo( TRUE );
else
{
pDoc->DoUndo( bDocUndo );
if( bSaveUndo )
pDoc->EndUndo( UNDO_INSDOKUMENT );
}
// Wenn der Pam nur fuers Lesen konstruiert wurde, jetzt zerstoeren.
if( !pCrsr )
{
delete pPam; // ein neues aufgemacht.
// alle Links updaten und Fehler melden
// (die Graphic-Links nicht, passiert ueber unseren Grafik-Cache!!)
// JP 20.03.96: aber nicht wenn die DocShell als INTERNAL
// construiert wurde (FileLinks in FileLinks in ...)
// JP 27.06.96: wenn internal, dann nie Updaten! (rekursionen werden
// sonst nicht erkannt! ( Bug )
SfxObjectCreateMode eMode;
USHORT nLinkMode = pDoc->GetLinkUpdMode();
if( nLinkMode != NEVER && pDoc->GetDocShell() &&
pDoc->GetLinkManager().GetLinks().Count() &&
SFX_CREATE_MODE_INTERNAL !=
( eMode = pDoc->GetDocShell()->GetCreateMode()) &&
SFX_CREATE_MODE_ORGANIZER != eMode &&
SFX_CREATE_MODE_PREVIEW != eMode &&
!pDoc->GetDocShell()->IsPreview() )
{
ViewShell* pVSh = 0;
if( pDoc->GetRootFrm() && !pDoc->GetEditShell( &pVSh ) && !pVSh )
{
ViewShell aVSh( *pDoc, 0, 0 );
SET_CURR_SHELL( &aVSh );
pDoc->GetLinkManager().UpdateAllLinks( nLinkMode == MANUAL, TRUE, FALSE );
}
else
pDoc->GetLinkManager().UpdateAllLinks( nLinkMode == MANUAL, TRUE, FALSE );
}
eOld = (SwRedlineMode)(pDoc->GetRedlineMode() & ~REDLINE_IGNORE);
pDoc->SetFieldsDirty( FALSE );
}
pDoc->SetRedlineMode_intern( eOld );
pDoc->SetOle2Link( aOLELink );
if( pCrsr ) // das Doc ist jetzt modifiziert
pDoc->SetModified();
if( po == ReadSw3 ) // am Sw3-Reader noch den pIo-Pointer "loeschen"
((Sw3Reader*)po)->SetSw3Io( 0 );
po->SetReadUTF8( FALSE );
po->SetBlockMode( FALSE );
po->SetOrganizerMode( FALSE );
return nError;
}
/*
* Konstruktoren, Destruktor
*/
// Initiales Einlesben
SwReader::SwReader( SvStream& rStrm, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
SwReader::SwReader( SvStorage& rStg, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
SwReader::SwReader( SfxMedium& rMedium, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
// In ein existierendes Dokument einlesen
SwReader::SwReader( SvStream& rStrm, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pCrsr( &rPam )
{
}
SwReader::SwReader( SvStorage& rStg, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStg( &rStg ),
pStrm( 0 ),
pMedium( 0 ),
pCrsr( &rPam )
{
}
SwReader::SwReader( SfxMedium& rMedium, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStg( 0 ),
pStrm( 0 ),
pMedium( &rMedium ),
pCrsr( &rPam )
{
}
Reader::Reader()
: pStrm(0), pStg(0), pMedium(0), pTemplate(0),
bTmplBrowseMode( FALSE ), bInsertMode( FALSE ),
bReadUTF8( FALSE ), bBlockMode( FALSE ), bOrganizerMode( FALSE ),
bHasAskTemplateName( FALSE )
{
}
Reader::~Reader()
{
delete pTemplate;
}
String Reader::GetTemplateName() const
{
return aEmptyStr;
}
// Die Filter-Vorlage laden, setzen und wieder freigeben
SwDoc* Reader::GetTemplateDoc()
{
if( !bHasAskTemplateName )
{
SetTemplateName( GetTemplateName() );
bHasAskTemplateName = TRUE;
}
if( !aTemplateNm.Len() )
ClearTemplate();
else
{
INetURLObject aTDir( URIHelper::SmartRelToAbs(aTemplateNm) );
DateTime aCurrDateTime;
BOOL bLoad = FALSE;
// Wenn das Template schon mal geladen wurde, nur einmal pro
// Minute nachschauen, ob es geaendert wurde.
if( !pTemplate || aCurrDateTime >= aChkDateTime )
{
Date aTstDate;
Time aTstTime;
if( FStatHelper::GetModifiedDateTimeOfFile(
aTDir.GetMainURL( INetURLObject::NO_DECODE ),
&aTstDate, &aTstTime ) &&
( !pTemplate || aDStamp != aTstDate || aTStamp != aTstTime ))
{
bLoad = TRUE;
aDStamp = aTstDate;
aTStamp = aTstTime;
}
// Erst in einer Minute wieder mal nachschauen, ob sich die
// Vorlage geaendert hat.
aChkDateTime = aCurrDateTime;
aChkDateTime += Time( 0L, 1L );
}
if( bLoad )
{
ClearTemplate();
ASSERT( !pTemplate, "Who holds the template doc?" );
SvStorageRef xStor( new SvStorage( aTDir.GetFull(), STREAM_READ ));
ULONG nFormat = xStor->GetFormat();
long nVersion = SOFFICE_FILEFORMAT_60;
switch( nFormat )
{
case SOT_FORMATSTR_ID_STARWRITER_50:
case SOT_FORMATSTR_ID_STARWRITERGLOB_50:
case SOT_FORMATSTR_ID_STARWRITERWEB_50:
nVersion = SOFFICE_FILEFORMAT_50;
break;
case SOT_FORMATSTR_ID_STARWRITER_40:
case SOT_FORMATSTR_ID_STARWRITERGLOB_40:
case SOT_FORMATSTR_ID_STARWRITERWEB_40:
nVersion = SOFFICE_FILEFORMAT_40;
break;
case SOT_FORMATSTR_ID_STARWRITER_30:
nVersion = SOFFICE_FILEFORMAT_31;
break;
}
if( nVersion >= SOFFICE_FILEFORMAT_60 )
{
SwDocShell *pDocSh =
new SwDocShell ( SFX_CREATE_MODE_INTERNAL );
SvEmbeddedObjectRef xDocSh = pDocSh;
if( pDocSh->DoInitNew( 0 ) )
{
pTemplate = pDocSh->GetDoc();
pTemplate->SetOle2Link( Link() );
pTemplate->DoUndo( FALSE ); // always FALSE
pTemplate->SetBrowseMode( bTmplBrowseMode );
ReadXML->SetOrganizerMode( TRUE );
SwReader aRdr( *xStor, aEmptyStr, pTemplate );
aRdr.Read( *ReadXML );
ReadXML->SetOrganizerMode( FALSE );
pTemplate->AddLink();
}
}
else
{
pTemplate = new SwDoc;
pTemplate->AddLink();
// sicher ist sicher
pTemplate->SetBrowseMode( bTmplBrowseMode );
xStor->SetVersion( nVersion );
Sw3Io aIO( *pTemplate );
aIO.LoadStyles( xStor );
}
}
ASSERT( !pTemplate || FStatHelper::IsDocument(
aTDir.GetMainURL( INetURLObject::NO_DECODE ) ) ||
aTemplateNm.EqualsAscii( "$$Dummy$$" ),
"TemplatePtr but no template exist!" );
}
return pTemplate;
}
BOOL Reader::SetTemplate( SwDoc& rDoc )
{
BOOL bRet = FALSE;
GetTemplateDoc();
if( pTemplate )
{
rDoc.ReplaceStyles( *pTemplate );
rDoc.SetFixFields();
bRet = TRUE;
}
return bRet;
}
void Reader::ClearTemplate()
{
if( pTemplate )
{
if( 0 == pTemplate->RemoveLink() )
delete pTemplate,
pTemplate = 0;
}
}
void Reader::SetTemplateName( const String& rDir )
{
if( rDir.Len() && aTemplateNm != rDir )
{
ClearTemplate();
aTemplateNm = rDir;
}
}
void Reader::MakeHTMLDummyTemplateDoc()
{
ClearTemplate();
pTemplate = new SwDoc;
pTemplate->AddLink();
pTemplate->SetBrowseMode( bTmplBrowseMode );
pTemplate->GetPrt( TRUE );
aChkDateTime = Date( 1, 1, 2300 ); // 2300. Jahrtausend sollte reichen
aTemplateNm.AssignAscii( "$$Dummy$$" );
}
// alle die die Streams / Storages nicht geoeffnet brauchen,
// muessen die Methode ueberladen
int Reader::SetStrmStgPtr()
{
ASSERT( pMedium, "Wo ist das Medium??" );
if( pMedium->IsStorage() )
{
if( SW_STORAGE_READER & GetReaderType() )
{
pStg = pMedium->GetStorage();
return TRUE;
}
}
else if( SW_STREAM_READER & GetReaderType() )
{
pStrm = pMedium->GetInStream();
return TRUE;
}
return FALSE;
}
int Reader::GetReaderType()
{
return SW_STREAM_READER;
}
void Reader::SetFltName( const String& )
{
}
void Reader::SetNoOutlineNum( SwDoc& rDoc )
{
// JP 10.03.96: jetzt wieder keine Nummerierung in den Vorlagen
#if 0
//JP 18.01.96: Alle Ueberschriften sind normalerweise ohne
// Kapitelnummer. Darum hier explizit abschalten
// weil das Default jetzt wieder auf AN ist.
SwNumRules aRules( OUTLINE_RULES );
if( rDoc.GetOutlineNumRules() )
aRules = *rDoc.GetOutlineNumRules();
for( BYTE n = 0; n < MAXLEVEL; ++n )
{
SwNumFmt aFmt( aRules.Get( n ) );
aFmt.eType = NUMBER_NONE;
aRules.Set( n, aFmt );
}
rDoc.SetOutlineNumRules( aRules );
// und UeberschirftBasis ohne Einrueckung!
SwTxtFmtColl* pCol = rDoc.GetTxtCollFromPool( RES_POOLCOLL_HEADLINE_BASE );
pCol->ResetAttr( RES_LR_SPACE );
#endif
}
void Reader::ResetFrmFmtAttrs( SfxItemSet &rFrmSet )
{
rFrmSet.Put( SvxLRSpaceItem() );
rFrmSet.Put( SvxULSpaceItem() );
rFrmSet.Put( SvxBoxItem() );
}
void Reader::ResetFrmFmts( SwDoc& rDoc )
{
for( USHORT i=0; i<3; i++ )
{
USHORT nPoolId;
switch( i )
{
case 0: nPoolId = RES_POOLFRM_FRAME; break;
case 1: nPoolId = RES_POOLFRM_GRAPHIC; break;
case 2: nPoolId = RES_POOLFRM_OLE; break;
}
SwFrmFmt *pFrmFmt = rDoc.GetFrmFmtFromPool( nPoolId );
pFrmFmt->ResetAttr( RES_LR_SPACE );
pFrmFmt->ResetAttr( RES_UL_SPACE );
pFrmFmt->ResetAttr( RES_BOX );
}
}
// ------------------------------------------------
BOOL SwReader::HasGlossaries( const Reader& rOptions )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = FALSE;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
BOOL bRet = FALSE;
if( !( 0 != (po->pMedium = pMedium ) && !po->SetStrmStgPtr() ))
bRet = po->HasGlossaries();
return bRet;
}
BOOL SwReader::ReadGlossaries( const Reader& rOptions,
SwTextBlocks& rBlocks, BOOL bSaveRelFiles )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = FALSE;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
BOOL bRet = FALSE;
if( !( 0 != (po->pMedium = pMedium ) && !po->SetStrmStgPtr() ))
bRet = po->ReadGlossaries( rBlocks, bSaveRelFiles );
return bRet;
}
BOOL Reader::HasGlossaries() const
{
return FALSE;
}
BOOL Reader::ReadGlossaries( SwTextBlocks&, BOOL ) const
{
return FALSE;
}
// ------------------------------------------------
int StgReader::GetReaderType()
{
return SW_STORAGE_READER;
}
/*
* Writer
*/
/*
* Konstruktoren, Destruktoren sind inline (inc/shellio.hxx).
*/
SwWriter::SwWriter( SvStream& rStrm, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
SwWriter::SwWriter(SvStream& rStrm,SwDoc &rDoc)
:pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
SwWriter::SwWriter( SvStream& rStrm, SwPaM& rPam, BOOL bWriteAll )
: pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
/*
SwWriter::SwWriter( SvStorage& rStg, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
SwWriter::SwWriter(SvStorage& rStg,SwDoc &rDoc)
:pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
/*
SwWriter::SwWriter( SvStorage& rStg, SwPaM& rPam, BOOL bWriteAll )
: pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
SwWriter::SwWriter( SfxMedium& rMedium, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
SwWriter::SwWriter( SfxMedium& rMedium, SwDoc &rDoc)
:pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
/*
SwWriter::SwWriter( SfxMedium& rMedium, SwPaM& rPam, BOOL bWriteAll )
: pStrm( 0 ),
pStg( 0 ),
pShell( 0 ),
pMedium( &rMedium ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
ULONG SwWriter::Write( WriterRef& rxWriter, const String* pRealFileName )
{
BOOL bHasMark = FALSE;
SwPaM * pPam;
SwDoc *pDoc = 0L;
if ( pShell && !bWriteAll && pShell->IsTableMode() )
{
bWriteAll = TRUE;
pDoc = new SwDoc;
pDoc->AddLink();
// kopiere Teile aus einer Tabelle: lege eine Tabelle mit der Breite
// von der Originalen an und kopiere die selectierten Boxen.
// Die Groessen werden prozentual korrigiert.
// lasse ueber das Layout die Boxen suchen
SwSelBoxes aBoxes;
GetTblSel( *pShell, aBoxes );
SwTableNode* pTblNd = (SwTableNode*)aBoxes[0]->GetSttNd()->FindStartNode();
SwNodeIndex aIdx( pDoc->GetNodes().GetEndOfExtras(), 2 );
SwCntntNode *pNd = aIdx.GetNode().GetCntntNode();
ASSERT( pNd, "Node not found" );
SwPosition aPos( aIdx, SwIndex( pNd ) );
pTblNd->GetTable().MakeCopy( pDoc, aPos, aBoxes );
}
if( !bWriteAll && ( pShell || pOutPam ))
{
if( pShell )
pPam = pShell->GetCrsr();
else
pPam = pOutPam;
SwPaM *pEnd = pPam;
// Erste Runde: Nachsehen, ob eine Selektion besteht.
while(TRUE)
{
bHasMark = bHasMark || pPam->HasMark();
pPam = (SwPaM *) pPam->GetNext();
if(bHasMark || pPam == pEnd)
break;
}
// Wenn keine Selektion besteht, eine ueber das ganze Dokument aufspannen.
if(!bHasMark)
{
if( pShell )
{
pShell->Push();
pShell->SttDoc();
pShell->SetMark();
pShell->EndDoc();
}
else
{
pPam = new SwPaM( *pPam );
pPam->Move( fnMoveBackward, fnGoDoc );
pPam->SetMark();
pPam->Move( fnMoveForward, fnGoDoc );
}
}
// pPam ist immer noch der akt. Cursor !!
}
else
{
// keine Shell oder alles schreiben -> eigenen Pam erzeugen
SwDoc* pOutDoc = pDoc ? pDoc : &rDoc;
pPam = new SwPaM( pOutDoc->GetNodes().GetEndOfContent() );
pPam->Move( fnMoveBackward, fnGoDoc );
pPam->SetMark();
pPam->Move( fnMoveForward, fnGoDoc );
}
rxWriter->bWriteAll = bWriteAll;
SwDoc* pOutDoc = pDoc ? pDoc : &rDoc;
// falls der Standart PageDesc. immer noch auf initalen Werten steht
// (wenn z.B. kein Drucker gesetzt wurde) dann setze jetzt auf DIN A4
if( !pOutDoc->GetPrt() )
{
const SwPageDesc& rPgDsc = pOutDoc->GetPageDesc( 0L );
//const SwPageDesc& rPgDsc = *pOutDoc->GetPageDescFromPool( RES_POOLPAGE_STANDARD );;
const SwFmtFrmSize& rSz = rPgDsc.GetMaster().GetFrmSize();
// Clipboard-Dokument wird immer ohne Drucker angelegt, so ist
// der Std.PageDesc immer aug LONG_MAX !! Mappe dann auf DIN A4
if( LONG_MAX == rSz.GetHeight() || LONG_MAX == rSz.GetWidth() )
{
SwPageDesc aNew( rPgDsc );
SwFmtFrmSize aNewSz( rSz );
aNewSz.SetHeight( lA4Height );
aNewSz.SetWidth( lA4Width );
aNew.GetMaster().SetAttr( aNewSz );
pOutDoc->ChgPageDesc( 0, aNew );
}
}
BOOL bWasPurgeOle = pOutDoc->IsPurgeOLE();
pOutDoc->SetPurgeOLE( FALSE );
ULONG nError = 0;
if( pMedium )
nError = rxWriter->Write( *pPam, *pMedium, pRealFileName );
else if( pStg )
nError = rxWriter->Write( *pPam, *pStg, pRealFileName );
else if( pStrm )
nError = rxWriter->Write( *pPam, *pStrm, pRealFileName );
pOutDoc->SetPurgeOLE( bWasPurgeOle );
// Falls nur zum Schreiben eine Selektion aufgespannt wurde, vor der
// Rueckkehr den alten Crsr wieder herstellen.
if( !bWriteAll && ( pShell || pOutPam ))
{
if(!bHasMark)
{
if( pShell )
pShell->Pop( FALSE );
else
delete pPam;
}
}
else
{
delete pPam; // loesche den hier erzeugten Pam
// Alles erfolgreich geschrieben? Sag' das dem Dokument!
if( !IsError( nError ) && !pDoc )
rDoc.ResetModified();
}
if ( pDoc )
{
if ( !pDoc->RemoveLink() )
delete pDoc;
bWriteAll = FALSE;
}
return nError;
}
/* */
// ----------------------------------------------------------------------
BOOL SetHTMLTemplate( SwDoc & rDoc )
{
// Vorlagennamen von den Sfx-HTML-Filter besorgen!!!
if( !ReadHTML->GetTemplateDoc() )
ReadHTML->MakeHTMLDummyTemplateDoc();
BOOL bRet = ReadHTML->SetTemplate( rDoc );
SwNodes& rNds = rDoc.GetNodes();
SwNodeIndex aIdx( rNds.GetEndOfExtras(), 1 );
SwCntntNode* pCNd = rNds.GoNext( &aIdx );
if( pCNd )
{
pCNd->SetAttr( SwFmtPageDesc(
rDoc.GetPageDescFromPool(RES_POOLPAGE_HTML) ) );
pCNd->ChgFmtColl( rDoc.GetTxtCollFromPool( RES_POOLCOLL_TEXT ));
}
return bRet;
}
#94187# prevent screen update during XML export (the export switches redline view modes)
checked in on behalf of JP
/*************************************************************************
*
* $RCSfile: shellio.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: dvo $ $Date: 2001-11-08 18:55:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif
#pragma hdrstop
#define ITEMID_BOXINFO SID_ATTR_BORDER_INNER
#include <hintids.hxx>
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif
#ifndef _TIME_HXX
#include <tools/time.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef SVTOOLS_FSTATHELPER_HXX
#include <svtools/fstathelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX //autogen
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_ULSPITEM_HXX //autogen
#include <svx/ulspitem.hxx>
#endif
#ifndef _SVX_BOXITEM_HXX //autogen
#include <svx/boxitem.hxx>
#endif
#ifndef _SVXLINKMGR_HXX
#include <svx/linkmgr.hxx>
#endif
#ifndef _SVX_PAPERINF_HXX //autogen
#include <svx/paperinf.hxx>
#endif
#ifndef _NODE_HXX //autogen
#include <node.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen
#include <fmtanchr.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _UNDOBJ_HXX
#include <undobj.hxx> // fuer Undo Insert-Dokument
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo Insert-Dokument
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx>
#endif
#ifndef _TBLSEL_HXX
#include <tblsel.hxx>
#endif
#ifndef _PAGEDESC_HXX
#include <pagedesc.hxx>
#endif
#ifndef _POOLFMT_HXX
#include <poolfmt.hxx>
#endif
#ifndef _FLTINI_HXX
#include <fltini.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SW3IO_HXX
#include <sw3io.hxx>
#endif
#ifndef _REDLINE_HXX
#include <redline.hxx>
#endif
#ifndef _LINKENUM_HXX
#include <linkenum.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
//////////////////////////////////////////////////////////////////////////
ULONG SwReader::Read( const Reader& rOptions )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = 0 != pCrsr;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
if( 0 != (po->pMedium = pMedium ) &&
!po->SetStrmStgPtr() )
{
po->SetReadUTF8( FALSE );
po->SetBlockMode( FALSE );
po->SetOrganizerMode( FALSE );
return ERR_SWG_FILE_FORMAT_ERROR;
}
ULONG nError = 0L;
GetDoc();
// am Sw3-Reader noch den pIo-Pointer "loeschen"
if( po == ReadSw3 && pDoc->GetDocShell() &&
((Sw3Reader*)po)->GetSw3Io() != pDoc->GetDocShell()->GetIoSystem() )
((Sw3Reader*)po)->SetSw3Io( pDoc->GetDocShell()->GetIoSystem() );
// waehrend des einlesens kein OLE-Modified rufen
Link aOLELink( pDoc->GetOle2Link() );
pDoc->SetOle2Link( Link() );
pDoc->bInReading = TRUE;
SwPaM *pPam;
if( pCrsr )
pPam = pCrsr;
else
{
// Wenn der Reader nicht mit einem Shell konstruiert wurde,
// selber einen Pam machen.
SwNodeIndex nNode( pDoc->GetNodes().GetEndOfContent(), -1 );
pPam = new SwPaM( nNode );
// Bei Web-Dokumenten wird die Default-Vorlage schon im InitNew
// gesetzt und braucht deshalb nicht nochmal gesetzt zu werden.
// Das gilt natuerlich nicht, wenn der Filter nicht der HTML-Filter
// ist oder im ConvertFrom zuvor ein SetTemplateName gerufen
// wurde.
if( !pDoc->IsHTMLMode() || ReadHTML != po || !po->pTemplate )
po->SetTemplate( *pDoc );
}
// Pams sind ringfoermig verkettet. Aufhoeren, wenn man wieder beim
// ersten ist.
SwPaM *pEnd = pPam;
SwUndoInsDoc* pUndo = 0L;
BOOL bReadPageDescs = FALSE;
BOOL bDocUndo = pDoc->DoesUndo();
BOOL bSaveUndo = bDocUndo && pCrsr;
if( bSaveUndo )
{
// das Einlesen von Seitenvorlagen ist nicht Undofaehig!
if( 0 != ( bReadPageDescs = po->aOpt.IsPageDescs() ) )
{
bSaveUndo = FALSE;
pDoc->DelAllUndoObj();
}
else
{
pDoc->ClearRedo();
pDoc->StartUndo( UNDO_INSDOKUMENT );
}
}
pDoc->DoUndo( FALSE );
SwNodeIndex aSplitIdx( pDoc->GetNodes() );
SwRedlineMode eOld = pDoc->GetRedlineMode();
pDoc->SetRedlineMode_intern( REDLINE_IGNORE );
// Array von FlyFormaten
SwSpzFrmFmts aFlyFrmArr;
// only read templates? then ignore multi selection!
BOOL bFmtsOnly = po->aOpt.IsFmtsOnly();
while( TRUE )
{
if( bSaveUndo )
pUndo = new SwUndoInsDoc( *pPam );
SwPaM* pUndoPam = 0L;
if( bDocUndo || pCrsr )
{
// Pam auf den Node davor setzen damit er nicht mit verschoben wird
const SwNodeIndex& rTmp = pPam->GetPoint()->nNode;
pUndoPam = new SwPaM( rTmp, rTmp, 0, -1 );
}
// Speicher mal alle Fly's
if( pCrsr )
aFlyFrmArr.Insert( pDoc->GetSpzFrmFmts(), 0L );
xub_StrLen nSttCntnt = pPam->GetPoint()->nContent.GetIndex();
// damit fuer alle Reader die Ende-Position immer stimmt, hier
// pflegen.
SwCntntNode* pCNd = pPam->GetCntntNode();
xub_StrLen nEndCntnt = pCNd ? pCNd->Len() - nSttCntnt : 0;
SwNodeIndex aEndPos( pPam->GetPoint()->nNode, 1 );
nError = po->Read( *pDoc, *pPam, aFileName );
if( !IsError( nError )) // dann setzen wir das Ende mal richtig
{
aEndPos--;
pCNd = aEndPos.GetNode().GetCntntNode();
if( !pCNd && 0 == ( pCNd = pDoc->GetNodes().GoPrevious( &aEndPos ) ))
pCNd = pDoc->GetNodes().GoNext( &aEndPos );
pPam->GetPoint()->nNode = aEndPos;
xub_StrLen nLen = pCNd->Len();
if( nLen < nEndCntnt )
nEndCntnt = 0;
else
nEndCntnt = nLen - nEndCntnt;
pPam->GetPoint()->nContent.Assign( pCNd, nEndCntnt );
}
if( pCrsr )
{
*pUndoPam->GetMark() = *pPam->GetPoint();
pUndoPam->GetPoint()->nNode++;
SwNode* pNd = pUndoPam->GetNode();
if( pNd->IsCntntNode() )
pUndoPam->GetPoint()->nContent.Assign(
(SwCntntNode*)pNd, nSttCntnt );
else
pUndoPam->GetPoint()->nContent.Assign( 0, 0 );
int bChkHeaderFooter = pNd->FindHeaderStartNode() ||
pNd->FindFooterStartNode();
// Suche alle neuen Fly's und speicher sie als einzelne Undo
// Objecte
for( USHORT n = 0; n < pDoc->GetSpzFrmFmts()->Count(); ++n )
{
SwFrmFmt* pFrmFmt = (*pDoc->GetSpzFrmFmts())[ n ];
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
if( USHRT_MAX == aFlyFrmArr.GetPos( pFrmFmt) )
{
if( FLY_PAGE == rAnchor.GetAnchorId() ||
( FLY_AT_CNTNT == rAnchor.GetAnchorId() &&
rAnchor.GetCntntAnchor() &&
( pUndoPam->GetPoint()->nNode ==
rAnchor.GetCntntAnchor()->nNode ||
pUndoPam->GetMark()->nNode ==
rAnchor.GetCntntAnchor()->nNode ) ) )
{
if( bChkHeaderFooter &&
FLY_AT_CNTNT == rAnchor.GetAnchorId() &&
RES_DRAWFRMFMT == pFrmFmt->Which() )
{
// DrawObjecte in Kopf-/Fusszeilen ist nicht
// erlaubt!
pFrmFmt->DelFrms();
pDoc->DelFrmFmt( pFrmFmt );
--n;
}
else
{
if( bSaveUndo )
pDoc->AppendUndo( new SwUndoInsLayFmt( pFrmFmt ) );
if( pFrmFmt->GetDepends() )
{
// beim Insert legen Draw-Objecte einen Frame an
// also weg damit.
pFrmFmt->DelFrms();
}
if( FLY_PAGE == rAnchor.GetAnchorId() )
{
if( !rAnchor.GetCntntAnchor() )
pFrmFmt->MakeFrms();
else if( pCrsr )
// seitengebundene Flys eingefuegt, dann schalte
// die Optimierungs-Flags vom SwDoc ab. Sonst
// werden die Flys nicht an der Position erzeugt.
pDoc->SetLoaded( FALSE );
}
else
pFrmFmt->MakeFrms();
}
}
}
}
if( aFlyFrmArr.Count() )
aFlyFrmArr.Remove( 0, aFlyFrmArr.Count() );
pDoc->SetRedlineMode_intern( eOld );
if( pDoc->IsRedlineOn() )
pDoc->AppendRedline( new SwRedline( REDLINE_INSERT, *pUndoPam ));
else
pDoc->SplitRedline( *pUndoPam );
pDoc->SetRedlineMode_intern( REDLINE_IGNORE );
}
if( bSaveUndo )
{
pUndo->SetInsertRange( *pUndoPam, FALSE );
pDoc->AppendUndo( pUndo );
}
delete pUndoPam;
pPam = (SwPaM *) pPam->GetNext();
if( pPam == pEnd )
break;
// only read templates? then ignore multi selection! Bug 68593
if( bFmtsOnly )
break;
/*
* !!! man muss selbst den Status vom Stream zuruecksetzen. !!!
* Beim seekg wird der akt. Status, eof- und bad-Bit
* gesetzt, warum weiss keiner
*/
if( pStrm )
{
pStrm->Seek(0);
pStrm->ResetError();
}
}
pDoc->bInReading = FALSE;
pDoc->SetAllUniqueFlyNames();
if( bReadPageDescs )
pDoc->DoUndo( TRUE );
else
{
pDoc->DoUndo( bDocUndo );
if( bSaveUndo )
pDoc->EndUndo( UNDO_INSDOKUMENT );
}
// Wenn der Pam nur fuers Lesen konstruiert wurde, jetzt zerstoeren.
if( !pCrsr )
{
delete pPam; // ein neues aufgemacht.
// alle Links updaten und Fehler melden
// (die Graphic-Links nicht, passiert ueber unseren Grafik-Cache!!)
// JP 20.03.96: aber nicht wenn die DocShell als INTERNAL
// construiert wurde (FileLinks in FileLinks in ...)
// JP 27.06.96: wenn internal, dann nie Updaten! (rekursionen werden
// sonst nicht erkannt! ( Bug )
SfxObjectCreateMode eMode;
USHORT nLinkMode = pDoc->GetLinkUpdMode();
if( nLinkMode != NEVER && pDoc->GetDocShell() &&
pDoc->GetLinkManager().GetLinks().Count() &&
SFX_CREATE_MODE_INTERNAL !=
( eMode = pDoc->GetDocShell()->GetCreateMode()) &&
SFX_CREATE_MODE_ORGANIZER != eMode &&
SFX_CREATE_MODE_PREVIEW != eMode &&
!pDoc->GetDocShell()->IsPreview() )
{
ViewShell* pVSh = 0;
if( pDoc->GetRootFrm() && !pDoc->GetEditShell( &pVSh ) && !pVSh )
{
ViewShell aVSh( *pDoc, 0, 0 );
SET_CURR_SHELL( &aVSh );
pDoc->GetLinkManager().UpdateAllLinks( nLinkMode == MANUAL, TRUE, FALSE );
}
else
pDoc->GetLinkManager().UpdateAllLinks( nLinkMode == MANUAL, TRUE, FALSE );
}
eOld = (SwRedlineMode)(pDoc->GetRedlineMode() & ~REDLINE_IGNORE);
pDoc->SetFieldsDirty( FALSE );
}
pDoc->SetRedlineMode_intern( eOld );
pDoc->SetOle2Link( aOLELink );
if( pCrsr ) // das Doc ist jetzt modifiziert
pDoc->SetModified();
if( po == ReadSw3 ) // am Sw3-Reader noch den pIo-Pointer "loeschen"
((Sw3Reader*)po)->SetSw3Io( 0 );
po->SetReadUTF8( FALSE );
po->SetBlockMode( FALSE );
po->SetOrganizerMode( FALSE );
return nError;
}
/*
* Konstruktoren, Destruktor
*/
// Initiales Einlesben
SwReader::SwReader( SvStream& rStrm, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
SwReader::SwReader( SvStorage& rStg, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
SwReader::SwReader( SfxMedium& rMedium, const String& rFileName, SwDoc *pDoc )
: SwDocFac( pDoc ),
pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
aFileName( rFileName ),
pCrsr( 0 )
{
}
// In ein existierendes Dokument einlesen
SwReader::SwReader( SvStream& rStrm, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pCrsr( &rPam )
{
}
SwReader::SwReader( SvStorage& rStg, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStg( &rStg ),
pStrm( 0 ),
pMedium( 0 ),
pCrsr( &rPam )
{
}
SwReader::SwReader( SfxMedium& rMedium, const String& rFileName, SwPaM& rPam )
: SwDocFac( rPam.GetDoc() ),
aFileName( rFileName ),
pStg( 0 ),
pStrm( 0 ),
pMedium( &rMedium ),
pCrsr( &rPam )
{
}
Reader::Reader()
: pStrm(0), pStg(0), pMedium(0), pTemplate(0),
bTmplBrowseMode( FALSE ), bInsertMode( FALSE ),
bReadUTF8( FALSE ), bBlockMode( FALSE ), bOrganizerMode( FALSE ),
bHasAskTemplateName( FALSE )
{
}
Reader::~Reader()
{
delete pTemplate;
}
String Reader::GetTemplateName() const
{
return aEmptyStr;
}
// Die Filter-Vorlage laden, setzen und wieder freigeben
SwDoc* Reader::GetTemplateDoc()
{
if( !bHasAskTemplateName )
{
SetTemplateName( GetTemplateName() );
bHasAskTemplateName = TRUE;
}
if( !aTemplateNm.Len() )
ClearTemplate();
else
{
INetURLObject aTDir( URIHelper::SmartRelToAbs(aTemplateNm) );
DateTime aCurrDateTime;
BOOL bLoad = FALSE;
// Wenn das Template schon mal geladen wurde, nur einmal pro
// Minute nachschauen, ob es geaendert wurde.
if( !pTemplate || aCurrDateTime >= aChkDateTime )
{
Date aTstDate;
Time aTstTime;
if( FStatHelper::GetModifiedDateTimeOfFile(
aTDir.GetMainURL( INetURLObject::NO_DECODE ),
&aTstDate, &aTstTime ) &&
( !pTemplate || aDStamp != aTstDate || aTStamp != aTstTime ))
{
bLoad = TRUE;
aDStamp = aTstDate;
aTStamp = aTstTime;
}
// Erst in einer Minute wieder mal nachschauen, ob sich die
// Vorlage geaendert hat.
aChkDateTime = aCurrDateTime;
aChkDateTime += Time( 0L, 1L );
}
if( bLoad )
{
ClearTemplate();
ASSERT( !pTemplate, "Who holds the template doc?" );
SvStorageRef xStor( new SvStorage( aTDir.GetFull(), STREAM_READ ));
ULONG nFormat = xStor->GetFormat();
long nVersion = SOFFICE_FILEFORMAT_60;
switch( nFormat )
{
case SOT_FORMATSTR_ID_STARWRITER_50:
case SOT_FORMATSTR_ID_STARWRITERGLOB_50:
case SOT_FORMATSTR_ID_STARWRITERWEB_50:
nVersion = SOFFICE_FILEFORMAT_50;
break;
case SOT_FORMATSTR_ID_STARWRITER_40:
case SOT_FORMATSTR_ID_STARWRITERGLOB_40:
case SOT_FORMATSTR_ID_STARWRITERWEB_40:
nVersion = SOFFICE_FILEFORMAT_40;
break;
case SOT_FORMATSTR_ID_STARWRITER_30:
nVersion = SOFFICE_FILEFORMAT_31;
break;
}
if( nVersion >= SOFFICE_FILEFORMAT_60 )
{
SwDocShell *pDocSh =
new SwDocShell ( SFX_CREATE_MODE_INTERNAL );
SvEmbeddedObjectRef xDocSh = pDocSh;
if( pDocSh->DoInitNew( 0 ) )
{
pTemplate = pDocSh->GetDoc();
pTemplate->SetOle2Link( Link() );
pTemplate->DoUndo( FALSE ); // always FALSE
pTemplate->SetBrowseMode( bTmplBrowseMode );
ReadXML->SetOrganizerMode( TRUE );
SwReader aRdr( *xStor, aEmptyStr, pTemplate );
aRdr.Read( *ReadXML );
ReadXML->SetOrganizerMode( FALSE );
pTemplate->AddLink();
}
}
else
{
pTemplate = new SwDoc;
pTemplate->AddLink();
// sicher ist sicher
pTemplate->SetBrowseMode( bTmplBrowseMode );
xStor->SetVersion( nVersion );
Sw3Io aIO( *pTemplate );
aIO.LoadStyles( xStor );
}
}
ASSERT( !pTemplate || FStatHelper::IsDocument(
aTDir.GetMainURL( INetURLObject::NO_DECODE ) ) ||
aTemplateNm.EqualsAscii( "$$Dummy$$" ),
"TemplatePtr but no template exist!" );
}
return pTemplate;
}
BOOL Reader::SetTemplate( SwDoc& rDoc )
{
BOOL bRet = FALSE;
GetTemplateDoc();
if( pTemplate )
{
rDoc.ReplaceStyles( *pTemplate );
rDoc.SetFixFields();
bRet = TRUE;
}
return bRet;
}
void Reader::ClearTemplate()
{
if( pTemplate )
{
if( 0 == pTemplate->RemoveLink() )
delete pTemplate,
pTemplate = 0;
}
}
void Reader::SetTemplateName( const String& rDir )
{
if( rDir.Len() && aTemplateNm != rDir )
{
ClearTemplate();
aTemplateNm = rDir;
}
}
void Reader::MakeHTMLDummyTemplateDoc()
{
ClearTemplate();
pTemplate = new SwDoc;
pTemplate->AddLink();
pTemplate->SetBrowseMode( bTmplBrowseMode );
pTemplate->GetPrt( TRUE );
aChkDateTime = Date( 1, 1, 2300 ); // 2300. Jahrtausend sollte reichen
aTemplateNm.AssignAscii( "$$Dummy$$" );
}
// alle die die Streams / Storages nicht geoeffnet brauchen,
// muessen die Methode ueberladen
int Reader::SetStrmStgPtr()
{
ASSERT( pMedium, "Wo ist das Medium??" );
if( pMedium->IsStorage() )
{
if( SW_STORAGE_READER & GetReaderType() )
{
pStg = pMedium->GetStorage();
return TRUE;
}
}
else if( SW_STREAM_READER & GetReaderType() )
{
pStrm = pMedium->GetInStream();
return TRUE;
}
return FALSE;
}
int Reader::GetReaderType()
{
return SW_STREAM_READER;
}
void Reader::SetFltName( const String& )
{
}
void Reader::SetNoOutlineNum( SwDoc& rDoc )
{
// JP 10.03.96: jetzt wieder keine Nummerierung in den Vorlagen
#if 0
//JP 18.01.96: Alle Ueberschriften sind normalerweise ohne
// Kapitelnummer. Darum hier explizit abschalten
// weil das Default jetzt wieder auf AN ist.
SwNumRules aRules( OUTLINE_RULES );
if( rDoc.GetOutlineNumRules() )
aRules = *rDoc.GetOutlineNumRules();
for( BYTE n = 0; n < MAXLEVEL; ++n )
{
SwNumFmt aFmt( aRules.Get( n ) );
aFmt.eType = NUMBER_NONE;
aRules.Set( n, aFmt );
}
rDoc.SetOutlineNumRules( aRules );
// und UeberschirftBasis ohne Einrueckung!
SwTxtFmtColl* pCol = rDoc.GetTxtCollFromPool( RES_POOLCOLL_HEADLINE_BASE );
pCol->ResetAttr( RES_LR_SPACE );
#endif
}
void Reader::ResetFrmFmtAttrs( SfxItemSet &rFrmSet )
{
rFrmSet.Put( SvxLRSpaceItem() );
rFrmSet.Put( SvxULSpaceItem() );
rFrmSet.Put( SvxBoxItem() );
}
void Reader::ResetFrmFmts( SwDoc& rDoc )
{
for( USHORT i=0; i<3; i++ )
{
USHORT nPoolId;
switch( i )
{
case 0: nPoolId = RES_POOLFRM_FRAME; break;
case 1: nPoolId = RES_POOLFRM_GRAPHIC; break;
case 2: nPoolId = RES_POOLFRM_OLE; break;
}
SwFrmFmt *pFrmFmt = rDoc.GetFrmFmtFromPool( nPoolId );
pFrmFmt->ResetAttr( RES_LR_SPACE );
pFrmFmt->ResetAttr( RES_UL_SPACE );
pFrmFmt->ResetAttr( RES_BOX );
}
}
// ------------------------------------------------
BOOL SwReader::HasGlossaries( const Reader& rOptions )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = FALSE;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
BOOL bRet = FALSE;
if( !( 0 != (po->pMedium = pMedium ) && !po->SetStrmStgPtr() ))
bRet = po->HasGlossaries();
return bRet;
}
BOOL SwReader::ReadGlossaries( const Reader& rOptions,
SwTextBlocks& rBlocks, BOOL bSaveRelFiles )
{
// Variable uebertragen
Reader* po = (Reader*) &rOptions;
po->pStrm = pStrm;
po->pStg = pStg;
po->bInsertMode = FALSE;
// ist ein Medium angegeben, dann aus diesem die Streams besorgen
BOOL bRet = FALSE;
if( !( 0 != (po->pMedium = pMedium ) && !po->SetStrmStgPtr() ))
bRet = po->ReadGlossaries( rBlocks, bSaveRelFiles );
return bRet;
}
BOOL Reader::HasGlossaries() const
{
return FALSE;
}
BOOL Reader::ReadGlossaries( SwTextBlocks&, BOOL ) const
{
return FALSE;
}
// ------------------------------------------------
int StgReader::GetReaderType()
{
return SW_STORAGE_READER;
}
/*
* Writer
*/
/*
* Konstruktoren, Destruktoren sind inline (inc/shellio.hxx).
*/
SwWriter::SwWriter( SvStream& rStrm, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
SwWriter::SwWriter(SvStream& rStrm,SwDoc &rDoc)
:pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
SwWriter::SwWriter( SvStream& rStrm, SwPaM& rPam, BOOL bWriteAll )
: pStrm( &rStrm ),
pStg( 0 ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
/*
SwWriter::SwWriter( SvStorage& rStg, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
SwWriter::SwWriter(SvStorage& rStg,SwDoc &rDoc)
:pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
/*
SwWriter::SwWriter( SvStorage& rStg, SwPaM& rPam, BOOL bWriteAll )
: pStrm( 0 ),
pStg( &rStg ),
pMedium( 0 ),
pShell( 0 ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
SwWriter::SwWriter( SfxMedium& rMedium, SwCrsrShell &rShell, BOOL bWriteAll )
: pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
pShell( &rShell ),
pOutPam( 0 ),
rDoc( *rShell.GetDoc() ),
bWriteAll( bWriteAll )
{
}
SwWriter::SwWriter( SfxMedium& rMedium, SwDoc &rDoc)
:pStrm( 0 ),
pStg( 0 ),
pMedium( &rMedium ),
pShell( 0 ),
pOutPam( 0 ),
rDoc( rDoc ),
bWriteAll( TRUE )
{
}
/*
SwWriter::SwWriter( SfxMedium& rMedium, SwPaM& rPam, BOOL bWriteAll )
: pStrm( 0 ),
pStg( 0 ),
pShell( 0 ),
pMedium( &rMedium ),
pOutPam( &rPam ),
rDoc( *rPam.GetDoc() ),
bWriteAll( bWriteAll )
{
}
*/
ULONG SwWriter::Write( WriterRef& rxWriter, const String* pRealFileName )
{
BOOL bHasMark = FALSE;
SwPaM * pPam;
SwDoc *pDoc = 0L;
if ( pShell && !bWriteAll && pShell->IsTableMode() )
{
bWriteAll = TRUE;
pDoc = new SwDoc;
pDoc->AddLink();
// kopiere Teile aus einer Tabelle: lege eine Tabelle mit der Breite
// von der Originalen an und kopiere die selectierten Boxen.
// Die Groessen werden prozentual korrigiert.
// lasse ueber das Layout die Boxen suchen
SwSelBoxes aBoxes;
GetTblSel( *pShell, aBoxes );
SwTableNode* pTblNd = (SwTableNode*)aBoxes[0]->GetSttNd()->FindStartNode();
SwNodeIndex aIdx( pDoc->GetNodes().GetEndOfExtras(), 2 );
SwCntntNode *pNd = aIdx.GetNode().GetCntntNode();
ASSERT( pNd, "Node not found" );
SwPosition aPos( aIdx, SwIndex( pNd ) );
pTblNd->GetTable().MakeCopy( pDoc, aPos, aBoxes );
}
if( !bWriteAll && ( pShell || pOutPam ))
{
if( pShell )
pPam = pShell->GetCrsr();
else
pPam = pOutPam;
SwPaM *pEnd = pPam;
// Erste Runde: Nachsehen, ob eine Selektion besteht.
while(TRUE)
{
bHasMark = bHasMark || pPam->HasMark();
pPam = (SwPaM *) pPam->GetNext();
if(bHasMark || pPam == pEnd)
break;
}
// Wenn keine Selektion besteht, eine ueber das ganze Dokument aufspannen.
if(!bHasMark)
{
if( pShell )
{
pShell->Push();
pShell->SttDoc();
pShell->SetMark();
pShell->EndDoc();
}
else
{
pPam = new SwPaM( *pPam );
pPam->Move( fnMoveBackward, fnGoDoc );
pPam->SetMark();
pPam->Move( fnMoveForward, fnGoDoc );
}
}
// pPam ist immer noch der akt. Cursor !!
}
else
{
// keine Shell oder alles schreiben -> eigenen Pam erzeugen
SwDoc* pOutDoc = pDoc ? pDoc : &rDoc;
pPam = new SwPaM( pOutDoc->GetNodes().GetEndOfContent() );
pPam->Move( fnMoveBackward, fnGoDoc );
pPam->SetMark();
pPam->Move( fnMoveForward, fnGoDoc );
}
rxWriter->bWriteAll = bWriteAll;
SwDoc* pOutDoc = pDoc ? pDoc : &rDoc;
// falls der Standart PageDesc. immer noch auf initalen Werten steht
// (wenn z.B. kein Drucker gesetzt wurde) dann setze jetzt auf DIN A4
if( !pOutDoc->GetPrt() )
{
const SwPageDesc& rPgDsc = pOutDoc->GetPageDesc( 0L );
//const SwPageDesc& rPgDsc = *pOutDoc->GetPageDescFromPool( RES_POOLPAGE_STANDARD );;
const SwFmtFrmSize& rSz = rPgDsc.GetMaster().GetFrmSize();
// Clipboard-Dokument wird immer ohne Drucker angelegt, so ist
// der Std.PageDesc immer aug LONG_MAX !! Mappe dann auf DIN A4
if( LONG_MAX == rSz.GetHeight() || LONG_MAX == rSz.GetWidth() )
{
SwPageDesc aNew( rPgDsc );
SwFmtFrmSize aNewSz( rSz );
aNewSz.SetHeight( lA4Height );
aNewSz.SetWidth( lA4Width );
aNew.GetMaster().SetAttr( aNewSz );
pOutDoc->ChgPageDesc( 0, aNew );
}
}
SwEditShell* pESh = pOutDoc->GetEditShell();
if( pESh )
pESh->StartAllAction();
BOOL bWasPurgeOle = pOutDoc->IsPurgeOLE();
pOutDoc->SetPurgeOLE( FALSE );
ULONG nError = 0;
if( pMedium )
nError = rxWriter->Write( *pPam, *pMedium, pRealFileName );
else if( pStg )
nError = rxWriter->Write( *pPam, *pStg, pRealFileName );
else if( pStrm )
nError = rxWriter->Write( *pPam, *pStrm, pRealFileName );
pOutDoc->SetPurgeOLE( bWasPurgeOle );
if( pESh )
pESh->EndAllAction();
// Falls nur zum Schreiben eine Selektion aufgespannt wurde, vor der
// Rueckkehr den alten Crsr wieder herstellen.
if( !bWriteAll && ( pShell || pOutPam ))
{
if(!bHasMark)
{
if( pShell )
pShell->Pop( FALSE );
else
delete pPam;
}
}
else
{
delete pPam; // loesche den hier erzeugten Pam
// Alles erfolgreich geschrieben? Sag' das dem Dokument!
if( !IsError( nError ) && !pDoc )
rDoc.ResetModified();
}
if ( pDoc )
{
if ( !pDoc->RemoveLink() )
delete pDoc;
bWriteAll = FALSE;
}
return nError;
}
/* */
// ----------------------------------------------------------------------
BOOL SetHTMLTemplate( SwDoc & rDoc )
{
// Vorlagennamen von den Sfx-HTML-Filter besorgen!!!
if( !ReadHTML->GetTemplateDoc() )
ReadHTML->MakeHTMLDummyTemplateDoc();
BOOL bRet = ReadHTML->SetTemplate( rDoc );
SwNodes& rNds = rDoc.GetNodes();
SwNodeIndex aIdx( rNds.GetEndOfExtras(), 1 );
SwCntntNode* pCNd = rNds.GoNext( &aIdx );
if( pCNd )
{
pCNd->SetAttr( SwFmtPageDesc(
rDoc.GetPageDescFromPool(RES_POOLPAGE_HTML) ) );
pCNd->ChgFmtColl( rDoc.GetTxtCollFromPool( RES_POOLCOLL_TEXT ));
}
return bRet;
}
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "assert.hpp"
#include "Variable.hpp"
#include "Type.hpp"
#include "VisitorUtils.hpp"
#include "mtac/ConstantPropagationProblem.hpp"
#include "mtac/Utils.hpp"
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/LiveVariableAnalysisProblem.hpp"
using namespace eddic;
typedef mtac::ConstantPropagationProblem::ProblemDomain ProblemDomain;
ProblemDomain mtac::ConstantPropagationProblem::Boundary(std::shared_ptr<mtac::Function> function){
pointer_escaped = mtac::escape_analysis(function);
return default_element();
}
ProblemDomain mtac::ConstantPropagationProblem::meet(ProblemDomain& in, ProblemDomain& out){
auto result = mtac::intersection_meet(in, out);
//Remove all the temporary
for(auto it = std::begin(result.values()); it != std::end(result.values());){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&it->second)){
auto variable = *ptr;
if (variable->position().isTemporary()){
it = result.values().erase(it);
} else {
++it;
}
} else {
++it;
}
}
return result;
}
namespace {
struct ConstantCollector : public boost::static_visitor<> {
ProblemDomain& out;
std::shared_ptr<Variable> var;
ConstantCollector(ProblemDomain& out, std::shared_ptr<Variable> var) : out(out), var(var) {}
void operator()(int value){
out[var] = value;
}
void operator()(const std::string& value){
out[var] = value;
}
void operator()(double value){
out[var] = value;
}
void operator()(std::shared_ptr<Variable> variable){
if(variable != var){
out[var] = variable;
}
}
template<typename T>
void operator()(T&){
out.erase(var);
}
};
} //end of anonymous namespace
ProblemDomain mtac::ConstantPropagationProblem::transfer(std::shared_ptr<mtac::BasicBlock>/* basic_block*/, mtac::Statement& statement, ProblemDomain& in){
auto out = in;
//Quadruple affects variable
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto quadruple = *ptr;
if(quadruple->op == mtac::Operator::NOP){
return out;
}
if(quadruple->op == mtac::Operator::ASSIGN || quadruple->op == mtac::Operator::FASSIGN){
ConstantCollector collector(out, quadruple->result);
visit(collector, *quadruple->arg1);
} else {
auto op = quadruple->op;
if(mtac::erase_result(op)){
//The result is not constant at this point
out.erase(quadruple->result);
//Cancel the copy of the variable erased
for(auto it = std::begin(out.values()); it != std::end(out.values());){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&it->second)){
auto variable = *ptr;
if (variable == quadruple->result){
it = out.values().erase(it);
} else {
++it;
}
} else {
++it;
}
}
}
}
}
//Passing a variable by pointer erases its value
else if (auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
auto param = *ptr;
if(param->address){
auto variable = boost::get<std::shared_ptr<Variable>>(param->arg);
//Impossible to know if the variable is modified or not, consider it modified
out.erase(variable);
}
}
return out;
}
namespace {
struct ConstantOptimizer : public boost::static_visitor<> {
mtac::Domain<mtac::ConstantPropagationValues>& results;
mtac::EscapedVariables& pointer_escaped;
bool changes = false;
ConstantOptimizer(mtac::Domain<mtac::ConstantPropagationValues>& results, mtac::EscapedVariables& pointer_escaped) : results(results), pointer_escaped(pointer_escaped) {}
bool optimize_arg(mtac::Argument& arg){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&arg)){
if(results.find(*ptr) != results.end() && pointer_escaped->find(*ptr) == pointer_escaped->end()){
arg = results[*ptr];
return true;
}
}
return false;
}
bool optimize_optional(boost::optional<mtac::Argument>& arg){
if(arg){
return optimize_arg(*arg);
}
return false;
}
void operator()(std::shared_ptr<mtac::Quadruple> quadruple){
//Do not replace a variable by a constant when used in offset
if(quadruple->op != mtac::Operator::PDOT && quadruple->op != mtac::Operator::DOT && quadruple->op != mtac::Operator::PASSIGN){
changes |= optimize_optional(quadruple->arg1);
}
if(quadruple->op != mtac::Operator::DOT_PASSIGN){
changes |= optimize_optional(quadruple->arg2);
}
if(!mtac::erase_result(quadruple->op) && quadruple->result && quadruple->op != mtac::Operator::DOT_ASSIGN){
if(results.find(quadruple->result) != results.end()){
if(mtac::isVariable(results[quadruple->result])){
auto var = boost::get<std::shared_ptr<Variable>>(results[quadruple->result]);
if(!var->position().isTemporary()){
quadruple->result = var;
}
}
}
}
}
void operator()(std::shared_ptr<mtac::Param> param){
if(!param->address){
changes |= optimize_arg(param->arg);
}
}
void operator()(std::shared_ptr<mtac::IfFalse> if_false){
changes |= optimize_arg(if_false->arg1);
changes |= optimize_optional(if_false->arg2);
}
void operator()(std::shared_ptr<mtac::If> if_){
changes |= optimize_arg(if_->arg1);
changes |= optimize_optional(if_->arg2);
}
template<typename T>
void operator()(T&){
//NOP
}
};
} //end of anonymous namespace
bool mtac::ConstantPropagationProblem::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> global_results){
ConstantOptimizer optimizer(global_results->IN_S[statement], pointer_escaped);
visit(optimizer, statement);
return optimizer.changes;
}
Fix support for label constant propagation
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "assert.hpp"
#include "Variable.hpp"
#include "Type.hpp"
#include "VisitorUtils.hpp"
#include "mtac/ConstantPropagationProblem.hpp"
#include "mtac/Utils.hpp"
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/LiveVariableAnalysisProblem.hpp"
using namespace eddic;
typedef mtac::ConstantPropagationProblem::ProblemDomain ProblemDomain;
ProblemDomain mtac::ConstantPropagationProblem::Boundary(std::shared_ptr<mtac::Function> function){
pointer_escaped = mtac::escape_analysis(function);
return default_element();
}
ProblemDomain mtac::ConstantPropagationProblem::meet(ProblemDomain& in, ProblemDomain& out){
auto result = mtac::intersection_meet(in, out);
//Remove all the temporary
for(auto it = std::begin(result.values()); it != std::end(result.values());){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&it->second)){
auto variable = *ptr;
if (variable->position().isTemporary()){
it = result.values().erase(it);
} else {
++it;
}
} else {
++it;
}
}
return result;
}
namespace {
struct ConstantCollector : public boost::static_visitor<> {
ProblemDomain& out;
std::shared_ptr<Variable> var;
ConstantCollector(ProblemDomain& out, std::shared_ptr<Variable> var) : out(out), var(var) {}
void operator()(int value){
out[var] = value;
}
//Warning : Do not pass it by reference to avoid going to the template function
void operator()(std::string value){
out[var] = value;
}
void operator()(double value){
out[var] = value;
}
void operator()(std::shared_ptr<Variable> variable){
if(variable != var){
out[var] = variable;
}
}
template<typename T>
void operator()(T&){
out.erase(var);
}
};
} //end of anonymous namespace
ProblemDomain mtac::ConstantPropagationProblem::transfer(std::shared_ptr<mtac::BasicBlock>/* basic_block*/, mtac::Statement& statement, ProblemDomain& in){
auto out = in;
//Quadruple affects variable
if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
auto quadruple = *ptr;
if(quadruple->op == mtac::Operator::NOP){
return out;
}
if(quadruple->op == mtac::Operator::ASSIGN || quadruple->op == mtac::Operator::FASSIGN){
ConstantCollector collector(out, quadruple->result);
visit(collector, *quadruple->arg1);
} else {
auto op = quadruple->op;
if(mtac::erase_result(op)){
//The result is not constant at this point
out.erase(quadruple->result);
//Cancel the copy of the variable erased
for(auto it = std::begin(out.values()); it != std::end(out.values());){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&it->second)){
auto variable = *ptr;
if (variable == quadruple->result){
it = out.values().erase(it);
} else {
++it;
}
} else {
++it;
}
}
}
}
}
//Passing a variable by pointer erases its value
else if (auto* ptr = boost::get<std::shared_ptr<mtac::Param>>(&statement)){
auto param = *ptr;
if(param->address){
auto variable = boost::get<std::shared_ptr<Variable>>(param->arg);
//Impossible to know if the variable is modified or not, consider it modified
out.erase(variable);
}
}
return out;
}
namespace {
struct ConstantOptimizer : public boost::static_visitor<> {
mtac::Domain<mtac::ConstantPropagationValues>& results;
mtac::EscapedVariables& pointer_escaped;
bool changes = false;
ConstantOptimizer(mtac::Domain<mtac::ConstantPropagationValues>& results, mtac::EscapedVariables& pointer_escaped) : results(results), pointer_escaped(pointer_escaped) {}
bool optimize_arg(mtac::Argument& arg){
if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&arg)){
if(results.find(*ptr) != results.end() && pointer_escaped->find(*ptr) == pointer_escaped->end()){
arg = results[*ptr];
return true;
}
}
return false;
}
bool optimize_optional(boost::optional<mtac::Argument>& arg){
if(arg){
return optimize_arg(*arg);
}
return false;
}
void operator()(std::shared_ptr<mtac::Quadruple> quadruple){
//Do not replace a variable by a constant when used in offset
if(quadruple->op != mtac::Operator::PDOT && quadruple->op != mtac::Operator::DOT && quadruple->op != mtac::Operator::PASSIGN){
changes |= optimize_optional(quadruple->arg1);
}
if(quadruple->op != mtac::Operator::DOT_PASSIGN){
changes |= optimize_optional(quadruple->arg2);
}
if(!mtac::erase_result(quadruple->op) && quadruple->result && quadruple->op != mtac::Operator::DOT_ASSIGN){
if(results.find(quadruple->result) != results.end()){
if(mtac::isVariable(results[quadruple->result])){
auto var = boost::get<std::shared_ptr<Variable>>(results[quadruple->result]);
if(!var->position().isTemporary()){
quadruple->result = var;
}
}
}
}
}
void operator()(std::shared_ptr<mtac::Param> param){
if(!param->address){
changes |= optimize_arg(param->arg);
}
}
void operator()(std::shared_ptr<mtac::IfFalse> if_false){
changes |= optimize_arg(if_false->arg1);
changes |= optimize_optional(if_false->arg2);
}
void operator()(std::shared_ptr<mtac::If> if_){
changes |= optimize_arg(if_->arg1);
changes |= optimize_optional(if_->arg2);
}
template<typename T>
void operator()(T&){
//NOP
}
};
} //end of anonymous namespace
bool mtac::ConstantPropagationProblem::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> global_results){
ConstantOptimizer optimizer(global_results->IN_S[statement], pointer_escaped);
visit(optimizer, statement);
return optimizer.changes;
}
|
/*
* Copyright 2009 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcState.h"
#include "SkColorPriv.h"
#include "SkUtils.h"
#include "SkShader.h"
#if defined(__ARM_HAVE_NEON)
#include "SkBitmapProcState_filter.h"
#include <arm_neon.h>
#endif
#if __ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
void SI8_D16_nofilter_DX_arm(
const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count,
uint16_t* SK_RESTRICT colors) __attribute__((optimize("O1")));
void SI8_D16_nofilter_DX_arm(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, uint16_t* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(s.fDoFilter == false);
const uint16_t* SK_RESTRICT table = s.fBitmap->getColorTable()->lock16BitCache();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fBitmap->getPixels();
// buffer is y32, x16, x16, x16, x16, x16
// bump srcAddr to the proper row, since we're told Y never changes
SkASSERT((unsigned)xy[0] < (unsigned)s.fBitmap->height());
srcAddr = (const uint8_t*)((const char*)srcAddr +
xy[0] * s.fBitmap->rowBytes());
uint8_t src;
if (1 == s.fBitmap->width()) {
src = srcAddr[0];
uint16_t dstValue = table[src];
sk_memset16(colors, dstValue, count);
} else {
int i;
int count8 = count >> 3;
const uint16_t* SK_RESTRICT xx = (const uint16_t*)(xy + 1);
asm volatile (
"cmp %[count8], #0 \n\t" // compare loop counter with 0
"beq 2f \n\t" // if loop counter == 0, exit
"1: \n\t"
"ldmia %[xx]!, {r5, r7, r9, r11} \n\t" // load ptrs to pixels 0-7
"subs %[count8], %[count8], #1 \n\t" // decrement loop counter
"uxth r4, r5 \n\t" // extract ptr 0
"mov r5, r5, lsr #16 \n\t" // extract ptr 1
"uxth r6, r7 \n\t" // extract ptr 2
"mov r7, r7, lsr #16 \n\t" // extract ptr 3
"ldrb r4, [%[srcAddr], r4] \n\t" // load pixel 0 from image
"uxth r8, r9 \n\t" // extract ptr 4
"ldrb r5, [%[srcAddr], r5] \n\t" // load pixel 1 from image
"mov r9, r9, lsr #16 \n\t" // extract ptr 5
"ldrb r6, [%[srcAddr], r6] \n\t" // load pixel 2 from image
"uxth r10, r11 \n\t" // extract ptr 6
"ldrb r7, [%[srcAddr], r7] \n\t" // load pixel 3 from image
"mov r11, r11, lsr #16 \n\t" // extract ptr 7
"ldrb r8, [%[srcAddr], r8] \n\t" // load pixel 4 from image
"add r4, r4, r4 \n\t" // double pixel 0 for RGB565 lookup
"ldrb r9, [%[srcAddr], r9] \n\t" // load pixel 5 from image
"add r5, r5, r5 \n\t" // double pixel 1 for RGB565 lookup
"ldrb r10, [%[srcAddr], r10] \n\t" // load pixel 6 from image
"add r6, r6, r6 \n\t" // double pixel 2 for RGB565 lookup
"ldrb r11, [%[srcAddr], r11] \n\t" // load pixel 7 from image
"add r7, r7, r7 \n\t" // double pixel 3 for RGB565 lookup
"ldrh r4, [%[table], r4] \n\t" // load pixel 0 RGB565 from colmap
"add r8, r8, r8 \n\t" // double pixel 4 for RGB565 lookup
"ldrh r5, [%[table], r5] \n\t" // load pixel 1 RGB565 from colmap
"add r9, r9, r9 \n\t" // double pixel 5 for RGB565 lookup
"ldrh r6, [%[table], r6] \n\t" // load pixel 2 RGB565 from colmap
"add r10, r10, r10 \n\t" // double pixel 6 for RGB565 lookup
"ldrh r7, [%[table], r7] \n\t" // load pixel 3 RGB565 from colmap
"add r11, r11, r11 \n\t" // double pixel 7 for RGB565 lookup
"ldrh r8, [%[table], r8] \n\t" // load pixel 4 RGB565 from colmap
"ldrh r9, [%[table], r9] \n\t" // load pixel 5 RGB565 from colmap
"ldrh r10, [%[table], r10] \n\t" // load pixel 6 RGB565 from colmap
"ldrh r11, [%[table], r11] \n\t" // load pixel 7 RGB565 from colmap
"pkhbt r5, r4, r5, lsl #16 \n\t" // pack pixels 0 and 1
"pkhbt r6, r6, r7, lsl #16 \n\t" // pack pixels 2 and 3
"pkhbt r8, r8, r9, lsl #16 \n\t" // pack pixels 4 and 5
"pkhbt r10, r10, r11, lsl #16 \n\t" // pack pixels 6 and 7
"stmia %[colors]!, {r5, r6, r8, r10} \n\t" // store last 8 pixels
"bgt 1b \n\t" // loop if counter > 0
"2: \n\t"
: [xx] "+r" (xx), [count8] "+r" (count8), [colors] "+r" (colors)
: [table] "r" (table), [srcAddr] "r" (srcAddr)
: "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"
);
for (i = (count & 7); i > 0; --i) {
src = srcAddr[*xx++]; *colors++ = table[src];
}
}
s.fBitmap->getColorTable()->unlock16BitCache();
}
void SI8_opaque_D32_nofilter_DX_arm(
const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count,
SkPMColor* SK_RESTRICT colors) __attribute__((optimize("O1")));
void SI8_opaque_D32_nofilter_DX_arm(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, SkPMColor* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(s.fDoFilter == false);
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fBitmap->getPixels();
// buffer is y32, x16, x16, x16, x16, x16
// bump srcAddr to the proper row, since we're told Y never changes
SkASSERT((unsigned)xy[0] < (unsigned)s.fBitmap->height());
srcAddr = (const uint8_t*)((const char*)srcAddr + xy[0] * s.fBitmap->rowBytes());
if (1 == s.fBitmap->width()) {
uint8_t src = srcAddr[0];
SkPMColor dstValue = table[src];
sk_memset32(colors, dstValue, count);
} else {
const uint16_t* xx = (const uint16_t*)(xy + 1);
asm volatile (
"subs %[count], %[count], #8 \n\t" // decrement count by 8, set flags
"blt 2f \n\t" // if count < 0, branch to singles
"1: \n\t" // eights loop
"ldmia %[xx]!, {r5, r7, r9, r11} \n\t" // load ptrs to pixels 0-7
"uxth r4, r5 \n\t" // extract ptr 0
"mov r5, r5, lsr #16 \n\t" // extract ptr 1
"uxth r6, r7 \n\t" // extract ptr 2
"mov r7, r7, lsr #16 \n\t" // extract ptr 3
"ldrb r4, [%[srcAddr], r4] \n\t" // load pixel 0 from image
"uxth r8, r9 \n\t" // extract ptr 4
"ldrb r5, [%[srcAddr], r5] \n\t" // load pixel 1 from image
"mov r9, r9, lsr #16 \n\t" // extract ptr 5
"ldrb r6, [%[srcAddr], r6] \n\t" // load pixel 2 from image
"uxth r10, r11 \n\t" // extract ptr 6
"ldrb r7, [%[srcAddr], r7] \n\t" // load pixel 3 from image
"mov r11, r11, lsr #16 \n\t" // extract ptr 7
"ldrb r8, [%[srcAddr], r8] \n\t" // load pixel 4 from image
"ldrb r9, [%[srcAddr], r9] \n\t" // load pixel 5 from image
"ldrb r10, [%[srcAddr], r10] \n\t" // load pixel 6 from image
"ldrb r11, [%[srcAddr], r11] \n\t" // load pixel 7 from image
"ldr r4, [%[table], r4, lsl #2] \n\t" // load pixel 0 SkPMColor from colmap
"ldr r5, [%[table], r5, lsl #2] \n\t" // load pixel 1 SkPMColor from colmap
"ldr r6, [%[table], r6, lsl #2] \n\t" // load pixel 2 SkPMColor from colmap
"ldr r7, [%[table], r7, lsl #2] \n\t" // load pixel 3 SkPMColor from colmap
"ldr r8, [%[table], r8, lsl #2] \n\t" // load pixel 4 SkPMColor from colmap
"ldr r9, [%[table], r9, lsl #2] \n\t" // load pixel 5 SkPMColor from colmap
"ldr r10, [%[table], r10, lsl #2] \n\t" // load pixel 6 SkPMColor from colmap
"ldr r11, [%[table], r11, lsl #2] \n\t" // load pixel 7 SkPMColor from colmap
"subs %[count], %[count], #8 \n\t" // decrement loop counter
"stmia %[colors]!, {r4-r11} \n\t" // store 8 pixels
"bge 1b \n\t" // loop if counter >= 0
"2: \n\t"
"adds %[count], %[count], #8 \n\t" // fix up counter, set flags
"beq 4f \n\t" // if count == 0, branch to exit
"3: \n\t" // singles loop
"ldrh r4, [%[xx]], #2 \n\t" // load pixel ptr
"subs %[count], %[count], #1 \n\t" // decrement loop counter
"ldrb r5, [%[srcAddr], r4] \n\t" // load pixel from image
"ldr r6, [%[table], r5, lsl #2] \n\t" // load SkPMColor from colmap
"str r6, [%[colors]], #4 \n\t" // store pixel, update ptr
"bne 3b \n\t" // loop if counter != 0
"4: \n\t" // exit
: [xx] "+r" (xx), [count] "+r" (count), [colors] "+r" (colors)
: [table] "r" (table), [srcAddr] "r" (srcAddr)
: "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"
);
}
s.fBitmap->getColorTable()->unlockColors(false);
}
#endif //__ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
void S16_opaque_D32_nofilter_DX_neon_asm(const SkBitmapProcState& s,
const uint32_t* __restrict__ xy,
int count, uint32_t* __restrict__ colors) {
const uint16_t* __restrict__ srcAddr = (const uint16_t*)s.fBitmap->getPixels();
uint16_t* index;
uint16_t src;
int i;
srcAddr = (const uint16_t*)((const char*)srcAddr + xy[0] * s.fBitmap->rowBytes());
const uint16_t* __restrict__ xx = (const uint16_t*)(++xy);
if (1 == s.fBitmap->width()) {
src = srcAddr[0];
uint32_t dstValue = SkPixel16ToPixel32(src);
sk_memset32(colors, dstValue, count);
} else if ((xx[count-1] - xx[0]) == (count-1)) {
// No scaling
const uint16_t* src_data = (const uint16_t*)(srcAddr + xx[0]);
asm volatile (
"subs %[count], %[count], #8 \n\t" // count -= 8, set flag
"blt 2f \n\t" // if count < 0, branch to label 2
"vmov.u16 q8, #0xFF00 \n\t" // Load alpha value into q8 for later use.
"1: \n\t" // 8 loop
// Handle 8 pixels in one loop.
"vld1.u16 {q0}, [%[src_data]]! \n\t" // load eight src 565 pixels
"vshl.u16 q2, q0, #5 \n\t" // put green in the 6 high bits of q2
"vshl.u16 q3, q0, #11 \n\t" // put blue in the 5 high bits of q3
"vmov.u16 q1, q8 \n\t" // copy alpha from q8
"vsri.u16 q1, q3, #8 \n\t" // put blue below alpha in q1
"vsri.u16 q1, q3, #13 \n\t" // put 3 MSB blue below blue in q1
"vsri.u16 q2, q2, #6 \n\t" // put 2 MSB green below green in q2
"vsri.u16 q2, q0, #8 \n\t" // put red below green in q2
"vsri.u16 q2, q0, #13 \n\t" // put 3 MSB red below red in q2
"vzip.16 q2, q1 \n\t" // interleave q1 and q2
"vst1.16 {d4, d5}, [%[colors]]! \n\t" // store q1 to dst
"subs %[count], %[count], #8 \n\t" // count -= 8, set flag
"vst1.16 {d2, d3}, [%[colors]]! \n\t" // store q1 to dst
"bge 1b \n\t" // loop if count >= 0
"2: \n\t" // exit of 8 loop
"adds %[count], %[count], #4 \n\t" // add 4 to count to see if a 4 loop is needed.
"blt 3f \n\t" // if count < 0, branch to label 3
// Handle 4 pixels at once
"vld1.u16 {d0}, [%[src_data]]! \n\t" // load eight src 565 pixels
"vshl.u16 d2, d0, #5 \n\t" // put green in the 6 high bits of d2
"vshl.u16 d1, d0, #11 \n\t" // put blue in the 5 high bits of d1
"vmov.u16 d3, d16 \n\t" // copy alpha from d16
"vsri.u16 d3, d1, #8 \n\t" // put blue below alpha in d3
"vsri.u16 d3, d1, #13 \n\t" // put 3 MSB blue below blue in d3
"vsri.u16 d2, d2, #6 \n\t" // put 2 MSB green below green in d2
"vsri.u16 d2, d0, #8 \n\t" // put red below green in d2
"vsri.u16 d2, d0, #13 \n\t" // put 3 MSB red below red in d2
"vzip.16 d2, d3 \n\t" // interleave d2 and d3
"vst1.16 {d2, d3}, [%[colors]]! \n\t" // store d2 and d3 to dst
"3: \n\t" // end
: [src_data] "+r" (src_data), [colors] "+r" (colors), [count] "+r" (count)
:
: "cc", "memory","d0","d1","d2","d3","d4","d5","d6","d7","d16","d17"
);
for (i = (count & 3); i > 0; --i) {
*colors++ = SkPixel16ToPixel32(*src_data++);
}
} else {
// Scaling case
uint16_t data[8];
asm volatile (
"subs %[count], %[count], #8 \n\t" // count -= 8, set flag
"blt 2f \n\t" // if count < 0, branch to label 2
"vmov.u16 q8, #0xFF00 \n\t" // Load alpha value into q8 for later use.
"1: \n\t" // 8 loop
// Handle 8 pixels in one loop.
"ldmia %[xx]!, {r4, r5, r6, r7} \n\t" // load ptrs to pixels 0-7
"mov r4, r4, lsl #1 \n\t" // <<1 because of 16 bit pointer
"mov r5, r5, lsl #1 \n\t" // <<1 because of 16 bit pointer
"mov r6, r6, lsl #1 \n\t" // <<1 because of 16 bit pointer
"mov r7, r7, lsl #1 \n\t" // <<1 because of 16 bit pointer
"uxth r8, r4 \n\t" // extract ptr 0
"mov r4, r4, lsr #16 \n\t" // extract ptr 1
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 0 from image
"ldrh r4, [%[srcAddr], r4] \n\t" // load pixel 1 from image
"pkhbt r4, r8, r4, lsl #16 \n\t" // combine pixel 0 and 1 in one register
"uxth r8, r5 \n\t" // extract ptr 2
"mov r5, r5, lsr #16 \n\t" // extract ptr 3
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 2 from image
"ldrh r5, [%[srcAddr], r5] \n\t" // load pixel 3 from image
"pkhbt r5, r8, r5, lsl #16 \n\t" // combine pixel 2 and 3 in one register
"uxth r8, r6 \n\t" // extract ptr 4
"mov r6, r6, lsr #16 \n\t" // extract ptr 5
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 4 from image
"ldrh r6, [%[srcAddr], r6] \n\t" // load pixel 5 from image
"pkhbt r6, r8, r6, lsl #16 \n\t" // combine pixel 4 and 5 in one register
"uxth r8, r7 \n\t" // extract ptr 6
"mov r7, r7, lsr #16 \n\t" // extract ptr 7
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 6 from image
"ldrh r7, [%[srcAddr], r7] \n\t" // load pixel 7 from image
"pkhbt r7, r8, r7, lsl #16 \n\t" // combine pixel 6 and 7 in one register
"stmia %[data], {r4, r5, r6, r7} \n\t" // store 8 src pixels
"vld1.u16 {q0}, [%[data]] \n\t" // load eight src 565 pixels
"vshl.u16 q2, q0, #5 \n\t" // put green in the 6 high bits of q2
"vshl.u16 q3, q0, #11 \n\t" // put blue in the 5 high bits of q3
"vmov.u16 q1, q8 \n\t" // copy alpha from q8
"vsri.u16 q1, q3, #8 \n\t" // put blue below alpha in q1
"vsri.u16 q1, q3, #13 \n\t" // put 3 MSB blue below blue in q1
"vsri.u16 q2, q2, #6 \n\t" // put 2 MSB green below green in q2
"vsri.u16 q2, q0, #8 \n\t" // put red below green in q2
"vsri.u16 q2, q0, #13 \n\t" // put 3 MSB red below red in q2
"vzip.16 q2, q1 \n\t" // interleave q1 and q2
"vst1.16 {d4, d5}, [%[colors]]! \n\t" // store q1 to dst
"subs %[count], %[count], #8 \n\t" // count -= 8, set flag
"vst1.16 {d2, d3}, [%[colors]]! \n\t" // store q2 to dst
"bge 1b \n\t" // loop if count >= 0
"2: \n\t" // exit of 8 loop
"adds %[count], %[count], #4 \n\t" // add 4 to count to see if a 4 loop is needed.
"blt 3f \n\t" // if count < 0, branch to label 3
// Handle 4 pixels at once
"ldmia %[xx]!, {r4, r5} \n\t" // load ptrs to pixels 0-3
"mov r4, r4, lsl #1 \n\t" // <<1 because of 16 bit pointer
"mov r5, r5, lsl #1 \n\t" // <<1 because of 16 bit pointer
"uxth r8, r4 \n\t" // extract ptr 0
"mov r4, r4, lsr #16 \n\t" // extract ptr 1
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 0 from image
"ldrh r4, [%[srcAddr], r4] \n\t" // load pixel 1 from image
"pkhbt r4, r8, r4, lsl #16 \n\t" // combine pixel 0 and 1 in one register
"uxth r8, r5 \n\t" // extract ptr 2
"mov r5, r5, lsr #16 \n\t" // extract ptr 3
"ldrh r8, [%[srcAddr], r8] \n\t" // load pixel 2 from image
"ldrh r5, [%[srcAddr], r5] \n\t" // load pixel 3 from image
"pkhbt r5, r8, r5, lsl #16 \n\t" // combine pixel 2 and 3 in one register
"stmia %[data], {r4, r5} \n\t" // store 4 src pixels
"vld1.u16 {d0}, [%[data]] \n\t" // load eight src 565 pixels
"vshl.u16 d2, d0, #5 \n\t" // put green in the 6 high bits of d2
"vshl.u16 d1, d0, #11 \n\t" // put blue in the 5 high bits of d1
"vmov.u16 d3, d16 \n\t" // copy alpha from d16
"vsri.u16 d3, d1, #8 \n\t" // put blue below alpha in d3
"vsri.u16 d3, d1, #13 \n\t" // put 3 MSB blue below blue in d3
"vsri.u16 d2, d2, #6 \n\t" // put 2 MSB green below green in d2
"vsri.u16 d2, d0, #8 \n\t" // put red below green in d2
"vsri.u16 d2, d0, #13 \n\t" // put 3 MSB red below red in d2
"vzip.16 d2, d3 \n\t" // interleave d2 and d3
"vst1.16 {d2, d3}, [%[colors]]! \n\t" // store d2 and d3 to dst
"3: \n\t" // End
: [xx] "+r" (xx), [colors] "+r" (colors), [count] "+r" (count)
: [data] "r" (data), [srcAddr] "r" (srcAddr)
: "cc", "memory","r4","r5","r6","r7","r8","d0","d1","d2","d3","d4","d5","d6","d7","d16","d17"
);
for (i = (count & 3); i > 0; --i) {
src = srcAddr[*xx++]; *colors++ = SkPixel16ToPixel32(src);
}
}
}
void Clamp_S32_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
SkPMColor* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kARGB_8888_Config); SkASSERT(s.fAlphaScale == 256);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const SkPMColor* SK_RESTRICT row0;
const SkPMColor* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = (((fy) >> 12) & 0xF);
int y0 = SkClampMax((fy) >> 16, maxY);
int y1 = SkClampMax((fy + s.fFilterOneY) >> 16, maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const SkPMColor*)(srcAddr + y0 * rb);
row1 = (const SkPMColor*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
do {
// Check if we can do the next four pixels using ARM NEON asm
if ((count >= 4) &&
(((dx >= 0) && (fx >= 0) && (((fx + 3 * dx) >> 16) < (const signed)maxX)) ||
((dx < 0) && ((fx >> 16) < (const signed)maxX) && (((fx + 3 * dx) >> 16) >= 0)))) {
int asm_count;
// How many iterations can we do while still clamped?
if (dx >= 0) {
asm_count = (((((const signed)maxX - 1) << 16) - fx) / dx) >> 2;
} else {
asm_count = ((0 - fx) / dx) >> 2;
}
if (asm_count <= 0) {
asm_count = 1;
} else if ((asm_count << 2) > count) {
asm_count = count >> 2;
}
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 pixels in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate address for row0
"vld1.32 {d0}, [r8] \n\t" // Load two RGBA pixels from row0
"add r7, %[row1], r7 \n\t" // Calculate address for row1
"vld1.32 {d1}, [r7] \n\t" // Load two RGBA pixels from row1
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
// Calculate pixel #1 and pre-load #2
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx)
: "cc", "memory", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = (((fx) >> 12) & 0xF);
unsigned x0 = SkClampMax((fx) >> 16, maxX);
unsigned x1 = SkClampMax((fx + oneX) >> 16, maxX);
Filter_32_opaque(subX, subY,
row0[x0],
row0[x1],
row1[x0],
row1[x1],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
}
void Clamp_SI8_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
uint32_t* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kIndex8_Config);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const uint8_t* SK_RESTRICT row0;
const uint8_t* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = ((fy >> 12) & 0xF);
int y0 = SkClampMax(fy >> 16, maxY);
int y1 = SkClampMax((fy + s.fFilterOneY) >> 16, maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const uint8_t*)(srcAddr + y0 * rb);
row1 = (const uint8_t*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
do {
// Check if we can do the next four pixels using ARM NEON asm
if ((count >= 4) &&
(((dx >= 0) && (fx >= 0) && (((fx + 3 * dx) >> 16) < (const signed)maxX)) ||
((dx < 0) && ((fx >> 16) < (const signed)maxX) && (((fx + 3 * dx) >> 16) >= 0)))) {
int asm_count;
// How many iterations can we do while still clamped?
if (dx >= 0) {
asm_count = (((((const signed)maxX - 1) << 16) - fx) / dx) >> 2;
} else {
asm_count = ((0 - fx) / dx) >> 2;
}
if (asm_count <= 0) {
asm_count = 1;
} else if ((asm_count << 2) > count) {
asm_count = count >> 2;
}
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 offsets in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
// Calculate pixel #1 and pre-load #2
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx), [table] "r" (table)
: "cc", "memory", "r6", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = ((fx >> 12) & 0xF);
unsigned x0 = SkClampMax(fx >> 16, maxX);
unsigned x1 = SkClampMax((fx + oneX) >> 16, maxX);
Filter_32_opaque(subX, subY,
table[row0[x0]],
table[row0[x1]],
table[row1[x0]],
table[row1[x1]],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
s.fBitmap->getColorTable()->unlockColors(false);
}
void Repeat_SI8_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
uint32_t* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kIndex8_Config);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const uint8_t* SK_RESTRICT row0;
const uint8_t* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = (((fy & 0xFFFF) * (maxY + 1) >> 12) & 0xF);
int y0 = ((fy & 0xFFFF) * (maxY + 1) >> 16);
int y1 = (((fy + s.fFilterOneY) & 0xFFFF) * (maxY + 1) >> 16);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const uint8_t*)(srcAddr + y0 * rb);
row1 = (const uint8_t*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
do {
// Check if we can do the next four pixels using ARM NEON asm
if (count >= 4) {
int asm_count = count >> 2;
unsigned maxX1 = (unsigned)(maxX + 1);
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 offsets in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
// Calculate pixel #1 and pre-load #2
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx), [table] "r" (table), [oneX] "r" (oneX), [maxX1] "r" (maxX1)
: "cc", "memory", "r6", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = (((fx & 0xFFFF) * (maxX + 1) >> 12) & 0xF);
unsigned x0 = ((fx & 0xFFFF) * (maxX + 1) >> 16);
unsigned x1 = (((fx + oneX) & 0xFFFF) * (maxX + 1) >> 16);
Filter_32_opaque(subX, subY,
table[row0[x0]],
table[row0[x1]],
table[row1[x0]],
table[row1[x1]],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
s.fBitmap->getColorTable()->unlockColors(false);
}
void Clamp_S32_opaque_D32_nofilter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
SkPMColor* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(!s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kARGB_8888_Config); SkASSERT(s.fAlphaScale == 256);)
const register unsigned maxX = s.fBitmap->width() - 1;
const SkFixed dx = s.fInvSx;
register SkFixed fx;
const SkPMColor* SK_RESTRICT row;
int num;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY);
const unsigned maxY = s.fBitmap->height() - 1;
int yy = SkClampMax(SkFixedFloorToInt(fy), maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row = (const SkPMColor*)(srcAddr + yy * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX);
}
// Single pixel left in source?
if (maxX == 0) {
sk_memset32(colors, row[0], count);
return;
}
// Special case if unscaled.
if (dx == SK_Fixed1) {
fx = SkFixedFloorToInt(fx);
// Any clamped pixels at the beginning?
if (fx < 0) {
num = SkMin32(-fx, count);
sk_memset32(colors, row[0], num);
count -= num;
fx += num;
colors += num;
}
// Copy pixels
num = SkMin32(SkMax32(maxX + 1 - fx, 0), count);
memcpy(colors, row + fx, num * sizeof(SkPMColor));
count -= num;
if (count > 0) {
colors += num;
sk_memset32(colors, row[maxX], count);
}
return;
}
// Can we run unclamped case?
if (((dx >= 0) && (((fx + (count - 1) * dx) >> 16) <= (const signed)maxX) && (fx >= 0)) ||
((dx < 0) && ((fx >> 16) <= (const signed)maxX) && (((fx + (count - 1) * dx) >> 16) >= 0))) {
asm volatile (
// Setup constants
"pld [%[row]] \n\t" // Pre-load source
"subs %[count], #4 \n\t" // Decrease loop counter
"bmi 2f \n\t" //
"pld [%[row], #32] \n\t" // Pre-load source
"1: \n\t" // Loop start
// Load pixels
"lsr r1, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r1, %[row], r1, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s0, [r1] \n\t" // Load pixel #1
"lsr r2, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r2, %[row], r2, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s1, [r2] \n\t" // Load pixel #2
"lsr r1, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r1, %[row], r1, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s2, [r1] \n\t" // Load pixel #3
"lsr r2, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add r2, %[row], r2, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s3, [r2] \n\t" // Load pixel #4
// Write pixels
"subs %[count], #4 \n\t" // Decrease loop counter
"pld [r2, #52] \n\t" // Pre-load source
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"vstm %[colors]!, {s0-s3} \n\t" // Write result to memory
"bpl 1b \n\t"
"2: \n\t" // Loop start
"add %[count], #4 \n\t" // Restore loop counter
: [fx] "+r" (fx), [colors] "+r" (colors), [count] "+r" (count)
: [row] "r" (row), [dx] "r" (dx)
: "cc", "memory", "r1", "r2", "s0", "s1", "s2", "s3"
);
for (num = (count & 3); num > 0; --num) {
*colors++ = row[SkFixedFloorToInt(fx)];
fx += dx;
}
return;
}
// Fallback case
for (num = (count >> 2); num > 0; --num) {
SkPMColor p0, p1, p2, p3;
p0 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p1 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p2 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p3 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
*colors++ = p0;
*colors++ = p1;
*colors++ = p2;
*colors++ = p3;
fx += dx;
}
for (num = (count & 3); num > 0; --num) {
*colors++ = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
/* If we replace a sampleproc, then we null-out the associated shaderproc,
otherwise the shader won't even look at the matrix/sampler
*/
void SkBitmapProcState::platformProcs() {
bool doFilter = fDoFilter;
bool isOpaque = 256 == fAlphaScale;
bool justDx = (fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
bool clamp_clamp = ((SkShader::kClamp_TileMode == fTileModeX) &&
(SkShader::kClamp_TileMode == fTileModeY));
switch (fBitmap->config()) {
case SkBitmap::kIndex8_Config:
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
if (SI8_opaque_D32_filter_DX == fSampleProc32) {
if (clamp_clamp) {
fShaderProc32 = Clamp_SI8_opaque_D32_filter_DX_shaderproc;
} else if ((SkShader::kRepeat_TileMode == fTileModeX) &&
(SkShader::kRepeat_TileMode == fTileModeY)) {
fShaderProc32 = Repeat_SI8_opaque_D32_filter_DX_shaderproc;
}
} else
#endif
#if __ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
if (justDx && !doFilter) {
#if 0 /* crashing on android device */
fSampleProc16 = SI8_D16_nofilter_DX_arm;
fShaderProc16 = NULL;
#endif
if (isOpaque) {
// this one is only very slighty faster than the C version
fSampleProc32 = SI8_opaque_D32_nofilter_DX_arm;
fShaderProc32 = NULL;
}
}
#endif
break;
case SkBitmap::kRGB_565_Config:
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
if (justDx && !doFilter) {
if (isOpaque) {
fSampleProc32 = S16_opaque_D32_nofilter_DX_neon_asm;
}
}
#endif
break;
case SkBitmap::kARGB_8888_Config:
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
if (S32_opaque_D32_filter_DX == fSampleProc32 && clamp_clamp) {
fShaderProc32 = Clamp_S32_opaque_D32_filter_DX_shaderproc;
} else if (S32_opaque_D32_nofilter_DX == fSampleProc32 && clamp_clamp) {
fShaderProc32 = Clamp_S32_opaque_D32_nofilter_DX_shaderproc;
}
#endif
break;
default:
break;
}
}
Revert "Neon optimized implementation of S16_opaque_D32_nofilter_DX"
This reverts commit a9a4c66d163e245628ddde71dca40e4c29a44f47.
Conflicts:
src/opts/SkBitmapProcState_opts_arm.cpp
Change-Id: I3b4054aac74c34eba234f929b56794e54250116c
/*
* Copyright 2009 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmapProcState.h"
#include "SkColorPriv.h"
#include "SkUtils.h"
#include "SkShader.h"
#if defined(__ARM_HAVE_NEON)
#include "SkBitmapProcState_filter.h"
#endif
#if __ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
void SI8_D16_nofilter_DX_arm(
const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count,
uint16_t* SK_RESTRICT colors) __attribute__((optimize("O1")));
void SI8_D16_nofilter_DX_arm(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, uint16_t* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(s.fDoFilter == false);
const uint16_t* SK_RESTRICT table = s.fBitmap->getColorTable()->lock16BitCache();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fBitmap->getPixels();
// buffer is y32, x16, x16, x16, x16, x16
// bump srcAddr to the proper row, since we're told Y never changes
SkASSERT((unsigned)xy[0] < (unsigned)s.fBitmap->height());
srcAddr = (const uint8_t*)((const char*)srcAddr +
xy[0] * s.fBitmap->rowBytes());
uint8_t src;
if (1 == s.fBitmap->width()) {
src = srcAddr[0];
uint16_t dstValue = table[src];
sk_memset16(colors, dstValue, count);
} else {
int i;
int count8 = count >> 3;
const uint16_t* SK_RESTRICT xx = (const uint16_t*)(xy + 1);
asm volatile (
"cmp %[count8], #0 \n\t" // compare loop counter with 0
"beq 2f \n\t" // if loop counter == 0, exit
"1: \n\t"
"ldmia %[xx]!, {r5, r7, r9, r11} \n\t" // load ptrs to pixels 0-7
"subs %[count8], %[count8], #1 \n\t" // decrement loop counter
"uxth r4, r5 \n\t" // extract ptr 0
"mov r5, r5, lsr #16 \n\t" // extract ptr 1
"uxth r6, r7 \n\t" // extract ptr 2
"mov r7, r7, lsr #16 \n\t" // extract ptr 3
"ldrb r4, [%[srcAddr], r4] \n\t" // load pixel 0 from image
"uxth r8, r9 \n\t" // extract ptr 4
"ldrb r5, [%[srcAddr], r5] \n\t" // load pixel 1 from image
"mov r9, r9, lsr #16 \n\t" // extract ptr 5
"ldrb r6, [%[srcAddr], r6] \n\t" // load pixel 2 from image
"uxth r10, r11 \n\t" // extract ptr 6
"ldrb r7, [%[srcAddr], r7] \n\t" // load pixel 3 from image
"mov r11, r11, lsr #16 \n\t" // extract ptr 7
"ldrb r8, [%[srcAddr], r8] \n\t" // load pixel 4 from image
"add r4, r4, r4 \n\t" // double pixel 0 for RGB565 lookup
"ldrb r9, [%[srcAddr], r9] \n\t" // load pixel 5 from image
"add r5, r5, r5 \n\t" // double pixel 1 for RGB565 lookup
"ldrb r10, [%[srcAddr], r10] \n\t" // load pixel 6 from image
"add r6, r6, r6 \n\t" // double pixel 2 for RGB565 lookup
"ldrb r11, [%[srcAddr], r11] \n\t" // load pixel 7 from image
"add r7, r7, r7 \n\t" // double pixel 3 for RGB565 lookup
"ldrh r4, [%[table], r4] \n\t" // load pixel 0 RGB565 from colmap
"add r8, r8, r8 \n\t" // double pixel 4 for RGB565 lookup
"ldrh r5, [%[table], r5] \n\t" // load pixel 1 RGB565 from colmap
"add r9, r9, r9 \n\t" // double pixel 5 for RGB565 lookup
"ldrh r6, [%[table], r6] \n\t" // load pixel 2 RGB565 from colmap
"add r10, r10, r10 \n\t" // double pixel 6 for RGB565 lookup
"ldrh r7, [%[table], r7] \n\t" // load pixel 3 RGB565 from colmap
"add r11, r11, r11 \n\t" // double pixel 7 for RGB565 lookup
"ldrh r8, [%[table], r8] \n\t" // load pixel 4 RGB565 from colmap
"ldrh r9, [%[table], r9] \n\t" // load pixel 5 RGB565 from colmap
"ldrh r10, [%[table], r10] \n\t" // load pixel 6 RGB565 from colmap
"ldrh r11, [%[table], r11] \n\t" // load pixel 7 RGB565 from colmap
"pkhbt r5, r4, r5, lsl #16 \n\t" // pack pixels 0 and 1
"pkhbt r6, r6, r7, lsl #16 \n\t" // pack pixels 2 and 3
"pkhbt r8, r8, r9, lsl #16 \n\t" // pack pixels 4 and 5
"pkhbt r10, r10, r11, lsl #16 \n\t" // pack pixels 6 and 7
"stmia %[colors]!, {r5, r6, r8, r10} \n\t" // store last 8 pixels
"bgt 1b \n\t" // loop if counter > 0
"2: \n\t"
: [xx] "+r" (xx), [count8] "+r" (count8), [colors] "+r" (colors)
: [table] "r" (table), [srcAddr] "r" (srcAddr)
: "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"
);
for (i = (count & 7); i > 0; --i) {
src = srcAddr[*xx++]; *colors++ = table[src];
}
}
s.fBitmap->getColorTable()->unlock16BitCache();
}
void SI8_opaque_D32_nofilter_DX_arm(
const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count,
SkPMColor* SK_RESTRICT colors) __attribute__((optimize("O1")));
void SI8_opaque_D32_nofilter_DX_arm(const SkBitmapProcState& s,
const uint32_t* SK_RESTRICT xy,
int count, SkPMColor* SK_RESTRICT colors) {
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
SkASSERT(s.fDoFilter == false);
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
const uint8_t* SK_RESTRICT srcAddr = (const uint8_t*)s.fBitmap->getPixels();
// buffer is y32, x16, x16, x16, x16, x16
// bump srcAddr to the proper row, since we're told Y never changes
SkASSERT((unsigned)xy[0] < (unsigned)s.fBitmap->height());
srcAddr = (const uint8_t*)((const char*)srcAddr + xy[0] * s.fBitmap->rowBytes());
if (1 == s.fBitmap->width()) {
uint8_t src = srcAddr[0];
SkPMColor dstValue = table[src];
sk_memset32(colors, dstValue, count);
} else {
const uint16_t* xx = (const uint16_t*)(xy + 1);
asm volatile (
"subs %[count], %[count], #8 \n\t" // decrement count by 8, set flags
"blt 2f \n\t" // if count < 0, branch to singles
"1: \n\t" // eights loop
"ldmia %[xx]!, {r5, r7, r9, r11} \n\t" // load ptrs to pixels 0-7
"uxth r4, r5 \n\t" // extract ptr 0
"mov r5, r5, lsr #16 \n\t" // extract ptr 1
"uxth r6, r7 \n\t" // extract ptr 2
"mov r7, r7, lsr #16 \n\t" // extract ptr 3
"ldrb r4, [%[srcAddr], r4] \n\t" // load pixel 0 from image
"uxth r8, r9 \n\t" // extract ptr 4
"ldrb r5, [%[srcAddr], r5] \n\t" // load pixel 1 from image
"mov r9, r9, lsr #16 \n\t" // extract ptr 5
"ldrb r6, [%[srcAddr], r6] \n\t" // load pixel 2 from image
"uxth r10, r11 \n\t" // extract ptr 6
"ldrb r7, [%[srcAddr], r7] \n\t" // load pixel 3 from image
"mov r11, r11, lsr #16 \n\t" // extract ptr 7
"ldrb r8, [%[srcAddr], r8] \n\t" // load pixel 4 from image
"ldrb r9, [%[srcAddr], r9] \n\t" // load pixel 5 from image
"ldrb r10, [%[srcAddr], r10] \n\t" // load pixel 6 from image
"ldrb r11, [%[srcAddr], r11] \n\t" // load pixel 7 from image
"ldr r4, [%[table], r4, lsl #2] \n\t" // load pixel 0 SkPMColor from colmap
"ldr r5, [%[table], r5, lsl #2] \n\t" // load pixel 1 SkPMColor from colmap
"ldr r6, [%[table], r6, lsl #2] \n\t" // load pixel 2 SkPMColor from colmap
"ldr r7, [%[table], r7, lsl #2] \n\t" // load pixel 3 SkPMColor from colmap
"ldr r8, [%[table], r8, lsl #2] \n\t" // load pixel 4 SkPMColor from colmap
"ldr r9, [%[table], r9, lsl #2] \n\t" // load pixel 5 SkPMColor from colmap
"ldr r10, [%[table], r10, lsl #2] \n\t" // load pixel 6 SkPMColor from colmap
"ldr r11, [%[table], r11, lsl #2] \n\t" // load pixel 7 SkPMColor from colmap
"subs %[count], %[count], #8 \n\t" // decrement loop counter
"stmia %[colors]!, {r4-r11} \n\t" // store 8 pixels
"bge 1b \n\t" // loop if counter >= 0
"2: \n\t"
"adds %[count], %[count], #8 \n\t" // fix up counter, set flags
"beq 4f \n\t" // if count == 0, branch to exit
"3: \n\t" // singles loop
"ldrh r4, [%[xx]], #2 \n\t" // load pixel ptr
"subs %[count], %[count], #1 \n\t" // decrement loop counter
"ldrb r5, [%[srcAddr], r4] \n\t" // load pixel from image
"ldr r6, [%[table], r5, lsl #2] \n\t" // load SkPMColor from colmap
"str r6, [%[colors]], #4 \n\t" // store pixel, update ptr
"bne 3b \n\t" // loop if counter != 0
"4: \n\t" // exit
: [xx] "+r" (xx), [count] "+r" (count), [colors] "+r" (colors)
: [table] "r" (table), [srcAddr] "r" (srcAddr)
: "memory", "cc", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"
);
}
s.fBitmap->getColorTable()->unlockColors(false);
}
#endif //__ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
void Clamp_S32_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
SkPMColor* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kARGB_8888_Config); SkASSERT(s.fAlphaScale == 256);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const SkPMColor* SK_RESTRICT row0;
const SkPMColor* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = (((fy) >> 12) & 0xF);
int y0 = SkClampMax((fy) >> 16, maxY);
int y1 = SkClampMax((fy + s.fFilterOneY) >> 16, maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const SkPMColor*)(srcAddr + y0 * rb);
row1 = (const SkPMColor*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
do {
// Check if we can do the next four pixels using ARM NEON asm
if ((count >= 4) &&
(((dx >= 0) && (fx >= 0) && (((fx + 3 * dx) >> 16) < (const signed)maxX)) ||
((dx < 0) && ((fx >> 16) < (const signed)maxX) && (((fx + 3 * dx) >> 16) >= 0)))) {
int asm_count;
// How many iterations can we do while still clamped?
if (dx >= 0) {
asm_count = (((((const signed)maxX - 1) << 16) - fx) / dx) >> 2;
} else {
asm_count = ((0 - fx) / dx) >> 2;
}
if (asm_count <= 0) {
asm_count = 1;
} else if ((asm_count << 2) > count) {
asm_count = count >> 2;
}
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 pixels in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate address for row0
"vld1.32 {d0}, [r8] \n\t" // Load two RGBA pixels from row0
"add r7, %[row1], r7 \n\t" // Calculate address for row1
"vld1.32 {d1}, [r7] \n\t" // Load two RGBA pixels from row1
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
// Calculate pixel #1 and pre-load #2
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"lsl r7, r7, #2 \n\t" // Adjust offset for 32-bit RGBA values
"add r8, %[row0], r7 \n\t" // Calculate next address for row0
"add r7, %[row1], r7 \n\t" // Calculate next address for row1
"vld1.32 {d0}, [r8] \n\t" // Load next two RGBA pixels from row0
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"vld1.32 {d1}, [r7] \n\t" // Load next two RGBA pixels from row1
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q1 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q2 = [a10|a11] * y
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx)
: "cc", "memory", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = (((fx) >> 12) & 0xF);
unsigned x0 = SkClampMax((fx) >> 16, maxX);
unsigned x1 = SkClampMax((fx + oneX) >> 16, maxX);
Filter_32_opaque(subX, subY,
row0[x0],
row0[x1],
row1[x0],
row1[x1],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
}
void Clamp_SI8_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
uint32_t* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kIndex8_Config);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const uint8_t* SK_RESTRICT row0;
const uint8_t* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = ((fy >> 12) & 0xF);
int y0 = SkClampMax(fy >> 16, maxY);
int y1 = SkClampMax((fy + s.fFilterOneY) >> 16, maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const uint8_t*)(srcAddr + y0 * rb);
row1 = (const uint8_t*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
do {
// Check if we can do the next four pixels using ARM NEON asm
if ((count >= 4) &&
(((dx >= 0) && (fx >= 0) && (((fx + 3 * dx) >> 16) < (const signed)maxX)) ||
((dx < 0) && ((fx >> 16) < (const signed)maxX) && (((fx + 3 * dx) >> 16) >= 0)))) {
int asm_count;
// How many iterations can we do while still clamped?
if (dx >= 0) {
asm_count = (((((const signed)maxX - 1) << 16) - fx) / dx) >> 2;
} else {
asm_count = ((0 - fx) / dx) >> 2;
}
if (asm_count <= 0) {
asm_count = 1;
} else if ((asm_count << 2) > count) {
asm_count = count >> 2;
}
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 offsets in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
// Calculate pixel #1 and pre-load #2
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"asr r7, %[fx], #16 \n\t" // Calculate offset fx >> 16
"ldrh r8, [%[row0], r7] \n\t" // Fetch row0 color table offsets
"ldrh r7, [%[row1], r7] \n\t" // Fetch row1 color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"and r6, r8, #0xFF \n\t" // Extract first offset
"lsr r8, r8, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"vld1.32 {d0[0]}, [r6] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"and r6, r7, #0xFF \n\t" // Extract first offset
"lsr r7, r7, #8 \n\t" // Extract second offset
"add r6, %[table], r6, lsl #2 \n\t" // Calculate a10 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d1[0]}, [r6] \n\t" // Load a10 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"lsr r8, %[fx], #12 \n\t" // Calculate subX = ((fx >> 12) & 0xF)
"and r8, r8, #0xF \n\t" //
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r8 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx), [table] "r" (table)
: "cc", "memory", "r6", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = ((fx >> 12) & 0xF);
unsigned x0 = SkClampMax(fx >> 16, maxX);
unsigned x1 = SkClampMax((fx + oneX) >> 16, maxX);
Filter_32_opaque(subX, subY,
table[row0[x0]],
table[row0[x1]],
table[row1[x0]],
table[row1[x1]],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
s.fBitmap->getColorTable()->unlockColors(false);
}
void Repeat_SI8_opaque_D32_filter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
uint32_t* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kIndex8_Config);)
const unsigned maxX = s.fBitmap->width() - 1;
const SkFixed oneX = s.fFilterOneX;
const SkFixed dx = s.fInvSx;
SkFixed fx;
const uint8_t* SK_RESTRICT row0;
const uint8_t* SK_RESTRICT row1;
unsigned subY;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY) - (s.fFilterOneY >> 1);
const unsigned maxY = s.fBitmap->height() - 1;
// compute our two Y values up front
subY = (((fy & 0xFFFF) * (maxY + 1) >> 12) & 0xF);
int y0 = ((fy & 0xFFFF) * (maxY + 1) >> 16);
int y1 = (((fy + s.fFilterOneY) & 0xFFFF) * (maxY + 1) >> 16);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row0 = (const uint8_t*)(srcAddr + y0 * rb);
row1 = (const uint8_t*)(srcAddr + y1 * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX) - (oneX >> 1);
}
const SkPMColor* SK_RESTRICT table = s.fBitmap->getColorTable()->lockColors();
do {
// Check if we can do the next four pixels using ARM NEON asm
if (count >= 4) {
int asm_count = count >> 2;
unsigned maxX1 = (unsigned)(maxX + 1);
count -= asm_count << 2;
// We know that oneX is 1.0 since we are running clamped.
// This means that we can load both x0 and x1 offsets in one go.
asm volatile (
// Setup constants
"rsb r8, %[subY], #16 \n\t" // 16 - subY
"vdup.8 d30, %[subY] \n\t" // Create constant for subY
"vdup.8 d31, r8 \n\t" // Create constant for 16 - subY
"vmov.u16 d29, #16 \n\t" // Create constant for 16
"1: \n\t" // Loop start
// Pre-load pixel #1
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"subs %[cnt], %[cnt], #1 \n\t" // Decrement loop counter
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
// Calculate pixel #1 and pre-load #2
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d16, d3, d28 \n\t" // d16 = a01 * x
"vmla.i16 d16, d5, d28 \n\t" // d16 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d16, d2, d27 \n\t" // d16 += a00 * (16 - x)
"vmla.i16 d16, d4, d27 \n\t" // d16 += a10 * (16 - x)
// Calculate pixel #2 and pre-load #3
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d17, d3, d28 \n\t" // d17 = a01 * x
"vmla.i16 d17, d5, d28 \n\t" // d17 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d17, d2, d27 \n\t" // d17 += a00 * (16 - x)
"vmla.i16 d17, d4, d27 \n\t" // d17 += a10 * (16 - x)
// Calculate pixel #3 and pre-load #4
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"vshrn.i16 d16, q8, #8 \n\t" // shift down result by 8
"add r7, %[fx], %[oneX] \n\t" // Start calculate x1 (fx + oneX)
"uxth r7, r7 \n\t" // (fx + oneX) & 0xFFFF
"mul r7, %[maxX1], r7 \n\t" // Multiply with maxX + 1
"lsr r7, r7, #16 \n\t" // Shift by 16 to get x1
"ldrb r8, [%[row0], r7] \n\t" // Fetch row0[x1] color table offsets
"ldrb r7, [%[row1], r7] \n\t" // Fetch row1[x1] color table offsets
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"uxth r6, %[fx] \n\t" // Start calculate x0/subX (fx & 0xFFFF)
"mul r6, %[maxX1], r6 \n\t" // Multiply with maxX + 1
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a01 address for table
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a11 address for table
"vld1.32 {d0[1]}, [r8] \n\t" // Load a01 RGBA pixel from table
"vld1.32 {d1[1]}, [r7] \n\t" // Load a11 RGBA pixel from table
"lsr r8, r6, #16 \n\t" // Shift by 16 to get x0
"ldrb r7, [%[row0], r8] \n\t" // Fetch row0[x0] color table offsets
"ldrb r8, [%[row1], r8] \n\t" // Fetch row1[x0] color table offsets
"vmul.i16 d18, d3, d28 \n\t" // d18 = a01 * x
"vmla.i16 d18, d5, d28 \n\t" // d18 += a11 * x
"add r7, %[table], r7, lsl #2 \n\t" // Calculate a00 address for table
"add r8, %[table], r8, lsl #2 \n\t" // Calculate a10 address for table
"vld1.32 {d0[0]}, [r7] \n\t" // Load a00 RGBA pixel from table
"vld1.32 {d1[0]}, [r8] \n\t" // Load a10 RGBA pixel from table
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d18, d2, d27 \n\t" // d18 += a00 * (16 - x)
"vmla.i16 d18, d4, d27 \n\t" // d18 += a10 * (16 - x)
// Calculate pixel #4
"vmull.u8 q1, d0, d31 \n\t" // q0 = [a00|a01] * (16 - y)
"vmull.u8 q2, d1, d30 \n\t" // q1 = [a10|a11] * y
"lsr r6, r6, #12 \n\t" // Calculate subX
"and r6, r6, #0xF \n\t" // ((fx & 0xFFFF) * (maxX1) >> 12) & 0xF
"add %[fx], %[fx], %[dx] \n\t" // Move fx to next position
"vdup.16 d28, r6 \n\t" // subX
"vmul.i16 d19, d3, d28 \n\t" // d19 = a01 * x
"vmla.i16 d19, d5, d28 \n\t" // d19 += a11 * x
"vsub.i16 d27, d29, d28 \n\t" // 16 - subX
"vmla.i16 d19, d2, d27 \n\t" // d19 += a00 * (16 - x)
"vmla.i16 d19, d4, d27 \n\t" // d19 += a10 * (16 - x)
"vshrn.i16 d17, q9, #8 \n\t" // shift down result by 8
"vst1.32 {d16-d17}, [%[colors]]! \n\t" // Write result to memory
"bne 1b \n\t"
: [fx] "+r" (fx), [colors] "+r" (colors), [cnt] "+r" (asm_count)
: [row0] "r" (row0), [row1] "r" (row1), [subY] "r" (subY), [dx] "r" (dx), [table] "r" (table), [oneX] "r" (oneX), [maxX1] "r" (maxX1)
: "cc", "memory", "r6", "r7", "r8", "d0", "d1", "d2", "d3", "d4", "d5", "d16", "d17", "d18", "d19", "d27", "d28", "d29", "d30", "d31"
);
} else {
unsigned subX = (((fx & 0xFFFF) * (maxX + 1) >> 12) & 0xF);
unsigned x0 = ((fx & 0xFFFF) * (maxX + 1) >> 16);
unsigned x1 = (((fx + oneX) & 0xFFFF) * (maxX + 1) >> 16);
Filter_32_opaque(subX, subY,
table[row0[x0]],
table[row0[x1]],
table[row1[x0]],
table[row1[x1]],
colors);
colors += 1;
fx += dx;
count--;
}
} while (count != 0);
s.fBitmap->getColorTable()->unlockColors(false);
}
void Clamp_S32_opaque_D32_nofilter_DX_shaderproc(const SkBitmapProcState& s, int x, int y,
SkPMColor* SK_RESTRICT colors, int count) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
SkASSERT(count > 0 && colors != NULL);
SkASSERT(!s.fDoFilter);
SkDEBUGCODE(SkASSERT(s.fBitmap->config() == SkBitmap::kARGB_8888_Config); SkASSERT(s.fAlphaScale == 256);)
const register unsigned maxX = s.fBitmap->width() - 1;
const SkFixed dx = s.fInvSx;
register SkFixed fx;
const SkPMColor* SK_RESTRICT row;
int num;
{
SkPoint pt;
s.fInvProc(*s.fInvMatrix, SkIntToScalar(x) + SK_ScalarHalf,
SkIntToScalar(y) + SK_ScalarHalf, &pt);
SkFixed fy = SkScalarToFixed(pt.fY);
const unsigned maxY = s.fBitmap->height() - 1;
int yy = SkClampMax(SkFixedFloorToInt(fy), maxY);
const char* SK_RESTRICT srcAddr = (const char*)s.fBitmap->getPixels();
unsigned rb = s.fBitmap->rowBytes();
row = (const SkPMColor*)(srcAddr + yy * rb);
// now initialize fx
fx = SkScalarToFixed(pt.fX);
}
// Single pixel left in source?
if (maxX == 0) {
sk_memset32(colors, row[0], count);
return;
}
// Special case if unscaled.
if (dx == SK_Fixed1) {
fx = SkFixedFloorToInt(fx);
// Any clamped pixels at the beginning?
if (fx < 0) {
num = SkMin32(-fx, count);
sk_memset32(colors, row[0], num);
count -= num;
fx += num;
colors += num;
}
// Copy pixels
num = SkMin32(SkMax32(maxX + 1 - fx, 0), count);
memcpy(colors, row + fx, num * sizeof(SkPMColor));
count -= num;
if (count > 0) {
colors += num;
sk_memset32(colors, row[maxX], count);
}
return;
}
// Can we run unclamped case?
if (((dx >= 0) && (((fx + (count - 1) * dx) >> 16) <= (const signed)maxX) && (fx >= 0)) ||
((dx < 0) && ((fx >> 16) <= (const signed)maxX) && (((fx + (count - 1) * dx) >> 16) >= 0))) {
asm volatile (
// Setup constants
"pld [%[row]] \n\t" // Pre-load source
"subs %[count], #4 \n\t" // Decrease loop counter
"bmi 2f \n\t" //
"pld [%[row], #32] \n\t" // Pre-load source
"1: \n\t" // Loop start
// Load pixels
"lsr r1, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r1, %[row], r1, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s0, [r1] \n\t" // Load pixel #1
"lsr r2, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r2, %[row], r2, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s1, [r2] \n\t" // Load pixel #2
"lsr r1, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"add r1, %[row], r1, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s2, [r1] \n\t" // Load pixel #3
"lsr r2, %[fx], #16 \n\t" // Calculate SkFixedFloorToInt(fx)
"add r2, %[row], r2, lsl #2 \n\t" // Calculate row[SkFixedFloorToInt(fx)];
"vldr.32 s3, [r2] \n\t" // Load pixel #4
// Write pixels
"subs %[count], #4 \n\t" // Decrease loop counter
"pld [r2, #52] \n\t" // Pre-load source
"add %[fx], %[fx], %[dx] \n\t" // Increment to next position
"vstm %[colors]!, {s0-s3} \n\t" // Write result to memory
"bpl 1b \n\t"
"2: \n\t" // Loop start
"add %[count], #4 \n\t" // Restore loop counter
: [fx] "+r" (fx), [colors] "+r" (colors), [count] "+r" (count)
: [row] "r" (row), [dx] "r" (dx)
: "cc", "memory", "r1", "r2", "s0", "s1", "s2", "s3"
);
for (num = (count & 3); num > 0; --num) {
*colors++ = row[SkFixedFloorToInt(fx)];
fx += dx;
}
return;
}
// Fallback case
for (num = (count >> 2); num > 0; --num) {
SkPMColor p0, p1, p2, p3;
p0 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p1 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p2 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
p3 = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
*colors++ = p0;
*colors++ = p1;
*colors++ = p2;
*colors++ = p3;
fx += dx;
}
for (num = (count & 3); num > 0; --num) {
*colors++ = row[SkClampMax(SkFixedFloorToInt(fx), maxX)];
fx += dx;
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
/* If we replace a sampleproc, then we null-out the associated shaderproc,
otherwise the shader won't even look at the matrix/sampler
*/
void SkBitmapProcState::platformProcs() {
bool doFilter = fDoFilter;
bool isOpaque = 256 == fAlphaScale;
bool justDx = (fInvType <= (SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask));
bool clamp_clamp = ((SkShader::kClamp_TileMode == fTileModeX) &&
(SkShader::kClamp_TileMode == fTileModeY));
switch (fBitmap->config()) {
case SkBitmap::kIndex8_Config:
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
if (SI8_opaque_D32_filter_DX == fSampleProc32) {
if (clamp_clamp) {
fShaderProc32 = Clamp_SI8_opaque_D32_filter_DX_shaderproc;
} else if ((SkShader::kRepeat_TileMode == fTileModeX) &&
(SkShader::kRepeat_TileMode == fTileModeY)) {
fShaderProc32 = Repeat_SI8_opaque_D32_filter_DX_shaderproc;
}
} else
#endif
#if __ARM_ARCH__ >= 6 && !defined(SK_CPU_BENDIAN)
if (justDx && !doFilter) {
#if 0 /* crashing on android device */
fSampleProc16 = SI8_D16_nofilter_DX_arm;
fShaderProc16 = NULL;
#endif
if (isOpaque) {
// this one is only very slighty faster than the C version
fSampleProc32 = SI8_opaque_D32_nofilter_DX_arm;
fShaderProc32 = NULL;
}
}
#endif
break;
case SkBitmap::kARGB_8888_Config:
#if defined(__ARM_HAVE_NEON) && defined(SK_CPU_LENDIAN)
if (S32_opaque_D32_filter_DX == fSampleProc32 && clamp_clamp) {
fShaderProc32 = Clamp_S32_opaque_D32_filter_DX_shaderproc;
} else if (S32_opaque_D32_nofilter_DX == fSampleProc32 && clamp_clamp) {
fShaderProc32 = Clamp_S32_opaque_D32_nofilter_DX_shaderproc;
}
#endif
break;
default:
break;
}
}
|
// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
#include "../PqaCore/CpuEngine.h"
#include "../PqaCore/PqaException.h"
#include "../PqaCore/CETrainTask.h"
#include "../PqaCore/ErrorHelper.h"
#include "../PqaCore/CETask.h"
#include "../PqaCore/CETrainSubtaskDistrib.h"
#include "../PqaCore/CETrainSubtaskAdd.h"
#include "../PqaCore/CETrainTaskNumSpec.h"
#include "../PqaCore/CEQuiz.h"
#include "../PqaCore/CECreateQuizOperation.h"
#include "../PqaCore/CEEvalQsTask.h"
#include "../PqaCore/CEEvalQsSubtaskConsider.h"
using namespace SRPlat;
namespace ProbQA {
#define CELOG(severityVar) SRLogStream(ISRLogger::Severity::severityVar, _pLogger.load(std::memory_order_acquire))
template<typename taNumber> CpuEngine<taNumber>::CpuEngine(const EngineDefinition& engDef) : BaseCpuEngine(engDef) {
if (_dims._nAnswers < cMinAnswers || _dims._nQuestions < cMinQuestions || _dims._nTargets < cMinTargets)
{
throw PqaException(PqaErrorCode::InsufficientEngineDimensions, new InsufficientEngineDimensionsErrorParams(
_dims._nAnswers, cMinAnswers, _dims._nQuestions, cMinQuestions, _dims._nTargets, cMinTargets));
}
taNumber initAmount(engDef._initAmount);
//// Init cube A: A[q][ao][t] is weight for answer option |ao| for question |q| for target |t|
_sA.resize(SRCast::ToSizeT(_dims._nQuestions));
for (size_t i = 0, iEn= SRCast::ToSizeT(_dims._nQuestions); i < iEn; i++) {
_sA[i].resize(SRCast::ToSizeT(_dims._nAnswers));
for (size_t k = 0, kEn= SRCast::ToSizeT(_dims._nAnswers); k < kEn; k++) {
_sA[i][k].Resize<false>(SRCast::ToSizeT(_dims._nTargets));
_sA[i][k].FillAll<false>(initAmount);
}
}
//// Init matrix D: D[q][t] is the sum of weigths over all answers for question |q| for target |t|. In the other
//// words, D[q][t] is A[0][q][t] + A[1][q][t] + ... + A[K-1][q][t], where K is the number of answer options.
//// Note that D is subject to summation errors, thus its regular recomputation is desired.
taNumber initMD = initAmount * _dims._nAnswers;
_mD.resize(size_t(_dims._nQuestions));
for (size_t i = 0, iEn=size_t(_dims._nQuestions); i < iEn; i++) {
_mD[i].Resize<false>(size_t(_dims._nTargets));
_mD[i].FillAll<false>(initMD);
}
//// Init vector B: the sums of weights over all trainings for each target
_vB.Resize<false>(size_t(_dims._nTargets));
_vB.FillAll<false>(initAmount);
_questionGaps.GrowTo(_dims._nQuestions);
_targetGaps.GrowTo(_dims._nTargets);
//throw PqaException(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
// "CpuEngine<taNumber>::CpuEngine(const EngineDefinition& engDef)")));
}
template<typename taNumber> CpuEngine<taNumber>::~CpuEngine() {
PqaError pqaErr = Shutdown();
if (!pqaErr.IsOk() && pqaErr.GetCode() != PqaErrorCode::ObjectShutDown) {
CELOG(Error) << "Failed CpuEngine::Shutdown(): " << pqaErr.ToString(true);
}
}
template<typename taNumber> PqaError CpuEngine<taNumber>::SetLogger(ISRLogger *pLogger) {
if (pLogger == nullptr) {
pLogger = SRDefaultLogger::Get();
}
_pLogger.store(pLogger, std::memory_order_release);
return PqaError();
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Shutdown(const char* const saveFilePath) {
if (!_maintSwitch.Shutdown()) {
// Return an error saying that the engine seems already shut down.
SRMessageBuilder mbMsg("MaintenanceSwitch seems already shut down.");
if (saveFilePath != nullptr) {
mbMsg(" Not saving file: ")(saveFilePath);
}
return PqaError(PqaErrorCode::ObjectShutDown, new ObjectShutDownErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::Shutdown()")), mbMsg.GetOwnedSRString());
}
// By this moment, all operations must have shut down and no new operations can be started.
if (saveFilePath != nullptr) {
//TODO: implement
}
//TODO: check the order - perhaps some releases should happen while the workers are still operational
//// Shutdown worker threads
_tpWorkers.RequestShutdown();
//// Release quizzes
for (size_t i = 0; i < _quizzes.size(); i++) {
SRCheckingRelease(_memPool, _quizzes[i]);
}
_quizzes.clear();
_quizGaps.Compact(0);
//// Release KB
_sA.clear();
_mD.clear();
_vB.Clear();
_questionGaps.Compact(0);
_targetGaps.Compact(0);
_dims._nAnswers = _dims._nQuestions = _dims._nTargets = 0;
//// Release memory pool
_memPool.FreeAllChunks();
return PqaError();
}
template<> void CpuEngine<SRDoubleNumber>::InitTrainTaskNumSpec(CETrainTaskNumSpec<SRDoubleNumber>& numSpec,
const TPqaAmount amount)
{
const double dAmount = SRCast::ToDouble(amount);
numSpec._collAddend = numSpec._fullAddend = _mm256_set1_pd(dAmount);
// Colliding addend: amount is added twice to _mD[iQuestion][iTarget] .
numSpec._collAddend.m256d_f64[1] += dAmount;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::TrainInternal(const TPqaId nQuestions,
const AnsweredQuestion* const pAQs, const TPqaId iTarget, const TPqaAmount amount)
{
if (nQuestions < 0) {
return PqaError(PqaErrorCode::NegativeCount, new NegativeCountErrorParams(nQuestions), SRString::MakeUnowned(
"|nQuestions| must be non-negative."));
}
if (amount <= 0) {
return PqaError(PqaErrorCode::NonPositiveAmount, new NonPositiveAmountErrorParams(amount), SRString::MakeUnowned(
"|amount| must be positive."));
}
PqaError resErr;
const SRThreadCount nWorkers = _tpWorkers.GetWorkerCount();
//// Do a single allocation for all needs. Allocate memory out of locks.
// For proper alignment, the data must be laid out in the decreasing order of item alignments.
const size_t ttLastOffs = nWorkers * SRMaxSizeof<CETrainSubtaskDistrib<taNumber>, CETrainSubtaskAdd<taNumber>>::value;
const size_t ttPrevOffs = ttLastOffs + sizeof(std::atomic<TPqaId>) * nWorkers;
const size_t nTotalBytes = ttPrevOffs + sizeof(TPqaId) * SRCast::ToSizeT(nQuestions);
SRSmartMPP<uint8_t> commonBuf(_memPool, nTotalBytes);
CETrainTask<taNumber> trainTask(*this, nWorkers, iTarget, pAQs);
//TODO: these are slow because threads share a cache line. It's not clear yet how to workaround this: the data is not
// per-source thread, but rather per target thread (after distribution).
trainTask._prev = SRCast::Ptr<TPqaId>(commonBuf.Get() + ttPrevOffs);
trainTask._last = SRCast::Ptr<std::atomic<TPqaId>>(commonBuf.Get() + ttLastOffs);
InitTrainTaskNumSpec(trainTask._numSpec, amount);
//TODO: vectorize/parallelize
for (size_t i = 0; i < nWorkers; i++) {
new(trainTask._last + i) std::atomic<TPqaId>(cInvalidPqaId);
}
// &trainTask, &nWorkers
auto&& ttLastFinally = SRMakeFinally([&pLast = trainTask._last, &nWorkers]{
//TODO: vectorize/parallelize
for (size_t i = 0; i < nWorkers; i++) {
pLast[i].~atomic();
}
}); (void)ttLastFinally; // prevent warning C4189
{ // Scope for the locks
MaintenanceSwitch::AgnosticLock msal(_maintSwitch);
//// The further code must be reader-writer locked, because we are validating the input before modifying the KB,
//// so noone must change or read the KB in between.
SRRWLock<true> rwl(_rws);
// Can't move dimensions-related code out of SRW lock because this operation can be run in maintenance mode too.
if (iTarget < 0 || iTarget >= _dims._nTargets) {
const TPqaId nKB = _dims._nTargets;
rwl.EarlyRelease();
return PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iTarget, 0, nKB - 1),
SRString::MakeUnowned("Target index is not in KB range."));
}
if (_targetGaps.IsGap(iTarget)) {
rwl.EarlyRelease();
return PqaError(PqaErrorCode::AbsentId, new AbsentIdErrorParams(iTarget), SRString::MakeUnowned(
"Target index is not in KB (but rather at a gap)."));
}
SRPoolRunner pr(_tpWorkers, commonBuf.Get());
//// Distribute the AQs into buckets with the number of buckets divisable by the number of workers.
pr.SplitAndRunSubtasks<CETrainSubtaskDistrib<taNumber>>(trainTask, nQuestions, trainTask.GetWorkerCount(),
[&](void *pStMem, SRThreadCount iWorker, int64_t iFirst, int64_t iLimit) {
new (pStMem) CETrainSubtaskDistrib<taNumber>(&trainTask, pAQs + iFirst, pAQs + iLimit);
(void)iWorker;
}
);
resErr = trainTask.TakeAggregateError(SRString::MakeUnowned("Failed " SR_FILE_LINE));
if (!resErr.IsOk()) {
return resErr;
}
//// Update the KB with the given training data.
pr.RunPerWorkerSubtasks<CETrainSubtaskAdd<taNumber>>(trainTask, trainTask.GetWorkerCount());
resErr = trainTask.TakeAggregateError(SRString::MakeUnowned("Failed " SR_FILE_LINE));
if (!resErr.IsOk()) {
return resErr;
}
_vB[iTarget] += amount;
// This method should increase the counter of questions asked by the number of questions in this training.
_nQuestionsAsked.fetch_add(nQuestions, std::memory_order_relaxed);
}
return PqaError();
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Train(const TPqaId nQuestions,
const AnsweredQuestion* const pAQs, const TPqaId iTarget, const TPqaAmount amount)
{
try {
return TrainInternal(nQuestions, pAQs, iTarget, amount);
}
CATCH_TO_ERR_RETURN;
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::CreateQuizInternal(CECreateQuizOpBase &op) {
try {
struct NoSrwTask : public CETask {
CEQuiz<taNumber> *_pQuiz;
public: // methods
explicit NoSrwTask(CpuEngine<taNumber> &ce) : CETask(ce, /*nWorkers*/ 3) { }
} tNoSrw(*this); // Subtasks without SRW locked
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
op._err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (Start/Resume quiz) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
// So long as this constructor only needs the number of questions and targets, it can be out of _rws because
// _maintSwitch guards engine dimensions in Regular mode (but not in Maintenance mode).
SRObjectMPP<CEQuiz<taNumber>> spQuiz(_memPool, this);
tNoSrw._pQuiz = spQuiz.Get();
TPqaId quizId;
{
SRLock<SRCriticalSection> csl(_csQuizReg);
quizId = _quizGaps.Acquire();
if (quizId >= TPqaId(_quizzes.size())) {
assert(quizId == TPqaId(_quizzes.size()));
_quizzes.emplace_back(nullptr);
}
_quizzes[SRCast::ToSizeT(quizId)] = spQuiz.Get();
}
{
auto&& lstSetQAsked = SRMakeLambdaSubtask(&tNoSrw, [&op](const SRBaseSubtask &subtask) {
auto& task = static_cast<NoSrwTask&>(*subtask.GetTask());
auto& engine = static_cast<const CpuEngine<taNumber>&>(task.GetBaseEngine());
__m256i *pQAsked = task._pQuiz->GetQAsked();
SRUtils::FillZeroVects<true>(pQAsked, SRSimd::VectsFromBits(engine._dims._nQuestions));
if (op.IsResume()) {
// Validate the indexes and set "is question asked" bits
auto& resumeOp = static_cast<CECreateQuizResume<taNumber>&>(op);
const EngineDimensions& dims = engine.GetDims();
for (size_t i = 0; i<SRCast::ToSizeT(resumeOp._nAnswered); i++) {
const TPqaId iQuestion = resumeOp._pAQs[i]._iQuestion;
if (iQuestion < 0 || iQuestion >= dims._nQuestions) {
task.AddError(PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iQuestion, 0,
dims._nQuestions - 1), SRString::MakeUnowned(SR_FILE_LINE "Question index is not in KB range.")));
return;
}
const TPqaId iAnswer = resumeOp._pAQs[i]._iAnswer;
if (iAnswer < 0 || iAnswer >= dims._nAnswers) {
task.AddError(PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iAnswer, 0,
dims._nAnswers - 1), SRString::MakeUnowned(SR_FILE_LINE "Answer index is not in KB range.")));
return;
}
*(SRCast::Ptr<uint8_t>(pQAsked) + (iQuestion >> 3)) |= (1ui8 << (iQuestion & 7));
}
}
});
auto&& lstAddAnswers = SRMakeLambdaSubtask(&tNoSrw, [&op](const SRBaseSubtask &subtask) {
auto& resumeOp = static_cast<const CECreateQuizResume<taNumber>&>(op);
auto& task = static_cast<const NoSrwTask&>(*subtask.GetTask());
std::vector<AnsweredQuestion>& answers = task._pQuiz->ModAnswers();
answers.insert(answers.end(), resumeOp._pAQs, resumeOp._pAQs + resumeOp._nAnswered);
});
SRTaskWaiter noSrwTaskWaiter(&tNoSrw);
if(op.IsResume()) {
_tpWorkers.Enqueue({&lstSetQAsked, &lstAddAnswers}, tNoSrw);
} else {
_tpWorkers.Enqueue(&lstSetQAsked);
}
}
op._err = tNoSrw.TakeAggregateError();
if(op._err.IsOk()) {
// If it's "resume quiz" operation, update the prior likelihoods with the questions answered, and normalize the
// priors. If it's "start quiz" operation, just divide the priors by their sum.
op.UpdateLikelihoods(*this, *spQuiz.Get());
}
if (!op._err.IsOk()) {
spQuiz.EarlyRelease();
SRLock<SRCriticalSection> csl(_csQuizReg);
_quizzes[SRCast::ToSizeT(quizId)] = nullptr;
_quizGaps.Release(quizId);
return cInvalidPqaId;
}
spQuiz.Detach();
return quizId;
}
CATCH_TO_ERR_SET(op._err);
return cInvalidPqaId;
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::StartQuiz(PqaError& err) {
CECreateQuizStart<taNumber> startOp(err);
return CreateQuizInternal(startOp);
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::ResumeQuiz(PqaError& err, const TPqaId nAnswered,
const AnsweredQuestion* const pAQs)
{
if(nAnswered < 0) {
err = PqaError(PqaErrorCode::NegativeCount, new NegativeCountErrorParams(nAnswered), SRString::MakeUnowned(
"|nAnswered| must be non-negative."));
return cInvalidPqaId;
}
if (nAnswered == 0) {
return StartQuiz(err);
}
CECreateQuizResume<taNumber> resumeOp(err, nAnswered, pAQs);
return CreateQuizInternal(resumeOp);
}
template<typename taNumber> CEQuiz<taNumber>* CpuEngine<taNumber>::UseQuiz(PqaError& err, const TPqaId iQuiz) {
SRLock<SRCriticalSection> csl(_csQuizReg);
const TPqaId nQuizzes = _quizzes.size();
if (iQuiz < 0 || iQuiz >= nQuizzes) {
csl.EarlyRelease();
// For nQuizzes == 0, this may return [0;-1] range: we can't otherwise return an empty range because we return
// the range with both bounds inclusive.
err = PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iQuiz, 0, nQuizzes - 1),
SRString::MakeUnowned(SR_FILE_LINE "Quiz index is not in quiz registry range."));
return nullptr;
}
if (_quizGaps.IsGap(iQuiz)) {
csl.EarlyRelease();
err = PqaError(PqaErrorCode::AbsentId, new AbsentIdErrorParams(iQuiz), SRString::MakeUnowned(
SR_FILE_LINE "Quiz index is not in the registry (but rather at a gap)."));
return nullptr;
}
return _quizzes[iQuiz];
}
template<typename taNumber> PqaError CpuEngine<taNumber>::NormalizePriors(CEQuiz<taNumber> &quiz, SRPoolRunner &pr,
SRBucketSummatorPar<taNumber> &bsp, const SRPoolRunner::Split& targSplit)
{
CENormPriorsTask<taNumber> normPriorsTask(*this, quiz, bsp);
{ // The lifetime for maximum selection subtasks
SRPoolRunner::Keeper<CENormPriorsSubtaskMax<taNumber>> kp = pr.RunPreSplit<CENormPriorsSubtaskMax<taNumber>>(
normPriorsTask, targSplit);
assert(kp.GetNSubtasks() == targSplit._nSubtasks);
const SRThreadCount nResultVects = kp.GetNSubtasks() >> SRSimd::_cLogNComps64;
const SRVectCompCount nTail = kp.GetNSubtasks() & ((SRThreadCount(1) << SRSimd::_cLogNComps64) - 1);
__m256i vMaxExps;
auto fnFetch = [&kp, iBase = (nResultVects << SRSimd::_cLogNComps64)](const SRVectCompCount at) {
return kp.GetSubtask(iBase + at)->_maxExp;
};
if (nResultVects == 0) {
SRSimd::ForTailI64(nTail, fnFetch, [&](const __m256i& vect) { vMaxExps = vect; },
std::numeric_limits<int64_t>::min());
}
else {
vMaxExps = _mm256_set_epi64x(kp.GetSubtask(3)->_maxExp, kp.GetSubtask(2)->_maxExp, kp.GetSubtask(1)->_maxExp,
kp.GetSubtask(0)->_maxExp);
for (SRThreadCount i = 1; i < nResultVects; i++) {
const SRThreadCount iBase = (i << SRSimd::_cLogNComps64);
const __m256i cand = _mm256_set_epi64x(kp.GetSubtask(iBase + 3)->_maxExp,
kp.GetSubtask(iBase + 2)->_maxExp, kp.GetSubtask(iBase + 1)->_maxExp, kp.GetSubtask(iBase)->_maxExp);
vMaxExps = SRSimd::MaxI64(vMaxExps, cand);
}
SRSimd::ForTailI64(nTail, fnFetch, [&](const __m256i& cand) { vMaxExps = SRSimd::MaxI64(vMaxExps, cand); },
std::numeric_limits<int64_t>::min());
}
const int64_t fullMax = SRSimd::FullHorizMaxI64(vMaxExps);
const int64_t highBound = taNumber::_cMaxExp + taNumber::_cExpOffs - SRMath::CeilLog2(_dims._nTargets) - 2;
const int64_t minAllowed = std::numeric_limits<int64_t>::min() + highBound + 1;
if (fullMax <= minAllowed) {
return PqaError(PqaErrorCode::I64Underflow, new I64UnderflowErrorParams(fullMax, minAllowed),
SRString::MakeUnowned("Max exponent over the priors is too low. Are all the targets in gaps?"));
}
normPriorsTask._corrExp = _mm256_set1_epi64x(highBound - fullMax); // so that fullMax + correction == highBound
}
// Correct the exponents towards the taNumber range, and calculate their sum
pr.RunPreSplit<CENormPriorsSubtaskCorrSum<taNumber>>(normPriorsTask, targSplit);
normPriorsTask._sumPriors.Set1(bsp.ComputeSum(pr));
// Divide priors by their sum, so to get probabilities.
pr.RunPreSplit<CEDivTargPriorsSubtask<CENormPriorsTask<taNumber>>>(normPriorsTask, targSplit);
return PqaError();
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::NextQuestion(PqaError& err, const TPqaId iQuiz) {
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (compute next question) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
CEQuiz<taNumber> *pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return cInvalidPqaId;
}
const SRThreadCount nWorkers = _tpWorkers.GetWorkerCount();
constexpr size_t subtasksOffs = 0;
const size_t splitOffs = subtasksOffs + nWorkers * std::max(_cNormPriorsMemReqPerSubtask,
SRMaxSizeof<CEEvalQsSubtaskConsider<taNumber> >::value);
const size_t bucketsOffs = SRSimd::GetPaddedBytes(splitOffs + SRPoolRunner::CalcSplitMemReq(nWorkers));
const size_t runLengthOffs = SRSimd::GetPaddedBytes(bucketsOffs + std::max(
SRBucketSummatorPar<taNumber>::GetMemoryRequirementBytes(nWorkers),
// Here we rely that SRBucketSummatorSeq::GetMemoryRequirementBytes() returns SIMD-aligned number of bytes,
// so that for each worker its bucket summator is aligned.
SRBucketSummatorSeq<taNumber>::GetMemoryRequirementBytes() * nWorkers ));
// The shared block for CEEvalQsSubtaskConsider
const size_t posteriorOffs = runLengthOffs + SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nQuestions);
const size_t threadPosteriorBytes = SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nTargets);
const size_t answerMetricsOffs = posteriorOffs + nWorkers * threadPosteriorBytes;
const size_t threadAnswerMetricsBytes = 2 * SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nAnswers);
const size_t nWithAnswerMetrics = answerMetricsOffs + nWorkers * threadAnswerMetricsBytes;
// The shared block for binary search over the run length.
const size_t grandTotalsOffs = posteriorOffs;
const size_t nWithGrandTotals = grandTotalsOffs + sizeof(taNumber) * nWorkers;
const size_t totalBytes = std::max(nWithAnswerMetrics, nWithGrandTotals);
SRSmartMPP<uint8_t> commonBuf(_memPool, totalBytes);
SRPoolRunner pr(_tpWorkers, commonBuf.Get() + subtasksOffs);
SRBucketSummatorPar<taNumber> bsp(nWorkers, commonBuf.Get() + bucketsOffs);
const TPqaId nTargetVects = SRMath::PosDivideRoundUp(_dims._nTargets, TPqaId(SRNumPack<taNumber>::_cnComps));
const SRPoolRunner::Split targSplit = SRPoolRunner::CalcSplit(commonBuf.Get() + splitOffs, nTargetVects, nWorkers);
err = NormalizePriors(*pQuiz, pr, bsp, targSplit);
if (!err.IsOk()) {
return cInvalidPqaId;
}
TPqaId selQuestion;
do {
CEEvalQsTask<taNumber> evalQsTask(*this, *pQuiz, _dims._nTargets - _targetGaps.GetNGaps(),
commonBuf.Get() + bucketsOffs, SRCast::Ptr<taNumber>(commonBuf.Get() + runLengthOffs),
commonBuf.Get() + posteriorOffs, threadPosteriorBytes, commonBuf.Get() + answerMetricsOffs,
threadAnswerMetricsBytes);
// Although there are no more subtasks which would use this split, it will be used for run-length analysis.
const SRPoolRunner::Split questionSplit = SRPoolRunner::CalcSplit(commonBuf.Get() + splitOffs, _dims._nQuestions,
nWorkers);
{
SRRWLock<false> rwl(_rws);
SRPoolRunner::Keeper<CEEvalQsSubtaskConsider<taNumber>> kp = pr.RunPreSplit<CEEvalQsSubtaskConsider<taNumber>>(
evalQsTask, questionSplit);
}
SRAccumulator<taNumber> accTotG(taNumber(0.0));
const taNumber *const PTR_RESTRICT pRunLength = evalQsTask.GetRunLength();
taNumber *const PTR_RESTRICT pGrandTotals = SRCast::Ptr<taNumber>(commonBuf.Get() + grandTotalsOffs);
for (SRThreadCount i = 0; i < questionSplit._nSubtasks; i++) {
const taNumber curGT = pRunLength[questionSplit._pBounds[i] - 1];
accTotG.Add(curGT);
pGrandTotals[i] = accTotG.Get();
}
const taNumber totG = pGrandTotals[questionSplit._nSubtasks - 1];
const taNumber selRunLen = taNumber::MakeRandom(totG, pQuiz->Random());
const SRThreadCount iWorker = static_cast<SRThreadCount>(
std::upper_bound(pGrandTotals, pGrandTotals + questionSplit._nSubtasks, selRunLen) - pGrandTotals);
if (iWorker >= questionSplit._nSubtasks) {
assert(iWorker == questionSplit._nSubtasks);
selQuestion = _dims._nQuestions - 1;
break;
}
const TPqaId iFirst = ((iWorker == 0) ? 0 : questionSplit._pBounds[iWorker - 1]);
const TPqaId iLimit = questionSplit._pBounds[iWorker];
selQuestion = std::upper_bound(pRunLength + iFirst, pRunLength + iLimit, selRunLen) - pRunLength;
if (selQuestion >= iLimit) {
assert(selQuestion == iLimit);
CELOG(Warning) << SR_FILE_LINE "Hopefully due to a rounding error, within-worker run length binary search hasn't"
" found a strictly greater value, while the binary search over grand totals pointed to this worker's piece."
" Random selection: " << selRunLen.ToAmount() << ", worker index " << iWorker << ", grand total "
<< pGrandTotals[iWorker].ToAmount() << ", worker max run length " << pRunLength[iLimit-1].ToAmount();
selQuestion = iLimit - 1;
}
} WHILE_FALSE;
// If the selected question is in a gap or already answered, try to select the neighboring questions
if (_questionGaps.IsGap(selQuestion) || SRBitHelper::Test(pQuiz->GetQAsked(), selQuestion)) {
selQuestion = FindNearestQuestion(selQuestion, *pQuiz);
}
if (selQuestion == cInvalidPqaId) {
err = PqaError(PqaErrorCode::QuestionsExhausted, nullptr, SRString::MakeUnowned(SR_FILE_LINE "Found no unasked"
" question that is not in a gap."));
return cInvalidPqaId;
}
pQuiz->SetActiveQuestion(selQuestion);
_nQuestionsAsked.fetch_add(1, std::memory_order_relaxed);
return selQuestion;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RecordAnswer(const TPqaId iQuiz, const TPqaId iAnswer) {
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
return PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (record an answer) because current mode is not regular (but maintenance/shutdown?)."));
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
// Check that iAnswer is within the range
if (iAnswer < 0 || iAnswer >= _dims._nAnswers) {
return PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iAnswer, 0, _dims._nAnswers - 1),
SRString::MakeUnowned("Answer index is not in the answer range."));
}
CEQuiz<taNumber> *pQuiz;
{
PqaError err;
pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return err;
}
}
return pQuiz->RecordAnswer(iAnswer);
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::ListTopTargets(PqaError& err, const TPqaId iQuiz,
const TPqaId maxCount, RatedTarget *pDest)
{
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (compute next question) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
CEQuiz<taNumber> *pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return cInvalidPqaId;
}
const SRThreadCount nWorkers = _tpWorkers.GetWorkerCount();
constexpr size_t subtasksOffs = 0;
const size_t splitOffs = subtasksOffs + nWorkers * _cNormPriorsMemReqPerSubtask;
const size_t bucketsOffs = SRSimd::GetPaddedBytes(splitOffs + SRPoolRunner::CalcSplitMemReq(nWorkers));
const size_t nWithBuckets = SRSimd::GetPaddedBytes(bucketsOffs +
SRBucketSummatorPar<taNumber>::GetMemoryRequirementBytes(nWorkers));
const size_t totalBytes = nWithBuckets;
SRSmartMPP<uint8_t> commonBuf(_memPool, totalBytes);
SRPoolRunner pr(_tpWorkers, commonBuf.Get() + subtasksOffs);
SRBucketSummatorPar<taNumber> bsp(nWorkers, commonBuf.Get() + bucketsOffs);
const TPqaId nTargetVects = SRMath::PosDivideRoundUp(_dims._nTargets, TPqaId(SRNumPack<taNumber>::_cnComps));
const SRPoolRunner::Split targSplit = SRPoolRunner::CalcSplit(commonBuf.Get() + splitOffs, nTargetVects, nWorkers);
err = NormalizePriors(*pQuiz, pr, bsp, targSplit);
if (!err.IsOk()) {
return cInvalidPqaId;
}
//TODO: remove when implemented
err = PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ListTopTargets")));
return cInvalidPqaId;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RecordQuizTarget(const TPqaId iQuiz, const TPqaId iTarget,
const TPqaAmount amount)
{
(void)iQuiz; (void)iTarget; (void)amount; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RecordQuizTarget")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::ReleaseQuiz(const TPqaId iQuiz) {
(void)iQuiz; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ReleaseQuiz")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::SaveKB(const char* const filePath, const bool bDoubleBuffer) {
(void)filePath; (void)bDoubleBuffer; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::SaveKB")));
}
template<typename taNumber> uint64_t CpuEngine<taNumber>::GetTotalQuestionsAsked(PqaError& err) {
err.Release();
return _nQuestionsAsked.load(std::memory_order_relaxed);
}
template<typename taNumber> PqaError CpuEngine<taNumber>::StartMaintenance(const bool forceQuizes) {
(void)forceQuizes; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::StartMaintenance")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::FinishMaintenance() {
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::FinishMaintenance")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::AddQuestions(TPqaId nQuestions, AddQuestionParam *pAqps) {
(void)nQuestions; (void)pAqps; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::AddQuestions")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::AddTargets(TPqaId nTargets, AddTargetParam *pAtps) {
(void)nTargets; (void)pAtps; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::AddTargets")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RemoveQuestions(const TPqaId nQuestions, const TPqaId *pQIds)
{
(void)nQuestions; (void)pQIds; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RemoveQuestions")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RemoveTargets(const TPqaId nTargets, const TPqaId *pTIds) {
(void)nTargets; (void)pTIds; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RemoveTargets")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Compact(CompactionResult &cr) {
(void)cr; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::Compact")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::ReleaseCompactionResult(CompactionResult &cr) {
(void)cr; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ReleaseCompactionResult")));
}
//// Instantiations
template class CpuEngine<SRDoubleNumber>;
} // namespace ProbQA
Removed normalization from the beginnings of NextQuestion() and ListTopTargets() of CpuEngine.
// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
#include "../PqaCore/CpuEngine.h"
#include "../PqaCore/PqaException.h"
#include "../PqaCore/CETrainTask.h"
#include "../PqaCore/ErrorHelper.h"
#include "../PqaCore/CETask.h"
#include "../PqaCore/CETrainSubtaskDistrib.h"
#include "../PqaCore/CETrainSubtaskAdd.h"
#include "../PqaCore/CETrainTaskNumSpec.h"
#include "../PqaCore/CEQuiz.h"
#include "../PqaCore/CECreateQuizOperation.h"
#include "../PqaCore/CEEvalQsTask.h"
#include "../PqaCore/CEEvalQsSubtaskConsider.h"
using namespace SRPlat;
namespace ProbQA {
#define CELOG(severityVar) SRLogStream(ISRLogger::Severity::severityVar, _pLogger.load(std::memory_order_acquire))
template<typename taNumber> CpuEngine<taNumber>::CpuEngine(const EngineDefinition& engDef) : BaseCpuEngine(engDef) {
if (_dims._nAnswers < cMinAnswers || _dims._nQuestions < cMinQuestions || _dims._nTargets < cMinTargets)
{
throw PqaException(PqaErrorCode::InsufficientEngineDimensions, new InsufficientEngineDimensionsErrorParams(
_dims._nAnswers, cMinAnswers, _dims._nQuestions, cMinQuestions, _dims._nTargets, cMinTargets));
}
taNumber initAmount(engDef._initAmount);
//// Init cube A: A[q][ao][t] is weight for answer option |ao| for question |q| for target |t|
_sA.resize(SRCast::ToSizeT(_dims._nQuestions));
for (size_t i = 0, iEn= SRCast::ToSizeT(_dims._nQuestions); i < iEn; i++) {
_sA[i].resize(SRCast::ToSizeT(_dims._nAnswers));
for (size_t k = 0, kEn= SRCast::ToSizeT(_dims._nAnswers); k < kEn; k++) {
_sA[i][k].Resize<false>(SRCast::ToSizeT(_dims._nTargets));
_sA[i][k].FillAll<false>(initAmount);
}
}
//// Init matrix D: D[q][t] is the sum of weigths over all answers for question |q| for target |t|. In the other
//// words, D[q][t] is A[0][q][t] + A[1][q][t] + ... + A[K-1][q][t], where K is the number of answer options.
//// Note that D is subject to summation errors, thus its regular recomputation is desired.
taNumber initMD = initAmount * _dims._nAnswers;
_mD.resize(size_t(_dims._nQuestions));
for (size_t i = 0, iEn=size_t(_dims._nQuestions); i < iEn; i++) {
_mD[i].Resize<false>(size_t(_dims._nTargets));
_mD[i].FillAll<false>(initMD);
}
//// Init vector B: the sums of weights over all trainings for each target
_vB.Resize<false>(size_t(_dims._nTargets));
_vB.FillAll<false>(initAmount);
_questionGaps.GrowTo(_dims._nQuestions);
_targetGaps.GrowTo(_dims._nTargets);
//throw PqaException(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
// "CpuEngine<taNumber>::CpuEngine(const EngineDefinition& engDef)")));
}
template<typename taNumber> CpuEngine<taNumber>::~CpuEngine() {
PqaError pqaErr = Shutdown();
if (!pqaErr.IsOk() && pqaErr.GetCode() != PqaErrorCode::ObjectShutDown) {
CELOG(Error) << "Failed CpuEngine::Shutdown(): " << pqaErr.ToString(true);
}
}
template<typename taNumber> PqaError CpuEngine<taNumber>::SetLogger(ISRLogger *pLogger) {
if (pLogger == nullptr) {
pLogger = SRDefaultLogger::Get();
}
_pLogger.store(pLogger, std::memory_order_release);
return PqaError();
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Shutdown(const char* const saveFilePath) {
if (!_maintSwitch.Shutdown()) {
// Return an error saying that the engine seems already shut down.
SRMessageBuilder mbMsg("MaintenanceSwitch seems already shut down.");
if (saveFilePath != nullptr) {
mbMsg(" Not saving file: ")(saveFilePath);
}
return PqaError(PqaErrorCode::ObjectShutDown, new ObjectShutDownErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::Shutdown()")), mbMsg.GetOwnedSRString());
}
// By this moment, all operations must have shut down and no new operations can be started.
if (saveFilePath != nullptr) {
//TODO: implement
}
//TODO: check the order - perhaps some releases should happen while the workers are still operational
//// Shutdown worker threads
_tpWorkers.RequestShutdown();
//// Release quizzes
for (size_t i = 0; i < _quizzes.size(); i++) {
SRCheckingRelease(_memPool, _quizzes[i]);
}
_quizzes.clear();
_quizGaps.Compact(0);
//// Release KB
_sA.clear();
_mD.clear();
_vB.Clear();
_questionGaps.Compact(0);
_targetGaps.Compact(0);
_dims._nAnswers = _dims._nQuestions = _dims._nTargets = 0;
//// Release memory pool
_memPool.FreeAllChunks();
return PqaError();
}
template<> void CpuEngine<SRDoubleNumber>::InitTrainTaskNumSpec(CETrainTaskNumSpec<SRDoubleNumber>& numSpec,
const TPqaAmount amount)
{
const double dAmount = SRCast::ToDouble(amount);
numSpec._collAddend = numSpec._fullAddend = _mm256_set1_pd(dAmount);
// Colliding addend: amount is added twice to _mD[iQuestion][iTarget] .
numSpec._collAddend.m256d_f64[1] += dAmount;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::TrainInternal(const TPqaId nQuestions,
const AnsweredQuestion* const pAQs, const TPqaId iTarget, const TPqaAmount amount)
{
if (nQuestions < 0) {
return PqaError(PqaErrorCode::NegativeCount, new NegativeCountErrorParams(nQuestions), SRString::MakeUnowned(
"|nQuestions| must be non-negative."));
}
if (amount <= 0) {
return PqaError(PqaErrorCode::NonPositiveAmount, new NonPositiveAmountErrorParams(amount), SRString::MakeUnowned(
"|amount| must be positive."));
}
PqaError resErr;
const SRThreadCount nWorkers = _tpWorkers.GetWorkerCount();
//// Do a single allocation for all needs. Allocate memory out of locks.
// For proper alignment, the data must be laid out in the decreasing order of item alignments.
const size_t ttLastOffs = nWorkers * SRMaxSizeof<CETrainSubtaskDistrib<taNumber>, CETrainSubtaskAdd<taNumber>>::value;
const size_t ttPrevOffs = ttLastOffs + sizeof(std::atomic<TPqaId>) * nWorkers;
const size_t nTotalBytes = ttPrevOffs + sizeof(TPqaId) * SRCast::ToSizeT(nQuestions);
SRSmartMPP<uint8_t> commonBuf(_memPool, nTotalBytes);
CETrainTask<taNumber> trainTask(*this, nWorkers, iTarget, pAQs);
//TODO: these are slow because threads share a cache line. It's not clear yet how to workaround this: the data is not
// per-source thread, but rather per target thread (after distribution).
trainTask._prev = SRCast::Ptr<TPqaId>(commonBuf.Get() + ttPrevOffs);
trainTask._last = SRCast::Ptr<std::atomic<TPqaId>>(commonBuf.Get() + ttLastOffs);
InitTrainTaskNumSpec(trainTask._numSpec, amount);
//TODO: vectorize/parallelize
for (size_t i = 0; i < nWorkers; i++) {
new(trainTask._last + i) std::atomic<TPqaId>(cInvalidPqaId);
}
// &trainTask, &nWorkers
auto&& ttLastFinally = SRMakeFinally([&pLast = trainTask._last, &nWorkers]{
//TODO: vectorize/parallelize
for (size_t i = 0; i < nWorkers; i++) {
pLast[i].~atomic();
}
}); (void)ttLastFinally; // prevent warning C4189
{ // Scope for the locks
MaintenanceSwitch::AgnosticLock msal(_maintSwitch);
//// The further code must be reader-writer locked, because we are validating the input before modifying the KB,
//// so noone must change or read the KB in between.
SRRWLock<true> rwl(_rws);
// Can't move dimensions-related code out of SRW lock because this operation can be run in maintenance mode too.
if (iTarget < 0 || iTarget >= _dims._nTargets) {
const TPqaId nKB = _dims._nTargets;
rwl.EarlyRelease();
return PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iTarget, 0, nKB - 1),
SRString::MakeUnowned("Target index is not in KB range."));
}
if (_targetGaps.IsGap(iTarget)) {
rwl.EarlyRelease();
return PqaError(PqaErrorCode::AbsentId, new AbsentIdErrorParams(iTarget), SRString::MakeUnowned(
"Target index is not in KB (but rather at a gap)."));
}
SRPoolRunner pr(_tpWorkers, commonBuf.Get());
//// Distribute the AQs into buckets with the number of buckets divisable by the number of workers.
pr.SplitAndRunSubtasks<CETrainSubtaskDistrib<taNumber>>(trainTask, nQuestions, trainTask.GetWorkerCount(),
[&](void *pStMem, SRThreadCount iWorker, int64_t iFirst, int64_t iLimit) {
new (pStMem) CETrainSubtaskDistrib<taNumber>(&trainTask, pAQs + iFirst, pAQs + iLimit);
(void)iWorker;
}
);
resErr = trainTask.TakeAggregateError(SRString::MakeUnowned("Failed " SR_FILE_LINE));
if (!resErr.IsOk()) {
return resErr;
}
//// Update the KB with the given training data.
pr.RunPerWorkerSubtasks<CETrainSubtaskAdd<taNumber>>(trainTask, trainTask.GetWorkerCount());
resErr = trainTask.TakeAggregateError(SRString::MakeUnowned("Failed " SR_FILE_LINE));
if (!resErr.IsOk()) {
return resErr;
}
_vB[iTarget] += amount;
// This method should increase the counter of questions asked by the number of questions in this training.
_nQuestionsAsked.fetch_add(nQuestions, std::memory_order_relaxed);
}
return PqaError();
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Train(const TPqaId nQuestions,
const AnsweredQuestion* const pAQs, const TPqaId iTarget, const TPqaAmount amount)
{
try {
return TrainInternal(nQuestions, pAQs, iTarget, amount);
}
CATCH_TO_ERR_RETURN;
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::CreateQuizInternal(CECreateQuizOpBase &op) {
try {
struct NoSrwTask : public CETask {
CEQuiz<taNumber> *_pQuiz;
public: // methods
explicit NoSrwTask(CpuEngine<taNumber> &ce) : CETask(ce, /*nWorkers*/ 3) { }
} tNoSrw(*this); // Subtasks without SRW locked
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
op._err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (Start/Resume quiz) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
// So long as this constructor only needs the number of questions and targets, it can be out of _rws because
// _maintSwitch guards engine dimensions in Regular mode (but not in Maintenance mode).
SRObjectMPP<CEQuiz<taNumber>> spQuiz(_memPool, this);
tNoSrw._pQuiz = spQuiz.Get();
TPqaId quizId;
{
SRLock<SRCriticalSection> csl(_csQuizReg);
quizId = _quizGaps.Acquire();
if (quizId >= TPqaId(_quizzes.size())) {
assert(quizId == TPqaId(_quizzes.size()));
_quizzes.emplace_back(nullptr);
}
_quizzes[SRCast::ToSizeT(quizId)] = spQuiz.Get();
}
{
auto&& lstSetQAsked = SRMakeLambdaSubtask(&tNoSrw, [&op](const SRBaseSubtask &subtask) {
auto& task = static_cast<NoSrwTask&>(*subtask.GetTask());
auto& engine = static_cast<const CpuEngine<taNumber>&>(task.GetBaseEngine());
__m256i *pQAsked = task._pQuiz->GetQAsked();
SRUtils::FillZeroVects<true>(pQAsked, SRSimd::VectsFromBits(engine._dims._nQuestions));
if (op.IsResume()) {
// Validate the indexes and set "is question asked" bits
auto& resumeOp = static_cast<CECreateQuizResume<taNumber>&>(op);
const EngineDimensions& dims = engine.GetDims();
for (size_t i = 0; i<SRCast::ToSizeT(resumeOp._nAnswered); i++) {
const TPqaId iQuestion = resumeOp._pAQs[i]._iQuestion;
if (iQuestion < 0 || iQuestion >= dims._nQuestions) {
task.AddError(PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iQuestion, 0,
dims._nQuestions - 1), SRString::MakeUnowned(SR_FILE_LINE "Question index is not in KB range.")));
return;
}
const TPqaId iAnswer = resumeOp._pAQs[i]._iAnswer;
if (iAnswer < 0 || iAnswer >= dims._nAnswers) {
task.AddError(PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iAnswer, 0,
dims._nAnswers - 1), SRString::MakeUnowned(SR_FILE_LINE "Answer index is not in KB range.")));
return;
}
*(SRCast::Ptr<uint8_t>(pQAsked) + (iQuestion >> 3)) |= (1ui8 << (iQuestion & 7));
}
}
});
auto&& lstAddAnswers = SRMakeLambdaSubtask(&tNoSrw, [&op](const SRBaseSubtask &subtask) {
auto& resumeOp = static_cast<const CECreateQuizResume<taNumber>&>(op);
auto& task = static_cast<const NoSrwTask&>(*subtask.GetTask());
std::vector<AnsweredQuestion>& answers = task._pQuiz->ModAnswers();
answers.insert(answers.end(), resumeOp._pAQs, resumeOp._pAQs + resumeOp._nAnswered);
});
SRTaskWaiter noSrwTaskWaiter(&tNoSrw);
if(op.IsResume()) {
_tpWorkers.Enqueue({&lstSetQAsked, &lstAddAnswers}, tNoSrw);
} else {
_tpWorkers.Enqueue(&lstSetQAsked);
}
}
op._err = tNoSrw.TakeAggregateError();
if(op._err.IsOk()) {
// If it's "resume quiz" operation, update the prior likelihoods with the questions answered, and normalize the
// priors. If it's "start quiz" operation, just divide the priors by their sum.
op.UpdateLikelihoods(*this, *spQuiz.Get());
}
if (!op._err.IsOk()) {
spQuiz.EarlyRelease();
SRLock<SRCriticalSection> csl(_csQuizReg);
_quizzes[SRCast::ToSizeT(quizId)] = nullptr;
_quizGaps.Release(quizId);
return cInvalidPqaId;
}
spQuiz.Detach();
return quizId;
}
CATCH_TO_ERR_SET(op._err);
return cInvalidPqaId;
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::StartQuiz(PqaError& err) {
CECreateQuizStart<taNumber> startOp(err);
return CreateQuizInternal(startOp);
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::ResumeQuiz(PqaError& err, const TPqaId nAnswered,
const AnsweredQuestion* const pAQs)
{
if(nAnswered < 0) {
err = PqaError(PqaErrorCode::NegativeCount, new NegativeCountErrorParams(nAnswered), SRString::MakeUnowned(
"|nAnswered| must be non-negative."));
return cInvalidPqaId;
}
if (nAnswered == 0) {
return StartQuiz(err);
}
CECreateQuizResume<taNumber> resumeOp(err, nAnswered, pAQs);
return CreateQuizInternal(resumeOp);
}
template<typename taNumber> CEQuiz<taNumber>* CpuEngine<taNumber>::UseQuiz(PqaError& err, const TPqaId iQuiz) {
SRLock<SRCriticalSection> csl(_csQuizReg);
const TPqaId nQuizzes = _quizzes.size();
if (iQuiz < 0 || iQuiz >= nQuizzes) {
csl.EarlyRelease();
// For nQuizzes == 0, this may return [0;-1] range: we can't otherwise return an empty range because we return
// the range with both bounds inclusive.
err = PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iQuiz, 0, nQuizzes - 1),
SRString::MakeUnowned(SR_FILE_LINE "Quiz index is not in quiz registry range."));
return nullptr;
}
if (_quizGaps.IsGap(iQuiz)) {
csl.EarlyRelease();
err = PqaError(PqaErrorCode::AbsentId, new AbsentIdErrorParams(iQuiz), SRString::MakeUnowned(
SR_FILE_LINE "Quiz index is not in the registry (but rather at a gap)."));
return nullptr;
}
return _quizzes[iQuiz];
}
template<typename taNumber> PqaError CpuEngine<taNumber>::NormalizePriors(CEQuiz<taNumber> &quiz, SRPoolRunner &pr,
SRBucketSummatorPar<taNumber> &bsp, const SRPoolRunner::Split& targSplit)
{
CENormPriorsTask<taNumber> normPriorsTask(*this, quiz, bsp);
{ // The lifetime for maximum selection subtasks
SRPoolRunner::Keeper<CENormPriorsSubtaskMax<taNumber>> kp = pr.RunPreSplit<CENormPriorsSubtaskMax<taNumber>>(
normPriorsTask, targSplit);
assert(kp.GetNSubtasks() == targSplit._nSubtasks);
const SRThreadCount nResultVects = kp.GetNSubtasks() >> SRSimd::_cLogNComps64;
const SRVectCompCount nTail = kp.GetNSubtasks() & ((SRThreadCount(1) << SRSimd::_cLogNComps64) - 1);
__m256i vMaxExps;
auto fnFetch = [&kp, iBase = (nResultVects << SRSimd::_cLogNComps64)](const SRVectCompCount at) {
return kp.GetSubtask(iBase + at)->_maxExp;
};
if (nResultVects == 0) {
SRSimd::ForTailI64(nTail, fnFetch, [&](const __m256i& vect) { vMaxExps = vect; },
std::numeric_limits<int64_t>::min());
}
else {
vMaxExps = _mm256_set_epi64x(kp.GetSubtask(3)->_maxExp, kp.GetSubtask(2)->_maxExp, kp.GetSubtask(1)->_maxExp,
kp.GetSubtask(0)->_maxExp);
for (SRThreadCount i = 1; i < nResultVects; i++) {
const SRThreadCount iBase = (i << SRSimd::_cLogNComps64);
const __m256i cand = _mm256_set_epi64x(kp.GetSubtask(iBase + 3)->_maxExp,
kp.GetSubtask(iBase + 2)->_maxExp, kp.GetSubtask(iBase + 1)->_maxExp, kp.GetSubtask(iBase)->_maxExp);
vMaxExps = SRSimd::MaxI64(vMaxExps, cand);
}
SRSimd::ForTailI64(nTail, fnFetch, [&](const __m256i& cand) { vMaxExps = SRSimd::MaxI64(vMaxExps, cand); },
std::numeric_limits<int64_t>::min());
}
const int64_t fullMax = SRSimd::FullHorizMaxI64(vMaxExps);
const int64_t highBound = taNumber::_cMaxExp + taNumber::_cExpOffs - SRMath::CeilLog2(_dims._nTargets) - 2;
const int64_t minAllowed = std::numeric_limits<int64_t>::min() + highBound + 1;
if (fullMax <= minAllowed) {
return PqaError(PqaErrorCode::I64Underflow, new I64UnderflowErrorParams(fullMax, minAllowed),
SRString::MakeUnowned("Max exponent over the priors is too low. Are all the targets in gaps?"));
}
normPriorsTask._corrExp = _mm256_set1_epi64x(highBound - fullMax); // so that fullMax + correction == highBound
}
// Correct the exponents towards the taNumber range, and calculate their sum
pr.RunPreSplit<CENormPriorsSubtaskCorrSum<taNumber>>(normPriorsTask, targSplit);
normPriorsTask._sumPriors.Set1(bsp.ComputeSum(pr));
// Divide priors by their sum, so to get probabilities.
pr.RunPreSplit<CEDivTargPriorsSubtask<CENormPriorsTask<taNumber>>>(normPriorsTask, targSplit);
return PqaError();
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::NextQuestion(PqaError& err, const TPqaId iQuiz) {
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (compute next question) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
CEQuiz<taNumber> *pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return cInvalidPqaId;
}
const SRThreadCount nWorkers = _tpWorkers.GetWorkerCount();
constexpr size_t subtasksOffs = 0;
const size_t splitOffs = subtasksOffs + nWorkers * SRMaxSizeof<CEEvalQsSubtaskConsider<taNumber> >::value;
const size_t bucketsOffs = SRSimd::GetPaddedBytes(splitOffs + SRPoolRunner::CalcSplitMemReq(nWorkers));
const size_t runLengthOffs = SRSimd::GetPaddedBytes(bucketsOffs +
// Here we rely that SRBucketSummatorSeq::GetMemoryRequirementBytes() returns SIMD-aligned number of bytes,
// so that for each worker its bucket summator is aligned.
SRBucketSummatorSeq<taNumber>::GetMemoryRequirementBytes() * nWorkers);
// The shared block for CEEvalQsSubtaskConsider
const size_t posteriorOffs = runLengthOffs + SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nQuestions);
const size_t threadPosteriorBytes = SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nTargets);
const size_t answerMetricsOffs = posteriorOffs + nWorkers * threadPosteriorBytes;
const size_t threadAnswerMetricsBytes = 2 * SRSimd::GetPaddedBytes(sizeof(taNumber) * _dims._nAnswers);
const size_t nWithAnswerMetrics = answerMetricsOffs + nWorkers * threadAnswerMetricsBytes;
// The shared block for binary search over the run length.
const size_t grandTotalsOffs = posteriorOffs;
const size_t nWithGrandTotals = grandTotalsOffs + sizeof(taNumber) * nWorkers;
const size_t totalBytes = std::max(nWithAnswerMetrics, nWithGrandTotals);
SRSmartMPP<uint8_t> commonBuf(_memPool, totalBytes);
SRPoolRunner pr(_tpWorkers, commonBuf.Get() + subtasksOffs);
TPqaId selQuestion;
do {
CEEvalQsTask<taNumber> evalQsTask(*this, *pQuiz, _dims._nTargets - _targetGaps.GetNGaps(),
commonBuf.Get() + bucketsOffs, SRCast::Ptr<taNumber>(commonBuf.Get() + runLengthOffs),
commonBuf.Get() + posteriorOffs, threadPosteriorBytes, commonBuf.Get() + answerMetricsOffs,
threadAnswerMetricsBytes);
// Although there are no more subtasks which would use this split, it will be used for run-length analysis.
const SRPoolRunner::Split questionSplit = SRPoolRunner::CalcSplit(commonBuf.Get() + splitOffs, _dims._nQuestions,
nWorkers);
{
SRRWLock<false> rwl(_rws);
SRPoolRunner::Keeper<CEEvalQsSubtaskConsider<taNumber>> kp = pr.RunPreSplit<CEEvalQsSubtaskConsider<taNumber>>(
evalQsTask, questionSplit);
}
SRAccumulator<taNumber> accTotG(taNumber(0.0));
const taNumber *const PTR_RESTRICT pRunLength = evalQsTask.GetRunLength();
taNumber *const PTR_RESTRICT pGrandTotals = SRCast::Ptr<taNumber>(commonBuf.Get() + grandTotalsOffs);
for (SRThreadCount i = 0; i < questionSplit._nSubtasks; i++) {
const taNumber curGT = pRunLength[questionSplit._pBounds[i] - 1];
accTotG.Add(curGT);
pGrandTotals[i] = accTotG.Get();
}
const taNumber totG = pGrandTotals[questionSplit._nSubtasks - 1];
const taNumber selRunLen = taNumber::MakeRandom(totG, pQuiz->Random());
const SRThreadCount iWorker = static_cast<SRThreadCount>(
std::upper_bound(pGrandTotals, pGrandTotals + questionSplit._nSubtasks, selRunLen) - pGrandTotals);
if (iWorker >= questionSplit._nSubtasks) {
assert(iWorker == questionSplit._nSubtasks);
selQuestion = _dims._nQuestions - 1;
break;
}
const TPqaId iFirst = ((iWorker == 0) ? 0 : questionSplit._pBounds[iWorker - 1]);
const TPqaId iLimit = questionSplit._pBounds[iWorker];
selQuestion = std::upper_bound(pRunLength + iFirst, pRunLength + iLimit, selRunLen) - pRunLength;
if (selQuestion >= iLimit) {
assert(selQuestion == iLimit);
CELOG(Warning) << SR_FILE_LINE "Hopefully due to a rounding error, within-worker run length binary search hasn't"
" found a strictly greater value, while the binary search over grand totals pointed to this worker's piece."
" Random selection: " << selRunLen.ToAmount() << ", worker index " << iWorker << ", grand total "
<< pGrandTotals[iWorker].ToAmount() << ", worker max run length " << pRunLength[iLimit-1].ToAmount();
selQuestion = iLimit - 1;
}
} WHILE_FALSE;
// If the selected question is in a gap or already answered, try to select the neighboring questions
if (_questionGaps.IsGap(selQuestion) || SRBitHelper::Test(pQuiz->GetQAsked(), selQuestion)) {
selQuestion = FindNearestQuestion(selQuestion, *pQuiz);
}
if (selQuestion == cInvalidPqaId) {
err = PqaError(PqaErrorCode::QuestionsExhausted, nullptr, SRString::MakeUnowned(SR_FILE_LINE "Found no unasked"
" question that is not in a gap."));
return cInvalidPqaId;
}
pQuiz->SetActiveQuestion(selQuestion);
_nQuestionsAsked.fetch_add(1, std::memory_order_relaxed);
return selQuestion;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RecordAnswer(const TPqaId iQuiz, const TPqaId iAnswer) {
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
return PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (record an answer) because current mode is not regular (but maintenance/shutdown?)."));
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
// Check that iAnswer is within the range
if (iAnswer < 0 || iAnswer >= _dims._nAnswers) {
return PqaError(PqaErrorCode::IndexOutOfRange, new IndexOutOfRangeErrorParams(iAnswer, 0, _dims._nAnswers - 1),
SRString::MakeUnowned("Answer index is not in the answer range."));
}
CEQuiz<taNumber> *pQuiz;
{
PqaError err;
pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return err;
}
}
return pQuiz->RecordAnswer(iAnswer);
}
template<typename taNumber> TPqaId CpuEngine<taNumber>::ListTopTargets(PqaError& err, const TPqaId iQuiz,
const TPqaId maxCount, RatedTarget *pDest)
{
constexpr auto msMode = MaintenanceSwitch::Mode::Regular;
if (!_maintSwitch.TryEnterSpecific<msMode>()) {
err = PqaError(PqaErrorCode::WrongMode, nullptr, SRString::MakeUnowned("Can't perform regular-only mode"
" operation (compute next question) because current mode is not regular (but maintenance/shutdown?)."));
return cInvalidPqaId;
}
MaintenanceSwitch::SpecificLeaver<msMode> mssl(_maintSwitch);
CEQuiz<taNumber> *pQuiz = UseQuiz(err, iQuiz);
if (pQuiz == nullptr) {
assert(!err.IsOk());
return cInvalidPqaId;
}
//TODO: implement, assuming normalized priors
//TODO: remove when implemented
err = PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ListTopTargets")));
return cInvalidPqaId;
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RecordQuizTarget(const TPqaId iQuiz, const TPqaId iTarget,
const TPqaAmount amount)
{
(void)iQuiz; (void)iTarget; (void)amount; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RecordQuizTarget")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::ReleaseQuiz(const TPqaId iQuiz) {
(void)iQuiz; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ReleaseQuiz")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::SaveKB(const char* const filePath, const bool bDoubleBuffer) {
(void)filePath; (void)bDoubleBuffer; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::SaveKB")));
}
template<typename taNumber> uint64_t CpuEngine<taNumber>::GetTotalQuestionsAsked(PqaError& err) {
err.Release();
return _nQuestionsAsked.load(std::memory_order_relaxed);
}
template<typename taNumber> PqaError CpuEngine<taNumber>::StartMaintenance(const bool forceQuizes) {
(void)forceQuizes; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::StartMaintenance")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::FinishMaintenance() {
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::FinishMaintenance")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::AddQuestions(TPqaId nQuestions, AddQuestionParam *pAqps) {
(void)nQuestions; (void)pAqps; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::AddQuestions")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::AddTargets(TPqaId nTargets, AddTargetParam *pAtps) {
(void)nTargets; (void)pAtps; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::AddTargets")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RemoveQuestions(const TPqaId nQuestions, const TPqaId *pQIds)
{
(void)nQuestions; (void)pQIds; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RemoveQuestions")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::RemoveTargets(const TPqaId nTargets, const TPqaId *pTIds) {
(void)nTargets; (void)pTIds; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::RemoveTargets")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::Compact(CompactionResult &cr) {
(void)cr; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::Compact")));
}
template<typename taNumber> PqaError CpuEngine<taNumber>::ReleaseCompactionResult(CompactionResult &cr) {
(void)cr; //TODO: remove when implemented
return PqaError(PqaErrorCode::NotImplemented, new NotImplementedErrorParams(SRString::MakeUnowned(
"CpuEngine<taNumber>::ReleaseCompactionResult")));
}
//// Instantiations
template class CpuEngine<SRDoubleNumber>;
} // namespace ProbQA
|
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] =
InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum =
InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = CardClass::_from_integral(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation =
InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable =
card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable >
MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() +
numCardToAddAvailable -
MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable
<< ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex =
InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID =
deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - "
<< deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck =
static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template <std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes")
? true
: (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(
std::string commandStr) const
{
// Output command string
std::cout << commandStr;
// Input commands
std::string cmd;
std::getline(std::cin, cmd);
// Split commands by whitespace and quote
std::istringstream iss(cmd);
std::vector<std::string> cmdTokens{"Hearthstone++"};
std::string cmdToken;
while (iss >> std::quoted(cmdToken))
{
cmdTokens.push_back(cmdToken);
}
// Convert std::string to const char*
std::vector<const char*> convertedSplitCmds{};
for (const auto& token : cmdTokens)
{
convertedSplitCmds.push_back(token.c_str());
}
// Parse command
bool showHelp = false;
std::string strName, strRarity, strPlayerClass, strCardType;
std::string strRace, strMechanics, strCost, strAttack, strHealth;
bool isValid = true, isFinish = false;
// Parsing
auto parser =
clara::Help(showHelp) |
clara::Opt(strName, "name")["-n"]["--name"]("the name of a card") |
clara::Opt(strRarity, "rarity")["-r"]["--rarity"](
"a rough measure of the quality and scarcity of a card") |
clara::Opt(strPlayerClass, "playerClass")["-c"]["--class"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strCardType, "cardType")["-t"]["--type"](
"spell cards, weapon cards, minion cards and hero cards") |
clara::Opt(strRace, "race")["-e"]["--race"](
"does not directly affect the behavior of the minion, but allows "
"it to be affected by certain type-specific effects") |
clara::Opt(strName, "cost")["-s"]["--cost"](
"determines how much mana is required to play that card from the "
"hand or to use that hero power") |
clara::Opt(strAttack, "attack")["-a"]["--attack"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strHealth, "health")["-l"]["--health"](
"an attribute found on heroes and minions, reflecting the "
"remaining survivability of the character") |
clara::Opt(strMechanics, "mechanics")["-m"]["--mechanics"](
"describes the total effect of playing that card or special "
"effects or powers additional to the basic functions of the card") |
clara::Opt(isFinish, "isFinish")["-f"]["--finish"]("finish the search");
auto result = parser.parse(
clara::Args(convertedSplitCmds.size(), convertedSplitCmds.data()));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
isValid = false;
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
isValid = false;
}
Rarity rarity = Rarity::_from_string_nothrow(strRarity.c_str())
? Rarity::_from_string(strRarity.c_str())
: Rarity::INVALID;
CardClass playerClass =
CardClass::_from_string_nothrow(strPlayerClass.c_str())
? CardClass::_from_string(strPlayerClass.c_str())
: CardClass::INVALID;
CardType cardType = CardType::_from_string_nothrow(strCardType.c_str())
? CardType::_from_string(strCardType.c_str())
: CardType::INVALID;
Race race = Race::_from_string_nothrow(strRace.c_str())
? Race::_from_string(strRace.c_str())
: Race::INVALID;
std::regex reValueRange("([[:digit:]]+)(-[[:digit:]]+)?");
if (std::regex_match(strCost, reValueRange))
{
std::cout << "Matched!\n";
}
else
{
std::cout << "Not matched!\n";
}
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = strName;
//filter.costMin = cost;
//filter.costMax = cost;
//filter.attackMin = attack;
//filter.attackMax = attack;
//filter.healthMin = health;
//filter.healthMax = health;
filter.mechanics = {};
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == +Rarity::INVALID ||
filter.rarity == card->GetRarity());
bool classCondition = false;
// When search mode is adding a card to a deck, the class is fixed to
// the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == +CardClass::NEUTRAL ||
filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == +CardClass::NEUTRAL ||
card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == +CardClass::INVALID ||
filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == +CardType::INVALID ||
filter.cardType == card->GetCardType());
bool raceCondition =
(filter.race == +Race::INVALID || filter.race == card->GetRace());
bool nameCondition =
(filter.name.empty() ||
card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) ||
(filter.costMin <= card->GetCost() &&
filter.costMax >= card->GetCost()));
bool attackCondition =
((filter.attackMin == -1 || filter.attackMax == -1) ||
(filter.attackMin <= card->GetAttack() &&
filter.attackMax >= card->GetAttack()));
bool healthCondition =
((filter.healthMin == -1 || filter.healthMax == -1) ||
(filter.healthMin <= card->GetHealth() &&
filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanics.size() == 0 ||
card->HasMechanics(filter.mechanics));
const bool isMatched =
AllCondIsTrue(rarityCondition, classCondition, typeCondition,
raceCondition, nameCondition, costCondition,
attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str,
std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
}
[ci skip] Fix incorrect variable use
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#include <clara.hpp>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
inline std::string ToString(const clara::Opt& opt)
{
std::ostringstream oss;
oss << (clara::Parser() | opt);
return oss.str();
}
inline std::string ToString(const clara::Parser& p)
{
std::ostringstream oss;
oss << p;
return oss.str();
}
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] =
InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum =
InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = CardClass::_from_integral(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation =
InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable =
card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable >
MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() +
numCardToAddAvailable -
MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable
<< ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex =
InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID =
deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - "
<< deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck =
static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template <std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes")
? true
: (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(
std::string commandStr) const
{
// Output command string
std::cout << commandStr;
// Input commands
std::string cmd;
std::getline(std::cin, cmd);
// Split commands by whitespace and quote
std::istringstream iss(cmd);
std::vector<std::string> cmdTokens{"Hearthstone++"};
std::string cmdToken;
while (iss >> std::quoted(cmdToken))
{
cmdTokens.push_back(cmdToken);
}
// Convert std::string to const char*
std::vector<const char*> convertedSplitCmds{};
for (const auto& token : cmdTokens)
{
convertedSplitCmds.push_back(token.c_str());
}
// Parse command
bool showHelp = false;
std::string strName, strRarity, strPlayerClass, strCardType;
std::string strRace, strMechanics, strCost, strAttack, strHealth;
bool isValid = true, isFinish = false;
// Parsing
auto parser =
clara::Help(showHelp) |
clara::Opt(strName, "name")["-n"]["--name"]("the name of a card") |
clara::Opt(strRarity, "rarity")["-r"]["--rarity"](
"a rough measure of the quality and scarcity of a card") |
clara::Opt(strPlayerClass, "playerClass")["-c"]["--class"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strCardType, "cardType")["-t"]["--type"](
"spell cards, weapon cards, minion cards and hero cards") |
clara::Opt(strRace, "race")["-e"]["--race"](
"does not directly affect the behavior of the minion, but allows "
"it to be affected by certain type-specific effects") |
clara::Opt(strCost, "cost")["-s"]["--cost"](
"determines how much mana is required to play that card from the "
"hand or to use that hero power") |
clara::Opt(strAttack, "attack")["-a"]["--attack"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strHealth, "health")["-l"]["--health"](
"an attribute found on heroes and minions, reflecting the "
"remaining survivability of the character") |
clara::Opt(strMechanics, "mechanics")["-m"]["--mechanics"](
"describes the total effect of playing that card or special "
"effects or powers additional to the basic functions of the card") |
clara::Opt(isFinish, "isFinish")["-f"]["--finish"]("finish the search");
auto result = parser.parse(
clara::Args(convertedSplitCmds.size(), convertedSplitCmds.data()));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
isValid = false;
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
isValid = false;
}
Rarity rarity = Rarity::_from_string_nothrow(strRarity.c_str())
? Rarity::_from_string(strRarity.c_str())
: Rarity::INVALID;
CardClass playerClass =
CardClass::_from_string_nothrow(strPlayerClass.c_str())
? CardClass::_from_string(strPlayerClass.c_str())
: CardClass::INVALID;
CardType cardType = CardType::_from_string_nothrow(strCardType.c_str())
? CardType::_from_string(strCardType.c_str())
: CardType::INVALID;
Race race = Race::_from_string_nothrow(strRace.c_str())
? Race::_from_string(strRace.c_str())
: Race::INVALID;
std::regex reValueRange("([[:digit:]]+)(-[[:digit:]]+)?");
if (std::regex_match(strCost, reValueRange))
{
std::cout << "Matched!\n";
}
else
{
std::cout << "Not matched!\n";
}
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = strName;
//filter.costMin = cost;
//filter.costMax = cost;
//filter.attackMin = attack;
//filter.attackMax = attack;
//filter.healthMin = health;
//filter.healthMax = health;
filter.mechanics = {};
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == +Rarity::INVALID ||
filter.rarity == card->GetRarity());
bool classCondition = false;
// When search mode is adding a card to a deck, the class is fixed to
// the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == +CardClass::NEUTRAL ||
filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == +CardClass::NEUTRAL ||
card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == +CardClass::INVALID ||
filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == +CardType::INVALID ||
filter.cardType == card->GetCardType());
bool raceCondition =
(filter.race == +Race::INVALID || filter.race == card->GetRace());
bool nameCondition =
(filter.name.empty() ||
card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) ||
(filter.costMin <= card->GetCost() &&
filter.costMax >= card->GetCost()));
bool attackCondition =
((filter.attackMin == -1 || filter.attackMax == -1) ||
(filter.attackMin <= card->GetAttack() &&
filter.attackMax >= card->GetAttack()));
bool healthCondition =
((filter.healthMin == -1 || filter.healthMax == -1) ||
(filter.healthMin <= card->GetHealth() &&
filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanics.size() == 0 ||
card->HasMechanics(filter.mechanics));
const bool isMatched =
AllCondIsTrue(rarityCondition, classCondition, typeCondition,
raceCondition, nameCondition, costCondition,
attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str,
std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
} |
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] =
InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum =
InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = CardClass::_from_integral(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation =
InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable =
card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable >
MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() +
numCardToAddAvailable -
MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable
<< ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex =
InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID =
deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - "
<< deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck =
static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template <std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes")
? true
: (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(
std::string commandStr) const
{
// Output command string
std::cout << commandStr;
// Input commands
std::string cmd;
std::getline(std::cin, cmd);
// Split commands by whitespace and quote
std::istringstream iss(cmd);
std::vector<std::string> cmdTokens{"Hearthstone++"};
std::string cmdToken;
while (iss >> std::quoted(cmdToken))
{
cmdTokens.push_back(cmdToken);
}
// Convert std::string to const char*
std::vector<const char*> convertedSplitCmds{};
for (const auto& token : cmdTokens)
{
convertedSplitCmds.push_back(token.c_str());
}
// Parse command
bool showHelp = false;
std::string strName, strRarity, strPlayerClass, strCardType;
std::string strRace, strMechanics, strCost, strAttack, strHealth;
bool isValid = true, isFinish = false;
// Parsing
auto parser =
clara::Help(showHelp) |
clara::Opt(strName, "name")["-n"]["--name"](
"the name of a card") |
clara::Opt(strRarity, "rarity")["-r"]["--rarity"](
"a rough measure of the quality and scarcity of a card") |
clara::Opt(strPlayerClass, "playerClass")["-c"]["--class"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strCardType, "cardType")["-t"]["--type"](
"spell cards, weapon cards, minion cards and hero cards") |
clara::Opt(strRace, "race")["-e"]["--race"](
"does not directly affect the behavior of the minion, but allows "
"it to be affected by certain type-specific effects") |
clara::Opt(strCost, "cost")["-s"]["--cost"](
"determines how much mana is required to play that card from the "
"hand or to use that hero power") |
clara::Opt(strAttack, "attack")["-a"]["--attack"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strHealth, "health")["-l"]["--health"](
"an attribute found on heroes and minions, reflecting the "
"remaining survivability of the character") |
clara::Opt(strMechanics, "mechanic")["-m"]["--mechanic"](
"describes the total effect of playing that card or special "
"effects or powers additional to the basic functions of the card") |
clara::Opt(isFinish, "isFinish")["-f"]["--finish"]("finish the search");
auto result = parser.parse(
clara::Args(convertedSplitCmds.size(), convertedSplitCmds.data()));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
isValid = false;
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
isValid = false;
}
Rarity rarity = Rarity::_from_string_nothrow(strRarity.c_str())
? Rarity::_from_string(strRarity.c_str())
: Rarity::INVALID;
CardClass playerClass =
CardClass::_from_string_nothrow(strPlayerClass.c_str())
? CardClass::_from_string(strPlayerClass.c_str())
: CardClass::INVALID;
CardType cardType = CardType::_from_string_nothrow(strCardType.c_str())
? CardType::_from_string(strCardType.c_str())
: CardType::INVALID;
Race race = Race::_from_string_nothrow(strRace.c_str())
? Race::_from_string(strRace.c_str())
: Race::INVALID;
GameTag mechanic = GameTag::_from_string_nothrow(strMechanics.c_str())
? GameTag::_from_string(strMechanics.c_str())
: GameTag::INVALID;
auto[minCost, maxCost] = ParseValueRangeFromString(strCost, isValid);
auto[minAttack, maxAttack] = ParseValueRangeFromString(strAttack, isValid);
auto[minHealth, maxHealth] = ParseValueRangeFromString(strHealth, isValid);
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = strName;
filter.costMin = minCost;
filter.costMax = maxCost;
filter.attackMin = minAttack;
filter.attackMax = maxAttack;
filter.healthMin = minHealth;
filter.healthMax = maxHealth;
filter.mechanic = mechanic;
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == +Rarity::INVALID ||
filter.rarity == card->GetRarity());
bool classCondition = false;
// When search mode is adding a card to a deck, the class is fixed to
// the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == +CardClass::NEUTRAL ||
filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == +CardClass::NEUTRAL ||
card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == +CardClass::INVALID ||
filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == +CardType::INVALID ||
filter.cardType == card->GetCardType());
bool raceCondition =
(filter.race == +Race::INVALID || filter.race == card->GetRace());
bool nameCondition =
(filter.name.empty() ||
card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) ||
(filter.costMin <= card->GetCost() &&
filter.costMax >= card->GetCost()));
bool attackCondition =
((filter.attackMin == -1 || filter.attackMax == -1) ||
(filter.attackMin <= card->GetAttack() &&
filter.attackMax >= card->GetAttack()));
bool healthCondition =
((filter.healthMin == -1 || filter.healthMax == -1) ||
(filter.healthMin <= card->GetHealth() &&
filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanic == +GameTag::INVALID ||
card->HasMechanic(filter.mechanic));
const bool isMatched =
AllCondIsTrue(rarityCondition, classCondition, typeCondition,
raceCondition, nameCondition, costCondition,
attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str,
std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
}
[ci skip] Add detail descriptions
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <regex>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] =
InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum =
InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = CardClass::_from_integral(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck =
InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation =
InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable =
card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable >
MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() +
numCardToAddAvailable -
MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable
<< ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex =
InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID =
deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - "
<< deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck =
static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template <std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes")
? true
: (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(
std::string commandStr) const
{
// Output command string
std::cout << commandStr;
// Input commands
std::string cmd;
std::getline(std::cin, cmd);
// Split commands by whitespace and quote
std::istringstream iss(cmd);
std::vector<std::string> cmdTokens{"Hearthstone++"};
std::string cmdToken;
while (iss >> std::quoted(cmdToken))
{
cmdTokens.push_back(cmdToken);
}
// Convert std::string to const char*
std::vector<const char*> convertedSplitCmds{};
for (const auto& token : cmdTokens)
{
convertedSplitCmds.push_back(token.c_str());
}
// Parse command
bool showHelp = false;
std::string strName, strRarity, strPlayerClass, strCardType;
std::string strRace, strMechanics, strCost, strAttack, strHealth;
bool isValid = true, isFinish = false;
// Parsing
auto parser =
clara::Help(showHelp) |
clara::Opt(strName, "name")["-n"]["--name"](
"the name of a card"
"(You can enclose the name with \"\", regardless of whether it "
"contains spaces.)") |
clara::Opt(strRarity, "rarity")["-r"]["--rarity"](
"a rough measure of the quality and scarcity of a card") |
clara::Opt(strPlayerClass, "playerClass")["-c"]["--class"](
"the primary determinant of a hero's powers and abilities") |
clara::Opt(strCardType, "cardType")["-t"]["--type"](
"spell cards, weapon cards, minion cards and hero cards") |
clara::Opt(strRace, "race")["-e"]["--race"](
"does not directly affect the behavior of the minion, but allows "
"it to be affected by certain type-specific effects") |
clara::Opt(strCost, "cost")["-s"]["--cost"](
"determines how much mana is required to play that card from the "
"hand or to use that hero power"
"(You can search for an exact value such as 3 or a range of values "
"like 3-4.)") |
clara::Opt(strAttack, "attack")["-a"]["--attack"](
"the primary determinant of a hero's powers and abilities"
"(You can search for an exact value such as 3 or a range of values "
"like 3-4.)") |
clara::Opt(strHealth, "health")["-l"]["--health"](
"an attribute found on heroes and minions, reflecting the "
"remaining survivability of the character"
"(You can search for an exact value such as 3 or a range of values "
"like 3-4.)") |
clara::Opt(strMechanics, "mechanic")["-m"]["--mechanic"](
"describes the total effect of playing that card or special "
"effects or powers additional to the basic functions of the card") |
clara::Opt(isFinish, "isFinish")["-f"]["--finish"]("finish the search");
auto result = parser.parse(
clara::Args(convertedSplitCmds.size(), convertedSplitCmds.data()));
if (!result)
{
std::cerr << "Error in command line: " << result.errorMessage() << '\n';
isValid = false;
}
if (showHelp)
{
std::cout << ToString(parser) << '\n';
isValid = false;
}
Rarity rarity = Rarity::_from_string_nothrow(strRarity.c_str())
? Rarity::_from_string(strRarity.c_str())
: Rarity::INVALID;
CardClass playerClass =
CardClass::_from_string_nothrow(strPlayerClass.c_str())
? CardClass::_from_string(strPlayerClass.c_str())
: CardClass::INVALID;
CardType cardType = CardType::_from_string_nothrow(strCardType.c_str())
? CardType::_from_string(strCardType.c_str())
: CardType::INVALID;
Race race = Race::_from_string_nothrow(strRace.c_str())
? Race::_from_string(strRace.c_str())
: Race::INVALID;
GameTag mechanic = GameTag::_from_string_nothrow(strMechanics.c_str())
? GameTag::_from_string(strMechanics.c_str())
: GameTag::INVALID;
auto[minCost, maxCost] = ParseValueRangeFromString(strCost, isValid);
auto[minAttack, maxAttack] = ParseValueRangeFromString(strAttack, isValid);
auto[minHealth, maxHealth] = ParseValueRangeFromString(strHealth, isValid);
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = strName;
filter.costMin = minCost;
filter.costMax = maxCost;
filter.attackMin = minAttack;
filter.attackMax = maxAttack;
filter.healthMin = minHealth;
filter.healthMax = maxHealth;
filter.mechanic = mechanic;
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == +Rarity::INVALID ||
filter.rarity == card->GetRarity());
bool classCondition = false;
// When search mode is adding a card to a deck, the class is fixed to
// the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == +CardClass::NEUTRAL ||
filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == +CardClass::NEUTRAL ||
card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == +CardClass::INVALID ||
filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == +CardType::INVALID ||
filter.cardType == card->GetCardType());
bool raceCondition =
(filter.race == +Race::INVALID || filter.race == card->GetRace());
bool nameCondition =
(filter.name.empty() ||
card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) ||
(filter.costMin <= card->GetCost() &&
filter.costMax >= card->GetCost()));
bool attackCondition =
((filter.attackMin == -1 || filter.attackMax == -1) ||
(filter.attackMin <= card->GetAttack() &&
filter.attackMax >= card->GetAttack()));
bool healthCondition =
((filter.healthMin == -1 || filter.healthMax == -1) ||
(filter.healthMin <= card->GetHealth() &&
filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanic == +GameTag::INVALID ||
card->HasMechanic(filter.mechanic));
const bool isMatched =
AllCondIsTrue(rarityCondition, classCondition, typeCondition,
raceCondition, nameCondition, costCondition,
attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str,
std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
} |
/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_host_server.cpp
* @version
* @brief
* @author duye
* @date 2014-10-13
* @note
*
* 1. 2014-10-13 duye Created this file
*
*/
#include <g_host_server.h>
Update g_host_server.cpp
/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_host_server.cpp
* @version
* @brief
* @author duye
* @date 2014-10-13
* @note
*
* 1. 2014-10-13 duye Created this file
*
*/
#include <g_host_server.h>
HostServer::HostServer() : m_serverState(G_HSERVER_INIT) {}
HostServer::~HostServer() {}
void HostServer::setState(const HostServerState& state)
{
m_state = state;
}
const HostServerState& HostServer::state() const
{
return m_state;
}
GResult HostServer::run()
{
return routine();
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2013 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Interface/Modules/Render/namespaces.h>
#include <Interface/Modules/Render/ES/SRInterface.h>
#include <Interface/Modules/Render/ES/SRCamera.h>
#include <Core/Application/Application.h>
// CPM modules.
#include <gl-platform/GLPlatform.hpp>
#include <gl-state/GLState.hpp>
#include <es-general/comp/StaticScreenDims.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/StaticOrthoCamera.hpp>
#include <es-general/comp/StaticObjRefID.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/Transform.hpp>
#include <es-render/comp/StaticGeomMan.hpp>
#include <es-render/comp/StaticIBOMan.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <es-render/comp/StaticShaderMan.hpp>
#include <es-render/util/Uniform.hpp>
#include <es-render/comp/VBO.hpp>
#include <es-render/comp/IBO.hpp>
#include <es-render/comp/Shader.hpp>
#include <es-fs/fscomp/StaticFS.hpp>
#include <es-fs/Filesystem.hpp>
#include <es-fs/FilesystemSync.hpp>
#include "CoreBootstrap.h"
#include "comp/StaticSRInterface.h"
#include "comp/RenderBasicGeom.h"
#include "systems/RenderBasicSys.h"
using namespace std::placeholders;
namespace fs = CPM_ES_FS_NS;
namespace SCIRun {
namespace Render {
//------------------------------------------------------------------------------
SRInterface::SRInterface(std::shared_ptr<Gui::GLContext> context,
const std::vector<std::string>& shaderDirs) :
mMouseMode(MOUSE_OLDSCIRUN),
mScreenWidth(640),
mScreenHeight(480),
mContext(context),
mCamera(new SRCamera(*this)) // Should come after all vars have been initialized.
{
// Create default colormaps.
generateColormaps();
// Construct ESCore. We will need to bootstrap the core. We should also
// probably add utility static classes.
setupCore();
}
//------------------------------------------------------------------------------
SRInterface::~SRInterface()
{
glDeleteTextures(1, &mRainbowCMap);
glDeleteTextures(1, &mGrayscaleCMap);
}
//------------------------------------------------------------------------------
void SRInterface::setupCore()
{
mCore.addUserSystem(getSystemName_CoreBootstrap());
// Add screen height / width static component.
{
gen::StaticScreenDims dims;
dims.width = static_cast<uint32_t>(mScreenWidth);
dims.height = static_cast<uint32_t>(mScreenHeight);
mCore.addStaticComponent(dims);
}
// Be exceptionally careful with non-serializable components. They must be
// created outside of the normal bootstrap. They cannot depend on anything
// being serialized correctly. In this circumstance, the filesystem component
// is system dependent and cannot be reliably serialized, so we add it and
// mark it as non-serializable.
{
// Generate synchronous filesystem, manually add its static component,
// then mark it as non-serializable.
std::string filesystemRoot = ""; // Should set this to the relative path containing static data.
fs::StaticFS fileSystem(
std::shared_ptr<fs::FilesystemSync>(new fs::FilesystemSync(filesystemRoot)));
mCore.addStaticComponent(fileSystem);
mCore.disableComponentSerialization<fs::StaticFS>();
}
// Add StaticSRInterface
{
StaticSRInterface iface(this);
mCore.addStaticComponent(iface);
}
/// \todo Add static mouse and keyboard inputs, if necessary.
}
//------------------------------------------------------------------------------
void SRInterface::setMouseMode(MouseMode mode)
{
mMouseMode = mode;
}
//------------------------------------------------------------------------------
SRInterface::MouseMode SRInterface::getMouseMode()
{
return mMouseMode;
}
//------------------------------------------------------------------------------
void SRInterface::eventResize(size_t width, size_t height)
{
mScreenWidth = width;
mScreenHeight = height;
mContext->makeCurrent();
GL(glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)));
// Obtain StaticScreenDims component and populate.
gen::StaticScreenDims* dims = mCore.getStaticComponent<gen::StaticScreenDims>();
if (dims)
{
dims->width = static_cast<size_t>(width);
dims->height = static_cast<size_t>(height);
}
// Setup default camera projection.
gen::StaticCamera* cam = mCore.getStaticComponent<gen::StaticCamera>();
gen::StaticOrthoCamera* orthoCam = mCore.getStaticComponent<gen::StaticOrthoCamera>();
if (cam == nullptr || orthoCam == nullptr) return;
float aspect = static_cast<float>(width) / static_cast<float>(height);
float perspFOVY = 0.59f;
float perspZNear = 1.0f;
float perspZFar = 2000.0f;
glm::mat4 proj = glm::perspective(perspFOVY, aspect, perspZNear, perspZFar);
cam->data.setProjection(proj, perspFOVY, aspect, perspZNear, perspZFar);
// Setup default ortho camera projection
float orthoZNear = -1000.0f;
float orthoZFar = 1000.0f;
glm::mat4 orthoProj =
glm::ortho(/*left*/ -1.0f, /*right*/ 1.0f,
/*bottom*/ -1.0f, /*top*/ 1.0f,
/*znear*/ orthoZNear, /*zfar*/ orthoZFar);
orthoCam->data.setOrthoProjection(orthoProj, aspect, 2.0f, 2.0f, orthoZNear, orthoZFar);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseDown(const glm::ivec2& pos, MouseButton btn)
{
mCamera->mouseDownEvent(pos, btn);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseMove(const glm::ivec2& pos, MouseButton btn)
{
mCamera->mouseMoveEvent(pos, btn);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseWheel(int32_t delta)
{
mCamera->mouseWheelEvent(delta);
}
//------------------------------------------------------------------------------
void SRInterface::doAutoView()
{
if (mSceneBBox.valid())
{
mCamera->doAutoView(mSceneBBox);
}
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseUp(const glm::ivec2& /*pos*/, MouseButton /*btn*/)
{
}
//------------------------------------------------------------------------------
uint64_t SRInterface::getEntityIDForName(const std::string& name)
{
return static_cast<uint64_t>(std::hash<std::string>()(name));
}
//------------------------------------------------------------------------------
void SRInterface::handleGeomObject(boost::shared_ptr<Core::Datatypes::GeometryObject> obj)
{
// Ensure our rendering context is current on our thread.
mContext->makeCurrent();
std::string objectName = obj->objectName;
Core::Geometry::BBox bbox; // Bounding box containing all vertex buffer objects.
// Check to see if the object already exists in our list. If so, then
// remove the object. We will re-add it.
auto foundObject = std::find_if(
mSRObjects.begin(), mSRObjects.end(),
[&objectName, this](const SRObject& obj) -> bool
{
if (obj.mName == objectName)
return true;
else
return false;
});
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
if (foundObject != mSRObjects.end())
{
// Iterate through each of the passes and remove their associated
// entity ID.
for (const auto& pass : foundObject->mPasses)
{
uint64_t entityID = getEntityIDForName(pass.passName);
mCore.removeEntity(entityID);
}
// Remove the object from the entity system.
mSRObjects.erase(foundObject);
// Run a garbage collection cycle for the VBOs and IBOs. We will likely
// be using similar VBO and IBO names.
vboMan.runGCCycle(mCore);
iboMan.runGCCycle(mCore);
}
// Add vertex buffer objects.
int nameIndex = 0;
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireVBO& vbo = *it;
// Generate vector of attributes to pass into the entity system.
std::vector<std::tuple<std::string, size_t, bool>> attributeData;
for (const auto& attribData : vbo.attributes)
{
attributeData.push_back(std::make_tuple(attribData.name, attribData.sizeInBytes, attribData.normalize));
}
GLuint vboID = vboMan.addInMemoryVBO(vbo.data->getBuffer(), vbo.data->getBufferSize(),
attributeData, vbo.name);
bbox.extend(vbo.boundingBox);
}
// Add index buffer objects.
nameIndex = 0;
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireIBO& ibo = *it;
GLenum primType = GL_UNSIGNED_SHORT;
switch (ibo.indexSize)
{
case 1: // 8-bit
primType = GL_UNSIGNED_BYTE;
break;
case 2: // 16-bit
primType = GL_UNSIGNED_SHORT;
break;
case 4: // 32-bit
primType = GL_UNSIGNED_INT;
break;
default:
primType = GL_UNSIGNED_INT;
throw std::invalid_argument("Unable to determine index buffer depth.");
break;
}
GLenum primitive = GL_TRIANGLES;
switch (ibo.prim)
{
case Core::Datatypes::GeometryObject::SpireIBO::POINTS:
primitive = GL_POINTS;
break;
case Core::Datatypes::GeometryObject::SpireIBO::LINES:
primitive = GL_LINES;
break;
case Core::Datatypes::GeometryObject::SpireIBO::TRIANGLES:
default:
primitive = GL_TRIANGLES;
break;
}
int numPrimitives = ibo.data->getBufferSize() / ibo.indexSize;
std::cout << "Num primitives: " << numPrimitives << std::endl;
iboMan.addInMemoryIBO(ibo.data->getBuffer(), ibo.data->getBufferSize(), primitive, primType,
numPrimitives, ibo.name);
}
// Add default identity transform to the object globally (instead of per-pass)
glm::mat4 xform;
mSRObjects.push_back(SRObject(objectName, xform, bbox, obj->mColorMap));
SRObject& elem = mSRObjects.back();
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
// Add passes
for (auto it = obj->mPasses.cbegin(); it != obj->mPasses.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireSubPass& pass = *it;
uint64_t entityID = getEntityIDForName(pass.passName);
addVBOToEntity(entityID, pass.vboName);
addIBOToEntity(entityID, pass.iboName);
// Load vertex and fragment shader will use an already loaded program.
//addShaderToEntity(entityID, pass.programName);
shaderMan.loadVertexAndFragmentShader(mCore, entityID, pass.programName);
// Add transformation
gen::Transform trafo;
mCore.addComponent(entityID, trafo);
// Add rendering
RenderBasicGeom geom;
mCore.addComponent(entityID, geom);
// Ensure common uniforms are covered.
ren::CommonUniforms commonUniforms;
mCore.addComponent(entityID, commonUniforms);
for (const auto& uniform : pass.mUniforms)
{
applyUniform(entityID, uniform);
}
// Compare entity and system requirements.
mCore.displayEntityVersusSystemInfo(entityID, getSystemName_RenderBasicGeom());
/// \todo Add component which will direct specific rendering subsystem.
// Add components associated with entity. We just need a base class which
// we can pass in an entity ID, then a derived class which bundles
// all associated components (including types) together. We can use
// a variadic template for this. This will allow us to place any components
// we want on the objects in question in show field. This could lead to
// much simpler customization.
// Add a pass to our local object.
elem.mPasses.push_back(pass.passName);
}
// We should perform a complete garbage collection after all of this.
// This is what gcInvalidObjects is all about.
}
//------------------------------------------------------------------------------
void SRInterface::addVBOToEntity(uint64_t entityID, const std::string& vboName)
{
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::VBO vbo;
vbo.glid = vboMan.hasVBO(vboName);
mCore.addComponent(entityID, vbo);
}
//------------------------------------------------------------------------------
void SRInterface::addIBOToEntity(uint64_t entityID, const std::string& iboName)
{
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
ren::IBO ibo;
auto iboData = iboMan.getIBOData(iboName);
ibo.glid = iboMan.hasIBO(iboName);
ibo.primType = iboData.primType;
ibo.primMode = iboData.primMode;
ibo.numPrims = iboData.numPrims;
mCore.addComponent(entityID, ibo);
}
//------------------------------------------------------------------------------
void SRInterface::addShaderToEntity(uint64_t entityID, const std::string& shaderName)
{
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
ren::Shader shader;
shader.glid = shaderMan.getIDForAsset(shaderName.c_str());
mCore.addComponent(entityID, shader);
}
//------------------------------------------------------------------------------
void SRInterface::applyUniform(uint64_t entityID, const Core::Datatypes::GeometryObject::SpireSubPass::Uniform& uniform)
{
switch (uniform.type)
{
case Core::Datatypes::GeometryObject::SpireSubPass::Uniform::UNIFORM_SCALAR:
ren::addGLUniform(mCore, entityID, uniform.name.c_str(), static_cast<float>(uniform.data.x));
break;
case Core::Datatypes::GeometryObject::SpireSubPass::Uniform::UNIFORM_VEC4:
ren::addGLUniform(mCore, entityID, uniform.name.c_str(), uniform.data);
break;
}
}
//------------------------------------------------------------------------------
void SRInterface::removeAllGeomObjects()
{
mContext->makeCurrent();
/// \todo Use function to clear out all non-kernel components.
/// We want to keep the systems in place, however.
}
//------------------------------------------------------------------------------
void SRInterface::gcInvalidObjects(const std::vector<std::string>& validObjects)
{
/// \todo Run an entity system GC cycle to get rid of unused resources (VBOs
/// and IBOs). We should do this during the GC cycle.
}
//------------------------------------------------------------------------------
void SRInterface::doFrame(double currentTime, double constantDeltaTime)
{
/// \todo Only render a frame if something has changed (new or deleted
/// objects, or the view point has changed).
mContext->makeCurrent();
mSceneBBox.reset();
updateCamera();
mCore.execute(currentTime, constantDeltaTime);
// Do not even attempt to render if the framebuffer is not complete.
// This can happen when the rendering window is hidden (in SCIRun5 for
// example);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
{
renderCoordinateAxes();
}
// Set directional light source (in world space).
// glm::vec3 viewDir = viewToWorld[2].xyz();
// viewDir = -viewDir; // Cameras look down -Z.
//mSpire->addGlobalUniform("uLightDirWorld", viewDir);
}
//------------------------------------------------------------------------------
void SRInterface::updateCamera()
{
// Update the static camera with the appropriate world to view transform.
mCamera->applyTransform();
glm::mat4 viewToWorld = mCamera->getViewToWorld();
gen::StaticCamera* camera = mCore.getStaticComponent<gen::StaticCamera>();
if (camera)
{
camera->data.setView(viewToWorld);
}
}
//------------------------------------------------------------------------------
void SRInterface::renderCoordinateAxes()
{
// Only execute if static rendering resources are available. All of these
// resource checks wouldn't be necessary if we were operating in the perview
// of the entity system.
if (mCore.getStaticComponent<ren::StaticVBOMan>() == nullptr) return;
// This rendering algorithm is fairly inefficient. Use the entity component
// system to optimize the rendering of a large amount of objects.
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
GLuint arrowVBO = vboMan.hasVBO("Assets/arrow.geom");
GLuint arrowIBO = iboMan.hasIBO("Assets/arrow.geom");
GLuint shader = shaderMan.getIDForAsset("Shaders/DirPhong");
// Bail if assets have not been loaded yet (asynchronous loading may take a
// few frames).
if (arrowVBO == 0 || arrowIBO == 0 || shader == 0) { return; }
const ren::IBOMan::IBOData* iboData;
try
{
iboData = &iboMan.getIBOData("Assets/arrow.geom");
}
catch (...)
{
// Return if IBO data not available.
return;
}
// Ensure shader attributes are setup appropriately.
mArrowAttribs.setup(arrowVBO, shader, vboMan);
glm::mat4 trafo;
GL(glUseProgram(shader));
GL(glBindBuffer(GL_ARRAY_BUFFER, arrowVBO));
GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, arrowIBO));
// Note that we can pull aspect ratio from the screen dimensions static
// variable.
gen::StaticScreenDims* dims = mCore.getStaticComponent<gen::StaticScreenDims>();
float aspect = static_cast<float>(dims->width) / static_cast<float>(dims->height);
glm::mat4 projection = glm::perspective(0.59f, aspect, 1.0f, 2000.0f);
// Build world transform for all axes. Rotates about uninverted camera's
// view, then translates to a specified corner on the screen.
glm::mat4 axesRot = mCamera->getWorldToView();
axesRot[3][0] = 0.0f;
axesRot[3][1] = 0.0f;
axesRot[3][2] = 0.0f;
glm::mat4 invCamTrans = glm::translate(glm::mat4(1.0f), glm::vec3(0.375f * aspect, 0.37f, -1.5f));
glm::mat4 axesScale = glm::scale(glm::mat4(1.0f), glm::vec3(0.8f));
glm::mat4 axesTransform = axesScale * axesRot;
GLint locCamViewVec = glGetUniformLocation(shader, "uCamViewVec");
GLint locLightDirWorld = glGetUniformLocation(shader, "uLightDirWorld");
GLint locAmbientColor = glGetUniformLocation(shader, "uAmbientColor");
GLint locDiffuseColor = glGetUniformLocation(shader, "uDiffuseColor");
GLint locSpecularColor = glGetUniformLocation(shader, "uSpecularColor");
GLint locSpecularPower = glGetUniformLocation(shader, "uSpecularPower");
GLint locProjIVObject = glGetUniformLocation(shader, "uProjIVObject");
GLint locObject = glGetUniformLocation(shader, "uObject");
GL(glUniform3f(locCamViewVec, 0.0f, 0.0f, -1.0f));
GL(glUniform3f(locLightDirWorld, 0.0f, 0.0f, -1.0f));
// Build projection for the axes to use on the screen. The arrors will not
// use the camera, but will use the camera's transformation matrix.
mArrowAttribs.bind();
// X Axis
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>() / 2.0f, glm::vec3(0.0, 1.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.5f, 0.01f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 1.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// X Axis (dark)
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() / 2.0f, glm::vec3(0.0, 1.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.1f, 0.01f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.25f, 0.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Y Axis
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() / 2.0f, glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.5f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 1.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Y Axis (dark)
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>() / 2.0f, glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.1f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.25f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Z Axis
{
// No rotation at all
glm::mat4 finalTrafo = axesTransform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.01f, 0.5f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.0f, 1.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Z Axis (dark)
{
// No rotation at all
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>(), glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.01f, 0.1f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.0f, 0.25f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
mArrowAttribs.unbind();
}
// Manually update the StaticCamera.
float rainbowRaw[] =
{
0.0000, 0.0000, 1.0000, 1.0,
0.0000, 0.0216, 1.0000, 1.0,
0.0000, 0.0432, 1.0000, 1.0,
0.0000, 0.0648, 1.0000, 1.0,
0.0000, 0.0864, 1.0000, 1.0,
0.0000, 0.1080, 1.0000, 1.0,
0.0000, 0.1296, 1.0000, 1.0,
0.0000, 0.1511, 1.0000, 1.0,
0.0000, 0.1727, 1.0000, 1.0,
0.0000, 0.1943, 1.0000, 1.0,
0.0002, 0.2104, 1.0000, 1.0,
0.0006, 0.2220, 1.0000, 1.0,
0.0011, 0.2336, 1.0000, 1.0,
0.0015, 0.2453, 1.0000, 1.0,
0.0019, 0.2569, 1.0000, 1.0,
0.0023, 0.2685, 1.0000, 1.0,
0.0027, 0.2801, 1.0000, 1.0,
0.0031, 0.2918, 1.0000, 1.0,
0.0036, 0.3034, 1.0000, 1.0,
0.0040, 0.3149, 1.0000, 1.0,
0.0048, 0.3253, 1.0000, 1.0,
0.0057, 0.3356, 1.0000, 1.0,
0.0065, 0.3460, 1.0000, 1.0,
0.0073, 0.3564, 1.0000, 1.0,
0.0082, 0.3668, 1.0000, 1.0,
0.0090, 0.3772, 1.0000, 1.0,
0.0098, 0.3875, 1.0000, 1.0,
0.0107, 0.3979, 1.0000, 1.0,
0.0115, 0.4083, 1.0000, 1.0,
0.0123, 0.4192, 1.0000, 1.0,
0.0131, 0.4304, 1.0000, 1.0,
0.0140, 0.4417, 1.0000, 1.0,
0.0148, 0.4529, 1.0000, 1.0,
0.0156, 0.4641, 1.0000, 1.0,
0.0165, 0.4753, 1.0000, 1.0,
0.0173, 0.4865, 1.0000, 1.0,
0.0181, 0.4977, 1.0000, 1.0,
0.0190, 0.5089, 1.0000, 1.0,
0.0200, 0.5200, 0.9989, 1.0,
0.0216, 0.5303, 0.9939, 1.0,
0.0233, 0.5407, 0.9889, 1.0,
0.0250, 0.5511, 0.9839, 1.0,
0.0266, 0.5615, 0.9790, 1.0,
0.0283, 0.5719, 0.9740, 1.0,
0.0299, 0.5822, 0.9690, 1.0,
0.0316, 0.5926, 0.9640, 1.0,
0.0333, 0.6030, 0.9590, 1.0,
0.0349, 0.6134, 0.9540, 1.0,
0.0359, 0.6221, 0.9433, 1.0,
0.0368, 0.6304, 0.9308, 1.0,
0.0376, 0.6388, 0.9183, 1.0,
0.0384, 0.6471, 0.9059, 1.0,
0.0393, 0.6554, 0.8934, 1.0,
0.0401, 0.6637, 0.8810, 1.0,
0.0409, 0.6720, 0.8685, 1.0,
0.0418, 0.6803, 0.8561, 1.0,
0.0426, 0.6886, 0.8436, 1.0,
0.0437, 0.6963, 0.8310, 1.0,
0.0454, 0.7030, 0.8181, 1.0,
0.0470, 0.7096, 0.8053, 1.0,
0.0487, 0.7163, 0.7924, 1.0,
0.0503, 0.7229, 0.7795, 1.0,
0.0520, 0.7296, 0.7666, 1.0,
0.0537, 0.7362, 0.7538, 1.0,
0.0553, 0.7428, 0.7409, 1.0,
0.0570, 0.7495, 0.7280, 1.0,
0.0586, 0.7561, 0.7152, 1.0,
0.0610, 0.7631, 0.7027, 1.0,
0.0635, 0.7702, 0.6902, 1.0,
0.0660, 0.7773, 0.6777, 1.0,
0.0685, 0.7843, 0.6653, 1.0,
0.0710, 0.7914, 0.6528, 1.0,
0.0735, 0.7984, 0.6404, 1.0,
0.0760, 0.8055, 0.6279, 1.0,
0.0785, 0.8125, 0.6155, 1.0,
0.0810, 0.8196, 0.6030, 1.0,
0.0840, 0.8263, 0.5913, 1.0,
0.0878, 0.8325, 0.5805, 1.0,
0.0915, 0.8388, 0.5697, 1.0,
0.0952, 0.8450, 0.5589, 1.0,
0.0990, 0.8512, 0.5481, 1.0,
0.1027, 0.8574, 0.5373, 1.0,
0.1064, 0.8637, 0.5265, 1.0,
0.1102, 0.8699, 0.5157, 1.0,
0.1139, 0.8761, 0.5049, 1.0,
0.1176, 0.8824, 0.4941, 1.0,
0.1226, 0.8873, 0.4842, 1.0,
0.1276, 0.8923, 0.4742, 1.0,
0.1326, 0.8973, 0.4642, 1.0,
0.1376, 0.9023, 0.4543, 1.0,
0.1426, 0.9073, 0.4443, 1.0,
0.1475, 0.9122, 0.4343, 1.0,
0.1525, 0.9172, 0.4244, 1.0,
0.1575, 0.9222, 0.4144, 1.0,
0.1625, 0.9272, 0.4044, 1.0,
0.1689, 0.9319, 0.3954, 1.0,
0.1763, 0.9365, 0.3871, 1.0,
0.1838, 0.9411, 0.3788, 1.0,
0.1913, 0.9457, 0.3705, 1.0,
0.1988, 0.9502, 0.3622, 1.0,
0.2062, 0.9548, 0.3539, 1.0,
0.2137, 0.9594, 0.3456, 1.0,
0.2212, 0.9639, 0.3373, 1.0,
0.2287, 0.9685, 0.3290, 1.0,
0.2365, 0.9729, 0.3206, 1.0,
0.2478, 0.9758, 0.3123, 1.0,
0.2590, 0.9787, 0.3040, 1.0,
0.2702, 0.9816, 0.2957, 1.0,
0.2814, 0.9845, 0.2874, 1.0,
0.2926, 0.9874, 0.2791, 1.0,
0.3038, 0.9903, 0.2708, 1.0,
0.3150, 0.9932, 0.2625, 1.0,
0.3262, 0.9961, 0.2542, 1.0,
0.3374, 0.9990, 0.2459, 1.0,
0.3492, 1.0000, 0.2395, 1.0,
0.3612, 1.0000, 0.2341, 1.0,
0.3733, 1.0000, 0.2287, 1.0,
0.3853, 1.0000, 0.2233, 1.0,
0.3974, 1.0000, 0.2179, 1.0,
0.4094, 1.0000, 0.2125, 1.0,
0.4215, 1.0000, 0.2072, 1.0,
0.4335, 1.0000, 0.2018, 1.0,
0.4455, 1.0000, 0.1964, 1.0,
0.4579, 0.9997, 0.1910, 1.0,
0.4711, 0.9985, 0.1861, 1.0,
0.4844, 0.9972, 0.1811, 1.0,
0.4977, 0.9960, 0.1761, 1.0,
0.5110, 0.9947, 0.1711, 1.0,
0.5243, 0.9935, 0.1661, 1.0,
0.5376, 0.9922, 0.1612, 1.0,
0.5509, 0.9910, 0.1562, 1.0,
0.5642, 0.9898, 0.1512, 1.0,
0.5774, 0.9885, 0.1462, 1.0,
0.5901, 0.9853, 0.1419, 1.0,
0.6025, 0.9816, 0.1377, 1.0,
0.6150, 0.9779, 0.1336, 1.0,
0.6275, 0.9741, 0.1294, 1.0,
0.6399, 0.9704, 0.1253, 1.0,
0.6524, 0.9666, 0.1211, 1.0,
0.6648, 0.9629, 0.1170, 1.0,
0.6773, 0.9592, 0.1128, 1.0,
0.6897, 0.9554, 0.1087, 1.0,
0.7012, 0.9516, 0.1048, 1.0,
0.7108, 0.9474, 0.1015, 1.0,
0.7203, 0.9433, 0.0981, 1.0,
0.7299, 0.9391, 0.0948, 1.0,
0.7394, 0.9349, 0.0915, 1.0,
0.7490, 0.9308, 0.0882, 1.0,
0.7585, 0.9266, 0.0848, 1.0,
0.7681, 0.9225, 0.0815, 1.0,
0.7776, 0.9183, 0.0782, 1.0,
0.7872, 0.9142, 0.0749, 1.0,
0.7952, 0.9089, 0.0727, 1.0,
0.8031, 0.9035, 0.0706, 1.0,
0.8110, 0.8981, 0.0685, 1.0,
0.8189, 0.8927, 0.0664, 1.0,
0.8268, 0.8873, 0.0644, 1.0,
0.8347, 0.8819, 0.0623, 1.0,
0.8426, 0.8765, 0.0602, 1.0,
0.8505, 0.8711, 0.0581, 1.0,
0.8584, 0.8657, 0.0561, 1.0,
0.8657, 0.8602, 0.0542, 1.0,
0.8723, 0.8543, 0.0525, 1.0,
0.8790, 0.8485, 0.0508, 1.0,
0.8856, 0.8427, 0.0492, 1.0,
0.8923, 0.8369, 0.0475, 1.0,
0.8989, 0.8311, 0.0459, 1.0,
0.9056, 0.8253, 0.0442, 1.0,
0.9122, 0.8195, 0.0425, 1.0,
0.9188, 0.8137, 0.0409, 1.0,
0.9255, 0.8078, 0.0392, 1.0,
0.9301, 0.7991, 0.0384, 1.0,
0.9346, 0.7904, 0.0376, 1.0,
0.9392, 0.7817, 0.0367, 1.0,
0.9438, 0.7730, 0.0359, 1.0,
0.9483, 0.7642, 0.0351, 1.0,
0.9529, 0.7555, 0.0342, 1.0,
0.9575, 0.7468, 0.0334, 1.0,
0.9620, 0.7381, 0.0326, 1.0,
0.9666, 0.7294, 0.0317, 1.0,
0.9700, 0.7223, 0.0307, 1.0,
0.9725, 0.7164, 0.0294, 1.0,
0.9750, 0.7106, 0.0282, 1.0,
0.9775, 0.7048, 0.0269, 1.0,
0.9800, 0.6990, 0.0257, 1.0,
0.9825, 0.6932, 0.0245, 1.0,
0.9850, 0.6874, 0.0232, 1.0,
0.9875, 0.6816, 0.0220, 1.0,
0.9899, 0.6758, 0.0207, 1.0,
0.9922, 0.6697, 0.0195, 1.0,
0.9931, 0.6614, 0.0187, 1.0,
0.9939, 0.6531, 0.0179, 1.0,
0.9947, 0.6448, 0.0170, 1.0,
0.9956, 0.6364, 0.0162, 1.0,
0.9964, 0.6281, 0.0154, 1.0,
0.9972, 0.6198, 0.0145, 1.0,
0.9981, 0.6115, 0.0137, 1.0,
0.9989, 0.6032, 0.0129, 1.0,
0.9997, 0.5949, 0.0120, 1.0,
1.0000, 0.5863, 0.0115, 1.0,
1.0000, 0.5776, 0.0111, 1.0,
1.0000, 0.5689, 0.0107, 1.0,
1.0000, 0.5602, 0.0102, 1.0,
1.0000, 0.5515, 0.0098, 1.0,
1.0000, 0.5427, 0.0094, 1.0,
1.0000, 0.5340, 0.0090, 1.0,
1.0000, 0.5253, 0.0086, 1.0,
1.0000, 0.5166, 0.0082, 1.0,
1.0000, 0.5081, 0.0078, 1.0,
1.0000, 0.5007, 0.0073, 1.0,
1.0000, 0.4932, 0.0069, 1.0,
1.0000, 0.4857, 0.0065, 1.0,
1.0000, 0.4782, 0.0061, 1.0,
1.0000, 0.4708, 0.0057, 1.0,
1.0000, 0.4633, 0.0053, 1.0,
1.0000, 0.4558, 0.0048, 1.0,
1.0000, 0.4484, 0.0044, 1.0,
1.0000, 0.4409, 0.0040, 1.0,
1.0000, 0.4334, 0.0036, 1.0,
1.0000, 0.4259, 0.0032, 1.0,
1.0000, 0.4185, 0.0028, 1.0,
1.0000, 0.4110, 0.0024, 1.0,
1.0000, 0.4035, 0.0019, 1.0,
1.0000, 0.3960, 0.0015, 1.0,
1.0000, 0.3886, 0.0011, 1.0,
1.0000, 0.3811, 0.0007, 1.0,
1.0000, 0.3736, 0.0003, 1.0,
1.0000, 0.3661, 0.0000, 1.0,
1.0000, 0.3587, 0.0000, 1.0,
1.0000, 0.3512, 0.0000, 1.0,
1.0000, 0.3437, 0.0000, 1.0,
1.0000, 0.3362, 0.0000, 1.0,
1.0000, 0.3288, 0.0000, 1.0,
1.0000, 0.3213, 0.0000, 1.0,
1.0000, 0.3138, 0.0000, 1.0,
1.0000, 0.3063, 0.0000, 1.0,
1.0000, 0.2989, 0.0000, 1.0,
1.0000, 0.2903, 0.0000, 1.0,
1.0000, 0.2816, 0.0000, 1.0,
1.0000, 0.2728, 0.0000, 1.0,
1.0000, 0.2641, 0.0000, 1.0,
1.0000, 0.2554, 0.0000, 1.0,
1.0000, 0.2467, 0.0000, 1.0,
1.0000, 0.2380, 0.0000, 1.0,
1.0000, 0.2293, 0.0000, 1.0,
1.0000, 0.2205, 0.0000, 1.0,
1.0000, 0.2055, 0.0000, 1.0,
1.0000, 0.1827, 0.0000, 1.0,
1.0000, 0.1599, 0.0000, 1.0,
1.0000, 0.1370, 0.0000, 1.0,
1.0000, 0.1142, 0.0000, 1.0,
1.0000, 0.0913, 0.0000, 1.0,
1.0000, 0.0685, 0.0000, 1.0,
1.0000, 0.0457, 0.0000, 1.0,
1.0000, 0.0228, 0.0000, 1.0,
1.0000, 0.0000, 0.0000, 1.0
};
// Create default colormaps.
void SRInterface::generateColormaps()
{
size_t rainbowArraySize = sizeof(rainbowRaw) / sizeof(*rainbowRaw);
std::vector<uint8_t> rainbow;
rainbow.reserve(rainbowArraySize);
for (int i = 0; i < rainbowArraySize; i++)
{
rainbow.push_back(static_cast<uint8_t>(rainbowRaw[i] * 255.0f));
}
// Build rainbow texture (eyetracking version -- will need to change).
GL(glGenTextures(1, &mRainbowCMap));
GL(glBindTexture(GL_TEXTURE_1D, mRainbowCMap));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glTexImage1D(GL_TEXTURE_1D, 0,
GL_RGBA8,
static_cast<GLsizei>(rainbow.size() / 4), 0,
GL_RGBA,
GL_UNSIGNED_BYTE, &rainbow[0]));
// build grayscale texture.
const int grayscaleSize = 255 * 4;
std::vector<uint8_t> grayscale;
grayscale.reserve(grayscaleSize);
for (int i = 0; i < 255; i++)
{
grayscale.push_back(i);
grayscale.push_back(i);
grayscale.push_back(i);
grayscale.push_back(255);
}
// Grayscale texture.
GL(glGenTextures(1, &mGrayscaleCMap));
GL(glBindTexture(GL_TEXTURE_1D, mGrayscaleCMap));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glTexImage1D(GL_TEXTURE_1D, 0,
GL_RGBA8,
static_cast<GLsizei>(grayscale.size() / 4), 0,
GL_RGBA,
GL_UNSIGNED_BYTE, &grayscale[0]));
}
} // namespace Render
} // namespace SCIRun
Attempt at quieting travis errors.
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2013 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
// Needed for OpenGL include files on Travis:
#include <QtOpenGL/QGLWidget>
#include <Interface/Modules/Render/namespaces.h>
#include <Interface/Modules/Render/ES/SRInterface.h>
#include <Interface/Modules/Render/ES/SRCamera.h>
#include <Core/Application/Application.h>
// CPM modules.
#include <gl-platform/GLPlatform.hpp>
#include <gl-state/GLState.hpp>
#include <es-general/comp/StaticScreenDims.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/StaticOrthoCamera.hpp>
#include <es-general/comp/StaticObjRefID.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/Transform.hpp>
#include <es-render/comp/StaticGeomMan.hpp>
#include <es-render/comp/StaticIBOMan.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <es-render/comp/StaticShaderMan.hpp>
#include <es-render/util/Uniform.hpp>
#include <es-render/comp/VBO.hpp>
#include <es-render/comp/IBO.hpp>
#include <es-render/comp/Shader.hpp>
#include <es-fs/fscomp/StaticFS.hpp>
#include <es-fs/Filesystem.hpp>
#include <es-fs/FilesystemSync.hpp>
#include "CoreBootstrap.h"
#include "comp/StaticSRInterface.h"
#include "comp/RenderBasicGeom.h"
#include "systems/RenderBasicSys.h"
using namespace std::placeholders;
namespace fs = CPM_ES_FS_NS;
namespace SCIRun {
namespace Render {
//------------------------------------------------------------------------------
SRInterface::SRInterface(std::shared_ptr<Gui::GLContext> context,
const std::vector<std::string>& shaderDirs) :
mMouseMode(MOUSE_OLDSCIRUN),
mScreenWidth(640),
mScreenHeight(480),
mContext(context),
mCamera(new SRCamera(*this)) // Should come after all vars have been initialized.
{
// Create default colormaps.
generateColormaps();
// Construct ESCore. We will need to bootstrap the core. We should also
// probably add utility static classes.
setupCore();
}
//------------------------------------------------------------------------------
SRInterface::~SRInterface()
{
glDeleteTextures(1, &mRainbowCMap);
glDeleteTextures(1, &mGrayscaleCMap);
}
//------------------------------------------------------------------------------
void SRInterface::setupCore()
{
mCore.addUserSystem(getSystemName_CoreBootstrap());
// Add screen height / width static component.
{
gen::StaticScreenDims dims;
dims.width = static_cast<uint32_t>(mScreenWidth);
dims.height = static_cast<uint32_t>(mScreenHeight);
mCore.addStaticComponent(dims);
}
// Be exceptionally careful with non-serializable components. They must be
// created outside of the normal bootstrap. They cannot depend on anything
// being serialized correctly. In this circumstance, the filesystem component
// is system dependent and cannot be reliably serialized, so we add it and
// mark it as non-serializable.
{
// Generate synchronous filesystem, manually add its static component,
// then mark it as non-serializable.
std::string filesystemRoot = ""; // Should set this to the relative path containing static data.
fs::StaticFS fileSystem(
std::shared_ptr<fs::FilesystemSync>(new fs::FilesystemSync(filesystemRoot)));
mCore.addStaticComponent(fileSystem);
mCore.disableComponentSerialization<fs::StaticFS>();
}
// Add StaticSRInterface
{
StaticSRInterface iface(this);
mCore.addStaticComponent(iface);
}
/// \todo Add static mouse and keyboard inputs, if necessary.
}
//------------------------------------------------------------------------------
void SRInterface::setMouseMode(MouseMode mode)
{
mMouseMode = mode;
}
//------------------------------------------------------------------------------
SRInterface::MouseMode SRInterface::getMouseMode()
{
return mMouseMode;
}
//------------------------------------------------------------------------------
void SRInterface::eventResize(size_t width, size_t height)
{
mScreenWidth = width;
mScreenHeight = height;
mContext->makeCurrent();
GL(glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)));
// Obtain StaticScreenDims component and populate.
gen::StaticScreenDims* dims = mCore.getStaticComponent<gen::StaticScreenDims>();
if (dims)
{
dims->width = static_cast<size_t>(width);
dims->height = static_cast<size_t>(height);
}
// Setup default camera projection.
gen::StaticCamera* cam = mCore.getStaticComponent<gen::StaticCamera>();
gen::StaticOrthoCamera* orthoCam = mCore.getStaticComponent<gen::StaticOrthoCamera>();
if (cam == nullptr || orthoCam == nullptr) return;
float aspect = static_cast<float>(width) / static_cast<float>(height);
float perspFOVY = 0.59f;
float perspZNear = 1.0f;
float perspZFar = 2000.0f;
glm::mat4 proj = glm::perspective(perspFOVY, aspect, perspZNear, perspZFar);
cam->data.setProjection(proj, perspFOVY, aspect, perspZNear, perspZFar);
// Setup default ortho camera projection
float orthoZNear = -1000.0f;
float orthoZFar = 1000.0f;
glm::mat4 orthoProj =
glm::ortho(/*left*/ -1.0f, /*right*/ 1.0f,
/*bottom*/ -1.0f, /*top*/ 1.0f,
/*znear*/ orthoZNear, /*zfar*/ orthoZFar);
orthoCam->data.setOrthoProjection(orthoProj, aspect, 2.0f, 2.0f, orthoZNear, orthoZFar);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseDown(const glm::ivec2& pos, MouseButton btn)
{
mCamera->mouseDownEvent(pos, btn);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseMove(const glm::ivec2& pos, MouseButton btn)
{
mCamera->mouseMoveEvent(pos, btn);
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseWheel(int32_t delta)
{
mCamera->mouseWheelEvent(delta);
}
//------------------------------------------------------------------------------
void SRInterface::doAutoView()
{
if (mSceneBBox.valid())
{
mCamera->doAutoView(mSceneBBox);
}
}
//------------------------------------------------------------------------------
void SRInterface::inputMouseUp(const glm::ivec2& /*pos*/, MouseButton /*btn*/)
{
}
//------------------------------------------------------------------------------
uint64_t SRInterface::getEntityIDForName(const std::string& name)
{
return static_cast<uint64_t>(std::hash<std::string>()(name));
}
//------------------------------------------------------------------------------
void SRInterface::handleGeomObject(boost::shared_ptr<Core::Datatypes::GeometryObject> obj)
{
// Ensure our rendering context is current on our thread.
mContext->makeCurrent();
std::string objectName = obj->objectName;
Core::Geometry::BBox bbox; // Bounding box containing all vertex buffer objects.
// Check to see if the object already exists in our list. If so, then
// remove the object. We will re-add it.
auto foundObject = std::find_if(
mSRObjects.begin(), mSRObjects.end(),
[&objectName, this](const SRObject& obj) -> bool
{
if (obj.mName == objectName)
return true;
else
return false;
});
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
if (foundObject != mSRObjects.end())
{
// Iterate through each of the passes and remove their associated
// entity ID.
for (const auto& pass : foundObject->mPasses)
{
uint64_t entityID = getEntityIDForName(pass.passName);
mCore.removeEntity(entityID);
}
// Remove the object from the entity system.
mSRObjects.erase(foundObject);
// Run a garbage collection cycle for the VBOs and IBOs. We will likely
// be using similar VBO and IBO names.
vboMan.runGCCycle(mCore);
iboMan.runGCCycle(mCore);
}
// Add vertex buffer objects.
int nameIndex = 0;
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireVBO& vbo = *it;
// Generate vector of attributes to pass into the entity system.
std::vector<std::tuple<std::string, size_t, bool>> attributeData;
for (const auto& attribData : vbo.attributes)
{
attributeData.push_back(std::make_tuple(attribData.name, attribData.sizeInBytes, attribData.normalize));
}
GLuint vboID = vboMan.addInMemoryVBO(vbo.data->getBuffer(), vbo.data->getBufferSize(),
attributeData, vbo.name);
bbox.extend(vbo.boundingBox);
}
// Add index buffer objects.
nameIndex = 0;
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireIBO& ibo = *it;
GLenum primType = GL_UNSIGNED_SHORT;
switch (ibo.indexSize)
{
case 1: // 8-bit
primType = GL_UNSIGNED_BYTE;
break;
case 2: // 16-bit
primType = GL_UNSIGNED_SHORT;
break;
case 4: // 32-bit
primType = GL_UNSIGNED_INT;
break;
default:
primType = GL_UNSIGNED_INT;
throw std::invalid_argument("Unable to determine index buffer depth.");
break;
}
GLenum primitive = GL_TRIANGLES;
switch (ibo.prim)
{
case Core::Datatypes::GeometryObject::SpireIBO::POINTS:
primitive = GL_POINTS;
break;
case Core::Datatypes::GeometryObject::SpireIBO::LINES:
primitive = GL_LINES;
break;
case Core::Datatypes::GeometryObject::SpireIBO::TRIANGLES:
default:
primitive = GL_TRIANGLES;
break;
}
int numPrimitives = ibo.data->getBufferSize() / ibo.indexSize;
std::cout << "Num primitives: " << numPrimitives << std::endl;
iboMan.addInMemoryIBO(ibo.data->getBuffer(), ibo.data->getBufferSize(), primitive, primType,
numPrimitives, ibo.name);
}
// Add default identity transform to the object globally (instead of per-pass)
glm::mat4 xform;
mSRObjects.push_back(SRObject(objectName, xform, bbox, obj->mColorMap));
SRObject& elem = mSRObjects.back();
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
// Add passes
for (auto it = obj->mPasses.cbegin(); it != obj->mPasses.cend(); ++it)
{
const Core::Datatypes::GeometryObject::SpireSubPass& pass = *it;
uint64_t entityID = getEntityIDForName(pass.passName);
addVBOToEntity(entityID, pass.vboName);
addIBOToEntity(entityID, pass.iboName);
// Load vertex and fragment shader will use an already loaded program.
//addShaderToEntity(entityID, pass.programName);
shaderMan.loadVertexAndFragmentShader(mCore, entityID, pass.programName);
// Add transformation
gen::Transform trafo;
mCore.addComponent(entityID, trafo);
// Add rendering
RenderBasicGeom geom;
mCore.addComponent(entityID, geom);
// Ensure common uniforms are covered.
ren::CommonUniforms commonUniforms;
mCore.addComponent(entityID, commonUniforms);
for (const auto& uniform : pass.mUniforms)
{
applyUniform(entityID, uniform);
}
// Compare entity and system requirements.
mCore.displayEntityVersusSystemInfo(entityID, getSystemName_RenderBasicGeom());
/// \todo Add component which will direct specific rendering subsystem.
// Add components associated with entity. We just need a base class which
// we can pass in an entity ID, then a derived class which bundles
// all associated components (including types) together. We can use
// a variadic template for this. This will allow us to place any components
// we want on the objects in question in show field. This could lead to
// much simpler customization.
// Add a pass to our local object.
elem.mPasses.push_back(pass.passName);
}
// We should perform a complete garbage collection after all of this.
// This is what gcInvalidObjects is all about.
}
//------------------------------------------------------------------------------
void SRInterface::addVBOToEntity(uint64_t entityID, const std::string& vboName)
{
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::VBO vbo;
vbo.glid = vboMan.hasVBO(vboName);
mCore.addComponent(entityID, vbo);
}
//------------------------------------------------------------------------------
void SRInterface::addIBOToEntity(uint64_t entityID, const std::string& iboName)
{
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
ren::IBO ibo;
auto iboData = iboMan.getIBOData(iboName);
ibo.glid = iboMan.hasIBO(iboName);
ibo.primType = iboData.primType;
ibo.primMode = iboData.primMode;
ibo.numPrims = iboData.numPrims;
mCore.addComponent(entityID, ibo);
}
//------------------------------------------------------------------------------
void SRInterface::addShaderToEntity(uint64_t entityID, const std::string& shaderName)
{
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
ren::Shader shader;
shader.glid = shaderMan.getIDForAsset(shaderName.c_str());
mCore.addComponent(entityID, shader);
}
//------------------------------------------------------------------------------
void SRInterface::applyUniform(uint64_t entityID, const Core::Datatypes::GeometryObject::SpireSubPass::Uniform& uniform)
{
switch (uniform.type)
{
case Core::Datatypes::GeometryObject::SpireSubPass::Uniform::UNIFORM_SCALAR:
ren::addGLUniform(mCore, entityID, uniform.name.c_str(), static_cast<float>(uniform.data.x));
break;
case Core::Datatypes::GeometryObject::SpireSubPass::Uniform::UNIFORM_VEC4:
ren::addGLUniform(mCore, entityID, uniform.name.c_str(), uniform.data);
break;
}
}
//------------------------------------------------------------------------------
void SRInterface::removeAllGeomObjects()
{
mContext->makeCurrent();
/// \todo Use function to clear out all non-kernel components.
/// We want to keep the systems in place, however.
}
//------------------------------------------------------------------------------
void SRInterface::gcInvalidObjects(const std::vector<std::string>& validObjects)
{
/// \todo Run an entity system GC cycle to get rid of unused resources (VBOs
/// and IBOs). We should do this during the GC cycle.
}
//------------------------------------------------------------------------------
void SRInterface::doFrame(double currentTime, double constantDeltaTime)
{
/// \todo Only render a frame if something has changed (new or deleted
/// objects, or the view point has changed).
mContext->makeCurrent();
mSceneBBox.reset();
updateCamera();
mCore.execute(currentTime, constantDeltaTime);
// Do not even attempt to render if the framebuffer is not complete.
// This can happen when the rendering window is hidden (in SCIRun5 for
// example);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
{
renderCoordinateAxes();
}
// Set directional light source (in world space).
// glm::vec3 viewDir = viewToWorld[2].xyz();
// viewDir = -viewDir; // Cameras look down -Z.
//mSpire->addGlobalUniform("uLightDirWorld", viewDir);
}
//------------------------------------------------------------------------------
void SRInterface::updateCamera()
{
// Update the static camera with the appropriate world to view transform.
mCamera->applyTransform();
glm::mat4 viewToWorld = mCamera->getViewToWorld();
gen::StaticCamera* camera = mCore.getStaticComponent<gen::StaticCamera>();
if (camera)
{
camera->data.setView(viewToWorld);
}
}
//------------------------------------------------------------------------------
void SRInterface::renderCoordinateAxes()
{
// Only execute if static rendering resources are available. All of these
// resource checks wouldn't be necessary if we were operating in the perview
// of the entity system.
if (mCore.getStaticComponent<ren::StaticVBOMan>() == nullptr) return;
// This rendering algorithm is fairly inefficient. Use the entity component
// system to optimize the rendering of a large amount of objects.
ren::VBOMan& vboMan = *mCore.getStaticComponent<ren::StaticVBOMan>()->instance;
ren::IBOMan& iboMan = *mCore.getStaticComponent<ren::StaticIBOMan>()->instance;
ren::ShaderMan& shaderMan = *mCore.getStaticComponent<ren::StaticShaderMan>()->instance;
GLuint arrowVBO = vboMan.hasVBO("Assets/arrow.geom");
GLuint arrowIBO = iboMan.hasIBO("Assets/arrow.geom");
GLuint shader = shaderMan.getIDForAsset("Shaders/DirPhong");
// Bail if assets have not been loaded yet (asynchronous loading may take a
// few frames).
if (arrowVBO == 0 || arrowIBO == 0 || shader == 0) { return; }
const ren::IBOMan::IBOData* iboData;
try
{
iboData = &iboMan.getIBOData("Assets/arrow.geom");
}
catch (...)
{
// Return if IBO data not available.
return;
}
// Ensure shader attributes are setup appropriately.
mArrowAttribs.setup(arrowVBO, shader, vboMan);
glm::mat4 trafo;
GL(glUseProgram(shader));
GL(glBindBuffer(GL_ARRAY_BUFFER, arrowVBO));
GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, arrowIBO));
// Note that we can pull aspect ratio from the screen dimensions static
// variable.
gen::StaticScreenDims* dims = mCore.getStaticComponent<gen::StaticScreenDims>();
float aspect = static_cast<float>(dims->width) / static_cast<float>(dims->height);
glm::mat4 projection = glm::perspective(0.59f, aspect, 1.0f, 2000.0f);
// Build world transform for all axes. Rotates about uninverted camera's
// view, then translates to a specified corner on the screen.
glm::mat4 axesRot = mCamera->getWorldToView();
axesRot[3][0] = 0.0f;
axesRot[3][1] = 0.0f;
axesRot[3][2] = 0.0f;
glm::mat4 invCamTrans = glm::translate(glm::mat4(1.0f), glm::vec3(0.375f * aspect, 0.37f, -1.5f));
glm::mat4 axesScale = glm::scale(glm::mat4(1.0f), glm::vec3(0.8f));
glm::mat4 axesTransform = axesScale * axesRot;
GLint locCamViewVec = glGetUniformLocation(shader, "uCamViewVec");
GLint locLightDirWorld = glGetUniformLocation(shader, "uLightDirWorld");
GLint locAmbientColor = glGetUniformLocation(shader, "uAmbientColor");
GLint locDiffuseColor = glGetUniformLocation(shader, "uDiffuseColor");
GLint locSpecularColor = glGetUniformLocation(shader, "uSpecularColor");
GLint locSpecularPower = glGetUniformLocation(shader, "uSpecularPower");
GLint locProjIVObject = glGetUniformLocation(shader, "uProjIVObject");
GLint locObject = glGetUniformLocation(shader, "uObject");
GL(glUniform3f(locCamViewVec, 0.0f, 0.0f, -1.0f));
GL(glUniform3f(locLightDirWorld, 0.0f, 0.0f, -1.0f));
// Build projection for the axes to use on the screen. The arrors will not
// use the camera, but will use the camera's transformation matrix.
mArrowAttribs.bind();
// X Axis
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>() / 2.0f, glm::vec3(0.0, 1.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.5f, 0.01f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 1.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// X Axis (dark)
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() / 2.0f, glm::vec3(0.0, 1.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.1f, 0.01f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.25f, 0.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Y Axis
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), -glm::pi<float>() / 2.0f, glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.5f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 1.0f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Y Axis (dark)
{
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>() / 2.0f, glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.1f, 0.01f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.25f, 0.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Z Axis
{
// No rotation at all
glm::mat4 finalTrafo = axesTransform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.01f, 0.5f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.0f, 1.0f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.5f, 0.5f, 0.5f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
// Z Axis (dark)
{
// No rotation at all
glm::mat4 xform = glm::rotate(glm::mat4(1.0f), glm::pi<float>(), glm::vec3(1.0, 0.0, 0.0));
glm::mat4 finalTrafo = axesTransform * xform;
GL(glUniform4f(locAmbientColor, 0.01f, 0.01f, 0.1f, 1.0f));
GL(glUniform4f(locDiffuseColor, 0.0f, 0.0f, 0.25f, 1.0f));
GL(glUniform4f(locSpecularColor, 0.0f, 0.0f, 0.0f, 1.0f));
GL(glUniform1f(locSpecularPower, 16.0f));
glm::mat4 worldToProj = projection * invCamTrans * finalTrafo;
const GLfloat* ptr = glm::value_ptr(worldToProj);
GL(glUniformMatrix4fv(locProjIVObject, 1, false, ptr));
glm::mat4 objectSpace = finalTrafo;
ptr = glm::value_ptr(objectSpace);
GL(glUniformMatrix4fv(locObject, 1, false, ptr));
GL(glDrawElements(iboData->primMode, iboData->numPrims, iboData->primType, 0));
}
mArrowAttribs.unbind();
}
// Manually update the StaticCamera.
float rainbowRaw[] =
{
0.0000, 0.0000, 1.0000, 1.0,
0.0000, 0.0216, 1.0000, 1.0,
0.0000, 0.0432, 1.0000, 1.0,
0.0000, 0.0648, 1.0000, 1.0,
0.0000, 0.0864, 1.0000, 1.0,
0.0000, 0.1080, 1.0000, 1.0,
0.0000, 0.1296, 1.0000, 1.0,
0.0000, 0.1511, 1.0000, 1.0,
0.0000, 0.1727, 1.0000, 1.0,
0.0000, 0.1943, 1.0000, 1.0,
0.0002, 0.2104, 1.0000, 1.0,
0.0006, 0.2220, 1.0000, 1.0,
0.0011, 0.2336, 1.0000, 1.0,
0.0015, 0.2453, 1.0000, 1.0,
0.0019, 0.2569, 1.0000, 1.0,
0.0023, 0.2685, 1.0000, 1.0,
0.0027, 0.2801, 1.0000, 1.0,
0.0031, 0.2918, 1.0000, 1.0,
0.0036, 0.3034, 1.0000, 1.0,
0.0040, 0.3149, 1.0000, 1.0,
0.0048, 0.3253, 1.0000, 1.0,
0.0057, 0.3356, 1.0000, 1.0,
0.0065, 0.3460, 1.0000, 1.0,
0.0073, 0.3564, 1.0000, 1.0,
0.0082, 0.3668, 1.0000, 1.0,
0.0090, 0.3772, 1.0000, 1.0,
0.0098, 0.3875, 1.0000, 1.0,
0.0107, 0.3979, 1.0000, 1.0,
0.0115, 0.4083, 1.0000, 1.0,
0.0123, 0.4192, 1.0000, 1.0,
0.0131, 0.4304, 1.0000, 1.0,
0.0140, 0.4417, 1.0000, 1.0,
0.0148, 0.4529, 1.0000, 1.0,
0.0156, 0.4641, 1.0000, 1.0,
0.0165, 0.4753, 1.0000, 1.0,
0.0173, 0.4865, 1.0000, 1.0,
0.0181, 0.4977, 1.0000, 1.0,
0.0190, 0.5089, 1.0000, 1.0,
0.0200, 0.5200, 0.9989, 1.0,
0.0216, 0.5303, 0.9939, 1.0,
0.0233, 0.5407, 0.9889, 1.0,
0.0250, 0.5511, 0.9839, 1.0,
0.0266, 0.5615, 0.9790, 1.0,
0.0283, 0.5719, 0.9740, 1.0,
0.0299, 0.5822, 0.9690, 1.0,
0.0316, 0.5926, 0.9640, 1.0,
0.0333, 0.6030, 0.9590, 1.0,
0.0349, 0.6134, 0.9540, 1.0,
0.0359, 0.6221, 0.9433, 1.0,
0.0368, 0.6304, 0.9308, 1.0,
0.0376, 0.6388, 0.9183, 1.0,
0.0384, 0.6471, 0.9059, 1.0,
0.0393, 0.6554, 0.8934, 1.0,
0.0401, 0.6637, 0.8810, 1.0,
0.0409, 0.6720, 0.8685, 1.0,
0.0418, 0.6803, 0.8561, 1.0,
0.0426, 0.6886, 0.8436, 1.0,
0.0437, 0.6963, 0.8310, 1.0,
0.0454, 0.7030, 0.8181, 1.0,
0.0470, 0.7096, 0.8053, 1.0,
0.0487, 0.7163, 0.7924, 1.0,
0.0503, 0.7229, 0.7795, 1.0,
0.0520, 0.7296, 0.7666, 1.0,
0.0537, 0.7362, 0.7538, 1.0,
0.0553, 0.7428, 0.7409, 1.0,
0.0570, 0.7495, 0.7280, 1.0,
0.0586, 0.7561, 0.7152, 1.0,
0.0610, 0.7631, 0.7027, 1.0,
0.0635, 0.7702, 0.6902, 1.0,
0.0660, 0.7773, 0.6777, 1.0,
0.0685, 0.7843, 0.6653, 1.0,
0.0710, 0.7914, 0.6528, 1.0,
0.0735, 0.7984, 0.6404, 1.0,
0.0760, 0.8055, 0.6279, 1.0,
0.0785, 0.8125, 0.6155, 1.0,
0.0810, 0.8196, 0.6030, 1.0,
0.0840, 0.8263, 0.5913, 1.0,
0.0878, 0.8325, 0.5805, 1.0,
0.0915, 0.8388, 0.5697, 1.0,
0.0952, 0.8450, 0.5589, 1.0,
0.0990, 0.8512, 0.5481, 1.0,
0.1027, 0.8574, 0.5373, 1.0,
0.1064, 0.8637, 0.5265, 1.0,
0.1102, 0.8699, 0.5157, 1.0,
0.1139, 0.8761, 0.5049, 1.0,
0.1176, 0.8824, 0.4941, 1.0,
0.1226, 0.8873, 0.4842, 1.0,
0.1276, 0.8923, 0.4742, 1.0,
0.1326, 0.8973, 0.4642, 1.0,
0.1376, 0.9023, 0.4543, 1.0,
0.1426, 0.9073, 0.4443, 1.0,
0.1475, 0.9122, 0.4343, 1.0,
0.1525, 0.9172, 0.4244, 1.0,
0.1575, 0.9222, 0.4144, 1.0,
0.1625, 0.9272, 0.4044, 1.0,
0.1689, 0.9319, 0.3954, 1.0,
0.1763, 0.9365, 0.3871, 1.0,
0.1838, 0.9411, 0.3788, 1.0,
0.1913, 0.9457, 0.3705, 1.0,
0.1988, 0.9502, 0.3622, 1.0,
0.2062, 0.9548, 0.3539, 1.0,
0.2137, 0.9594, 0.3456, 1.0,
0.2212, 0.9639, 0.3373, 1.0,
0.2287, 0.9685, 0.3290, 1.0,
0.2365, 0.9729, 0.3206, 1.0,
0.2478, 0.9758, 0.3123, 1.0,
0.2590, 0.9787, 0.3040, 1.0,
0.2702, 0.9816, 0.2957, 1.0,
0.2814, 0.9845, 0.2874, 1.0,
0.2926, 0.9874, 0.2791, 1.0,
0.3038, 0.9903, 0.2708, 1.0,
0.3150, 0.9932, 0.2625, 1.0,
0.3262, 0.9961, 0.2542, 1.0,
0.3374, 0.9990, 0.2459, 1.0,
0.3492, 1.0000, 0.2395, 1.0,
0.3612, 1.0000, 0.2341, 1.0,
0.3733, 1.0000, 0.2287, 1.0,
0.3853, 1.0000, 0.2233, 1.0,
0.3974, 1.0000, 0.2179, 1.0,
0.4094, 1.0000, 0.2125, 1.0,
0.4215, 1.0000, 0.2072, 1.0,
0.4335, 1.0000, 0.2018, 1.0,
0.4455, 1.0000, 0.1964, 1.0,
0.4579, 0.9997, 0.1910, 1.0,
0.4711, 0.9985, 0.1861, 1.0,
0.4844, 0.9972, 0.1811, 1.0,
0.4977, 0.9960, 0.1761, 1.0,
0.5110, 0.9947, 0.1711, 1.0,
0.5243, 0.9935, 0.1661, 1.0,
0.5376, 0.9922, 0.1612, 1.0,
0.5509, 0.9910, 0.1562, 1.0,
0.5642, 0.9898, 0.1512, 1.0,
0.5774, 0.9885, 0.1462, 1.0,
0.5901, 0.9853, 0.1419, 1.0,
0.6025, 0.9816, 0.1377, 1.0,
0.6150, 0.9779, 0.1336, 1.0,
0.6275, 0.9741, 0.1294, 1.0,
0.6399, 0.9704, 0.1253, 1.0,
0.6524, 0.9666, 0.1211, 1.0,
0.6648, 0.9629, 0.1170, 1.0,
0.6773, 0.9592, 0.1128, 1.0,
0.6897, 0.9554, 0.1087, 1.0,
0.7012, 0.9516, 0.1048, 1.0,
0.7108, 0.9474, 0.1015, 1.0,
0.7203, 0.9433, 0.0981, 1.0,
0.7299, 0.9391, 0.0948, 1.0,
0.7394, 0.9349, 0.0915, 1.0,
0.7490, 0.9308, 0.0882, 1.0,
0.7585, 0.9266, 0.0848, 1.0,
0.7681, 0.9225, 0.0815, 1.0,
0.7776, 0.9183, 0.0782, 1.0,
0.7872, 0.9142, 0.0749, 1.0,
0.7952, 0.9089, 0.0727, 1.0,
0.8031, 0.9035, 0.0706, 1.0,
0.8110, 0.8981, 0.0685, 1.0,
0.8189, 0.8927, 0.0664, 1.0,
0.8268, 0.8873, 0.0644, 1.0,
0.8347, 0.8819, 0.0623, 1.0,
0.8426, 0.8765, 0.0602, 1.0,
0.8505, 0.8711, 0.0581, 1.0,
0.8584, 0.8657, 0.0561, 1.0,
0.8657, 0.8602, 0.0542, 1.0,
0.8723, 0.8543, 0.0525, 1.0,
0.8790, 0.8485, 0.0508, 1.0,
0.8856, 0.8427, 0.0492, 1.0,
0.8923, 0.8369, 0.0475, 1.0,
0.8989, 0.8311, 0.0459, 1.0,
0.9056, 0.8253, 0.0442, 1.0,
0.9122, 0.8195, 0.0425, 1.0,
0.9188, 0.8137, 0.0409, 1.0,
0.9255, 0.8078, 0.0392, 1.0,
0.9301, 0.7991, 0.0384, 1.0,
0.9346, 0.7904, 0.0376, 1.0,
0.9392, 0.7817, 0.0367, 1.0,
0.9438, 0.7730, 0.0359, 1.0,
0.9483, 0.7642, 0.0351, 1.0,
0.9529, 0.7555, 0.0342, 1.0,
0.9575, 0.7468, 0.0334, 1.0,
0.9620, 0.7381, 0.0326, 1.0,
0.9666, 0.7294, 0.0317, 1.0,
0.9700, 0.7223, 0.0307, 1.0,
0.9725, 0.7164, 0.0294, 1.0,
0.9750, 0.7106, 0.0282, 1.0,
0.9775, 0.7048, 0.0269, 1.0,
0.9800, 0.6990, 0.0257, 1.0,
0.9825, 0.6932, 0.0245, 1.0,
0.9850, 0.6874, 0.0232, 1.0,
0.9875, 0.6816, 0.0220, 1.0,
0.9899, 0.6758, 0.0207, 1.0,
0.9922, 0.6697, 0.0195, 1.0,
0.9931, 0.6614, 0.0187, 1.0,
0.9939, 0.6531, 0.0179, 1.0,
0.9947, 0.6448, 0.0170, 1.0,
0.9956, 0.6364, 0.0162, 1.0,
0.9964, 0.6281, 0.0154, 1.0,
0.9972, 0.6198, 0.0145, 1.0,
0.9981, 0.6115, 0.0137, 1.0,
0.9989, 0.6032, 0.0129, 1.0,
0.9997, 0.5949, 0.0120, 1.0,
1.0000, 0.5863, 0.0115, 1.0,
1.0000, 0.5776, 0.0111, 1.0,
1.0000, 0.5689, 0.0107, 1.0,
1.0000, 0.5602, 0.0102, 1.0,
1.0000, 0.5515, 0.0098, 1.0,
1.0000, 0.5427, 0.0094, 1.0,
1.0000, 0.5340, 0.0090, 1.0,
1.0000, 0.5253, 0.0086, 1.0,
1.0000, 0.5166, 0.0082, 1.0,
1.0000, 0.5081, 0.0078, 1.0,
1.0000, 0.5007, 0.0073, 1.0,
1.0000, 0.4932, 0.0069, 1.0,
1.0000, 0.4857, 0.0065, 1.0,
1.0000, 0.4782, 0.0061, 1.0,
1.0000, 0.4708, 0.0057, 1.0,
1.0000, 0.4633, 0.0053, 1.0,
1.0000, 0.4558, 0.0048, 1.0,
1.0000, 0.4484, 0.0044, 1.0,
1.0000, 0.4409, 0.0040, 1.0,
1.0000, 0.4334, 0.0036, 1.0,
1.0000, 0.4259, 0.0032, 1.0,
1.0000, 0.4185, 0.0028, 1.0,
1.0000, 0.4110, 0.0024, 1.0,
1.0000, 0.4035, 0.0019, 1.0,
1.0000, 0.3960, 0.0015, 1.0,
1.0000, 0.3886, 0.0011, 1.0,
1.0000, 0.3811, 0.0007, 1.0,
1.0000, 0.3736, 0.0003, 1.0,
1.0000, 0.3661, 0.0000, 1.0,
1.0000, 0.3587, 0.0000, 1.0,
1.0000, 0.3512, 0.0000, 1.0,
1.0000, 0.3437, 0.0000, 1.0,
1.0000, 0.3362, 0.0000, 1.0,
1.0000, 0.3288, 0.0000, 1.0,
1.0000, 0.3213, 0.0000, 1.0,
1.0000, 0.3138, 0.0000, 1.0,
1.0000, 0.3063, 0.0000, 1.0,
1.0000, 0.2989, 0.0000, 1.0,
1.0000, 0.2903, 0.0000, 1.0,
1.0000, 0.2816, 0.0000, 1.0,
1.0000, 0.2728, 0.0000, 1.0,
1.0000, 0.2641, 0.0000, 1.0,
1.0000, 0.2554, 0.0000, 1.0,
1.0000, 0.2467, 0.0000, 1.0,
1.0000, 0.2380, 0.0000, 1.0,
1.0000, 0.2293, 0.0000, 1.0,
1.0000, 0.2205, 0.0000, 1.0,
1.0000, 0.2055, 0.0000, 1.0,
1.0000, 0.1827, 0.0000, 1.0,
1.0000, 0.1599, 0.0000, 1.0,
1.0000, 0.1370, 0.0000, 1.0,
1.0000, 0.1142, 0.0000, 1.0,
1.0000, 0.0913, 0.0000, 1.0,
1.0000, 0.0685, 0.0000, 1.0,
1.0000, 0.0457, 0.0000, 1.0,
1.0000, 0.0228, 0.0000, 1.0,
1.0000, 0.0000, 0.0000, 1.0
};
// Create default colormaps.
void SRInterface::generateColormaps()
{
size_t rainbowArraySize = sizeof(rainbowRaw) / sizeof(*rainbowRaw);
std::vector<uint8_t> rainbow;
rainbow.reserve(rainbowArraySize);
for (int i = 0; i < rainbowArraySize; i++)
{
rainbow.push_back(static_cast<uint8_t>(rainbowRaw[i] * 255.0f));
}
// Build rainbow texture (eyetracking version -- will need to change).
GL(glGenTextures(1, &mRainbowCMap));
GL(glBindTexture(GL_TEXTURE_1D, mRainbowCMap));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glTexImage1D(GL_TEXTURE_1D, 0,
GL_RGBA8,
static_cast<GLsizei>(rainbow.size() / 4), 0,
GL_RGBA,
GL_UNSIGNED_BYTE, &rainbow[0]));
// build grayscale texture.
const int grayscaleSize = 255 * 4;
std::vector<uint8_t> grayscale;
grayscale.reserve(grayscaleSize);
for (int i = 0; i < 255; i++)
{
grayscale.push_back(i);
grayscale.push_back(i);
grayscale.push_back(i);
grayscale.push_back(255);
}
// Grayscale texture.
GL(glGenTextures(1, &mGrayscaleCMap));
GL(glBindTexture(GL_TEXTURE_1D, mGrayscaleCMap));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GL(glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL(glPixelStorei(GL_PACK_ALIGNMENT, 1));
GL(glTexImage1D(GL_TEXTURE_1D, 0,
GL_RGBA8,
static_cast<GLsizei>(grayscale.size() / 4), 0,
GL_RGBA,
GL_UNSIGNED_BYTE, &grayscale[0]));
}
} // namespace Render
} // namespace SCIRun
|
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Enums/EnumsToString.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <winix/getopt.h>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] = InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum = InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = static_cast<CardClass>(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck = InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck = InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation = InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable = card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable > MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() + numCardToAddAvailable - MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable << ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex = InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID = deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - " << deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck = static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template<std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
void Console::ShowSearchCardUsage() const
{
std::cout << "Usage: -r rarity -c class -t type -e race -n name -s cost -a attack -h health -m mechanics\n";
std::cout << "-r, --rarity: a rough measure of the quality and scarcity of a card\n";
std::cout << "(1 = Common, 2 = Free, 3 = Rare, 4 = Epic, 5 = Legendary)\n";
std::cout << "-c, --class: the primary determinant of a hero's powers and abilities\n";
std::cout << "(1 = Deathknight, 2 = Druid, 3 = Hunter, 4 = Mage, 5 = Paladin)\n";
std::cout << "(6 = Priest, 7 = Rogue, 8 = Shaman, 9 = Warlock, 10 = Warrior)\n";
std::cout << "-t, --type: spell cards, weapon cards, minion cards and hero cards\n";
std::cout << "(3 = Hero, 4 = Minion, 5 = Spell, 7 = Weapon)\n";
std::cout << "-e, --race: does not directly affect the behavior of the minion, but allows it to be affected by certain type-specific effects\n";
std::cout << "(14 = Murloc, 15 = Demon, 17 = Mechanical, 18 = Elemental)\n";
std::cout << "(20 = Beast, 21 = Totem, 23 = Pirate, 24 = Dragon)\n";
std::cout << "-n, --name: the name of a card (must type \"_\" between words)\n";
std::cout << "-s, --cost: determines how much mana is required to play that card from the hand or to use that hero power\n";
std::cout << "-a, --attack: what occurs when a player commands one character to attack another, causing them to simultaneously deal damage to each other\n";
std::cout << "-h, --health: an attribute found on heroes and minions, reflecting the remaining survivability of the character\n";
std::cout << "(-s|-a|-h \"x\": exact value, -s|-a|-h \"x\",\"y\": range value)\n";
std::cout << "-m, --mechanics: describes the total effect of playing that card or special effects or powers additional to the basic functions of the card\n";
std::cout << "(546 = Adapt, 218 = Battlecry, 197 = Charge, 443 = Choose one, 220 = Combo)\n";
std::cout << "(340 = Counter, 217 = Deathrattle, 415 = Discover, 194 = Divine Shield, 212 = Enraged)\n";
std::cout << "(208 = Freeze, 240 = Immune, 403 = Inspire, 685 = Lifesteal, 215 = Overload)\n";
std::cout << "(363 = Poisonous, 462 = Quest, 219 = Secret, 339 = Silence, 191 = Stealth)\n";
std::cout << "(190 = Taunt, 189 = Windfury)\n";
std::cout << "-p, --help: print this message\n";
std::cout << "-x, --exit: exit the menu\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes") ? true : (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(std::string commandStr) const
{
// Input commands
std::cout << commandStr;
char searchInput[256];
std::cin.getline(searchInput, 256);
int argc = 1;
char** argv = new char*[32];
char* context = nullptr;
const char* delimiter = " ";
for (int i = 0; i < 32; ++i)
{
argv[i] = new char[16];
}
#ifdef HEARTHSTONEPP_WINDOWS
argv[0] = _strdup("Hearthstone++");
#else
argv[0] = strdup("Hearthstone++");
#endif
#ifdef HEARTHSTONEPP_WINDOWS
char* nextToken = strtok_s(searchInput, delimiter, &context);
#else
char* nextToken = strtok_r(searchInput, delimiter, &context);
#endif
while (nextToken != nullptr)
{
#ifdef HEARTHSTONEPP_WINDOWS
argv[argc] = _strdup(nextToken);
nextToken = strtok_s(context, delimiter, &context);
#else
argv[argc] = strdup(nextToken);
nextToken = strtok_r(context, delimiter, &context);
#endif
argc++;
}
// Parse command
std::vector<std::string> tokens;
int opt, longIndex = 0;
Rarity rarity = Rarity::INVALID;
CardClass playerClass = CardClass::INVALID;
CardType cardType = CardType::INVALID;
Race race = Race::INVALID;
std::string name = "";
int costMin = -1, costMax = -1;
int attackMin = -1, attackMax = -1;
int healthMin = -1, healthMax = -1;
std::vector<GameTag> mechanics;
bool isValid = false, isFinish = false;
// Parse options
static struct option longOptions[] =
{
{ "rarity", required_argument, nullptr, 'r' },
{ "class", required_argument, nullptr, 'c' },
{ "type", required_argument, nullptr, 't' },
{ "race", required_argument, nullptr, 'e' },
{ "name", required_argument, nullptr, 'n' },
{ "cost", required_argument, nullptr, 's' },
{ "attack", required_argument, nullptr, 'a' },
{ "health", required_argument, nullptr, 'h' },
{ "mechanics", required_argument, nullptr, 'm' },
{ "help", no_argument, nullptr, 'p' },
{ "exit", no_argument, nullptr, 'x' },
{ nullptr, 0, nullptr, 0 }
};
// Initialize opt index
optind = 1;
char options[] = "r:c:t:e:n:s:a:h:m:p:x";
while ((opt = getopt_long(argc, argv, options, longOptions, &longIndex)) != -1)
{
isValid = true;
switch (opt)
{
case 'r':
rarity = static_cast<Rarity>(atoi(optarg));
break;
case 'c':
playerClass = static_cast<CardClass>(atoi(optarg));
break;
case 't':
cardType = static_cast<CardType>(atoi(optarg));
break;
case 'e':
race = static_cast<Race>(atoi(optarg));
break;
case 'n':
name = optarg;
break;
case 's':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
costMin = costMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
costMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
costMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'a':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
attackMin = attackMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
attackMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
attackMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'h':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
healthMin = healthMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
healthMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
healthMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'm':
tokens.clear();
tokens = SplitString(optarg, ",");
mechanics.clear();
for (auto& token : tokens)
{
mechanics.emplace_back(std::move(static_cast<GameTag>(atoi(token.c_str()))));
}
break;
case 'p':
isValid = false;
ShowSearchCardUsage();
break;
case 'x':
isFinish = true;
break;
default:
isValid = false;
ShowSearchCardUsage();
break;
}
}
for (int i = 0; i < 32; ++i)
{
delete[] argv[i];
}
delete[] argv;
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = name;
filter.costMin = costMin;
filter.costMax = costMax;
filter.attackMin = attackMin;
filter.attackMax = attackMax;
filter.healthMin = healthMin;
filter.healthMax = healthMax;
filter.mechanics = mechanics;
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == Rarity::INVALID || filter.rarity == card->GetRarity());
bool classCondition;
// When search mode is adding a card to a deck, the class is fixed to the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == CardClass::NEUTRAL || filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == CardClass::NEUTRAL || card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == CardClass::INVALID || filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == CardType::INVALID || filter.cardType == card->GetCardType());
bool raceCondition = (filter.race == Race::INVALID || filter.race == card->GetRace());
bool nameCondition = (filter.name.empty() || card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) || (filter.costMin <= card->GetCost() && filter.costMax >= card->GetCost()));
bool attackCondition = ((filter.attackMin == -1 || filter.attackMax == -1) || (filter.attackMin <= card->GetAttack() && filter.attackMax >= card->GetAttack()));
bool healthCondition = ((filter.healthMin == -1 || filter.healthMax == -1) || (filter.healthMin <= card->GetHealth() && filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanics.size() == 0 || card->HasMechanics(filter.mechanics));
const bool isMatched = AllCondIsTrue(rarityCondition, classCondition, typeCondition, raceCondition, nameCondition, costCondition, attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str, std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
}
Update Console - Fix -Werror=maybe-uninitialized
/*************************************************************************
> File Name: Console.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Console version of Hearthstone++ game.
> Created Time: 2017/10/08
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include "Console.h"
#include <Agents/GameAgent.h>
#include <Commons/Constants.h>
#include <Commons/Macros.h>
#include <Commons/Utils.h>
#include <Enums/EnumsToString.h>
#include <Interface/Interface.h>
#include <Loaders/CardLoader.h>
#include <Loaders/PlayerLoader.h>
#include <Models/Card.h>
#include <Models/Cards.h>
#ifdef HEARTHSTONEPP_WINDOWS
#include <filesystem>
#endif
#ifdef HEARTHSTONEPP_LINUX
#include <experimental/filesystem>
#endif
#ifdef HEARTHSTONEPP_MACOSX
#include <sys/stat.h>
#endif
#include <fstream>
#include <iostream>
#include <winix/getopt.h>
#ifndef HEARTHSTONEPP_MACOSX
namespace filesystem = std::experimental::filesystem;
#endif
namespace Hearthstonepp
{
void Console::SignIn()
{
std::cout << "Input Player ID to load data.\n";
std::cout << "If you do not want to load, please input \"STOP\"\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
if (playerID == "STOP")
{
break;
}
#ifndef HEARTHSTONEPP_MACOSX
if (!filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == -1)
#endif
{
std::cout << playerID << ".json doesn't exist. Try again.\n";
continue;
}
PlayerLoader loader;
m_player = loader.Load(playerID);
if (m_player == nullptr)
{
std::cout << "An error occurred while loading player data.\n";
continue;
}
std::cout << "You are signed in. Hello, " << playerID << "!\n";
Main();
break;
}
}
void Console::SignUp()
{
std::cout << "Input Player ID to create data.\n";
while (true)
{
std::cout << "Player ID: ";
std::string playerID;
std::cin >> playerID;
#ifndef HEARTHSTONEPP_MACOSX
if (filesystem::exists("Datas/" + playerID + ".json"))
#else
struct stat buf;
std::string path = "Datas/" + playerID + ".json";
if (stat(path.c_str(), &buf) == 0)
#endif
{
std::cout << playerID << ".json already exists. Try again.\n";
continue;
}
std::cout << "Name: ";
std::string name;
std::cin >> name;
m_player = new Player(std::move(playerID), std::move(name));
PlayerLoader loader;
loader.Save(m_player);
std::cout << "Your account has been created. Please sign in.\n";
break;
}
}
#ifndef HEARTHSTONEPP_MACOSX
std::optional<Card*> Console::SearchCard()
#else
std::experimental::optional<Card*> Console::SearchCard()
#endif
{
std::cout << "========================================\n";
std::cout << " Search Card! \n";
std::cout << "========================================\n";
// Extracts and discards characters from the input stream.
std::cin.ignore();
std::cout << "If you want to get help, type -h or --help.\n";
while (true)
{
auto[filter, isValid, isFinish] = InputAndParseSearchCommand("Command > ");
if (!isValid)
{
continue;
}
if (isFinish)
{
break;
}
std::cout << "========================================\n";
std::cout << " Search Result! \n";
std::cout << "========================================\n";
size_t idx = 1;
std::vector<Card*> result = ProcessSearchCommand(filter);
if (result.empty())
{
std::cout << "There are no cards matching your search condition.\n";
}
else
{
for (auto& card : result)
{
std::cout << idx << ". ";
card->ShowBriefInfo();
std::cout << '\n';
idx++;
}
if (m_searchMode == SearchMode::AddCardInDeck)
{
const size_t selectedCardIndex = InputMenuNum("Select: ", idx);
return result.at(selectedCardIndex);
}
}
}
return {};
}
int Console::ManageDeck()
{
std::cout << "========================================\n";
std::cout << " Manage Deck! \n";
std::cout << "========================================\n";
ShowMenu(m_manageDeckStr);
const size_t selectedNum = InputMenuNum("Select: ", MANAGE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedNum != MANAGE_DECK_MENU_SIZE)
{
m_manageDeckFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : ManageDeck();
}
void Console::SimulateGame()
{
int deck1, deck2;
std::string user1, user2;
std::cout << "[*] input first id, deck index : ";
std::cin >> user1 >> deck1;
std::cout << "[*] input second id, deck index : ";
std::cin >> user2 >> deck2;
PlayerLoader loader;
Player* p1 = loader.Load(user1);
Player* p2 = loader.Load(user2);
GameAgent agent(User(p1, deck1), User(p2, deck2));
GameInterface game(agent);
GameResult result = game.StartGame();
}
void Console::Leave()
{
PlayerLoader loader;
loader.Save(m_player);
if (m_player != nullptr)
{
delete m_player;
m_player = nullptr;
}
std::cout << "You have been successfully signed out. Have a nice day!\n";
}
void Console::CreateDeck()
{
std::cout << "========================================\n";
std::cout << " Create Deck! \n";
std::cout << "========================================\n";
std::cout << "What's your deck name? ";
std::string name;
std::cin >> name;
ShowMenu(m_playerClassStr);
const size_t selectedClassNum = InputMenuNum("What's your player class? ", PLAYER_CLASS_SIZE);
const CardClass deckClass = static_cast<CardClass>(selectedClassNum + 1);
m_player->CreateDeck(name, deckClass);
OperateDeck(m_player->GetNumOfDeck());
}
void Console::ModifyDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Modify Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to modify your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck = InputMenuNum("Select: ", m_player->GetNumOfDeck());
OperateDeck(selectedDeck);
}
void Console::DeleteDeck()
{
if (m_player->GetNumOfDeck() == 0)
{
std::cout << "Deck does not exist. Create a new deck!\n";
return;
}
std::cout << "========================================\n";
std::cout << " Delete Deck! \n";
std::cout << "========================================\n";
std::cout << "Input the number to delete your deck.\n";
m_player->ShowDeckList();
const size_t selectedDeck = InputMenuNum("Select: ", m_player->GetNumOfDeck());
m_player->DeleteDeck(selectedDeck);
}
int Console::OperateDeck(size_t deckIndex)
{
ShowMenu(m_deckOperationStr);
const size_t selectedOperation = InputMenuNum("What do you want to do? ", CREATE_DECK_MENU_SIZE);
bool isFinish = false;
if (selectedOperation != CREATE_DECK_MENU_SIZE)
{
m_deckOperationFuncs[selectedOperation - 1](*this, deckIndex);
}
else
{
isFinish = true;
}
return isFinish ? 0 : OperateDeck(deckIndex);
}
void Console::AddCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() >= MAXIMUM_NUM_CARDS_IN_DECK)
{
std::cout << "The deck " << deck->GetName() << " is full of cards.\n";
return;
}
// Set flag that the card should be returned.
m_searchMode = SearchMode::AddCardInDeck;
m_deckClass = deck->GetClass();
const Card* card = SearchCard().value_or(nullptr);
if (card == nullptr)
{
std::cout << " doesn't exist. Try again.\n";
return;
}
while (true)
{
int numCardToAddAvailable = card->GetMaxAllowedInDeck() - deck->GetNumCardInDeck(card->GetID());
if (deck->GetNumOfCards() + numCardToAddAvailable > MAXIMUM_NUM_CARDS_IN_DECK)
{
numCardToAddAvailable = deck->GetNumOfCards() + numCardToAddAvailable - MAXIMUM_NUM_CARDS_IN_DECK;
}
std::cout << "How many cards to add (0 - " << numCardToAddAvailable << ") ? ";
int numCardToAdd;
std::cin >> numCardToAdd;
if (numCardToAdd < 0 || numCardToAdd > numCardToAddAvailable)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->AddCard(card->GetID(), numCardToAdd);
break;
}
}
}
void Console::DeleteCardInDeck(size_t deckIndex)
{
Deck* deck = m_player->GetDeck(deckIndex - 1);
if (deck->GetNumOfCards() == 0)
{
std::cout << "The deck " << deck->GetName() << " is empty.\n";
return;
}
deck->ShowCardList();
const size_t selectedCardIndex = InputMenuNum("Select: ", deck->GetUniqueNumOfCards());
const std::string selectedCardID = deck->GetCard(selectedCardIndex - 1).first;
while (true)
{
std::cout << "How many cards to delete (0 - " << deck->GetNumCardInDeck(selectedCardID) << ") ? ";
int numCardToDelete;
std::cin >> numCardToDelete;
int numCardinDeck = static_cast<int>(deck->GetNumCardInDeck(selectedCardID));
if (numCardToDelete < 0 || numCardToDelete > numCardinDeck)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
deck->DeleteCard(selectedCardID, numCardToDelete);
break;
}
}
}
int Console::Login()
{
std::cout << " Welcome to Hearthstone++ Ver " << VERSION << '\n';
ShowMenu(m_loginMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", LOGIN_MENU_SIZE);
bool isFinish = false;
if (selectedNum != LOGIN_MENU_SIZE)
{
m_loginMenuFuncs[selectedNum - 1](*this);
}
else
{
isFinish = true;
}
return isFinish ? 0 : Login();
}
int Console::Main()
{
ShowMenu(m_mainMenuStr);
const size_t selectedNum = InputMenuNum("Select: ", MAIN_MENU_SIZE);
bool isFinish = false;
// Set flag that you do not need to return the card.
m_searchMode = SearchMode::JustSearch;
m_deckClass = CardClass::INVALID;
m_mainMenuFuncs[selectedNum - 1](*this);
if (selectedNum == MAIN_MENU_SIZE)
{
isFinish = true;
}
return isFinish ? 0 : Main();
}
template<std::size_t SIZE>
void Console::ShowMenu(std::array<std::string, SIZE>& menus)
{
std::cout << "========================================\n";
for (auto& menu : menus)
{
std::cout << menu.c_str() << '\n';
}
std::cout << "========================================\n";
}
void Console::ShowSearchCardUsage() const
{
std::cout << "Usage: -r rarity -c class -t type -e race -n name -s cost -a attack -h health -m mechanics\n";
std::cout << "-r, --rarity: a rough measure of the quality and scarcity of a card\n";
std::cout << "(1 = Common, 2 = Free, 3 = Rare, 4 = Epic, 5 = Legendary)\n";
std::cout << "-c, --class: the primary determinant of a hero's powers and abilities\n";
std::cout << "(1 = Deathknight, 2 = Druid, 3 = Hunter, 4 = Mage, 5 = Paladin)\n";
std::cout << "(6 = Priest, 7 = Rogue, 8 = Shaman, 9 = Warlock, 10 = Warrior)\n";
std::cout << "-t, --type: spell cards, weapon cards, minion cards and hero cards\n";
std::cout << "(3 = Hero, 4 = Minion, 5 = Spell, 7 = Weapon)\n";
std::cout << "-e, --race: does not directly affect the behavior of the minion, but allows it to be affected by certain type-specific effects\n";
std::cout << "(14 = Murloc, 15 = Demon, 17 = Mechanical, 18 = Elemental)\n";
std::cout << "(20 = Beast, 21 = Totem, 23 = Pirate, 24 = Dragon)\n";
std::cout << "-n, --name: the name of a card (must type \"_\" between words)\n";
std::cout << "-s, --cost: determines how much mana is required to play that card from the hand or to use that hero power\n";
std::cout << "-a, --attack: what occurs when a player commands one character to attack another, causing them to simultaneously deal damage to each other\n";
std::cout << "-h, --health: an attribute found on heroes and minions, reflecting the remaining survivability of the character\n";
std::cout << "(-s|-a|-h \"x\": exact value, -s|-a|-h \"x\",\"y\": range value)\n";
std::cout << "-m, --mechanics: describes the total effect of playing that card or special effects or powers additional to the basic functions of the card\n";
std::cout << "(546 = Adapt, 218 = Battlecry, 197 = Charge, 443 = Choose one, 220 = Combo)\n";
std::cout << "(340 = Counter, 217 = Deathrattle, 415 = Discover, 194 = Divine Shield, 212 = Enraged)\n";
std::cout << "(208 = Freeze, 240 = Immune, 403 = Inspire, 685 = Lifesteal, 215 = Overload)\n";
std::cout << "(363 = Poisonous, 462 = Quest, 219 = Secret, 339 = Silence, 191 = Stealth)\n";
std::cout << "(190 = Taunt, 189 = Windfury)\n";
std::cout << "-p, --help: print this message\n";
std::cout << "-x, --exit: exit the menu\n";
}
size_t Console::InputMenuNum(std::string questionStr, size_t menuSize)
{
while (true)
{
std::cout << questionStr;
size_t num;
std::cin >> num;
if (num < 1 || num > menuSize)
{
std::cout << "Invalid number! Try again.\n";
}
else
{
return num;
}
}
}
bool Console::InputYesNo(std::string sentence) const
{
std::cout << sentence;
std::cout << "(Please input \"y/yes\" or \"n/no\" (insensitive))\n";
std::cout << "Input: ";
std::string str;
std::cin >> str;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return (str == "y" || str == "yes") ? true : (str == "n" || str == "no") ? false : InputYesNo(sentence);
}
std::tuple<SearchFilter, bool, bool> Console::InputAndParseSearchCommand(std::string commandStr) const
{
// Input commands
std::cout << commandStr;
char searchInput[256];
std::cin.getline(searchInput, 256);
int argc = 1;
char** argv = new char*[32];
char* context = nullptr;
const char* delimiter = " ";
for (int i = 0; i < 32; ++i)
{
argv[i] = new char[16];
}
#ifdef HEARTHSTONEPP_WINDOWS
argv[0] = _strdup("Hearthstone++");
#else
argv[0] = strdup("Hearthstone++");
#endif
#ifdef HEARTHSTONEPP_WINDOWS
char* nextToken = strtok_s(searchInput, delimiter, &context);
#else
char* nextToken = strtok_r(searchInput, delimiter, &context);
#endif
while (nextToken != nullptr)
{
#ifdef HEARTHSTONEPP_WINDOWS
argv[argc] = _strdup(nextToken);
nextToken = strtok_s(context, delimiter, &context);
#else
argv[argc] = strdup(nextToken);
nextToken = strtok_r(context, delimiter, &context);
#endif
argc++;
}
// Parse command
std::vector<std::string> tokens;
int opt, longIndex = 0;
Rarity rarity = Rarity::INVALID;
CardClass playerClass = CardClass::INVALID;
CardType cardType = CardType::INVALID;
Race race = Race::INVALID;
std::string name = "";
int costMin = -1, costMax = -1;
int attackMin = -1, attackMax = -1;
int healthMin = -1, healthMax = -1;
std::vector<GameTag> mechanics;
bool isValid = false, isFinish = false;
// Parse options
static struct option longOptions[] =
{
{ "rarity", required_argument, nullptr, 'r' },
{ "class", required_argument, nullptr, 'c' },
{ "type", required_argument, nullptr, 't' },
{ "race", required_argument, nullptr, 'e' },
{ "name", required_argument, nullptr, 'n' },
{ "cost", required_argument, nullptr, 's' },
{ "attack", required_argument, nullptr, 'a' },
{ "health", required_argument, nullptr, 'h' },
{ "mechanics", required_argument, nullptr, 'm' },
{ "help", no_argument, nullptr, 'p' },
{ "exit", no_argument, nullptr, 'x' },
{ nullptr, 0, nullptr, 0 }
};
// Initialize opt index
optind = 1;
char options[] = "r:c:t:e:n:s:a:h:m:p:x";
while ((opt = getopt_long(argc, argv, options, longOptions, &longIndex)) != -1)
{
isValid = true;
switch (opt)
{
case 'r':
rarity = static_cast<Rarity>(atoi(optarg));
break;
case 'c':
playerClass = static_cast<CardClass>(atoi(optarg));
break;
case 't':
cardType = static_cast<CardType>(atoi(optarg));
break;
case 'e':
race = static_cast<Race>(atoi(optarg));
break;
case 'n':
name = optarg;
break;
case 's':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
costMin = costMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
costMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
costMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'a':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
attackMin = attackMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
attackMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
attackMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'h':
tokens.clear();
tokens = SplitString(optarg, ",");
if (tokens.size() == 1)
{
healthMin = healthMax = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
}
else if (tokens.size() == 2)
{
healthMin = std::clamp(atoi(tokens[0].c_str()), 0, std::numeric_limits<int>::max());
healthMax = std::clamp(atoi(tokens[1].c_str()), 0, std::numeric_limits<int>::max());
}
break;
case 'm':
tokens.clear();
tokens = SplitString(optarg, ",");
mechanics.clear();
for (auto& token : tokens)
{
mechanics.emplace_back(std::move(static_cast<GameTag>(atoi(token.c_str()))));
}
break;
case 'p':
isValid = false;
ShowSearchCardUsage();
break;
case 'x':
isFinish = true;
break;
default:
isValid = false;
ShowSearchCardUsage();
break;
}
}
for (int i = 0; i < 32; ++i)
{
delete[] argv[i];
}
delete[] argv;
SearchFilter filter;
filter.rarity = rarity;
filter.playerClass = playerClass;
filter.cardType = cardType;
filter.race = race;
filter.name = name;
filter.costMin = costMin;
filter.costMax = costMax;
filter.attackMin = attackMin;
filter.attackMax = attackMax;
filter.healthMin = healthMin;
filter.healthMax = healthMax;
filter.mechanics = mechanics;
return std::make_tuple(filter, isValid, isFinish);
}
std::vector<Card*> Console::ProcessSearchCommand(SearchFilter filter) const
{
std::vector<Card*> result;
for (auto& card : Cards::GetInstance()->GetAllCards())
{
if (card->GetCollectible() == false)
{
continue;
}
bool rarityCondition = (filter.rarity == Rarity::INVALID || filter.rarity == card->GetRarity());
bool classCondition = false;
// When search mode is adding a card to a deck, the class is fixed to the deck class and the neutral class.
if (m_searchMode == SearchMode::AddCardInDeck)
{
if (filter.playerClass == CardClass::NEUTRAL || filter.playerClass == m_deckClass)
{
classCondition = filter.playerClass == card->GetCardClass();
}
else
{
classCondition = (card->GetCardClass() == CardClass::NEUTRAL || card->GetCardClass() == m_deckClass);
}
}
else if (m_searchMode == SearchMode::JustSearch)
{
classCondition = (filter.playerClass == CardClass::INVALID || filter.playerClass == card->GetCardClass());
}
bool typeCondition = (filter.cardType == CardType::INVALID || filter.cardType == card->GetCardType());
bool raceCondition = (filter.race == Race::INVALID || filter.race == card->GetRace());
bool nameCondition = (filter.name.empty() || card->GetName().find(filter.name) != std::string::npos);
bool costCondition = ((filter.costMin == -1 || filter.costMax == -1) || (filter.costMin <= card->GetCost() && filter.costMax >= card->GetCost()));
bool attackCondition = ((filter.attackMin == -1 || filter.attackMax == -1) || (filter.attackMin <= card->GetAttack() && filter.attackMax >= card->GetAttack()));
bool healthCondition = ((filter.healthMin == -1 || filter.healthMax == -1) || (filter.healthMin <= card->GetHealth() && filter.healthMax >= card->GetHealth()));
bool mechanicsCondition = (filter.mechanics.size() == 0 || card->HasMechanics(filter.mechanics));
const bool isMatched = AllCondIsTrue(rarityCondition, classCondition, typeCondition, raceCondition, nameCondition, costCondition, attackCondition, healthCondition, mechanicsCondition);
if (isMatched)
{
result.emplace_back(card);
}
}
return result;
}
std::vector<std::string> Console::SplitString(std::string str, std::string delimiter) const
{
size_t pos;
std::vector<std::string> tokens;
// If the number of tokens is 1
if ((pos = str.find(delimiter)) == std::string::npos)
{
tokens.emplace_back(str);
return tokens;
}
// If the number of tokens is greater than 1
while ((pos = str.find(delimiter)) != std::string::npos)
{
tokens.emplace_back(str.substr(0, pos));
str.erase(0, pos + delimiter.length());
}
return tokens;
}
} |
/**
* kmeditor.cpp
*
* Copyright 2007 Laurent Montel <montel@kde.org>
* Copyright 2008 Thomas McGuire <thomas.mcguire@gmx.net>
* Copyright 2008 Stephen Kelly <steveire@gmail.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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "kmeditor.h"
#include "kemailquotinghighter.h"
#include "kmutils.h"
#include "klinkdialog.h"
#include <maillistdrag.h>
//kdepimlibs includes
#include <kpimidentities/signature.h>
//kdelibs includes
#include <kdebug.h>
#include <kdeversion.h>
#include <kfind.h>
#include <kreplace.h>
#include <kreplacedialog.h>
#include <kfinddialog.h>
#include <KWindowSystem>
#include <KFindDialog>
#include <KColorDialog>
#include <KFileDialog>
#include <KComboBox>
#include <KToolBar>
#include <KCharsets>
#include <KPushButton>
#include <klocale.h>
#include <kmenu.h>
#include <KMessageBox>
#include <KDirWatch>
#include <KTemporaryFile>
#include <KCursor>
#include <sonnet/configdialog.h>
//qt includes
#include <QApplication>
#include <QClipboard>
#include <QShortcut>
#include <QPointer>
#include <QTextCodec>
#include <QTextList>
#include <QTextDocumentFragment>
#include <QAction>
#include <QProcess>
#include <QTextLayout>
#include <QTimer>
//system includes
#include <assert.h>
namespace KPIM {
class KMeditorPrivate
{
public:
KMeditorPrivate( KMeditor *parent )
: q( parent ),
useExtEditor( false ),
mExtEditorProcess( 0 ),
mExtEditorTempFileWatcher( 0 ),
mExtEditorTempFile( 0 ),
mMode( KMeditor::Plain )
{
}
~KMeditorPrivate()
{
}
//
// Slots
//
void addSuggestion( const QString&,const QStringList& );
// Just calls KTextEdit::ensureCursorVisible(), workaround for some bug.
void ensureCursorVisibleDelayed();
//
// Normal functions
//
// If the text under the cursor is a link, the cursor's selection is set to
// the complete link text.
void selectLinkText( QTextCursor *cursor ) const;
QString addQuotesToText( const QString &inputText );
QString removeQuotesFromText( const QString &inputText ) const;
void init();
// Switches to rich text mode and emits the mode changed signal if the
// mode really changed.
void activateRichText();
// Applies formatting to the current word if there is no selection.
void mergeFormatOnWordOrSelection( const QTextCharFormat &format );
// Returns the text of the signature. If the signature is HTML, the HTML
// tags will be stripped.
QString plainSignatureText( const KPIMIdentities::Signature &signature ) const;
// Replaces each text which matches the regular expression with another text.
// Text inside quotes or the given signature will be ignored.
void cleanWhitespaceHelper( const QRegExp ®Exp, const QString &newText,
const KPIMIdentities::Signature &sig );
// Returns a list of positions of occurences of the given signature.
// Each pair is the index of the start- and end position of the signature.
QList< QPair<int,int> > signaturePositions( const KPIMIdentities::Signature &sig ) const;
// Data members
QMap<QString,QStringList> replacements;
QString extEditorPath;
QString language;
KMeditor *q;
bool useExtEditor;
bool spellCheckingEnabled;
QProcess *mExtEditorProcess;
KDirWatch *mExtEditorTempFileWatcher;
KTemporaryFile *mExtEditorTempFile;
KMeditor::Mode mMode;
};
}
using namespace KPIM;
void KMeditorPrivate::activateRichText()
{
if ( mMode == KMeditor::Plain ) {
q->setAcceptRichText( true );
mMode = KMeditor::Rich;
emit q->textModeChanged( mMode );
}
}
QList< QPair<int,int> > KMeditorPrivate::signaturePositions( const KPIMIdentities::Signature &sig ) const
{
QList< QPair<int,int> > signaturePositions;
if ( !sig.rawText().isEmpty() ) {
QString sigText = plainSignatureText( sig );
int currentSearchPosition = 0;
forever {
// Find the next occurence of the signature text
QString text = q->document()->toPlainText();
int currentMatch = text.indexOf( sigText, currentSearchPosition );
currentSearchPosition = currentMatch + sigText.length();
if ( currentMatch == -1 )
break;
signaturePositions.append( QPair<int,int>( currentMatch,
currentMatch + sigText.length() ) );
}
}
return signaturePositions;
}
void KMeditorPrivate::cleanWhitespaceHelper( const QRegExp ®Exp,
const QString &newText,
const KPIMIdentities::Signature &sig )
{
int currentSearchPosition = 0;
forever {
// Find the text
QString text = q->document()->toPlainText();
int currentMatch = regExp.indexIn( text, currentSearchPosition );
currentSearchPosition = currentMatch;
if ( currentMatch == -1 )
break;
// Select the text
QTextCursor cursor( q->document() );
cursor.setPosition( currentMatch );
cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
regExp.matchedLength() );
// Skip quoted text
if ( cursor.block().text().startsWith( q->quotePrefixName() ) ) {
currentSearchPosition += regExp.matchedLength();
continue;
}
// Skip text inside signatures
bool insideSignature = false;
QList< QPair<int,int> > sigPositions = signaturePositions( sig );
QPair<int,int> position;
foreach( position, sigPositions ) {
if ( cursor.position() >= position.first &&
cursor.position() <= position.second )
insideSignature = true;
}
if ( insideSignature ) {
currentSearchPosition += regExp.matchedLength();
continue;
}
// Replace the text
cursor.removeSelectedText();
cursor.insertText( newText );
currentSearchPosition += newText.length();
}
}
QString KMeditorPrivate::plainSignatureText( const KPIMIdentities::Signature &signature ) const
{
QString sigText = signature.rawText();
if ( signature.isInlinedHtml() &&
signature.type() == KPIMIdentities::Signature::Inlined ) {
// Use a QTextDocument as a helper, it does all the work for us and
// strips all HTML tags.
QTextDocument helper;
QTextCursor helperCursor( &helper );
helperCursor.insertHtml( sigText );
sigText = helper.toPlainText();
}
return sigText;
}
void KMeditorPrivate::addSuggestion( const QString& originalWord,
const QStringList& lst )
{
replacements[originalWord] = lst;
}
void KMeditorPrivate::ensureCursorVisibleDelayed()
{
static_cast<KTextEdit*>( q )->ensureCursorVisible();
}
void KMeditorPrivate::mergeFormatOnWordOrSelection( const QTextCharFormat &format )
{
QTextCursor cursor = q->textCursor();
if ( !cursor.hasSelection() )
cursor.select( QTextCursor::WordUnderCursor );
cursor.mergeCharFormat( format );
q->mergeCurrentCharFormat( format );
}
void KMeditor::dragEnterEvent( QDragEnterEvent *e )
{
if ( KPIM::MailList::canDecode( e->mimeData() ) ) {
e->setAccepted( true );
} else if ( e->mimeData()->hasFormat( "image/png" ) ) {
e->accept();
} else {
return KTextEdit::dragEnterEvent( e );
}
}
void KMeditor::dragMoveEvent( QDragMoveEvent *e )
{
if ( KPIM::MailList::canDecode( e->mimeData() ) ) {
e->accept();
} else if ( e->mimeData()->hasFormat( "image/png" ) ) {
e->accept();
} else {
return KTextEdit::dragMoveEvent( e );
}
}
void KMeditor::paste()
{
if ( !QApplication::clipboard()->image().isNull() ) {
emit pasteImage();
}
else
KTextEdit::paste();
}
void KMeditor::keyPressEvent ( QKeyEvent * e )
{
if ( e->key() == Qt::Key_Return ) {
QTextCursor cursor = textCursor();
int oldPos = cursor.position();
int blockPos = cursor.block().position();
//selection all the line.
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString lineText = cursor.selectedText();
if ( ( ( oldPos -blockPos ) > 0 ) &&
( ( oldPos-blockPos ) < int( lineText.length() ) ) ) {
bool isQuotedLine = false;
int bot = 0; // bot = begin of text after quote indicators
while ( bot < lineText.length() ) {
if( ( lineText[bot] == '>' ) || ( lineText[bot] == '|' ) ) {
isQuotedLine = true;
++bot;
}
else if ( lineText[bot].isSpace() ) {
++bot;
}
else {
break;
}
}
KTextEdit::keyPressEvent( e );
// duplicate quote indicators of the previous line before the new
// line if the line actually contained text (apart from the quote
// indicators) and the cursor is behind the quote indicators
if ( isQuotedLine
&& ( bot != lineText.length() )
&& ( ( oldPos-blockPos ) >= int( bot ) ) ) {
// The cursor position might have changed unpredictably if there was selected
// text which got replaced by a new line, so we query it again:
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString newLine = cursor.selectedText();
// remove leading white space from the new line and instead
// add the quote indicators of the previous line
int leadingWhiteSpaceCount = 0;
while ( ( leadingWhiteSpaceCount < newLine.length() )
&& newLine[leadingWhiteSpaceCount].isSpace() ) {
++leadingWhiteSpaceCount;
}
newLine = newLine.replace( 0, leadingWhiteSpaceCount,
lineText.left( bot ) );
cursor.insertText( newLine );
//cursor.setPosition( cursor.position() + 2);
cursor.movePosition( QTextCursor::StartOfBlock );
setTextCursor( cursor );
}
}
else
KTextEdit::keyPressEvent( e );
}
else if ( e->key() == Qt::Key_Up && e->modifiers() != Qt::ShiftModifier &&
textCursor().block().position() == 0 &&
textCursor().position() <
textCursor().block().layout()->lineAt( 0 ).textLength() )
{
textCursor().clearSelection();
emit focusUp();
}
else if ( e->key() == Qt::Key_Backtab && e->modifiers() == Qt::ShiftModifier )
{
textCursor().clearSelection();
emit focusUp();
}
else
{
KTextEdit::keyPressEvent( e );
}
}
KMeditor::KMeditor( const QString& text, QWidget *parent )
: KTextEdit( text, parent ), d( new KMeditorPrivate( this ) )
{
d->init();
}
KMeditor::KMeditor( QWidget *parent )
: KTextEdit( parent ), d( new KMeditorPrivate( this ) )
{
d->init();
}
KMeditor::~KMeditor()
{
delete d;
}
bool KMeditor::eventFilter( QObject*o, QEvent* e )
{
if (o == this)
KCursor::autoHideEventFilter( o, e );
return KTextEdit::eventFilter( o, e );
}
void KMeditorPrivate::init()
{
// We tell the KTextEdit to enable spell checking, because only then it will
// call createHighlighter() which will create our own highlighter which also
// does quote highlighting.
// However, *our* spellchecking is still disabled. Our own highlighter only
// cares about our spellcheck status, it will not highlight missspellt words
// if our spellchecking is disabled.
// See also KEMailQuotingHighlighter::highlightBlock().
spellCheckingEnabled = false;
static_cast<KTextEdit*>( q )->setCheckSpellingEnabled( true );
KCursor::setAutoHideCursor( q, true, true );
q->installEventFilter( q );
QShortcut * insertMode = new QShortcut( QKeySequence( Qt::Key_Insert ), q );
q->connect( insertMode, SIGNAL( activated() ),
q, SLOT( slotChangeInsertMode() ) );
#if KDE_IS_VERSION(4,0,67)
q->connect( q, SIGNAL( languageChanged(const QString &) ),
q, SLOT( setSpellCheckLanguage(const QString &) ) );
#endif
}
void KMeditor::slotChangeInsertMode()
{
setOverwriteMode( !overwriteMode() );
emit overwriteModeText();
}
void KMeditor::createHighlighter()
{
KPIM::KEMailQuotingHighlighter *emailHighLighter =
new KPIM::KEMailQuotingHighlighter( this );
changeHighlighterColors( emailHighLighter );
connect( emailHighLighter, SIGNAL( newSuggestions(const QString&,const QStringList&) ),
this, SLOT( addSuggestion(const QString&,const QStringList&) ) );
//TODO change config
KTextEdit::setHighlighter( emailHighLighter );
if ( !d->language.isEmpty() )
setSpellCheckLanguage( d->language );
toggleSpellChecking( d->spellCheckingEnabled );
}
void KMeditor::changeHighlighterColors(KPIM::KEMailQuotingHighlighter *)
{
}
void KMeditor::setUseExternalEditor( bool use )
{
d->useExtEditor = use;
}
void KMeditor::setExternalEditorPath( const QString & path )
{
d->extEditorPath = path;
}
void KMeditor::slotChangeParagStyle( QTextListFormat::Style _style )
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
// Create a list with the specified format
if ( _style != QTextListFormat::ListStyleUndefined ) {
QTextBlockFormat blockFmt = cursor.blockFormat();
QTextListFormat listFmt;
if ( cursor.currentList() ) {
listFmt = cursor.currentList()->format();
} else {
listFmt.setIndent( blockFmt.indent() + 1 );
blockFmt.setIndent( 0 );
cursor.setBlockFormat( blockFmt );
}
listFmt.setStyle( _style );
cursor.createList( listFmt );
d->activateRichText();
}
// Remove the list formatting again
else {
QTextList *list = cursor.currentList();
if ( list ) {
QTextListFormat listFormat = list->format();
listFormat.setIndent( 0 );
list->setFormat( listFormat );
int count = list->count();
while ( count > 0 ) {
list->removeItem( 0 );
count--;
}
}
}
cursor.endEditBlock();
setFocus();
}
void KMeditor::setColor( const QColor& col )
{
QTextCharFormat fmt;
fmt.setForeground( col );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::setFont( const QFont &font )
{
QTextCharFormat fmt;
fmt.setFont( font );
d->mergeFormatOnWordOrSelection( fmt );
}
void KMeditor::setFontForWholeText( const QFont &font )
{
QTextCharFormat fmt;
fmt.setFont( font );
QTextCursor cursor( document() );
cursor.movePosition( QTextCursor::End, QTextCursor::KeepAnchor );
cursor.mergeCharFormat( fmt );
document()->setDefaultFont( font );
}
void KMeditor::slotAlignLeft()
{
setAlignment( Qt::AlignLeft );
d->activateRichText();
}
void KMeditor::slotAlignCenter()
{
setAlignment( Qt::AlignHCenter );
d->activateRichText();
}
void KMeditor::slotAlignRight()
{
setAlignment( Qt::AlignRight );
d->activateRichText();
}
void KMeditor::slotTextBold( bool _b )
{
QTextCharFormat fmt;
fmt.setFontWeight( _b ? QFont::Bold : QFont::Normal );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextItalic( bool _b)
{
QTextCharFormat fmt;
fmt.setFontItalic( _b );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextUnder( bool _b )
{
QTextCharFormat fmt;
fmt.setFontUnderline( _b );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextColor()
{
QColor color = textColor();
if ( KColorDialog::getColor( color, this ) ) {
QTextCharFormat fmt;
fmt.setForeground( color );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
}
void KMeditor::slotFontFamilyChanged( const QString &f )
{
QTextCharFormat fmt;
fmt.setFontFamily( f );
d->mergeFormatOnWordOrSelection( fmt );
setFocus();
d->activateRichText();
}
void KMeditor::slotFontSizeChanged( int size )
{
QTextCharFormat fmt;
fmt.setFontPointSize( size );
d->mergeFormatOnWordOrSelection( fmt );
setFocus();
d->activateRichText();
}
KUrl KMeditor::insertFile( const QStringList &encodingLst, QString &encodingStr )
{
KUrl url;
KFileDialog fdlg( url, QString(), this );
fdlg.setOperationMode( KFileDialog::Opening );
fdlg.okButton()->setText( i18n( "&Insert" ) );
fdlg.setCaption( i18n( "Insert File" ) );
if ( !encodingLst.isEmpty() )
{
KComboBox *combo = new KComboBox( this );
combo->addItems( encodingLst );
fdlg.toolBar()->addWidget( combo );
for ( int i = 0; i < combo->count(); i++ )
if ( KGlobal::charsets()->codecForName( KGlobal::charsets()->
encodingForName( combo->itemText( i ) ) )
== QTextCodec::codecForLocale() )
combo->setCurrentIndex(i);
encodingStr = combo->currentText();
}
if ( !fdlg.exec() )
return KUrl();
KUrl u = fdlg.selectedUrl();
return u;
}
void KMeditor::enableWordWrap( int wrapColumn )
{
setWordWrapMode( QTextOption::WordWrap );
setLineWrapMode( QTextEdit::FixedColumnWidth );
setLineWrapColumnOrWidth( wrapColumn );
}
void KMeditor::disableWordWrap()
{
setLineWrapMode( QTextEdit::WidgetWidth );
}
void KMeditor::contextMenuEvent( QContextMenuEvent *event )
{
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
{
//if we have selection so use standard menu
KTextEdit::contextMenuEvent( event );
return;
}
else
{
//select word under current cursor
cursor.select( QTextCursor::WordUnderCursor );
setTextCursor( cursor );
QString word = textCursor().selectedText();
if ( word.isEmpty() || !d->replacements.contains( word ) )
KTextEdit::contextMenuEvent( event );
else //try to create spell check menu
{
KMenu p;
p.addTitle( i18n( "Suggestions" ) );
//Add the suggestions to the popup menu
QStringList reps = d->replacements[word];
if ( reps.count() > 0 ) {
for ( QStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {
p.addAction( *it );
}
}
else {
p.addAction( i18n( "No Suggestions" ) );
}
//Execute the popup inline
const QAction *selectedAction = p.exec( mapToGlobal( event->pos() ) );
if ( selectedAction && ( reps.count() > 0 ) ) {
int oldPos = cursor.position();
const QString replacement = selectedAction->text();
cursor.insertText( replacement );
#if 0
// Restore the cursor position; if the cursor was behind the
// misspelled word then adjust the cursor position
if ( para == parIdx && txtIdx >= lastSpace )
txtIdx += replacement.length() - word.length();
setCursorPosition( parIdx, txtIdx );
#endif
cursor.setPosition(oldPos);
setTextCursor(cursor);
}
return;
}
}
}
void KMeditor::slotPasteAsQuotation()
{
if ( hasFocus() ) {
QString s = QApplication::clipboard()->text();
if ( !s.isEmpty() ) {
insertPlainText( d->addQuotesToText( s ) );
}
}
}
void KMeditor::slotRemoveQuotes()
{
// TODO: I think this is backwards.
// i.e, if no region is marked then remove quotes from every line
// else remove quotes only on the lines that are marked.
QTextCursor cursor = textCursor();
if(cursor.hasSelection())
{
QString s = cursor.selectedText();
insertPlainText( d->removeQuotesFromText( s ) );
}
else
{
int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
if ( !s.isEmpty() )
{
cursor.insertText( d->removeQuotesFromText( s ) );
cursor.setPosition( qMax( 0, oldPos - 2 ) );
setTextCursor( cursor );
}
}
}
void KMeditor::slotAddQuotes()
{
// TODO: I think this is backwards.
// i.e, if no region is marked then add quotes to every line
// else add quotes only on the lines that are marked.
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
{
QString s = cursor.selectedText();
if ( !s.isEmpty() ) {
cursor.insertText( d->addQuotesToText( s ) );
setTextCursor( cursor );
}
}
else {
int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
cursor.insertText( d->addQuotesToText( s ) );
cursor.setPosition( oldPos + 2 ); //FIXME: 2 probably wrong
setTextCursor( cursor );
}
}
QString KMeditorPrivate::removeQuotesFromText( const QString &inputText ) const
{
QString s = inputText;
// remove first leading quote
QString quotePrefix = '^' + q->quotePrefixName();
QRegExp rx( quotePrefix );
s.remove( rx );
// now remove all remaining leading quotes
quotePrefix = QString( QChar::ParagraphSeparator ) + ' ' + q->quotePrefixName();
QRegExp srx( quotePrefix );
s.remove( srx );
return s;
}
QString KMeditorPrivate::addQuotesToText( const QString &inputText )
{
QString answer = QString( inputText );
QString indentStr = q->quotePrefixName();
answer.replace( '\n', '\n' + indentStr );
//cursor.selectText() as QChar::ParagraphSeparator as paragraph separator.
answer.replace( QChar::ParagraphSeparator, '\n' + indentStr );
answer.prepend( indentStr );
answer += '\n';
return q->smartQuote( answer );
}
QString KMeditor::smartQuote( const QString & msg )
{
return msg;
}
QString KMeditor::quotePrefixName() const
{
//Need to redefine into each apps
return "> ";
}
bool KMeditor::checkExternalEditorFinished()
{
if ( !d->mExtEditorProcess )
return true;
switch ( KMessageBox::warningYesNoCancel( topLevelWidget(),
i18n("The external editor is still running.\n"
"Abort the external editor or leave it open?"),
i18n("External Editor"),
KGuiItem( i18n("Abort Editor") ),
KGuiItem( i18n("Leave Editor Open") ) ) ) {
case KMessageBox::Yes:
killExternalEditor();
return true;
case KMessageBox::No:
return true;
default:
return false;
}
}
void KMeditor::killExternalEditor()
{
delete d->mExtEditorProcess;
d->mExtEditorProcess = 0;
delete d->mExtEditorTempFileWatcher;
d->mExtEditorTempFileWatcher = 0;
delete d->mExtEditorTempFile;
d->mExtEditorTempFile = 0;
}
void KMeditor::setCursorPositionFromStart( unsigned int pos )
{
if ( pos > 0 )
{
QTextCursor cursor = textCursor();
cursor.setPosition( pos );
setTextCursor( cursor );
ensureCursorVisible();
}
}
void KMeditor::slotRemoveBox()
{
//Laurent: fix me
#if 0
if (hasMarkedText()) {
QString s = QString::fromLatin1("\n") + markedText() + QString::fromLatin1("\n");
s.replace(QRegExp("\n,----[^\n]*\n"),"\n");
s.replace(QRegExp("\n| "),"\n");
s.replace(QRegExp("\n`----[^\n]*\n"),"\n");
s.remove(0,1);
s.truncate(s.length()-1);
insert(s);
} else {
int l = currentLine();
int c = currentColumn();
QString s = textLine(l); // test if we are in a box
if (!((s.left(2) == "| ")||(s.left(5)==",----")||(s.left(5)=="`----")))
return;
setAutoUpdate(false);
// find & remove box begin
int x = l;
while ((x>=0)&&(textLine(x).left(5)!=",----"))
x--;
if ((x>=0)&&(textLine(x).left(5)==",----")) {
removeLine(x);
l--;
for (int i=x;i<=l;i++) { // remove quotation
s = textLine(i);
if (s.left(2) == "| ") {
s.remove(0,2);
insertLine(s,i);
removeLine(i+1);
}
}
}
// find & remove box end
x = l;
while ((x<numLines())&&(textLine(x).left(5)!="`----"))
x++;
if ((x<numLines())&&(textLine(x).left(5)=="`----")) {
removeLine(x);
for (int i=l+1;i<x;i++) { // remove quotation
s = textLine(i);
if (s.left(2) == "| ") {
s.remove(0,2);
insertLine(s,i);
removeLine(i+1);
}
}
}
setCursorPosition(l,c-2);
setAutoUpdate(true);
repaint();
}
#endif
}
void KMeditor::slotAddBox()
{
//Laurent fixme
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
{
QString s = cursor.selectedText();
s.prepend( ",----[ ]\n" );
s.replace( QRegExp("\n"),"\n| " );
s.append( "\n`----" );
insertPlainText( s );
} else {
//int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
QString str = QString::fromLatin1(",----[ ]\n| %1\n`----").arg(s);
cursor.insertText( str );
//cursor.setPosition( qMax( 0, oldPos - 2 ) );
setTextCursor( cursor );
}
}
int KMeditor::linePosition()
{
QTextCursor cursor = textCursor();
return cursor.blockNumber();
}
int KMeditor::columnNumber()
{
QTextCursor cursor = textCursor();
return cursor.columnNumber();
}
void KMeditor::slotRot13()
{
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
insertPlainText( KMUtils::rot13( cursor.selectedText() ) );
//FIXME: breaks HTML formatting
}
void KMeditor::setCursorPosition( int linePos, int columnPos )
{
//TODO
Q_UNUSED( linePos );
Q_UNUSED( columnPos );
}
void KMeditor::cleanWhitespace( const KPIMIdentities::Signature &sig )
{
QTextCursor cursor( document() );
cursor.beginEditBlock();
// Squeeze tabs and spaces
d->cleanWhitespaceHelper( QRegExp( "[\t ]+" ), QString( ' ' ), sig );
// Remove trailing whitespace
d->cleanWhitespaceHelper( QRegExp( "[\t ][\n]" ), QString( '\n' ), sig );
// Single space lines
d->cleanWhitespaceHelper( QRegExp( "[\n]{3,}" ), "\n\n", sig );
if ( !textCursor().hasSelection() ) {
textCursor().clearSelection();
}
cursor.endEditBlock();
}
void KMeditor::insertSignature( const KPIMIdentities::Signature &sig,
Placement placement, bool addSeparator )
{
QString signature;
if ( addSeparator )
signature = sig.withSeparator();
else
signature = sig.rawText();
insertSignature( signature, placement,
( sig.isInlinedHtml() &&
sig.type() == KPIMIdentities::Signature::Inlined ) );
}
void KMeditor::insertSignature( const QString &signature, Placement placement,
bool isHtml )
{
if ( !signature.isEmpty() ) {
// Save the modified state of the document, as inserting a signature
// shouldn't change this. Restore it at the end of this function.
bool isModified = document()->isModified();
// Move to the desired position, where the signature should be inserted
QTextCursor cursor = textCursor();
QTextCursor oldCursor = cursor;
cursor.beginEditBlock();
if ( placement == End )
cursor.movePosition( QTextCursor::End );
else if ( placement == Start )
cursor.movePosition( QTextCursor::Start );
setTextCursor( cursor );
// Insert the signature and newlines depending on where it was inserted.
if ( placement == End ) {
if ( isHtml ) {
insertHtml( "<br>" + signature );
} else {
insertPlainText( '\n' + signature );
}
} else if ( placement == Start || placement == AtCursor ) {
if ( isHtml ) {
insertHtml( "<br>" + signature + "<br>" );
} else {
insertPlainText( '\n' + signature + '\n' );
}
}
cursor.endEditBlock();
setTextCursor( oldCursor );
ensureCursorVisible();
document()->setModified( isModified );
if ( isHtml )
d->activateRichText();
}
}
void KMeditor::replaceSignature( const KPIMIdentities::Signature &oldSig,
const KPIMIdentities::Signature &newSig )
{
QTextCursor cursor( document() );
cursor.beginEditBlock();
QString oldSigText = d->plainSignatureText( oldSig );
int currentSearchPosition = 0;
forever {
// Find the next occurence of the signature text
QString text = document()->toPlainText();
int currentMatch = text.indexOf( oldSigText, currentSearchPosition );
currentSearchPosition = currentMatch;
if ( currentMatch == -1 )
break;
// Select the signature
QTextCursor cursor( document() );
cursor.setPosition( currentMatch );
// If the new signature is completely empty, we also want to remove the
// signature separator, so include it in the selection
int additionalMove = 0;
if ( newSig.rawText().isEmpty() &&
text.mid( currentMatch - 4, 4) == "-- \n" ) {
cursor.movePosition( QTextCursor::PreviousCharacter,
QTextCursor::MoveAnchor, 4 );
additionalMove = 4;
}
cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
oldSigText.length() + additionalMove );
// Skip quoted signatures
if ( cursor.block().text().startsWith( quotePrefixName() ) ) {
currentSearchPosition += d->plainSignatureText( oldSig ).length();
continue;
}
// Remove the old and instert the new signature
cursor.removeSelectedText();
if ( newSig.isInlinedHtml() &&
newSig.type() == KPIMIdentities::Signature::Inlined ) {
cursor.insertHtml( newSig.rawText() );
d->activateRichText();
}
else
cursor.insertText( newSig.rawText() );
currentSearchPosition += d->plainSignatureText( newSig ).length();
}
cursor.endEditBlock();
}
void KMeditor::switchToPlainText()
{
if ( d->mMode == Rich ) {
d->mMode = Plain;
// TODO: Warn the user about this?
document()->setPlainText( document()->toPlainText() );
setAcceptRichText( false );
emit textModeChanged( d->mMode );
}
}
void KMeditor::enableRichTextMode()
{
d->activateRichText();
}
KMeditor::Mode KMeditor::textMode() const
{
return d->mMode;
}
QString KMeditor::textOrHTML() const
{
if ( textMode() == Rich )
return toHtml();
else
return toPlainText();
}
void KMeditor::setSpellCheckLanguage( const QString &language )
{
if ( KTextEdit::highlighter() ) {
d->replacements.clear();
KTextEdit::highlighter()->setCurrentLanguage( language );
KTextEdit::highlighter()->rehighlight();
}
#if KDE_IS_VERSION(4,0,60)
KTextEdit::setSpellCheckingLanguage( language );
#endif
if ( language != d->language )
emit spellcheckLanguageChanged( language );
d->language = language;
}
void KMeditor::slotCheckSpelling()
{
KTextEdit::checkSpelling();
}
bool KMeditor::isSpellCheckingEnabled() const
{
return d->spellCheckingEnabled;
}
void KMeditor::toggleSpellChecking( bool on )
{
KEMailQuotingHighlighter *hlighter =
dynamic_cast<KEMailQuotingHighlighter*>( KTextEdit::highlighter() );
if ( hlighter )
hlighter->toggleSpellHighlighting( on );
if ( !on )
d->replacements.clear();
d->spellCheckingEnabled = on;
}
void KMeditor::showSpellConfigDialog( const QString &configFileName )
{
KConfig config( configFileName );
Sonnet::ConfigDialog dialog( &config, this );
#if KDE_IS_VERSION(4,0,67)
if ( !d->language.isEmpty() )
dialog.setLanguage( d->language );
connect( &dialog, SIGNAL( languageChanged(const QString &) ),
this, SLOT( setSpellCheckLanguage(const QString &) ) );
#endif
dialog.setWindowIcon( KIcon( "internet-mail" ) );
dialog.exec();
}
QString KMeditor::toWrappedPlainText() const
{
QString temp;
QTextDocument* doc = document();
QTextBlock block = doc->begin();
while ( block.isValid() ) {
QTextLayout* layout = block.layout();
for ( int i = 0; i < layout->lineCount(); i++ ) {
QTextLine line = layout->lineAt( i );
temp += block.text().mid( line.textStart(), line.textLength() ) + '\n';
}
block = block.next();
}
return temp;
}
void KMeditor::ensureCursorVisible()
{
QCoreApplication::processEvents();
// Hack: In KMail, the layout of the composer changes again after
// creating the editor (the toolbar/menubar creation is delayed), so
// the size of the editor changes as well, possibly hiding the cursor
// even though we called ensureCursorVisible() before the layout phase.
//
// Delay the actual call to ensureCursorVisible() a bit to work around
// the problem.
QTimer::singleShot( 500, this, SLOT( ensureCursorVisibleDelayed() ) );
}
QString KMeditor::currentLinkText() const
{
QTextCursor cursor = textCursor();
d->selectLinkText(&cursor);
return cursor.selectedText();
}
void KMeditorPrivate::selectLinkText(QTextCursor *cursor) const
{
// If the cursor is on a link, select the text of the link.
if (cursor->charFormat().isAnchor()) {
QString aHref = cursor->charFormat().anchorHref();
// Move cursor to start of link
while (cursor->charFormat().anchorHref() == aHref) {
if (cursor->atStart())
break;
cursor->setPosition(cursor->position() - 1);
}
if (cursor->charFormat().anchorHref() != aHref)
cursor->setPosition(cursor->position() + 1, QTextCursor::KeepAnchor);
// Move selection to the end of the link
while (cursor->charFormat().anchorHref() == aHref) {
if (cursor->atEnd())
break;
cursor->setPosition(cursor->position() + 1, QTextCursor::KeepAnchor);
}
if (cursor->charFormat().anchorHref() != aHref)
cursor->setPosition(cursor->position() - 1, QTextCursor::KeepAnchor);
}
}
QString KMeditor::currentLinkUrl() const
{
return textCursor().charFormat().anchorHref();
}
void KMeditor::slotConfigureLink()
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
QTextCharFormat format = cursor.charFormat();
d->selectLinkText(&cursor);
if (!cursor.hasSelection()) {
cursor.select(QTextCursor::WordUnderCursor);
}
setTextCursor(cursor);
KLinkDialog *linkDialog = new KLinkDialog(this);
linkDialog->setLinkText(cursor.selectedText());
linkDialog->setLinkUrl(format.anchorHref());
if (linkDialog->exec()) {
if (!linkDialog->linkUrl().isEmpty()) {
format.setAnchor(true);
format.setAnchorHref(linkDialog->linkUrl());
}
else {
format = cursor.block().charFormat();
format.setAnchor(false);
format.setAnchorHref(QString());
}
QString linkText;
int lowPos = qMin(cursor.selectionStart(), cursor.selectionEnd());
if (!linkDialog->linkText().isEmpty()) {
linkText = linkDialog->linkText();
}
else {
linkText = linkDialog->linkUrl();
}
cursor.insertText(linkText, format);
// Workaround for qt bug 203510:
// Link formatting does not get applied immediately. Removing and reinserting
// the marked up html does format the text correctly.
// -- Stephen Kelly, 15th March 2008
cursor.setPosition(lowPos);
cursor.setPosition(lowPos + linkText.length(), QTextCursor::KeepAnchor);
cursor.insertHtml(cursor.selection().toHtml());
// Insert a space after the link if at the end of the block so that
// typing some text after the link does not carry link formatting
if (cursor.position() == cursor.block().position() + cursor.block().length() - 1) {
cursor.setCharFormat(cursor.block().charFormat());
cursor.insertText(QString(' '));
}
d->activateRichText();
}
cursor.endEditBlock();
delete linkDialog;
}
#include "kmeditor.moc"
Don't select a word when right-clicking it, only select it when it is
misspellt.
svn path=/trunk/KDE/kdepim/; revision=802994
/**
* kmeditor.cpp
*
* Copyright 2007 Laurent Montel <montel@kde.org>
* Copyright 2008 Thomas McGuire <thomas.mcguire@gmx.net>
* Copyright 2008 Stephen Kelly <steveire@gmail.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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "kmeditor.h"
#include "kemailquotinghighter.h"
#include "kmutils.h"
#include "klinkdialog.h"
#include <maillistdrag.h>
//kdepimlibs includes
#include <kpimidentities/signature.h>
//kdelibs includes
#include <kdebug.h>
#include <kdeversion.h>
#include <kfind.h>
#include <kreplace.h>
#include <kreplacedialog.h>
#include <kfinddialog.h>
#include <KWindowSystem>
#include <KFindDialog>
#include <KColorDialog>
#include <KFileDialog>
#include <KComboBox>
#include <KToolBar>
#include <KCharsets>
#include <KPushButton>
#include <klocale.h>
#include <kmenu.h>
#include <KMessageBox>
#include <KDirWatch>
#include <KTemporaryFile>
#include <KCursor>
#include <sonnet/configdialog.h>
//qt includes
#include <QApplication>
#include <QClipboard>
#include <QShortcut>
#include <QPointer>
#include <QTextCodec>
#include <QTextList>
#include <QTextDocumentFragment>
#include <QAction>
#include <QProcess>
#include <QTextLayout>
#include <QTimer>
//system includes
#include <assert.h>
namespace KPIM {
class KMeditorPrivate
{
public:
KMeditorPrivate( KMeditor *parent )
: q( parent ),
useExtEditor( false ),
mExtEditorProcess( 0 ),
mExtEditorTempFileWatcher( 0 ),
mExtEditorTempFile( 0 ),
mMode( KMeditor::Plain )
{
}
~KMeditorPrivate()
{
}
//
// Slots
//
void addSuggestion( const QString&,const QStringList& );
// Just calls KTextEdit::ensureCursorVisible(), workaround for some bug.
void ensureCursorVisibleDelayed();
//
// Normal functions
//
// If the text under the cursor is a link, the cursor's selection is set to
// the complete link text.
void selectLinkText( QTextCursor *cursor ) const;
QString addQuotesToText( const QString &inputText );
QString removeQuotesFromText( const QString &inputText ) const;
void init();
// Switches to rich text mode and emits the mode changed signal if the
// mode really changed.
void activateRichText();
// Applies formatting to the current word if there is no selection.
void mergeFormatOnWordOrSelection( const QTextCharFormat &format );
// Returns the text of the signature. If the signature is HTML, the HTML
// tags will be stripped.
QString plainSignatureText( const KPIMIdentities::Signature &signature ) const;
// Replaces each text which matches the regular expression with another text.
// Text inside quotes or the given signature will be ignored.
void cleanWhitespaceHelper( const QRegExp ®Exp, const QString &newText,
const KPIMIdentities::Signature &sig );
// Returns a list of positions of occurences of the given signature.
// Each pair is the index of the start- and end position of the signature.
QList< QPair<int,int> > signaturePositions( const KPIMIdentities::Signature &sig ) const;
// Data members
QMap<QString,QStringList> replacements;
QString extEditorPath;
QString language;
KMeditor *q;
bool useExtEditor;
bool spellCheckingEnabled;
QProcess *mExtEditorProcess;
KDirWatch *mExtEditorTempFileWatcher;
KTemporaryFile *mExtEditorTempFile;
KMeditor::Mode mMode;
};
}
using namespace KPIM;
void KMeditorPrivate::activateRichText()
{
if ( mMode == KMeditor::Plain ) {
q->setAcceptRichText( true );
mMode = KMeditor::Rich;
emit q->textModeChanged( mMode );
}
}
QList< QPair<int,int> > KMeditorPrivate::signaturePositions( const KPIMIdentities::Signature &sig ) const
{
QList< QPair<int,int> > signaturePositions;
if ( !sig.rawText().isEmpty() ) {
QString sigText = plainSignatureText( sig );
int currentSearchPosition = 0;
forever {
// Find the next occurence of the signature text
QString text = q->document()->toPlainText();
int currentMatch = text.indexOf( sigText, currentSearchPosition );
currentSearchPosition = currentMatch + sigText.length();
if ( currentMatch == -1 )
break;
signaturePositions.append( QPair<int,int>( currentMatch,
currentMatch + sigText.length() ) );
}
}
return signaturePositions;
}
void KMeditorPrivate::cleanWhitespaceHelper( const QRegExp ®Exp,
const QString &newText,
const KPIMIdentities::Signature &sig )
{
int currentSearchPosition = 0;
forever {
// Find the text
QString text = q->document()->toPlainText();
int currentMatch = regExp.indexIn( text, currentSearchPosition );
currentSearchPosition = currentMatch;
if ( currentMatch == -1 )
break;
// Select the text
QTextCursor cursor( q->document() );
cursor.setPosition( currentMatch );
cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
regExp.matchedLength() );
// Skip quoted text
if ( cursor.block().text().startsWith( q->quotePrefixName() ) ) {
currentSearchPosition += regExp.matchedLength();
continue;
}
// Skip text inside signatures
bool insideSignature = false;
QList< QPair<int,int> > sigPositions = signaturePositions( sig );
QPair<int,int> position;
foreach( position, sigPositions ) {
if ( cursor.position() >= position.first &&
cursor.position() <= position.second )
insideSignature = true;
}
if ( insideSignature ) {
currentSearchPosition += regExp.matchedLength();
continue;
}
// Replace the text
cursor.removeSelectedText();
cursor.insertText( newText );
currentSearchPosition += newText.length();
}
}
QString KMeditorPrivate::plainSignatureText( const KPIMIdentities::Signature &signature ) const
{
QString sigText = signature.rawText();
if ( signature.isInlinedHtml() &&
signature.type() == KPIMIdentities::Signature::Inlined ) {
// Use a QTextDocument as a helper, it does all the work for us and
// strips all HTML tags.
QTextDocument helper;
QTextCursor helperCursor( &helper );
helperCursor.insertHtml( sigText );
sigText = helper.toPlainText();
}
return sigText;
}
void KMeditorPrivate::addSuggestion( const QString& originalWord,
const QStringList& lst )
{
replacements[originalWord] = lst;
}
void KMeditorPrivate::ensureCursorVisibleDelayed()
{
static_cast<KTextEdit*>( q )->ensureCursorVisible();
}
void KMeditorPrivate::mergeFormatOnWordOrSelection( const QTextCharFormat &format )
{
QTextCursor cursor = q->textCursor();
if ( !cursor.hasSelection() )
cursor.select( QTextCursor::WordUnderCursor );
cursor.mergeCharFormat( format );
q->mergeCurrentCharFormat( format );
}
void KMeditor::dragEnterEvent( QDragEnterEvent *e )
{
if ( KPIM::MailList::canDecode( e->mimeData() ) ) {
e->setAccepted( true );
} else if ( e->mimeData()->hasFormat( "image/png" ) ) {
e->accept();
} else {
return KTextEdit::dragEnterEvent( e );
}
}
void KMeditor::dragMoveEvent( QDragMoveEvent *e )
{
if ( KPIM::MailList::canDecode( e->mimeData() ) ) {
e->accept();
} else if ( e->mimeData()->hasFormat( "image/png" ) ) {
e->accept();
} else {
return KTextEdit::dragMoveEvent( e );
}
}
void KMeditor::paste()
{
if ( !QApplication::clipboard()->image().isNull() ) {
emit pasteImage();
}
else
KTextEdit::paste();
}
void KMeditor::keyPressEvent ( QKeyEvent * e )
{
if ( e->key() == Qt::Key_Return ) {
QTextCursor cursor = textCursor();
int oldPos = cursor.position();
int blockPos = cursor.block().position();
//selection all the line.
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString lineText = cursor.selectedText();
if ( ( ( oldPos -blockPos ) > 0 ) &&
( ( oldPos-blockPos ) < int( lineText.length() ) ) ) {
bool isQuotedLine = false;
int bot = 0; // bot = begin of text after quote indicators
while ( bot < lineText.length() ) {
if( ( lineText[bot] == '>' ) || ( lineText[bot] == '|' ) ) {
isQuotedLine = true;
++bot;
}
else if ( lineText[bot].isSpace() ) {
++bot;
}
else {
break;
}
}
KTextEdit::keyPressEvent( e );
// duplicate quote indicators of the previous line before the new
// line if the line actually contained text (apart from the quote
// indicators) and the cursor is behind the quote indicators
if ( isQuotedLine
&& ( bot != lineText.length() )
&& ( ( oldPos-blockPos ) >= int( bot ) ) ) {
// The cursor position might have changed unpredictably if there was selected
// text which got replaced by a new line, so we query it again:
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString newLine = cursor.selectedText();
// remove leading white space from the new line and instead
// add the quote indicators of the previous line
int leadingWhiteSpaceCount = 0;
while ( ( leadingWhiteSpaceCount < newLine.length() )
&& newLine[leadingWhiteSpaceCount].isSpace() ) {
++leadingWhiteSpaceCount;
}
newLine = newLine.replace( 0, leadingWhiteSpaceCount,
lineText.left( bot ) );
cursor.insertText( newLine );
//cursor.setPosition( cursor.position() + 2);
cursor.movePosition( QTextCursor::StartOfBlock );
setTextCursor( cursor );
}
}
else
KTextEdit::keyPressEvent( e );
}
else if ( e->key() == Qt::Key_Up && e->modifiers() != Qt::ShiftModifier &&
textCursor().block().position() == 0 &&
textCursor().position() <
textCursor().block().layout()->lineAt( 0 ).textLength() )
{
textCursor().clearSelection();
emit focusUp();
}
else if ( e->key() == Qt::Key_Backtab && e->modifiers() == Qt::ShiftModifier )
{
textCursor().clearSelection();
emit focusUp();
}
else
{
KTextEdit::keyPressEvent( e );
}
}
KMeditor::KMeditor( const QString& text, QWidget *parent )
: KTextEdit( text, parent ), d( new KMeditorPrivate( this ) )
{
d->init();
}
KMeditor::KMeditor( QWidget *parent )
: KTextEdit( parent ), d( new KMeditorPrivate( this ) )
{
d->init();
}
KMeditor::~KMeditor()
{
delete d;
}
bool KMeditor::eventFilter( QObject*o, QEvent* e )
{
if (o == this)
KCursor::autoHideEventFilter( o, e );
return KTextEdit::eventFilter( o, e );
}
void KMeditorPrivate::init()
{
// We tell the KTextEdit to enable spell checking, because only then it will
// call createHighlighter() which will create our own highlighter which also
// does quote highlighting.
// However, *our* spellchecking is still disabled. Our own highlighter only
// cares about our spellcheck status, it will not highlight missspellt words
// if our spellchecking is disabled.
// See also KEMailQuotingHighlighter::highlightBlock().
spellCheckingEnabled = false;
static_cast<KTextEdit*>( q )->setCheckSpellingEnabled( true );
KCursor::setAutoHideCursor( q, true, true );
q->installEventFilter( q );
QShortcut * insertMode = new QShortcut( QKeySequence( Qt::Key_Insert ), q );
q->connect( insertMode, SIGNAL( activated() ),
q, SLOT( slotChangeInsertMode() ) );
#if KDE_IS_VERSION(4,0,67)
q->connect( q, SIGNAL( languageChanged(const QString &) ),
q, SLOT( setSpellCheckLanguage(const QString &) ) );
#endif
}
void KMeditor::slotChangeInsertMode()
{
setOverwriteMode( !overwriteMode() );
emit overwriteModeText();
}
void KMeditor::createHighlighter()
{
KPIM::KEMailQuotingHighlighter *emailHighLighter =
new KPIM::KEMailQuotingHighlighter( this );
changeHighlighterColors( emailHighLighter );
connect( emailHighLighter, SIGNAL( newSuggestions(const QString&,const QStringList&) ),
this, SLOT( addSuggestion(const QString&,const QStringList&) ) );
//TODO change config
KTextEdit::setHighlighter( emailHighLighter );
if ( !d->language.isEmpty() )
setSpellCheckLanguage( d->language );
toggleSpellChecking( d->spellCheckingEnabled );
}
void KMeditor::changeHighlighterColors(KPIM::KEMailQuotingHighlighter *)
{
}
void KMeditor::setUseExternalEditor( bool use )
{
d->useExtEditor = use;
}
void KMeditor::setExternalEditorPath( const QString & path )
{
d->extEditorPath = path;
}
void KMeditor::slotChangeParagStyle( QTextListFormat::Style _style )
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
// Create a list with the specified format
if ( _style != QTextListFormat::ListStyleUndefined ) {
QTextBlockFormat blockFmt = cursor.blockFormat();
QTextListFormat listFmt;
if ( cursor.currentList() ) {
listFmt = cursor.currentList()->format();
} else {
listFmt.setIndent( blockFmt.indent() + 1 );
blockFmt.setIndent( 0 );
cursor.setBlockFormat( blockFmt );
}
listFmt.setStyle( _style );
cursor.createList( listFmt );
d->activateRichText();
}
// Remove the list formatting again
else {
QTextList *list = cursor.currentList();
if ( list ) {
QTextListFormat listFormat = list->format();
listFormat.setIndent( 0 );
list->setFormat( listFormat );
int count = list->count();
while ( count > 0 ) {
list->removeItem( 0 );
count--;
}
}
}
cursor.endEditBlock();
setFocus();
}
void KMeditor::setColor( const QColor& col )
{
QTextCharFormat fmt;
fmt.setForeground( col );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::setFont( const QFont &font )
{
QTextCharFormat fmt;
fmt.setFont( font );
d->mergeFormatOnWordOrSelection( fmt );
}
void KMeditor::setFontForWholeText( const QFont &font )
{
QTextCharFormat fmt;
fmt.setFont( font );
QTextCursor cursor( document() );
cursor.movePosition( QTextCursor::End, QTextCursor::KeepAnchor );
cursor.mergeCharFormat( fmt );
document()->setDefaultFont( font );
}
void KMeditor::slotAlignLeft()
{
setAlignment( Qt::AlignLeft );
d->activateRichText();
}
void KMeditor::slotAlignCenter()
{
setAlignment( Qt::AlignHCenter );
d->activateRichText();
}
void KMeditor::slotAlignRight()
{
setAlignment( Qt::AlignRight );
d->activateRichText();
}
void KMeditor::slotTextBold( bool _b )
{
QTextCharFormat fmt;
fmt.setFontWeight( _b ? QFont::Bold : QFont::Normal );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextItalic( bool _b)
{
QTextCharFormat fmt;
fmt.setFontItalic( _b );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextUnder( bool _b )
{
QTextCharFormat fmt;
fmt.setFontUnderline( _b );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
void KMeditor::slotTextColor()
{
QColor color = textColor();
if ( KColorDialog::getColor( color, this ) ) {
QTextCharFormat fmt;
fmt.setForeground( color );
d->mergeFormatOnWordOrSelection( fmt );
d->activateRichText();
}
}
void KMeditor::slotFontFamilyChanged( const QString &f )
{
QTextCharFormat fmt;
fmt.setFontFamily( f );
d->mergeFormatOnWordOrSelection( fmt );
setFocus();
d->activateRichText();
}
void KMeditor::slotFontSizeChanged( int size )
{
QTextCharFormat fmt;
fmt.setFontPointSize( size );
d->mergeFormatOnWordOrSelection( fmt );
setFocus();
d->activateRichText();
}
KUrl KMeditor::insertFile( const QStringList &encodingLst, QString &encodingStr )
{
KUrl url;
KFileDialog fdlg( url, QString(), this );
fdlg.setOperationMode( KFileDialog::Opening );
fdlg.okButton()->setText( i18n( "&Insert" ) );
fdlg.setCaption( i18n( "Insert File" ) );
if ( !encodingLst.isEmpty() )
{
KComboBox *combo = new KComboBox( this );
combo->addItems( encodingLst );
fdlg.toolBar()->addWidget( combo );
for ( int i = 0; i < combo->count(); i++ )
if ( KGlobal::charsets()->codecForName( KGlobal::charsets()->
encodingForName( combo->itemText( i ) ) )
== QTextCodec::codecForLocale() )
combo->setCurrentIndex(i);
encodingStr = combo->currentText();
}
if ( !fdlg.exec() )
return KUrl();
KUrl u = fdlg.selectedUrl();
return u;
}
void KMeditor::enableWordWrap( int wrapColumn )
{
setWordWrapMode( QTextOption::WordWrap );
setLineWrapMode( QTextEdit::FixedColumnWidth );
setLineWrapColumnOrWidth( wrapColumn );
}
void KMeditor::disableWordWrap()
{
setLineWrapMode( QTextEdit::WidgetWidth );
}
void KMeditor::contextMenuEvent( QContextMenuEvent *event )
{
// Obtain the cursor at the mouse position and the current cursor
QTextCursor cursorAtMouse = cursorForPosition( event->pos() );
int mousePos = cursorAtMouse.position();
QTextCursor cursor = textCursor();
// Check if the user clicked a selected word
bool selectedWordClicked = cursor.hasSelection() &&
mousePos >= cursor.selectionStart() &&
mousePos <= cursor.selectionEnd();
// Get the word under the (mouse-)cursor and see if it is misspellt
QTextCursor wordSelectCursor( cursorAtMouse );
wordSelectCursor.clearSelection();
wordSelectCursor.select( QTextCursor::WordUnderCursor );
QString selectedWord = wordSelectCursor.selectedText();
bool wordIsMisspellt = !selectedWord.isEmpty() &&
d->replacements.contains ( selectedWord );
// If the user clicked a selected word, do nothing.
// If the user clicked somewhere else, move the cursor there.
// If the user clicked on a misspellt word, select that word.
// Same behavior as in OpenOffice Writer.
if ( !selectedWordClicked ) {
if ( wordIsMisspellt )
setTextCursor( wordSelectCursor );
else
setTextCursor( cursorAtMouse );
cursor = textCursor();
}
// Use standard context menu for normal words and our own for misspellt words
if ( !wordIsMisspellt || selectedWordClicked ) {
KTextEdit::contextMenuEvent( event );
}
else {
KMenu p;
p.addTitle( i18n( "Suggestions" ) );
//Add the suggestions to the popup menu
QStringList reps = d->replacements[selectedWord];
if ( reps.count() > 0 ) {
for ( QStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {
p.addAction( *it );
}
}
else {
p.addAction( i18n( "No Suggestions" ) );
}
//Execute the popup inline
const QAction *selectedAction = p.exec( mapToGlobal( event->pos() ) );
if ( selectedAction && ( reps.count() > 0 ) ) {
const QString replacement = selectedAction->text();
Q_ASSERT( cursor.selectedText() == selectedWord );
cursor.insertText( replacement );
setTextCursor( cursor );
}
}
}
void KMeditor::slotPasteAsQuotation()
{
if ( hasFocus() ) {
QString s = QApplication::clipboard()->text();
if ( !s.isEmpty() ) {
insertPlainText( d->addQuotesToText( s ) );
}
}
}
void KMeditor::slotRemoveQuotes()
{
// TODO: I think this is backwards.
// i.e, if no region is marked then remove quotes from every line
// else remove quotes only on the lines that are marked.
QTextCursor cursor = textCursor();
if(cursor.hasSelection())
{
QString s = cursor.selectedText();
insertPlainText( d->removeQuotesFromText( s ) );
}
else
{
int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
if ( !s.isEmpty() )
{
cursor.insertText( d->removeQuotesFromText( s ) );
cursor.setPosition( qMax( 0, oldPos - 2 ) );
setTextCursor( cursor );
}
}
}
void KMeditor::slotAddQuotes()
{
// TODO: I think this is backwards.
// i.e, if no region is marked then add quotes to every line
// else add quotes only on the lines that are marked.
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
{
QString s = cursor.selectedText();
if ( !s.isEmpty() ) {
cursor.insertText( d->addQuotesToText( s ) );
setTextCursor( cursor );
}
}
else {
int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
cursor.insertText( d->addQuotesToText( s ) );
cursor.setPosition( oldPos + 2 ); //FIXME: 2 probably wrong
setTextCursor( cursor );
}
}
QString KMeditorPrivate::removeQuotesFromText( const QString &inputText ) const
{
QString s = inputText;
// remove first leading quote
QString quotePrefix = '^' + q->quotePrefixName();
QRegExp rx( quotePrefix );
s.remove( rx );
// now remove all remaining leading quotes
quotePrefix = QString( QChar::ParagraphSeparator ) + ' ' + q->quotePrefixName();
QRegExp srx( quotePrefix );
s.remove( srx );
return s;
}
QString KMeditorPrivate::addQuotesToText( const QString &inputText )
{
QString answer = QString( inputText );
QString indentStr = q->quotePrefixName();
answer.replace( '\n', '\n' + indentStr );
//cursor.selectText() as QChar::ParagraphSeparator as paragraph separator.
answer.replace( QChar::ParagraphSeparator, '\n' + indentStr );
answer.prepend( indentStr );
answer += '\n';
return q->smartQuote( answer );
}
QString KMeditor::smartQuote( const QString & msg )
{
return msg;
}
QString KMeditor::quotePrefixName() const
{
//Need to redefine into each apps
return "> ";
}
bool KMeditor::checkExternalEditorFinished()
{
if ( !d->mExtEditorProcess )
return true;
switch ( KMessageBox::warningYesNoCancel( topLevelWidget(),
i18n("The external editor is still running.\n"
"Abort the external editor or leave it open?"),
i18n("External Editor"),
KGuiItem( i18n("Abort Editor") ),
KGuiItem( i18n("Leave Editor Open") ) ) ) {
case KMessageBox::Yes:
killExternalEditor();
return true;
case KMessageBox::No:
return true;
default:
return false;
}
}
void KMeditor::killExternalEditor()
{
delete d->mExtEditorProcess;
d->mExtEditorProcess = 0;
delete d->mExtEditorTempFileWatcher;
d->mExtEditorTempFileWatcher = 0;
delete d->mExtEditorTempFile;
d->mExtEditorTempFile = 0;
}
void KMeditor::setCursorPositionFromStart( unsigned int pos )
{
if ( pos > 0 )
{
QTextCursor cursor = textCursor();
cursor.setPosition( pos );
setTextCursor( cursor );
ensureCursorVisible();
}
}
void KMeditor::slotRemoveBox()
{
//Laurent: fix me
#if 0
if (hasMarkedText()) {
QString s = QString::fromLatin1("\n") + markedText() + QString::fromLatin1("\n");
s.replace(QRegExp("\n,----[^\n]*\n"),"\n");
s.replace(QRegExp("\n| "),"\n");
s.replace(QRegExp("\n`----[^\n]*\n"),"\n");
s.remove(0,1);
s.truncate(s.length()-1);
insert(s);
} else {
int l = currentLine();
int c = currentColumn();
QString s = textLine(l); // test if we are in a box
if (!((s.left(2) == "| ")||(s.left(5)==",----")||(s.left(5)=="`----")))
return;
setAutoUpdate(false);
// find & remove box begin
int x = l;
while ((x>=0)&&(textLine(x).left(5)!=",----"))
x--;
if ((x>=0)&&(textLine(x).left(5)==",----")) {
removeLine(x);
l--;
for (int i=x;i<=l;i++) { // remove quotation
s = textLine(i);
if (s.left(2) == "| ") {
s.remove(0,2);
insertLine(s,i);
removeLine(i+1);
}
}
}
// find & remove box end
x = l;
while ((x<numLines())&&(textLine(x).left(5)!="`----"))
x++;
if ((x<numLines())&&(textLine(x).left(5)=="`----")) {
removeLine(x);
for (int i=l+1;i<x;i++) { // remove quotation
s = textLine(i);
if (s.left(2) == "| ") {
s.remove(0,2);
insertLine(s,i);
removeLine(i+1);
}
}
}
setCursorPosition(l,c-2);
setAutoUpdate(true);
repaint();
}
#endif
}
void KMeditor::slotAddBox()
{
//Laurent fixme
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
{
QString s = cursor.selectedText();
s.prepend( ",----[ ]\n" );
s.replace( QRegExp("\n"),"\n| " );
s.append( "\n`----" );
insertPlainText( s );
} else {
//int oldPos = cursor.position();
cursor.movePosition( QTextCursor::StartOfBlock );
cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );
QString s = cursor.selectedText();
QString str = QString::fromLatin1(",----[ ]\n| %1\n`----").arg(s);
cursor.insertText( str );
//cursor.setPosition( qMax( 0, oldPos - 2 ) );
setTextCursor( cursor );
}
}
int KMeditor::linePosition()
{
QTextCursor cursor = textCursor();
return cursor.blockNumber();
}
int KMeditor::columnNumber()
{
QTextCursor cursor = textCursor();
return cursor.columnNumber();
}
void KMeditor::slotRot13()
{
QTextCursor cursor = textCursor();
if ( cursor.hasSelection() )
insertPlainText( KMUtils::rot13( cursor.selectedText() ) );
//FIXME: breaks HTML formatting
}
void KMeditor::setCursorPosition( int linePos, int columnPos )
{
//TODO
Q_UNUSED( linePos );
Q_UNUSED( columnPos );
}
void KMeditor::cleanWhitespace( const KPIMIdentities::Signature &sig )
{
QTextCursor cursor( document() );
cursor.beginEditBlock();
// Squeeze tabs and spaces
d->cleanWhitespaceHelper( QRegExp( "[\t ]+" ), QString( ' ' ), sig );
// Remove trailing whitespace
d->cleanWhitespaceHelper( QRegExp( "[\t ][\n]" ), QString( '\n' ), sig );
// Single space lines
d->cleanWhitespaceHelper( QRegExp( "[\n]{3,}" ), "\n\n", sig );
if ( !textCursor().hasSelection() ) {
textCursor().clearSelection();
}
cursor.endEditBlock();
}
void KMeditor::insertSignature( const KPIMIdentities::Signature &sig,
Placement placement, bool addSeparator )
{
QString signature;
if ( addSeparator )
signature = sig.withSeparator();
else
signature = sig.rawText();
insertSignature( signature, placement,
( sig.isInlinedHtml() &&
sig.type() == KPIMIdentities::Signature::Inlined ) );
}
void KMeditor::insertSignature( const QString &signature, Placement placement,
bool isHtml )
{
if ( !signature.isEmpty() ) {
// Save the modified state of the document, as inserting a signature
// shouldn't change this. Restore it at the end of this function.
bool isModified = document()->isModified();
// Move to the desired position, where the signature should be inserted
QTextCursor cursor = textCursor();
QTextCursor oldCursor = cursor;
cursor.beginEditBlock();
if ( placement == End )
cursor.movePosition( QTextCursor::End );
else if ( placement == Start )
cursor.movePosition( QTextCursor::Start );
setTextCursor( cursor );
// Insert the signature and newlines depending on where it was inserted.
if ( placement == End ) {
if ( isHtml ) {
insertHtml( "<br>" + signature );
} else {
insertPlainText( '\n' + signature );
}
} else if ( placement == Start || placement == AtCursor ) {
if ( isHtml ) {
insertHtml( "<br>" + signature + "<br>" );
} else {
insertPlainText( '\n' + signature + '\n' );
}
}
cursor.endEditBlock();
setTextCursor( oldCursor );
ensureCursorVisible();
document()->setModified( isModified );
if ( isHtml )
d->activateRichText();
}
}
void KMeditor::replaceSignature( const KPIMIdentities::Signature &oldSig,
const KPIMIdentities::Signature &newSig )
{
QTextCursor cursor( document() );
cursor.beginEditBlock();
QString oldSigText = d->plainSignatureText( oldSig );
int currentSearchPosition = 0;
forever {
// Find the next occurence of the signature text
QString text = document()->toPlainText();
int currentMatch = text.indexOf( oldSigText, currentSearchPosition );
currentSearchPosition = currentMatch;
if ( currentMatch == -1 )
break;
// Select the signature
QTextCursor cursor( document() );
cursor.setPosition( currentMatch );
// If the new signature is completely empty, we also want to remove the
// signature separator, so include it in the selection
int additionalMove = 0;
if ( newSig.rawText().isEmpty() &&
text.mid( currentMatch - 4, 4) == "-- \n" ) {
cursor.movePosition( QTextCursor::PreviousCharacter,
QTextCursor::MoveAnchor, 4 );
additionalMove = 4;
}
cursor.movePosition( QTextCursor::NextCharacter, QTextCursor::KeepAnchor,
oldSigText.length() + additionalMove );
// Skip quoted signatures
if ( cursor.block().text().startsWith( quotePrefixName() ) ) {
currentSearchPosition += d->plainSignatureText( oldSig ).length();
continue;
}
// Remove the old and instert the new signature
cursor.removeSelectedText();
if ( newSig.isInlinedHtml() &&
newSig.type() == KPIMIdentities::Signature::Inlined ) {
cursor.insertHtml( newSig.rawText() );
d->activateRichText();
}
else
cursor.insertText( newSig.rawText() );
currentSearchPosition += d->plainSignatureText( newSig ).length();
}
cursor.endEditBlock();
}
void KMeditor::switchToPlainText()
{
if ( d->mMode == Rich ) {
d->mMode = Plain;
// TODO: Warn the user about this?
document()->setPlainText( document()->toPlainText() );
setAcceptRichText( false );
emit textModeChanged( d->mMode );
}
}
void KMeditor::enableRichTextMode()
{
d->activateRichText();
}
KMeditor::Mode KMeditor::textMode() const
{
return d->mMode;
}
QString KMeditor::textOrHTML() const
{
if ( textMode() == Rich )
return toHtml();
else
return toPlainText();
}
void KMeditor::setSpellCheckLanguage( const QString &language )
{
if ( KTextEdit::highlighter() ) {
d->replacements.clear();
KTextEdit::highlighter()->setCurrentLanguage( language );
KTextEdit::highlighter()->rehighlight();
}
#if KDE_IS_VERSION(4,0,60)
KTextEdit::setSpellCheckingLanguage( language );
#endif
if ( language != d->language )
emit spellcheckLanguageChanged( language );
d->language = language;
}
void KMeditor::slotCheckSpelling()
{
KTextEdit::checkSpelling();
}
bool KMeditor::isSpellCheckingEnabled() const
{
return d->spellCheckingEnabled;
}
void KMeditor::toggleSpellChecking( bool on )
{
KEMailQuotingHighlighter *hlighter =
dynamic_cast<KEMailQuotingHighlighter*>( KTextEdit::highlighter() );
if ( hlighter )
hlighter->toggleSpellHighlighting( on );
if ( !on )
d->replacements.clear();
d->spellCheckingEnabled = on;
}
void KMeditor::showSpellConfigDialog( const QString &configFileName )
{
KConfig config( configFileName );
Sonnet::ConfigDialog dialog( &config, this );
#if KDE_IS_VERSION(4,0,67)
if ( !d->language.isEmpty() )
dialog.setLanguage( d->language );
connect( &dialog, SIGNAL( languageChanged(const QString &) ),
this, SLOT( setSpellCheckLanguage(const QString &) ) );
#endif
dialog.setWindowIcon( KIcon( "internet-mail" ) );
dialog.exec();
}
QString KMeditor::toWrappedPlainText() const
{
QString temp;
QTextDocument* doc = document();
QTextBlock block = doc->begin();
while ( block.isValid() ) {
QTextLayout* layout = block.layout();
for ( int i = 0; i < layout->lineCount(); i++ ) {
QTextLine line = layout->lineAt( i );
temp += block.text().mid( line.textStart(), line.textLength() ) + '\n';
}
block = block.next();
}
return temp;
}
void KMeditor::ensureCursorVisible()
{
QCoreApplication::processEvents();
// Hack: In KMail, the layout of the composer changes again after
// creating the editor (the toolbar/menubar creation is delayed), so
// the size of the editor changes as well, possibly hiding the cursor
// even though we called ensureCursorVisible() before the layout phase.
//
// Delay the actual call to ensureCursorVisible() a bit to work around
// the problem.
QTimer::singleShot( 500, this, SLOT( ensureCursorVisibleDelayed() ) );
}
QString KMeditor::currentLinkText() const
{
QTextCursor cursor = textCursor();
d->selectLinkText(&cursor);
return cursor.selectedText();
}
void KMeditorPrivate::selectLinkText(QTextCursor *cursor) const
{
// If the cursor is on a link, select the text of the link.
if (cursor->charFormat().isAnchor()) {
QString aHref = cursor->charFormat().anchorHref();
// Move cursor to start of link
while (cursor->charFormat().anchorHref() == aHref) {
if (cursor->atStart())
break;
cursor->setPosition(cursor->position() - 1);
}
if (cursor->charFormat().anchorHref() != aHref)
cursor->setPosition(cursor->position() + 1, QTextCursor::KeepAnchor);
// Move selection to the end of the link
while (cursor->charFormat().anchorHref() == aHref) {
if (cursor->atEnd())
break;
cursor->setPosition(cursor->position() + 1, QTextCursor::KeepAnchor);
}
if (cursor->charFormat().anchorHref() != aHref)
cursor->setPosition(cursor->position() - 1, QTextCursor::KeepAnchor);
}
}
QString KMeditor::currentLinkUrl() const
{
return textCursor().charFormat().anchorHref();
}
void KMeditor::slotConfigureLink()
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
QTextCharFormat format = cursor.charFormat();
d->selectLinkText(&cursor);
if (!cursor.hasSelection()) {
cursor.select(QTextCursor::WordUnderCursor);
}
setTextCursor(cursor);
KLinkDialog *linkDialog = new KLinkDialog(this);
linkDialog->setLinkText(cursor.selectedText());
linkDialog->setLinkUrl(format.anchorHref());
if (linkDialog->exec()) {
if (!linkDialog->linkUrl().isEmpty()) {
format.setAnchor(true);
format.setAnchorHref(linkDialog->linkUrl());
}
else {
format = cursor.block().charFormat();
format.setAnchor(false);
format.setAnchorHref(QString());
}
QString linkText;
int lowPos = qMin(cursor.selectionStart(), cursor.selectionEnd());
if (!linkDialog->linkText().isEmpty()) {
linkText = linkDialog->linkText();
}
else {
linkText = linkDialog->linkUrl();
}
cursor.insertText(linkText, format);
// Workaround for qt bug 203510:
// Link formatting does not get applied immediately. Removing and reinserting
// the marked up html does format the text correctly.
// -- Stephen Kelly, 15th March 2008
cursor.setPosition(lowPos);
cursor.setPosition(lowPos + linkText.length(), QTextCursor::KeepAnchor);
cursor.insertHtml(cursor.selection().toHtml());
// Insert a space after the link if at the end of the block so that
// typing some text after the link does not carry link formatting
if (cursor.position() == cursor.block().position() + cursor.block().length() - 1) {
cursor.setCharFormat(cursor.block().charFormat());
cursor.insertText(QString(' '));
}
d->activateRichText();
}
cursor.endEditBlock();
delete linkDialog;
}
#include "kmeditor.moc"
|
#include "Header.h"
void Isometric_Render::create_image(World_Map world)
{
}
void Isometric_Render::recursive_place(int curr_x, int curr_y, int curr_z) {
if (curr_x <= this->get_x()[1] && curr_x >= this->get_x()[0] &&
curr_y <= this->get_y()[1] && curr_y >= this->get_y()[0] &&
curr_z <= this->get_z()[1] && curr_z >= this->get_z()[0]) {
place_cube(curr_x, curr_y, curr_z);
this->recursive_place(curr_x + 1, curr_y, curr_z);
this->recursive_place(curr_x, curr_y + 1, curr_z);
this->recursive_place(curr_x, curr_y, curr_z + 1);
cout << "rec: curr_x: " << curr_x << " curr_y: " << curr_y << " curr_z: " << curr_z << " sum: " << curr_x+curr_y+curr_z<< endl;
}
}
void Isometric_Render::draw_line(int *x, int *y, RGBApixel * pixel) {
int x1 = x[0];
int x2 = x[1];
int y1 = y[0];
int y2 = y[1];
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if (steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = (float)(x2 - x1);
const float dy = (float)fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y_new = (int)y1;
const int maxX = (int)x2;
for (int x = (int)x1; x<maxX; x++)
{
if (steep)
{
RGBApixel* pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = 192;
pixel->Green = 192; //SILVER
pixel->Blue = 192;
this->bmp_image->SetPixel(y_new,x,*pixel);
for (int x_f = x; x < FACE_HEIGHT - (dy * 2) - 1; x_f++) {
}
}
else
{
RGBApixel* pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = 192;
pixel->Green = 192; //SILVER
pixel->Blue = 192;
this->bmp_image->SetPixel(x, y_new, *pixel);
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}
void Isometric_Render::place_cube(int x, int y, int z) {
int * xy = find_xy(x, y, z);
RGBApixel * pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = this->the_map->getpixel->r;
pixel->Blue = this->the_map->getpixel->b;
pixel->Green = this->the_map->getpixel->g;
int point_start[2];
int point_end_r[2];
int point_end_l[2];
int point_bottom[2];
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
int h_half = h / 2;
for (int i = 0; i < 2; i++) {
point_start[i] = xy[i];
}
//point_bottom[0] = xy[0];
//point_bottom[1] = xy[1] - h;
//draw_line(point_start, point_bottom);
point_end_r[0] = xy[0] + h_root;
point_end_r[1] = xy[1] + h_half;
point_end_l[0] = -point_end_r[0];
point_end_l[1] = point_end_r[1];
draw_line(point_start, point_end_r, pixel);
draw_line(point_start, point_end_l, pixel);
//point_start[1] = point_start[1] + h;
//draw_line(point_start, point_end_r);
//draw_line(point_start, point_end_l);
//point_bottom[0] = point_end_r[0];
//point_bottom[1] = point_end_r[1] - h;
//draw_line(point_bottom, point_end_r);
//point_end_r[0] = xy[0];
//point_end_r[1] = xy[1] - h;
//draw_line(point_end_r, point_bottom);
//point_bottom[0] = point_end_l[0];
//point_bottom[1] = point_end_l[1] - h;
//draw_line(point_bottom, point_end_l);
//draw_line(point_end_r, point_bottom);
free(xy);
}
int* Isometric_Render::find_xy(int x, int y, int z) {
int *x_y = (int*)malloc(sizeof(int)*2);
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
int h_half = h / 2;
//inititalize to 0,0,0
x_y[0] = (this->get_y()[1] - this->get_y()[0] + 1)*(h_root-1) + 0;
x_y[1] = h-1;
printf("initial: x:%d,y:%d\n", x_y[0], x_y[1]);
//add x components
if (x) {
x_y[0] += x*(h_root-1);
x_y[1] += x*h_half;
printf("x components: x:%d,y:%d\n", x_y[0], x_y[1]);
}
//add y components
if (y) {
x_y[0] -=y*(h_root-1);
x_y[1] += y*h_half;
printf("y components: x:%d,y:%d\n", x_y[0], x_y[1]);
}//add z components
if (z) {
x_y[0] += 0;
x_y[1] += z*(h-1);
printf("final/z components: x:%d,y:%d\n", x_y[0], x_y[1]);
}
printf("point_xyz (%d,%d,%d) moved to point_xy(%d,%d)\n",x,y,z,x_y[0],x_y[1]);
return x_y;
}
int * Isometric_Render::get_x() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->x_l;
result[1] = this->x_u;
return result;
}
int * Isometric_Render::get_y() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->y_l;
result[1] = this->y_u;
return result;
}
int * Isometric_Render::get_z() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->z_l;
result[1] = this->z_u;
return result;
}
void Isometric_Render::set_x(int low, int up) {
this->x_l = low;
this->x_u = up;
}
void Isometric_Render::set_y(int low, int up) {
this->y_l = low;
this->y_u = up;
}
void Isometric_Render::set_z(int low, int up) {
this->z_l = low;
this->z_u = up;
}
Isometric_Render::Isometric_Render(World_Map* _map, BMP *the_bmp_image, int xl, int xu, int yl, int yu, int zl, int zu) {
set_x(xl, xu);
set_y(yl, yu);
this->the_map = _map;
set_z(zl, zu);
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
this->bmp_image = the_bmp_image;
//int h_half = h / 2;
//int max_xy = (xu - xl + 1) > (yu - yl + 1) ? (xu - xl + 1) : (yu - yl + 1);
int * dimensions = this->find_xy((xu - xl + 1), (yu - yl + 1), (zu - zl + 1));
this->width = ((xu - xl + 1)+ (xu - xl + 1))*(h_root-1) + 1;
this->height = dimensions[1] - h + 1;
free(dimensions);
}
Isometric_Render::Isometric_Render() {}
Worked on filling
#include "Header.h"
void Isometric_Render::create_image(World_Map world)
{
}
void Isometric_Render::recursive_place(int curr_x, int curr_y, int curr_z) {
if (curr_x <= this->get_x()[1] && curr_x >= this->get_x()[0] &&
curr_y <= this->get_y()[1] && curr_y >= this->get_y()[0] &&
curr_z <= this->get_z()[1] && curr_z >= this->get_z()[0]) {
place_cube(curr_x, curr_y, curr_z);
this->recursive_place(curr_x + 1, curr_y, curr_z);
this->recursive_place(curr_x, curr_y + 1, curr_z);
this->recursive_place(curr_x, curr_y, curr_z + 1);
cout << "rec: curr_x: " << curr_x << " curr_y: " << curr_y << " curr_z: " << curr_z << " sum: " << curr_x+curr_y+curr_z<< endl;
}
}
void Isometric_Render::draw_line(int *x, int *y, RGBApixel * pixel) {
int x1 = x[0];
int x2 = x[1];
int y1 = y[0];
int y2 = y[1];
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if (steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = (float)(x2 - x1);
const float dy = (float)fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y_new = (int)y1;
const int maxX = (int)x2;
for (int x_new = (int)x1; x_new<maxX; x_new++)
{
if (steep)
{
RGBApixel* pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = 192;
pixel->Green = 192; //SILVER
pixel->Blue = 192;
this->bmp_image->SetPixel(y_new,x_new,*pixel);
int x_f = 0;
for ( x_f = x_new; x_f < FACE_HEIGHT - (dx * 2); x_f++) {
}
for (x_f = x_new; x_f > -FACE_HEIGHT * dx; x_f--) {
}
}
else
{
RGBApixel* pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = 192;
pixel->Green = 192; //SILVER
pixel->Blue = 192;
this->bmp_image->SetPixel(x_new, y_new, *pixel);
int y_f = 0;
for (int y_f = y_new; y_f < FACE_HEIGHT - (dy * 2) - 1; y_f++) {
}
for (y_f = y_new; y_f > -FACE_HEIGHT * dx; y_f--) {
}
}
error -= dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
}
void Isometric_Render::place_cube(int x, int y, int z) {
int * xy = find_xy(x, y, z);
RGBApixel * pixel = new RGBApixel;
pixel->Alpha = 127;
pixel->Red = this->the_map->get_point->r;
pixel->Blue = this->the_map->get_point->b;
pixel->Green = this->the_map->get_point->g;
int point_start[2];
int point_end_r[2];
int point_end_l[2];
int point_bottom[2];
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
int h_half = h / 2;
for (int i = 0; i < 2; i++) {
point_start[i] = xy[i];
}
//point_bottom[0] = xy[0];
//point_bottom[1] = xy[1] - h;
//draw_line(point_start, point_bottom);
point_end_r[0] = xy[0] + h_root;
point_end_r[1] = xy[1] + h_half;
point_end_l[0] = -point_end_r[0];
point_end_l[1] = point_end_r[1];
draw_line(point_start, point_end_r, pixel);
draw_line(point_start, point_end_l, pixel);
//point_start[1] = point_start[1] + h;
//draw_line(point_start, point_end_r);
//draw_line(point_start, point_end_l);
//point_bottom[0] = point_end_r[0];
//point_bottom[1] = point_end_r[1] - h;
//draw_line(point_bottom, point_end_r);
//point_end_r[0] = xy[0];
//point_end_r[1] = xy[1] - h;
//draw_line(point_end_r, point_bottom);
//point_bottom[0] = point_end_l[0];
//point_bottom[1] = point_end_l[1] - h;
//draw_line(point_bottom, point_end_l);
//draw_line(point_end_r, point_bottom);
free(xy);
}
int* Isometric_Render::find_xy(int x, int y, int z) {
int *x_y = (int*)malloc(sizeof(int)*2);
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
int h_half = h / 2;
//inititalize to 0,0,0
x_y[0] = (this->get_y()[1] - this->get_y()[0] + 1)*(h_root-1) + 0;
x_y[1] = h-1;
printf("initial: x:%d,y:%d\n", x_y[0], x_y[1]);
//add x components
if (x) {
x_y[0] += x*(h_root-1);
x_y[1] += x*h_half;
printf("x components: x:%d,y:%d\n", x_y[0], x_y[1]);
}
//add y components
if (y) {
x_y[0] -=y*(h_root-1);
x_y[1] += y*h_half;
printf("y components: x:%d,y:%d\n", x_y[0], x_y[1]);
}//add z components
if (z) {
x_y[0] += 0;
x_y[1] += z*(h-1);
printf("final/z components: x:%d,y:%d\n", x_y[0], x_y[1]);
}
printf("point_xyz (%d,%d,%d) moved to point_xy(%d,%d)\n",x,y,z,x_y[0],x_y[1]);
return x_y;
}
int * Isometric_Render::get_x() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->x_l;
result[1] = this->x_u;
return result;
}
int * Isometric_Render::get_y() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->y_l;
result[1] = this->y_u;
return result;
}
int * Isometric_Render::get_z() {
int* result = static_cast<int*>(malloc(sizeof(int)*2));
result[0] = this->z_l;
result[1] = this->z_u;
return result;
}
void Isometric_Render::set_x(int low, int up) {
this->x_l = low;
this->x_u = up;
}
void Isometric_Render::set_y(int low, int up) {
this->y_l = low;
this->y_u = up;
}
void Isometric_Render::set_z(int low, int up) {
this->z_l = low;
this->z_u = up;
}
Isometric_Render::Isometric_Render(World_Map* _map, BMP *the_bmp_image, int xl, int xu, int yl, int yu, int zl, int zu) {
set_x(xl, xu);
set_y(yl, yu);
this->the_map = _map;
set_z(zl, zu);
int h = FACE_HEIGHT;
int h_root = (int)(h * sqrt(3)) / 2;
this->bmp_image = the_bmp_image;
//int h_half = h / 2;
//int max_xy = (xu - xl + 1) > (yu - yl + 1) ? (xu - xl + 1) : (yu - yl + 1);
int * dimensions = this->find_xy((xu - xl + 1), (yu - yl + 1), (zu - zl + 1));
this->width = ((xu - xl + 1)+ (xu - xl + 1))*(h_root-1) + 1;
this->height = dimensions[1] - h + 1;
free(dimensions);
}
Isometric_Render::Isometric_Render() {} |
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2011, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE or contributors 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::ostream;
using std::endl;
using std::hex;
using std::dec;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <set>
using std::set;
#include <typeinfo>
//*************************** User Include Files ****************************
#include <include/uint.h>
#include "CCT-Tree.hpp"
#include "CallPath-Profile.hpp" // for CCT::Tree::metadata()
#include <lib/xml/xml.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/Logic.hpp>
#include <lib/support/SrcFile.hpp>
using SrcFile::ln_NULL;
#include <lib/support/StrUtil.hpp>
#include <lib/support/Trace.hpp>
//*************************** Forward Declarations ***************************
//***************************************************************************
//***************************************************************************
// Tree
//***************************************************************************
namespace Prof {
namespace CCT {
Tree::Tree(const CallPath::Profile* metadata)
: m_root(NULL), m_metadata(metadata),
m_maxDenseId(0), m_nodeidMap(NULL),
m_mergeCtxt(NULL)
{
}
Tree::~Tree()
{
delete m_root;
m_metadata = NULL;
delete m_nodeidMap;
delete m_mergeCtxt;
}
MergeEffectList*
Tree::merge(const Tree* y, uint x_newMetricBegIdx, uint mrgFlag, uint oFlag)
{
Tree* x = this;
ANode* x_root = root();
ANode* y_root = y->root();
// -------------------------------------------------------
// Merge pre-condition: both x and y should be "locally merged",
// i.e. they should be equal except for metrics and children.
// -------------------------------------------------------
bool isPrecondition = false;
if (typeid(*x_root) == typeid(CCT::Root)
&& typeid(*y_root) == typeid(CCT::Root)) {
// Case 1
isPrecondition = true;
}
else {
ADynNode* x_dyn = dynamic_cast<ADynNode*>(x_root);
ADynNode* y_dyn = dynamic_cast<ADynNode*>(y_root);
if (x_dyn && y_dyn && ADynNode::isMergable(*x_dyn, *y_dyn)) {
// Case 2a
isPrecondition = true;
}
else if ((x_dyn->childCount() == 0 || y_dyn->childCount() == 0)
&& x_dyn->isPrimarySynthRoot() && y_dyn->isPrimarySynthRoot()) {
// Case 2b (A special sub-case of Case 1): (a) Neither tree x
// nor y have been canonicalized (and therefore do not have a
// CCT::Root node); and (b) one of x or y is a single-node tree.
isPrecondition = true;
}
}
DIAG_Assert(isPrecondition, "Prof::CCT::Tree::merge: Merge precondition fails!");
// -------------------------------------------------------
//
// -------------------------------------------------------
if (!m_mergeCtxt) {
bool doTrackCPIds = !metadata()->traceFileNameSet().empty();
m_mergeCtxt = new MergeContext(x, doTrackCPIds);
}
m_mergeCtxt->flags(mrgFlag);
MergeEffectList* mrgEffects =
x_root->mergeDeep(y_root, x_newMetricBegIdx, *m_mergeCtxt, oFlag);
DIAG_If(0) {
verifyUniqueCPIds();
}
return mrgEffects;
}
void
Tree::pruneCCTByNodeId(const uint8_t* prunedNodes)
{
m_root->pruneChildrenByNodeId(prunedNodes);
DIAG_Assert(!prunedNodes[m_root->id()], "Prof::CCT::Tree::pruneCCTByNodeId(): cannot delete root!");
//Prof::CCT::ANode::pruneByNodeId(m_root, prunedNodes);
//DIAG_Assert(m_root, "Prof::CCT::Tree::pruneCCTByNodeId(): cannot delete root!");
}
uint
Tree::makeDensePreorderIds()
{
uint nextId = 1; // cf. s_nextUniqueId
nextId = m_root->makeDensePreorderIds(nextId);
m_maxDenseId = (nextId - 1);
return m_maxDenseId;
}
ANode*
Tree::findNode(uint nodeId) const
{
if (!m_nodeidMap) {
m_nodeidMap = new NodeIdToANodeMap;
for (ANodeIterator it(m_root); it.Current(); ++it) {
ANode* n = it.current();
m_nodeidMap->insert(std::make_pair(n->id(), n));
}
}
NodeIdToANodeMap::iterator it = m_nodeidMap->find(nodeId);
return (it != m_nodeidMap->end()) ? it->second : NULL;
}
bool
Tree::verifyUniqueCPIds()
{
bool areAllUnique = true;
MergeContext::CPIdSet cpIdSet;
for (ANodeIterator it(root()); it.Current(); ++it) {
ANode* n = it.current();
ADynNode* n_dyn = dynamic_cast<ADynNode*>(n);
if (n_dyn && n_dyn->cpId() != HPCRUN_FMT_CCTNodeId_NULL) {
std::pair<MergeContext::CPIdSet::iterator, bool> ret =
cpIdSet.insert(n_dyn->cpId());
bool isInserted = ret.second;
areAllUnique = areAllUnique && isInserted;
DIAG_MsgIf(!isInserted, "CCT::Tree::verifyUniqueCPIds: Duplicate CPId: " << n_dyn->cpId());
}
}
return areAllUnique;
}
std::ostream&
Tree::writeXML(std::ostream& os, uint metricBeg, uint metricEnd,
uint oFlags) const
{
if (m_root) {
m_root->writeXML(os, metricBeg, metricEnd, oFlags);
}
return os;
}
std::ostream&
Tree::dump(std::ostream& os, uint oFlags) const
{
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags);
return os;
}
void
Tree::ddump() const
{
dump(std::cerr, Tree::OFlg_DebugAll);
}
} // namespace CCT
} // namespace Prof
namespace Prof {
namespace CCT {
//***************************************************************************
// ANodeTy `methods' (could completely replace with dynamic typing)
//***************************************************************************
const string ANode::NodeNames[ANode::TyNUMBER] = {
"Root", "PF", "Pr", "L", "C", "S", "Any"
};
const string&
ANode::ANodeTyToName(ANodeTy tp)
{
return NodeNames[tp];
}
ANode::ANodeTy
ANode::IntToANodeType(long i)
{
DIAG_Assert((i >= 0) && (i < TyNUMBER), "");
return (ANodeTy)i;
}
uint ANode::s_nextUniqueId = 2;
//***************************************************************************
// ANode, etc: constructors/destructors
//***************************************************************************
uint ANode::s_raToCallsiteOfst = 1;
string AProcNode::BOGUS;
//***************************************************************************
// ANode, etc: Tree Navigation
//***************************************************************************
#define dyn_cast_return(base, derived, expr) \
{ base* ptr = expr; \
if (ptr == NULL) { \
return NULL; \
} else { \
return dynamic_cast<derived*>(ptr); \
} \
}
ANode*
ANode::ancestor(ANodeTy tp) const
{
ANode* s = const_cast<ANode*>(this);
while (s && s->type() != tp) {
s = s->parent();
}
return s;
}
#if 0 // is this obsolete?
int
isAncestorOf(ANode* parent, ANode* son, int difference)
{
ANode *iter = son;
while (iter && difference > 0 && iter != parent) {
iter = iter->Parent();
difference--;
}
if (iter && iter == parent) {
return 1;
}
return 0;
}
#endif
Root*
ANode::ancestorRoot() const
{
if (Parent() == NULL) {
return NULL;
}
else {
dyn_cast_return(ANode, Root, ancestor(TyRoot));
}
}
ProcFrm*
ANode::ancestorProcFrm() const
{
dyn_cast_return(ANode, ProcFrm, ancestor(TyProcFrm));
}
Proc*
ANode::ancestorProc() const
{
dyn_cast_return(ANode, Proc, ancestor(TyProc));
}
Loop*
ANode::ancestorLoop() const
{
dyn_cast_return(ANode, Loop, ancestor(TyLoop));
}
Call*
ANode::ancestorCall() const
{
dyn_cast_return(ANode, Call, ancestor(TyCall));
}
Stmt*
ANode::ancestorStmt() const
{
dyn_cast_return(ANode, Stmt, ancestor(TyStmt));
}
//***************************************************************************
// Metrics
//***************************************************************************
void
ANode::zeroMetricsDeep(uint mBegId, uint mEndId)
{
if ( !(mBegId < mEndId) ) {
return; // short circuit
}
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->zeroMetrics(mBegId, mEndId);
}
}
void
ANode::aggregateMetricsIncl(uint mBegId, uint mEndId)
{
VMAIntervalSet ivalset; // TODO: cheat using a VMAInterval set
for (uint mId = mBegId; mId < mEndId; ++mId) {
ivalset.insert(VMAInterval(mId, mId + 1)); // [ )
}
aggregateMetricsIncl(ivalset);
}
void
ANode::aggregateMetricsIncl(const VMAIntervalSet& ivalset)
{
if (ivalset.empty()) {
return; // short circuit
}
const ANode* root = this;
ANodeIterator it(root, NULL/*filter*/, false/*leavesOnly*/,
IteratorStack::PostOrder);
for (ANode* n = NULL; (n = it.current()); ++it) {
if (n != root) {
ANode* n_parent = n->parent();
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
double mVal = n->demandMetric(mId, mEndId/*size*/);
n_parent->demandMetric(mId, mEndId/*size*/) += mVal;
}
}
}
}
}
void
ANode::aggregateMetricsExcl(uint mBegId, uint mEndId)
{
VMAIntervalSet ivalset; // TODO: cheat using a VMAInterval set
for (uint mId = mBegId; mId < mEndId; ++mId) {
ivalset.insert(VMAInterval(mId, mId + 1)); // [ )
}
aggregateMetricsExcl(ivalset);
}
void
ANode::aggregateMetricsExcl(const VMAIntervalSet& ivalset)
{
if (ivalset.empty()) {
return; // short circuit
}
ProcFrm* frame = NULL; // will be set during tree traversal
aggregateMetricsExcl(frame, ivalset);
}
void
ANode::aggregateMetricsExcl(ProcFrm* frame, const VMAIntervalSet& ivalset)
{
ANode* n = this;
// -------------------------------------------------------
// Pre-order visit
// -------------------------------------------------------
bool isFrame = (typeid(*n) == typeid(ProcFrm));
ProcFrm* frameNxt = (isFrame) ? static_cast<ProcFrm*>(n) : frame;
// -------------------------------------------------------
//
// -------------------------------------------------------
for (ANodeChildIterator it(n); it.Current(); ++it) {
ANode* x = it.current();
x->aggregateMetricsExcl(frameNxt, ivalset);
}
// -------------------------------------------------------
// Post-order visit
// -------------------------------------------------------
if (typeid(*n) == typeid(CCT::Stmt)) {
ANode* n_parent = n->parent();
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
double mVal = n->demandMetric(mId, mEndId/*size*/);
n_parent->demandMetric(mId, mEndId/*size*/) += mVal;
if (frame && frame != n_parent) {
frame->demandMetric(mId, mEndId/*size*/) += mVal;
}
}
}
}
}
void
ANode::computeMetrics(const Metric::Mgr& mMgr, uint mBegId, uint mEndId)
{
if ( !(mBegId < mEndId) ) {
return;
}
// N.B. pre-order walk assumes point-wise metrics
// Cf. Analysis::Flat::Driver::computeDerivedBatch().
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->computeMetricsMe(mMgr, mBegId, mEndId);
}
}
void
ANode::computeMetricsMe(const Metric::Mgr& mMgr, uint mBegId, uint mEndId)
{
//uint numMetrics = mMgr.size();
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Metric::ADesc* m = mMgr.metric(mId);
const Metric::DerivedDesc* mm = dynamic_cast<const Metric::DerivedDesc*>(m);
if (mm && mm->expr()) {
const Metric::AExpr* expr = mm->expr();
expr->evalNF(*this);
// double val = eval(); demandMetric(mId, numMetrics/*size*/) = val;
}
}
}
void
ANode::computeMetricsIncr(const Metric::Mgr& mMgr, uint mBegId, uint mEndId,
Metric::AExprIncr::FnTy fn)
{
if ( !(mBegId < mEndId) ) {
return;
}
// N.B. pre-order walk assumes point-wise metrics
// Cf. Analysis::Flat::Driver::computeDerivedBatch().
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->computeMetricsIncrMe(mMgr, mBegId, mEndId, fn);
}
}
void
ANode::computeMetricsIncrMe(const Metric::Mgr& mMgr, uint mBegId, uint mEndId,
Metric::AExprIncr::FnTy fn)
{
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Metric::ADesc* m = mMgr.metric(mId);
const Metric::DerivedIncrDesc* mm =
dynamic_cast<const Metric::DerivedIncrDesc*>(m);
if (mm && mm->expr()) {
const Metric::AExprIncr* expr = mm->expr();
switch (fn) {
case Metric::AExprIncr::FnInit:
expr->initialize(*this); break;
case Metric::AExprIncr::FnInitSrc:
expr->initializeSrc(*this); break;
case Metric::AExprIncr::FnAccum:
expr->accumulate(*this); break;
case Metric::AExprIncr::FnCombine:
expr->combine(*this); break;
case Metric::AExprIncr::FnFini:
expr->finalize(*this); break;
default:
DIAG_Die(DIAG_UnexpectedInput);
}
}
}
}
void
ANode::pruneByMetrics(const Metric::Mgr& mMgr, const VMAIntervalSet& ivalset,
const ANode* root, double thresholdPct,
uint8_t* prunedNodes)
{
for (ANodeChildIterator it(this); it.Current(); /* */) {
ANode* x = it.current();
it++; // advance iterator -- it is pointing at 'x'
// ----------------------------------------------------------
// Determine whether 'x' is important: any inclusive metric >= threshold
// ----------------------------------------------------------
uint numIncl = 0;
bool isImportant = false;
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Prof::Metric::ADesc* m = mMgr.metric(mId);
if (m->type() != Metric::ADesc::TyIncl) {
continue;
}
numIncl++;
double total = root->metric(mId); // root->metric(m->partner()->id());
double pct = x->metric(mId) * 100 / total;
if (pct >= thresholdPct) {
isImportant = true;
break;
}
}
if (isImportant) { break; }
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
if (isImportant || numIncl == 0) {
x->pruneByMetrics(mMgr, ivalset, root, thresholdPct, prunedNodes);
}
else {
deleteChaff(x, prunedNodes);
}
}
}
#if 0
void
ANode::pruneByNodeId(ANode*& x, const uint8_t* prunedNodes)
{
// Visiting in preorder can save a little work since a whole subtree
// can be deleted (factoring out the destructor's recursion)
if (prunedNodes[x->id()]) {
x->unlink(); // unlink 'x' from tree
delete x;
x = NULL;
}
else {
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
pruneByNodeId(x_child, prunedNodes);
}
}
}
#endif
void
ANode::pruneChildrenByNodeId(const uint8_t* prunedNodes)
{
ANode* x = this;
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
// Visiting in preorder can save a little work since a whole subtree
// can be deleted (factoring out the destructor's recursion)
if (prunedNodes[x_child->id()]) {
x_child->unlink(); // unlink 'x_child' from tree
delete x_child;
}
else {
x_child->pruneChildrenByNodeId(prunedNodes);
}
}
}
bool
ANode::deleteChaff(ANode* x, uint8_t* deletedNodes)
{
bool x_isLeaf = x->isLeaf(); // N.B. must perform before below
uint x_id = x->id();
bool wereAllChildrenDeleted = true;
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
wereAllChildrenDeleted = (wereAllChildrenDeleted
&& deleteChaff(x_child, deletedNodes));
}
bool wasDeleted = false;
if (wereAllChildrenDeleted) {
Prof::CCT::ADynNode* x_dyn = dynamic_cast<Prof::CCT::ADynNode*>(x);
bool mustRetain = (x_dyn && hpcrun_fmt_doRetainId(x_dyn->cpId()));
if ((x_isLeaf && !mustRetain) || !x_isLeaf) {
x->unlink(); // unlink 'x' from tree
delete x;
if (deletedNodes) {
deletedNodes[x_id] = 1;
}
wasDeleted = true;
}
}
return wasDeleted;
}
//**********************************************************************
// Merging
//**********************************************************************
MergeEffectList*
ANode::mergeDeep(ANode* y, uint x_newMetricBegIdx, MergeContext& mrgCtxt,
uint oFlag)
{
ANode* x = this;
// ------------------------------------------------------------
// 0. If y is childless, return.
// ------------------------------------------------------------
if (y->isLeaf()) {
return NULL;
}
// ------------------------------------------------------------
// 1. If a child y_child of y _does not_ appear as a child of x,
// then copy (subtree) y_child [fixing its metrics], make it a
// child of x and return.
// 2. If a child y_child of y _does_ have a corresponding child
// x_child of x, merge [the metrics of] y_child into x_child and
// recur.
// ------------------------------------------------------------
MergeEffectList* effctLst = new MergeEffectList;
for (ANodeChildIterator it(y); it.Current(); /* */) {
ANode* y_child = it.current();
ADynNode* y_child_dyn = dynamic_cast<ADynNode*>(y_child);
DIAG_Assert(y_child_dyn, "ANode::mergeDeep");
it++; // advance iterator -- it is pointing at 'child'
MergeEffectList* effctLst1 = NULL;
ADynNode* x_child_dyn = x->findDynChild(*y_child_dyn);
if (!x_child_dyn) {
// case 1: insert nodes
DIAG_Assert( !(mrgCtxt.flags() & MrgFlg_AssertCCTMergeOnly),
"CCT::ANode::mergeDeep: adding not permitted");
if ( !(mrgCtxt.flags() & MrgFlg_CCTMergeOnly) ) {
DIAG_MsgIf(0 /*(oFlag & Tree::OFlg_Debug)*/,
"CCT::ANode::mergeDeep: Adding:\n "
<< y_child->toStringMe(Tree::OFlg_Debug));
y_child->unlink();
effctLst1 = y_child->mergeDeep_fixInsert(x_newMetricBegIdx, mrgCtxt);
y_child->link(x);
}
}
else {
// case 2: merge nodes
DIAG_MsgIf(0 /*(oFlag & Tree::OFlg_Debug)*/,
"CCT::ANode::mergeDeep: Merging x <= y:\n"
<< " x: " << x_child_dyn->toStringMe(Tree::OFlg_Debug)
<< "\n y: " << y_child_dyn->toStringMe(Tree::OFlg_Debug));
MergeEffect effct =
x_child_dyn->mergeMe(*y_child_dyn, &mrgCtxt, x_newMetricBegIdx);
if (mrgCtxt.doPropagateEffects() && !effct.isNoop()) {
effctLst->push_back(effct);
}
effctLst1 = x_child_dyn->mergeDeep(y_child, x_newMetricBegIdx, mrgCtxt,
oFlag);
}
if (effctLst1 && !effctLst1->empty()) {
effctLst->splice(effctLst->end(), *effctLst1);
DIAG_MsgIf(0, MergeEffect::toString(*effctLst));
}
delete effctLst1;
}
return effctLst;
}
MergeEffect
ANode::merge(ANode* y)
{
ANode* x = this;
// 1. copy y's metrics into x
MergeEffect effct = x->mergeMe(*y);
// 2. copy y's children into x
for (ANodeChildIterator it(y); it.Current(); /* */) {
ANode* y_child = it.current();
it++; // advance iterator -- it is pointing at 'y_child'
y_child->unlink();
y_child->link(x);
}
y->unlink();
delete y;
return effct;
}
MergeEffect
ANode::mergeMe(const ANode& y, MergeContext* mrgCtxt, uint metricBegIdx)
{
ANode* x = this;
uint x_end = metricBegIdx + y.numMetrics(); // open upper bound
if ( !(x_end <= x->numMetrics()) ) {
ensureMetricsSize(x_end);
}
for (uint x_i = metricBegIdx, y_i = 0; x_i < x_end; ++x_i, ++y_i) {
x->metric(x_i) += y.metric(y_i);
}
MergeEffect noopEffect;
return noopEffect;
}
MergeEffect
ADynNode::mergeMe(const ANode& y, MergeContext* mrgCtxt, uint metricBegIdx)
{
// N.B.: Assumes ADynNode::isMergable() holds
ADynNode* x = this;
const ADynNode* y_dyn = dynamic_cast<const ADynNode*>(&y);
DIAG_Assert(y_dyn, "ADynNode::mergeMe: " << DIAG_UnexpectedInput);
MergeEffect effct = ANode::mergeMe(y, mrgCtxt, metricBegIdx);
// merge cp-ids
if (hasMergeEffects(*x, *y_dyn)) {
// 1. Conflicting ids:
// => keep x's cpId; within y, translate [y_dyn->m_cpId ==> m_cpId]
effct.old_cpId = y_dyn->m_cpId;
effct.new_cpId = m_cpId;
}
else if (y_dyn->cpId() == HPCRUN_FMT_CCTNodeId_NULL) {
// 2. Trivial conflict: y's cpId is NULL; x's may or may not be NULL:
// => keep x's cpId.
}
else if (m_cpId == HPCRUN_FMT_CCTNodeId_NULL) {
// 3. Semi-trivial conflict: x's cpId is NULL, but y's is not
// => use y's cpId *if* it does not conflict with one already
// in x's tree.
DIAG_Assert(mrgCtxt, "ADynNode::mergeMe: potentially introducing cp-id conflicts; cannot verify with out MergeContext!");
MergeContext::pair ret = mrgCtxt->ensureUniqueCPId(y_dyn->cpId());
m_cpId = ret.cpId;
DIAG_Assert(effct.isNoop(), DIAG_UnexpectedInput);
effct = ret.effect;
}
return effct;
}
ADynNode*
ANode::findDynChild(const ADynNode& y_dyn)
{
for (ANodeChildIterator it(this); it.Current(); ++it) {
ANode* x = it.current();
ADynNode* x_dyn = dynamic_cast<ADynNode*>(x);
if (x_dyn) {
// Base case: an ADynNode descendent
if (ADynNode::isMergable(*x_dyn, y_dyn)) {
return x_dyn;
}
}
else {
// Inductive case: some other type; find the first ADynNode descendents.
ADynNode* x_dyn_descendent = x->findDynChild(y_dyn);
if (x_dyn_descendent) {
return x_dyn_descendent;
}
}
}
return NULL;
}
MergeEffectList*
ANode::mergeDeep_fixInsert(int newMetrics, MergeContext& mrgCtxt)
{
// Assumes: While merging CCT::Tree y into CCT::Tree x, subtree
// 'this', which used to live in 'y', has just been inserted into
// 'x'.
MergeEffectList* effctLst = new MergeEffectList();
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
// -----------------------------------------------------
// 1. Ensure no cpId in subtree 'this' conflicts with an existing
// cpId in CCT::Tree x.
// -----------------------------------------------------
ADynNode* n_dyn = dynamic_cast<ADynNode*>(n);
if (n_dyn) {
MergeContext::pair ret = mrgCtxt.ensureUniqueCPId(n_dyn->cpId());
n_dyn->cpId(ret.cpId);
if (!ret.effect.isNoop()) {
effctLst->push_back(ret.effect);
}
}
// -----------------------------------------------------
// 2. Make space for the metrics of CCT::Tree x
// -----------------------------------------------------
n->insertMetricsBefore(newMetrics);
}
return effctLst;
}
//**********************************************************************
//
//**********************************************************************
uint
ANode::makeDensePreorderIds(uint nextId)
{
// N.B.: use a sorted iterator to support hpcprof-mpi where we need
// to ensure multiple processes obtain the same numbering.
id(nextId);
nextId++;
for (ANodeSortedChildIterator it(this, ANodeSortedIterator::cmpByStructureInfo);
it.current(); it++) {
CCT::ANode* n = it.current();
nextId = n->makeDensePreorderIds(nextId);
}
return nextId;
}
//**********************************************************************
// ANode, etc: CodeName methods
//**********************************************************************
// NOTE: tallent: used for lush_cilkNormalize
string
ANode::codeName() const
{
string self = ANodeTyToName(type()) + " "
//+ GetFile() + ":"
+ StrUtil::toStr(begLine()) + "-" + StrUtil::toStr(endLine());
return self;
}
string
ProcFrm::codeName() const
{
string self = ANodeTyToName(type()) + " "
+ procName() + " @ "
+ fileName() + ":"
+ StrUtil::toStr(begLine()) + "-" + StrUtil::toStr(endLine());
return self;
}
string
ProcFrm::procNameDbg() const
{
string nm = procName();
CCT::Call* caller = ancestorCall();
if (caller) {
nm += " <= " + caller->nameDyn();
}
return nm;
}
//**********************************************************************
// ANode, etc: Dump contents for inspection
//**********************************************************************
string
ANode::toString(uint oFlags, const char* pfx) const
{
std::ostringstream os;
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags, pfx);
return os.str();
}
string
ANode::toStringMe(uint oFlags) const
{
string self;
self = ANodeTyToName(type());
SrcFile::ln lnBeg = begLine();
string line = StrUtil::toStr(lnBeg);
//SrcFile::ln lnEnd = endLine();
//if (lnBeg != lnEnd) {
// line += "-" + StrUtil::toStr(lnEnd);
//}
uint sId = (m_strct) ? m_strct->id() : 0;
self += " i" + xml::MakeAttrNum(m_id);
self += " s" + xml::MakeAttrNum(sId) + " l" + xml::MakeAttrStr(line);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " strct" + xml::MakeAttrNum((uintptr_t)m_strct, 16);
}
return self;
}
string
ADynNode::assocInfo_str() const
{
char str[LUSH_ASSOC_INFO_STR_MIN_LEN];
lush_assoc_info_sprintf(str, m_as_info);
return string(str);
}
string
ADynNode::lip_str() const
{
char str[LUSH_LIP_STR_MIN_LEN];
lush_lip_sprintf(str, m_lip);
return string(str);
}
string
ADynNode::nameDyn() const
{
string nm = "[assoc(" + assocInfo_str() + ") ip("
+ StrUtil::toStr(m_lmId) + ", " + StrUtil::toStr(m_lmIP, 16) + ") lip("
+ lip_str() + ")]";
return nm;
}
void
ADynNode::writeDyn(std::ostream& o, uint oFlags, const char* pfx) const
{
string p(pfx);
o << std::showbase;
o << p << assocInfo_str()
<< hex << " [ip " << m_lmIP << ", " << dec << m_opIdx << "] "
<< hex << m_lip << " [lip " << lip_str() << "]" << dec;
o << p << " [metrics";
for (uint i = 0; i < numMetrics(); ++i) {
o << " " << metric(i);
}
o << "]" << endl;
}
string
Root::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags) + " n" + xml::MakeAttrStr(m_name);
return self;
}
string
ProcFrm::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if (m_strct) {
string lm_nm = xml::MakeAttrNum(lmId());
string fnm = xml::MakeAttrNum(fileId());
string pnm = xml::MakeAttrNum(procId());
if (oFlags & Tree::OFlg_DebugAll) {
lm_nm = xml::MakeAttrStr(lmName());
fnm = xml::MakeAttrStr(fileName());
}
if ( (oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll) ) {
pnm = xml::MakeAttrStr(procNameDbg());
}
self += " lm" + lm_nm + " f" + fnm + " n" + pnm;
}
return self;
}
string
Proc::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if (m_strct) {
string lm_nm = xml::MakeAttrNum(lmId());
string fnm = xml::MakeAttrNum(fileId());
string pnm = xml::MakeAttrNum(procId());
if (oFlags & Tree::OFlg_DebugAll) {
lm_nm = xml::MakeAttrStr(lmName());
fnm = xml::MakeAttrStr(fileName());
pnm = xml::MakeAttrStr(procName());
}
self += " lm" + lm_nm + " f" + fnm + " n" + pnm;
if (isAlien()) {
self = self + " a=\"1\"";
}
}
return self;
}
string
Loop::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
return self;
}
string
Call::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " n=\"" + nameDyn() + "\"";
}
return self;
}
string
Stmt::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " n=\"" + nameDyn() + "\"";
}
if (hpcrun_fmt_doRetainId(cpId())) {
self += " it" + xml::MakeAttrNum(cpId());
}
return self;
}
std::ostream&
ANode::writeXML(ostream& os, uint metricBeg, uint metricEnd,
uint oFlags, const char* pfx) const
{
string indent = " ";
if (oFlags & CCT::Tree::OFlg_Compressed) {
pfx = "";
indent = "";
}
bool doPost = writeXML_pre(os, metricBeg, metricEnd, oFlags, pfx);
string prefix = pfx + indent;
for (ANodeSortedChildIterator it(this, ANodeSortedIterator::cmpByStructureInfo);
it.current(); it++) {
ANode* n = it.current();
n->writeXML(os, metricBeg, metricEnd, oFlags, prefix.c_str());
}
if (doPost) {
writeXML_post(os, oFlags, pfx);
}
return os;
}
std::ostream&
ANode::dump(ostream& os, uint oFlags, const char* pfx) const
{
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags, pfx);
return os;
}
void
ANode::ddump() const
{
writeXML(std::cerr, Metric::IData::npos, Metric::IData::npos,
Tree::OFlg_DebugAll, "");
}
void
ANode::ddumpMe() const
{
string str = toStringMe(Tree::OFlg_DebugAll);
std::cerr << str;
}
bool
ANode::writeXML_pre(ostream& os, uint metricBeg, uint metricEnd,
uint oFlags, const char* pfx) const
{
bool doTag = (type() != TyRoot);
bool doMetrics = ((oFlags & Tree::OFlg_LeafMetricsOnly)
? isLeaf() && hasMetrics(metricBeg, metricEnd)
: hasMetrics(metricBeg, metricEnd));
bool isXMLLeaf = isLeaf() && !doMetrics;
// 1. Write element name
if (doTag) {
if (isXMLLeaf) {
os << pfx << "<" << toStringMe(oFlags) << "/>" << endl;
}
else {
os << pfx << "<" << toStringMe(oFlags) << ">" << endl;
}
}
// 2. Write associated metrics
if (doMetrics) {
writeMetricsXML(os, metricBeg, metricEnd, oFlags, pfx);
os << endl;
}
return !isXMLLeaf; // whether to execute writeXML_post()
}
void
ANode::writeXML_post(ostream& os, uint oFlags, const char* pfx) const
{
bool doTag = (type() != ANode::TyRoot);
if (!doTag) {
return;
}
os << pfx << "</" << ANodeTyToName(type()) << ">" << endl;
}
//**********************************************************************
//
//**********************************************************************
int ANodeLineComp(ANode* x, ANode* y)
{
if (x->begLine() == y->begLine()) {
// Given two ANode's with identical endpoints consider two
// special cases:
bool endLinesEqual = (x->endLine() == y->endLine());
// 1. Otherwise: rank a leaf node before a non-leaf node
if (endLinesEqual && !(x->isLeaf() && y->isLeaf())) {
if (x->isLeaf()) { return -1; } // x < y
else if (y->isLeaf()) { return 1; } // x > y
}
// 2. General case
return SrcFile::compare(x->endLine(), y->endLine());
}
else {
return SrcFile::compare(x->begLine(), y->begLine());
}
}
} // namespace CCT
} // namespace Prof
Prof::CCT::ADynNode::nameDyn(): Cleanup. Use lmId/lmIP functions rather
than member data.
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2011, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE or contributors 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::ostream;
using std::endl;
using std::hex;
using std::dec;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <set>
using std::set;
#include <typeinfo>
//*************************** User Include Files ****************************
#include <include/uint.h>
#include "CCT-Tree.hpp"
#include "CallPath-Profile.hpp" // for CCT::Tree::metadata()
#include <lib/xml/xml.hpp>
#include <lib/support/diagnostics.h>
#include <lib/support/Logic.hpp>
#include <lib/support/SrcFile.hpp>
using SrcFile::ln_NULL;
#include <lib/support/StrUtil.hpp>
#include <lib/support/Trace.hpp>
//*************************** Forward Declarations ***************************
//***************************************************************************
//***************************************************************************
// Tree
//***************************************************************************
namespace Prof {
namespace CCT {
Tree::Tree(const CallPath::Profile* metadata)
: m_root(NULL), m_metadata(metadata),
m_maxDenseId(0), m_nodeidMap(NULL),
m_mergeCtxt(NULL)
{
}
Tree::~Tree()
{
delete m_root;
m_metadata = NULL;
delete m_nodeidMap;
delete m_mergeCtxt;
}
MergeEffectList*
Tree::merge(const Tree* y, uint x_newMetricBegIdx, uint mrgFlag, uint oFlag)
{
Tree* x = this;
ANode* x_root = root();
ANode* y_root = y->root();
// -------------------------------------------------------
// Merge pre-condition: both x and y should be "locally merged",
// i.e. they should be equal except for metrics and children.
// -------------------------------------------------------
bool isPrecondition = false;
if (typeid(*x_root) == typeid(CCT::Root)
&& typeid(*y_root) == typeid(CCT::Root)) {
// Case 1
isPrecondition = true;
}
else {
ADynNode* x_dyn = dynamic_cast<ADynNode*>(x_root);
ADynNode* y_dyn = dynamic_cast<ADynNode*>(y_root);
if (x_dyn && y_dyn && ADynNode::isMergable(*x_dyn, *y_dyn)) {
// Case 2a
isPrecondition = true;
}
else if ((x_dyn->childCount() == 0 || y_dyn->childCount() == 0)
&& x_dyn->isPrimarySynthRoot() && y_dyn->isPrimarySynthRoot()) {
// Case 2b (A special sub-case of Case 1): (a) Neither tree x
// nor y have been canonicalized (and therefore do not have a
// CCT::Root node); and (b) one of x or y is a single-node tree.
isPrecondition = true;
}
}
DIAG_Assert(isPrecondition, "Prof::CCT::Tree::merge: Merge precondition fails!");
// -------------------------------------------------------
//
// -------------------------------------------------------
if (!m_mergeCtxt) {
bool doTrackCPIds = !metadata()->traceFileNameSet().empty();
m_mergeCtxt = new MergeContext(x, doTrackCPIds);
}
m_mergeCtxt->flags(mrgFlag);
MergeEffectList* mrgEffects =
x_root->mergeDeep(y_root, x_newMetricBegIdx, *m_mergeCtxt, oFlag);
DIAG_If(0) {
verifyUniqueCPIds();
}
return mrgEffects;
}
void
Tree::pruneCCTByNodeId(const uint8_t* prunedNodes)
{
m_root->pruneChildrenByNodeId(prunedNodes);
DIAG_Assert(!prunedNodes[m_root->id()], "Prof::CCT::Tree::pruneCCTByNodeId(): cannot delete root!");
//Prof::CCT::ANode::pruneByNodeId(m_root, prunedNodes);
//DIAG_Assert(m_root, "Prof::CCT::Tree::pruneCCTByNodeId(): cannot delete root!");
}
uint
Tree::makeDensePreorderIds()
{
uint nextId = 1; // cf. s_nextUniqueId
nextId = m_root->makeDensePreorderIds(nextId);
m_maxDenseId = (nextId - 1);
return m_maxDenseId;
}
ANode*
Tree::findNode(uint nodeId) const
{
if (!m_nodeidMap) {
m_nodeidMap = new NodeIdToANodeMap;
for (ANodeIterator it(m_root); it.Current(); ++it) {
ANode* n = it.current();
m_nodeidMap->insert(std::make_pair(n->id(), n));
}
}
NodeIdToANodeMap::iterator it = m_nodeidMap->find(nodeId);
return (it != m_nodeidMap->end()) ? it->second : NULL;
}
bool
Tree::verifyUniqueCPIds()
{
bool areAllUnique = true;
MergeContext::CPIdSet cpIdSet;
for (ANodeIterator it(root()); it.Current(); ++it) {
ANode* n = it.current();
ADynNode* n_dyn = dynamic_cast<ADynNode*>(n);
if (n_dyn && n_dyn->cpId() != HPCRUN_FMT_CCTNodeId_NULL) {
std::pair<MergeContext::CPIdSet::iterator, bool> ret =
cpIdSet.insert(n_dyn->cpId());
bool isInserted = ret.second;
areAllUnique = areAllUnique && isInserted;
DIAG_MsgIf(!isInserted, "CCT::Tree::verifyUniqueCPIds: Duplicate CPId: " << n_dyn->cpId());
}
}
return areAllUnique;
}
std::ostream&
Tree::writeXML(std::ostream& os, uint metricBeg, uint metricEnd,
uint oFlags) const
{
if (m_root) {
m_root->writeXML(os, metricBeg, metricEnd, oFlags);
}
return os;
}
std::ostream&
Tree::dump(std::ostream& os, uint oFlags) const
{
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags);
return os;
}
void
Tree::ddump() const
{
dump(std::cerr, Tree::OFlg_DebugAll);
}
} // namespace CCT
} // namespace Prof
namespace Prof {
namespace CCT {
//***************************************************************************
// ANodeTy `methods' (could completely replace with dynamic typing)
//***************************************************************************
const string ANode::NodeNames[ANode::TyNUMBER] = {
"Root", "PF", "Pr", "L", "C", "S", "Any"
};
const string&
ANode::ANodeTyToName(ANodeTy tp)
{
return NodeNames[tp];
}
ANode::ANodeTy
ANode::IntToANodeType(long i)
{
DIAG_Assert((i >= 0) && (i < TyNUMBER), "");
return (ANodeTy)i;
}
uint ANode::s_nextUniqueId = 2;
//***************************************************************************
// ANode, etc: constructors/destructors
//***************************************************************************
uint ANode::s_raToCallsiteOfst = 1;
string AProcNode::BOGUS;
//***************************************************************************
// ANode, etc: Tree Navigation
//***************************************************************************
#define dyn_cast_return(base, derived, expr) \
{ base* ptr = expr; \
if (ptr == NULL) { \
return NULL; \
} else { \
return dynamic_cast<derived*>(ptr); \
} \
}
ANode*
ANode::ancestor(ANodeTy tp) const
{
ANode* s = const_cast<ANode*>(this);
while (s && s->type() != tp) {
s = s->parent();
}
return s;
}
#if 0 // is this obsolete?
int
isAncestorOf(ANode* parent, ANode* son, int difference)
{
ANode *iter = son;
while (iter && difference > 0 && iter != parent) {
iter = iter->Parent();
difference--;
}
if (iter && iter == parent) {
return 1;
}
return 0;
}
#endif
Root*
ANode::ancestorRoot() const
{
if (Parent() == NULL) {
return NULL;
}
else {
dyn_cast_return(ANode, Root, ancestor(TyRoot));
}
}
ProcFrm*
ANode::ancestorProcFrm() const
{
dyn_cast_return(ANode, ProcFrm, ancestor(TyProcFrm));
}
Proc*
ANode::ancestorProc() const
{
dyn_cast_return(ANode, Proc, ancestor(TyProc));
}
Loop*
ANode::ancestorLoop() const
{
dyn_cast_return(ANode, Loop, ancestor(TyLoop));
}
Call*
ANode::ancestorCall() const
{
dyn_cast_return(ANode, Call, ancestor(TyCall));
}
Stmt*
ANode::ancestorStmt() const
{
dyn_cast_return(ANode, Stmt, ancestor(TyStmt));
}
//***************************************************************************
// Metrics
//***************************************************************************
void
ANode::zeroMetricsDeep(uint mBegId, uint mEndId)
{
if ( !(mBegId < mEndId) ) {
return; // short circuit
}
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->zeroMetrics(mBegId, mEndId);
}
}
void
ANode::aggregateMetricsIncl(uint mBegId, uint mEndId)
{
VMAIntervalSet ivalset; // TODO: cheat using a VMAInterval set
for (uint mId = mBegId; mId < mEndId; ++mId) {
ivalset.insert(VMAInterval(mId, mId + 1)); // [ )
}
aggregateMetricsIncl(ivalset);
}
void
ANode::aggregateMetricsIncl(const VMAIntervalSet& ivalset)
{
if (ivalset.empty()) {
return; // short circuit
}
const ANode* root = this;
ANodeIterator it(root, NULL/*filter*/, false/*leavesOnly*/,
IteratorStack::PostOrder);
for (ANode* n = NULL; (n = it.current()); ++it) {
if (n != root) {
ANode* n_parent = n->parent();
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
double mVal = n->demandMetric(mId, mEndId/*size*/);
n_parent->demandMetric(mId, mEndId/*size*/) += mVal;
}
}
}
}
}
void
ANode::aggregateMetricsExcl(uint mBegId, uint mEndId)
{
VMAIntervalSet ivalset; // TODO: cheat using a VMAInterval set
for (uint mId = mBegId; mId < mEndId; ++mId) {
ivalset.insert(VMAInterval(mId, mId + 1)); // [ )
}
aggregateMetricsExcl(ivalset);
}
void
ANode::aggregateMetricsExcl(const VMAIntervalSet& ivalset)
{
if (ivalset.empty()) {
return; // short circuit
}
ProcFrm* frame = NULL; // will be set during tree traversal
aggregateMetricsExcl(frame, ivalset);
}
void
ANode::aggregateMetricsExcl(ProcFrm* frame, const VMAIntervalSet& ivalset)
{
ANode* n = this;
// -------------------------------------------------------
// Pre-order visit
// -------------------------------------------------------
bool isFrame = (typeid(*n) == typeid(ProcFrm));
ProcFrm* frameNxt = (isFrame) ? static_cast<ProcFrm*>(n) : frame;
// -------------------------------------------------------
//
// -------------------------------------------------------
for (ANodeChildIterator it(n); it.Current(); ++it) {
ANode* x = it.current();
x->aggregateMetricsExcl(frameNxt, ivalset);
}
// -------------------------------------------------------
// Post-order visit
// -------------------------------------------------------
if (typeid(*n) == typeid(CCT::Stmt)) {
ANode* n_parent = n->parent();
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
double mVal = n->demandMetric(mId, mEndId/*size*/);
n_parent->demandMetric(mId, mEndId/*size*/) += mVal;
if (frame && frame != n_parent) {
frame->demandMetric(mId, mEndId/*size*/) += mVal;
}
}
}
}
}
void
ANode::computeMetrics(const Metric::Mgr& mMgr, uint mBegId, uint mEndId)
{
if ( !(mBegId < mEndId) ) {
return;
}
// N.B. pre-order walk assumes point-wise metrics
// Cf. Analysis::Flat::Driver::computeDerivedBatch().
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->computeMetricsMe(mMgr, mBegId, mEndId);
}
}
void
ANode::computeMetricsMe(const Metric::Mgr& mMgr, uint mBegId, uint mEndId)
{
//uint numMetrics = mMgr.size();
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Metric::ADesc* m = mMgr.metric(mId);
const Metric::DerivedDesc* mm = dynamic_cast<const Metric::DerivedDesc*>(m);
if (mm && mm->expr()) {
const Metric::AExpr* expr = mm->expr();
expr->evalNF(*this);
// double val = eval(); demandMetric(mId, numMetrics/*size*/) = val;
}
}
}
void
ANode::computeMetricsIncr(const Metric::Mgr& mMgr, uint mBegId, uint mEndId,
Metric::AExprIncr::FnTy fn)
{
if ( !(mBegId < mEndId) ) {
return;
}
// N.B. pre-order walk assumes point-wise metrics
// Cf. Analysis::Flat::Driver::computeDerivedBatch().
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
n->computeMetricsIncrMe(mMgr, mBegId, mEndId, fn);
}
}
void
ANode::computeMetricsIncrMe(const Metric::Mgr& mMgr, uint mBegId, uint mEndId,
Metric::AExprIncr::FnTy fn)
{
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Metric::ADesc* m = mMgr.metric(mId);
const Metric::DerivedIncrDesc* mm =
dynamic_cast<const Metric::DerivedIncrDesc*>(m);
if (mm && mm->expr()) {
const Metric::AExprIncr* expr = mm->expr();
switch (fn) {
case Metric::AExprIncr::FnInit:
expr->initialize(*this); break;
case Metric::AExprIncr::FnInitSrc:
expr->initializeSrc(*this); break;
case Metric::AExprIncr::FnAccum:
expr->accumulate(*this); break;
case Metric::AExprIncr::FnCombine:
expr->combine(*this); break;
case Metric::AExprIncr::FnFini:
expr->finalize(*this); break;
default:
DIAG_Die(DIAG_UnexpectedInput);
}
}
}
}
void
ANode::pruneByMetrics(const Metric::Mgr& mMgr, const VMAIntervalSet& ivalset,
const ANode* root, double thresholdPct,
uint8_t* prunedNodes)
{
for (ANodeChildIterator it(this); it.Current(); /* */) {
ANode* x = it.current();
it++; // advance iterator -- it is pointing at 'x'
// ----------------------------------------------------------
// Determine whether 'x' is important: any inclusive metric >= threshold
// ----------------------------------------------------------
uint numIncl = 0;
bool isImportant = false;
for (VMAIntervalSet::const_iterator it = ivalset.begin();
it != ivalset.end(); ++it) {
const VMAInterval& ival = *it;
uint mBegId = (uint)ival.beg(), mEndId = (uint)ival.end();
for (uint mId = mBegId; mId < mEndId; ++mId) {
const Prof::Metric::ADesc* m = mMgr.metric(mId);
if (m->type() != Metric::ADesc::TyIncl) {
continue;
}
numIncl++;
double total = root->metric(mId); // root->metric(m->partner()->id());
double pct = x->metric(mId) * 100 / total;
if (pct >= thresholdPct) {
isImportant = true;
break;
}
}
if (isImportant) { break; }
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
if (isImportant || numIncl == 0) {
x->pruneByMetrics(mMgr, ivalset, root, thresholdPct, prunedNodes);
}
else {
deleteChaff(x, prunedNodes);
}
}
}
#if 0
void
ANode::pruneByNodeId(ANode*& x, const uint8_t* prunedNodes)
{
// Visiting in preorder can save a little work since a whole subtree
// can be deleted (factoring out the destructor's recursion)
if (prunedNodes[x->id()]) {
x->unlink(); // unlink 'x' from tree
delete x;
x = NULL;
}
else {
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
pruneByNodeId(x_child, prunedNodes);
}
}
}
#endif
void
ANode::pruneChildrenByNodeId(const uint8_t* prunedNodes)
{
ANode* x = this;
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
// Visiting in preorder can save a little work since a whole subtree
// can be deleted (factoring out the destructor's recursion)
if (prunedNodes[x_child->id()]) {
x_child->unlink(); // unlink 'x_child' from tree
delete x_child;
}
else {
x_child->pruneChildrenByNodeId(prunedNodes);
}
}
}
bool
ANode::deleteChaff(ANode* x, uint8_t* deletedNodes)
{
bool x_isLeaf = x->isLeaf(); // N.B. must perform before below
uint x_id = x->id();
bool wereAllChildrenDeleted = true;
for (ANodeChildIterator it(x); it.Current(); /* */) {
ANode* x_child = it.current();
it++; // advance iterator -- it is pointing at 'x_child'
wereAllChildrenDeleted = (wereAllChildrenDeleted
&& deleteChaff(x_child, deletedNodes));
}
bool wasDeleted = false;
if (wereAllChildrenDeleted) {
Prof::CCT::ADynNode* x_dyn = dynamic_cast<Prof::CCT::ADynNode*>(x);
bool mustRetain = (x_dyn && hpcrun_fmt_doRetainId(x_dyn->cpId()));
if ((x_isLeaf && !mustRetain) || !x_isLeaf) {
x->unlink(); // unlink 'x' from tree
delete x;
if (deletedNodes) {
deletedNodes[x_id] = 1;
}
wasDeleted = true;
}
}
return wasDeleted;
}
//**********************************************************************
// Merging
//**********************************************************************
MergeEffectList*
ANode::mergeDeep(ANode* y, uint x_newMetricBegIdx, MergeContext& mrgCtxt,
uint oFlag)
{
ANode* x = this;
// ------------------------------------------------------------
// 0. If y is childless, return.
// ------------------------------------------------------------
if (y->isLeaf()) {
return NULL;
}
// ------------------------------------------------------------
// 1. If a child y_child of y _does not_ appear as a child of x,
// then copy (subtree) y_child [fixing its metrics], make it a
// child of x and return.
// 2. If a child y_child of y _does_ have a corresponding child
// x_child of x, merge [the metrics of] y_child into x_child and
// recur.
// ------------------------------------------------------------
MergeEffectList* effctLst = new MergeEffectList;
for (ANodeChildIterator it(y); it.Current(); /* */) {
ANode* y_child = it.current();
ADynNode* y_child_dyn = dynamic_cast<ADynNode*>(y_child);
DIAG_Assert(y_child_dyn, "ANode::mergeDeep");
it++; // advance iterator -- it is pointing at 'child'
MergeEffectList* effctLst1 = NULL;
ADynNode* x_child_dyn = x->findDynChild(*y_child_dyn);
if (!x_child_dyn) {
// case 1: insert nodes
DIAG_Assert( !(mrgCtxt.flags() & MrgFlg_AssertCCTMergeOnly),
"CCT::ANode::mergeDeep: adding not permitted");
if ( !(mrgCtxt.flags() & MrgFlg_CCTMergeOnly) ) {
DIAG_MsgIf(0 /*(oFlag & Tree::OFlg_Debug)*/,
"CCT::ANode::mergeDeep: Adding:\n "
<< y_child->toStringMe(Tree::OFlg_Debug));
y_child->unlink();
effctLst1 = y_child->mergeDeep_fixInsert(x_newMetricBegIdx, mrgCtxt);
y_child->link(x);
}
}
else {
// case 2: merge nodes
DIAG_MsgIf(0 /*(oFlag & Tree::OFlg_Debug)*/,
"CCT::ANode::mergeDeep: Merging x <= y:\n"
<< " x: " << x_child_dyn->toStringMe(Tree::OFlg_Debug)
<< "\n y: " << y_child_dyn->toStringMe(Tree::OFlg_Debug));
MergeEffect effct =
x_child_dyn->mergeMe(*y_child_dyn, &mrgCtxt, x_newMetricBegIdx);
if (mrgCtxt.doPropagateEffects() && !effct.isNoop()) {
effctLst->push_back(effct);
}
effctLst1 = x_child_dyn->mergeDeep(y_child, x_newMetricBegIdx, mrgCtxt,
oFlag);
}
if (effctLst1 && !effctLst1->empty()) {
effctLst->splice(effctLst->end(), *effctLst1);
DIAG_MsgIf(0, MergeEffect::toString(*effctLst));
}
delete effctLst1;
}
return effctLst;
}
MergeEffect
ANode::merge(ANode* y)
{
ANode* x = this;
// 1. copy y's metrics into x
MergeEffect effct = x->mergeMe(*y);
// 2. copy y's children into x
for (ANodeChildIterator it(y); it.Current(); /* */) {
ANode* y_child = it.current();
it++; // advance iterator -- it is pointing at 'y_child'
y_child->unlink();
y_child->link(x);
}
y->unlink();
delete y;
return effct;
}
MergeEffect
ANode::mergeMe(const ANode& y, MergeContext* mrgCtxt, uint metricBegIdx)
{
ANode* x = this;
uint x_end = metricBegIdx + y.numMetrics(); // open upper bound
if ( !(x_end <= x->numMetrics()) ) {
ensureMetricsSize(x_end);
}
for (uint x_i = metricBegIdx, y_i = 0; x_i < x_end; ++x_i, ++y_i) {
x->metric(x_i) += y.metric(y_i);
}
MergeEffect noopEffect;
return noopEffect;
}
MergeEffect
ADynNode::mergeMe(const ANode& y, MergeContext* mrgCtxt, uint metricBegIdx)
{
// N.B.: Assumes ADynNode::isMergable() holds
ADynNode* x = this;
const ADynNode* y_dyn = dynamic_cast<const ADynNode*>(&y);
DIAG_Assert(y_dyn, "ADynNode::mergeMe: " << DIAG_UnexpectedInput);
MergeEffect effct = ANode::mergeMe(y, mrgCtxt, metricBegIdx);
// merge cp-ids
if (hasMergeEffects(*x, *y_dyn)) {
// 1. Conflicting ids:
// => keep x's cpId; within y, translate [y_dyn->m_cpId ==> m_cpId]
effct.old_cpId = y_dyn->m_cpId;
effct.new_cpId = m_cpId;
}
else if (y_dyn->cpId() == HPCRUN_FMT_CCTNodeId_NULL) {
// 2. Trivial conflict: y's cpId is NULL; x's may or may not be NULL:
// => keep x's cpId.
}
else if (m_cpId == HPCRUN_FMT_CCTNodeId_NULL) {
// 3. Semi-trivial conflict: x's cpId is NULL, but y's is not
// => use y's cpId *if* it does not conflict with one already
// in x's tree.
DIAG_Assert(mrgCtxt, "ADynNode::mergeMe: potentially introducing cp-id conflicts; cannot verify with out MergeContext!");
MergeContext::pair ret = mrgCtxt->ensureUniqueCPId(y_dyn->cpId());
m_cpId = ret.cpId;
DIAG_Assert(effct.isNoop(), DIAG_UnexpectedInput);
effct = ret.effect;
}
return effct;
}
ADynNode*
ANode::findDynChild(const ADynNode& y_dyn)
{
for (ANodeChildIterator it(this); it.Current(); ++it) {
ANode* x = it.current();
ADynNode* x_dyn = dynamic_cast<ADynNode*>(x);
if (x_dyn) {
// Base case: an ADynNode descendent
if (ADynNode::isMergable(*x_dyn, y_dyn)) {
return x_dyn;
}
}
else {
// Inductive case: some other type; find the first ADynNode descendents.
ADynNode* x_dyn_descendent = x->findDynChild(y_dyn);
if (x_dyn_descendent) {
return x_dyn_descendent;
}
}
}
return NULL;
}
MergeEffectList*
ANode::mergeDeep_fixInsert(int newMetrics, MergeContext& mrgCtxt)
{
// Assumes: While merging CCT::Tree y into CCT::Tree x, subtree
// 'this', which used to live in 'y', has just been inserted into
// 'x'.
MergeEffectList* effctLst = new MergeEffectList();
for (ANodeIterator it(this); it.Current(); ++it) {
ANode* n = it.current();
// -----------------------------------------------------
// 1. Ensure no cpId in subtree 'this' conflicts with an existing
// cpId in CCT::Tree x.
// -----------------------------------------------------
ADynNode* n_dyn = dynamic_cast<ADynNode*>(n);
if (n_dyn) {
MergeContext::pair ret = mrgCtxt.ensureUniqueCPId(n_dyn->cpId());
n_dyn->cpId(ret.cpId);
if (!ret.effect.isNoop()) {
effctLst->push_back(ret.effect);
}
}
// -----------------------------------------------------
// 2. Make space for the metrics of CCT::Tree x
// -----------------------------------------------------
n->insertMetricsBefore(newMetrics);
}
return effctLst;
}
//**********************************************************************
//
//**********************************************************************
uint
ANode::makeDensePreorderIds(uint nextId)
{
// N.B.: use a sorted iterator to support hpcprof-mpi where we need
// to ensure multiple processes obtain the same numbering.
id(nextId);
nextId++;
for (ANodeSortedChildIterator it(this, ANodeSortedIterator::cmpByStructureInfo);
it.current(); it++) {
CCT::ANode* n = it.current();
nextId = n->makeDensePreorderIds(nextId);
}
return nextId;
}
//**********************************************************************
// ANode, etc: CodeName methods
//**********************************************************************
// NOTE: tallent: used for lush_cilkNormalize
string
ANode::codeName() const
{
string self = ANodeTyToName(type()) + " "
//+ GetFile() + ":"
+ StrUtil::toStr(begLine()) + "-" + StrUtil::toStr(endLine());
return self;
}
string
ProcFrm::codeName() const
{
string self = ANodeTyToName(type()) + " "
+ procName() + " @ "
+ fileName() + ":"
+ StrUtil::toStr(begLine()) + "-" + StrUtil::toStr(endLine());
return self;
}
string
ProcFrm::procNameDbg() const
{
string nm = procName();
CCT::Call* caller = ancestorCall();
if (caller) {
nm += " <= " + caller->nameDyn();
}
return nm;
}
//**********************************************************************
// ANode, etc: Dump contents for inspection
//**********************************************************************
string
ANode::toString(uint oFlags, const char* pfx) const
{
std::ostringstream os;
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags, pfx);
return os.str();
}
string
ANode::toStringMe(uint oFlags) const
{
string self;
self = ANodeTyToName(type());
SrcFile::ln lnBeg = begLine();
string line = StrUtil::toStr(lnBeg);
//SrcFile::ln lnEnd = endLine();
//if (lnBeg != lnEnd) {
// line += "-" + StrUtil::toStr(lnEnd);
//}
uint sId = (m_strct) ? m_strct->id() : 0;
self += " i" + xml::MakeAttrNum(m_id);
self += " s" + xml::MakeAttrNum(sId) + " l" + xml::MakeAttrStr(line);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " strct" + xml::MakeAttrNum((uintptr_t)m_strct, 16);
}
return self;
}
string
ADynNode::assocInfo_str() const
{
char str[LUSH_ASSOC_INFO_STR_MIN_LEN];
lush_assoc_info_sprintf(str, m_as_info);
return string(str);
}
string
ADynNode::lip_str() const
{
char str[LUSH_LIP_STR_MIN_LEN];
lush_lip_sprintf(str, m_lip);
return string(str);
}
string
ADynNode::nameDyn() const
{
string nm = "[assoc(" + assocInfo_str() + ") ip("
+ StrUtil::toStr(lmId_real()) + ", "
+ StrUtil::toStr(lmIP_real(), 16) + ") lip(" + lip_str() + ")]";
return nm;
}
void
ADynNode::writeDyn(std::ostream& o, uint oFlags, const char* pfx) const
{
string p(pfx);
o << std::showbase;
o << p << assocInfo_str()
<< hex << " [ip " << m_lmIP << ", " << dec << m_opIdx << "] "
<< hex << m_lip << " [lip " << lip_str() << "]" << dec;
o << p << " [metrics";
for (uint i = 0; i < numMetrics(); ++i) {
o << " " << metric(i);
}
o << "]" << endl;
}
string
Root::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags) + " n" + xml::MakeAttrStr(m_name);
return self;
}
string
ProcFrm::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if (m_strct) {
string lm_nm = xml::MakeAttrNum(lmId());
string fnm = xml::MakeAttrNum(fileId());
string pnm = xml::MakeAttrNum(procId());
if (oFlags & Tree::OFlg_DebugAll) {
lm_nm = xml::MakeAttrStr(lmName());
fnm = xml::MakeAttrStr(fileName());
}
if ( (oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll) ) {
pnm = xml::MakeAttrStr(procNameDbg());
}
self += " lm" + lm_nm + " f" + fnm + " n" + pnm;
}
return self;
}
string
Proc::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if (m_strct) {
string lm_nm = xml::MakeAttrNum(lmId());
string fnm = xml::MakeAttrNum(fileId());
string pnm = xml::MakeAttrNum(procId());
if (oFlags & Tree::OFlg_DebugAll) {
lm_nm = xml::MakeAttrStr(lmName());
fnm = xml::MakeAttrStr(fileName());
pnm = xml::MakeAttrStr(procName());
}
self += " lm" + lm_nm + " f" + fnm + " n" + pnm;
if (isAlien()) {
self = self + " a=\"1\"";
}
}
return self;
}
string
Loop::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
return self;
}
string
Call::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " n=\"" + nameDyn() + "\"";
}
return self;
}
string
Stmt::toStringMe(uint oFlags) const
{
string self = ANode::toStringMe(oFlags);
if ((oFlags & Tree::OFlg_Debug) || (oFlags & Tree::OFlg_DebugAll)) {
self += " n=\"" + nameDyn() + "\"";
}
if (hpcrun_fmt_doRetainId(cpId())) {
self += " it" + xml::MakeAttrNum(cpId());
}
return self;
}
std::ostream&
ANode::writeXML(ostream& os, uint metricBeg, uint metricEnd,
uint oFlags, const char* pfx) const
{
string indent = " ";
if (oFlags & CCT::Tree::OFlg_Compressed) {
pfx = "";
indent = "";
}
bool doPost = writeXML_pre(os, metricBeg, metricEnd, oFlags, pfx);
string prefix = pfx + indent;
for (ANodeSortedChildIterator it(this, ANodeSortedIterator::cmpByStructureInfo);
it.current(); it++) {
ANode* n = it.current();
n->writeXML(os, metricBeg, metricEnd, oFlags, prefix.c_str());
}
if (doPost) {
writeXML_post(os, oFlags, pfx);
}
return os;
}
std::ostream&
ANode::dump(ostream& os, uint oFlags, const char* pfx) const
{
writeXML(os, Metric::IData::npos, Metric::IData::npos, oFlags, pfx);
return os;
}
void
ANode::ddump() const
{
writeXML(std::cerr, Metric::IData::npos, Metric::IData::npos,
Tree::OFlg_DebugAll, "");
}
void
ANode::ddumpMe() const
{
string str = toStringMe(Tree::OFlg_DebugAll);
std::cerr << str;
}
bool
ANode::writeXML_pre(ostream& os, uint metricBeg, uint metricEnd,
uint oFlags, const char* pfx) const
{
bool doTag = (type() != TyRoot);
bool doMetrics = ((oFlags & Tree::OFlg_LeafMetricsOnly)
? isLeaf() && hasMetrics(metricBeg, metricEnd)
: hasMetrics(metricBeg, metricEnd));
bool isXMLLeaf = isLeaf() && !doMetrics;
// 1. Write element name
if (doTag) {
if (isXMLLeaf) {
os << pfx << "<" << toStringMe(oFlags) << "/>" << endl;
}
else {
os << pfx << "<" << toStringMe(oFlags) << ">" << endl;
}
}
// 2. Write associated metrics
if (doMetrics) {
writeMetricsXML(os, metricBeg, metricEnd, oFlags, pfx);
os << endl;
}
return !isXMLLeaf; // whether to execute writeXML_post()
}
void
ANode::writeXML_post(ostream& os, uint oFlags, const char* pfx) const
{
bool doTag = (type() != ANode::TyRoot);
if (!doTag) {
return;
}
os << pfx << "</" << ANodeTyToName(type()) << ">" << endl;
}
//**********************************************************************
//
//**********************************************************************
int ANodeLineComp(ANode* x, ANode* y)
{
if (x->begLine() == y->begLine()) {
// Given two ANode's with identical endpoints consider two
// special cases:
bool endLinesEqual = (x->endLine() == y->endLine());
// 1. Otherwise: rank a leaf node before a non-leaf node
if (endLinesEqual && !(x->isLeaf() && y->isLeaf())) {
if (x->isLeaf()) { return -1; } // x < y
else if (y->isLeaf()) { return 1; } // x > y
}
// 2. General case
return SrcFile::compare(x->endLine(), y->endLine());
}
else {
return SrcFile::compare(x->begLine(), y->begLine());
}
}
} // namespace CCT
} // namespace Prof
|
#include <iostream>
extern "C"
{
#include <unistd.h>
}
#include "pqxx/connection.h"
#include "pqxx/transaction.h"
#include "pqxx/trigger.h"
#include "pqxx/result.h"
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
//
// Usage: test4 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
// Sample implementation of trigger handler
class TestTrig : public Trigger
{
bool m_Done;
public:
explicit TestTrig(Connection &C) : Trigger(C, "trig"), m_Done(false) {}
virtual void operator()(int be_pid)
{
m_Done = true;
if (be_pid != Conn().BackendPID())
throw logic_error("Expected notification from backend process " +
ToString(Conn().BackendPID()) +
", but got one from " +
ToString(be_pid));
cout << "Received notification: " << Name() << " pid=" << be_pid << endl;
}
bool Done() const { return m_Done; }
};
// A Transactor to trigger our trigger handler
class Notify : public Transactor
{
string m_Trigger;
public:
explicit Notify(string TrigName) :
Transactor("Notifier"), m_Trigger(TrigName) { }
void operator()(TRANSACTIONTYPE &T)
{
T.Exec(("NOTIFY " + m_Trigger).c_str());
}
void OnAbort(const char Reason[]) throw ()
{
try
{
cerr << "Notify failed!" << endl;
if (Reason) cerr << "Reason: " << Reason << endl;
}
catch (const exception &)
{
}
}
};
int main(int argc, char *argv[])
{
try
{
Connection C(argv[1] ? argv[1] : "");
cout << "Adding trigger..." << endl;
TestTrig Trig(C);
cout << "Sending notification..." << endl;
C.Perform(Notify(Trig.Name()));
for (int i=0; (i < 20) && !Trig.Done(); ++i)
{
sleep(1);
C.GetNotifs();
cout << ".";
}
cout << endl;
if (!Trig.Done())
{
cout << "No notification received!" << endl;
return 1;
}
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
Windows workaround
#include <iostream>
#include "pqxx/connection.h"
#include "pqxx/transaction.h"
#include "pqxx/trigger.h"
#include "pqxx/result.h"
// Make sure we have the Unix sleep() function, which Windows provides in a
// slightly different form
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
inline void sleep(unsigned seconds)
{
Sleep(seconds * 1000);
}
#else
extern "C"
{
#include <unistd.h>
}
#endif
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
//
// Usage: test4 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
// Sample implementation of trigger handler
class TestTrig : public Trigger
{
bool m_Done;
public:
explicit TestTrig(Connection &C) : Trigger(C, "trig"), m_Done(false) {}
virtual void operator()(int be_pid)
{
m_Done = true;
if (be_pid != Conn().BackendPID())
throw logic_error("Expected notification from backend process " +
ToString(Conn().BackendPID()) +
", but got one from " +
ToString(be_pid));
cout << "Received notification: " << Name() << " pid=" << be_pid << endl;
}
bool Done() const { return m_Done; }
};
// A Transactor to trigger our trigger handler
class Notify : public Transactor
{
string m_Trigger;
public:
explicit Notify(string TrigName) :
Transactor("Notifier"), m_Trigger(TrigName) { }
void operator()(TRANSACTIONTYPE &T)
{
T.Exec(("NOTIFY " + m_Trigger).c_str());
}
void OnAbort(const char Reason[]) throw ()
{
try
{
cerr << "Notify failed!" << endl;
if (Reason) cerr << "Reason: " << Reason << endl;
}
catch (const exception &)
{
}
}
};
int main(int argc, char *argv[])
{
try
{
Connection C(argv[1] ? argv[1] : "");
cout << "Adding trigger..." << endl;
TestTrig Trig(C);
cout << "Sending notification..." << endl;
C.Perform(Notify(Trig.Name()));
for (int i=0; (i < 20) && !Trig.Done(); ++i)
{
sleep(1);
C.GetNotifs();
cout << ".";
}
cout << endl;
if (!Trig.Done())
{
cout << "No notification received!" << endl;
return 1;
}
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifdef WEBRTC_ANDROID
#include <sys/stat.h>
#endif
#include <algorithm>
#include "gtest/gtest.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/cpu_features_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/perf_test.h"
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
#else
#include "webrtc/audio_processing/debug.pb.h"
#endif
using webrtc::AudioFrame;
using webrtc::AudioProcessing;
using webrtc::EchoCancellation;
using webrtc::GainControl;
using webrtc::NoiseSuppression;
using webrtc::scoped_array;
using webrtc::TickInterval;
using webrtc::TickTime;
using webrtc::VoiceDetection;
using webrtc::audioproc::Event;
using webrtc::audioproc::Init;
using webrtc::audioproc::ReverseStream;
using webrtc::audioproc::Stream;
namespace {
// Returns true on success, false on error or end-of-file.
bool ReadMessageFromFile(FILE* file,
::google::protobuf::MessageLite* msg) {
// The "wire format" for the size is little-endian.
// Assume process_test is running on a little-endian machine.
int32_t size = 0;
if (fread(&size, sizeof(int32_t), 1, file) != 1) {
return false;
}
if (size <= 0) {
return false;
}
const size_t usize = static_cast<size_t>(size);
scoped_array<char> array(new char[usize]);
if (fread(array.get(), sizeof(char), usize, file) != usize) {
return false;
}
msg->Clear();
return msg->ParseFromArray(array.get(), usize);
}
void PrintStat(const AudioProcessing::Statistic& stat) {
printf("%d, %d, %d\n", stat.average,
stat.maximum,
stat.minimum);
}
void usage() {
printf(
"Usage: process_test [options] [-pb PROTOBUF_FILE]\n"
" [-ir REVERSE_FILE] [-i PRIMARY_FILE] [-o OUT_FILE]\n");
printf(
"process_test is a test application for AudioProcessing.\n\n"
"When a protobuf debug file is available, specify it with -pb.\n"
"Alternately, when -ir or -i is used, the specified files will be\n"
"processed directly in a simulation mode. Otherwise the full set of\n"
"legacy test files is expected to be present in the working directory.\n");
printf("\n");
printf("Options\n");
printf("General configuration (only used for the simulation mode):\n");
printf(" -fs SAMPLE_RATE_HZ\n");
printf(" -ch CHANNELS_IN CHANNELS_OUT\n");
printf(" -rch REVERSE_CHANNELS\n");
printf("\n");
printf("Component configuration:\n");
printf(
"All components are disabled by default. Each block below begins with a\n"
"flag to enable the component with default settings. The subsequent flags\n"
"in the block are used to provide configuration settings.\n");
printf("\n -aec Echo cancellation\n");
printf(" --drift_compensation\n");
printf(" --no_drift_compensation\n");
printf(" --no_echo_metrics\n");
printf(" --no_delay_logging\n");
printf("\n -aecm Echo control mobile\n");
printf(" --aecm_echo_path_in_file FILE\n");
printf(" --aecm_echo_path_out_file FILE\n");
printf(" --no_comfort_noise\n");
printf(" --routing_mode MODE [0 - 4]\n");
printf("\n -agc Gain control\n");
printf(" --analog\n");
printf(" --adaptive_digital\n");
printf(" --fixed_digital\n");
printf(" --target_level LEVEL\n");
printf(" --compression_gain GAIN\n");
printf(" --limiter\n");
printf(" --no_limiter\n");
printf("\n -hpf High pass filter\n");
printf("\n -ns Noise suppression\n");
printf(" --ns_low\n");
printf(" --ns_moderate\n");
printf(" --ns_high\n");
printf(" --ns_very_high\n");
printf(" --ns_prob_file FILE\n");
printf("\n -vad Voice activity detection\n");
printf(" --vad_out_file FILE\n");
printf("\n Level metrics (enabled by default)\n");
printf(" --no_level_metrics\n");
printf("\n");
printf("Modifiers:\n");
printf(" --noasm Disable SSE optimization.\n");
printf(" --delay DELAY Add DELAY ms to input value.\n");
printf(" --perf Measure performance.\n");
printf(" --quiet Suppress text output.\n");
printf(" --no_progress Suppress progress.\n");
printf(" --debug_file FILE Dump a debug recording.\n");
}
static float MicLevel2Gain(int level) {
return pow(10.0f, ((level - 127.0f) / 128.0f * 40.0f) / 20.0f);
}
static void SimulateMic(int mic_level, AudioFrame* frame) {
mic_level = std::min(std::max(mic_level, 0), 255);
float mic_gain = MicLevel2Gain(mic_level);
int num_samples = frame->samples_per_channel_ * frame->num_channels_;
float v;
for (int n = 0; n < num_samples; n++) {
v = floor(frame->data_[n] * mic_gain + 0.5);
v = std::max(std::min(32767.0f, v), -32768.0f);
frame->data_[n] = static_cast<int16_t>(v);
}
}
// void function for gtest.
void void_main(int argc, char* argv[]) {
if (argc > 1 && strcmp(argv[1], "--help") == 0) {
usage();
return;
}
if (argc < 2) {
printf("Did you mean to run without arguments?\n");
printf("Try `process_test --help' for more information.\n\n");
}
AudioProcessing* apm = AudioProcessing::Create(0);
ASSERT_TRUE(apm != NULL);
const char* pb_filename = NULL;
const char* far_filename = NULL;
const char* near_filename = NULL;
const char* out_filename = NULL;
const char* vad_out_filename = NULL;
const char* ns_prob_filename = NULL;
const char* aecm_echo_path_in_filename = NULL;
const char* aecm_echo_path_out_filename = NULL;
int32_t sample_rate_hz = 16000;
int32_t device_sample_rate_hz = 16000;
int num_capture_input_channels = 1;
int num_capture_output_channels = 1;
int num_render_channels = 1;
int samples_per_channel = sample_rate_hz / 100;
bool simulating = false;
bool perf_testing = false;
bool verbose = true;
bool progress = true;
int extra_delay_ms = 0;
//bool interleaved = true;
ASSERT_EQ(apm->kNoError, apm->level_estimator()->Enable(true));
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-pb") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify protobuf filename after -pb";
pb_filename = argv[i];
} else if (strcmp(argv[i], "-ir") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -ir";
far_filename = argv[i];
simulating = true;
} else if (strcmp(argv[i], "-i") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -i";
near_filename = argv[i];
simulating = true;
} else if (strcmp(argv[i], "-o") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -o";
out_filename = argv[i];
} else if (strcmp(argv[i], "-fs") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify sample rate after -fs";
ASSERT_EQ(1, sscanf(argv[i], "%d", &sample_rate_hz));
samples_per_channel = sample_rate_hz / 100;
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(sample_rate_hz));
} else if (strcmp(argv[i], "-ch") == 0) {
i++;
ASSERT_LT(i + 1, argc) << "Specify number of channels after -ch";
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_capture_input_channels));
i++;
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_capture_output_channels));
ASSERT_EQ(apm->kNoError,
apm->set_num_channels(num_capture_input_channels,
num_capture_output_channels));
} else if (strcmp(argv[i], "-rch") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify number of channels after -rch";
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_render_channels));
ASSERT_EQ(apm->kNoError,
apm->set_num_reverse_channels(num_render_channels));
} else if (strcmp(argv[i], "-aec") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_metrics(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_delay_logging(true));
} else if (strcmp(argv[i], "--drift_compensation") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
// TODO(ajm): this is enabled in the VQE test app by default. Investigate
// why it can give better performance despite passing zeros.
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_drift_compensation(true));
} else if (strcmp(argv[i], "--no_drift_compensation") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_drift_compensation(false));
} else if (strcmp(argv[i], "--no_echo_metrics") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_metrics(false));
} else if (strcmp(argv[i], "--no_delay_logging") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_delay_logging(false));
} else if (strcmp(argv[i], "--no_level_metrics") == 0) {
ASSERT_EQ(apm->kNoError, apm->level_estimator()->Enable(false));
} else if (strcmp(argv[i], "-aecm") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_control_mobile()->Enable(true));
} else if (strcmp(argv[i], "--aecm_echo_path_in_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --aecm_echo_path_in_file";
aecm_echo_path_in_filename = argv[i];
} else if (strcmp(argv[i], "--aecm_echo_path_out_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --aecm_echo_path_out_file";
aecm_echo_path_out_filename = argv[i];
} else if (strcmp(argv[i], "--no_comfort_noise") == 0) {
ASSERT_EQ(apm->kNoError,
apm->echo_control_mobile()->enable_comfort_noise(false));
} else if (strcmp(argv[i], "--routing_mode") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify mode after --routing_mode";
int routing_mode;
ASSERT_EQ(1, sscanf(argv[i], "%d", &routing_mode));
ASSERT_EQ(apm->kNoError,
apm->echo_control_mobile()->set_routing_mode(
static_cast<webrtc::EchoControlMobile::RoutingMode>(
routing_mode)));
} else if (strcmp(argv[i], "-agc") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
} else if (strcmp(argv[i], "--analog") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
} else if (strcmp(argv[i], "--adaptive_digital") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kAdaptiveDigital));
} else if (strcmp(argv[i], "--fixed_digital") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kFixedDigital));
} else if (strcmp(argv[i], "--target_level") == 0) {
i++;
int level;
ASSERT_EQ(1, sscanf(argv[i], "%d", &level));
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_target_level_dbfs(level));
} else if (strcmp(argv[i], "--compression_gain") == 0) {
i++;
int gain;
ASSERT_EQ(1, sscanf(argv[i], "%d", &gain));
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_compression_gain_db(gain));
} else if (strcmp(argv[i], "--limiter") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->enable_limiter(true));
} else if (strcmp(argv[i], "--no_limiter") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->enable_limiter(false));
} else if (strcmp(argv[i], "-hpf") == 0) {
ASSERT_EQ(apm->kNoError, apm->high_pass_filter()->Enable(true));
} else if (strcmp(argv[i], "-ns") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
} else if (strcmp(argv[i], "--ns_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kLow));
} else if (strcmp(argv[i], "--ns_moderate") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kModerate));
} else if (strcmp(argv[i], "--ns_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kHigh));
} else if (strcmp(argv[i], "--ns_very_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kVeryHigh));
} else if (strcmp(argv[i], "--ns_prob_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --ns_prob_file";
ns_prob_filename = argv[i];
} else if (strcmp(argv[i], "-vad") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
} else if (strcmp(argv[i], "--vad_very_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kVeryLowLikelihood));
} else if (strcmp(argv[i], "--vad_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kLowLikelihood));
} else if (strcmp(argv[i], "--vad_moderate") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kModerateLikelihood));
} else if (strcmp(argv[i], "--vad_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kHighLikelihood));
} else if (strcmp(argv[i], "--vad_out_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --vad_out_file";
vad_out_filename = argv[i];
} else if (strcmp(argv[i], "--noasm") == 0) {
WebRtc_GetCPUInfo = WebRtc_GetCPUInfoNoASM;
// We need to reinitialize here if components have already been enabled.
ASSERT_EQ(apm->kNoError, apm->Initialize());
} else if (strcmp(argv[i], "--delay") == 0) {
i++;
ASSERT_EQ(1, sscanf(argv[i], "%d", &extra_delay_ms));
} else if (strcmp(argv[i], "--perf") == 0) {
perf_testing = true;
} else if (strcmp(argv[i], "--quiet") == 0) {
verbose = false;
progress = false;
} else if (strcmp(argv[i], "--no_progress") == 0) {
progress = false;
} else if (strcmp(argv[i], "--debug_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --debug_file";
ASSERT_EQ(apm->kNoError, apm->StartDebugRecording(argv[i]));
} else {
FAIL() << "Unrecognized argument " << argv[i];
}
}
// If we're reading a protobuf file, ensure a simulation hasn't also
// been requested (which makes no sense...)
ASSERT_FALSE(pb_filename && simulating);
if (verbose) {
printf("Sample rate: %d Hz\n", sample_rate_hz);
printf("Primary channels: %d (in), %d (out)\n",
num_capture_input_channels,
num_capture_output_channels);
printf("Reverse channels: %d \n", num_render_channels);
}
const std::string out_path = webrtc::test::OutputPath();
const char far_file_default[] = "apm_far.pcm";
const char near_file_default[] = "apm_near.pcm";
const std::string out_file_default = out_path + "out.pcm";
const char event_filename[] = "apm_event.dat";
const char delay_filename[] = "apm_delay.dat";
const char drift_filename[] = "apm_drift.dat";
const std::string vad_file_default = out_path + "vad_out.dat";
const std::string ns_prob_file_default = out_path + "ns_prob.dat";
if (!simulating) {
far_filename = far_file_default;
near_filename = near_file_default;
}
if (!out_filename) {
out_filename = out_file_default.c_str();
}
if (!vad_out_filename) {
vad_out_filename = vad_file_default.c_str();
}
if (!ns_prob_filename) {
ns_prob_filename = ns_prob_file_default.c_str();
}
FILE* pb_file = NULL;
FILE* far_file = NULL;
FILE* near_file = NULL;
FILE* out_file = NULL;
FILE* event_file = NULL;
FILE* delay_file = NULL;
FILE* drift_file = NULL;
FILE* vad_out_file = NULL;
FILE* ns_prob_file = NULL;
FILE* aecm_echo_path_in_file = NULL;
FILE* aecm_echo_path_out_file = NULL;
if (pb_filename) {
pb_file = fopen(pb_filename, "rb");
ASSERT_TRUE(NULL != pb_file) << "Unable to open protobuf file "
<< pb_filename;
} else {
if (far_filename) {
far_file = fopen(far_filename, "rb");
ASSERT_TRUE(NULL != far_file) << "Unable to open far-end audio file "
<< far_filename;
}
near_file = fopen(near_filename, "rb");
ASSERT_TRUE(NULL != near_file) << "Unable to open near-end audio file "
<< near_filename;
if (!simulating) {
event_file = fopen(event_filename, "rb");
ASSERT_TRUE(NULL != event_file) << "Unable to open event file "
<< event_filename;
delay_file = fopen(delay_filename, "rb");
ASSERT_TRUE(NULL != delay_file) << "Unable to open buffer file "
<< delay_filename;
drift_file = fopen(drift_filename, "rb");
ASSERT_TRUE(NULL != drift_file) << "Unable to open drift file "
<< drift_filename;
}
}
out_file = fopen(out_filename, "wb");
ASSERT_TRUE(NULL != out_file) << "Unable to open output audio file "
<< out_filename;
int near_size_bytes = 0;
if (pb_file) {
struct stat st;
stat(pb_filename, &st);
// Crude estimate, but should be good enough.
near_size_bytes = st.st_size / 3;
} else {
struct stat st;
stat(near_filename, &st);
near_size_bytes = st.st_size;
}
if (apm->voice_detection()->is_enabled()) {
vad_out_file = fopen(vad_out_filename, "wb");
ASSERT_TRUE(NULL != vad_out_file) << "Unable to open VAD output file "
<< vad_out_file;
}
if (apm->noise_suppression()->is_enabled()) {
ns_prob_file = fopen(ns_prob_filename, "wb");
ASSERT_TRUE(NULL != ns_prob_file) << "Unable to open NS output file "
<< ns_prob_file;
}
if (aecm_echo_path_in_filename != NULL) {
aecm_echo_path_in_file = fopen(aecm_echo_path_in_filename, "rb");
ASSERT_TRUE(NULL != aecm_echo_path_in_file) << "Unable to open file "
<< aecm_echo_path_in_filename;
const size_t path_size =
apm->echo_control_mobile()->echo_path_size_bytes();
scoped_array<char> echo_path(new char[path_size]);
ASSERT_EQ(path_size, fread(echo_path.get(),
sizeof(char),
path_size,
aecm_echo_path_in_file));
EXPECT_EQ(apm->kNoError,
apm->echo_control_mobile()->SetEchoPath(echo_path.get(),
path_size));
fclose(aecm_echo_path_in_file);
aecm_echo_path_in_file = NULL;
}
if (aecm_echo_path_out_filename != NULL) {
aecm_echo_path_out_file = fopen(aecm_echo_path_out_filename, "wb");
ASSERT_TRUE(NULL != aecm_echo_path_out_file) << "Unable to open file "
<< aecm_echo_path_out_filename;
}
size_t read_count = 0;
int reverse_count = 0;
int primary_count = 0;
int near_read_bytes = 0;
TickInterval acc_ticks;
AudioFrame far_frame;
AudioFrame near_frame;
int delay_ms = 0;
int drift_samples = 0;
int capture_level = 127;
int8_t stream_has_voice = 0;
float ns_speech_prob = 0.0f;
TickTime t0 = TickTime::Now();
TickTime t1 = t0;
int64_t max_time_us = 0;
int64_t max_time_reverse_us = 0;
int64_t min_time_us = 1e6;
int64_t min_time_reverse_us = 1e6;
// TODO(ajm): Ideally we would refactor this block into separate functions,
// but for now we want to share the variables.
if (pb_file) {
Event event_msg;
while (ReadMessageFromFile(pb_file, &event_msg)) {
std::ostringstream trace_stream;
trace_stream << "Processed frames: " << reverse_count << " (reverse), "
<< primary_count << " (primary)";
SCOPED_TRACE(trace_stream.str());
if (event_msg.type() == Event::INIT) {
ASSERT_TRUE(event_msg.has_init());
const Init msg = event_msg.init();
ASSERT_TRUE(msg.has_sample_rate());
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(msg.sample_rate()));
ASSERT_TRUE(msg.has_device_sample_rate());
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->set_device_sample_rate_hz(
msg.device_sample_rate()));
ASSERT_TRUE(msg.has_num_input_channels());
ASSERT_TRUE(msg.has_num_output_channels());
ASSERT_EQ(apm->kNoError,
apm->set_num_channels(msg.num_input_channels(),
msg.num_output_channels()));
ASSERT_TRUE(msg.has_num_reverse_channels());
ASSERT_EQ(apm->kNoError,
apm->set_num_reverse_channels(msg.num_reverse_channels()));
samples_per_channel = msg.sample_rate() / 100;
far_frame.sample_rate_hz_ = msg.sample_rate();
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = msg.num_reverse_channels();
near_frame.sample_rate_hz_ = msg.sample_rate();
near_frame.samples_per_channel_ = samples_per_channel;
near_frame.num_channels_ = msg.num_input_channels();
if (verbose) {
printf("Init at frame: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
printf(" Sample rate: %d Hz\n", msg.sample_rate());
printf(" Primary channels: %d (in), %d (out)\n",
msg.num_input_channels(),
msg.num_output_channels());
printf(" Reverse channels: %d \n", msg.num_reverse_channels());
}
} else if (event_msg.type() == Event::REVERSE_STREAM) {
ASSERT_TRUE(event_msg.has_reverse_stream());
const ReverseStream msg = event_msg.reverse_stream();
reverse_count++;
ASSERT_TRUE(msg.has_data());
ASSERT_EQ(sizeof(int16_t) * samples_per_channel *
far_frame.num_channels_, msg.data().size());
memcpy(far_frame.data_, msg.data().data(), msg.data().size());
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->AnalyzeReverseStream(&far_frame));
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_reverse_us) {
max_time_reverse_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_reverse_us) {
min_time_reverse_us = tick_diff.Microseconds();
}
}
} else if (event_msg.type() == Event::STREAM) {
ASSERT_TRUE(event_msg.has_stream());
const Stream msg = event_msg.stream();
primary_count++;
// ProcessStream could have changed this for the output frame.
near_frame.num_channels_ = apm->num_input_channels();
ASSERT_TRUE(msg.has_input_data());
ASSERT_EQ(sizeof(int16_t) * samples_per_channel *
near_frame.num_channels_, msg.input_data().size());
memcpy(near_frame.data_,
msg.input_data().data(),
msg.input_data().size());
near_read_bytes += msg.input_data().size();
if (progress && primary_count % 100 == 0) {
printf("%.0f%% complete\r",
(near_read_bytes * 100.0) / near_size_bytes);
fflush(stdout);
}
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_stream_analog_level(msg.level()));
ASSERT_EQ(apm->kNoError,
apm->set_stream_delay_ms(msg.delay() + extra_delay_ms));
apm->echo_cancellation()->set_stream_drift_samples(msg.drift());
int err = apm->ProcessStream(&near_frame);
if (err == apm->kBadStreamParameterWarning) {
printf("Bad parameter warning. %s\n", trace_stream.str().c_str());
}
ASSERT_TRUE(err == apm->kNoError ||
err == apm->kBadStreamParameterWarning);
ASSERT_TRUE(near_frame.num_channels_ == apm->num_output_channels());
stream_has_voice =
static_cast<int8_t>(apm->voice_detection()->stream_has_voice());
if (vad_out_file != NULL) {
ASSERT_EQ(1u, fwrite(&stream_has_voice,
sizeof(stream_has_voice),
1,
vad_out_file));
}
if (ns_prob_file != NULL) {
ns_speech_prob = apm->noise_suppression()->speech_probability();
ASSERT_EQ(1u, fwrite(&ns_speech_prob,
sizeof(ns_speech_prob),
1,
ns_prob_file));
}
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_us) {
max_time_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_us) {
min_time_us = tick_diff.Microseconds();
}
}
size_t size = samples_per_channel * near_frame.num_channels_;
ASSERT_EQ(size, fwrite(near_frame.data_,
sizeof(int16_t),
size,
out_file));
}
}
ASSERT_TRUE(feof(pb_file));
} else {
enum Events {
kInitializeEvent,
kRenderEvent,
kCaptureEvent,
kResetEventDeprecated
};
int16_t event = 0;
while (simulating || feof(event_file) == 0) {
std::ostringstream trace_stream;
trace_stream << "Processed frames: " << reverse_count << " (reverse), "
<< primary_count << " (primary)";
SCOPED_TRACE(trace_stream.str());
if (simulating) {
if (far_file == NULL) {
event = kCaptureEvent;
} else {
if (event == kRenderEvent) {
event = kCaptureEvent;
} else {
event = kRenderEvent;
}
}
} else {
read_count = fread(&event, sizeof(event), 1, event_file);
if (read_count != 1) {
break;
}
}
far_frame.sample_rate_hz_ = sample_rate_hz;
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = num_render_channels;
near_frame.sample_rate_hz_ = sample_rate_hz;
near_frame.samples_per_channel_ = samples_per_channel;
if (event == kInitializeEvent || event == kResetEventDeprecated) {
ASSERT_EQ(1u,
fread(&sample_rate_hz, sizeof(sample_rate_hz), 1, event_file));
samples_per_channel = sample_rate_hz / 100;
ASSERT_EQ(1u,
fread(&device_sample_rate_hz,
sizeof(device_sample_rate_hz),
1,
event_file));
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(sample_rate_hz));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->set_device_sample_rate_hz(
device_sample_rate_hz));
far_frame.sample_rate_hz_ = sample_rate_hz;
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = num_render_channels;
near_frame.sample_rate_hz_ = sample_rate_hz;
near_frame.samples_per_channel_ = samples_per_channel;
if (verbose) {
printf("Init at frame: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
printf(" Sample rate: %d Hz\n", sample_rate_hz);
}
} else if (event == kRenderEvent) {
reverse_count++;
size_t size = samples_per_channel * num_render_channels;
read_count = fread(far_frame.data_,
sizeof(int16_t),
size,
far_file);
if (simulating) {
if (read_count != size) {
// Read an equal amount from the near file to avoid errors due to
// not reaching end-of-file.
EXPECT_EQ(0, fseek(near_file, read_count * sizeof(int16_t),
SEEK_CUR));
break; // This is expected.
}
} else {
ASSERT_EQ(size, read_count);
}
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->AnalyzeReverseStream(&far_frame));
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_reverse_us) {
max_time_reverse_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_reverse_us) {
min_time_reverse_us = tick_diff.Microseconds();
}
}
} else if (event == kCaptureEvent) {
primary_count++;
near_frame.num_channels_ = num_capture_input_channels;
size_t size = samples_per_channel * num_capture_input_channels;
read_count = fread(near_frame.data_,
sizeof(int16_t),
size,
near_file);
near_read_bytes += read_count * sizeof(int16_t);
if (progress && primary_count % 100 == 0) {
printf("%.0f%% complete\r",
(near_read_bytes * 100.0) / near_size_bytes);
fflush(stdout);
}
if (simulating) {
if (read_count != size) {
break; // This is expected.
}
delay_ms = 0;
drift_samples = 0;
} else {
ASSERT_EQ(size, read_count);
// TODO(ajm): sizeof(delay_ms) for current files?
ASSERT_EQ(1u,
fread(&delay_ms, 2, 1, delay_file));
ASSERT_EQ(1u,
fread(&drift_samples, sizeof(drift_samples), 1, drift_file));
}
if (apm->gain_control()->is_enabled() &&
apm->gain_control()->mode() == GainControl::kAdaptiveAnalog) {
SimulateMic(capture_level, &near_frame);
}
if (perf_testing) {
t0 = TickTime::Now();
}
const int capture_level_in = capture_level;
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_stream_analog_level(capture_level));
ASSERT_EQ(apm->kNoError,
apm->set_stream_delay_ms(delay_ms + extra_delay_ms));
apm->echo_cancellation()->set_stream_drift_samples(drift_samples);
int err = apm->ProcessStream(&near_frame);
if (err == apm->kBadStreamParameterWarning) {
printf("Bad parameter warning. %s\n", trace_stream.str().c_str());
}
ASSERT_TRUE(err == apm->kNoError ||
err == apm->kBadStreamParameterWarning);
ASSERT_TRUE(near_frame.num_channels_ == apm->num_output_channels());
capture_level = apm->gain_control()->stream_analog_level();
stream_has_voice =
static_cast<int8_t>(apm->voice_detection()->stream_has_voice());
if (vad_out_file != NULL) {
ASSERT_EQ(1u, fwrite(&stream_has_voice,
sizeof(stream_has_voice),
1,
vad_out_file));
}
if (ns_prob_file != NULL) {
ns_speech_prob = apm->noise_suppression()->speech_probability();
ASSERT_EQ(1u, fwrite(&ns_speech_prob,
sizeof(ns_speech_prob),
1,
ns_prob_file));
}
if (apm->gain_control()->mode() != GainControl::kAdaptiveAnalog) {
ASSERT_EQ(capture_level_in, capture_level);
}
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_us) {
max_time_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_us) {
min_time_us = tick_diff.Microseconds();
}
}
size = samples_per_channel * near_frame.num_channels_;
ASSERT_EQ(size, fwrite(near_frame.data_,
sizeof(int16_t),
size,
out_file));
}
else {
FAIL() << "Event " << event << " is unrecognized";
}
}
}
printf("100%% complete\r");
if (aecm_echo_path_out_file != NULL) {
const size_t path_size =
apm->echo_control_mobile()->echo_path_size_bytes();
scoped_array<char> echo_path(new char[path_size]);
apm->echo_control_mobile()->GetEchoPath(echo_path.get(), path_size);
ASSERT_EQ(path_size, fwrite(echo_path.get(),
sizeof(char),
path_size,
aecm_echo_path_out_file));
fclose(aecm_echo_path_out_file);
aecm_echo_path_out_file = NULL;
}
if (verbose) {
printf("\nProcessed frames: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
if (apm->level_estimator()->is_enabled()) {
printf("\n--Level metrics--\n");
printf("RMS: %d dBFS\n", -apm->level_estimator()->RMS());
}
if (apm->echo_cancellation()->are_metrics_enabled()) {
EchoCancellation::Metrics metrics;
apm->echo_cancellation()->GetMetrics(&metrics);
printf("\n--Echo metrics--\n");
printf("(avg, max, min)\n");
printf("ERL: ");
PrintStat(metrics.echo_return_loss);
printf("ERLE: ");
PrintStat(metrics.echo_return_loss_enhancement);
printf("ANLP: ");
PrintStat(metrics.a_nlp);
}
if (apm->echo_cancellation()->is_delay_logging_enabled()) {
int median = 0;
int std = 0;
apm->echo_cancellation()->GetDelayMetrics(&median, &std);
printf("\n--Delay metrics--\n");
printf("Median: %3d\n", median);
printf("Standard deviation: %3d\n", std);
}
}
if (!pb_file) {
int8_t temp_int8;
if (far_file) {
read_count = fread(&temp_int8, sizeof(temp_int8), 1, far_file);
EXPECT_NE(0, feof(far_file)) << "Far-end file not fully processed";
}
read_count = fread(&temp_int8, sizeof(temp_int8), 1, near_file);
EXPECT_NE(0, feof(near_file)) << "Near-end file not fully processed";
if (!simulating) {
read_count = fread(&temp_int8, sizeof(temp_int8), 1, event_file);
EXPECT_NE(0, feof(event_file)) << "Event file not fully processed";
read_count = fread(&temp_int8, sizeof(temp_int8), 1, delay_file);
EXPECT_NE(0, feof(delay_file)) << "Delay file not fully processed";
read_count = fread(&temp_int8, sizeof(temp_int8), 1, drift_file);
EXPECT_NE(0, feof(drift_file)) << "Drift file not fully processed";
}
}
if (perf_testing) {
if (primary_count > 0) {
int64_t exec_time = acc_ticks.Milliseconds();
printf("\nTotal time: %.3f s, file time: %.2f s\n",
exec_time * 0.001, primary_count * 0.01);
printf("Time per frame: %.3f ms (average), %.3f ms (max),"
" %.3f ms (min)\n",
(exec_time * 1.0) / primary_count,
(max_time_us + max_time_reverse_us) / 1000.0,
(min_time_us + min_time_reverse_us) / 1000.0);
// Record the results with Perf test tools.
webrtc::test::PrintResult("audioproc", "", "time_per_10ms_frame",
(exec_time * 1000) / primary_count, "us", false);
} else {
printf("Warning: no capture frames\n");
}
}
AudioProcessing::Destroy(apm);
apm = NULL;
}
} // namespace
int main(int argc, char* argv[])
{
void_main(argc, argv);
// Optional, but removes memory leak noise from Valgrind.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
Add AEC suppression level option to audioproc.
TBR=bjornv
Review URL: https://webrtc-codereview.appspot.com/1368007
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: dff69c56b06418a1267a280a9ea419502741ba05
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifdef WEBRTC_ANDROID
#include <sys/stat.h>
#endif
#include <algorithm>
#include "gtest/gtest.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/cpu_features_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/perf_test.h"
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
#else
#include "webrtc/audio_processing/debug.pb.h"
#endif
using webrtc::AudioFrame;
using webrtc::AudioProcessing;
using webrtc::EchoCancellation;
using webrtc::GainControl;
using webrtc::NoiseSuppression;
using webrtc::scoped_array;
using webrtc::TickInterval;
using webrtc::TickTime;
using webrtc::VoiceDetection;
using webrtc::audioproc::Event;
using webrtc::audioproc::Init;
using webrtc::audioproc::ReverseStream;
using webrtc::audioproc::Stream;
namespace {
// Returns true on success, false on error or end-of-file.
bool ReadMessageFromFile(FILE* file,
::google::protobuf::MessageLite* msg) {
// The "wire format" for the size is little-endian.
// Assume process_test is running on a little-endian machine.
int32_t size = 0;
if (fread(&size, sizeof(int32_t), 1, file) != 1) {
return false;
}
if (size <= 0) {
return false;
}
const size_t usize = static_cast<size_t>(size);
scoped_array<char> array(new char[usize]);
if (fread(array.get(), sizeof(char), usize, file) != usize) {
return false;
}
msg->Clear();
return msg->ParseFromArray(array.get(), usize);
}
void PrintStat(const AudioProcessing::Statistic& stat) {
printf("%d, %d, %d\n", stat.average,
stat.maximum,
stat.minimum);
}
void usage() {
printf(
"Usage: process_test [options] [-pb PROTOBUF_FILE]\n"
" [-ir REVERSE_FILE] [-i PRIMARY_FILE] [-o OUT_FILE]\n");
printf(
"process_test is a test application for AudioProcessing.\n\n"
"When a protobuf debug file is available, specify it with -pb.\n"
"Alternately, when -ir or -i is used, the specified files will be\n"
"processed directly in a simulation mode. Otherwise the full set of\n"
"legacy test files is expected to be present in the working directory.\n");
printf("\n");
printf("Options\n");
printf("General configuration (only used for the simulation mode):\n");
printf(" -fs SAMPLE_RATE_HZ\n");
printf(" -ch CHANNELS_IN CHANNELS_OUT\n");
printf(" -rch REVERSE_CHANNELS\n");
printf("\n");
printf("Component configuration:\n");
printf(
"All components are disabled by default. Each block below begins with a\n"
"flag to enable the component with default settings. The subsequent flags\n"
"in the block are used to provide configuration settings.\n");
printf("\n -aec Echo cancellation\n");
printf(" --drift_compensation\n");
printf(" --no_drift_compensation\n");
printf(" --no_echo_metrics\n");
printf(" --no_delay_logging\n");
printf(" --aec_suppression_level LEVEL [0 - 2]\n");
printf("\n -aecm Echo control mobile\n");
printf(" --aecm_echo_path_in_file FILE\n");
printf(" --aecm_echo_path_out_file FILE\n");
printf(" --no_comfort_noise\n");
printf(" --routing_mode MODE [0 - 4]\n");
printf("\n -agc Gain control\n");
printf(" --analog\n");
printf(" --adaptive_digital\n");
printf(" --fixed_digital\n");
printf(" --target_level LEVEL\n");
printf(" --compression_gain GAIN\n");
printf(" --limiter\n");
printf(" --no_limiter\n");
printf("\n -hpf High pass filter\n");
printf("\n -ns Noise suppression\n");
printf(" --ns_low\n");
printf(" --ns_moderate\n");
printf(" --ns_high\n");
printf(" --ns_very_high\n");
printf(" --ns_prob_file FILE\n");
printf("\n -vad Voice activity detection\n");
printf(" --vad_out_file FILE\n");
printf("\n Level metrics (enabled by default)\n");
printf(" --no_level_metrics\n");
printf("\n");
printf("Modifiers:\n");
printf(" --noasm Disable SSE optimization.\n");
printf(" --delay DELAY Add DELAY ms to input value.\n");
printf(" --perf Measure performance.\n");
printf(" --quiet Suppress text output.\n");
printf(" --no_progress Suppress progress.\n");
printf(" --debug_file FILE Dump a debug recording.\n");
}
static float MicLevel2Gain(int level) {
return pow(10.0f, ((level - 127.0f) / 128.0f * 40.0f) / 20.0f);
}
static void SimulateMic(int mic_level, AudioFrame* frame) {
mic_level = std::min(std::max(mic_level, 0), 255);
float mic_gain = MicLevel2Gain(mic_level);
int num_samples = frame->samples_per_channel_ * frame->num_channels_;
float v;
for (int n = 0; n < num_samples; n++) {
v = floor(frame->data_[n] * mic_gain + 0.5);
v = std::max(std::min(32767.0f, v), -32768.0f);
frame->data_[n] = static_cast<int16_t>(v);
}
}
// void function for gtest.
void void_main(int argc, char* argv[]) {
if (argc > 1 && strcmp(argv[1], "--help") == 0) {
usage();
return;
}
if (argc < 2) {
printf("Did you mean to run without arguments?\n");
printf("Try `process_test --help' for more information.\n\n");
}
AudioProcessing* apm = AudioProcessing::Create(0);
ASSERT_TRUE(apm != NULL);
const char* pb_filename = NULL;
const char* far_filename = NULL;
const char* near_filename = NULL;
const char* out_filename = NULL;
const char* vad_out_filename = NULL;
const char* ns_prob_filename = NULL;
const char* aecm_echo_path_in_filename = NULL;
const char* aecm_echo_path_out_filename = NULL;
int32_t sample_rate_hz = 16000;
int32_t device_sample_rate_hz = 16000;
int num_capture_input_channels = 1;
int num_capture_output_channels = 1;
int num_render_channels = 1;
int samples_per_channel = sample_rate_hz / 100;
bool simulating = false;
bool perf_testing = false;
bool verbose = true;
bool progress = true;
int extra_delay_ms = 0;
//bool interleaved = true;
ASSERT_EQ(apm->kNoError, apm->level_estimator()->Enable(true));
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-pb") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify protobuf filename after -pb";
pb_filename = argv[i];
} else if (strcmp(argv[i], "-ir") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -ir";
far_filename = argv[i];
simulating = true;
} else if (strcmp(argv[i], "-i") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -i";
near_filename = argv[i];
simulating = true;
} else if (strcmp(argv[i], "-o") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after -o";
out_filename = argv[i];
} else if (strcmp(argv[i], "-fs") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify sample rate after -fs";
ASSERT_EQ(1, sscanf(argv[i], "%d", &sample_rate_hz));
samples_per_channel = sample_rate_hz / 100;
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(sample_rate_hz));
} else if (strcmp(argv[i], "-ch") == 0) {
i++;
ASSERT_LT(i + 1, argc) << "Specify number of channels after -ch";
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_capture_input_channels));
i++;
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_capture_output_channels));
ASSERT_EQ(apm->kNoError,
apm->set_num_channels(num_capture_input_channels,
num_capture_output_channels));
} else if (strcmp(argv[i], "-rch") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify number of channels after -rch";
ASSERT_EQ(1, sscanf(argv[i], "%d", &num_render_channels));
ASSERT_EQ(apm->kNoError,
apm->set_num_reverse_channels(num_render_channels));
} else if (strcmp(argv[i], "-aec") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_metrics(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_delay_logging(true));
} else if (strcmp(argv[i], "--drift_compensation") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
// TODO(ajm): this is enabled in the VQE test app by default. Investigate
// why it can give better performance despite passing zeros.
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_drift_compensation(true));
} else if (strcmp(argv[i], "--no_drift_compensation") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_drift_compensation(false));
} else if (strcmp(argv[i], "--no_echo_metrics") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_metrics(false));
} else if (strcmp(argv[i], "--no_delay_logging") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_cancellation()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->enable_delay_logging(false));
} else if (strcmp(argv[i], "--no_level_metrics") == 0) {
ASSERT_EQ(apm->kNoError, apm->level_estimator()->Enable(false));
} else if (strcmp(argv[i], "--aec_suppression_level") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify level after --aec_suppression_level";
int suppression_level;
ASSERT_EQ(1, sscanf(argv[i], "%d", &suppression_level));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->set_suppression_level(
static_cast<webrtc::EchoCancellation::SuppressionLevel>(
suppression_level)));
} else if (strcmp(argv[i], "-aecm") == 0) {
ASSERT_EQ(apm->kNoError, apm->echo_control_mobile()->Enable(true));
} else if (strcmp(argv[i], "--aecm_echo_path_in_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --aecm_echo_path_in_file";
aecm_echo_path_in_filename = argv[i];
} else if (strcmp(argv[i], "--aecm_echo_path_out_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --aecm_echo_path_out_file";
aecm_echo_path_out_filename = argv[i];
} else if (strcmp(argv[i], "--no_comfort_noise") == 0) {
ASSERT_EQ(apm->kNoError,
apm->echo_control_mobile()->enable_comfort_noise(false));
} else if (strcmp(argv[i], "--routing_mode") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify mode after --routing_mode";
int routing_mode;
ASSERT_EQ(1, sscanf(argv[i], "%d", &routing_mode));
ASSERT_EQ(apm->kNoError,
apm->echo_control_mobile()->set_routing_mode(
static_cast<webrtc::EchoControlMobile::RoutingMode>(
routing_mode)));
} else if (strcmp(argv[i], "-agc") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
} else if (strcmp(argv[i], "--analog") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kAdaptiveAnalog));
} else if (strcmp(argv[i], "--adaptive_digital") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kAdaptiveDigital));
} else if (strcmp(argv[i], "--fixed_digital") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_mode(GainControl::kFixedDigital));
} else if (strcmp(argv[i], "--target_level") == 0) {
i++;
int level;
ASSERT_EQ(1, sscanf(argv[i], "%d", &level));
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_target_level_dbfs(level));
} else if (strcmp(argv[i], "--compression_gain") == 0) {
i++;
int gain;
ASSERT_EQ(1, sscanf(argv[i], "%d", &gain));
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_compression_gain_db(gain));
} else if (strcmp(argv[i], "--limiter") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->enable_limiter(true));
} else if (strcmp(argv[i], "--no_limiter") == 0) {
ASSERT_EQ(apm->kNoError, apm->gain_control()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->gain_control()->enable_limiter(false));
} else if (strcmp(argv[i], "-hpf") == 0) {
ASSERT_EQ(apm->kNoError, apm->high_pass_filter()->Enable(true));
} else if (strcmp(argv[i], "-ns") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
} else if (strcmp(argv[i], "--ns_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kLow));
} else if (strcmp(argv[i], "--ns_moderate") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kModerate));
} else if (strcmp(argv[i], "--ns_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kHigh));
} else if (strcmp(argv[i], "--ns_very_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->noise_suppression()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->noise_suppression()->set_level(NoiseSuppression::kVeryHigh));
} else if (strcmp(argv[i], "--ns_prob_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --ns_prob_file";
ns_prob_filename = argv[i];
} else if (strcmp(argv[i], "-vad") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
} else if (strcmp(argv[i], "--vad_very_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kVeryLowLikelihood));
} else if (strcmp(argv[i], "--vad_low") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kLowLikelihood));
} else if (strcmp(argv[i], "--vad_moderate") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kModerateLikelihood));
} else if (strcmp(argv[i], "--vad_high") == 0) {
ASSERT_EQ(apm->kNoError, apm->voice_detection()->Enable(true));
ASSERT_EQ(apm->kNoError,
apm->voice_detection()->set_likelihood(
VoiceDetection::kHighLikelihood));
} else if (strcmp(argv[i], "--vad_out_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --vad_out_file";
vad_out_filename = argv[i];
} else if (strcmp(argv[i], "--noasm") == 0) {
WebRtc_GetCPUInfo = WebRtc_GetCPUInfoNoASM;
// We need to reinitialize here if components have already been enabled.
ASSERT_EQ(apm->kNoError, apm->Initialize());
} else if (strcmp(argv[i], "--delay") == 0) {
i++;
ASSERT_EQ(1, sscanf(argv[i], "%d", &extra_delay_ms));
} else if (strcmp(argv[i], "--perf") == 0) {
perf_testing = true;
} else if (strcmp(argv[i], "--quiet") == 0) {
verbose = false;
progress = false;
} else if (strcmp(argv[i], "--no_progress") == 0) {
progress = false;
} else if (strcmp(argv[i], "--debug_file") == 0) {
i++;
ASSERT_LT(i, argc) << "Specify filename after --debug_file";
ASSERT_EQ(apm->kNoError, apm->StartDebugRecording(argv[i]));
} else {
FAIL() << "Unrecognized argument " << argv[i];
}
}
// If we're reading a protobuf file, ensure a simulation hasn't also
// been requested (which makes no sense...)
ASSERT_FALSE(pb_filename && simulating);
if (verbose) {
printf("Sample rate: %d Hz\n", sample_rate_hz);
printf("Primary channels: %d (in), %d (out)\n",
num_capture_input_channels,
num_capture_output_channels);
printf("Reverse channels: %d \n", num_render_channels);
}
const std::string out_path = webrtc::test::OutputPath();
const char far_file_default[] = "apm_far.pcm";
const char near_file_default[] = "apm_near.pcm";
const std::string out_file_default = out_path + "out.pcm";
const char event_filename[] = "apm_event.dat";
const char delay_filename[] = "apm_delay.dat";
const char drift_filename[] = "apm_drift.dat";
const std::string vad_file_default = out_path + "vad_out.dat";
const std::string ns_prob_file_default = out_path + "ns_prob.dat";
if (!simulating) {
far_filename = far_file_default;
near_filename = near_file_default;
}
if (!out_filename) {
out_filename = out_file_default.c_str();
}
if (!vad_out_filename) {
vad_out_filename = vad_file_default.c_str();
}
if (!ns_prob_filename) {
ns_prob_filename = ns_prob_file_default.c_str();
}
FILE* pb_file = NULL;
FILE* far_file = NULL;
FILE* near_file = NULL;
FILE* out_file = NULL;
FILE* event_file = NULL;
FILE* delay_file = NULL;
FILE* drift_file = NULL;
FILE* vad_out_file = NULL;
FILE* ns_prob_file = NULL;
FILE* aecm_echo_path_in_file = NULL;
FILE* aecm_echo_path_out_file = NULL;
if (pb_filename) {
pb_file = fopen(pb_filename, "rb");
ASSERT_TRUE(NULL != pb_file) << "Unable to open protobuf file "
<< pb_filename;
} else {
if (far_filename) {
far_file = fopen(far_filename, "rb");
ASSERT_TRUE(NULL != far_file) << "Unable to open far-end audio file "
<< far_filename;
}
near_file = fopen(near_filename, "rb");
ASSERT_TRUE(NULL != near_file) << "Unable to open near-end audio file "
<< near_filename;
if (!simulating) {
event_file = fopen(event_filename, "rb");
ASSERT_TRUE(NULL != event_file) << "Unable to open event file "
<< event_filename;
delay_file = fopen(delay_filename, "rb");
ASSERT_TRUE(NULL != delay_file) << "Unable to open buffer file "
<< delay_filename;
drift_file = fopen(drift_filename, "rb");
ASSERT_TRUE(NULL != drift_file) << "Unable to open drift file "
<< drift_filename;
}
}
out_file = fopen(out_filename, "wb");
ASSERT_TRUE(NULL != out_file) << "Unable to open output audio file "
<< out_filename;
int near_size_bytes = 0;
if (pb_file) {
struct stat st;
stat(pb_filename, &st);
// Crude estimate, but should be good enough.
near_size_bytes = st.st_size / 3;
} else {
struct stat st;
stat(near_filename, &st);
near_size_bytes = st.st_size;
}
if (apm->voice_detection()->is_enabled()) {
vad_out_file = fopen(vad_out_filename, "wb");
ASSERT_TRUE(NULL != vad_out_file) << "Unable to open VAD output file "
<< vad_out_file;
}
if (apm->noise_suppression()->is_enabled()) {
ns_prob_file = fopen(ns_prob_filename, "wb");
ASSERT_TRUE(NULL != ns_prob_file) << "Unable to open NS output file "
<< ns_prob_file;
}
if (aecm_echo_path_in_filename != NULL) {
aecm_echo_path_in_file = fopen(aecm_echo_path_in_filename, "rb");
ASSERT_TRUE(NULL != aecm_echo_path_in_file) << "Unable to open file "
<< aecm_echo_path_in_filename;
const size_t path_size =
apm->echo_control_mobile()->echo_path_size_bytes();
scoped_array<char> echo_path(new char[path_size]);
ASSERT_EQ(path_size, fread(echo_path.get(),
sizeof(char),
path_size,
aecm_echo_path_in_file));
EXPECT_EQ(apm->kNoError,
apm->echo_control_mobile()->SetEchoPath(echo_path.get(),
path_size));
fclose(aecm_echo_path_in_file);
aecm_echo_path_in_file = NULL;
}
if (aecm_echo_path_out_filename != NULL) {
aecm_echo_path_out_file = fopen(aecm_echo_path_out_filename, "wb");
ASSERT_TRUE(NULL != aecm_echo_path_out_file) << "Unable to open file "
<< aecm_echo_path_out_filename;
}
size_t read_count = 0;
int reverse_count = 0;
int primary_count = 0;
int near_read_bytes = 0;
TickInterval acc_ticks;
AudioFrame far_frame;
AudioFrame near_frame;
int delay_ms = 0;
int drift_samples = 0;
int capture_level = 127;
int8_t stream_has_voice = 0;
float ns_speech_prob = 0.0f;
TickTime t0 = TickTime::Now();
TickTime t1 = t0;
int64_t max_time_us = 0;
int64_t max_time_reverse_us = 0;
int64_t min_time_us = 1e6;
int64_t min_time_reverse_us = 1e6;
// TODO(ajm): Ideally we would refactor this block into separate functions,
// but for now we want to share the variables.
if (pb_file) {
Event event_msg;
while (ReadMessageFromFile(pb_file, &event_msg)) {
std::ostringstream trace_stream;
trace_stream << "Processed frames: " << reverse_count << " (reverse), "
<< primary_count << " (primary)";
SCOPED_TRACE(trace_stream.str());
if (event_msg.type() == Event::INIT) {
ASSERT_TRUE(event_msg.has_init());
const Init msg = event_msg.init();
ASSERT_TRUE(msg.has_sample_rate());
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(msg.sample_rate()));
ASSERT_TRUE(msg.has_device_sample_rate());
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->set_device_sample_rate_hz(
msg.device_sample_rate()));
ASSERT_TRUE(msg.has_num_input_channels());
ASSERT_TRUE(msg.has_num_output_channels());
ASSERT_EQ(apm->kNoError,
apm->set_num_channels(msg.num_input_channels(),
msg.num_output_channels()));
ASSERT_TRUE(msg.has_num_reverse_channels());
ASSERT_EQ(apm->kNoError,
apm->set_num_reverse_channels(msg.num_reverse_channels()));
samples_per_channel = msg.sample_rate() / 100;
far_frame.sample_rate_hz_ = msg.sample_rate();
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = msg.num_reverse_channels();
near_frame.sample_rate_hz_ = msg.sample_rate();
near_frame.samples_per_channel_ = samples_per_channel;
near_frame.num_channels_ = msg.num_input_channels();
if (verbose) {
printf("Init at frame: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
printf(" Sample rate: %d Hz\n", msg.sample_rate());
printf(" Primary channels: %d (in), %d (out)\n",
msg.num_input_channels(),
msg.num_output_channels());
printf(" Reverse channels: %d \n", msg.num_reverse_channels());
}
} else if (event_msg.type() == Event::REVERSE_STREAM) {
ASSERT_TRUE(event_msg.has_reverse_stream());
const ReverseStream msg = event_msg.reverse_stream();
reverse_count++;
ASSERT_TRUE(msg.has_data());
ASSERT_EQ(sizeof(int16_t) * samples_per_channel *
far_frame.num_channels_, msg.data().size());
memcpy(far_frame.data_, msg.data().data(), msg.data().size());
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->AnalyzeReverseStream(&far_frame));
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_reverse_us) {
max_time_reverse_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_reverse_us) {
min_time_reverse_us = tick_diff.Microseconds();
}
}
} else if (event_msg.type() == Event::STREAM) {
ASSERT_TRUE(event_msg.has_stream());
const Stream msg = event_msg.stream();
primary_count++;
// ProcessStream could have changed this for the output frame.
near_frame.num_channels_ = apm->num_input_channels();
ASSERT_TRUE(msg.has_input_data());
ASSERT_EQ(sizeof(int16_t) * samples_per_channel *
near_frame.num_channels_, msg.input_data().size());
memcpy(near_frame.data_,
msg.input_data().data(),
msg.input_data().size());
near_read_bytes += msg.input_data().size();
if (progress && primary_count % 100 == 0) {
printf("%.0f%% complete\r",
(near_read_bytes * 100.0) / near_size_bytes);
fflush(stdout);
}
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_stream_analog_level(msg.level()));
ASSERT_EQ(apm->kNoError,
apm->set_stream_delay_ms(msg.delay() + extra_delay_ms));
apm->echo_cancellation()->set_stream_drift_samples(msg.drift());
int err = apm->ProcessStream(&near_frame);
if (err == apm->kBadStreamParameterWarning) {
printf("Bad parameter warning. %s\n", trace_stream.str().c_str());
}
ASSERT_TRUE(err == apm->kNoError ||
err == apm->kBadStreamParameterWarning);
ASSERT_TRUE(near_frame.num_channels_ == apm->num_output_channels());
stream_has_voice =
static_cast<int8_t>(apm->voice_detection()->stream_has_voice());
if (vad_out_file != NULL) {
ASSERT_EQ(1u, fwrite(&stream_has_voice,
sizeof(stream_has_voice),
1,
vad_out_file));
}
if (ns_prob_file != NULL) {
ns_speech_prob = apm->noise_suppression()->speech_probability();
ASSERT_EQ(1u, fwrite(&ns_speech_prob,
sizeof(ns_speech_prob),
1,
ns_prob_file));
}
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_us) {
max_time_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_us) {
min_time_us = tick_diff.Microseconds();
}
}
size_t size = samples_per_channel * near_frame.num_channels_;
ASSERT_EQ(size, fwrite(near_frame.data_,
sizeof(int16_t),
size,
out_file));
}
}
ASSERT_TRUE(feof(pb_file));
} else {
enum Events {
kInitializeEvent,
kRenderEvent,
kCaptureEvent,
kResetEventDeprecated
};
int16_t event = 0;
while (simulating || feof(event_file) == 0) {
std::ostringstream trace_stream;
trace_stream << "Processed frames: " << reverse_count << " (reverse), "
<< primary_count << " (primary)";
SCOPED_TRACE(trace_stream.str());
if (simulating) {
if (far_file == NULL) {
event = kCaptureEvent;
} else {
if (event == kRenderEvent) {
event = kCaptureEvent;
} else {
event = kRenderEvent;
}
}
} else {
read_count = fread(&event, sizeof(event), 1, event_file);
if (read_count != 1) {
break;
}
}
far_frame.sample_rate_hz_ = sample_rate_hz;
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = num_render_channels;
near_frame.sample_rate_hz_ = sample_rate_hz;
near_frame.samples_per_channel_ = samples_per_channel;
if (event == kInitializeEvent || event == kResetEventDeprecated) {
ASSERT_EQ(1u,
fread(&sample_rate_hz, sizeof(sample_rate_hz), 1, event_file));
samples_per_channel = sample_rate_hz / 100;
ASSERT_EQ(1u,
fread(&device_sample_rate_hz,
sizeof(device_sample_rate_hz),
1,
event_file));
ASSERT_EQ(apm->kNoError,
apm->set_sample_rate_hz(sample_rate_hz));
ASSERT_EQ(apm->kNoError,
apm->echo_cancellation()->set_device_sample_rate_hz(
device_sample_rate_hz));
far_frame.sample_rate_hz_ = sample_rate_hz;
far_frame.samples_per_channel_ = samples_per_channel;
far_frame.num_channels_ = num_render_channels;
near_frame.sample_rate_hz_ = sample_rate_hz;
near_frame.samples_per_channel_ = samples_per_channel;
if (verbose) {
printf("Init at frame: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
printf(" Sample rate: %d Hz\n", sample_rate_hz);
}
} else if (event == kRenderEvent) {
reverse_count++;
size_t size = samples_per_channel * num_render_channels;
read_count = fread(far_frame.data_,
sizeof(int16_t),
size,
far_file);
if (simulating) {
if (read_count != size) {
// Read an equal amount from the near file to avoid errors due to
// not reaching end-of-file.
EXPECT_EQ(0, fseek(near_file, read_count * sizeof(int16_t),
SEEK_CUR));
break; // This is expected.
}
} else {
ASSERT_EQ(size, read_count);
}
if (perf_testing) {
t0 = TickTime::Now();
}
ASSERT_EQ(apm->kNoError,
apm->AnalyzeReverseStream(&far_frame));
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_reverse_us) {
max_time_reverse_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_reverse_us) {
min_time_reverse_us = tick_diff.Microseconds();
}
}
} else if (event == kCaptureEvent) {
primary_count++;
near_frame.num_channels_ = num_capture_input_channels;
size_t size = samples_per_channel * num_capture_input_channels;
read_count = fread(near_frame.data_,
sizeof(int16_t),
size,
near_file);
near_read_bytes += read_count * sizeof(int16_t);
if (progress && primary_count % 100 == 0) {
printf("%.0f%% complete\r",
(near_read_bytes * 100.0) / near_size_bytes);
fflush(stdout);
}
if (simulating) {
if (read_count != size) {
break; // This is expected.
}
delay_ms = 0;
drift_samples = 0;
} else {
ASSERT_EQ(size, read_count);
// TODO(ajm): sizeof(delay_ms) for current files?
ASSERT_EQ(1u,
fread(&delay_ms, 2, 1, delay_file));
ASSERT_EQ(1u,
fread(&drift_samples, sizeof(drift_samples), 1, drift_file));
}
if (apm->gain_control()->is_enabled() &&
apm->gain_control()->mode() == GainControl::kAdaptiveAnalog) {
SimulateMic(capture_level, &near_frame);
}
if (perf_testing) {
t0 = TickTime::Now();
}
const int capture_level_in = capture_level;
ASSERT_EQ(apm->kNoError,
apm->gain_control()->set_stream_analog_level(capture_level));
ASSERT_EQ(apm->kNoError,
apm->set_stream_delay_ms(delay_ms + extra_delay_ms));
apm->echo_cancellation()->set_stream_drift_samples(drift_samples);
int err = apm->ProcessStream(&near_frame);
if (err == apm->kBadStreamParameterWarning) {
printf("Bad parameter warning. %s\n", trace_stream.str().c_str());
}
ASSERT_TRUE(err == apm->kNoError ||
err == apm->kBadStreamParameterWarning);
ASSERT_TRUE(near_frame.num_channels_ == apm->num_output_channels());
capture_level = apm->gain_control()->stream_analog_level();
stream_has_voice =
static_cast<int8_t>(apm->voice_detection()->stream_has_voice());
if (vad_out_file != NULL) {
ASSERT_EQ(1u, fwrite(&stream_has_voice,
sizeof(stream_has_voice),
1,
vad_out_file));
}
if (ns_prob_file != NULL) {
ns_speech_prob = apm->noise_suppression()->speech_probability();
ASSERT_EQ(1u, fwrite(&ns_speech_prob,
sizeof(ns_speech_prob),
1,
ns_prob_file));
}
if (apm->gain_control()->mode() != GainControl::kAdaptiveAnalog) {
ASSERT_EQ(capture_level_in, capture_level);
}
if (perf_testing) {
t1 = TickTime::Now();
TickInterval tick_diff = t1 - t0;
acc_ticks += tick_diff;
if (tick_diff.Microseconds() > max_time_us) {
max_time_us = tick_diff.Microseconds();
}
if (tick_diff.Microseconds() < min_time_us) {
min_time_us = tick_diff.Microseconds();
}
}
size = samples_per_channel * near_frame.num_channels_;
ASSERT_EQ(size, fwrite(near_frame.data_,
sizeof(int16_t),
size,
out_file));
}
else {
FAIL() << "Event " << event << " is unrecognized";
}
}
}
printf("100%% complete\r");
if (aecm_echo_path_out_file != NULL) {
const size_t path_size =
apm->echo_control_mobile()->echo_path_size_bytes();
scoped_array<char> echo_path(new char[path_size]);
apm->echo_control_mobile()->GetEchoPath(echo_path.get(), path_size);
ASSERT_EQ(path_size, fwrite(echo_path.get(),
sizeof(char),
path_size,
aecm_echo_path_out_file));
fclose(aecm_echo_path_out_file);
aecm_echo_path_out_file = NULL;
}
if (verbose) {
printf("\nProcessed frames: %d (primary), %d (reverse)\n",
primary_count, reverse_count);
if (apm->level_estimator()->is_enabled()) {
printf("\n--Level metrics--\n");
printf("RMS: %d dBFS\n", -apm->level_estimator()->RMS());
}
if (apm->echo_cancellation()->are_metrics_enabled()) {
EchoCancellation::Metrics metrics;
apm->echo_cancellation()->GetMetrics(&metrics);
printf("\n--Echo metrics--\n");
printf("(avg, max, min)\n");
printf("ERL: ");
PrintStat(metrics.echo_return_loss);
printf("ERLE: ");
PrintStat(metrics.echo_return_loss_enhancement);
printf("ANLP: ");
PrintStat(metrics.a_nlp);
}
if (apm->echo_cancellation()->is_delay_logging_enabled()) {
int median = 0;
int std = 0;
apm->echo_cancellation()->GetDelayMetrics(&median, &std);
printf("\n--Delay metrics--\n");
printf("Median: %3d\n", median);
printf("Standard deviation: %3d\n", std);
}
}
if (!pb_file) {
int8_t temp_int8;
if (far_file) {
read_count = fread(&temp_int8, sizeof(temp_int8), 1, far_file);
EXPECT_NE(0, feof(far_file)) << "Far-end file not fully processed";
}
read_count = fread(&temp_int8, sizeof(temp_int8), 1, near_file);
EXPECT_NE(0, feof(near_file)) << "Near-end file not fully processed";
if (!simulating) {
read_count = fread(&temp_int8, sizeof(temp_int8), 1, event_file);
EXPECT_NE(0, feof(event_file)) << "Event file not fully processed";
read_count = fread(&temp_int8, sizeof(temp_int8), 1, delay_file);
EXPECT_NE(0, feof(delay_file)) << "Delay file not fully processed";
read_count = fread(&temp_int8, sizeof(temp_int8), 1, drift_file);
EXPECT_NE(0, feof(drift_file)) << "Drift file not fully processed";
}
}
if (perf_testing) {
if (primary_count > 0) {
int64_t exec_time = acc_ticks.Milliseconds();
printf("\nTotal time: %.3f s, file time: %.2f s\n",
exec_time * 0.001, primary_count * 0.01);
printf("Time per frame: %.3f ms (average), %.3f ms (max),"
" %.3f ms (min)\n",
(exec_time * 1.0) / primary_count,
(max_time_us + max_time_reverse_us) / 1000.0,
(min_time_us + min_time_reverse_us) / 1000.0);
// Record the results with Perf test tools.
webrtc::test::PrintResult("audioproc", "", "time_per_10ms_frame",
(exec_time * 1000) / primary_count, "us", false);
} else {
printf("Warning: no capture frames\n");
}
}
AudioProcessing::Destroy(apm);
apm = NULL;
}
} // namespace
int main(int argc, char* argv[])
{
void_main(argc, argv);
// Optional, but removes memory leak noise from Valgrind.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
|
// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/Billboard>
#include <osg/BoundingBox>
#include <osg/Camera>
#include <osg/ClearNode>
#include <osg/ClipNode>
#include <osg/Drawable>
#include <osg/Geode>
#include <osg/Group>
#include <osg/LOD>
#include <osg/LightSource>
#include <osg/Matrix>
#include <osg/Matrixd>
#include <osg/Matrixf>
#include <osg/Node>
#include <osg/OccluderNode>
#include <osg/OcclusionQueryNode>
#include <osg/Polytope>
#include <osg/Projection>
#include <osg/RenderInfo>
#include <osg/State>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Switch>
#include <osg/TexGenNode>
#include <osg/Transform>
#include <osg/Vec3>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderBin>
#include <osgUtil/RenderStage>
#include <osgUtil/StateGraph>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
TYPE_NAME_ALIAS(osg::Matrix::value_type, osgUtil::CullVisitor::value_type)
BEGIN_OBJECT_REFLECTOR(osgUtil::CullVisitor)
I_DeclaringFile("osgUtil/CullVisitor");
I_BaseType(osg::NodeVisitor);
I_BaseType(osg::CullStack);
I_Constructor0(____CullVisitor,
"",
"");
I_Constructor1(IN, const osgUtil::CullVisitor &, x,
Properties::NON_EXPLICIT,
____CullVisitor__C5_CullVisitor_R1,
"Copy constructor that does a shallow copy. ",
"");
I_Method0(osgUtil::CullVisitor *, clone,
Properties::VIRTUAL,
__CullVisitor_P1__clone,
"Create a shallow copy of the CullVisitor, used by CullVisitor::create() to clone the prototype. ",
"");
I_Method0(void, reset,
Properties::VIRTUAL,
__void__reset,
"",
"");
I_Method0(osg::Vec3, getEyePoint,
Properties::VIRTUAL,
__osg_Vec3__getEyePoint,
"Get the eye point in local coordinates. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. ");
I_Method0(osg::Vec3, getViewPoint,
Properties::VIRTUAL,
__osg_Vec3__getViewPoint,
"Get the view point in local coordinates. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. ");
I_Method2(float, getDistanceToEyePoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceToEyePoint__C5_osg_Vec3_R1__bool,
"Get the distance from a point to the eye point, distance value in local coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceFromEyePoint(pos) is not implemented then a default value of 0.0 is returned. ");
I_Method2(float, getDistanceFromEyePoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceFromEyePoint__C5_osg_Vec3_R1__bool,
"Get the distance of a point from the eye point, distance value in the eye coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceFromEyePoint(pos) is not implemented than a default value of 0.0 is returned. ");
I_Method2(float, getDistanceToViewPoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceToViewPoint__C5_osg_Vec3_R1__bool,
"Get the distance from a point to the view point, distance value in local coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceToViewPoint(pos) is not implemented then a default value of 0.0 is returned. ");
I_Method1(void, apply, IN, osg::Node &, x,
Properties::VIRTUAL,
__void__apply__osg_Node_R1,
"",
"");
I_Method1(void, apply, IN, osg::Geode &, node,
Properties::VIRTUAL,
__void__apply__osg_Geode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Billboard &, node,
Properties::VIRTUAL,
__void__apply__osg_Billboard_R1,
"",
"");
I_Method1(void, apply, IN, osg::LightSource &, node,
Properties::VIRTUAL,
__void__apply__osg_LightSource_R1,
"",
"");
I_Method1(void, apply, IN, osg::ClipNode &, node,
Properties::VIRTUAL,
__void__apply__osg_ClipNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::TexGenNode &, node,
Properties::VIRTUAL,
__void__apply__osg_TexGenNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Group &, node,
Properties::VIRTUAL,
__void__apply__osg_Group_R1,
"",
"");
I_Method1(void, apply, IN, osg::Transform &, node,
Properties::VIRTUAL,
__void__apply__osg_Transform_R1,
"",
"");
I_Method1(void, apply, IN, osg::Projection &, node,
Properties::VIRTUAL,
__void__apply__osg_Projection_R1,
"",
"");
I_Method1(void, apply, IN, osg::Switch &, node,
Properties::VIRTUAL,
__void__apply__osg_Switch_R1,
"",
"");
I_Method1(void, apply, IN, osg::LOD &, node,
Properties::VIRTUAL,
__void__apply__osg_LOD_R1,
"",
"");
I_Method1(void, apply, IN, osg::ClearNode &, node,
Properties::VIRTUAL,
__void__apply__osg_ClearNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Camera &, node,
Properties::VIRTUAL,
__void__apply__osg_Camera_R1,
"",
"");
I_Method1(void, apply, IN, osg::OccluderNode &, node,
Properties::VIRTUAL,
__void__apply__osg_OccluderNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::OcclusionQueryNode &, node,
Properties::VIRTUAL,
__void__apply__osg_OcclusionQueryNode_R1,
"",
"");
I_Method1(void, pushStateSet, IN, const osg::StateSet *, ss,
Properties::NON_VIRTUAL,
__void__pushStateSet__C5_osg_StateSet_P1,
"Push state set on the current state group. ",
"If the state exists in a child state group of the current state group then move the current state group to that child. Otherwise, create a new state group for the state set, add it to the current state group then move the current state group pointer to the new state group. ");
I_Method0(void, popStateSet,
Properties::NON_VIRTUAL,
__void__popStateSet,
"Pop the top state set and hence associated state group. ",
"Move the current state group to the parent of the popped state group. ");
I_Method1(void, setStateGraph, IN, osgUtil::StateGraph *, rg,
Properties::NON_VIRTUAL,
__void__setStateGraph__StateGraph_P1,
"",
"");
I_Method0(osgUtil::StateGraph *, getRootStateGraph,
Properties::NON_VIRTUAL,
__StateGraph_P1__getRootStateGraph,
"",
"");
I_Method0(osgUtil::StateGraph *, getCurrentStateGraph,
Properties::NON_VIRTUAL,
__StateGraph_P1__getCurrentStateGraph,
"",
"");
I_Method1(void, setRenderStage, IN, osgUtil::RenderStage *, rg,
Properties::NON_VIRTUAL,
__void__setRenderStage__RenderStage_P1,
"",
"");
I_Method0(osgUtil::RenderStage *, getRenderStage,
Properties::NON_VIRTUAL,
__RenderStage_P1__getRenderStage,
"",
"");
I_Method0(osgUtil::RenderBin *, getCurrentRenderBin,
Properties::NON_VIRTUAL,
__RenderBin_P1__getCurrentRenderBin,
"",
"");
I_Method1(void, setCurrentRenderBin, IN, osgUtil::RenderBin *, rb,
Properties::NON_VIRTUAL,
__void__setCurrentRenderBin__RenderBin_P1,
"",
"");
I_Method0(osgUtil::CullVisitor::value_type, getCalculatedNearPlane,
Properties::NON_VIRTUAL,
__value_type__getCalculatedNearPlane,
"",
"");
I_Method0(osgUtil::CullVisitor::value_type, getCalculatedFarPlane,
Properties::NON_VIRTUAL,
__value_type__getCalculatedFarPlane,
"",
"");
I_Method3(osgUtil::CullVisitor::value_type, computeNearestPointInFrustum, IN, const osg::Matrix &, matrix, IN, const osg::Polytope::PlaneList &, planes, IN, const osg::Drawable &, drawable,
Properties::NON_VIRTUAL,
__value_type__computeNearestPointInFrustum__C5_osg_Matrix_R1__C5_osg_Polytope_PlaneList_R1__C5_osg_Drawable_R1,
"",
"");
I_Method2(bool, updateCalculatedNearFar, IN, const osg::Matrix &, matrix, IN, const osg::BoundingBox &, bb,
Properties::NON_VIRTUAL,
__bool__updateCalculatedNearFar__C5_osg_Matrix_R1__C5_osg_BoundingBox_R1,
"",
"");
I_MethodWithDefaults3(bool, updateCalculatedNearFar, IN, const osg::Matrix &, matrix, , IN, const osg::Drawable &, drawable, , IN, bool, isBillboard, false,
Properties::NON_VIRTUAL,
__bool__updateCalculatedNearFar__C5_osg_Matrix_R1__C5_osg_Drawable_R1__bool,
"",
"");
I_Method1(void, updateCalculatedNearFar, IN, const osg::Vec3 &, pos,
Properties::NON_VIRTUAL,
__void__updateCalculatedNearFar__C5_osg_Vec3_R1,
"",
"");
I_Method2(void, addDrawable, IN, osg::Drawable *, drawable, IN, osg::RefMatrix *, matrix,
Properties::NON_VIRTUAL,
__void__addDrawable__osg_Drawable_P1__osg_RefMatrix_P1,
"Add a drawable to current render graph. ",
"");
I_Method3(void, addDrawableAndDepth, IN, osg::Drawable *, drawable, IN, osg::RefMatrix *, matrix, IN, float, depth,
Properties::NON_VIRTUAL,
__void__addDrawableAndDepth__osg_Drawable_P1__osg_RefMatrix_P1__float,
"Add a drawable and depth to current render graph. ",
"");
I_Method2(void, addPositionedAttribute, IN, osg::RefMatrix *, matrix, IN, const osg::StateAttribute *, attr,
Properties::NON_VIRTUAL,
__void__addPositionedAttribute__osg_RefMatrix_P1__C5_osg_StateAttribute_P1,
"Add an attribute which is positioned relative to the modelview matrix. ",
"");
I_Method3(void, addPositionedTextureAttribute, IN, unsigned int, textureUnit, IN, osg::RefMatrix *, matrix, IN, const osg::StateAttribute *, attr,
Properties::NON_VIRTUAL,
__void__addPositionedTextureAttribute__unsigned_int__osg_RefMatrix_P1__C5_osg_StateAttribute_P1,
"Add an attribute which is positioned relative to the modelview matrix. ",
"");
I_Method0(void, computeNearPlane,
Properties::NON_VIRTUAL,
__void__computeNearPlane,
"compute near plane based on the polgon intersection of primtives in near plane candidate list of drawables. ",
"Note, you have to set ComputeNearFarMode to COMPUTE_NEAR_FAR_USING_PRIMITIVES to be able to near plane candidate drawables to be recorded by the cull traversal. ");
I_Method0(void, popProjectionMatrix,
Properties::VIRTUAL,
__void__popProjectionMatrix,
"Re-implement CullStack's popProjectionMatrix() adding clamping of the projection matrix to the computed near and far. ",
"");
I_Method3(bool, clampProjectionMatrixImplementation, IN, osg::Matrixf &, projection, IN, double &, znear, IN, double &, zfar,
Properties::VIRTUAL,
__bool__clampProjectionMatrixImplementation__osg_Matrixf_R1__double_R1__double_R1,
"CullVisitor's default clamping of the projection float matrix to computed near and far values. ",
"Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback. ");
I_Method3(bool, clampProjectionMatrixImplementation, IN, osg::Matrixd &, projection, IN, double &, znear, IN, double &, zfar,
Properties::VIRTUAL,
__bool__clampProjectionMatrixImplementation__osg_Matrixd_R1__double_R1__double_R1,
"CullVisitor's default clamping of the projection double matrix to computed near and far values. ",
"Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback. ");
I_Method3(bool, clampProjectionMatrix, IN, osg::Matrixf &, projection, IN, osgUtil::CullVisitor::value_type &, znear, IN, osgUtil::CullVisitor::value_type &, zfar,
Properties::NON_VIRTUAL,
__bool__clampProjectionMatrix__osg_Matrixf_R1__value_type_R1__value_type_R1,
"Clamp the projection float matrix to computed near and far values, use callback if it exists, otherwise use default CullVisitor implementation. ",
"");
I_Method3(bool, clampProjectionMatrix, IN, osg::Matrixd &, projection, IN, osgUtil::CullVisitor::value_type &, znear, IN, osgUtil::CullVisitor::value_type &, zfar,
Properties::NON_VIRTUAL,
__bool__clampProjectionMatrix__osg_Matrixd_R1__value_type_R1__value_type_R1,
"Clamp the projection double matrix to computed near and far values, use callback if it exists, otherwise use default CullVisitor implementation. ",
"");
I_Method1(void, setState, IN, osg::State *, state,
Properties::NON_VIRTUAL,
__void__setState__osg_State_P1,
"",
"");
I_Method0(osg::State *, getState,
Properties::NON_VIRTUAL,
__osg_State_P1__getState,
"",
"");
I_Method0(const osg::State *, getState,
Properties::NON_VIRTUAL,
__C5_osg_State_P1__getState,
"",
"");
I_Method1(void, setRenderInfo, IN, osg::RenderInfo &, renderInfo,
Properties::NON_VIRTUAL,
__void__setRenderInfo__osg_RenderInfo_R1,
"",
"");
I_Method0(osg::RenderInfo &, getRenderInfo,
Properties::NON_VIRTUAL,
__osg_RenderInfo_R1__getRenderInfo,
"",
"");
I_Method0(const osg::RenderInfo &, getRenderInfo,
Properties::NON_VIRTUAL,
__C5_osg_RenderInfo_R1__getRenderInfo,
"",
"");
I_StaticMethod0(osg::ref_ptr< osgUtil::CullVisitor > &, prototype,
__osg_ref_ptrT1_CullVisitor__R1__prototype_S,
"get the prototype singleton used by CullVisitor::create(). ",
"");
I_StaticMethod0(osgUtil::CullVisitor *, create,
__CullVisitor_P1__create_S,
"create a CullVisitor by cloning CullVisitor::prototype(). ",
"");
I_ProtectedMethod1(void, handle_cull_callbacks_and_traverse, IN, osg::Node &, node,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__void__handle_cull_callbacks_and_traverse__osg_Node_R1,
"",
"");
I_ProtectedMethod2(void, handle_cull_callbacks_and_accept, IN, osg::Node &, node, IN, osg::Node *, acceptNode,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__void__handle_cull_callbacks_and_accept__osg_Node_R1__osg_Node_P1,
"",
"");
I_ProtectedMethodWithDefaults4(osgUtil::RenderLeaf *, createOrReuseRenderLeaf, IN, osg::Drawable *, drawable, , IN, osg::RefMatrix *, projection, , IN, osg::RefMatrix *, matrix, , IN, float, depth, 0.0f,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__RenderLeaf_P1__createOrReuseRenderLeaf__osg_Drawable_P1__osg_RefMatrix_P1__osg_RefMatrix_P1__float,
"",
"");
I_SimpleProperty(osgUtil::CullVisitor::value_type, CalculatedFarPlane,
__value_type__getCalculatedFarPlane,
0);
I_SimpleProperty(osgUtil::CullVisitor::value_type, CalculatedNearPlane,
__value_type__getCalculatedNearPlane,
0);
I_SimpleProperty(osgUtil::RenderBin *, CurrentRenderBin,
__RenderBin_P1__getCurrentRenderBin,
__void__setCurrentRenderBin__RenderBin_P1);
I_SimpleProperty(osgUtil::StateGraph *, CurrentStateGraph,
__StateGraph_P1__getCurrentStateGraph,
0);
I_SimpleProperty(osg::Vec3, EyePoint,
__osg_Vec3__getEyePoint,
0);
I_SimpleProperty(osg::RenderInfo &, RenderInfo,
__osg_RenderInfo_R1__getRenderInfo,
__void__setRenderInfo__osg_RenderInfo_R1);
I_SimpleProperty(osgUtil::RenderStage *, RenderStage,
__RenderStage_P1__getRenderStage,
__void__setRenderStage__RenderStage_P1);
I_SimpleProperty(osgUtil::StateGraph *, RootStateGraph,
__StateGraph_P1__getRootStateGraph,
0);
I_SimpleProperty(osg::State *, State,
__osg_State_P1__getState,
__void__setState__osg_State_P1);
I_SimpleProperty(osgUtil::StateGraph *, StateGraph,
0,
__void__setStateGraph__StateGraph_P1);
I_SimpleProperty(osg::Vec3, ViewPoint,
__osg_Vec3__getViewPoint,
0);
END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osgUtil::CullVisitor >)
I_DeclaringFile("osg/ref_ptr");
I_Constructor0(____ref_ptr,
"",
"");
I_Constructor1(IN, osgUtil::CullVisitor *, ptr,
Properties::NON_EXPLICIT,
____ref_ptr__T_P1,
"",
"");
I_Constructor1(IN, const osg::ref_ptr< osgUtil::CullVisitor > &, rp,
Properties::NON_EXPLICIT,
____ref_ptr__C5_ref_ptr_R1,
"",
"");
I_Method0(osgUtil::CullVisitor *, get,
Properties::NON_VIRTUAL,
__T_P1__get,
"",
"");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"",
"");
I_Method0(osgUtil::CullVisitor *, release,
Properties::NON_VIRTUAL,
__T_P1__release,
"",
"");
I_Method1(void, swap, IN, osg::ref_ptr< osgUtil::CullVisitor > &, rp,
Properties::NON_VIRTUAL,
__void__swap__ref_ptr_R1,
"",
"");
I_SimpleProperty(osgUtil::CullVisitor *, ,
__T_P1__get,
0);
END_REFLECTOR
Updated wrappers
git-svn-id: 23b6355f2bb369032457de4eb5f713ee134f73a8@8676 16af8721-9629-0410-8352-f15c8da7e697
// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/Billboard>
#include <osg/BoundingBox>
#include <osg/Camera>
#include <osg/ClearNode>
#include <osg/ClipNode>
#include <osg/Drawable>
#include <osg/Geode>
#include <osg/Group>
#include <osg/LOD>
#include <osg/LightSource>
#include <osg/Matrix>
#include <osg/Matrixd>
#include <osg/Matrixf>
#include <osg/Node>
#include <osg/OccluderNode>
#include <osg/OcclusionQueryNode>
#include <osg/Polytope>
#include <osg/Projection>
#include <osg/RenderInfo>
#include <osg/State>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Switch>
#include <osg/TexGenNode>
#include <osg/Transform>
#include <osg/Vec3>
#include <osgUtil/CullVisitor>
#include <osgUtil/RenderBin>
#include <osgUtil/RenderStage>
#include <osgUtil/StateGraph>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
TYPE_NAME_ALIAS(osg::Matrix::value_type, osgUtil::CullVisitor::value_type)
BEGIN_OBJECT_REFLECTOR(osgUtil::CullVisitor)
I_DeclaringFile("osgUtil/CullVisitor");
I_BaseType(osg::NodeVisitor);
I_BaseType(osg::CullStack);
I_Constructor0(____CullVisitor,
"",
"");
I_Constructor1(IN, const osgUtil::CullVisitor &, x,
Properties::NON_EXPLICIT,
____CullVisitor__C5_CullVisitor_R1,
"Copy constructor that does a shallow copy. ",
"");
I_Method0(osgUtil::CullVisitor *, clone,
Properties::VIRTUAL,
__CullVisitor_P1__clone,
"Create a shallow copy of the CullVisitor, used by CullVisitor::create() to clone the prototype. ",
"");
I_Method0(void, reset,
Properties::VIRTUAL,
__void__reset,
"",
"");
I_Method0(osg::Vec3, getEyePoint,
Properties::VIRTUAL,
__osg_Vec3__getEyePoint,
"Get the eye point in local coordinates. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. ");
I_Method0(osg::Vec3, getViewPoint,
Properties::VIRTUAL,
__osg_Vec3__getViewPoint,
"Get the view point in local coordinates. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. ");
I_Method2(float, getDistanceToEyePoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceToEyePoint__C5_osg_Vec3_R1__bool,
"Get the distance from a point to the eye point, distance value in local coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceFromEyePoint(pos) is not implemented then a default value of 0.0 is returned. ");
I_Method2(float, getDistanceFromEyePoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceFromEyePoint__C5_osg_Vec3_R1__bool,
"Get the distance of a point from the eye point, distance value in the eye coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceFromEyePoint(pos) is not implemented than a default value of 0.0 is returned. ");
I_Method2(float, getDistanceToViewPoint, IN, const osg::Vec3 &, pos, IN, bool, withLODScale,
Properties::VIRTUAL,
__float__getDistanceToViewPoint__C5_osg_Vec3_R1__bool,
"Get the distance from a point to the view point, distance value in local coordinate system. ",
"Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. If the getDistanceToViewPoint(pos) is not implemented then a default value of 0.0 is returned. ");
I_Method1(void, apply, IN, osg::Node &, x,
Properties::VIRTUAL,
__void__apply__osg_Node_R1,
"",
"");
I_Method1(void, apply, IN, osg::Geode &, node,
Properties::VIRTUAL,
__void__apply__osg_Geode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Billboard &, node,
Properties::VIRTUAL,
__void__apply__osg_Billboard_R1,
"",
"");
I_Method1(void, apply, IN, osg::LightSource &, node,
Properties::VIRTUAL,
__void__apply__osg_LightSource_R1,
"",
"");
I_Method1(void, apply, IN, osg::ClipNode &, node,
Properties::VIRTUAL,
__void__apply__osg_ClipNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::TexGenNode &, node,
Properties::VIRTUAL,
__void__apply__osg_TexGenNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Group &, node,
Properties::VIRTUAL,
__void__apply__osg_Group_R1,
"",
"");
I_Method1(void, apply, IN, osg::Transform &, node,
Properties::VIRTUAL,
__void__apply__osg_Transform_R1,
"",
"");
I_Method1(void, apply, IN, osg::Projection &, node,
Properties::VIRTUAL,
__void__apply__osg_Projection_R1,
"",
"");
I_Method1(void, apply, IN, osg::Switch &, node,
Properties::VIRTUAL,
__void__apply__osg_Switch_R1,
"",
"");
I_Method1(void, apply, IN, osg::LOD &, node,
Properties::VIRTUAL,
__void__apply__osg_LOD_R1,
"",
"");
I_Method1(void, apply, IN, osg::ClearNode &, node,
Properties::VIRTUAL,
__void__apply__osg_ClearNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::Camera &, node,
Properties::VIRTUAL,
__void__apply__osg_Camera_R1,
"",
"");
I_Method1(void, apply, IN, osg::OccluderNode &, node,
Properties::VIRTUAL,
__void__apply__osg_OccluderNode_R1,
"",
"");
I_Method1(void, apply, IN, osg::OcclusionQueryNode &, node,
Properties::VIRTUAL,
__void__apply__osg_OcclusionQueryNode_R1,
"",
"");
I_Method1(void, pushStateSet, IN, const osg::StateSet *, ss,
Properties::NON_VIRTUAL,
__void__pushStateSet__C5_osg_StateSet_P1,
"Push state set on the current state group. ",
"If the state exists in a child state group of the current state group then move the current state group to that child. Otherwise, create a new state group for the state set, add it to the current state group then move the current state group pointer to the new state group. ");
I_Method0(void, popStateSet,
Properties::NON_VIRTUAL,
__void__popStateSet,
"Pop the top state set and hence associated state group. ",
"Move the current state group to the parent of the popped state group. ");
I_Method1(void, setStateGraph, IN, osgUtil::StateGraph *, rg,
Properties::NON_VIRTUAL,
__void__setStateGraph__StateGraph_P1,
"",
"");
I_Method0(osgUtil::StateGraph *, getRootStateGraph,
Properties::NON_VIRTUAL,
__StateGraph_P1__getRootStateGraph,
"",
"");
I_Method0(osgUtil::StateGraph *, getCurrentStateGraph,
Properties::NON_VIRTUAL,
__StateGraph_P1__getCurrentStateGraph,
"",
"");
I_Method1(void, setRenderStage, IN, osgUtil::RenderStage *, rg,
Properties::NON_VIRTUAL,
__void__setRenderStage__RenderStage_P1,
"",
"");
I_Method0(osgUtil::RenderStage *, getRenderStage,
Properties::NON_VIRTUAL,
__RenderStage_P1__getRenderStage,
"",
"");
I_Method0(osgUtil::RenderStage *, getCurrentRenderStage,
Properties::NON_VIRTUAL,
__RenderStage_P1__getCurrentRenderStage,
"",
"");
I_Method0(osg::Camera *, getCurrentCamera,
Properties::NON_VIRTUAL,
__osg_Camera_P1__getCurrentCamera,
"",
"");
I_Method0(osgUtil::RenderBin *, getCurrentRenderBin,
Properties::NON_VIRTUAL,
__RenderBin_P1__getCurrentRenderBin,
"",
"");
I_Method1(void, setCurrentRenderBin, IN, osgUtil::RenderBin *, rb,
Properties::NON_VIRTUAL,
__void__setCurrentRenderBin__RenderBin_P1,
"",
"");
I_Method0(osgUtil::CullVisitor::value_type, getCalculatedNearPlane,
Properties::NON_VIRTUAL,
__value_type__getCalculatedNearPlane,
"",
"");
I_Method0(osgUtil::CullVisitor::value_type, getCalculatedFarPlane,
Properties::NON_VIRTUAL,
__value_type__getCalculatedFarPlane,
"",
"");
I_Method3(osgUtil::CullVisitor::value_type, computeNearestPointInFrustum, IN, const osg::Matrix &, matrix, IN, const osg::Polytope::PlaneList &, planes, IN, const osg::Drawable &, drawable,
Properties::NON_VIRTUAL,
__value_type__computeNearestPointInFrustum__C5_osg_Matrix_R1__C5_osg_Polytope_PlaneList_R1__C5_osg_Drawable_R1,
"",
"");
I_Method2(bool, updateCalculatedNearFar, IN, const osg::Matrix &, matrix, IN, const osg::BoundingBox &, bb,
Properties::NON_VIRTUAL,
__bool__updateCalculatedNearFar__C5_osg_Matrix_R1__C5_osg_BoundingBox_R1,
"",
"");
I_MethodWithDefaults3(bool, updateCalculatedNearFar, IN, const osg::Matrix &, matrix, , IN, const osg::Drawable &, drawable, , IN, bool, isBillboard, false,
Properties::NON_VIRTUAL,
__bool__updateCalculatedNearFar__C5_osg_Matrix_R1__C5_osg_Drawable_R1__bool,
"",
"");
I_Method1(void, updateCalculatedNearFar, IN, const osg::Vec3 &, pos,
Properties::NON_VIRTUAL,
__void__updateCalculatedNearFar__C5_osg_Vec3_R1,
"",
"");
I_Method2(void, addDrawable, IN, osg::Drawable *, drawable, IN, osg::RefMatrix *, matrix,
Properties::NON_VIRTUAL,
__void__addDrawable__osg_Drawable_P1__osg_RefMatrix_P1,
"Add a drawable to current render graph. ",
"");
I_Method3(void, addDrawableAndDepth, IN, osg::Drawable *, drawable, IN, osg::RefMatrix *, matrix, IN, float, depth,
Properties::NON_VIRTUAL,
__void__addDrawableAndDepth__osg_Drawable_P1__osg_RefMatrix_P1__float,
"Add a drawable and depth to current render graph. ",
"");
I_Method2(void, addPositionedAttribute, IN, osg::RefMatrix *, matrix, IN, const osg::StateAttribute *, attr,
Properties::NON_VIRTUAL,
__void__addPositionedAttribute__osg_RefMatrix_P1__C5_osg_StateAttribute_P1,
"Add an attribute which is positioned relative to the modelview matrix. ",
"");
I_Method3(void, addPositionedTextureAttribute, IN, unsigned int, textureUnit, IN, osg::RefMatrix *, matrix, IN, const osg::StateAttribute *, attr,
Properties::NON_VIRTUAL,
__void__addPositionedTextureAttribute__unsigned_int__osg_RefMatrix_P1__C5_osg_StateAttribute_P1,
"Add an attribute which is positioned relative to the modelview matrix. ",
"");
I_Method0(void, computeNearPlane,
Properties::NON_VIRTUAL,
__void__computeNearPlane,
"compute near plane based on the polgon intersection of primtives in near plane candidate list of drawables. ",
"Note, you have to set ComputeNearFarMode to COMPUTE_NEAR_FAR_USING_PRIMITIVES to be able to near plane candidate drawables to be recorded by the cull traversal. ");
I_Method0(void, popProjectionMatrix,
Properties::VIRTUAL,
__void__popProjectionMatrix,
"Re-implement CullStack's popProjectionMatrix() adding clamping of the projection matrix to the computed near and far. ",
"");
I_Method3(bool, clampProjectionMatrixImplementation, IN, osg::Matrixf &, projection, IN, double &, znear, IN, double &, zfar,
Properties::VIRTUAL,
__bool__clampProjectionMatrixImplementation__osg_Matrixf_R1__double_R1__double_R1,
"CullVisitor's default clamping of the projection float matrix to computed near and far values. ",
"Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback. ");
I_Method3(bool, clampProjectionMatrixImplementation, IN, osg::Matrixd &, projection, IN, double &, znear, IN, double &, zfar,
Properties::VIRTUAL,
__bool__clampProjectionMatrixImplementation__osg_Matrixd_R1__double_R1__double_R1,
"CullVisitor's default clamping of the projection double matrix to computed near and far values. ",
"Note, do not call this method directly, use clampProjectionMatrix(..) instead, unless you want to bypass the callback. ");
I_Method3(bool, clampProjectionMatrix, IN, osg::Matrixf &, projection, IN, osgUtil::CullVisitor::value_type &, znear, IN, osgUtil::CullVisitor::value_type &, zfar,
Properties::NON_VIRTUAL,
__bool__clampProjectionMatrix__osg_Matrixf_R1__value_type_R1__value_type_R1,
"Clamp the projection float matrix to computed near and far values, use callback if it exists, otherwise use default CullVisitor implementation. ",
"");
I_Method3(bool, clampProjectionMatrix, IN, osg::Matrixd &, projection, IN, osgUtil::CullVisitor::value_type &, znear, IN, osgUtil::CullVisitor::value_type &, zfar,
Properties::NON_VIRTUAL,
__bool__clampProjectionMatrix__osg_Matrixd_R1__value_type_R1__value_type_R1,
"Clamp the projection double matrix to computed near and far values, use callback if it exists, otherwise use default CullVisitor implementation. ",
"");
I_Method1(void, setState, IN, osg::State *, state,
Properties::NON_VIRTUAL,
__void__setState__osg_State_P1,
"",
"");
I_Method0(osg::State *, getState,
Properties::NON_VIRTUAL,
__osg_State_P1__getState,
"",
"");
I_Method0(const osg::State *, getState,
Properties::NON_VIRTUAL,
__C5_osg_State_P1__getState,
"",
"");
I_Method1(void, setRenderInfo, IN, osg::RenderInfo &, renderInfo,
Properties::NON_VIRTUAL,
__void__setRenderInfo__osg_RenderInfo_R1,
"",
"");
I_Method0(osg::RenderInfo &, getRenderInfo,
Properties::NON_VIRTUAL,
__osg_RenderInfo_R1__getRenderInfo,
"",
"");
I_Method0(const osg::RenderInfo &, getRenderInfo,
Properties::NON_VIRTUAL,
__C5_osg_RenderInfo_R1__getRenderInfo,
"",
"");
I_StaticMethod0(osg::ref_ptr< osgUtil::CullVisitor > &, prototype,
__osg_ref_ptrT1_CullVisitor__R1__prototype_S,
"get the prototype singleton used by CullVisitor::create(). ",
"");
I_StaticMethod0(osgUtil::CullVisitor *, create,
__CullVisitor_P1__create_S,
"create a CullVisitor by cloning CullVisitor::prototype(). ",
"");
I_ProtectedMethod1(void, handle_cull_callbacks_and_traverse, IN, osg::Node &, node,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__void__handle_cull_callbacks_and_traverse__osg_Node_R1,
"",
"");
I_ProtectedMethod2(void, handle_cull_callbacks_and_accept, IN, osg::Node &, node, IN, osg::Node *, acceptNode,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__void__handle_cull_callbacks_and_accept__osg_Node_R1__osg_Node_P1,
"",
"");
I_ProtectedMethodWithDefaults4(osgUtil::RenderLeaf *, createOrReuseRenderLeaf, IN, osg::Drawable *, drawable, , IN, osg::RefMatrix *, projection, , IN, osg::RefMatrix *, matrix, , IN, float, depth, 0.0f,
Properties::NON_VIRTUAL,
Properties::NON_CONST,
__RenderLeaf_P1__createOrReuseRenderLeaf__osg_Drawable_P1__osg_RefMatrix_P1__osg_RefMatrix_P1__float,
"",
"");
I_SimpleProperty(osgUtil::CullVisitor::value_type, CalculatedFarPlane,
__value_type__getCalculatedFarPlane,
0);
I_SimpleProperty(osgUtil::CullVisitor::value_type, CalculatedNearPlane,
__value_type__getCalculatedNearPlane,
0);
I_SimpleProperty(osg::Camera *, CurrentCamera,
__osg_Camera_P1__getCurrentCamera,
0);
I_SimpleProperty(osgUtil::RenderBin *, CurrentRenderBin,
__RenderBin_P1__getCurrentRenderBin,
__void__setCurrentRenderBin__RenderBin_P1);
I_SimpleProperty(osgUtil::RenderStage *, CurrentRenderStage,
__RenderStage_P1__getCurrentRenderStage,
0);
I_SimpleProperty(osgUtil::StateGraph *, CurrentStateGraph,
__StateGraph_P1__getCurrentStateGraph,
0);
I_SimpleProperty(osg::Vec3, EyePoint,
__osg_Vec3__getEyePoint,
0);
I_SimpleProperty(osg::RenderInfo &, RenderInfo,
__osg_RenderInfo_R1__getRenderInfo,
__void__setRenderInfo__osg_RenderInfo_R1);
I_SimpleProperty(osgUtil::RenderStage *, RenderStage,
__RenderStage_P1__getRenderStage,
__void__setRenderStage__RenderStage_P1);
I_SimpleProperty(osgUtil::StateGraph *, RootStateGraph,
__StateGraph_P1__getRootStateGraph,
0);
I_SimpleProperty(osg::State *, State,
__osg_State_P1__getState,
__void__setState__osg_State_P1);
I_SimpleProperty(osgUtil::StateGraph *, StateGraph,
0,
__void__setStateGraph__StateGraph_P1);
I_SimpleProperty(osg::Vec3, ViewPoint,
__osg_Vec3__getViewPoint,
0);
END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osgUtil::CullVisitor >)
I_DeclaringFile("osg/ref_ptr");
I_Constructor0(____ref_ptr,
"",
"");
I_Constructor1(IN, osgUtil::CullVisitor *, ptr,
Properties::NON_EXPLICIT,
____ref_ptr__T_P1,
"",
"");
I_Constructor1(IN, const osg::ref_ptr< osgUtil::CullVisitor > &, rp,
Properties::NON_EXPLICIT,
____ref_ptr__C5_ref_ptr_R1,
"",
"");
I_Method0(osgUtil::CullVisitor *, get,
Properties::NON_VIRTUAL,
__T_P1__get,
"",
"");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"",
"");
I_Method0(osgUtil::CullVisitor *, release,
Properties::NON_VIRTUAL,
__T_P1__release,
"",
"");
I_Method1(void, swap, IN, osg::ref_ptr< osgUtil::CullVisitor > &, rp,
Properties::NON_VIRTUAL,
__void__swap__ref_ptr_R1,
"",
"");
I_SimpleProperty(osgUtil::CullVisitor *, ,
__T_P1__get,
0);
END_REFLECTOR
|
/*
Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifdef RENDERER_NULL
#include "RendererInternal.h"
#include "utils/Utils.h"
namespace renderer {
RendererImpl::RendererImpl(const RendererDesc &desc)
: RendererBase(desc)
{
SDL_Init(SDL_INIT_EVENTS);
swapchainFormat = Format::sRGBA8;
currentRefreshRate = 60;
maxRefreshRate = 60;
recreateRingBuffer(desc.ephemeralRingBufSize);
frames.resize(desc.swapchain.numFrames);
}
void RendererImpl::recreateRingBuffer(unsigned int newSize) {
assert(newSize > 0);
ringBufPtr = 0;
ringBufSize = newSize;
ringBuffer.resize(newSize, 0);
LOG_TODO("use valgrind to make sure we only write to intended parts of ring buffer");
}
RendererImpl::~RendererImpl() {
waitForDeviceIdle();
for (unsigned int i = 0; i < frames.size(); i++) {
auto &f = frames.at(i);
assert(!f.outstanding);
deleteFrameInternal(f);
}
frames.clear();
SDL_Quit();
}
bool Renderer::isRenderTargetFormatSupported(Format /* format */) const {
LOG_TODO("actually check it...");
return true;
}
BufferHandle Renderer::createBuffer(BufferType /* type */, uint32_t size, const void *contents) {
assert(size != 0);
assert(contents != nullptr);
Buffer buffer;
buffer.ringBufferAlloc = false;
buffer.beginOffs = 0;
buffer.size = size;
LOG_TODO("store contents into buffer");
return impl->buffers.add(std::move(buffer));
}
BufferHandle Renderer::createEphemeralBuffer(BufferType /* type */, uint32_t size, const void *contents) {
assert(size != 0);
assert(contents != nullptr);
unsigned int beginPtr = impl->ringBufferAllocate(size, 256);
LOG_TODO("use valgrind to enforce we only write to intended parts of ring buffer");
memcpy(&impl->ringBuffer[beginPtr], contents, size);
auto result = impl->buffers.add();
Buffer &buffer = result.first;
buffer.ringBufferAlloc = true;
buffer.beginOffs = beginPtr;
buffer.size = size;
impl->frames.at(impl->currentFrameIdx).ephemeralBuffers.push_back(result.second);
return result.second;
}
FramebufferHandle Renderer::createFramebuffer(const FramebufferDesc &desc) {
auto result = impl->framebuffers.add();
auto &fb = result.first;
fb.renderPass = desc.renderPass_;
return result.second;
}
RenderPassHandle Renderer::createRenderPass(const RenderPassDesc &desc) {
auto result = impl->renderpasses.add();
auto &rp = result.first;
rp.desc = desc;
return result.second;
}
PipelineHandle Renderer::createPipeline(const PipelineDesc &desc) {
auto result = impl->pipelines.add();
auto &pipeline = result.first;
pipeline.desc = desc;
return result.second;
}
RenderTargetHandle Renderer::createRenderTarget(const RenderTargetDesc &desc) {
assert(desc.width_ > 0);
assert(desc.height_ > 0);
assert(desc.format_ != +Format::Invalid);
auto result = impl->rendertargets.add();
auto &rendertarget = result.first;
rendertarget.desc = desc;
return result.second;
}
SamplerHandle Renderer::createSampler(const SamplerDesc &desc) {
Sampler sampler;
LOG_TODO("check desc");
sampler.desc = desc;
return impl->samplers.add(std::move(sampler));
}
VertexShaderHandle RendererImpl::createVertexShader(const std::string &name, const ShaderMacros & /* macros */) {
std::string vertexShaderName = name + ".vert";
auto result_ = vertexShaders.add();
auto &v = result_.first;
v.name = vertexShaderName;
return result_.second;
}
FragmentShaderHandle RendererImpl::createFragmentShader(const std::string &name, const ShaderMacros & /* macros */) {
std::string fragmentShaderName = name + ".frag";
auto result_ = fragmentShaders.add();
auto &f = result_.first;
f.name = fragmentShaderName;
return result_.second;
}
TextureHandle Renderer::createTexture(const TextureDesc &desc) {
assert(desc.width_ > 0);
assert(desc.height_ > 0);
assert(desc.numMips_ > 0);
LOG_TODO("check data");
Texture texture;
LOG_TODO("check desc");
texture.desc = desc;
return impl->textures.add(std::move(texture));
}
DSLayoutHandle Renderer::createDescriptorSetLayout(const DescriptorLayout *layout) {
DescriptorSetLayout dsLayout;
while (layout->type != +DescriptorType::End) {
dsLayout.layout.push_back(*layout);
layout++;
}
assert(layout->offset == 0);
return impl->dsLayouts.add(std::move(dsLayout));
}
TextureHandle Renderer::getRenderTargetView(RenderTargetHandle /* handle */, Format /* f */) {
TextureHandle handle;
return handle;
}
void Renderer::deleteBuffer(BufferHandle & /* handle */) {
}
void Renderer::deleteFramebuffer(FramebufferHandle & /* */) {
}
void Renderer::deletePipeline(PipelineHandle & /* handle */) {
}
void Renderer::deleteRenderPass(RenderPassHandle & /* handle */) {
}
void Renderer::deleteRenderTarget(RenderTargetHandle & /* handle */) {
}
void Renderer::deleteSampler(SamplerHandle & /* handle */) {
}
void Renderer::deleteTexture(TextureHandle & /* handle */) {
}
void Renderer::deleteBuffer(BufferHandle && /* handle */) {
}
void Renderer::deleteFramebuffer(FramebufferHandle && /* */) {
}
void Renderer::deletePipeline(PipelineHandle && /* handle */) {
}
void Renderer::deleteRenderPass(RenderPassHandle && /* handle */) {
}
void Renderer::deleteRenderTarget(RenderTargetHandle && /* handle */) {
}
void Renderer::deleteSampler(SamplerHandle && /* handle */) {
}
void Renderer::deleteTexture(TextureHandle && /* handle */) {
}
void Renderer::setSwapchainDesc(const SwapchainDesc &desc) {
impl->swapchainDesc = desc;
}
glm::uvec2 Renderer::getDrawableSize() const {
return glm::uvec2(impl->swapchainDesc.width, impl->swapchainDesc.height);
}
MemoryStats Renderer::getMemStats() const {
MemoryStats stats;
return stats;
}
void RendererImpl::waitForDeviceIdle() {
for (unsigned int i = 0; i < frames.size(); i++) {
auto &f = frames.at(i);
if (f.outstanding) {
// try to wait
waitForFrame(i);
assert(!f.outstanding);
}
}
}
void Renderer::beginFrame() {
assert(!impl->inFrame);
impl->inFrame = true;
impl->inRenderPass = false;
impl->validPipeline = false;
impl->pipelineDrawn = true;
impl->currentFrameIdx = impl->frameNum % impl->frames.size();
assert(impl->currentFrameIdx < impl->frames.size());
auto &frame = impl->frames.at(impl->currentFrameIdx);
// frames are a ringbuffer
// if the frame we want to reuse is still pending on the GPU, wait for it
if (frame.outstanding) {
impl->waitForFrame(impl->currentFrameIdx);
}
assert(!frame.outstanding);
}
void Renderer::beginRenderPassSwapchain(RenderPassHandle rpHandle) {
assert(rpHandle);
assert(!impl->inFrame);
impl->inFrame = true;
impl->inRenderPass = false;
impl->validPipeline = false;
impl->pipelineDrawn = true;
assert(!impl->renderingToSwapchain);
impl->renderingToSwapchain = true;
impl->currentFrameIdx = impl->frameNum % impl->frames.size();
assert(impl->currentFrameIdx < impl->frames.size());
auto &frame = impl->frames.at(impl->currentFrameIdx);
// frames are a ringbuffer
// if the frame we want to reuse is still pending on the GPU, wait for it
if (frame.outstanding) {
impl->waitForFrame(impl->currentFrameIdx);
}
assert(!frame.outstanding);
}
void Renderer::presentFrame() {
assert(impl->inFrame);
impl->inFrame = false;
auto &frame = impl->frames.at(impl->currentFrameIdx);
frame.usedRingBufPtr = impl->ringBufPtr;
frame.outstanding = true;
frame.lastFrameNum = impl->frameNum;
impl->frameNum++;
}
void RendererImpl::waitForFrame(unsigned int frameIdx) {
assert(frameIdx < frames.size());
Frame &frame = frames.at(frameIdx);
assert(frame.outstanding);
for (auto handle : frame.ephemeralBuffers) {
Buffer &buffer = buffers.get(handle);
if (buffer.ringBufferAlloc) {
buffer.ringBufferAlloc = false;
}
assert(buffer.size > 0);
buffer.size = 0;
buffer.beginOffs = 0;
buffers.remove(handle);
}
frame.ephemeralBuffers.clear();
frame.outstanding = false;
lastSyncedFrame = std::max(lastSyncedFrame, frame.lastFrameNum);
lastSyncedRingBufPtr = std::max(lastSyncedRingBufPtr, frame.usedRingBufPtr);
}
void RendererImpl::deleteFrameInternal(Frame &f) {
assert(!f.outstanding);
}
void Renderer::beginRenderPass(RenderPassHandle rpHandle, FramebufferHandle fbHandle) {
assert(impl->inFrame);
assert(!impl->inRenderPass);
assert(!impl->renderingToSwapchain);
impl->inRenderPass = true;
impl->validPipeline = false;
assert(fbHandle);
const auto &fb = impl->framebuffers.get(fbHandle);
// make sure renderpass and framebuffer match
assert(fb.renderPass == rpHandle);
}
void Renderer::endRenderPass() {
assert(impl->inFrame);
assert(impl->inRenderPass);
impl->inRenderPass = false;
impl->renderingToSwapchain = false;
}
void Renderer::layoutTransition(RenderTargetHandle image, Layout src, Layout dest) {
assert(image);
assert(dest != +Layout::Undefined);
assert(src != dest);
}
void Renderer::bindPipeline(PipelineHandle pipeline) {
assert(impl->inFrame);
assert(pipeline);
assert(impl->inRenderPass);
assert(impl->pipelineDrawn);
impl->pipelineDrawn = false;
impl->validPipeline = true;
impl->scissorSet = false;
impl->currentPipeline = impl->pipelines.get(pipeline).desc;
}
void Renderer::bindIndexBuffer(BufferHandle /* buffer */, bool /* bit16 */ ) {
assert(impl->inFrame);
assert(impl->validPipeline);
}
void Renderer::bindVertexBuffer(unsigned int /* binding */, BufferHandle /* buffer */) {
assert(impl->inFrame);
assert(impl->validPipeline);
}
void Renderer::bindDescriptorSet(unsigned int /* index */, DSLayoutHandle /* layout */, const void * /* data_ */) {
assert(impl->validPipeline);
}
void Renderer::setViewport(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) {
assert(impl->inFrame);
}
void Renderer::setScissorRect(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) {
assert(impl->validPipeline);
assert(impl->currentPipeline.scissorTest_);
impl->scissorSet = true;
}
void Renderer::blit(RenderTargetHandle source, RenderTargetHandle target) {
assert(source);
assert(target);
assert(!impl->inRenderPass);
}
void Renderer::resolveMSAA(RenderTargetHandle source, RenderTargetHandle target) {
assert(source);
assert(target);
assert(!impl->inRenderPass);
}
void Renderer::resolveMSAAToSwapchain(RenderTargetHandle source, Layout finalLayout) {
assert(source);
assert(finalLayout != +Layout::Undefined);
assert(impl->inFrame);
assert(!impl->inRenderPass);
assert(!impl->renderingToSwapchain);
}
void Renderer::draw(unsigned int /* firstVertex */, unsigned int vertexCount) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
void Renderer::drawIndexedInstanced(unsigned int vertexCount, unsigned int instanceCount) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(instanceCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
void Renderer::drawIndexedOffset(unsigned int vertexCount, unsigned int /* firstIndex */, unsigned int /* minIndex */, unsigned int /* maxIndex */) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
} // namespace renderer
#endif // RENDERER_NULL
Refactor null Renderer::createRenderTarget
/*
Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifdef RENDERER_NULL
#include "RendererInternal.h"
#include "utils/Utils.h"
namespace renderer {
RendererImpl::RendererImpl(const RendererDesc &desc)
: RendererBase(desc)
{
SDL_Init(SDL_INIT_EVENTS);
swapchainFormat = Format::sRGBA8;
currentRefreshRate = 60;
maxRefreshRate = 60;
recreateRingBuffer(desc.ephemeralRingBufSize);
frames.resize(desc.swapchain.numFrames);
}
void RendererImpl::recreateRingBuffer(unsigned int newSize) {
assert(newSize > 0);
ringBufPtr = 0;
ringBufSize = newSize;
ringBuffer.resize(newSize, 0);
LOG_TODO("use valgrind to make sure we only write to intended parts of ring buffer");
}
RendererImpl::~RendererImpl() {
waitForDeviceIdle();
for (unsigned int i = 0; i < frames.size(); i++) {
auto &f = frames.at(i);
assert(!f.outstanding);
deleteFrameInternal(f);
}
frames.clear();
SDL_Quit();
}
bool Renderer::isRenderTargetFormatSupported(Format /* format */) const {
LOG_TODO("actually check it...");
return true;
}
BufferHandle Renderer::createBuffer(BufferType /* type */, uint32_t size, const void *contents) {
assert(size != 0);
assert(contents != nullptr);
Buffer buffer;
buffer.ringBufferAlloc = false;
buffer.beginOffs = 0;
buffer.size = size;
LOG_TODO("store contents into buffer");
return impl->buffers.add(std::move(buffer));
}
BufferHandle Renderer::createEphemeralBuffer(BufferType /* type */, uint32_t size, const void *contents) {
assert(size != 0);
assert(contents != nullptr);
unsigned int beginPtr = impl->ringBufferAllocate(size, 256);
LOG_TODO("use valgrind to enforce we only write to intended parts of ring buffer");
memcpy(&impl->ringBuffer[beginPtr], contents, size);
auto result = impl->buffers.add();
Buffer &buffer = result.first;
buffer.ringBufferAlloc = true;
buffer.beginOffs = beginPtr;
buffer.size = size;
impl->frames.at(impl->currentFrameIdx).ephemeralBuffers.push_back(result.second);
return result.second;
}
FramebufferHandle Renderer::createFramebuffer(const FramebufferDesc &desc) {
auto result = impl->framebuffers.add();
auto &fb = result.first;
fb.renderPass = desc.renderPass_;
return result.second;
}
RenderPassHandle Renderer::createRenderPass(const RenderPassDesc &desc) {
auto result = impl->renderpasses.add();
auto &rp = result.first;
rp.desc = desc;
return result.second;
}
PipelineHandle Renderer::createPipeline(const PipelineDesc &desc) {
auto result = impl->pipelines.add();
auto &pipeline = result.first;
pipeline.desc = desc;
return result.second;
}
RenderTargetHandle Renderer::createRenderTarget(const RenderTargetDesc &desc) {
assert(desc.width_ > 0);
assert(desc.height_ > 0);
assert(desc.format_ != +Format::Invalid);
RenderTarget rendertarget;
rendertarget.desc = desc;
return impl->rendertargets.add(std::move(rendertarget));
}
SamplerHandle Renderer::createSampler(const SamplerDesc &desc) {
Sampler sampler;
LOG_TODO("check desc");
sampler.desc = desc;
return impl->samplers.add(std::move(sampler));
}
VertexShaderHandle RendererImpl::createVertexShader(const std::string &name, const ShaderMacros & /* macros */) {
std::string vertexShaderName = name + ".vert";
auto result_ = vertexShaders.add();
auto &v = result_.first;
v.name = vertexShaderName;
return result_.second;
}
FragmentShaderHandle RendererImpl::createFragmentShader(const std::string &name, const ShaderMacros & /* macros */) {
std::string fragmentShaderName = name + ".frag";
auto result_ = fragmentShaders.add();
auto &f = result_.first;
f.name = fragmentShaderName;
return result_.second;
}
TextureHandle Renderer::createTexture(const TextureDesc &desc) {
assert(desc.width_ > 0);
assert(desc.height_ > 0);
assert(desc.numMips_ > 0);
LOG_TODO("check data");
Texture texture;
LOG_TODO("check desc");
texture.desc = desc;
return impl->textures.add(std::move(texture));
}
DSLayoutHandle Renderer::createDescriptorSetLayout(const DescriptorLayout *layout) {
DescriptorSetLayout dsLayout;
while (layout->type != +DescriptorType::End) {
dsLayout.layout.push_back(*layout);
layout++;
}
assert(layout->offset == 0);
return impl->dsLayouts.add(std::move(dsLayout));
}
TextureHandle Renderer::getRenderTargetView(RenderTargetHandle /* handle */, Format /* f */) {
TextureHandle handle;
return handle;
}
void Renderer::deleteBuffer(BufferHandle & /* handle */) {
}
void Renderer::deleteFramebuffer(FramebufferHandle & /* */) {
}
void Renderer::deletePipeline(PipelineHandle & /* handle */) {
}
void Renderer::deleteRenderPass(RenderPassHandle & /* handle */) {
}
void Renderer::deleteRenderTarget(RenderTargetHandle & /* handle */) {
}
void Renderer::deleteSampler(SamplerHandle & /* handle */) {
}
void Renderer::deleteTexture(TextureHandle & /* handle */) {
}
void Renderer::deleteBuffer(BufferHandle && /* handle */) {
}
void Renderer::deleteFramebuffer(FramebufferHandle && /* */) {
}
void Renderer::deletePipeline(PipelineHandle && /* handle */) {
}
void Renderer::deleteRenderPass(RenderPassHandle && /* handle */) {
}
void Renderer::deleteRenderTarget(RenderTargetHandle && /* handle */) {
}
void Renderer::deleteSampler(SamplerHandle && /* handle */) {
}
void Renderer::deleteTexture(TextureHandle && /* handle */) {
}
void Renderer::setSwapchainDesc(const SwapchainDesc &desc) {
impl->swapchainDesc = desc;
}
glm::uvec2 Renderer::getDrawableSize() const {
return glm::uvec2(impl->swapchainDesc.width, impl->swapchainDesc.height);
}
MemoryStats Renderer::getMemStats() const {
MemoryStats stats;
return stats;
}
void RendererImpl::waitForDeviceIdle() {
for (unsigned int i = 0; i < frames.size(); i++) {
auto &f = frames.at(i);
if (f.outstanding) {
// try to wait
waitForFrame(i);
assert(!f.outstanding);
}
}
}
void Renderer::beginFrame() {
assert(!impl->inFrame);
impl->inFrame = true;
impl->inRenderPass = false;
impl->validPipeline = false;
impl->pipelineDrawn = true;
impl->currentFrameIdx = impl->frameNum % impl->frames.size();
assert(impl->currentFrameIdx < impl->frames.size());
auto &frame = impl->frames.at(impl->currentFrameIdx);
// frames are a ringbuffer
// if the frame we want to reuse is still pending on the GPU, wait for it
if (frame.outstanding) {
impl->waitForFrame(impl->currentFrameIdx);
}
assert(!frame.outstanding);
}
void Renderer::beginRenderPassSwapchain(RenderPassHandle rpHandle) {
assert(rpHandle);
assert(!impl->inFrame);
impl->inFrame = true;
impl->inRenderPass = false;
impl->validPipeline = false;
impl->pipelineDrawn = true;
assert(!impl->renderingToSwapchain);
impl->renderingToSwapchain = true;
impl->currentFrameIdx = impl->frameNum % impl->frames.size();
assert(impl->currentFrameIdx < impl->frames.size());
auto &frame = impl->frames.at(impl->currentFrameIdx);
// frames are a ringbuffer
// if the frame we want to reuse is still pending on the GPU, wait for it
if (frame.outstanding) {
impl->waitForFrame(impl->currentFrameIdx);
}
assert(!frame.outstanding);
}
void Renderer::presentFrame() {
assert(impl->inFrame);
impl->inFrame = false;
auto &frame = impl->frames.at(impl->currentFrameIdx);
frame.usedRingBufPtr = impl->ringBufPtr;
frame.outstanding = true;
frame.lastFrameNum = impl->frameNum;
impl->frameNum++;
}
void RendererImpl::waitForFrame(unsigned int frameIdx) {
assert(frameIdx < frames.size());
Frame &frame = frames.at(frameIdx);
assert(frame.outstanding);
for (auto handle : frame.ephemeralBuffers) {
Buffer &buffer = buffers.get(handle);
if (buffer.ringBufferAlloc) {
buffer.ringBufferAlloc = false;
}
assert(buffer.size > 0);
buffer.size = 0;
buffer.beginOffs = 0;
buffers.remove(handle);
}
frame.ephemeralBuffers.clear();
frame.outstanding = false;
lastSyncedFrame = std::max(lastSyncedFrame, frame.lastFrameNum);
lastSyncedRingBufPtr = std::max(lastSyncedRingBufPtr, frame.usedRingBufPtr);
}
void RendererImpl::deleteFrameInternal(Frame &f) {
assert(!f.outstanding);
}
void Renderer::beginRenderPass(RenderPassHandle rpHandle, FramebufferHandle fbHandle) {
assert(impl->inFrame);
assert(!impl->inRenderPass);
assert(!impl->renderingToSwapchain);
impl->inRenderPass = true;
impl->validPipeline = false;
assert(fbHandle);
const auto &fb = impl->framebuffers.get(fbHandle);
// make sure renderpass and framebuffer match
assert(fb.renderPass == rpHandle);
}
void Renderer::endRenderPass() {
assert(impl->inFrame);
assert(impl->inRenderPass);
impl->inRenderPass = false;
impl->renderingToSwapchain = false;
}
void Renderer::layoutTransition(RenderTargetHandle image, Layout src, Layout dest) {
assert(image);
assert(dest != +Layout::Undefined);
assert(src != dest);
}
void Renderer::bindPipeline(PipelineHandle pipeline) {
assert(impl->inFrame);
assert(pipeline);
assert(impl->inRenderPass);
assert(impl->pipelineDrawn);
impl->pipelineDrawn = false;
impl->validPipeline = true;
impl->scissorSet = false;
impl->currentPipeline = impl->pipelines.get(pipeline).desc;
}
void Renderer::bindIndexBuffer(BufferHandle /* buffer */, bool /* bit16 */ ) {
assert(impl->inFrame);
assert(impl->validPipeline);
}
void Renderer::bindVertexBuffer(unsigned int /* binding */, BufferHandle /* buffer */) {
assert(impl->inFrame);
assert(impl->validPipeline);
}
void Renderer::bindDescriptorSet(unsigned int /* index */, DSLayoutHandle /* layout */, const void * /* data_ */) {
assert(impl->validPipeline);
}
void Renderer::setViewport(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) {
assert(impl->inFrame);
}
void Renderer::setScissorRect(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) {
assert(impl->validPipeline);
assert(impl->currentPipeline.scissorTest_);
impl->scissorSet = true;
}
void Renderer::blit(RenderTargetHandle source, RenderTargetHandle target) {
assert(source);
assert(target);
assert(!impl->inRenderPass);
}
void Renderer::resolveMSAA(RenderTargetHandle source, RenderTargetHandle target) {
assert(source);
assert(target);
assert(!impl->inRenderPass);
}
void Renderer::resolveMSAAToSwapchain(RenderTargetHandle source, Layout finalLayout) {
assert(source);
assert(finalLayout != +Layout::Undefined);
assert(impl->inFrame);
assert(!impl->inRenderPass);
assert(!impl->renderingToSwapchain);
}
void Renderer::draw(unsigned int /* firstVertex */, unsigned int vertexCount) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
void Renderer::drawIndexedInstanced(unsigned int vertexCount, unsigned int instanceCount) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(instanceCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
void Renderer::drawIndexedOffset(unsigned int vertexCount, unsigned int /* firstIndex */, unsigned int /* minIndex */, unsigned int /* maxIndex */) {
assert(impl->inRenderPass);
assert(impl->validPipeline);
assert(vertexCount > 0);
assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet);
impl->pipelineDrawn = true;
}
} // namespace renderer
#endif // RENDERER_NULL
|
#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include "HalideBuffer.h"
#include <assert.h>
#if defined(TEST_OPENCL)
#include "HalideRuntimeOpenCL.h"
#elif defined(TEST_CUDA)
#include "HalideRuntimeCuda.h"
#endif
#include "gpu_only.h"
using namespace Halide::Runtime;
int main(int argc, char **argv) {
#if defined(TEST_OPENCL) || defined(TEST_CUDA)
const int W = 32, H = 32;
Buffer<int> input(W, H);
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
input(x, y) = x + y;
}
}
// Explicitly copy data to the GPU.
input.set_host_dirty();
#if defined(TEST_OPENCL)
input.copy_to_device(halide_opencl_device_interface());
#elif defined(TEST_CUDA)
input.copy_to_device(halide_cuda_device_interface());
#endif
Buffer<int> output(W, H);
// Create buffer_ts without host pointers.
buffer_t input_no_host = *((buffer_t *)input);
input_no_host.host = nullptr;
buffer_t output_no_host = *((buffer_t *)output);
// We need a fake pointer here to trick Halide into creating the
// device buffer (and not do bounds inference instead of running
// the pipeline). Halide will not dereference this pointer.
output_no_host.host = (uint8_t *)1;
gpu_only(&input_no_host, &output_no_host);
// Restore the host pointer and copy to host.
output_no_host.host = (uint8_t *)output.data();
halide_copy_to_host(nullptr, &output_no_host);
// Verify output.
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (input(x, y) * 2 != output(x, y)) {
printf("Error at %d, %d: %d != %d\n", x, y, input(x, y), output(x, y));
return -1;
}
}
}
printf("Success!\n");
#else
printf("No GPU target enabled, skipping...\n");
#endif
return 0;
}
Fix test
Former-commit-id: 540868f38b98be9c97d28775f4b1090c1cb1897e
#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include "HalideBuffer.h"
#include <assert.h>
#if defined(TEST_OPENCL)
#include "HalideRuntimeOpenCL.h"
#elif defined(TEST_CUDA)
#include "HalideRuntimeCuda.h"
#endif
#include "gpu_only.h"
using namespace Halide::Runtime;
int main(int argc, char **argv) {
#if defined(TEST_OPENCL) || defined(TEST_CUDA)
const int W = 32, H = 32;
Buffer<int> input(W, H);
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
input(x, y) = x + y;
}
}
// Explicitly copy data to the GPU.
input.set_host_dirty();
#if defined(TEST_OPENCL)
input.copy_to_device(halide_opencl_device_interface());
#elif defined(TEST_CUDA)
input.copy_to_device(halide_cuda_device_interface());
#endif
Buffer<int> output(W, H);
// Create halide_buffer_ts without host pointers.
halide_buffer_t input_no_host = *((halide_buffer_t *)input);
input_no_host.host = nullptr;
halide_buffer_t output_no_host = *((halide_buffer_t *)output);
// We need a fake pointer here to trick Halide into creating the
// device buffer (and not do bounds inference instead of running
// the pipeline). Halide will not dereference this pointer.
output_no_host.host = (uint8_t *)1;
gpu_only(&input_no_host, &output_no_host);
// Restore the host pointer and copy to host.
output_no_host.host = (uint8_t *)output.data();
halide_copy_to_host(nullptr, &output_no_host);
// Verify output.
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (input(x, y) * 2 != output(x, y)) {
printf("Error at %d, %d: %d != %d\n", x, y, input(x, y), output(x, y));
return -1;
}
}
}
printf("Success!\n");
#else
printf("No GPU target enabled, skipping...\n");
#endif
return 0;
}
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "mimedatabase.h"
#include "coreconstants.h"
#include "icore.h"
#include <utils/qtcassert.h>
#include <utils/algorithm.h>
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QLocale>
#include <QHash>
#include <QMultiHash>
#include <QRegExp>
#include <QSharedData>
#include <QSharedPointer>
#include <QStringList>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <functional>
enum { debugMimeDB = 0 };
// XML tags in mime files
static const char mimeInfoTagC[] = "mime-info";
static const char mimeTypeTagC[] = "mime-type";
static const char mimeTypeAttributeC[] = "type";
static const char subClassTagC[] = "sub-class-of";
static const char commentTagC[] = "comment";
static const char globTagC[] = "glob";
static const char aliasTagC[] = "alias";
static const char patternAttributeC[] = "pattern";
static const char weightAttributeC[] = "weight";
static const char localeAttributeC[] = "xml:lang";
static const char magicTagC[] = "magic";
static const char priorityAttributeC[] = "priority";
static const char matchTagC[] = "match";
static const char matchValueAttributeC[] = "value";
static const char matchTypeAttributeC[] = "type";
static const char matchStringTypeValueC[] = "string";
static const char matchByteTypeValueC[] = "byte";
static const char matchOffsetAttributeC[] = "offset";
// Types
static const char textTypeC[] = "text/plain";
static const char binaryTypeC[] = "application/octet-stream";
// UTF16 byte order marks
static const char bigEndianByteOrderMarkC[] = "\xFE\xFF";
static const char littleEndianByteOrderMarkC[] = "\xFF\xFE";
// Fallback priorities, must be low.
enum {
BinaryMatchPriority = Core::MimeGlobPattern::MinWeight + 1,
TextMatchPriority
};
/*!
\class Core::IMagicMatcher
\brief The IMagicMatcher class is an interface for a MIME type magic
matcher that examines file contents to determine the MIME type of a file.
\sa Core::MimeType, Core::MimeDatabase, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
namespace Core {
typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr;
namespace Internal {
/*!
\class Core::Internal::FileMatchContext
\brief The FileMatchContext class is the context passed on to the MIME
types when looking for a file match.
This class exists to enable reading the file contents \e {on demand},
as opposed to each mime type trying to open and read while checking.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class FileMatchContext
{
Q_DISABLE_COPY(FileMatchContext)
public:
// Max data to be read from a file
enum { MaxData = 2048 };
explicit FileMatchContext(const QFileInfo &fi);
inline QString fileName() const { return m_fileName; }
// Return (cached) first MaxData bytes of file
QByteArray data();
private:
enum State {
// File cannot be read/does not exist
NoDataAvailable,
// Not read yet
DataNotRead,
// Available
DataRead };
const QFileInfo m_fileInfo;
const QString m_fileName;
State m_state;
QByteArray m_data;
};
FileMatchContext::FileMatchContext(const QFileInfo &fi) :
m_fileInfo(fi),
m_fileName(fi.fileName()),
m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable)
{
}
QByteArray FileMatchContext::data()
{
// Do we need to read?
if (m_state == DataNotRead) {
const QString fullName = m_fileInfo.absoluteFilePath();
QFile file(fullName);
if (file.open(QIODevice::ReadOnly)) {
m_data = file.read(MaxData);
m_state = DataRead;
} else {
qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData());
m_state = NoDataAvailable;
}
}
return m_data;
}
/*!
\class Core::Internal::BinaryMatcher
\brief The BinaryMatcher class is the binary fallback matcher for the MIME
type \c{application/octet-stream}.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class BinaryMatcher : public IMagicMatcher
{
public:
BinaryMatcher() {}
virtual bool matches(const QByteArray & /*data*/) const { return true; }
virtual int priority() const { return BinaryMatchPriority; }
};
/*!
\class Core::Internal::HeuristicTextMagicMatcher
\brief The HeuristicTextMagicMatcher class implements a heuristic text file
matcher for MIME types.
If the data does not contain any character below tab (9), it is detected as
text. Additionally, UTF16 byte order markers are checked.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class HeuristicTextMagicMatcher : public IMagicMatcher
{
public:
HeuristicTextMagicMatcher() {}
virtual bool matches(const QByteArray &data) const;
virtual int priority() const { return TextMatchPriority; }
static bool isTextFile(const QByteArray &data);
};
bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data)
{
const int size = data.size();
for (int i = 0; i < size; i++) {
const char c = data.at(i);
if (c >= 0x01 && c < 0x09) // Sure-fire binary
return false;
if (c == 0) // Check for UTF16
return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC);
}
return true;
}
bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const
{
const bool rc = isTextFile(data);
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc;
return rc;
}
} // namespace Internal
/*!
\class Core::MagicRule
\brief The MagicRule class is a base class for standard Magic matching rules
based on contents
and offset specification.
Stores the offset and provides conversion helpers.
Base class for implementations for \c string and \c byte.
Others, such as \c little16 and \c big16, can be created when needed.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QChar MagicRule::kColon(QLatin1Char(':'));
MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos)
{
}
MagicRule::~MagicRule()
{
}
int MagicRule::startPos() const
{
return m_startPos;
}
int MagicRule::endPos() const
{
return m_endPos;
}
QString MagicRule::toOffset(const QPair<int, int> &startEnd)
{
return QString::fromLatin1("%1:%2").arg(startEnd.first).arg(startEnd.second);
}
QPair<int, int> MagicRule::fromOffset(const QString &offset)
{
const QStringList &startEnd = offset.split(kColon);
Q_ASSERT(startEnd.size() == 2);
return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt());
}
/*!
\class Core::MagicStringRule
\brief The MagicStringRule class provides rules for matching strings.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QString MagicStringRule::kMatchType(QLatin1String("string"));
MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) :
MagicRule(startPos, endPos), m_pattern(s.toUtf8())
{
}
MagicStringRule::~MagicStringRule()
{
}
QString MagicStringRule::matchType() const
{
return kMatchType;
}
QString MagicStringRule::matchValue() const
{
return QLatin1String(m_pattern);
}
bool MagicStringRule::matches(const QByteArray &data) const
{
// Quick check
if ((startPos() + m_pattern.size()) > data.size())
return false;
// Most common: some string at position 0:
if (startPos() == 0 && startPos() == endPos())
return data.startsWith(m_pattern);
// Range
const int index = data.indexOf(m_pattern, startPos());
const bool rc = index != -1 && index <= endPos();
if (debugMimeDB)
qDebug() << "Checking " << m_pattern << startPos() << endPos() << " returns " << rc;
return rc;
}
/*!
\class Core::MagicByteRule
\brief The MagicByteRule class provides rules for matching a sequence of
binary data.
Format:
\code
\0x7f\0x45\0x4c\0x46
\endcode
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QString MagicByteRule::kMatchType(QLatin1String("byte"));
MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) :
MagicRule(startPos, endPos), m_bytesSize(0)
{
if (validateByteSequence(s, &m_bytes))
m_bytesSize = m_bytes.size();
else
m_bytes.clear();
}
MagicByteRule::~MagicByteRule()
{
}
bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes)
{
// Expect an hex format value like this: \0x7f\0x45\0x4c\0x46
const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts);
foreach (const QString &byte, byteSequence) {
bool ok;
const int hex = byte.toInt(&ok, 16);
if (ok) {
if (bytes)
bytes->push_back(hex);
} else {
return false;
}
}
return true;
}
QString MagicByteRule::matchType() const
{
return kMatchType;
}
QString MagicByteRule::matchValue() const
{
QString value;
foreach (int byte, m_bytes)
value.append(QString::fromLatin1("\\0x%1").arg(byte, 0, 16));
return value;
}
bool MagicByteRule::matches(const QByteArray &data) const
{
if (m_bytesSize == 0)
return false;
const int dataSize = data.size();
for (int start = startPos(); start <= endPos(); ++start) {
if ((start + m_bytesSize) > dataSize)
return false;
int matchAt = 0;
while (matchAt < m_bytesSize) {
if (data.at(start + matchAt) != m_bytes.at(matchAt))
break;
++matchAt;
}
if (matchAt == m_bytesSize)
return true;
}
return false;
}
/*!
\class Core::MagicRuleMatcher
\brief The MagicRuleMatcher class implements a Magic matcher that checks the
number of rules based on the boolean operator OR.
This class is used for rules parsed from XML files.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
MagicRuleMatcher::MagicRuleMatcher() :
m_priority(65535)
{
}
void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule)
{
m_list.append(rule);
}
void MagicRuleMatcher::add(const MagicRuleList &ruleList)
{
m_list.append(ruleList);
}
MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const
{
return m_list;
}
bool MagicRuleMatcher::matches(const QByteArray &data) const
{
const MagicRuleList::const_iterator cend = m_list.constEnd();
for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it)
if ( (*it)->matches(data))
return true;
return false;
}
int MagicRuleMatcher::priority() const
{
return m_priority;
}
void MagicRuleMatcher::setPriority(int p)
{
m_priority = p;
}
IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers(
const QHash<int, MagicRuleList> &rulesByPriority)
{
IMagicMatcher::IMagicMatcherList matchers;
QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin();
for (; ruleIt != rulesByPriority.end(); ++ruleIt) {
MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher();
magicRuleMatcher->setPriority(ruleIt.key());
magicRuleMatcher->add(ruleIt.value());
matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher));
}
return matchers;
}
/*!
\class Core::GlobPattern
\brief The GlobPattern class provides a glob pattern for file names for
MIME type matching.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
MimeGlobPattern::MimeGlobPattern(const QString &pattern, unsigned weight) :
m_pattern(pattern), m_weight(weight)
{
bool hasQuestionMark = pattern.contains(QLatin1Char('?'));
bool hasStar = pattern.contains(QLatin1Char('*'));
if (!hasQuestionMark && hasStar && pattern.lastIndexOf(QLatin1Char('*')) == 0) {
m_type = Suffix;
} else if (!hasQuestionMark && !hasStar) {
m_type = Exact;
} else {
// This hopefully never happens as it is expensive.
m_type = Glob;
m_regexp.setPattern(pattern);
m_regexp.setPatternSyntax(QRegExp::Wildcard);
if (!m_regexp.isValid())
qWarning("%s: Invalid wildcard '%s'.", Q_FUNC_INFO, pattern.toUtf8().constData());
}
}
MimeGlobPattern::~MimeGlobPattern()
{
}
bool MimeGlobPattern::matches(const QString &fileName) const
{
if (m_type == Exact)
return fileName == m_pattern;
if (m_type == Suffix)
return fileName.endsWith(m_pattern.midRef(1));
return m_regexp.exactMatch(fileName);
}
/*!
\class Core::MimeType
\brief The MimeType class contains MIME type data used in \QC.
Contains most information from standard MIME type XML database files.
Currently, magic of types \c string anc \c bytes is supported. In addition,
C++ classes, derived from \c Core::IMagicMatcher can be added to check
on contents.
The class provides a list of suffixes and a concept of a
\e {preferred suffix} (derived from glob patterns). This is used for example
to be able to configure the suffix used for C++ files in \QC.
MIME type XML files look like follows:
\code
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<!-- Mime types must match the desktop file associations -->
<mime-type type="application/vnd.qt.qmakeprofile">
<comment xml:lang="en">Qt qmake Profile</comment>
<glob pattern="*.pro" weight="50"/>
</mime-type>
</mime-info>
\endcode
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class MimeTypeData : public QSharedData {
public:
typedef QHash<QString,QString> LocaleHash;
MimeTypeData();
void clear();
void assignSuffix(const QString &pattern);
void assignSuffixes(const QStringList &patterns);
void debug(QTextStream &str, int indent = 0) const;
QRegExp suffixPattern;
QString type;
QString comment;
LocaleHash localeComments;
QStringList aliases;
QList<MimeGlobPattern> globPatterns;
QStringList subClassesOf;
QString preferredSuffix;
QStringList suffixes;
IMagicMatcher::IMagicMatcherList magicMatchers;
};
MimeTypeData::MimeTypeData()
// RE to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or
// "*.log[1-9]"
: suffixPattern(QLatin1String("^\\*\\.[\\w+]+$"))
{
QTC_CHECK(suffixPattern.isValid());
}
void MimeTypeData::clear()
{
type.clear();
comment.clear();
aliases.clear();
globPatterns.clear();
subClassesOf.clear();
preferredSuffix.clear();
suffixes.clear();
magicMatchers.clear();
}
void MimeTypeData::assignSuffix(const QString &pattern)
{
if (suffixPattern.exactMatch(pattern)) {
const QString suffix = pattern.right(pattern.size() - 2);
suffixes.push_back(suffix);
if (preferredSuffix.isEmpty())
preferredSuffix = suffix;
}
}
void MimeTypeData::assignSuffixes(const QStringList &patterns)
{
foreach (const QString &pattern, patterns)
assignSuffix(pattern);
}
void MimeTypeData::debug(QTextStream &str, int indent) const
{
const QString indentS = QString(indent, QLatin1Char(' '));
const QLatin1Char comma(',');
str << indentS << "Type: " << type;
if (!aliases.empty())
str << " Aliases: " << aliases.join(comma);
str << ", magic: " << magicMatchers.size() << '\n';
str << indentS << "Comment: " << comment << '\n';
if (!subClassesOf.empty())
str << indentS << "SubClassesOf: " << subClassesOf.join(comma) << '\n';
if (!globPatterns.empty()) {
str << indentS << "Glob: ";
foreach (const MimeGlobPattern &gp, globPatterns)
str << gp.pattern() << '(' << gp.weight() << ')';
str << '\n';
if (!suffixes.empty()) {
str << indentS << "Suffixes: " << suffixes.join(comma)
<< " preferred: " << preferredSuffix << '\n';
}
}
str << '\n';
}
// ---------------- MimeType
MimeType::MimeType() :
m_d(new MimeTypeData)
{
}
MimeType::MimeType(const MimeType &rhs) :
m_d(rhs.m_d)
{
}
MimeType &MimeType::operator=(const MimeType &rhs)
{
if (this != &rhs)
m_d = rhs.m_d;
return *this;
}
MimeType::MimeType(const MimeTypeData &d) :
m_d(new MimeTypeData(d))
{
}
MimeType::~MimeType()
{
}
void MimeType::clear()
{
m_d->clear();
}
bool MimeType::isNull() const
{
return m_d->type.isEmpty();
}
MimeType::operator bool() const
{
return !isNull();
}
bool MimeType::isTopLevel() const
{
return m_d->subClassesOf.empty();
}
QString MimeType::type() const
{
return m_d->type;
}
void MimeType::setType(const QString &type)
{
m_d->type = type;
}
QString MimeType::comment() const
{
return m_d->comment;
}
void MimeType::setComment(const QString &comment)
{
m_d->comment = comment;
}
// Return "en", "de", etc. derived from "en_US", de_DE".
static inline QString systemLanguage()
{
QString name = QLocale::system().name();
const int underScorePos = name.indexOf(QLatin1Char('_'));
if (underScorePos != -1)
name.truncate(underScorePos);
return name;
}
QString MimeType::localeComment(const QString &localeArg) const
{
const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg;
const MimeTypeData::LocaleHash::const_iterator it = m_d->localeComments.constFind(locale);
if (it == m_d->localeComments.constEnd())
return m_d->comment;
return it.value();
}
void MimeType::setLocaleComment(const QString &locale, const QString &comment)
{
m_d->localeComments[locale] = comment;
}
QStringList MimeType::aliases() const
{
return m_d->aliases;
}
void MimeType::setAliases(const QStringList &a)
{
m_d->aliases = a;
}
QList<MimeGlobPattern> MimeType::globPatterns() const
{
return m_d->globPatterns;
}
void MimeType::setGlobPatterns(const QList<MimeGlobPattern> &g)
{
m_d->globPatterns = g;
QString oldPrefferedSuffix = m_d->preferredSuffix;
m_d->suffixes.clear();
m_d->preferredSuffix.clear();
m_d->assignSuffixes(MimeDatabase::fromGlobPatterns(g));
if (m_d->preferredSuffix != oldPrefferedSuffix && m_d->suffixes.contains(oldPrefferedSuffix))
m_d->preferredSuffix = oldPrefferedSuffix;
}
QStringList MimeType::subClassesOf() const
{
return m_d->subClassesOf;
}
void MimeType::setSubClassesOf(const QStringList &s)
{
m_d->subClassesOf = s;
}
QString MimeType::preferredSuffix() const
{
return m_d->preferredSuffix;
}
bool MimeType::setPreferredSuffix(const QString &s)
{
if (!m_d->suffixes.contains(s)) {
qWarning("%s: Attempt to set preferred suffix to '%s', which is not in the list of suffixes: %s.",
m_d->type.toUtf8().constData(),
s.toUtf8().constData(),
m_d->suffixes.join(QLatin1Char(',')).toUtf8().constData());
return false;
}
m_d->preferredSuffix = s;
return true;
}
QString MimeType::formatFilterString(const QString &description, const QList<MimeGlobPattern> &globs)
{
QString rc;
if (globs.empty()) // Binary files
return rc;
{
QTextStream str(&rc);
str << description;
if (!globs.empty()) {
str << " (";
const int size = globs.size();
for (int i = 0; i < size; i++) {
if (i)
str << ' ';
str << globs.at(i).pattern();
}
str << ')';
}
}
return rc;
}
QString MimeType::filterString() const
{
// @todo: Use localeComment() once creator is shipped with translations
return formatFilterString(comment(), m_d->globPatterns);
}
bool MimeType::matchesType(const QString &type) const
{
return m_d->type == type || m_d->aliases.contains(type);
}
unsigned MimeType::matchesFile(const QFileInfo &file) const
{
Internal::FileMatchContext context(file);
const unsigned suffixPriority = matchesFileBySuffix(context);
if (suffixPriority >= MimeGlobPattern::MaxWeight)
return suffixPriority;
return qMax(suffixPriority, matchesFileByContent(context));
}
unsigned MimeType::matchesFileBySuffix(Internal::FileMatchContext &c) const
{
// check globs
foreach (const MimeGlobPattern &gp, m_d->globPatterns) {
if (gp.matches(c.fileName()))
return gp.weight();
}
return 0;
}
unsigned MimeType::matchesFileByContent(Internal::FileMatchContext &c) const
{
// Nope, try magic matchers on context data
if (m_d->magicMatchers.isEmpty())
return 0;
return matchesData(c.data());
}
unsigned MimeType::matchesData(const QByteArray &data) const
{
unsigned priority = 0;
if (!data.isEmpty()) {
foreach (const IMagicMatcher::IMagicMatcherSharedPointer &matcher, m_d->magicMatchers) {
const unsigned magicPriority = matcher->priority();
if (magicPriority > priority && matcher->matches(data))
priority = magicPriority;
}
}
return priority;
}
QStringList MimeType::suffixes() const
{
return m_d->suffixes;
}
void MimeType::addMagicMatcher(const IMagicMatcherSharedPointer &matcher)
{
m_d->magicMatchers.push_back(matcher);
}
const MimeType::IMagicMatcherList &MimeType::magicMatchers() const
{
return m_d->magicMatchers;
}
void MimeType::setMagicMatchers(const IMagicMatcherList &matchers)
{
m_d->magicMatchers = matchers;
}
namespace {
struct RemovePred : std::unary_function<MimeType::IMagicMatcherSharedPointer, bool>
{
RemovePred(bool keepRuleBased) : m_keepRuleBase(keepRuleBased) {}
bool m_keepRuleBase;
bool operator()(const MimeType::IMagicMatcherSharedPointer &matcher) {
if ((m_keepRuleBase && !dynamic_cast<MagicRuleMatcher *>(matcher.data()))
|| (!m_keepRuleBase && dynamic_cast<MagicRuleMatcher *>(matcher.data())))
return true;
return false;
}
};
} // Anonymous
MimeType::IMagicMatcherList MimeType::magicRuleMatchers() const
{
IMagicMatcherList ruleMatchers = m_d->magicMatchers;
Utils::erase(ruleMatchers, RemovePred(true));
return ruleMatchers;
}
void MimeType::setMagicRuleMatchers(const IMagicMatcherList &matchers)
{
Utils::erase(m_d->magicMatchers, RemovePred(false));
m_d->magicMatchers.append(matchers);
}
QDebug operator<<(QDebug d, const MimeType &mt)
{
QString s;
{
QTextStream str(&s);
mt.m_d->debug(str);
}
d << s;
return d;
}
namespace Internal {
/*!
\class Core::Internal::BaseMimeTypeParser
\brief The BaseMimeTypeParser class provides a generic parser for a
sequence of <mime-type>.
This class calls the abstract handler function process for the MIME types
it finds.
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::MimeTypeParser
*/
class BaseMimeTypeParser
{
Q_DISABLE_COPY(BaseMimeTypeParser)
public:
BaseMimeTypeParser() {}
virtual ~BaseMimeTypeParser() {}
bool parse(QIODevice *dev, const QString &fileName, QString *errorMessage);
private:
// Overwrite to process the sequence of parsed data
virtual bool process(const MimeType &t, QString *errorMessage) = 0;
void addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const;
enum ParseStage { ParseBeginning,
ParseMimeInfo,
ParseMimeType,
ParseComment,
ParseGlobPattern,
ParseSubClass,
ParseAlias,
ParseMagic,
ParseMagicMatchRule,
ParseOtherMimeTypeSubTag,
ParseError };
static ParseStage nextStage(ParseStage currentStage, const QStringRef &startElement);
};
void BaseMimeTypeParser::addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const
{
if (pattern.isEmpty())
return;
// Collect patterns as a QRegExp list and filter out the plain
// suffix ones for our suffix list. Use first one as preferred
if (weight.isEmpty())
d->globPatterns.push_back(MimeGlobPattern(pattern));
else
d->globPatterns.push_back(MimeGlobPattern(pattern, weight.toInt()));
d->assignSuffix(pattern);
}
BaseMimeTypeParser::ParseStage BaseMimeTypeParser::nextStage(ParseStage currentStage, const QStringRef &startElement)
{
switch (currentStage) {
case ParseBeginning:
if (startElement == QLatin1String(mimeInfoTagC))
return ParseMimeInfo;
if (startElement == QLatin1String(mimeTypeTagC))
return ParseMimeType;
return ParseError;
case ParseMimeInfo:
return startElement == QLatin1String(mimeTypeTagC) ? ParseMimeType : ParseError;
case ParseMimeType:
case ParseComment:
case ParseGlobPattern:
case ParseSubClass:
case ParseAlias:
case ParseOtherMimeTypeSubTag:
case ParseMagicMatchRule:
if (startElement == QLatin1String(mimeTypeTagC)) // Sequence of <mime-type>
return ParseMimeType;
if (startElement == QLatin1String(commentTagC ))
return ParseComment;
if (startElement == QLatin1String(globTagC))
return ParseGlobPattern;
if (startElement == QLatin1String(subClassTagC))
return ParseSubClass;
if (startElement == QLatin1String(aliasTagC))
return ParseAlias;
if (startElement == QLatin1String(magicTagC))
return ParseMagic;
if (startElement == QLatin1String(matchTagC))
return ParseMagicMatchRule;
return ParseOtherMimeTypeSubTag;
case ParseMagic:
if (startElement == QLatin1String(matchTagC))
return ParseMagicMatchRule;
break;
case ParseError:
break;
}
return ParseError;
}
// Parse int number from an (attribute) string)
static bool parseNumber(const QString &n, int *target, QString *errorMessage)
{
bool ok;
*target = n.toInt(&ok);
if (!ok) {
*errorMessage = QString::fromLatin1("Not a number \"%1\".").arg(n);
return false;
}
return true;
}
// Evaluate a magic match rule like
// <match value="must be converted with BinHex" type="string" offset="11"/>
// <match value="0x9501" type="big16" offset="0:64"/>
static bool addMagicMatchRule(const QXmlStreamAttributes &atts,
const MagicRuleMatcherPtr &ruleMatcher,
QString *errorMessage)
{
const QStringRef type = atts.value(QLatin1String(matchTypeAttributeC));
if (type != QLatin1String(matchStringTypeValueC) &&
type != QLatin1String(matchByteTypeValueC)) {
qWarning("%s: match type %s is not supported.", Q_FUNC_INFO, type.toUtf8().constData());
return true;
}
const QString value = atts.value(QLatin1String(matchValueAttributeC)).toString();
if (value.isEmpty()) {
*errorMessage = QString::fromLatin1("Empty match value detected.");
return false;
}
// Parse for offset as "1" or "1:10"
int startPos, endPos;
const QString offsetS = atts.value(QLatin1String(matchOffsetAttributeC)).toString();
const int colonIndex = offsetS.indexOf(QLatin1Char(':'));
const QString startPosS = colonIndex == -1 ? offsetS : offsetS.mid(0, colonIndex);
const QString endPosS = colonIndex == -1 ? offsetS : offsetS.mid(colonIndex + 1);
if (!parseNumber(startPosS, &startPos, errorMessage) || !parseNumber(endPosS, &endPos, errorMessage))
return false;
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << value << startPos << endPos;
if (type == QLatin1String(matchStringTypeValueC))
ruleMatcher->add(QSharedPointer<MagicRule>(new MagicStringRule(value, startPos, endPos)));
else
ruleMatcher->add(QSharedPointer<MagicRule>(new MagicByteRule(value, startPos, endPos)));
return true;
}
bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
MimeTypeData data;
MagicRuleMatcherPtr ruleMatcher;
QXmlStreamReader reader(dev);
ParseStage ps = ParseBeginning;
QXmlStreamAttributes atts;
while (!reader.atEnd()) {
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
ps = nextStage(ps, reader.name());
atts = reader.attributes();
switch (ps) {
case ParseMimeType: { // start parsing a type
const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (type.isEmpty())
reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
else
data.type = type;
}
break;
case ParseGlobPattern:
addGlobPattern(atts.value(QLatin1String(patternAttributeC)).toString(),
atts.value(QLatin1String(weightAttributeC)).toString(), &data);
break;
case ParseSubClass: {
const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (!inheritsFrom.isEmpty())
data.subClassesOf.push_back(inheritsFrom);
}
break;
case ParseComment: {
// comments have locale attributes. We want the default, English one
const QStringRef locale = atts.value(QLatin1String(localeAttributeC));
const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
if (locale.isEmpty())
data.comment = comment;
else
data.localeComments.insert(locale.toString(), comment);
}
break;
case ParseAlias: {
const QStringRef alias = atts.value(QLatin1String(mimeTypeAttributeC));
if (!alias.isEmpty())
data.aliases.push_back(alias.toString());
}
break;
case ParseMagic: {
int priority = 0;
const QStringRef priorityS = atts.value(QLatin1String(priorityAttributeC));
if (!priorityS.isEmpty()) {
if (!parseNumber(priorityS.toString(), &priority, errorMessage))
return false;
}
ruleMatcher = MagicRuleMatcherPtr(new MagicRuleMatcher);
ruleMatcher->setPriority(priority);
}
break;
case ParseMagicMatchRule:
QTC_ASSERT(!ruleMatcher.isNull(), return false);
if (!addMagicMatchRule(atts, ruleMatcher, errorMessage))
return false;
break;
case ParseError:
reader.raiseError(QString::fromLatin1("Unexpected element <%1>").arg(reader.name().toString()));
break;
default:
break;
} // switch nextStage
break;
// continue switch QXmlStreamReader::Token...
case QXmlStreamReader::EndElement: // Finished element
if (reader.name() == QLatin1String(mimeTypeTagC)) {
if (!process(MimeType(data), errorMessage))
return false;
data.clear();
} else {
// Finished a match sequence
if (reader.name() == QLatin1String(magicTagC)) {
QTC_ASSERT(!ruleMatcher.isNull(), return false);
data.magicMatchers.push_back(ruleMatcher);
ruleMatcher = MagicRuleMatcherPtr();
}
}
break;
default:
break;
} // switch reader.readNext()
}
if (reader.hasError()) {
*errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString());
return false;
}
return true;
}
} // namespace Internal
// MimeMapEntry: Entry of a type map, consisting of type and level.
enum { Dangling = 32767 };
struct MimeMapEntry
{
explicit MimeMapEntry(const MimeType &t = MimeType(), int aLevel = Dangling);
MimeType type;
int level; // hierachy level
};
MimeMapEntry::MimeMapEntry(const MimeType &t, int aLevel) :
type(t),
level(aLevel)
{
}
/*!
\class Core::MimeDatabase
\brief The MimeDatabase class is a MIME type database to which the plugins
can add the MIME types they handle.
The class is protected by a QMutex and can therefore be accessed by threads.
A good testcase is to run it over \c {/usr/share/mime/<*>/<*>.xml} on Linux.
When adding a \c{text/plain} to it, the MIME type will receive a magic matcher
that checks for text files that do not match the globs by heuristics.
\section1 Design Considerations
Storage requirements:
\list
\li Must be robust in case of incomplete hierarchies and dangling entries.
\li Plugins will not load and register their MIME types in order of
inheritance.
\li Multiple inheritance (several subClassesOf) can occur.
\li Provide quick lookup by name.
\li Provide quick lookup by file type.
\endlist
This basically rules out a pointer-based tree, so the structure chosen is:
\list
\li An alias map \c {QString->QString} for mapping aliases to types.
\li A map \c {QString->MimeMapEntry} for the types (MimeMapEntry being a pair of
MimeType and (hierarchy) level.
\li A map \c {QString->QString} representing parent to child relations (enabling
recursing over children).
\li Using strings avoids dangling pointers.
\endlist
The hierarchy level is used for mapping by file types. When \c findByFile()
is first called after \c addMimeType(), it recurses over the hierarchy and sets
the hierarchy level of the entries accordingly (0 toplevel, 1 first
order...). It then does several passes over the type map, checking the
globs for maxLevel, maxLevel-1....until it finds a match (the idea being
to check the most specific types first). Starting a recursion from the
leaves is not suitable since it will hit parent nodes several times.
\sa Core::MimeType, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class MimeDatabasePrivate
{
Q_DISABLE_COPY(MimeDatabasePrivate)
public:
MimeDatabasePrivate();
bool addMimeTypes(const QString &fileName, QString *errorMessage);
bool addMimeTypes(QIODevice *device, QString *errorMessage);
bool addMimeType(MimeType mt);
MimeType findByType(const QString &type) const;
MimeType findByFile(const QFileInfo &f) const;
MimeType findByData(const QByteArray &data) const;
QStringList filterStrings() const;
QStringList suffixes() const;
bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);
QList<MimeGlobPattern> globPatterns() const;
void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns);
QList<QSharedPointer<IMagicMatcher> > magicMatchers() const;
void setMagicMatchers(const QString &typeOrAlias,
const QList<QSharedPointer<IMagicMatcher> > &matchers);
QList<MimeType> mimeTypes() const;
void syncUserModifiedMimeTypes();
static QList<MimeType> readUserModifiedMimeTypes();
static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes);
void clearUserModifiedMimeTypes();
static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns,
int weight = MimeGlobPattern::MaxWeight);
static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns);
void debug(QTextStream &str) const;
typedef QHash<QString, MimeMapEntry> TypeMimeTypeMap;
typedef QHash<QString, QString> AliasMap;
typedef QMultiHash<QString, QString> ParentChildrenMap;
static const QString kModifiedMimeTypesFile;
static QString kModifiedMimeTypesPath;
bool addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage);
inline const QString &resolveAlias(const QString &name) const;
MimeType findByFile(const QFileInfo &f, unsigned *priority) const;
MimeType findByData(const QByteArray &data, unsigned *priority) const;
void determineLevels();
void raiseLevelRecursion(MimeMapEntry &e, int level);
TypeMimeTypeMap m_typeMimeTypeMap;
AliasMap m_aliasMap;
ParentChildrenMap m_parentChildrenMap;
int m_maxLevel;
QMutex m_mutex;
};
const QString MimeDatabasePrivate::kModifiedMimeTypesFile(QLatin1String("modifiedmimetypes.xml"));
QString MimeDatabasePrivate::kModifiedMimeTypesPath;
MimeDatabasePrivate::MimeDatabasePrivate() :
m_maxLevel(-1)
{
// Assign here to avoid non-local static data initialization issues.
kModifiedMimeTypesPath = ICore::userResourcePath() + QLatin1String("/mimetypes/");
}
/*!
\class Core::Internal::MimeTypeParser
\brief The MimeTypeParser class provides a MIME type parser.
Populates Core::MimeDataBase
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::MimeTypeParser
*/
namespace Internal {
// Parser that builds MimeDB hierarchy by adding to MimeDatabasePrivate
class MimeTypeParser : public BaseMimeTypeParser {
public:
explicit MimeTypeParser(MimeDatabasePrivate &db) : m_db(db) {}
private:
virtual bool process(const MimeType &t, QString *) { m_db.addMimeType(t); return true; }
MimeDatabasePrivate &m_db;
};
} // namespace Internal
bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage)
{
Internal::MimeTypeParser parser(*this);
return parser.parse(device, fileName, errorMessage);
}
bool MimeDatabasePrivate::addMimeTypes(const QString &fileName, QString *errorMessage)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
*errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString());
return false;
}
return addMimeTypes(&file, fileName, errorMessage);
}
bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, QString *errorMessage)
{
return addMimeTypes(device, QLatin1String("<stream>"), errorMessage);
}
bool MimeDatabasePrivate::addMimeType(MimeType mt)
{
if (!mt)
return false;
const QString type = mt.type();
// Hack: Add a magic text matcher to "text/plain" and the fallback matcher to
// binary types "application/octet-stream"
if (type == QLatin1String(textTypeC)) {
mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::HeuristicTextMagicMatcher));
} else {
if (type == QLatin1String(binaryTypeC))
mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::BinaryMatcher));
}
// insert the type.
m_typeMimeTypeMap.insert(type, MimeMapEntry(mt));
// Register the children
// Aliases will be resolved later once all mime types are known.
const QStringList subClassesOf = mt.subClassesOf();
if (!subClassesOf.empty()) {
const QStringList::const_iterator socend = subClassesOf.constEnd();
for (QStringList::const_iterator soit = subClassesOf.constBegin(); soit != socend; ++soit)
m_parentChildrenMap.insert(*soit, type);
}
// register aliasses
const QStringList aliases = mt.aliases();
if (!aliases.empty()) {
const QStringList::const_iterator cend = aliases.constEnd();
for (QStringList::const_iterator it = aliases.constBegin(); it != cend; ++it)
m_aliasMap.insert(*it, type);
}
m_maxLevel = -1; // Mark as dirty
return true;
}
const QString &MimeDatabasePrivate::resolveAlias(const QString &name) const
{
const AliasMap::const_iterator aliasIt = m_aliasMap.constFind(name);
return aliasIt == m_aliasMap.constEnd() ? name : aliasIt.value();
}
void MimeDatabasePrivate::raiseLevelRecursion(MimeMapEntry &e, int level)
{
if (e.level == Dangling || e.level < level)
e.level = level;
if (m_maxLevel < level)
m_maxLevel = level;
// At all events recurse over children since nodes might have been
// added.
QStringList childTypes = m_parentChildrenMap.values(e.type.type());
foreach (const QString &alias, e.type.aliases())
childTypes.append(m_parentChildrenMap.values(alias));
if (childTypes.empty())
return;
// look them up in the type->mime type map
const int nextLevel = level + 1;
const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
const QStringList::const_iterator cend = childTypes.constEnd();
for (QStringList::const_iterator it = childTypes.constBegin(); it != cend; ++it) {
const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*it));
if (tm_it == tm_end) {
qWarning("%s: Inconsistent mime hierarchy detected, child %s of %s cannot be found.",
Q_FUNC_INFO, it->toUtf8().constData(), e.type.type().toUtf8().constData());
} else {
raiseLevelRecursion(*tm_it, nextLevel);
}
}
}
void MimeDatabasePrivate::determineLevels()
{
// Loop over toplevels and recurse down their hierarchies.
// Determine top levels by subtracting the children from the parent
// set. Note that a toplevel at this point might have 'subclassesOf'
// set to some class that is not in the DB, so, checking for an empty
// 'subclassesOf' set is not sufficient to find the toplevels.
// First, take the parent->child entries whose parent exists and build
// sets of parents/children
QSet<QString> parentSet, childrenSet;
const ParentChildrenMap::const_iterator pcend = m_parentChildrenMap.constEnd();
for (ParentChildrenMap::const_iterator it = m_parentChildrenMap.constBegin(); it != pcend; ++it)
if (m_typeMimeTypeMap.contains(it.key())) {
parentSet.insert(it.key());
childrenSet.insert(it.value());
}
const QSet<QString> topLevels = parentSet.subtract(childrenSet);
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << "top levels" << topLevels;
const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
const QSet<QString>::const_iterator tl_cend = topLevels.constEnd();
for (QSet<QString>::const_iterator tl_it = topLevels.constBegin(); tl_it != tl_cend; ++tl_it) {
const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*tl_it));
if (tm_it == tm_end) {
qWarning("%s: Inconsistent mime hierarchy detected, top level element %s cannot be found.",
Q_FUNC_INFO, tl_it->toUtf8().constData());
} else {
raiseLevelRecursion(tm_it.value(), 0);
}
}
}
bool MimeDatabasePrivate::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
return tit.value().type.setPreferredSuffix(suffix);
return false;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByType(const QString &typeOrAlias) const
{
const TypeMimeTypeMap::const_iterator tit = m_typeMimeTypeMap.constFind(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.constEnd())
return tit.value().type;
return MimeType();
}
// Debugging wrapper around findByFile()
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const
{
unsigned priority = 0;
if (debugMimeDB)
qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath();
const MimeType rc = findByFile(f, &priority);
if (debugMimeDB) {
if (rc)
qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type();
else
qDebug() << "<MimeDatabase::findByFile: no match";
}
return rc;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityPtr) const
{
// Is the hierarchy set up in case we find several matches?
if (m_maxLevel < 0) {
MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this);
db->determineLevels();
}
// First, glob patterns are evaluated. If there is a match with max weight,
// this one is selected and we are done. Otherwise, the file contents are
// evaluated and the match with the highest value (either a magic priority or
// a glob pattern weight) is selected. Matching starts from max level (most
// specific) in both cases, even when there is already a suffix matching candidate.
*priorityPtr = 0;
MimeType candidate;
Internal::FileMatchContext context(f);
// Pass 1) Try to match on suffix
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (int level = m_maxLevel; level >= 0; level--) {
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned suffixPriority = it.value().type.matchesFileBySuffix(context);
if (suffixPriority && suffixPriority > *priorityPtr) {
*priorityPtr = suffixPriority;
candidate = it.value().type;
if (suffixPriority >= MimeGlobPattern::MaxWeight)
return candidate;
}
}
}
}
// Pass 2) Match on content
if (!f.isReadable())
return candidate;
for (int level = m_maxLevel; level >= 0; level--) {
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned contentPriority = it.value().type.matchesFileByContent(context);
if (contentPriority && contentPriority > *priorityPtr) {
*priorityPtr = contentPriority;
candidate = it.value().type;
}
}
}
}
return candidate;
}
// Debugging wrapper around findByData()
MimeType MimeDatabasePrivate::findByData(const QByteArray &data) const
{
unsigned priority = 0;
if (debugMimeDB)
qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex();
const MimeType rc = findByData(data, &priority);
if (debugMimeDB) {
if (rc)
qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type();
else
qDebug() << "<MimeDatabase::findByData: no match";
}
return rc;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByData(const QByteArray &data, unsigned *priorityPtr) const
{
// Is the hierarchy set up in case we find several matches?
if (m_maxLevel < 0) {
MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this);
db->determineLevels();
}
*priorityPtr = 0;
MimeType candidate;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (int level = m_maxLevel; level >= 0; level--)
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
if (it.value().level == level) {
const unsigned contentPriority = it.value().type.matchesData(data);
if (contentPriority && contentPriority > *priorityPtr) {
*priorityPtr = contentPriority;
candidate = it.value().type;
}
}
return candidate;
}
// Return all known suffixes
QStringList MimeDatabasePrivate::suffixes() const
{
QStringList rc;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
rc += it.value().type.suffixes();
return rc;
}
QStringList MimeDatabasePrivate::filterStrings() const
{
QStringList rc;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
const QString filterString = it.value().type.filterString();
if (!filterString.isEmpty())
rc += filterString;
}
return rc;
}
QList<MimeGlobPattern> MimeDatabasePrivate::globPatterns() const
{
QList<MimeGlobPattern> globPatterns;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
globPatterns.append(it.value().type.globPatterns());
return globPatterns;
}
void MimeDatabasePrivate::setGlobPatterns(const QString &typeOrAlias,
const QList<MimeGlobPattern> &globPatterns)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
tit.value().type.setGlobPatterns(globPatterns);
}
QList<QSharedPointer<IMagicMatcher> > MimeDatabasePrivate::magicMatchers() const
{
QList<QSharedPointer<IMagicMatcher> > magicMatchers;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
magicMatchers.append(it.value().type.magicMatchers());
return magicMatchers;
}
void MimeDatabasePrivate::setMagicMatchers(const QString &typeOrAlias,
const QList<QSharedPointer<IMagicMatcher> > &matchers)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
tit.value().type.setMagicMatchers(matchers);
}
QList<MimeType> MimeDatabasePrivate::mimeTypes() const
{
QList<MimeType> mimeTypes;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
mimeTypes.append(it.value().type);
return mimeTypes;
}
void MimeDatabasePrivate::syncUserModifiedMimeTypes()
{
QHash<QString, MimeType> userModified;
const QList<MimeType> &userMimeTypes = readUserModifiedMimeTypes();
foreach (const MimeType &userMimeType, userMimeTypes)
userModified.insert(userMimeType.type(), userMimeType);
TypeMimeTypeMap::iterator end = m_typeMimeTypeMap.end();
QHash<QString, MimeType>::const_iterator userMimeEnd = userModified.end();
for (TypeMimeTypeMap::iterator it = m_typeMimeTypeMap.begin(); it != end; ++it) {
QHash<QString, MimeType>::const_iterator userMimeIt =
userModified.find(it.value().type.type());
if (userMimeIt != userMimeEnd) {
it.value().type.setGlobPatterns(userMimeIt.value().globPatterns());
it.value().type.setMagicRuleMatchers(userMimeIt.value().magicRuleMatchers());
}
}
}
QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes()
{
typedef MagicRuleMatcher::MagicRuleList MagicRuleList;
typedef MagicRuleMatcher::MagicRuleSharedPointer MagicRuleSharedPointer;
QList<MimeType> mimeTypes;
QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
if (file.open(QFile::ReadOnly)) {
MimeType mimeType;
QHash<int, MagicRuleList> rules;
QXmlStreamReader reader(&file);
QXmlStreamAttributes atts;
const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC);
const QString patternAttribute = QLatin1String(patternAttributeC);
const QString matchValueAttribute = QLatin1String(matchValueAttributeC);
const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC);
const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC);
const QString priorityAttribute = QLatin1String(priorityAttributeC);
while (!reader.atEnd()) {
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
atts = reader.attributes();
if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setType(atts.value(mimeTypeAttribute).toString());
const QString &patterns = atts.value(patternAttribute).toString();
mimeType.setGlobPatterns(toGlobPatterns(patterns.split(QLatin1Char(';'))));
} else if (reader.name() == QLatin1String(matchTagC)) {
const QString &value = atts.value(matchValueAttribute).toString();
const QStringRef type = atts.value(matchTypeAttribute);
const QString &offset = atts.value(matchOffsetAttribute).toString();
QPair<int, int> range = MagicRule::fromOffset(offset);
const int priority = atts.value(priorityAttribute).toString().toInt();
MagicRule *magicRule;
if (type == MagicStringRule::kMatchType)
magicRule = new MagicStringRule(value, range.first, range.second);
else
magicRule = new MagicByteRule(value, range.first, range.second);
rules[priority].append(MagicRuleSharedPointer(magicRule));
}
break;
case QXmlStreamReader::EndElement:
if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setMagicRuleMatchers(MagicRuleMatcher::createMatchers(rules));
mimeTypes.append(mimeType);
mimeType.clear();
rules.clear();
}
break;
default:
break;
}
}
if (reader.hasError())
qWarning() << kModifiedMimeTypesFile << reader.errorString() << reader.lineNumber()
<< reader.columnNumber();
file.close();
}
return mimeTypes;
}
void MimeDatabasePrivate::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes)
{
// Keep mime types modified which are already on file, unless they are part of the current set.
QSet<QString> currentMimeTypes;
foreach (const MimeType &mimeType, mimeTypes)
currentMimeTypes.insert(mimeType.type());
const QList<MimeType> &inFileMimeTypes = readUserModifiedMimeTypes();
QList<MimeType> allModifiedMimeTypes = mimeTypes;
foreach (const MimeType &mimeType, inFileMimeTypes)
if (!currentMimeTypes.contains(mimeType.type()))
allModifiedMimeTypes.append(mimeType);
if (QFile::exists(kModifiedMimeTypesPath) || QDir().mkpath(kModifiedMimeTypesPath)) {
QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
if (file.open(QFile::WriteOnly | QFile::Truncate)) {
// Notice this file only represents user modifications. It is writen in a
// convienient way for synchronization, which is similar to but not exactly the
// same format we use for the embedded mime type files.
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement(QLatin1String(mimeInfoTagC));
const QString mimeTypeTag = QLatin1String(mimeTypeTagC);
const QString matchTag = QLatin1String(matchTagC);
const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC);
const QString patternAttribute = QLatin1String(patternAttributeC);
const QString matchValueAttribute = QLatin1String(matchValueAttributeC);
const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC);
const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC);
const QString priorityAttribute = QLatin1String(priorityAttributeC);
foreach (const MimeType &mimeType, allModifiedMimeTypes) {
writer.writeStartElement(mimeTypeTag);
writer.writeAttribute(mimeTypeAttribute, mimeType.type());
writer.writeAttribute(patternAttribute,
fromGlobPatterns(mimeType.globPatterns()).join(QLatin1Char(';')));
const QList<QSharedPointer<IMagicMatcher> > &matchers = mimeType.magicMatchers();
foreach (const QSharedPointer<IMagicMatcher> &matcher, matchers) {
// Only care about rule-based matchers.
if (MagicRuleMatcher *ruleMatcher =
dynamic_cast<MagicRuleMatcher *>(matcher.data())) {
const MagicRuleMatcher::MagicRuleList &rules = ruleMatcher->magicRules();
foreach (const MagicRuleMatcher::MagicRuleSharedPointer &rule, rules) {
writer.writeStartElement(matchTag);
writer.writeAttribute(matchValueAttribute, rule->matchValue());
writer.writeAttribute(matchTypeAttribute, rule->matchType());
writer.writeAttribute(matchOffsetAttribute,
MagicRule::toOffset(
qMakePair(rule->startPos(), rule->endPos())));
writer.writeAttribute(priorityAttribute,
QString::number(ruleMatcher->priority()));
writer.writeEndElement();
}
}
}
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
file.close();
}
}
}
void MimeDatabasePrivate::clearUserModifiedMimeTypes()
{
// This removes the user's file. However, the operation will actually take place the next time
// Creator starts, since we currently don't support removing stuff from the mime database.
QFile::remove(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
}
QList<MimeGlobPattern> MimeDatabasePrivate::toGlobPatterns(const QStringList &patterns, int weight)
{
QList<MimeGlobPattern> globPatterns;
foreach (const QString &pattern, patterns)
globPatterns.append(Core::MimeGlobPattern(pattern, weight));
return globPatterns;
}
QStringList MimeDatabasePrivate::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns)
{
QStringList patterns;
foreach (const MimeGlobPattern &globPattern, globPatterns)
patterns.append(globPattern.pattern());
return patterns;
}
void MimeDatabasePrivate::debug(QTextStream &str) const
{
str << ">MimeDatabase\n";
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
str << "Entry level " << it.value().level << '\n';
it.value().type.m_d->debug(str);
}
str << "<MimeDatabase\n";
}
static MimeDatabasePrivate *d;
MimeDatabase::MimeDatabase()
{
d = new MimeDatabasePrivate;
}
MimeDatabase::~MimeDatabase()
{
delete d;
}
MimeType MimeDatabase::findByType(const QString &typeOrAlias)
{
d->m_mutex.lock();
const MimeType rc = d->findByType(typeOrAlias);
d->m_mutex.unlock();
return rc;
}
MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f)
{
return d->findByFile(f);
}
MimeType MimeDatabase::findByFile(const QFileInfo &f)
{
d->m_mutex.lock();
const MimeType rc = findByFileUnlocked(f);
d->m_mutex.unlock();
return rc;
}
MimeType MimeDatabase::findByData(const QByteArray &data)
{
d->m_mutex.lock();
const MimeType rc = d->findByData(data);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeType(const MimeType &mt)
{
d->m_mutex.lock();
const bool rc = d->addMimeType(mt);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(const QString &fileName, QString *errorMessage)
{
d->m_mutex.lock();
const bool rc = d->addMimeTypes(fileName, errorMessage);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(QIODevice *device, QString *errorMessage)
{
d->m_mutex.lock();
const bool rc = d->addMimeTypes(device, errorMessage);
d->m_mutex.unlock();
return rc;
}
QStringList MimeDatabase::suffixes()
{
d->m_mutex.lock();
const QStringList rc = d->suffixes();
d->m_mutex.unlock();
return rc;
}
QStringList MimeDatabase::filterStrings()
{
d->m_mutex.lock();
const QStringList rc = d->filterStrings();
d->m_mutex.unlock();
return rc;
}
QString MimeDatabase::allFiltersString(QString *allFilesFilter)
{
if (allFilesFilter)
allFilesFilter->clear();
// Compile list of filter strings, sort, and remove duplicates (different mime types might
// generate the same filter).
QStringList filters = filterStrings();
if (filters.empty())
return QString();
filters.sort();
filters.erase(std::unique(filters.begin(), filters.end()), filters.end());
static const QString allFiles =
QCoreApplication::translate("Core", Constants::ALL_FILES_FILTER);
if (allFilesFilter)
*allFilesFilter = allFiles;
// Prepend all files filter (instead of appending to work around a bug in Qt/Mac).
filters.prepend(allFiles);
return filters.join(QLatin1String(";;"));
}
QList<MimeGlobPattern> MimeDatabase::globPatterns()
{
d->m_mutex.lock();
const QList<MimeGlobPattern> rc = d->globPatterns();
d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setGlobPatterns(const QString &typeOrAlias,
const QList<MimeGlobPattern> &globPatterns)
{
d->m_mutex.lock();
d->setGlobPatterns(typeOrAlias, globPatterns);
d->m_mutex.unlock();
}
MimeDatabase::IMagicMatcherList MimeDatabase::magicMatchers()
{
d->m_mutex.lock();
const IMagicMatcherList rc = d->magicMatchers();
d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setMagicMatchers(const QString &typeOrAlias,
const IMagicMatcherList &matchers)
{
d->m_mutex.lock();
d->setMagicMatchers(typeOrAlias, matchers);
d->m_mutex.unlock();
}
QList<MimeType> MimeDatabase::mimeTypes()
{
d->m_mutex.lock();
const QList<MimeType> &mimeTypes = d->mimeTypes();
d->m_mutex.unlock();
return mimeTypes;
}
void MimeDatabase::syncUserModifiedMimeTypes()
{
d->m_mutex.lock();
d->syncUserModifiedMimeTypes();
d->m_mutex.unlock();
}
void MimeDatabase::clearUserModifiedMimeTypes()
{
d->m_mutex.lock();
d->clearUserModifiedMimeTypes();
d->m_mutex.unlock();
}
QList<MimeType> MimeDatabase::readUserModifiedMimeTypes()
{
return MimeDatabasePrivate::readUserModifiedMimeTypes();
}
void MimeDatabase::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes)
{
MimeDatabasePrivate::writeUserModifiedMimeTypes(mimeTypes);
}
QString MimeDatabase::preferredSuffixByType(const QString &type)
{
if (const MimeType mt = findByType(type))
return mt.preferredSuffix(); // already does Mutex locking
return QString();
}
QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f)
{
if (const MimeType mt = findByFile(f))
return mt.preferredSuffix(); // already does Mutex locking
return QString();
}
bool MimeDatabase::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
d->m_mutex.lock();
const bool rc = d->setPreferredSuffix(typeOrAlias, suffix);
d->m_mutex.unlock();
return rc;
}
QList<MimeGlobPattern> MimeDatabase::toGlobPatterns(const QStringList &patterns, int weight)
{
return MimeDatabasePrivate::toGlobPatterns(patterns, weight);
}
QStringList MimeDatabase::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns)
{
return MimeDatabasePrivate::fromGlobPatterns(globPatterns);
}
//QDebug operator<<(QDebug d, const MimeDatabase &mt)
//{
// QString s;
// {
// QTextStream str(&s);
// d->debug(str);
// }
// db << s;
// return db;
//}
} // namespace Core
Allow multiple '.' for a suffix in MimeTypeData
(e.g. ".ui.qml")
Change-Id: I476585649f02651eeb99564417ec46de6346c67d
Reviewed-by: Tobias Hunger <012f8d714267bccc9d4766fbeace9f175fcc70c4@theqtcompany.com>
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "mimedatabase.h"
#include "coreconstants.h"
#include "icore.h"
#include <utils/qtcassert.h>
#include <utils/algorithm.h>
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QLocale>
#include <QHash>
#include <QMultiHash>
#include <QRegExp>
#include <QSharedData>
#include <QSharedPointer>
#include <QStringList>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <functional>
enum { debugMimeDB = 0 };
// XML tags in mime files
static const char mimeInfoTagC[] = "mime-info";
static const char mimeTypeTagC[] = "mime-type";
static const char mimeTypeAttributeC[] = "type";
static const char subClassTagC[] = "sub-class-of";
static const char commentTagC[] = "comment";
static const char globTagC[] = "glob";
static const char aliasTagC[] = "alias";
static const char patternAttributeC[] = "pattern";
static const char weightAttributeC[] = "weight";
static const char localeAttributeC[] = "xml:lang";
static const char magicTagC[] = "magic";
static const char priorityAttributeC[] = "priority";
static const char matchTagC[] = "match";
static const char matchValueAttributeC[] = "value";
static const char matchTypeAttributeC[] = "type";
static const char matchStringTypeValueC[] = "string";
static const char matchByteTypeValueC[] = "byte";
static const char matchOffsetAttributeC[] = "offset";
// Types
static const char textTypeC[] = "text/plain";
static const char binaryTypeC[] = "application/octet-stream";
// UTF16 byte order marks
static const char bigEndianByteOrderMarkC[] = "\xFE\xFF";
static const char littleEndianByteOrderMarkC[] = "\xFF\xFE";
// Fallback priorities, must be low.
enum {
BinaryMatchPriority = Core::MimeGlobPattern::MinWeight + 1,
TextMatchPriority
};
/*!
\class Core::IMagicMatcher
\brief The IMagicMatcher class is an interface for a MIME type magic
matcher that examines file contents to determine the MIME type of a file.
\sa Core::MimeType, Core::MimeDatabase, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
namespace Core {
typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr;
namespace Internal {
/*!
\class Core::Internal::FileMatchContext
\brief The FileMatchContext class is the context passed on to the MIME
types when looking for a file match.
This class exists to enable reading the file contents \e {on demand},
as opposed to each mime type trying to open and read while checking.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class FileMatchContext
{
Q_DISABLE_COPY(FileMatchContext)
public:
// Max data to be read from a file
enum { MaxData = 2048 };
explicit FileMatchContext(const QFileInfo &fi);
inline QString fileName() const { return m_fileName; }
// Return (cached) first MaxData bytes of file
QByteArray data();
private:
enum State {
// File cannot be read/does not exist
NoDataAvailable,
// Not read yet
DataNotRead,
// Available
DataRead };
const QFileInfo m_fileInfo;
const QString m_fileName;
State m_state;
QByteArray m_data;
};
FileMatchContext::FileMatchContext(const QFileInfo &fi) :
m_fileInfo(fi),
m_fileName(fi.fileName()),
m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable)
{
}
QByteArray FileMatchContext::data()
{
// Do we need to read?
if (m_state == DataNotRead) {
const QString fullName = m_fileInfo.absoluteFilePath();
QFile file(fullName);
if (file.open(QIODevice::ReadOnly)) {
m_data = file.read(MaxData);
m_state = DataRead;
} else {
qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData());
m_state = NoDataAvailable;
}
}
return m_data;
}
/*!
\class Core::Internal::BinaryMatcher
\brief The BinaryMatcher class is the binary fallback matcher for the MIME
type \c{application/octet-stream}.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class BinaryMatcher : public IMagicMatcher
{
public:
BinaryMatcher() {}
virtual bool matches(const QByteArray & /*data*/) const { return true; }
virtual int priority() const { return BinaryMatchPriority; }
};
/*!
\class Core::Internal::HeuristicTextMagicMatcher
\brief The HeuristicTextMagicMatcher class implements a heuristic text file
matcher for MIME types.
If the data does not contain any character below tab (9), it is detected as
text. Additionally, UTF16 byte order markers are checked.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class HeuristicTextMagicMatcher : public IMagicMatcher
{
public:
HeuristicTextMagicMatcher() {}
virtual bool matches(const QByteArray &data) const;
virtual int priority() const { return TextMatchPriority; }
static bool isTextFile(const QByteArray &data);
};
bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data)
{
const int size = data.size();
for (int i = 0; i < size; i++) {
const char c = data.at(i);
if (c >= 0x01 && c < 0x09) // Sure-fire binary
return false;
if (c == 0) // Check for UTF16
return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC);
}
return true;
}
bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const
{
const bool rc = isTextFile(data);
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc;
return rc;
}
} // namespace Internal
/*!
\class Core::MagicRule
\brief The MagicRule class is a base class for standard Magic matching rules
based on contents
and offset specification.
Stores the offset and provides conversion helpers.
Base class for implementations for \c string and \c byte.
Others, such as \c little16 and \c big16, can be created when needed.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QChar MagicRule::kColon(QLatin1Char(':'));
MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos)
{
}
MagicRule::~MagicRule()
{
}
int MagicRule::startPos() const
{
return m_startPos;
}
int MagicRule::endPos() const
{
return m_endPos;
}
QString MagicRule::toOffset(const QPair<int, int> &startEnd)
{
return QString::fromLatin1("%1:%2").arg(startEnd.first).arg(startEnd.second);
}
QPair<int, int> MagicRule::fromOffset(const QString &offset)
{
const QStringList &startEnd = offset.split(kColon);
Q_ASSERT(startEnd.size() == 2);
return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt());
}
/*!
\class Core::MagicStringRule
\brief The MagicStringRule class provides rules for matching strings.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QString MagicStringRule::kMatchType(QLatin1String("string"));
MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) :
MagicRule(startPos, endPos), m_pattern(s.toUtf8())
{
}
MagicStringRule::~MagicStringRule()
{
}
QString MagicStringRule::matchType() const
{
return kMatchType;
}
QString MagicStringRule::matchValue() const
{
return QLatin1String(m_pattern);
}
bool MagicStringRule::matches(const QByteArray &data) const
{
// Quick check
if ((startPos() + m_pattern.size()) > data.size())
return false;
// Most common: some string at position 0:
if (startPos() == 0 && startPos() == endPos())
return data.startsWith(m_pattern);
// Range
const int index = data.indexOf(m_pattern, startPos());
const bool rc = index != -1 && index <= endPos();
if (debugMimeDB)
qDebug() << "Checking " << m_pattern << startPos() << endPos() << " returns " << rc;
return rc;
}
/*!
\class Core::MagicByteRule
\brief The MagicByteRule class provides rules for matching a sequence of
binary data.
Format:
\code
\0x7f\0x45\0x4c\0x46
\endcode
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
const QString MagicByteRule::kMatchType(QLatin1String("byte"));
MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) :
MagicRule(startPos, endPos), m_bytesSize(0)
{
if (validateByteSequence(s, &m_bytes))
m_bytesSize = m_bytes.size();
else
m_bytes.clear();
}
MagicByteRule::~MagicByteRule()
{
}
bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes)
{
// Expect an hex format value like this: \0x7f\0x45\0x4c\0x46
const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts);
foreach (const QString &byte, byteSequence) {
bool ok;
const int hex = byte.toInt(&ok, 16);
if (ok) {
if (bytes)
bytes->push_back(hex);
} else {
return false;
}
}
return true;
}
QString MagicByteRule::matchType() const
{
return kMatchType;
}
QString MagicByteRule::matchValue() const
{
QString value;
foreach (int byte, m_bytes)
value.append(QString::fromLatin1("\\0x%1").arg(byte, 0, 16));
return value;
}
bool MagicByteRule::matches(const QByteArray &data) const
{
if (m_bytesSize == 0)
return false;
const int dataSize = data.size();
for (int start = startPos(); start <= endPos(); ++start) {
if ((start + m_bytesSize) > dataSize)
return false;
int matchAt = 0;
while (matchAt < m_bytesSize) {
if (data.at(start + matchAt) != m_bytes.at(matchAt))
break;
++matchAt;
}
if (matchAt == m_bytesSize)
return true;
}
return false;
}
/*!
\class Core::MagicRuleMatcher
\brief The MagicRuleMatcher class implements a Magic matcher that checks the
number of rules based on the boolean operator OR.
This class is used for rules parsed from XML files.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
MagicRuleMatcher::MagicRuleMatcher() :
m_priority(65535)
{
}
void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule)
{
m_list.append(rule);
}
void MagicRuleMatcher::add(const MagicRuleList &ruleList)
{
m_list.append(ruleList);
}
MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const
{
return m_list;
}
bool MagicRuleMatcher::matches(const QByteArray &data) const
{
const MagicRuleList::const_iterator cend = m_list.constEnd();
for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it)
if ( (*it)->matches(data))
return true;
return false;
}
int MagicRuleMatcher::priority() const
{
return m_priority;
}
void MagicRuleMatcher::setPriority(int p)
{
m_priority = p;
}
IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers(
const QHash<int, MagicRuleList> &rulesByPriority)
{
IMagicMatcher::IMagicMatcherList matchers;
QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin();
for (; ruleIt != rulesByPriority.end(); ++ruleIt) {
MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher();
magicRuleMatcher->setPriority(ruleIt.key());
magicRuleMatcher->add(ruleIt.value());
matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher));
}
return matchers;
}
/*!
\class Core::GlobPattern
\brief The GlobPattern class provides a glob pattern for file names for
MIME type matching.
\sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
MimeGlobPattern::MimeGlobPattern(const QString &pattern, unsigned weight) :
m_pattern(pattern), m_weight(weight)
{
bool hasQuestionMark = pattern.contains(QLatin1Char('?'));
bool hasStar = pattern.contains(QLatin1Char('*'));
if (!hasQuestionMark && hasStar && pattern.lastIndexOf(QLatin1Char('*')) == 0) {
m_type = Suffix;
} else if (!hasQuestionMark && !hasStar) {
m_type = Exact;
} else {
// This hopefully never happens as it is expensive.
m_type = Glob;
m_regexp.setPattern(pattern);
m_regexp.setPatternSyntax(QRegExp::Wildcard);
if (!m_regexp.isValid())
qWarning("%s: Invalid wildcard '%s'.", Q_FUNC_INFO, pattern.toUtf8().constData());
}
}
MimeGlobPattern::~MimeGlobPattern()
{
}
bool MimeGlobPattern::matches(const QString &fileName) const
{
if (m_type == Exact)
return fileName == m_pattern;
if (m_type == Suffix)
return fileName.endsWith(m_pattern.midRef(1));
return m_regexp.exactMatch(fileName);
}
/*!
\class Core::MimeType
\brief The MimeType class contains MIME type data used in \QC.
Contains most information from standard MIME type XML database files.
Currently, magic of types \c string anc \c bytes is supported. In addition,
C++ classes, derived from \c Core::IMagicMatcher can be added to check
on contents.
The class provides a list of suffixes and a concept of a
\e {preferred suffix} (derived from glob patterns). This is used for example
to be able to configure the suffix used for C++ files in \QC.
MIME type XML files look like follows:
\code
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<!-- Mime types must match the desktop file associations -->
<mime-type type="application/vnd.qt.qmakeprofile">
<comment xml:lang="en">Qt qmake Profile</comment>
<glob pattern="*.pro" weight="50"/>
</mime-type>
</mime-info>
\endcode
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class MimeTypeData : public QSharedData {
public:
typedef QHash<QString,QString> LocaleHash;
MimeTypeData();
void clear();
void assignSuffix(const QString &pattern);
void assignSuffixes(const QStringList &patterns);
void debug(QTextStream &str, int indent = 0) const;
QRegExp suffixPattern;
QString type;
QString comment;
LocaleHash localeComments;
QStringList aliases;
QList<MimeGlobPattern> globPatterns;
QStringList subClassesOf;
QString preferredSuffix;
QStringList suffixes;
IMagicMatcher::IMagicMatcherList magicMatchers;
};
MimeTypeData::MimeTypeData()
// RE to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or
// "*.log[1-9]"
: suffixPattern(QLatin1String("^\\*(?:\\.[\\w+]+)+$"))
{
QTC_CHECK(suffixPattern.isValid());
}
void MimeTypeData::clear()
{
type.clear();
comment.clear();
aliases.clear();
globPatterns.clear();
subClassesOf.clear();
preferredSuffix.clear();
suffixes.clear();
magicMatchers.clear();
}
void MimeTypeData::assignSuffix(const QString &pattern)
{
if (suffixPattern.exactMatch(pattern)) {
const QString suffix = pattern.right(pattern.size() - 2);
suffixes.push_back(suffix);
if (preferredSuffix.isEmpty())
preferredSuffix = suffix;
}
}
void MimeTypeData::assignSuffixes(const QStringList &patterns)
{
foreach (const QString &pattern, patterns)
assignSuffix(pattern);
}
void MimeTypeData::debug(QTextStream &str, int indent) const
{
const QString indentS = QString(indent, QLatin1Char(' '));
const QLatin1Char comma(',');
str << indentS << "Type: " << type;
if (!aliases.empty())
str << " Aliases: " << aliases.join(comma);
str << ", magic: " << magicMatchers.size() << '\n';
str << indentS << "Comment: " << comment << '\n';
if (!subClassesOf.empty())
str << indentS << "SubClassesOf: " << subClassesOf.join(comma) << '\n';
if (!globPatterns.empty()) {
str << indentS << "Glob: ";
foreach (const MimeGlobPattern &gp, globPatterns)
str << gp.pattern() << '(' << gp.weight() << ')';
str << '\n';
if (!suffixes.empty()) {
str << indentS << "Suffixes: " << suffixes.join(comma)
<< " preferred: " << preferredSuffix << '\n';
}
}
str << '\n';
}
// ---------------- MimeType
MimeType::MimeType() :
m_d(new MimeTypeData)
{
}
MimeType::MimeType(const MimeType &rhs) :
m_d(rhs.m_d)
{
}
MimeType &MimeType::operator=(const MimeType &rhs)
{
if (this != &rhs)
m_d = rhs.m_d;
return *this;
}
MimeType::MimeType(const MimeTypeData &d) :
m_d(new MimeTypeData(d))
{
}
MimeType::~MimeType()
{
}
void MimeType::clear()
{
m_d->clear();
}
bool MimeType::isNull() const
{
return m_d->type.isEmpty();
}
MimeType::operator bool() const
{
return !isNull();
}
bool MimeType::isTopLevel() const
{
return m_d->subClassesOf.empty();
}
QString MimeType::type() const
{
return m_d->type;
}
void MimeType::setType(const QString &type)
{
m_d->type = type;
}
QString MimeType::comment() const
{
return m_d->comment;
}
void MimeType::setComment(const QString &comment)
{
m_d->comment = comment;
}
// Return "en", "de", etc. derived from "en_US", de_DE".
static inline QString systemLanguage()
{
QString name = QLocale::system().name();
const int underScorePos = name.indexOf(QLatin1Char('_'));
if (underScorePos != -1)
name.truncate(underScorePos);
return name;
}
QString MimeType::localeComment(const QString &localeArg) const
{
const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg;
const MimeTypeData::LocaleHash::const_iterator it = m_d->localeComments.constFind(locale);
if (it == m_d->localeComments.constEnd())
return m_d->comment;
return it.value();
}
void MimeType::setLocaleComment(const QString &locale, const QString &comment)
{
m_d->localeComments[locale] = comment;
}
QStringList MimeType::aliases() const
{
return m_d->aliases;
}
void MimeType::setAliases(const QStringList &a)
{
m_d->aliases = a;
}
QList<MimeGlobPattern> MimeType::globPatterns() const
{
return m_d->globPatterns;
}
void MimeType::setGlobPatterns(const QList<MimeGlobPattern> &g)
{
m_d->globPatterns = g;
QString oldPrefferedSuffix = m_d->preferredSuffix;
m_d->suffixes.clear();
m_d->preferredSuffix.clear();
m_d->assignSuffixes(MimeDatabase::fromGlobPatterns(g));
if (m_d->preferredSuffix != oldPrefferedSuffix && m_d->suffixes.contains(oldPrefferedSuffix))
m_d->preferredSuffix = oldPrefferedSuffix;
}
QStringList MimeType::subClassesOf() const
{
return m_d->subClassesOf;
}
void MimeType::setSubClassesOf(const QStringList &s)
{
m_d->subClassesOf = s;
}
QString MimeType::preferredSuffix() const
{
return m_d->preferredSuffix;
}
bool MimeType::setPreferredSuffix(const QString &s)
{
if (!m_d->suffixes.contains(s)) {
qWarning("%s: Attempt to set preferred suffix to '%s', which is not in the list of suffixes: %s.",
m_d->type.toUtf8().constData(),
s.toUtf8().constData(),
m_d->suffixes.join(QLatin1Char(',')).toUtf8().constData());
return false;
}
m_d->preferredSuffix = s;
return true;
}
QString MimeType::formatFilterString(const QString &description, const QList<MimeGlobPattern> &globs)
{
QString rc;
if (globs.empty()) // Binary files
return rc;
{
QTextStream str(&rc);
str << description;
if (!globs.empty()) {
str << " (";
const int size = globs.size();
for (int i = 0; i < size; i++) {
if (i)
str << ' ';
str << globs.at(i).pattern();
}
str << ')';
}
}
return rc;
}
QString MimeType::filterString() const
{
// @todo: Use localeComment() once creator is shipped with translations
return formatFilterString(comment(), m_d->globPatterns);
}
bool MimeType::matchesType(const QString &type) const
{
return m_d->type == type || m_d->aliases.contains(type);
}
unsigned MimeType::matchesFile(const QFileInfo &file) const
{
Internal::FileMatchContext context(file);
const unsigned suffixPriority = matchesFileBySuffix(context);
if (suffixPriority >= MimeGlobPattern::MaxWeight)
return suffixPriority;
return qMax(suffixPriority, matchesFileByContent(context));
}
unsigned MimeType::matchesFileBySuffix(Internal::FileMatchContext &c) const
{
// check globs
foreach (const MimeGlobPattern &gp, m_d->globPatterns) {
if (gp.matches(c.fileName()))
return gp.weight();
}
return 0;
}
unsigned MimeType::matchesFileByContent(Internal::FileMatchContext &c) const
{
// Nope, try magic matchers on context data
if (m_d->magicMatchers.isEmpty())
return 0;
return matchesData(c.data());
}
unsigned MimeType::matchesData(const QByteArray &data) const
{
unsigned priority = 0;
if (!data.isEmpty()) {
foreach (const IMagicMatcher::IMagicMatcherSharedPointer &matcher, m_d->magicMatchers) {
const unsigned magicPriority = matcher->priority();
if (magicPriority > priority && matcher->matches(data))
priority = magicPriority;
}
}
return priority;
}
QStringList MimeType::suffixes() const
{
return m_d->suffixes;
}
void MimeType::addMagicMatcher(const IMagicMatcherSharedPointer &matcher)
{
m_d->magicMatchers.push_back(matcher);
}
const MimeType::IMagicMatcherList &MimeType::magicMatchers() const
{
return m_d->magicMatchers;
}
void MimeType::setMagicMatchers(const IMagicMatcherList &matchers)
{
m_d->magicMatchers = matchers;
}
namespace {
struct RemovePred : std::unary_function<MimeType::IMagicMatcherSharedPointer, bool>
{
RemovePred(bool keepRuleBased) : m_keepRuleBase(keepRuleBased) {}
bool m_keepRuleBase;
bool operator()(const MimeType::IMagicMatcherSharedPointer &matcher) {
if ((m_keepRuleBase && !dynamic_cast<MagicRuleMatcher *>(matcher.data()))
|| (!m_keepRuleBase && dynamic_cast<MagicRuleMatcher *>(matcher.data())))
return true;
return false;
}
};
} // Anonymous
MimeType::IMagicMatcherList MimeType::magicRuleMatchers() const
{
IMagicMatcherList ruleMatchers = m_d->magicMatchers;
Utils::erase(ruleMatchers, RemovePred(true));
return ruleMatchers;
}
void MimeType::setMagicRuleMatchers(const IMagicMatcherList &matchers)
{
Utils::erase(m_d->magicMatchers, RemovePred(false));
m_d->magicMatchers.append(matchers);
}
QDebug operator<<(QDebug d, const MimeType &mt)
{
QString s;
{
QTextStream str(&s);
mt.m_d->debug(str);
}
d << s;
return d;
}
namespace Internal {
/*!
\class Core::Internal::BaseMimeTypeParser
\brief The BaseMimeTypeParser class provides a generic parser for a
sequence of <mime-type>.
This class calls the abstract handler function process for the MIME types
it finds.
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::MimeTypeParser
*/
class BaseMimeTypeParser
{
Q_DISABLE_COPY(BaseMimeTypeParser)
public:
BaseMimeTypeParser() {}
virtual ~BaseMimeTypeParser() {}
bool parse(QIODevice *dev, const QString &fileName, QString *errorMessage);
private:
// Overwrite to process the sequence of parsed data
virtual bool process(const MimeType &t, QString *errorMessage) = 0;
void addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const;
enum ParseStage { ParseBeginning,
ParseMimeInfo,
ParseMimeType,
ParseComment,
ParseGlobPattern,
ParseSubClass,
ParseAlias,
ParseMagic,
ParseMagicMatchRule,
ParseOtherMimeTypeSubTag,
ParseError };
static ParseStage nextStage(ParseStage currentStage, const QStringRef &startElement);
};
void BaseMimeTypeParser::addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const
{
if (pattern.isEmpty())
return;
// Collect patterns as a QRegExp list and filter out the plain
// suffix ones for our suffix list. Use first one as preferred
if (weight.isEmpty())
d->globPatterns.push_back(MimeGlobPattern(pattern));
else
d->globPatterns.push_back(MimeGlobPattern(pattern, weight.toInt()));
d->assignSuffix(pattern);
}
BaseMimeTypeParser::ParseStage BaseMimeTypeParser::nextStage(ParseStage currentStage, const QStringRef &startElement)
{
switch (currentStage) {
case ParseBeginning:
if (startElement == QLatin1String(mimeInfoTagC))
return ParseMimeInfo;
if (startElement == QLatin1String(mimeTypeTagC))
return ParseMimeType;
return ParseError;
case ParseMimeInfo:
return startElement == QLatin1String(mimeTypeTagC) ? ParseMimeType : ParseError;
case ParseMimeType:
case ParseComment:
case ParseGlobPattern:
case ParseSubClass:
case ParseAlias:
case ParseOtherMimeTypeSubTag:
case ParseMagicMatchRule:
if (startElement == QLatin1String(mimeTypeTagC)) // Sequence of <mime-type>
return ParseMimeType;
if (startElement == QLatin1String(commentTagC ))
return ParseComment;
if (startElement == QLatin1String(globTagC))
return ParseGlobPattern;
if (startElement == QLatin1String(subClassTagC))
return ParseSubClass;
if (startElement == QLatin1String(aliasTagC))
return ParseAlias;
if (startElement == QLatin1String(magicTagC))
return ParseMagic;
if (startElement == QLatin1String(matchTagC))
return ParseMagicMatchRule;
return ParseOtherMimeTypeSubTag;
case ParseMagic:
if (startElement == QLatin1String(matchTagC))
return ParseMagicMatchRule;
break;
case ParseError:
break;
}
return ParseError;
}
// Parse int number from an (attribute) string)
static bool parseNumber(const QString &n, int *target, QString *errorMessage)
{
bool ok;
*target = n.toInt(&ok);
if (!ok) {
*errorMessage = QString::fromLatin1("Not a number \"%1\".").arg(n);
return false;
}
return true;
}
// Evaluate a magic match rule like
// <match value="must be converted with BinHex" type="string" offset="11"/>
// <match value="0x9501" type="big16" offset="0:64"/>
static bool addMagicMatchRule(const QXmlStreamAttributes &atts,
const MagicRuleMatcherPtr &ruleMatcher,
QString *errorMessage)
{
const QStringRef type = atts.value(QLatin1String(matchTypeAttributeC));
if (type != QLatin1String(matchStringTypeValueC) &&
type != QLatin1String(matchByteTypeValueC)) {
qWarning("%s: match type %s is not supported.", Q_FUNC_INFO, type.toUtf8().constData());
return true;
}
const QString value = atts.value(QLatin1String(matchValueAttributeC)).toString();
if (value.isEmpty()) {
*errorMessage = QString::fromLatin1("Empty match value detected.");
return false;
}
// Parse for offset as "1" or "1:10"
int startPos, endPos;
const QString offsetS = atts.value(QLatin1String(matchOffsetAttributeC)).toString();
const int colonIndex = offsetS.indexOf(QLatin1Char(':'));
const QString startPosS = colonIndex == -1 ? offsetS : offsetS.mid(0, colonIndex);
const QString endPosS = colonIndex == -1 ? offsetS : offsetS.mid(colonIndex + 1);
if (!parseNumber(startPosS, &startPos, errorMessage) || !parseNumber(endPosS, &endPos, errorMessage))
return false;
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << value << startPos << endPos;
if (type == QLatin1String(matchStringTypeValueC))
ruleMatcher->add(QSharedPointer<MagicRule>(new MagicStringRule(value, startPos, endPos)));
else
ruleMatcher->add(QSharedPointer<MagicRule>(new MagicByteRule(value, startPos, endPos)));
return true;
}
bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
MimeTypeData data;
MagicRuleMatcherPtr ruleMatcher;
QXmlStreamReader reader(dev);
ParseStage ps = ParseBeginning;
QXmlStreamAttributes atts;
while (!reader.atEnd()) {
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
ps = nextStage(ps, reader.name());
atts = reader.attributes();
switch (ps) {
case ParseMimeType: { // start parsing a type
const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (type.isEmpty())
reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
else
data.type = type;
}
break;
case ParseGlobPattern:
addGlobPattern(atts.value(QLatin1String(patternAttributeC)).toString(),
atts.value(QLatin1String(weightAttributeC)).toString(), &data);
break;
case ParseSubClass: {
const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (!inheritsFrom.isEmpty())
data.subClassesOf.push_back(inheritsFrom);
}
break;
case ParseComment: {
// comments have locale attributes. We want the default, English one
const QStringRef locale = atts.value(QLatin1String(localeAttributeC));
const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
if (locale.isEmpty())
data.comment = comment;
else
data.localeComments.insert(locale.toString(), comment);
}
break;
case ParseAlias: {
const QStringRef alias = atts.value(QLatin1String(mimeTypeAttributeC));
if (!alias.isEmpty())
data.aliases.push_back(alias.toString());
}
break;
case ParseMagic: {
int priority = 0;
const QStringRef priorityS = atts.value(QLatin1String(priorityAttributeC));
if (!priorityS.isEmpty()) {
if (!parseNumber(priorityS.toString(), &priority, errorMessage))
return false;
}
ruleMatcher = MagicRuleMatcherPtr(new MagicRuleMatcher);
ruleMatcher->setPriority(priority);
}
break;
case ParseMagicMatchRule:
QTC_ASSERT(!ruleMatcher.isNull(), return false);
if (!addMagicMatchRule(atts, ruleMatcher, errorMessage))
return false;
break;
case ParseError:
reader.raiseError(QString::fromLatin1("Unexpected element <%1>").arg(reader.name().toString()));
break;
default:
break;
} // switch nextStage
break;
// continue switch QXmlStreamReader::Token...
case QXmlStreamReader::EndElement: // Finished element
if (reader.name() == QLatin1String(mimeTypeTagC)) {
if (!process(MimeType(data), errorMessage))
return false;
data.clear();
} else {
// Finished a match sequence
if (reader.name() == QLatin1String(magicTagC)) {
QTC_ASSERT(!ruleMatcher.isNull(), return false);
data.magicMatchers.push_back(ruleMatcher);
ruleMatcher = MagicRuleMatcherPtr();
}
}
break;
default:
break;
} // switch reader.readNext()
}
if (reader.hasError()) {
*errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString());
return false;
}
return true;
}
} // namespace Internal
// MimeMapEntry: Entry of a type map, consisting of type and level.
enum { Dangling = 32767 };
struct MimeMapEntry
{
explicit MimeMapEntry(const MimeType &t = MimeType(), int aLevel = Dangling);
MimeType type;
int level; // hierachy level
};
MimeMapEntry::MimeMapEntry(const MimeType &t, int aLevel) :
type(t),
level(aLevel)
{
}
/*!
\class Core::MimeDatabase
\brief The MimeDatabase class is a MIME type database to which the plugins
can add the MIME types they handle.
The class is protected by a QMutex and can therefore be accessed by threads.
A good testcase is to run it over \c {/usr/share/mime/<*>/<*>.xml} on Linux.
When adding a \c{text/plain} to it, the MIME type will receive a magic matcher
that checks for text files that do not match the globs by heuristics.
\section1 Design Considerations
Storage requirements:
\list
\li Must be robust in case of incomplete hierarchies and dangling entries.
\li Plugins will not load and register their MIME types in order of
inheritance.
\li Multiple inheritance (several subClassesOf) can occur.
\li Provide quick lookup by name.
\li Provide quick lookup by file type.
\endlist
This basically rules out a pointer-based tree, so the structure chosen is:
\list
\li An alias map \c {QString->QString} for mapping aliases to types.
\li A map \c {QString->MimeMapEntry} for the types (MimeMapEntry being a pair of
MimeType and (hierarchy) level.
\li A map \c {QString->QString} representing parent to child relations (enabling
recursing over children).
\li Using strings avoids dangling pointers.
\endlist
The hierarchy level is used for mapping by file types. When \c findByFile()
is first called after \c addMimeType(), it recurses over the hierarchy and sets
the hierarchy level of the entries accordingly (0 toplevel, 1 first
order...). It then does several passes over the type map, checking the
globs for maxLevel, maxLevel-1....until it finds a match (the idea being
to check the most specific types first). Starting a recursion from the
leaves is not suitable since it will hit parent nodes several times.
\sa Core::MimeType, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
class MimeDatabasePrivate
{
Q_DISABLE_COPY(MimeDatabasePrivate)
public:
MimeDatabasePrivate();
bool addMimeTypes(const QString &fileName, QString *errorMessage);
bool addMimeTypes(QIODevice *device, QString *errorMessage);
bool addMimeType(MimeType mt);
MimeType findByType(const QString &type) const;
MimeType findByFile(const QFileInfo &f) const;
MimeType findByData(const QByteArray &data) const;
QStringList filterStrings() const;
QStringList suffixes() const;
bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);
QList<MimeGlobPattern> globPatterns() const;
void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns);
QList<QSharedPointer<IMagicMatcher> > magicMatchers() const;
void setMagicMatchers(const QString &typeOrAlias,
const QList<QSharedPointer<IMagicMatcher> > &matchers);
QList<MimeType> mimeTypes() const;
void syncUserModifiedMimeTypes();
static QList<MimeType> readUserModifiedMimeTypes();
static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes);
void clearUserModifiedMimeTypes();
static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns,
int weight = MimeGlobPattern::MaxWeight);
static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns);
void debug(QTextStream &str) const;
typedef QHash<QString, MimeMapEntry> TypeMimeTypeMap;
typedef QHash<QString, QString> AliasMap;
typedef QMultiHash<QString, QString> ParentChildrenMap;
static const QString kModifiedMimeTypesFile;
static QString kModifiedMimeTypesPath;
bool addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage);
inline const QString &resolveAlias(const QString &name) const;
MimeType findByFile(const QFileInfo &f, unsigned *priority) const;
MimeType findByData(const QByteArray &data, unsigned *priority) const;
void determineLevels();
void raiseLevelRecursion(MimeMapEntry &e, int level);
TypeMimeTypeMap m_typeMimeTypeMap;
AliasMap m_aliasMap;
ParentChildrenMap m_parentChildrenMap;
int m_maxLevel;
QMutex m_mutex;
};
const QString MimeDatabasePrivate::kModifiedMimeTypesFile(QLatin1String("modifiedmimetypes.xml"));
QString MimeDatabasePrivate::kModifiedMimeTypesPath;
MimeDatabasePrivate::MimeDatabasePrivate() :
m_maxLevel(-1)
{
// Assign here to avoid non-local static data initialization issues.
kModifiedMimeTypesPath = ICore::userResourcePath() + QLatin1String("/mimetypes/");
}
/*!
\class Core::Internal::MimeTypeParser
\brief The MimeTypeParser class provides a MIME type parser.
Populates Core::MimeDataBase
\sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
\sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
\sa Core::Internal::MimeTypeParser
*/
namespace Internal {
// Parser that builds MimeDB hierarchy by adding to MimeDatabasePrivate
class MimeTypeParser : public BaseMimeTypeParser {
public:
explicit MimeTypeParser(MimeDatabasePrivate &db) : m_db(db) {}
private:
virtual bool process(const MimeType &t, QString *) { m_db.addMimeType(t); return true; }
MimeDatabasePrivate &m_db;
};
} // namespace Internal
bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage)
{
Internal::MimeTypeParser parser(*this);
return parser.parse(device, fileName, errorMessage);
}
bool MimeDatabasePrivate::addMimeTypes(const QString &fileName, QString *errorMessage)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
*errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString());
return false;
}
return addMimeTypes(&file, fileName, errorMessage);
}
bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, QString *errorMessage)
{
return addMimeTypes(device, QLatin1String("<stream>"), errorMessage);
}
bool MimeDatabasePrivate::addMimeType(MimeType mt)
{
if (!mt)
return false;
const QString type = mt.type();
// Hack: Add a magic text matcher to "text/plain" and the fallback matcher to
// binary types "application/octet-stream"
if (type == QLatin1String(textTypeC)) {
mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::HeuristicTextMagicMatcher));
} else {
if (type == QLatin1String(binaryTypeC))
mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::BinaryMatcher));
}
// insert the type.
m_typeMimeTypeMap.insert(type, MimeMapEntry(mt));
// Register the children
// Aliases will be resolved later once all mime types are known.
const QStringList subClassesOf = mt.subClassesOf();
if (!subClassesOf.empty()) {
const QStringList::const_iterator socend = subClassesOf.constEnd();
for (QStringList::const_iterator soit = subClassesOf.constBegin(); soit != socend; ++soit)
m_parentChildrenMap.insert(*soit, type);
}
// register aliasses
const QStringList aliases = mt.aliases();
if (!aliases.empty()) {
const QStringList::const_iterator cend = aliases.constEnd();
for (QStringList::const_iterator it = aliases.constBegin(); it != cend; ++it)
m_aliasMap.insert(*it, type);
}
m_maxLevel = -1; // Mark as dirty
return true;
}
const QString &MimeDatabasePrivate::resolveAlias(const QString &name) const
{
const AliasMap::const_iterator aliasIt = m_aliasMap.constFind(name);
return aliasIt == m_aliasMap.constEnd() ? name : aliasIt.value();
}
void MimeDatabasePrivate::raiseLevelRecursion(MimeMapEntry &e, int level)
{
if (e.level == Dangling || e.level < level)
e.level = level;
if (m_maxLevel < level)
m_maxLevel = level;
// At all events recurse over children since nodes might have been
// added.
QStringList childTypes = m_parentChildrenMap.values(e.type.type());
foreach (const QString &alias, e.type.aliases())
childTypes.append(m_parentChildrenMap.values(alias));
if (childTypes.empty())
return;
// look them up in the type->mime type map
const int nextLevel = level + 1;
const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
const QStringList::const_iterator cend = childTypes.constEnd();
for (QStringList::const_iterator it = childTypes.constBegin(); it != cend; ++it) {
const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*it));
if (tm_it == tm_end) {
qWarning("%s: Inconsistent mime hierarchy detected, child %s of %s cannot be found.",
Q_FUNC_INFO, it->toUtf8().constData(), e.type.type().toUtf8().constData());
} else {
raiseLevelRecursion(*tm_it, nextLevel);
}
}
}
void MimeDatabasePrivate::determineLevels()
{
// Loop over toplevels and recurse down their hierarchies.
// Determine top levels by subtracting the children from the parent
// set. Note that a toplevel at this point might have 'subclassesOf'
// set to some class that is not in the DB, so, checking for an empty
// 'subclassesOf' set is not sufficient to find the toplevels.
// First, take the parent->child entries whose parent exists and build
// sets of parents/children
QSet<QString> parentSet, childrenSet;
const ParentChildrenMap::const_iterator pcend = m_parentChildrenMap.constEnd();
for (ParentChildrenMap::const_iterator it = m_parentChildrenMap.constBegin(); it != pcend; ++it)
if (m_typeMimeTypeMap.contains(it.key())) {
parentSet.insert(it.key());
childrenSet.insert(it.value());
}
const QSet<QString> topLevels = parentSet.subtract(childrenSet);
if (debugMimeDB)
qDebug() << Q_FUNC_INFO << "top levels" << topLevels;
const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
const QSet<QString>::const_iterator tl_cend = topLevels.constEnd();
for (QSet<QString>::const_iterator tl_it = topLevels.constBegin(); tl_it != tl_cend; ++tl_it) {
const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*tl_it));
if (tm_it == tm_end) {
qWarning("%s: Inconsistent mime hierarchy detected, top level element %s cannot be found.",
Q_FUNC_INFO, tl_it->toUtf8().constData());
} else {
raiseLevelRecursion(tm_it.value(), 0);
}
}
}
bool MimeDatabasePrivate::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
return tit.value().type.setPreferredSuffix(suffix);
return false;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByType(const QString &typeOrAlias) const
{
const TypeMimeTypeMap::const_iterator tit = m_typeMimeTypeMap.constFind(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.constEnd())
return tit.value().type;
return MimeType();
}
// Debugging wrapper around findByFile()
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const
{
unsigned priority = 0;
if (debugMimeDB)
qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath();
const MimeType rc = findByFile(f, &priority);
if (debugMimeDB) {
if (rc)
qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type();
else
qDebug() << "<MimeDatabase::findByFile: no match";
}
return rc;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityPtr) const
{
// Is the hierarchy set up in case we find several matches?
if (m_maxLevel < 0) {
MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this);
db->determineLevels();
}
// First, glob patterns are evaluated. If there is a match with max weight,
// this one is selected and we are done. Otherwise, the file contents are
// evaluated and the match with the highest value (either a magic priority or
// a glob pattern weight) is selected. Matching starts from max level (most
// specific) in both cases, even when there is already a suffix matching candidate.
*priorityPtr = 0;
MimeType candidate;
Internal::FileMatchContext context(f);
// Pass 1) Try to match on suffix
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (int level = m_maxLevel; level >= 0; level--) {
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned suffixPriority = it.value().type.matchesFileBySuffix(context);
if (suffixPriority && suffixPriority > *priorityPtr) {
*priorityPtr = suffixPriority;
candidate = it.value().type;
if (suffixPriority >= MimeGlobPattern::MaxWeight)
return candidate;
}
}
}
}
// Pass 2) Match on content
if (!f.isReadable())
return candidate;
for (int level = m_maxLevel; level >= 0; level--) {
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned contentPriority = it.value().type.matchesFileByContent(context);
if (contentPriority && contentPriority > *priorityPtr) {
*priorityPtr = contentPriority;
candidate = it.value().type;
}
}
}
}
return candidate;
}
// Debugging wrapper around findByData()
MimeType MimeDatabasePrivate::findByData(const QByteArray &data) const
{
unsigned priority = 0;
if (debugMimeDB)
qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex();
const MimeType rc = findByData(data, &priority);
if (debugMimeDB) {
if (rc)
qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type();
else
qDebug() << "<MimeDatabase::findByData: no match";
}
return rc;
}
// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByData(const QByteArray &data, unsigned *priorityPtr) const
{
// Is the hierarchy set up in case we find several matches?
if (m_maxLevel < 0) {
MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this);
db->determineLevels();
}
*priorityPtr = 0;
MimeType candidate;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (int level = m_maxLevel; level >= 0; level--)
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
if (it.value().level == level) {
const unsigned contentPriority = it.value().type.matchesData(data);
if (contentPriority && contentPriority > *priorityPtr) {
*priorityPtr = contentPriority;
candidate = it.value().type;
}
}
return candidate;
}
// Return all known suffixes
QStringList MimeDatabasePrivate::suffixes() const
{
QStringList rc;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
rc += it.value().type.suffixes();
return rc;
}
QStringList MimeDatabasePrivate::filterStrings() const
{
QStringList rc;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
const QString filterString = it.value().type.filterString();
if (!filterString.isEmpty())
rc += filterString;
}
return rc;
}
QList<MimeGlobPattern> MimeDatabasePrivate::globPatterns() const
{
QList<MimeGlobPattern> globPatterns;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
globPatterns.append(it.value().type.globPatterns());
return globPatterns;
}
void MimeDatabasePrivate::setGlobPatterns(const QString &typeOrAlias,
const QList<MimeGlobPattern> &globPatterns)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
tit.value().type.setGlobPatterns(globPatterns);
}
QList<QSharedPointer<IMagicMatcher> > MimeDatabasePrivate::magicMatchers() const
{
QList<QSharedPointer<IMagicMatcher> > magicMatchers;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
magicMatchers.append(it.value().type.magicMatchers());
return magicMatchers;
}
void MimeDatabasePrivate::setMagicMatchers(const QString &typeOrAlias,
const QList<QSharedPointer<IMagicMatcher> > &matchers)
{
TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
if (tit != m_typeMimeTypeMap.end())
tit.value().type.setMagicMatchers(matchers);
}
QList<MimeType> MimeDatabasePrivate::mimeTypes() const
{
QList<MimeType> mimeTypes;
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
mimeTypes.append(it.value().type);
return mimeTypes;
}
void MimeDatabasePrivate::syncUserModifiedMimeTypes()
{
QHash<QString, MimeType> userModified;
const QList<MimeType> &userMimeTypes = readUserModifiedMimeTypes();
foreach (const MimeType &userMimeType, userMimeTypes)
userModified.insert(userMimeType.type(), userMimeType);
TypeMimeTypeMap::iterator end = m_typeMimeTypeMap.end();
QHash<QString, MimeType>::const_iterator userMimeEnd = userModified.end();
for (TypeMimeTypeMap::iterator it = m_typeMimeTypeMap.begin(); it != end; ++it) {
QHash<QString, MimeType>::const_iterator userMimeIt =
userModified.find(it.value().type.type());
if (userMimeIt != userMimeEnd) {
it.value().type.setGlobPatterns(userMimeIt.value().globPatterns());
it.value().type.setMagicRuleMatchers(userMimeIt.value().magicRuleMatchers());
}
}
}
QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes()
{
typedef MagicRuleMatcher::MagicRuleList MagicRuleList;
typedef MagicRuleMatcher::MagicRuleSharedPointer MagicRuleSharedPointer;
QList<MimeType> mimeTypes;
QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
if (file.open(QFile::ReadOnly)) {
MimeType mimeType;
QHash<int, MagicRuleList> rules;
QXmlStreamReader reader(&file);
QXmlStreamAttributes atts;
const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC);
const QString patternAttribute = QLatin1String(patternAttributeC);
const QString matchValueAttribute = QLatin1String(matchValueAttributeC);
const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC);
const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC);
const QString priorityAttribute = QLatin1String(priorityAttributeC);
while (!reader.atEnd()) {
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
atts = reader.attributes();
if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setType(atts.value(mimeTypeAttribute).toString());
const QString &patterns = atts.value(patternAttribute).toString();
mimeType.setGlobPatterns(toGlobPatterns(patterns.split(QLatin1Char(';'))));
} else if (reader.name() == QLatin1String(matchTagC)) {
const QString &value = atts.value(matchValueAttribute).toString();
const QStringRef type = atts.value(matchTypeAttribute);
const QString &offset = atts.value(matchOffsetAttribute).toString();
QPair<int, int> range = MagicRule::fromOffset(offset);
const int priority = atts.value(priorityAttribute).toString().toInt();
MagicRule *magicRule;
if (type == MagicStringRule::kMatchType)
magicRule = new MagicStringRule(value, range.first, range.second);
else
magicRule = new MagicByteRule(value, range.first, range.second);
rules[priority].append(MagicRuleSharedPointer(magicRule));
}
break;
case QXmlStreamReader::EndElement:
if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setMagicRuleMatchers(MagicRuleMatcher::createMatchers(rules));
mimeTypes.append(mimeType);
mimeType.clear();
rules.clear();
}
break;
default:
break;
}
}
if (reader.hasError())
qWarning() << kModifiedMimeTypesFile << reader.errorString() << reader.lineNumber()
<< reader.columnNumber();
file.close();
}
return mimeTypes;
}
void MimeDatabasePrivate::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes)
{
// Keep mime types modified which are already on file, unless they are part of the current set.
QSet<QString> currentMimeTypes;
foreach (const MimeType &mimeType, mimeTypes)
currentMimeTypes.insert(mimeType.type());
const QList<MimeType> &inFileMimeTypes = readUserModifiedMimeTypes();
QList<MimeType> allModifiedMimeTypes = mimeTypes;
foreach (const MimeType &mimeType, inFileMimeTypes)
if (!currentMimeTypes.contains(mimeType.type()))
allModifiedMimeTypes.append(mimeType);
if (QFile::exists(kModifiedMimeTypesPath) || QDir().mkpath(kModifiedMimeTypesPath)) {
QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
if (file.open(QFile::WriteOnly | QFile::Truncate)) {
// Notice this file only represents user modifications. It is writen in a
// convienient way for synchronization, which is similar to but not exactly the
// same format we use for the embedded mime type files.
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement(QLatin1String(mimeInfoTagC));
const QString mimeTypeTag = QLatin1String(mimeTypeTagC);
const QString matchTag = QLatin1String(matchTagC);
const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC);
const QString patternAttribute = QLatin1String(patternAttributeC);
const QString matchValueAttribute = QLatin1String(matchValueAttributeC);
const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC);
const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC);
const QString priorityAttribute = QLatin1String(priorityAttributeC);
foreach (const MimeType &mimeType, allModifiedMimeTypes) {
writer.writeStartElement(mimeTypeTag);
writer.writeAttribute(mimeTypeAttribute, mimeType.type());
writer.writeAttribute(patternAttribute,
fromGlobPatterns(mimeType.globPatterns()).join(QLatin1Char(';')));
const QList<QSharedPointer<IMagicMatcher> > &matchers = mimeType.magicMatchers();
foreach (const QSharedPointer<IMagicMatcher> &matcher, matchers) {
// Only care about rule-based matchers.
if (MagicRuleMatcher *ruleMatcher =
dynamic_cast<MagicRuleMatcher *>(matcher.data())) {
const MagicRuleMatcher::MagicRuleList &rules = ruleMatcher->magicRules();
foreach (const MagicRuleMatcher::MagicRuleSharedPointer &rule, rules) {
writer.writeStartElement(matchTag);
writer.writeAttribute(matchValueAttribute, rule->matchValue());
writer.writeAttribute(matchTypeAttribute, rule->matchType());
writer.writeAttribute(matchOffsetAttribute,
MagicRule::toOffset(
qMakePair(rule->startPos(), rule->endPos())));
writer.writeAttribute(priorityAttribute,
QString::number(ruleMatcher->priority()));
writer.writeEndElement();
}
}
}
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
file.close();
}
}
}
void MimeDatabasePrivate::clearUserModifiedMimeTypes()
{
// This removes the user's file. However, the operation will actually take place the next time
// Creator starts, since we currently don't support removing stuff from the mime database.
QFile::remove(kModifiedMimeTypesPath + kModifiedMimeTypesFile);
}
QList<MimeGlobPattern> MimeDatabasePrivate::toGlobPatterns(const QStringList &patterns, int weight)
{
QList<MimeGlobPattern> globPatterns;
foreach (const QString &pattern, patterns)
globPatterns.append(Core::MimeGlobPattern(pattern, weight));
return globPatterns;
}
QStringList MimeDatabasePrivate::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns)
{
QStringList patterns;
foreach (const MimeGlobPattern &globPattern, globPatterns)
patterns.append(globPattern.pattern());
return patterns;
}
void MimeDatabasePrivate::debug(QTextStream &str) const
{
str << ">MimeDatabase\n";
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
str << "Entry level " << it.value().level << '\n';
it.value().type.m_d->debug(str);
}
str << "<MimeDatabase\n";
}
static MimeDatabasePrivate *d;
MimeDatabase::MimeDatabase()
{
d = new MimeDatabasePrivate;
}
MimeDatabase::~MimeDatabase()
{
delete d;
}
MimeType MimeDatabase::findByType(const QString &typeOrAlias)
{
d->m_mutex.lock();
const MimeType rc = d->findByType(typeOrAlias);
d->m_mutex.unlock();
return rc;
}
MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f)
{
return d->findByFile(f);
}
MimeType MimeDatabase::findByFile(const QFileInfo &f)
{
d->m_mutex.lock();
const MimeType rc = findByFileUnlocked(f);
d->m_mutex.unlock();
return rc;
}
MimeType MimeDatabase::findByData(const QByteArray &data)
{
d->m_mutex.lock();
const MimeType rc = d->findByData(data);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeType(const MimeType &mt)
{
d->m_mutex.lock();
const bool rc = d->addMimeType(mt);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(const QString &fileName, QString *errorMessage)
{
d->m_mutex.lock();
const bool rc = d->addMimeTypes(fileName, errorMessage);
d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(QIODevice *device, QString *errorMessage)
{
d->m_mutex.lock();
const bool rc = d->addMimeTypes(device, errorMessage);
d->m_mutex.unlock();
return rc;
}
QStringList MimeDatabase::suffixes()
{
d->m_mutex.lock();
const QStringList rc = d->suffixes();
d->m_mutex.unlock();
return rc;
}
QStringList MimeDatabase::filterStrings()
{
d->m_mutex.lock();
const QStringList rc = d->filterStrings();
d->m_mutex.unlock();
return rc;
}
QString MimeDatabase::allFiltersString(QString *allFilesFilter)
{
if (allFilesFilter)
allFilesFilter->clear();
// Compile list of filter strings, sort, and remove duplicates (different mime types might
// generate the same filter).
QStringList filters = filterStrings();
if (filters.empty())
return QString();
filters.sort();
filters.erase(std::unique(filters.begin(), filters.end()), filters.end());
static const QString allFiles =
QCoreApplication::translate("Core", Constants::ALL_FILES_FILTER);
if (allFilesFilter)
*allFilesFilter = allFiles;
// Prepend all files filter (instead of appending to work around a bug in Qt/Mac).
filters.prepend(allFiles);
return filters.join(QLatin1String(";;"));
}
QList<MimeGlobPattern> MimeDatabase::globPatterns()
{
d->m_mutex.lock();
const QList<MimeGlobPattern> rc = d->globPatterns();
d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setGlobPatterns(const QString &typeOrAlias,
const QList<MimeGlobPattern> &globPatterns)
{
d->m_mutex.lock();
d->setGlobPatterns(typeOrAlias, globPatterns);
d->m_mutex.unlock();
}
MimeDatabase::IMagicMatcherList MimeDatabase::magicMatchers()
{
d->m_mutex.lock();
const IMagicMatcherList rc = d->magicMatchers();
d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setMagicMatchers(const QString &typeOrAlias,
const IMagicMatcherList &matchers)
{
d->m_mutex.lock();
d->setMagicMatchers(typeOrAlias, matchers);
d->m_mutex.unlock();
}
QList<MimeType> MimeDatabase::mimeTypes()
{
d->m_mutex.lock();
const QList<MimeType> &mimeTypes = d->mimeTypes();
d->m_mutex.unlock();
return mimeTypes;
}
void MimeDatabase::syncUserModifiedMimeTypes()
{
d->m_mutex.lock();
d->syncUserModifiedMimeTypes();
d->m_mutex.unlock();
}
void MimeDatabase::clearUserModifiedMimeTypes()
{
d->m_mutex.lock();
d->clearUserModifiedMimeTypes();
d->m_mutex.unlock();
}
QList<MimeType> MimeDatabase::readUserModifiedMimeTypes()
{
return MimeDatabasePrivate::readUserModifiedMimeTypes();
}
void MimeDatabase::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes)
{
MimeDatabasePrivate::writeUserModifiedMimeTypes(mimeTypes);
}
QString MimeDatabase::preferredSuffixByType(const QString &type)
{
if (const MimeType mt = findByType(type))
return mt.preferredSuffix(); // already does Mutex locking
return QString();
}
QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f)
{
if (const MimeType mt = findByFile(f))
return mt.preferredSuffix(); // already does Mutex locking
return QString();
}
bool MimeDatabase::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
d->m_mutex.lock();
const bool rc = d->setPreferredSuffix(typeOrAlias, suffix);
d->m_mutex.unlock();
return rc;
}
QList<MimeGlobPattern> MimeDatabase::toGlobPatterns(const QStringList &patterns, int weight)
{
return MimeDatabasePrivate::toGlobPatterns(patterns, weight);
}
QStringList MimeDatabase::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns)
{
return MimeDatabasePrivate::fromGlobPatterns(globPatterns);
}
//QDebug operator<<(QDebug d, const MimeDatabase &mt)
//{
// QString s;
// {
// QTextStream str(&s);
// d->debug(str);
// }
// db << s;
// return db;
//}
} // namespace Core
|
/******************************************************************************
** Copyright (c) 2014-2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. 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. **
** 3. Neither the name of the copyright holder 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 THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS 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. **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#if defined(LIBXSTREAM_EXPORTED) || defined(__LIBXSTREAM)
#include "libxstream_stream.hpp"
#include "libxstream_capture.hpp"
#include "libxstream_event.hpp"
#include "libxstream_queue.hpp"
#include <libxstream_begin.h>
#include <algorithm>
#include <string>
#include <cstdio>
#if defined(LIBXSTREAM_STDFEATURES)
# include <atomic>
#endif
#include <libxstream_end.h>
// allows to wait for an event issued prior to the pending signal
//#define LIBXSTREAM_STREAM_WAIT_PAST
// unlocking the stream is only allowed for the thread that locked
//#define LIBXSTREAM_STREAM_UNLOCK_OWNER
namespace libxstream_stream_internal {
static/*IPO*/ class registry_type {
public:
typedef libxstream_stream* value_type;
public:
registry_type()
: m_istreams(0)
{
std::fill_n(m_signals, LIBXSTREAM_MAX_NDEVICES, 0);
std::fill_n(m_streams, LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS, static_cast<value_type>(0));
}
~registry_type() {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
#if defined(LIBXSTREAM_DEBUG)
if (0 != m_streams[i]) {
LIBXSTREAM_PRINT(1, "dangling stream \"%s\"!", m_streams[i]->name());
}
#endif
libxstream_stream_destroy(m_streams[i]);
}
}
public:
volatile value_type& allocate() {
#if !defined(LIBXSTREAM_STDFEATURES)
libxstream_lock *const lock = libxstream_lock_get(this);
libxstream_lock_acquire(lock);
#endif
volatile value_type* i = m_streams + (m_istreams++ % (LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS));
while (0 != *i) i = m_streams + (m_istreams++ % (LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS));
#if !defined(LIBXSTREAM_STDFEATURES)
libxstream_lock_release(lock);
#endif
return *i;
}
size_t max_nstreams() const {
return std::min<size_t>(m_istreams, LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS);
}
size_t nstreams(int device) const {
const size_t n = max_nstreams();
size_t result = 0;
for (size_t i = 0; i < n; ++i) {
result += (0 != m_streams[i] && m_streams[i]->device() == device) ? 1 : 0;
}
return result;
}
size_t nstreams() const {
const size_t n = max_nstreams();
size_t result = 0;
for (size_t i = 0; i < n; ++i) {
result += 0 != m_streams[i] ? 1 : 0;
}
return result;
}
libxstream_signal& signal(int device) {
LIBXSTREAM_ASSERT(-1 <= device && device <= LIBXSTREAM_MAX_NDEVICES);
return m_signals[device+1];
}
volatile value_type* streams() {
return m_streams;
}
int enqueue(libxstream_event& event, const libxstream_stream* exclude) {
LIBXSTREAM_ASSERT(0 == event.expected());
int result = LIBXSTREAM_ERROR_NONE;
const size_t n = max_nstreams();
bool reset = true;
for (size_t i = 0; i < n; ++i) {
const value_type stream = m_streams[i];
if (stream != exclude) {
result = event.enqueue(*stream, reset);
LIBXSTREAM_CHECK_ERROR(result);
reset = false;
}
}
if (reset) {
result = event.reset();
}
return result;
}
value_type schedule(const libxstream_stream* exclude) {
value_type result = 0;
const size_t n = max_nstreams();
size_t j = 0;
for (size_t i = 0; i < n; ++i) {
const value_type stream = m_streams[i];
if (0 != stream) {
result = stream;
j = i + 1;
i = n; // break
}
}
for (size_t i = j; i < n; ++i) {
const value_type stream = m_streams[i];
if (stream == exclude) {
j = i + 1;
i = n; // break
}
}
for (size_t i = j; i < n; ++i) {
const value_type stream = m_streams[i];
if (0 != stream) {
result = stream;
i = n; // break
}
}
return result;
}
int sync(int device) {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
if (const value_type stream = m_streams[i]) {
const int stream_device = stream->device();
if (stream_device == device) {
const int result = stream->wait(0);
LIBXSTREAM_CHECK_ERROR(result);
}
}
}
return LIBXSTREAM_ERROR_NONE;
}
int sync() {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
if (const value_type stream = m_streams[i]) {
const int result = stream->wait(0);
LIBXSTREAM_CHECK_ERROR(result);
}
}
return LIBXSTREAM_ERROR_NONE;
}
private:
// not necessary to be device-specific due to single-threaded offload
libxstream_signal m_signals[LIBXSTREAM_MAX_NDEVICES + 1];
volatile value_type m_streams[LIBXSTREAM_MAX_NDEVICES*LIBXSTREAM_MAX_NSTREAMS];
#if defined(LIBXSTREAM_STDFEATURES)
std::atomic<size_t> m_istreams;
#else
size_t m_istreams;
#endif
} registry;
template<typename A, typename E, typename D>
bool atomic_compare_exchange(A& atomic, E& expected, D desired)
{
#if defined(LIBXSTREAM_STDFEATURES)
const bool result = std::atomic_compare_exchange_weak(&atomic, &expected, desired);
#elif defined(_OPENMP)
bool result = false;
# pragma omp critical
{
result = atomic == expected;
if (result) {
atomic = desired;
}
else {
expected = atomic;
}
}
#else // generic
bool result = false;
libxstream_lock *const lock = libxstream_lock_get(&atomic);
libxstream_lock_acquire(lock);
result = atomic == expected;
if (result) {
atomic = desired;
}
else {
expected = atomic;
}
libxstream_lock_release(lock);
#endif
return result;
}
template<typename A, typename T>
T atomic_store(A& atomic, T value)
{
T result = value;
#if defined(LIBXSTREAM_STDFEATURES)
result = std::atomic_exchange(&atomic, value);
#elif defined(_OPENMP)
# pragma omp critical
{
result = atomic;
atomic = value;
}
#else // generic
libxstream_lock_acquire(registry.lock());
result = atomic;
atomic = value;
libxstream_lock_release(registry.lock());
#endif
return result;
}
} // namespace libxstream_stream_internal
/*static*/int libxstream_stream::enqueue(libxstream_event& event, const libxstream_stream* exclude)
{
return libxstream_stream_internal::registry.enqueue(event, exclude);
}
/*static*/libxstream_stream* libxstream_stream::schedule(const libxstream_stream* exclude)
{
return libxstream_stream_internal::registry.schedule(exclude);
}
/*static*/int libxstream_stream::sync(int device)
{
return libxstream_stream_internal::registry.sync(device);
}
/*static*/int libxstream_stream::sync()
{
return libxstream_stream_internal::registry.sync();
}
libxstream_stream::libxstream_stream(int device, int priority, const char* name)
: m_device(device), m_priority(priority), m_thread(-1)
#if defined(LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
, m_handle(0) // lazy creation
, m_npartitions(0)
#endif
{
std::fill_n(m_pending, LIBXSTREAM_MAX_NTHREADS, static_cast<libxstream_signal>(0));
std::fill_n(m_queues, LIBXSTREAM_MAX_NTHREADS, static_cast<libxstream_queue*>(0));
#if defined(LIBXSTREAM_TRACE) && ((1 == ((2*LIBXSTREAM_TRACE+1)/2) && defined(LIBXSTREAM_DEBUG)) || 1 < ((2*LIBXSTREAM_TRACE+1)/2))
if (name && 0 != *name) {
const size_t length = std::min(std::char_traits<char>::length(name), sizeof(m_name) - 1);
std::copy(name, name + length, m_name);
m_name[length] = 0;
}
else {
m_name[0] = 0;
}
#else
libxstream_use_sink(name);
#endif
using namespace libxstream_stream_internal;
volatile registry_type::value_type& slot = libxstream_stream_internal::registry.allocate();
slot = this;
}
libxstream_stream::~libxstream_stream()
{
using namespace libxstream_stream_internal;
volatile registry_type::value_type *const end = registry.streams() + registry.max_nstreams();
volatile registry_type::value_type *const stream = std::find(registry.streams(), end, this);
LIBXSTREAM_ASSERT(stream != end);
*stream = 0; // unregister stream
const size_t nthreads = nthreads_active();
for (size_t i = 0; i < nthreads; ++i) {
delete m_queues[i];
}
#if defined(LIBXSTREAM_OFFLOAD) && (0 != LIBXSTREAM_OFFLOAD) && !defined(__MIC__) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
if (0 != m_handle) {
_Offload_stream_destroy(m_device, m_handle);
}
#endif
}
libxstream_signal libxstream_stream::signal() const
{
return ++libxstream_stream_internal::registry.signal(m_device);
}
int libxstream_stream::wait(libxstream_signal signal)
{
int result = LIBXSTREAM_ERROR_NONE;
LIBXSTREAM_ASYNC_BEGIN(this, m_pending, signal)
{
libxstream_signal *const pending_signals = ptr<libxstream_signal,0>();
const libxstream_signal signal = val<const libxstream_signal,1>();
const int nthreads = static_cast<int>(nthreads_active());
for (int i = 0; i < nthreads; ++i) {
const libxstream_signal pending_signal = pending_signals[i];
if (0 != pending_signal) {
#if defined(LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (0 != (2*LIBXSTREAM_ASYNC+1)/2)
if (0 <= LIBXSTREAM_ASYNC_DEVICE) {
# if defined(LIBXSTREAM_STREAM_WAIT_PAST)
const libxstream_signal wait_pending = 0 != signal ? signal : pending_signal;
# else
const libxstream_signal wait_pending = pending_signal;
# endif
# pragma offload_wait LIBXSTREAM_ASYNC_TARGET wait(wait_pending)
}
#endif
if (0 == signal) {
pending_signals[i] = 0;
}
#if defined(LIBXSTREAM_STREAM_WAIT_PAST)
else {
i = nthreads; // break
}
#endif
}
}
if (0 != signal) {
for (int i = 0; i < nthreads; ++i) {
if (signal == pending_signals[i]) {
pending_signals[i] = 0;
}
}
}
}
LIBXSTREAM_ASYNC_END(LIBXSTREAM_CALL_DEFAULT | LIBXSTREAM_CALL_WAIT, result);
return result;
}
void libxstream_stream::pending(int thread, libxstream_signal signal)
{
LIBXSTREAM_ASSERT(0 <= thread && thread < LIBXSTREAM_MAX_NTHREADS);
m_pending[thread] = signal;
}
libxstream_signal libxstream_stream::pending(int thread) const
{
LIBXSTREAM_ASSERT(0 <= thread && thread < LIBXSTREAM_MAX_NTHREADS);
const libxstream_signal signal = m_pending[thread];
return signal;
}
void libxstream_stream::enqueue(const libxstream_capture_base& work_item)
{
libxstream_capture_base *const item = work_item.clone();
#if !defined(LIBXSTREAM_SYNCHRONOUS) || 2 != (LIBXSTREAM_SYNCHRONOUS)
const int thread = this_thread_id();
LIBXSTREAM_ASSERT(thread < LIBXSTREAM_MAX_NTHREADS);
libxstream_queue *volatile *const q = m_queues + thread;
if (0 == *q) {
libxstream_lock* lock = libxstream_lock_get(q);
libxstream_lock_acquire(lock);
if (0 == *q) {
*q = new libxstream_queue;
}
libxstream_lock_release(lock);
}
LIBXSTREAM_ASSERT(0 != *q);
volatile libxstream_queue::value_type& slot = (*q)->allocate_push();
LIBXSTREAM_ASSERT(0 == slot);
slot = item;
if (0 != (work_item.flags() & LIBXSTREAM_CALL_WAIT)) {
while (item == slot) {
this_thread_yield();
}
}
#else
(*item)();
delete item;
#endif
}
libxstream_queue* libxstream_stream::queue(const libxstream_queue* exclude)
{
libxstream_queue* result = 0;
if (0 == exclude) {
result = 0 <= m_thread ? m_queues[m_thread] : 0;
if (0 == result || 0 == m_pending[m_thread] || result->empty()) {
size_t size = 0;
const int nthreads = static_cast<int>(nthreads_active());
for (int i = 0; i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
const size_t si = 0 != qi ? qi->size() : 0;
if (size < si) {
m_thread = i;
result = qi;
size = si;
}
}
}
}
else { // round-robin
const size_t nthreads = nthreads_active();
int thread = -1;
for (size_t/*-Wstrict-overflow*/ i = 0; i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (exclude != qi) {
result = qi;
thread = static_cast<int>(i);
i = nthreads; // break
}
else {
thread = static_cast<int>(i + 1);
i = nthreads; // break
}
}
if (0 <= thread) {
if (0 != result) {
for (size_t i = static_cast<size_t>(thread); i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (exclude == qi) {
thread = static_cast<int>(i + 1);
i = nthreads; // break
}
}
}
for (size_t i = static_cast<size_t>(thread); i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (0 != qi) {
result = qi;
m_thread = static_cast<int>(i);
i = nthreads; // break
}
}
}
}
return result;
}
#if defined(LIBXSTREAM_OFFLOAD) && (0 != LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
_Offload_stream libxstream_stream::handle() const
{
const size_t nstreams = libxstream_stream_internal::registry.nstreams(m_device);
if (nstreams != m_npartitions) {
if (0 != m_handle) {
const_cast<libxstream_stream*>(this)->wait(0); // complete pending operations on old stream
_Offload_stream_destroy(m_device, m_handle);
}
// TODO: implement device discovery (number of threads)
const size_t nthreads = 224;
// TODO: implement stream priorities (weighting)
m_handle = _Offload_stream_create(m_device, static_cast<int>(nthreads / nstreams));
m_npartitions = nstreams;
}
return m_handle;
}
#endif
#if defined(LIBXSTREAM_TRACE) && ((1 == ((2*LIBXSTREAM_TRACE+1)/2) && defined(LIBXSTREAM_DEBUG)) || 1 < ((2*LIBXSTREAM_TRACE+1)/2))
const char* libxstream_stream::name() const
{
return m_name;
}
#endif
const libxstream_stream* cast_to_stream(const void* stream)
{
return static_cast<const libxstream_stream*>(stream);
}
libxstream_stream* cast_to_stream(void* stream)
{
return static_cast<libxstream_stream*>(stream);
}
const libxstream_stream* cast_to_stream(const libxstream_stream* stream)
{
return stream;
}
libxstream_stream* cast_to_stream(libxstream_stream* stream)
{
return stream;
}
const libxstream_stream* cast_to_stream(const libxstream_stream& stream)
{
return &stream;
}
libxstream_stream* cast_to_stream(libxstream_stream& stream)
{
return &stream;
}
#endif // defined(LIBXSTREAM_EXPORTED) || defined(__LIBXSTREAM)
Code cleanup.
/******************************************************************************
** Copyright (c) 2014-2015, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. 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. **
** 3. Neither the name of the copyright holder 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 THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS 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. **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#if defined(LIBXSTREAM_EXPORTED) || defined(__LIBXSTREAM)
#include "libxstream_stream.hpp"
#include "libxstream_capture.hpp"
#include "libxstream_event.hpp"
#include "libxstream_queue.hpp"
#include <libxstream_begin.h>
#include <algorithm>
#include <string>
#include <cstdio>
#if defined(LIBXSTREAM_STDFEATURES)
# include <atomic>
#endif
#include <libxstream_end.h>
// allows to wait for an event issued prior to the pending signal
//#define LIBXSTREAM_STREAM_WAIT_PAST
// unlocking the stream is only allowed for the thread that locked
//#define LIBXSTREAM_STREAM_UNLOCK_OWNER
namespace libxstream_stream_internal {
static/*IPO*/ class registry_type {
public:
typedef libxstream_stream* value_type;
public:
registry_type()
: m_istreams(0)
{
std::fill_n(m_signals, LIBXSTREAM_MAX_NDEVICES, 0);
std::fill_n(m_streams, LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS, static_cast<value_type>(0));
}
~registry_type() {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
#if defined(LIBXSTREAM_DEBUG)
if (0 != m_streams[i]) {
LIBXSTREAM_PRINT(1, "dangling stream \"%s\"!", m_streams[i]->name());
}
#endif
libxstream_stream_destroy(m_streams[i]);
}
}
public:
volatile value_type& allocate() {
#if !defined(LIBXSTREAM_STDFEATURES)
libxstream_lock *const lock = libxstream_lock_get(this);
libxstream_lock_acquire(lock);
#endif
volatile value_type* i = m_streams + (m_istreams++ % (LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS));
while (0 != *i) i = m_streams + (m_istreams++ % (LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS));
#if !defined(LIBXSTREAM_STDFEATURES)
libxstream_lock_release(lock);
#endif
return *i;
}
size_t max_nstreams() const {
return std::min<size_t>(m_istreams, LIBXSTREAM_MAX_NDEVICES * LIBXSTREAM_MAX_NSTREAMS);
}
size_t nstreams(int device) const {
const size_t n = max_nstreams();
size_t result = 0;
for (size_t i = 0; i < n; ++i) {
result += (0 != m_streams[i] && m_streams[i]->device() == device) ? 1 : 0;
}
return result;
}
size_t nstreams() const {
const size_t n = max_nstreams();
size_t result = 0;
for (size_t i = 0; i < n; ++i) {
result += 0 != m_streams[i] ? 1 : 0;
}
return result;
}
libxstream_signal& signal(int device) {
LIBXSTREAM_ASSERT(-1 <= device && device <= LIBXSTREAM_MAX_NDEVICES);
return m_signals[device+1];
}
volatile value_type* streams() {
return m_streams;
}
int enqueue(libxstream_event& event, const libxstream_stream* exclude) {
LIBXSTREAM_ASSERT(0 == event.expected());
int result = LIBXSTREAM_ERROR_NONE;
const size_t n = max_nstreams();
bool reset = true;
for (size_t i = 0; i < n; ++i) {
const value_type stream = m_streams[i];
if (stream != exclude) {
result = event.enqueue(*stream, reset);
LIBXSTREAM_CHECK_ERROR(result);
reset = false;
}
}
if (reset) {
result = event.reset();
}
return result;
}
value_type schedule(const libxstream_stream* exclude) {
value_type result = 0;
const size_t n = max_nstreams();
size_t j = 0;
for (size_t i = 0; i < n; ++i) {
const value_type stream = m_streams[i];
if (0 != stream) {
result = stream;
j = i + 1;
i = n; // break
}
}
for (size_t i = j; i < n; ++i) {
const value_type stream = m_streams[i];
if (stream == exclude) {
j = i + 1;
i = n; // break
}
}
for (size_t i = j; i < n; ++i) {
const value_type stream = m_streams[i];
if (0 != stream) {
result = stream;
i = n; // break
}
}
return result;
}
int sync(int device) {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
if (const value_type stream = m_streams[i]) {
const int stream_device = stream->device();
if (stream_device == device) {
const int result = stream->wait(0);
LIBXSTREAM_CHECK_ERROR(result);
}
}
}
return LIBXSTREAM_ERROR_NONE;
}
int sync() {
const size_t n = max_nstreams();
for (size_t i = 0; i < n; ++i) {
if (const value_type stream = m_streams[i]) {
const int result = stream->wait(0);
LIBXSTREAM_CHECK_ERROR(result);
}
}
return LIBXSTREAM_ERROR_NONE;
}
private:
// not necessary to be device-specific due to single-threaded offload
libxstream_signal m_signals[LIBXSTREAM_MAX_NDEVICES + 1];
volatile value_type m_streams[LIBXSTREAM_MAX_NDEVICES*LIBXSTREAM_MAX_NSTREAMS];
#if defined(LIBXSTREAM_STDFEATURES)
std::atomic<size_t> m_istreams;
#else
size_t m_istreams;
#endif
} registry;
template<typename A, typename E, typename D>
bool atomic_compare_exchange(A& atomic, E& expected, D desired)
{
#if defined(LIBXSTREAM_STDFEATURES)
const bool result = std::atomic_compare_exchange_weak(&atomic, &expected, desired);
#elif defined(_OPENMP)
bool result = false;
# pragma omp critical
{
result = atomic == expected;
if (result) {
atomic = desired;
}
else {
expected = atomic;
}
}
#else // generic
bool result = false;
libxstream_lock *const lock = libxstream_lock_get(&atomic);
libxstream_lock_acquire(lock);
result = atomic == expected;
if (result) {
atomic = desired;
}
else {
expected = atomic;
}
libxstream_lock_release(lock);
#endif
return result;
}
template<typename A, typename T>
T atomic_store(A& atomic, T value)
{
T result = value;
#if defined(LIBXSTREAM_STDFEATURES)
result = std::atomic_exchange(&atomic, value);
#elif defined(_OPENMP)
# pragma omp critical
{
result = atomic;
atomic = value;
}
#else // generic
libxstream_lock_acquire(registry.lock());
result = atomic;
atomic = value;
libxstream_lock_release(registry.lock());
#endif
return result;
}
} // namespace libxstream_stream_internal
/*static*/int libxstream_stream::enqueue(libxstream_event& event, const libxstream_stream* exclude)
{
return libxstream_stream_internal::registry.enqueue(event, exclude);
}
/*static*/libxstream_stream* libxstream_stream::schedule(const libxstream_stream* exclude)
{
return libxstream_stream_internal::registry.schedule(exclude);
}
/*static*/int libxstream_stream::sync(int device)
{
return libxstream_stream_internal::registry.sync(device);
}
/*static*/int libxstream_stream::sync()
{
return libxstream_stream_internal::registry.sync();
}
libxstream_stream::libxstream_stream(int device, int priority, const char* name)
: m_device(device), m_priority(priority), m_thread(-1)
#if defined(LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
, m_handle(0) // lazy creation
, m_npartitions(0)
#endif
{
std::fill_n(m_pending, LIBXSTREAM_MAX_NTHREADS, static_cast<libxstream_signal>(0));
std::fill_n(m_queues, LIBXSTREAM_MAX_NTHREADS, static_cast<libxstream_queue*>(0));
#if defined(LIBXSTREAM_TRACE) && ((1 == ((2*LIBXSTREAM_TRACE+1)/2) && defined(LIBXSTREAM_DEBUG)) || 1 < ((2*LIBXSTREAM_TRACE+1)/2))
if (name && 0 != *name) {
const size_t length = std::min(std::char_traits<char>::length(name), sizeof(m_name) - 1);
std::copy(name, name + length, m_name);
m_name[length] = 0;
}
else {
m_name[0] = 0;
}
#else
libxstream_use_sink(name);
#endif
using namespace libxstream_stream_internal;
volatile registry_type::value_type& slot = libxstream_stream_internal::registry.allocate();
slot = this;
}
libxstream_stream::~libxstream_stream()
{
using namespace libxstream_stream_internal;
volatile registry_type::value_type *const end = registry.streams() + registry.max_nstreams();
volatile registry_type::value_type *const stream = std::find(registry.streams(), end, this);
LIBXSTREAM_ASSERT(stream != end);
*stream = 0; // unregister stream
const size_t nthreads = nthreads_active();
for (size_t i = 0; i < nthreads; ++i) {
delete m_queues[i];
}
#if defined(LIBXSTREAM_OFFLOAD) && (0 != LIBXSTREAM_OFFLOAD) && !defined(__MIC__) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
if (0 != m_handle) {
_Offload_stream_destroy(m_device, m_handle);
}
#endif
}
libxstream_signal libxstream_stream::signal() const
{
return ++libxstream_stream_internal::registry.signal(m_device);
}
int libxstream_stream::wait(libxstream_signal signal)
{
int result = LIBXSTREAM_ERROR_NONE;
LIBXSTREAM_ASYNC_BEGIN(this, m_pending, signal)
{
libxstream_signal *const pending_signals = ptr<libxstream_signal,0>();
const libxstream_signal signal = val<const libxstream_signal,1>();
const int nthreads = static_cast<int>(nthreads_active());
for (int i = 0; i < nthreads; ++i) {
const libxstream_signal pending_signal = pending_signals[i];
if (0 != pending_signal) {
#if defined(LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (0 != (2*LIBXSTREAM_ASYNC+1)/2)
if (0 <= LIBXSTREAM_ASYNC_DEVICE) {
# if defined(LIBXSTREAM_STREAM_WAIT_PAST)
const libxstream_signal wait_pending = 0 != signal ? signal : pending_signal;
# else
const libxstream_signal wait_pending = pending_signal;
# endif
# pragma offload_wait LIBXSTREAM_ASYNC_TARGET wait(wait_pending)
}
#endif
if (0 == signal) {
pending_signals[i] = 0;
}
#if defined(LIBXSTREAM_STREAM_WAIT_PAST)
else {
i = nthreads; // break
}
#endif
}
}
if (0 != signal) {
for (int i = 0; i < nthreads; ++i) {
if (signal == pending_signals[i]) {
pending_signals[i] = 0;
}
}
}
}
LIBXSTREAM_ASYNC_END(LIBXSTREAM_CALL_DEFAULT | LIBXSTREAM_CALL_WAIT, result);
return result;
}
void libxstream_stream::pending(int thread, libxstream_signal signal)
{
LIBXSTREAM_ASSERT(0 <= thread && thread < LIBXSTREAM_MAX_NTHREADS);
m_pending[thread] = signal;
}
libxstream_signal libxstream_stream::pending(int thread) const
{
LIBXSTREAM_ASSERT(0 <= thread && thread < LIBXSTREAM_MAX_NTHREADS);
const libxstream_signal signal = m_pending[thread];
return signal;
}
void libxstream_stream::enqueue(const libxstream_capture_base& work_item)
{
const int thread = this_thread_id();
LIBXSTREAM_ASSERT(thread < LIBXSTREAM_MAX_NTHREADS);
libxstream_queue *volatile *const q = m_queues + thread;
if (0 == *q) {
libxstream_lock* lock = libxstream_lock_get(q);
libxstream_lock_acquire(lock);
if (0 == *q) {
*q = new libxstream_queue;
}
libxstream_lock_release(lock);
}
LIBXSTREAM_ASSERT(0 != *q);
volatile libxstream_queue::value_type& slot = (*q)->allocate_push();
libxstream_capture_base *const item = work_item.clone();
slot = item;
if (0 != (work_item.flags() & LIBXSTREAM_CALL_WAIT)) {
while (item == slot) {
this_thread_yield();
}
}
}
libxstream_queue* libxstream_stream::queue(const libxstream_queue* exclude)
{
libxstream_queue* result = 0;
if (0 == exclude) {
result = 0 <= m_thread ? m_queues[m_thread] : 0;
if (0 == result || 0 == m_pending[m_thread] || result->empty()) {
size_t size = 0;
const int nthreads = static_cast<int>(nthreads_active());
for (int i = 0; i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
const size_t si = 0 != qi ? qi->size() : 0;
if (size < si) {
m_thread = i;
result = qi;
size = si;
}
}
}
}
else { // round-robin
const size_t nthreads = nthreads_active();
int thread = -1;
for (size_t/*-Wstrict-overflow*/ i = 0; i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (exclude != qi) {
result = qi;
thread = static_cast<int>(i);
i = nthreads; // break
}
else {
thread = static_cast<int>(i + 1);
i = nthreads; // break
}
}
if (0 <= thread) {
if (0 != result) {
for (size_t i = static_cast<size_t>(thread); i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (exclude == qi) {
thread = static_cast<int>(i + 1);
i = nthreads; // break
}
}
}
for (size_t i = static_cast<size_t>(thread); i < nthreads; ++i) {
libxstream_queue *const qi = m_queues[i];
if (0 != qi) {
result = qi;
m_thread = static_cast<int>(i);
i = nthreads; // break
}
}
}
}
return result;
}
#if defined(LIBXSTREAM_OFFLOAD) && (0 != LIBXSTREAM_OFFLOAD) && defined(LIBXSTREAM_ASYNC) && (2 == (2*LIBXSTREAM_ASYNC+1)/2)
_Offload_stream libxstream_stream::handle() const
{
const size_t nstreams = libxstream_stream_internal::registry.nstreams(m_device);
if (nstreams != m_npartitions) {
if (0 != m_handle) {
const_cast<libxstream_stream*>(this)->wait(0); // complete pending operations on old stream
_Offload_stream_destroy(m_device, m_handle);
}
// TODO: implement device discovery (number of threads)
const size_t nthreads = 224;
// TODO: implement stream priorities (weighting)
m_handle = _Offload_stream_create(m_device, static_cast<int>(nthreads / nstreams));
m_npartitions = nstreams;
}
return m_handle;
}
#endif
#if defined(LIBXSTREAM_TRACE) && ((1 == ((2*LIBXSTREAM_TRACE+1)/2) && defined(LIBXSTREAM_DEBUG)) || 1 < ((2*LIBXSTREAM_TRACE+1)/2))
const char* libxstream_stream::name() const
{
return m_name;
}
#endif
const libxstream_stream* cast_to_stream(const void* stream)
{
return static_cast<const libxstream_stream*>(stream);
}
libxstream_stream* cast_to_stream(void* stream)
{
return static_cast<libxstream_stream*>(stream);
}
const libxstream_stream* cast_to_stream(const libxstream_stream* stream)
{
return stream;
}
libxstream_stream* cast_to_stream(libxstream_stream* stream)
{
return stream;
}
const libxstream_stream* cast_to_stream(const libxstream_stream& stream)
{
return &stream;
}
libxstream_stream* cast_to_stream(libxstream_stream& stream)
{
return &stream;
}
#endif // defined(LIBXSTREAM_EXPORTED) || defined(__LIBXSTREAM)
|
/*
* Copyright 2009-2016 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define NDEBUG
// Overload of uBLAS prod function with MKL/GSL implementations
#include <votca/xtp/votca_xtp_config.h>
#include <votca/xtp/bsecoupling.h>
#include <votca/tools/linalg.h>
#include <votca/tools/constants.h>
#include <boost/format.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/banded.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/progress.hpp>
namespace votca { namespace xtp {
namespace ub = boost::numeric::ublas;
using boost::format;
void BSECoupling::Initialize(Property* options){
#if (GWBSE_DOUBLE)
LOG(logDEBUG, *_pLog) << " Compiled with full double support" << flush;
#else
LOG(logDEBUG, *_pLog) << " Compiled with float/double mixture (standard)" << flush;
#endif
std::string key = Identify();
_doSinglets=false;
_doTriplets=false;
_openmp_threads = 0;
_openmp_threads = options->get(key + ".openmp").as<int> ();
_spintype = options->get(key + ".spin").as<string> ();
if(_spintype=="all"){
_doSinglets=true;
_doTriplets=true;
}
else if(_spintype=="triplet"){
_doTriplets=true;
}
else if(_spintype=="singlet"){
_doSinglets=true;
}
else{
throw std::runtime_error((boost::format("Choice % for type not known.") % _spintype).str());
}
_degeneracy = options->get(key + ".degeneracy").as<double> ();
_levA = options->get(key + ".moleculeA.states").as<int> ();
_levB = options->get(key + ".moleculeB.states").as<int> ();
_occA = options->get(key + ".moleculeA.occLevels").as<int> ();
_occB = options->get(key + ".moleculeB.occLevels").as<int> ();
_unoccA = options->get(key + ".moleculeA.unoccLevels").as<int> ();
_unoccB = options->get(key + ".moleculeB.unoccLevels").as<int> ();
if ( options->exists(key+".moleculeA.Frenkel")) {
_FeA = options->get(key + ".moleculeA.Frenkel").as<int> ();
}
else{
_FeA=_levA;
}
if ( options->exists(key+".moleculeB.Frenkel")) {
_FeB = options->get(key + ".moleculeB.Frenkel").as<int> ();
}
else{
_FeB=_levB;
}
}
void BSECoupling::addoutput(Property *_type_summary,Orbitals* _orbitalsA,
Orbitals* _orbitalsB){
//cout << JAB_singlet<<endl;
//cout << JAB_singlet*conv::ryd2ev_f<<endl;
if (_doSinglets){
Property *_singlet_summary = &_type_summary->add("singlets","");
for (int stateA = 0; stateA < _levA ; ++stateA ) {
for (int stateB = 0; stateB <_levB ; ++stateB ) {
real JAB = getSingletCouplingElement( stateA , stateB );
//real energyAD = getSingletDimerEnergy( stateA );
//real energyBD = getSingletDimerEnergy( stateB );
Property *_coupling_summary = &_singlet_summary->add("coupling", boost::lexical_cast<string>(JAB));
real energyA = _orbitalsA->BSESingletEnergies()(stateA)*conv::ryd2ev_f;
real energyB = _orbitalsB->BSESingletEnergies()(stateB)*conv::ryd2ev_f;
_coupling_summary->setAttribute("excitonA", stateA);
_coupling_summary->setAttribute("excitonB", stateB);
_coupling_summary->setAttribute("energyA", energyA);
_coupling_summary->setAttribute("energyB", energyB);
//_coupling_summary->setAttribute("energyA_dimer", energyAD);
//_coupling_summary->setAttribute("energyB_dimer", energyBD);
}
}
}
//cout << JAB_triplet<<endl;
//cout << JAB_triplet*conv::ryd2ev_f<<endl;
if ( _doTriplets){
Property *_triplet_summary = &_type_summary->add("triplets","");
for (int stateA = 0; stateA < _levA ; ++stateA ) {
for (int stateB = 0; stateB < _levA ; ++stateB ) {
real JAB = getTripletCouplingElement( stateA , stateB );
//real energyAD = getTripletDimerEnergy( stateA );
//real energyBD = getTripletDimerEnergy( stateB );
Property *_coupling_summary = &_triplet_summary->add("coupling", boost::lexical_cast<string>(JAB));
real energyA = _orbitalsA->BSETripletEnergies()(stateA)*conv::ryd2ev_f;
real energyB = _orbitalsB->BSETripletEnergies()(stateB)*conv::ryd2ev_f;
_coupling_summary->setAttribute("excitonA", stateA);
_coupling_summary->setAttribute("excitonB", stateB);
_coupling_summary->setAttribute("energyA", energyA);
_coupling_summary->setAttribute("energyB", energyB);
//_coupling_summary->setAttribute("energyA_dimer", energyAD);
//_coupling_summary->setAttribute("energyB_dimer", energyBD);
}
}
}
}
/*
* Calculates S^{-1/2}
*/
void BSECoupling::SQRTOverlap(ub::symmetric_matrix<double> &S,
ub::matrix<double> &S2 ) {
//double (*_inv_sqrt)(double);
//_inv_sqrt = &inv_sqrt;
ub::vector<double> _eigenvalues;
ub::matrix<double> _eigenvectors;
int _size = S.size1();
_eigenvalues.resize( _size );
_eigenvectors.resize( _size, _size );
votca::tools::linalg_eigenvalues_symmetric(S, _eigenvalues, _eigenvectors);
// compute inverse sqrt of all eigenvalues
// std::transform(_eigenvalues.begin(), _eigenvalues.end(), _eigenvalues.begin(), _inv_sqrt );
// form a diagonal matrix S^{-1/2}
ub::diagonal_matrix<double> _diagS2( _eigenvalues.size(), _eigenvalues.data() );
// multiply from the left on the U
ub::matrix<double> _temp = ub::prod( _eigenvectors, _diagS2 );
// multiply from the right on the transpose U
S2 = ub::prod( _temp, ub::trans( _eigenvectors ) );
}
real BSECoupling::getSingletCouplingElement( int levelA, int levelB) {
return JAB_singlet( levelA , levelB + _levA ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getSingletDimerEnergy( int level) {
return JAB_singlet( level , level ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getTripletDimerEnergy( int level) {
return JAB_triplet( level , level ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getTripletCouplingElement( int levelA, int levelB) {
//cout << levelA<<endl;
//cout << levelB + _levA<<endl;
return JAB_triplet( levelA , levelB + _levA ) * votca::tools::conv::ryd2ev_f;
/*int _statesA = _orbitalsA->BSE;
int _statesB = _orbitalsB->getNumberOfLevels();
if ( _energy_difference != 0 ) {
std::vector<int> list_levelsA = *_orbitalsA->getDegeneracy( levelA, _energy_difference );
std::vector<int> list_levelsB = *_orbitalsA->getDegeneracy( levelB, _energy_difference );
double _JAB_sq = 0; double _JAB_one_level;
for (std::vector<int>::iterator iA = list_levelsA.begin()++; iA != list_levelsA.end(); iA++) {
for (std::vector<int>::iterator iB = list_levelsB.begin()++; iB != list_levelsB.end(); iB++) {
//cout << *iA << ':' << *iB << endl;
_JAB_one_level = _JAB->at_element( *iA - 1 , *iB -1 + _levelsA );
_JAB_sq += _JAB_one_level*_JAB_one_level ;
}
}
return sqrt(_JAB_sq / ( list_levelsA.size() * list_levelsB.size() ) ) * _conv_Hrt_eV ;
} else {
return _JAB->at_element( levelA , levelB + _levelsA ) * _conv_Ryd_eV;
}*/
// the matrix should be symmetric, could also return this element
// _JAB.at_element( _levelsA + levelB - 1 , levelA - 1 );
}
/**
* \brief evaluates electronic couplings
*
* This is a slow version with a rather large block matrix AxB
*
* @param _orbitalsA molecular orbitals of molecule A
* @param _orbitalsB molecular orbitals of molecule B
* @param _orbitalsAB molecular orbitals of the dimer AB
* @param _JAB matrix with electronic couplings
* @return false if failed
*/
bool BSECoupling::CalculateCouplings_OLD(Orbitals* _orbitalsA, Orbitals* _orbitalsB,
Orbitals* _orbitalsAB, ub::matrix<real>* _JAB) {
LOG(logDEBUG, *_pLog) << TimeStamp() << "Calculating exciton couplings" << flush;
// constructing the direct product orbA x orbB
int _basisA = _orbitalsA->getBasisSetSize();
int _basisB = _orbitalsB->getBasisSetSize();
if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {
LOG(logERROR,*_pLog) << "Basis set size is not stored in monomers" << flush;
return false;
}
// number of levels stored in monomers
int _levelsA = _orbitalsA->getNumberOfLevels();
int _levelsB = _orbitalsB->getNumberOfLevels();
boost::timer t; // start timing
double _st = t.elapsed();
// get exciton information of molecule A
ub::matrix<real>& _bseA = _orbitalsA->BSESingletCoefficients();
int _bseA_cmax = _orbitalsA->getBSEcmax();
int _bseA_cmin = _orbitalsA->getBSEcmin();
int _bseA_vmax = _orbitalsA->getBSEvmax();
int _bseA_vmin = _orbitalsA->getBSEvmin();
int _bseA_vtotal = _bseA_vmax - _bseA_vmin +1 ;
int _bseA_ctotal = _bseA_cmax - _bseA_cmin +1 ;
int _bseA_size = _bseA_vtotal * _bseA_ctotal;
int _bseA_exc = _bseA.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_exc << " excitons with dimension " << _bseA_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combA;
_combA.resize(_bseA_size,2);
int _cnt = 0;
for ( int _v = 0; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c < _bseA_ctotal; _c++){
_combA(_cnt,0) = _v;
_combA(_cnt,1) = _bseA_vtotal + _c;
_cnt++;
}
}
// get exciton information of molecule B
ub::matrix<real>& _bseB = _orbitalsB->BSESingletCoefficients();
int _bseB_cmax = _orbitalsB->getBSEcmax();
int _bseB_cmin = _orbitalsB->getBSEcmin();
int _bseB_vmax = _orbitalsB->getBSEvmax();
int _bseB_vmin = _orbitalsB->getBSEvmin();
int _bseB_vtotal = _bseB_vmax - _bseB_vmin +1 ;
int _bseB_ctotal = _bseB_cmax - _bseB_cmin +1 ;
int _bseB_size = _bseB_vtotal * _bseB_ctotal;
int _bseB_exc = _bseB.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_exc << " excitons with dimension " << _bseB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combB;
_combB.resize(_bseB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c < _bseB_ctotal; _c++){
_combB(_cnt,0) = _bseA_vtotal + _bseA_ctotal + _v;
_combB(_cnt,1) = _bseA_vtotal + _bseA_ctotal + _bseB_vtotal + _c;
_cnt++;
}
}
// get exciton information of pair AB
ub::matrix<real>& _bseAB = _orbitalsAB->BSESingletCoefficients();
int _bseAB_cmax = _orbitalsAB->getBSEcmax();
int _bseAB_cmin = _orbitalsAB->getBSEcmin();
int _bseAB_vmax = _orbitalsAB->getBSEvmax();
int _bseAB_vmin = _orbitalsAB->getBSEvmin();
int _bseAB_vtotal = _bseAB_vmax - _bseAB_vmin +1 ;
int _bseAB_ctotal = _bseAB_cmax - _bseAB_cmin +1 ;
int _bseAB_size = _bseAB_vtotal * _bseAB_ctotal;
int _bseAB_exc = _bseAB.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has " << _bseAB_exc << " excitons with dimension " << _bseAB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combAB;
_combAB.resize(_bseAB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseAB_vtotal; _v++){
for ( int _c = 0; _c < _bseAB_ctotal; _c++){
_combAB(_cnt,0) = _v;
_combAB(_cnt,1) = _bseAB_vtotal + _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << "Levels stored: Basis A[" << _levelsA << ":" << _basisA << "]"
<< " B[" << _levelsB << ":" << _basisB << "]" << flush;
// DFT levels can be reduced to those used in BSE
_levelsA = _bseA_vtotal + _bseA_ctotal;
_levelsB = _bseB_vtotal + _bseB_ctotal;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Levels used in BSE of molA: " << _bseA_vmin << " to " << _bseA_cmax << " total: " << _bseA_vtotal + _bseA_ctotal << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Levels used in BSE of molB: " << _bseB_vmin << " to " << _bseB_cmax << " total: " << _bseB_vtotal + _bseB_ctotal << flush;
if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {
LOG(logERROR,*_pLog) << "No information about number of occupied/unoccupied levels is stored" << flush;
return false;
}
// | Orbitals_A 0 | | Overlap_A |
// | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )
ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;
ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;
ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB );
LOG(logDEBUG, *_pLog) << TimeStamp() << "Constructing direct product AxB ["
<< _psi_AxB.size1() << "x"
<< _psi_AxB.size2() << "]";
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;
//ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = *_orbitalsA->getOrbitals();
// ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = *_orbitalsB->getOrbitals();
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = ub::project( *_orbitalsA->getOrbitals() , ub::range(_bseA_vmin, _bseA_cmax+1) , ub::range ( 0, _basisA ));
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = ub::project( *_orbitalsB->getOrbitals(), ub::range(_bseB_vmin, _bseB_cmax+1) , ub::range ( 0, _basisB ));
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// psi_AxB * S_AB * psi_AB
LOG(logDEBUG, *_pLog) << TimeStamp() << "Projecting monomer orbitals onto dimer ";
ub::matrix<double> _orbitalsAB_Transposed = ub::trans( *_orbitalsAB->getOrbitals() );
if ( (*_orbitalsAB->getOverlap()).size1() == 0 ) {
LOG(logERROR,*_pLog) << "Overlap matrix is not stored";
return false;
}
#ifdef OVERLAP_DEBUG
cout << "\n\t\tprod1 ["
<< (*_orbitalsAB->getOverlap()).size1() << "x" << (*_orbitalsAB->getOverlap()).size2() << "] ["
<< _orbitalsAB_Transposed.size1() << "x" << _orbitalsAB_Transposed.size2() << "] ";
#endif
ub::matrix<double> _psi_AB = ub::prod( *_orbitalsAB->getOverlap(), _orbitalsAB_Transposed );
#ifdef OVERLAP_DEBUG
cout << "\t\tprod2 ["
<< _psi_AxB.size1() << "x" << _psi_AxB.size2() << "] ["
<< _psi_AB.size1() << "x" << _psi_AB.size2() << "] ";
#endif
ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );
_psi_AB.clear();
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// row: monomer orbitals, col: dimer orbitals
ub::matrix<double> _proj_check = ub::zero_matrix<double>(_levelsA + _levelsB, _psi_AxB_dimer_basis.size2() );
for ( int i = 0; i < _levelsA + _levelsB; i++ ){
// occupied dimer levels
for ( int j = 0; j < _bseAB_vtotal ; j++ ){
_proj_check(i,0) += _psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
// empty dimer levels
for ( unsigned j = _bseAB_vtotal ; j < _psi_AxB_dimer_basis.size2() ; j++ ){
_proj_check(i,1) += _psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
//cout << " Monomer level projection (occ:virt:total)" << i << " : " << _proj_check(i,0) << " : " << _proj_check(i,1) << " : " << _proj_check(i,0) + _proj_check(i,1) << endl;
}
// some more convenient storage
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) );
}
}
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) );
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " projection of product functions(" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// now project the exciton functions (ugly!)
// ub::matrix<real> _proj_excA;
// _proj_excA.resize(_bseA_exc,_bseAB_exc);
ub::matrix<real> _temp = ub::prod( _kap, _bseAB );
ub::matrix<real> _proj_excA = ub::prod( ub::trans(_bseA), _temp);
/*
for ( unsigned i = 0 ; i < _proj_excA.size1() ; i++ ){
real check = 0.0;
for ( unsigned j = 0; j < _proj_excA.size2(); j++ ){
check += _proj_excA(i,j) * _proj_excA(i,j) ;
}
cout << " Monomer exciton " << i << " norm " << check << endl;
}
*/
_temp = ub::prod( _kbp, _bseAB );
ub::matrix<real> _proj_excB = ub::prod( ub::trans(_bseB ), _temp);
// cout << "exciton projectors: " << _proj_excA.size1() << " : " << _proj_excA.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " projection of exciton wave functions (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
ub::matrix<real> _Hamiltonian_AB = ub::zero_matrix<real>(_bseAB_size,_bseAB_size );
ub::vector<real>& _bseAB_energies = _orbitalsAB->BSESingletEnergies();
for ( int _i=0; _i<_bseAB_size; _i++){
_Hamiltonian_AB(_i,_i) = _bseAB_energies(_i);
}
ub::matrix<real> _J_dimer = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
ub::matrix<real> _S_dimer = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
// setup J
_temp = ub::prod( _Hamiltonian_AB , ub::trans(_proj_excA) );
ub::project( _J_dimer, ub::range (0, _bseA_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excA, _temp ); // J_AA = proj_excA x H x trans(proj_excA)
ub::project( _J_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excB, _temp ); // J_BA = proj_excB x H x trans(proj_excA)
_temp = ub::prod( _Hamiltonian_AB , ub::trans(_proj_excB) );
ub::project( _J_dimer, ub::range (0, _bseA_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc ) ) = ub::prod( _proj_excA, _temp ); // J_AB = proj_excA x H x trans(proj_excB)
ub::project( _J_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc) ) = ub::prod( _proj_excB, _temp ); // J_BB = proj_excB x H x trans(proj_excB)
LOG(logDEBUG, *_pLog) << TimeStamp() << " setup J (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// setup S
ub::project( _S_dimer, ub::range (0, _bseA_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excA, ub::trans(_proj_excA) ); // S_AA = proj_excA x trans(proj_excA)
ub::project( _S_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excB, ub::trans(_proj_excA)); // S_BA = proj_excB x trans(proj_excA)
ub::project( _S_dimer, ub::range (0, _bseA_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc ) ) = ub::prod( _proj_excA, ub::trans(_proj_excB)); // J_AB = proj_excA x H x trans(proj_excB)
ub::project( _S_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc) ) = ub::prod( _proj_excB, ub::trans(_proj_excB) ); // J_BB = proj_excB x H x trans(proj_excB)
LOG(logDEBUG, *_pLog) << TimeStamp() << " setup S (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
ub::vector<real> _S_eigenvalues;
linalg_eigenvalues( _S_eigenvalues, _S_dimer);
ub::matrix<real> _diagS = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
for ( int _i =0; _i < _bseA_exc + _bseB_exc ; _i++){
_diagS(_i,_i) = 1.0/sqrt(_S_eigenvalues[_i]);
}
_temp=ub::prod( _diagS, ub::trans(_S_dimer) ) ;
ub::matrix<real> _transform = ub::prod( _S_dimer, _temp );
LOG(logDEBUG, *_pLog) << TimeStamp() << " transformation matrix (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// final coupling elements
_temp=ub::prod(_J_dimer, _transform);
ub::matrix<real> _J_eff = ub::prod( _transform, _temp);
LOG(logDEBUG, *_pLog) << TimeStamp() << " effective couplings (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(0,_bseA_exc+1)*13.6058 << " and " << _J_eff(_bseA_exc+1, 0) * 13.6058 << endl;
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(0,_bseA_exc)*13.6058 << " and " << _J_eff(_bseA_exc, 0) * 13.6058 << endl;
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(1,_bseA_exc+1)*13.6058 << " and " << _J_eff(_bseA_exc+1, 1) * 13.6058 << endl;
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
LOG(logDEBUG, *_pLog) << TimeStamp() << "Done with exciton couplings" << flush;
return true;
}
/**
* \brief evaluates electronic couplings
*
* This is a different version with not diagonalized BSE Hamiltonian
*
* @param _orbitalsA molecular orbitals of molecule A
* @param _orbitalsB molecular orbitals of molecule B
* @param _orbitalsAB molecular orbitals of the dimer AB
* @param _JAB matrix with electronic couplings
* @return false if failed
*/
bool BSECoupling::CalculateCouplings(Orbitals* _orbitalsA, Orbitals* _orbitalsB, Orbitals* _orbitalsAB) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " Calculating exciton couplings" << flush;
// set the parallelization
#ifdef _OPENMP
if ( _openmp_threads > 0 ) omp_set_num_threads(_openmp_threads);
LOG(logDEBUG, *_pLog) << TimeStamp() << " Using "<< omp_get_max_threads()<<" threads" << flush;
#endif
_orbitalsAB->setCoupledExcitonsA(_levA);
_orbitalsAB->setCoupledExcitonsB(_levB);
//check to see if ordering of atoms agrees
const std::vector<QMAtom*> atomsA=_orbitalsA->QMAtoms();
const std::vector<QMAtom*> atomsB=_orbitalsB->QMAtoms();
const std::vector<QMAtom*> atomsAB=_orbitalsAB->QMAtoms();
for (unsigned i=0;i<atomsAB.size();i++){
QMAtom* dimer=atomsAB[i];
QMAtom* monomer=NULL;
if (i<atomsA.size()){
monomer=atomsA[i];
}
else if (i<atomsB.size()+atomsA.size() ){
monomer=atomsB[i-atomsA.size()];
}
else{
throw runtime_error((boost::format("Number of Atoms in dimer %3i and the two monomers A:%3i B:%3i does not agree") %atomsAB.size() %atomsA.size() %atomsB.size()).str());
}
if(monomer->type != dimer->type){
throw runtime_error("\nERROR: Atom types do not agree in dimer and monomers\n");
}
if(std::abs(monomer->x-dimer->x)>0.001 || std::abs(monomer->y-dimer->y)>0.001 || std::abs(monomer->z-dimer->z)>0.001){
LOG(logERROR,*_pLog) << "======WARNING=======\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\n " << flush;
break;
}
}
// constructing the direct product orbA x orbB
int _basisA = _orbitalsA->getBasisSetSize();
int _basisB = _orbitalsB->getBasisSetSize();
if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {
LOG(logERROR,*_pLog) << "Basis set size is not stored in monomers" << flush;
return false;
}
// number of levels stored in monomers
int _levelsA = _orbitalsA->getNumberOfLevels();
int _levelsB = _orbitalsB->getNumberOfLevels();
boost::timer t; // start timing
//double _st = t.elapsed();
// get exciton information of molecule A
int _bseA_cmax = _orbitalsA->getBSEcmax();
int _bseA_cmin = _orbitalsA->getBSEcmin();
int _bseA_vmax = _orbitalsA->getBSEvmax();
int _bseA_vmin = _orbitalsA->getBSEvmin();
int _bseA_vtotal = _bseA_vmax - _bseA_vmin +1 ;
int _bseA_ctotal = _bseA_cmax - _bseA_cmin +1 ;
int _bseA_size = _bseA_vtotal * _bseA_ctotal;
int _bseA_singlet_exc = _orbitalsA->BSESingletCoefficients().size2();
int _bseA_triplet_exc = _orbitalsA->BSETripletCoefficients().size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_singlet_exc << " singlet excitons with dimension " << _bseA_size << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_triplet_exc << " triplet excitons with dimension " << _bseA_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combA;
_combA.resize(_bseA_size,2);
int _cnt = 0;
for ( int _v = 0; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c < _bseA_ctotal; _c++){
_combA(_cnt,0) = _v;
_combA(_cnt,1) = _bseA_vtotal + _c;
_cnt++;
}
}
// get exciton information of molecule B
int _bseB_cmax = _orbitalsB->getBSEcmax();
int _bseB_cmin = _orbitalsB->getBSEcmin();
int _bseB_vmax = _orbitalsB->getBSEvmax();
int _bseB_vmin = _orbitalsB->getBSEvmin();
int _bseB_vtotal = _bseB_vmax - _bseB_vmin +1 ;
int _bseB_ctotal = _bseB_cmax - _bseB_cmin +1 ;
int _bseB_size = _bseB_vtotal * _bseB_ctotal;
int _bseB_singlet_exc = _orbitalsB->BSESingletCoefficients().size2();
int _bseB_triplet_exc = _orbitalsB->BSETripletCoefficients().size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_singlet_exc << " singlet excitons with dimension " << _bseB_size << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_triplet_exc << " triplet excitons with dimension " << _bseB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combB;
_combB.resize(_bseB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c < _bseB_ctotal; _c++){
_combB(_cnt,0) = _bseA_vtotal + _bseA_ctotal + _v;
_combB(_cnt,1) = _bseA_vtotal + _bseA_ctotal + _bseB_vtotal + _c;
_cnt++;
}
}
if(_levA>_bseA_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of excitons you want is greater than stored for molecule B. Setting to max number available" << flush;
_levA=_bseA_singlet_exc;
}
if(_levB>_bseB_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of excitons you want is greater than stored for molecule B. Setting to max number available" << flush;
_levB=_bseB_singlet_exc;
}
if(_FeA>_bseA_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of Frenkel states you want is greater than stored for molecule B. Setting to max number available" << flush;
_FeA=_bseA_singlet_exc;
}
if(_FeB>_bseB_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of Frenkel states you want is greater than stored for molecule B. Setting to max number available" << flush;
_FeB=_bseB_singlet_exc;
}
if(_unoccA>_bseA_ctotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of occupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE" << flush;
_unoccA=_bseA_ctotal;
}
else if (_unoccA<0){
_unoccA=_bseA_ctotal;
}
if(_unoccB>_bseB_ctotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of occupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE" << flush;
_unoccB=_bseB_ctotal;
}
else if (_unoccB<0){
_unoccB=_bseB_ctotal;
}
if(_occA>_bseA_vtotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of unoccupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE" << flush;
_occA=_bseA_vtotal;
}
else if (_occA<0){
_occA=_bseA_vtotal;
}
if(_occB>_bseB_vtotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of unoccupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE" << flush;
_occB=_bseB_vtotal;
}else if (_occB<0){
_occB=_bseB_vtotal;
}
// get exciton information of pair AB
int _bseAB_cmax = _orbitalsAB->getBSEcmax();
int _bseAB_cmin = _orbitalsAB->getBSEcmin();
int _bseAB_vmax = _orbitalsAB->getBSEvmax();
int _bseAB_vmin = _orbitalsAB->getBSEvmin();
int _bseAB_vtotal = _bseAB_vmax - _bseAB_vmin +1 ;
int _bseAB_ctotal = _bseAB_cmax - _bseAB_cmin +1 ;
int _bseAB_size = _bseAB_vtotal * _bseAB_ctotal;
// check if electron-hole interaction matrices are stored
if ( ! _orbitalsAB->hasEHinteraction() ){
LOG(logERROR,*_pLog) << "BSE EH int not stored in dimer " << flush;
return false;
}
ub::matrix<real>& _eh_d = _orbitalsAB->eh_d();
ub::matrix<real>& _eh_x = _orbitalsAB->eh_x();
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has BSE EH interaction (direct) with dimension " << _eh_d.size1() << " x " << _eh_d.size2() << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has BSE EH interaction (exchange) with dimension " << _eh_x.size1() << " x " << _eh_x.size2() << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combAB;
_combAB.resize(_bseAB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseAB_vtotal; _v++){
for ( int _c = 0; _c < _bseAB_ctotal; _c++){
//_combAB(_cnt,0) = _v;
//_combAB(_cnt,1) = _bseAB_vtotal + _c;
_combAB(_cnt,0) = _bseAB_vmin + _v;
_combAB(_cnt,1) = _bseAB_vmin + _bseAB_vtotal + _c;
_cnt++;
}
}
// DFT levels of monomers can be reduced to those used in BSE
_levelsA = _bseA_vtotal + _bseA_ctotal;
_levelsB = _bseB_vtotal + _bseB_ctotal;
LOG(logDEBUG, *_pLog) << TimeStamp() << " levels used in BSE of molA: " << _bseA_vmin << " to " << _bseA_cmax << " total: " << _bseA_vtotal + _bseA_ctotal << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " levels used in BSE of molB: " << _bseB_vmin << " to " << _bseB_cmax << " total: " << _bseB_vtotal + _bseB_ctotal << flush;
if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {
LOG(logERROR,*_pLog) << "No information about number of occupied/unoccupied levels is stored" << flush;
return false;
}
// | Orbitals_A 0 | | Overlap_A |
// | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )
ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;
ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;
ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB );
// constructing merged orbitals
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = ub::project( *_orbitalsA->getOrbitals() , ub::range(_bseA_vmin, _bseA_cmax+1) , ub::range ( 0, _basisA ));
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = ub::project( *_orbitalsB->getOrbitals(), ub::range(_bseB_vmin, _bseB_cmax+1) , ub::range ( 0, _basisB ));
// psi_AxB * S_AB * psi_AB
LOG(logDEBUG, *_pLog) << TimeStamp() << " projecting monomer onto dimer orbitals" << flush;
ub::matrix<double> _orbitalsAB_Transposed = ub::trans( *_orbitalsAB->getOrbitals() );
if ( (*_orbitalsAB->getOverlap()).size1() == 0 ) {
LOG(logERROR,*_pLog) << "Overlap matrix is not stored";
return false;
}
ub::matrix<double> _psi_AB = ub::prod( *_orbitalsAB->getOverlap(), _orbitalsAB_Transposed );
ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );
_psi_AB.clear();
//cout<< "_psi_AxB_dimer"<<endl;
unsigned int LevelsA = _levelsA;
for (unsigned i=0;i<_psi_AxB_dimer_basis.size1();i++){
double mag=0.0;
for (unsigned j=0;j<_psi_AxB_dimer_basis.size2();j++){
mag+=_psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
if (mag<0.95){
int monomer = 0;
int level = 0;
if ( i < LevelsA ) {
monomer = 1;
level = _bseA_vmin + i;
} else {
monomer = 2;
level = _bseB_vmin + i -_levelsA;
}
LOG(logERROR,*_pLog) << "\nERROR: " << i << " Projection of orbital " << level << " of monomer " << monomer << " on dimer is insufficient,mag="<<mag<<" maybe the orbital order is screwed up, otherwise increase dimer basis.\n"<<flush;
}
}
//exit(0);
// _psi_AxB_dimer_basis = T in notes, dimension ( LA + LB, LD)
// cout << "Size of _psi_AxB_dimer_basis " << _psi_AxB_dimer_basis.size1() << " : " << _psi_AxB_dimer_basis.size2() << flush;
//notation AB is CT states with A+B-, BA is the counterpart
//Setting up CT-states:
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up CT-states" << flush;
//Number of A+B- states
int noAB=_occA*_unoccB;
//Number of A-B+ states
int noBA=_unoccA*_occB;
ub::matrix<int> comb_CTAB;
comb_CTAB.resize(noAB,2);
_cnt = 0;
// iterate A over occupied, B over unoccupied
int v_start=_bseA_vtotal-_occA;
for ( int _v = v_start; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c <_unoccB; _c++){
comb_CTAB(_cnt,0) =_v;
comb_CTAB(_cnt,1) = _bseA_vtotal+_bseA_ctotal+_bseB_vtotal + _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() <<" "<<noAB <<" CT states A+B- created" << flush;
//cout << "comb_CTAB" << endl;
//cout << comb_CTAB << endl;
ub::matrix<int> comb_CTBA;
comb_CTBA.resize(noBA,2);
_cnt = 0;
// iterate A over unoccupied, B over occupied
v_start=_bseB_vtotal-_occB;
for ( int _v = v_start; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c <_unoccA; _c++){
comb_CTBA(_cnt,0) =_bseA_vtotal+_bseA_ctotal+_v;
comb_CTBA(_cnt,1) = _bseA_vtotal+ _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() <<" "<<noBA <<" CT states B+A- created" << flush;
//cout << "comb_CTBA" << endl;
//cout << comb_CTBA << endl;
// these 4 matrixes, matrix(i,j) contains the j-th dimer MO component of the i-th excitation
ub::matrix<real> ctAB;
ctAB.resize(noAB,_bseAB_size);
#pragma omp parallel for
for ( int _i_CT = 0 ; _i_CT < noAB ; _i_CT++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
ctAB(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTAB(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTAB(_i_CT,1), _combAB( _i_bseAB,1) );
}
}
ub::matrix<real>ctBA;
ctBA.resize(noBA,_bseAB_size);
#pragma omp parallel for
for ( int _i_CT = 0 ; _i_CT < noBA ; _i_CT++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
ctBA(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTBA(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTBA(_i_CT,1), _combAB( _i_bseAB,1) );
}
}
// some more convenient storage
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
#pragma omp parallel for
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) );
}
}
//ub::matrix<real> check;
//check.resize(_bseA_size,_bseA_size);
//check= ub::prod(_kap,ub::trans(_kap));
//cout << "check"<<endl;
//cout <<ub::project(check, ub::range (0, 10 ), ub::range ( 0, 10 ) ) <<endl;
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
#pragma omp parallel for
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) );
}
}
// Same routines but also take <v|c'> <c|v'> projections into account
/*
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) )+
_psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,1) ) ;
}
}
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) )+
_psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,1) );
}
}
*/
LOG(logDEBUG, *_pLog) << TimeStamp() << " construct projection of product functions " << flush;
// cout << "Size of _kap " << _kap.size1() << " : " << _kap.size2() << "\n" << flush;
// cout << "Size of _kbp " << _kbp.size1() << " : " << _kbp.size2() << "\n" << flush;
// now the different spin types
if ( _doSinglets){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Evaluating singlets" << flush;
// get singlet BSE Hamiltonian from _orbitalsAB
ub::matrix<real> _Hamiltonian_AB = _eh_d + 2.0 * _eh_x;
const ub::matrix<real>& _bseA = ub::project( _orbitalsA->BSESingletCoefficients(),
ub::range (0, _orbitalsA->BSESingletCoefficients().size1() ), ub::range ( 0, _FeA ) );
const ub::matrix<real>& _bseB = ub::project( _orbitalsB->BSESingletCoefficients(),
ub::range (0, _orbitalsB->BSESingletCoefficients().size1() ), ub::range ( 0, _FeB ) );
// cout << "Size of _Hamiltonian_AB " << _Hamiltonian_AB.size1() << " : " << _Hamiltonian_AB.size2() << flush;
// cout << "Size of _bseA " << _bseA.size1() << " : " << _bseA.size2() << flush;
// cout << "Size of _bseB " << _bseB.size1() << " : " << _bseB.size2() << flush;
bool _singlets = ProjectExcitons( _kap, _kbp,ctAB,ctBA, _bseA, _bseB, _Hamiltonian_AB, JAB_singlet);
if ( _singlets ) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated singlet couplings " << flush;
}
/*
// diagonalize the effective Hamiltonian?
ub::vector<real> _coupled_energies;
ub::matrix<real> _coupled_coefficients;
std::vector< std::vector<double> >& _free_dipolesA = _orbitalsA->TransitionDipoles();
std::vector< std::vector<double> >& _free_dipolesB = _orbitalsB->TransitionDipoles();
linalg_eigenvalues(*_JAB_singlet, _coupled_energies, _coupled_coefficients,_JAB_singlet->size1() );
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated EVs of coupling matrix " << flush;
cout << "\n" << endl;
for ( int i =0 ; i< _JAB_singlet->size1(); i++){
std::vector<double> tdipole(3,0.0);
for ( int j = 0; j < 50; j++){
tdipole[0] += _coupled_coefficients(j,i)*_free_dipolesA[j][0] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][0];
tdipole[1] += _coupled_coefficients(j,i)*_free_dipolesA[j][1] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][1];
tdipole[2] += _coupled_coefficients(j,i)*_free_dipolesA[j][2] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][2];
}
double tdipole_strength = tdipole[0]*tdipole[0] + tdipole[1]*tdipole[1] + tdipole[2]*tdipole[2];
double oscillator_strength = tdipole_strength * _coupled_energies(i) /3.0;
LOG(logINFO, *_pLog) << (format(" S = %1$4d Omega = %2$+1.4f eV lamdba = %3$+3.2f nm ") % (i + 1) % (13.6058 * _coupled_energies(i)) % (1240.0/(13.6058 * _coupled_energies(i))) ).str() << flush;
LOG(logINFO, *_pLog) << (format(" TrDipole length gauge dx = %1$+1.4f dy = %2$+1.4f dz = %3$+1.4f |d|^2 = %4$+1.4f f = %5$+1.4f") % (tdipole[0]) % (tdipole[1]) % (tdipole[2]) % (tdipole_strength) % (oscillator_strength)).str() << flush;
for (int _i_bse = 0; _i_bse < _JAB_singlet->size1(); _i_bse++) {
// if contribution is larger than 0.2, print
double _weight = pow(_coupled_coefficients(_i_bse, i), 2);
if (_weight > 0.2) {
if ( _i_bse < 50) {
LOG(logINFO, *_pLog) << (format(" EXCITON A %1$-3d : %2$3.1f%%") % _i_bse % (100.0 * _weight)).str() << flush;
} else
{
LOG(logINFO, *_pLog) << (format(" EXCITON B %1$-3d : %2$3.1f%%") % (_i_bse-50) % (100.0 * _weight)).str() << flush;
}
}
}
LOG(logINFO, *_pLog) << (format(" ")).str() << flush;
cout << " E" << i << " : " << _coupled_energies(i)*13.605 << " TD " << tdipole[0] << " " << tdipole[1] << " " << tdipole[2] << endl;
}
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _JAB_singlet->at_element(0,_bseA_singlet_exc)*13.6058 << " and " << _JAB_singlet->at_element(_bseA_singlet_exc, 0) * 13.6058 << endl;
*/
}
if ( _doTriplets){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Evaluating triplets" << flush;
// get triplet BSE Hamiltonian from _orbitalsAB
ub::matrix<real> _Hamiltonian_AB = _eh_d;
//ub::matrix<real>& _bseA= _orbitalsA->BSETripletCoefficients();
const ub::matrix<real>& _bseA = ub::project( _orbitalsA->BSETripletCoefficients(),
ub::range (0, _orbitalsA->BSETripletCoefficients().size1() ), ub::range ( 0, _FeA ) );
const ub::matrix<real>& _bseB = ub::project( _orbitalsB->BSETripletCoefficients(),
ub::range (0, _orbitalsB->BSETripletCoefficients().size1() ), ub::range ( 0, _FeB ) );
//ub::matrix<real>& _bseB = _orbitalsB->BSETripletCoefficients();
bool _triplets = ProjectExcitons( _kap, _kbp,ctAB,ctBA, _bseA, _bseB, _Hamiltonian_AB, JAB_triplet);
if ( _triplets ) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated triplet couplings " << flush;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Done with exciton couplings" << flush;
return true;
};
bool BSECoupling::ProjectExcitons(const ub::matrix<real>& _kap,const ub::matrix<real>& _kbp,
const ub::matrix<real>& ctAB,const ub::matrix<real>& ctBA,
const ub::matrix<real>& _bseA, const ub::matrix<real>& _bseB,
const ub::matrix<real>& _H, ub::matrix<real>& _J){
//cout << " Dimensions of _bseA " << _bseA.size1() << " : " << _bseA.size2() << endl;
// get projection of monomer excitons on dimer product functions
ub::matrix<real> _proj_excA = ub::prod( ub::trans( _bseA ), _kap);
ub::matrix<real> _proj_excB = ub::prod( ub::trans( _bseB ), _kbp);
//cout << "_proj_excA"<<_proj_excA.size1()<<"x"<<_proj_excA.size2()<<endl;
//cout << "_proj_excB"<<_proj_excB.size1()<<"x"<<_proj_excB.size2()<<endl;
//cout << "_ctAB"<<ctAB.size1()<<"x"<<ctAB.size2()<<endl;
//cout << "_ctBA"<<ctBA.size1()<<"x"<<ctBA.size2()<<endl;
unsigned _bseA_exc = _proj_excA.size1();
unsigned _bseB_exc = _proj_excB.size1();
unsigned _bse_exc=_bseA_exc+_bseB_exc;
_J=ub::zero_matrix<real>(_bse_exc,_bse_exc);
unsigned _ctAB=ctAB.size1();
unsigned _ctBA=ctBA.size1();
unsigned _ct=_ctAB+_ctBA;
unsigned nobasisfunc=_H.size1();
//cout << _ctAB <<_ctBA<<endl;
//ub::matrix<double> _J_dimer = ub::zero_matrix<double>( _bse_exc +_ct, _bse_exc+_ct );
//ub::matrix<double> _S_dimer = ub::zero_matrix<double>( _bse_exc +_ct, _bse_exc +_ct);
//cout << _J_dimer.size1()<< " : "<<_J_dimer.size2()<<endl;
//cout << _S_dimer.size1()<< " : "<<_S_dimer.size2()<<endl;
LOG(logDEBUG, *_pLog) << TimeStamp() << " casting Hamiltonian to double " << flush;
ub::matrix<double> projection =ub::zero_matrix<double>(_bse_exc+_ct,nobasisfunc);
ub::matrix<double> Htemp=_H;
LOG(logDEBUG, *_pLog) << TimeStamp() << " merging projections into one vector " << flush;
ub::project(projection, ub::range ( 0, _bseA_exc ),ub::range (0, nobasisfunc ) )=_proj_excA;
ub::project(projection, ub::range ( _bseA_exc, _bse_exc ),ub::range (0, nobasisfunc ) )=_proj_excB;
if(_ctAB>0){
ub::project(projection, ub::range ( _bse_exc , _bse_exc+_ctAB ) ,ub::range (0,nobasisfunc ) )=ctAB;
}
if(_ctBA>0){
ub::project(projection, ub::range ( _bse_exc+_ctAB, _bse_exc+_ct ),ub::range (0, nobasisfunc ) )=ctBA;
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up coupling matrix size "<< _bse_exc +_ct<<"x"<<_bse_exc +_ct << flush;
// matrix _J
// E_A J_AB J_A_ABCT J_A_BACT
// J_BA E_B J_B_ABCT J_B_BACT
// J_ABCT_A J_ABCT_B E_ABCT J_ABCT_BACT
// J_BACT_A J_BACT_B J_BACT_ABCT E_BACT
// I think this only works for hermitian/symmetric H so only in TDA
// setup J
ub::matrix<double> _temp=ub::prod(Htemp,ub::trans(projection));
ub::matrix<double> _J_dimer=ub::prod(projection,_temp);
Htemp.resize(0,0);
_temp.resize(0,0);
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up overlap matrix size "<< _bse_exc +_ct<<"x"<<_bse_exc +_ct << flush;
// setup S
ub::matrix<double> _S_dimer=ub::prod(projection,ub::trans(projection));
//cout << "_J_dimer"<<endl;
//cout << _J_dimer<<endl;
//cout << "_S_dimer"<<endl;
//cout << _S_dimer<<endl;
//LOG(logDEBUG, *_pLog) << TimeStamp() << " Diagonlaize overlap "<< flush;
//ub::vector<double> _S_eigenvalues;
//cout << "_J_ortho"<<endl;
//cout << _J_dimer<<endl;
//linalg_eigenvalues(_S_eigenvalues,_S_dimer);
//LOG(logDEBUG, *_pLog) << TimeStamp() << " done "<< flush;
double small=linalg_loewdin(_J_dimer,_S_dimer);
LOG(logDEBUG, *_pLog) << TimeStamp() << " Smallest value of dimer overlapmatrix is "<< small<< flush;
ub::vector<double> _J_eigenvalues;
//cout << "_J_ortho"<<endl;
//cout << _J_dimer<<endl;
linalg_eigenvalues(_J_eigenvalues,_J_dimer);
//cout << "_Eigenvectors"<<endl;
//cout << _J_dimer<<endl;
//cout << "_J_eigenvalues"<< endl;
//cout << _J_eigenvalues<< endl;
//Calculate projection on subspace for every pair of excitons separately
for (int stateA=0;stateA<_levA; stateA++){
for (int stateB=0;stateB<_levB; stateB++){
int stateBd=stateB+_bseA_exc;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Calculating coupling between exciton A"<< stateA+1<<" and exciton B"<<stateB+1 << flush;
std::vector<unsigned> index;
for (unsigned i = 0; i < _bse_exc+_ct; i++) {
if (i == unsigned(stateA) || i == unsigned(stateBd)) {
double close = 0.0;
unsigned ind = 0;
//row
for (unsigned j = 0; j < _bse_exc+_ct; j++) {
bool check = true;
// if index i is already in index
// should not happen but if one vector was similar to two others.
for (unsigned l = 0; l < index.size(); l++) {
if (j == index[l]) {
check = false;
break;
}
}
if (check && std::abs(_J_dimer(i, j)) > close) {
ind = j;
close = std::abs(_J_dimer(i, j));
}
}
index.push_back(ind);
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Order is: [Initial state n->nth eigenvalue]"<<flush;
LOG(logDEBUG, *_pLog) << " A" << stateA+1<<":"<<stateA+1<<"->"<<index[0]+1<<" " ;
LOG(logDEBUG, *_pLog) << " B" << stateB+1<<":"<<stateBd+1<<"->"<<index[1]+1<<" "<<flush ;
//setting up transformation matrix _T and diagonal matrix _E for the eigenvalues;
ub::matrix<double> _E=ub::zero_matrix<double>(2,2);
ub::matrix<double> _T=ub::zero_matrix<double>(2,2);
ub::matrix<double> _Tinv;
//find the eigenvectors which are most similar to the initial states
//row
for (unsigned i = 0; i < 2; i++) {
unsigned k=index[i];
double normr =1/std::sqrt(_J_dimer(stateA, k)*_J_dimer(stateA, k)+_J_dimer(stateBd, k)*_J_dimer(stateBd, k)) ;
_T(i,0 ) = _J_dimer(stateA,k)* normr;
_T(i,1 ) = _J_dimer(stateBd,k)*normr;
_E(i,i)=_J_eigenvalues(k);
}
//Transformation TET-1
linalg_invert(_T,_Tinv);
//cout << ub::prod(_T,_Tinv)<<endl;
_temp=ub::prod(_T,_E);
ub::matrix<double> _J_small=ub::prod(_temp,_Tinv);
_J(stateA,stateBd)=_J_small(0,1);
//_J(stateA,stateBd)=_J_small(0,0);
// _J(stateBd,stateBd)=_J_small(1,1);
_J(stateBd,stateA)=_J_small(1,0);
//cout << _temp2<<endl;
//cout << _J<<endl;
//cout <<_J_small*conv::ryd2ev_f<<endl;
}
}
return true;
}
}}
Revert ":q"
This reverts commit aa36d578e9763764d18dcfe1cce71dc69f358225.
/*
* Copyright 2009-2016 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define NDEBUG
// Overload of uBLAS prod function with MKL/GSL implementations
#include <votca/xtp/votca_xtp_config.h>
#include <votca/xtp/bsecoupling.h>
#include <votca/tools/linalg.h>
#include <votca/tools/constants.h>
#include <boost/format.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/banded.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/progress.hpp>
namespace votca { namespace xtp {
namespace ub = boost::numeric::ublas;
using boost::format;
void BSECoupling::Initialize(Property* options){
#if (GWBSE_DOUBLE)
LOG(logDEBUG, *_pLog) << " Compiled with full double support" << flush;
#else
LOG(logDEBUG, *_pLog) << " Compiled with float/double mixture (standard)" << flush;
#endif
std::string key = Identify();
_doSinglets=false;
_doTriplets=false;
_openmp_threads = 0;
if ( options->exists( key + ".openmp") ) {
_openmp_threads = options->get(key + ".openmp").as<int> ();
}
_spintype = options->get(key + ".spin").as<string> ();
if(_spintype=="all"){
_doSinglets=true;
_doTriplets=true;
}
else if(_spintype=="triplet"){
_doTriplets=true;
}
else if(_spintype=="singlet"){
_doSinglets=true;
}
else{
throw std::runtime_error((boost::format("Choice % for type not known.") % _spintype).str());
}
_degeneracy = options->get(key + ".degeneracy").as<double> ();
_levA = options->get(key + ".moleculeA.states").as<int> ();
_levB = options->get(key + ".moleculeB.states").as<int> ();
_occA = options->get(key + ".moleculeA.occLevels").as<int> ();
_occB = options->get(key + ".moleculeB.occLevels").as<int> ();
_unoccA = options->get(key + ".moleculeA.unoccLevels").as<int> ();
_unoccB = options->get(key + ".moleculeB.unoccLevels").as<int> ();
if ( options->exists(key+".moleculeA.Frenkel")) {
_FeA = options->get(key + ".moleculeA.Frenkel").as<int> ();
}
else{
_FeA=_levA;
}
if ( options->exists(key+".moleculeB.Frenkel")) {
_FeB = options->get(key + ".moleculeB.Frenkel").as<int> ();
}
else{
_FeB=_levB;
}
}
void BSECoupling::addoutput(Property *_type_summary,Orbitals* _orbitalsA,
Orbitals* _orbitalsB){
//cout << JAB_singlet<<endl;
//cout << JAB_singlet*conv::ryd2ev_f<<endl;
if (_doSinglets){
Property *_singlet_summary = &_type_summary->add("singlets","");
for (int stateA = 0; stateA < _levA ; ++stateA ) {
for (int stateB = 0; stateB <_levB ; ++stateB ) {
real JAB = getSingletCouplingElement( stateA , stateB );
//real energyAD = getSingletDimerEnergy( stateA );
//real energyBD = getSingletDimerEnergy( stateB );
Property *_coupling_summary = &_singlet_summary->add("coupling", boost::lexical_cast<string>(JAB));
real energyA = _orbitalsA->BSESingletEnergies()(stateA)*conv::ryd2ev_f;
real energyB = _orbitalsB->BSESingletEnergies()(stateB)*conv::ryd2ev_f;
_coupling_summary->setAttribute("excitonA", stateA);
_coupling_summary->setAttribute("excitonB", stateB);
_coupling_summary->setAttribute("energyA", energyA);
_coupling_summary->setAttribute("energyB", energyB);
//_coupling_summary->setAttribute("energyA_dimer", energyAD);
//_coupling_summary->setAttribute("energyB_dimer", energyBD);
}
}
}
//cout << JAB_triplet<<endl;
//cout << JAB_triplet*conv::ryd2ev_f<<endl;
if ( _doTriplets){
Property *_triplet_summary = &_type_summary->add("triplets","");
for (int stateA = 0; stateA < _levA ; ++stateA ) {
for (int stateB = 0; stateB < _levA ; ++stateB ) {
real JAB = getTripletCouplingElement( stateA , stateB );
//real energyAD = getTripletDimerEnergy( stateA );
//real energyBD = getTripletDimerEnergy( stateB );
Property *_coupling_summary = &_triplet_summary->add("coupling", boost::lexical_cast<string>(JAB));
real energyA = _orbitalsA->BSETripletEnergies()(stateA)*conv::ryd2ev_f;
real energyB = _orbitalsB->BSETripletEnergies()(stateB)*conv::ryd2ev_f;
_coupling_summary->setAttribute("excitonA", stateA);
_coupling_summary->setAttribute("excitonB", stateB);
_coupling_summary->setAttribute("energyA", energyA);
_coupling_summary->setAttribute("energyB", energyB);
//_coupling_summary->setAttribute("energyA_dimer", energyAD);
//_coupling_summary->setAttribute("energyB_dimer", energyBD);
}
}
}
}
/*
* Calculates S^{-1/2}
*/
void BSECoupling::SQRTOverlap(ub::symmetric_matrix<double> &S,
ub::matrix<double> &S2 ) {
//double (*_inv_sqrt)(double);
//_inv_sqrt = &inv_sqrt;
ub::vector<double> _eigenvalues;
ub::matrix<double> _eigenvectors;
int _size = S.size1();
_eigenvalues.resize( _size );
_eigenvectors.resize( _size, _size );
votca::tools::linalg_eigenvalues_symmetric(S, _eigenvalues, _eigenvectors);
// compute inverse sqrt of all eigenvalues
// std::transform(_eigenvalues.begin(), _eigenvalues.end(), _eigenvalues.begin(), _inv_sqrt );
// form a diagonal matrix S^{-1/2}
ub::diagonal_matrix<double> _diagS2( _eigenvalues.size(), _eigenvalues.data() );
// multiply from the left on the U
ub::matrix<double> _temp = ub::prod( _eigenvectors, _diagS2 );
// multiply from the right on the transpose U
S2 = ub::prod( _temp, ub::trans( _eigenvectors ) );
}
real BSECoupling::getSingletCouplingElement( int levelA, int levelB) {
return JAB_singlet( levelA , levelB + _levA ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getSingletDimerEnergy( int level) {
return JAB_singlet( level , level ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getTripletDimerEnergy( int level) {
return JAB_triplet( level , level ) * votca::tools::conv::ryd2ev_f;
}
real BSECoupling::getTripletCouplingElement( int levelA, int levelB) {
//cout << levelA<<endl;
//cout << levelB + _levA<<endl;
return JAB_triplet( levelA , levelB + _levA ) * votca::tools::conv::ryd2ev_f;
/*int _statesA = _orbitalsA->BSE;
int _statesB = _orbitalsB->getNumberOfLevels();
if ( _energy_difference != 0 ) {
std::vector<int> list_levelsA = *_orbitalsA->getDegeneracy( levelA, _energy_difference );
std::vector<int> list_levelsB = *_orbitalsA->getDegeneracy( levelB, _energy_difference );
double _JAB_sq = 0; double _JAB_one_level;
for (std::vector<int>::iterator iA = list_levelsA.begin()++; iA != list_levelsA.end(); iA++) {
for (std::vector<int>::iterator iB = list_levelsB.begin()++; iB != list_levelsB.end(); iB++) {
//cout << *iA << ':' << *iB << endl;
_JAB_one_level = _JAB->at_element( *iA - 1 , *iB -1 + _levelsA );
_JAB_sq += _JAB_one_level*_JAB_one_level ;
}
}
return sqrt(_JAB_sq / ( list_levelsA.size() * list_levelsB.size() ) ) * _conv_Hrt_eV ;
} else {
return _JAB->at_element( levelA , levelB + _levelsA ) * _conv_Ryd_eV;
}*/
// the matrix should be symmetric, could also return this element
// _JAB.at_element( _levelsA + levelB - 1 , levelA - 1 );
}
/**
* \brief evaluates electronic couplings
*
* This is a slow version with a rather large block matrix AxB
*
* @param _orbitalsA molecular orbitals of molecule A
* @param _orbitalsB molecular orbitals of molecule B
* @param _orbitalsAB molecular orbitals of the dimer AB
* @param _JAB matrix with electronic couplings
* @return false if failed
*/
bool BSECoupling::CalculateCouplings_OLD(Orbitals* _orbitalsA, Orbitals* _orbitalsB,
Orbitals* _orbitalsAB, ub::matrix<real>* _JAB) {
LOG(logDEBUG, *_pLog) << TimeStamp() << "Calculating exciton couplings" << flush;
// constructing the direct product orbA x orbB
int _basisA = _orbitalsA->getBasisSetSize();
int _basisB = _orbitalsB->getBasisSetSize();
if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {
LOG(logERROR,*_pLog) << "Basis set size is not stored in monomers" << flush;
return false;
}
// number of levels stored in monomers
int _levelsA = _orbitalsA->getNumberOfLevels();
int _levelsB = _orbitalsB->getNumberOfLevels();
boost::timer t; // start timing
double _st = t.elapsed();
// get exciton information of molecule A
ub::matrix<real>& _bseA = _orbitalsA->BSESingletCoefficients();
int _bseA_cmax = _orbitalsA->getBSEcmax();
int _bseA_cmin = _orbitalsA->getBSEcmin();
int _bseA_vmax = _orbitalsA->getBSEvmax();
int _bseA_vmin = _orbitalsA->getBSEvmin();
int _bseA_vtotal = _bseA_vmax - _bseA_vmin +1 ;
int _bseA_ctotal = _bseA_cmax - _bseA_cmin +1 ;
int _bseA_size = _bseA_vtotal * _bseA_ctotal;
int _bseA_exc = _bseA.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_exc << " excitons with dimension " << _bseA_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combA;
_combA.resize(_bseA_size,2);
int _cnt = 0;
for ( int _v = 0; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c < _bseA_ctotal; _c++){
_combA(_cnt,0) = _v;
_combA(_cnt,1) = _bseA_vtotal + _c;
_cnt++;
}
}
// get exciton information of molecule B
ub::matrix<real>& _bseB = _orbitalsB->BSESingletCoefficients();
int _bseB_cmax = _orbitalsB->getBSEcmax();
int _bseB_cmin = _orbitalsB->getBSEcmin();
int _bseB_vmax = _orbitalsB->getBSEvmax();
int _bseB_vmin = _orbitalsB->getBSEvmin();
int _bseB_vtotal = _bseB_vmax - _bseB_vmin +1 ;
int _bseB_ctotal = _bseB_cmax - _bseB_cmin +1 ;
int _bseB_size = _bseB_vtotal * _bseB_ctotal;
int _bseB_exc = _bseB.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_exc << " excitons with dimension " << _bseB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combB;
_combB.resize(_bseB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c < _bseB_ctotal; _c++){
_combB(_cnt,0) = _bseA_vtotal + _bseA_ctotal + _v;
_combB(_cnt,1) = _bseA_vtotal + _bseA_ctotal + _bseB_vtotal + _c;
_cnt++;
}
}
// get exciton information of pair AB
ub::matrix<real>& _bseAB = _orbitalsAB->BSESingletCoefficients();
int _bseAB_cmax = _orbitalsAB->getBSEcmax();
int _bseAB_cmin = _orbitalsAB->getBSEcmin();
int _bseAB_vmax = _orbitalsAB->getBSEvmax();
int _bseAB_vmin = _orbitalsAB->getBSEvmin();
int _bseAB_vtotal = _bseAB_vmax - _bseAB_vmin +1 ;
int _bseAB_ctotal = _bseAB_cmax - _bseAB_cmin +1 ;
int _bseAB_size = _bseAB_vtotal * _bseAB_ctotal;
int _bseAB_exc = _bseAB.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has " << _bseAB_exc << " excitons with dimension " << _bseAB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combAB;
_combAB.resize(_bseAB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseAB_vtotal; _v++){
for ( int _c = 0; _c < _bseAB_ctotal; _c++){
_combAB(_cnt,0) = _v;
_combAB(_cnt,1) = _bseAB_vtotal + _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << "Levels stored: Basis A[" << _levelsA << ":" << _basisA << "]"
<< " B[" << _levelsB << ":" << _basisB << "]" << flush;
// DFT levels can be reduced to those used in BSE
_levelsA = _bseA_vtotal + _bseA_ctotal;
_levelsB = _bseB_vtotal + _bseB_ctotal;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Levels used in BSE of molA: " << _bseA_vmin << " to " << _bseA_cmax << " total: " << _bseA_vtotal + _bseA_ctotal << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Levels used in BSE of molB: " << _bseB_vmin << " to " << _bseB_cmax << " total: " << _bseB_vtotal + _bseB_ctotal << flush;
if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {
LOG(logERROR,*_pLog) << "No information about number of occupied/unoccupied levels is stored" << flush;
return false;
}
// | Orbitals_A 0 | | Overlap_A |
// | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )
ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;
ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;
ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB );
LOG(logDEBUG, *_pLog) << TimeStamp() << "Constructing direct product AxB ["
<< _psi_AxB.size1() << "x"
<< _psi_AxB.size2() << "]";
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;
//ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = *_orbitalsA->getOrbitals();
// ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = *_orbitalsB->getOrbitals();
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = ub::project( *_orbitalsA->getOrbitals() , ub::range(_bseA_vmin, _bseA_cmax+1) , ub::range ( 0, _basisA ));
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = ub::project( *_orbitalsB->getOrbitals(), ub::range(_bseB_vmin, _bseB_cmax+1) , ub::range ( 0, _basisB ));
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// psi_AxB * S_AB * psi_AB
LOG(logDEBUG, *_pLog) << TimeStamp() << "Projecting monomer orbitals onto dimer ";
ub::matrix<double> _orbitalsAB_Transposed = ub::trans( *_orbitalsAB->getOrbitals() );
if ( (*_orbitalsAB->getOverlap()).size1() == 0 ) {
LOG(logERROR,*_pLog) << "Overlap matrix is not stored";
return false;
}
#ifdef OVERLAP_DEBUG
cout << "\n\t\tprod1 ["
<< (*_orbitalsAB->getOverlap()).size1() << "x" << (*_orbitalsAB->getOverlap()).size2() << "] ["
<< _orbitalsAB_Transposed.size1() << "x" << _orbitalsAB_Transposed.size2() << "] ";
#endif
ub::matrix<double> _psi_AB = ub::prod( *_orbitalsAB->getOverlap(), _orbitalsAB_Transposed );
#ifdef OVERLAP_DEBUG
cout << "\t\tprod2 ["
<< _psi_AxB.size1() << "x" << _psi_AxB.size2() << "] ["
<< _psi_AB.size1() << "x" << _psi_AB.size2() << "] ";
#endif
ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );
_psi_AB.clear();
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// row: monomer orbitals, col: dimer orbitals
ub::matrix<double> _proj_check = ub::zero_matrix<double>(_levelsA + _levelsB, _psi_AxB_dimer_basis.size2() );
for ( int i = 0; i < _levelsA + _levelsB; i++ ){
// occupied dimer levels
for ( int j = 0; j < _bseAB_vtotal ; j++ ){
_proj_check(i,0) += _psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
// empty dimer levels
for ( unsigned j = _bseAB_vtotal ; j < _psi_AxB_dimer_basis.size2() ; j++ ){
_proj_check(i,1) += _psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
//cout << " Monomer level projection (occ:virt:total)" << i << " : " << _proj_check(i,0) << " : " << _proj_check(i,1) << " : " << _proj_check(i,0) + _proj_check(i,1) << endl;
}
// some more convenient storage
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) );
}
}
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) );
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " projection of product functions(" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// now project the exciton functions (ugly!)
// ub::matrix<real> _proj_excA;
// _proj_excA.resize(_bseA_exc,_bseAB_exc);
ub::matrix<real> _temp = ub::prod( _kap, _bseAB );
ub::matrix<real> _proj_excA = ub::prod( ub::trans(_bseA), _temp);
/*
for ( unsigned i = 0 ; i < _proj_excA.size1() ; i++ ){
real check = 0.0;
for ( unsigned j = 0; j < _proj_excA.size2(); j++ ){
check += _proj_excA(i,j) * _proj_excA(i,j) ;
}
cout << " Monomer exciton " << i << " norm " << check << endl;
}
*/
_temp = ub::prod( _kbp, _bseAB );
ub::matrix<real> _proj_excB = ub::prod( ub::trans(_bseB ), _temp);
// cout << "exciton projectors: " << _proj_excA.size1() << " : " << _proj_excA.size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " projection of exciton wave functions (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
ub::matrix<real> _Hamiltonian_AB = ub::zero_matrix<real>(_bseAB_size,_bseAB_size );
ub::vector<real>& _bseAB_energies = _orbitalsAB->BSESingletEnergies();
for ( int _i=0; _i<_bseAB_size; _i++){
_Hamiltonian_AB(_i,_i) = _bseAB_energies(_i);
}
ub::matrix<real> _J_dimer = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
ub::matrix<real> _S_dimer = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
// setup J
_temp = ub::prod( _Hamiltonian_AB , ub::trans(_proj_excA) );
ub::project( _J_dimer, ub::range (0, _bseA_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excA, _temp ); // J_AA = proj_excA x H x trans(proj_excA)
ub::project( _J_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excB, _temp ); // J_BA = proj_excB x H x trans(proj_excA)
_temp = ub::prod( _Hamiltonian_AB , ub::trans(_proj_excB) );
ub::project( _J_dimer, ub::range (0, _bseA_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc ) ) = ub::prod( _proj_excA, _temp ); // J_AB = proj_excA x H x trans(proj_excB)
ub::project( _J_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc) ) = ub::prod( _proj_excB, _temp ); // J_BB = proj_excB x H x trans(proj_excB)
LOG(logDEBUG, *_pLog) << TimeStamp() << " setup J (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// setup S
ub::project( _S_dimer, ub::range (0, _bseA_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excA, ub::trans(_proj_excA) ); // S_AA = proj_excA x trans(proj_excA)
ub::project( _S_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( 0, _bseA_exc ) ) = ub::prod( _proj_excB, ub::trans(_proj_excA)); // S_BA = proj_excB x trans(proj_excA)
ub::project( _S_dimer, ub::range (0, _bseA_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc ) ) = ub::prod( _proj_excA, ub::trans(_proj_excB)); // J_AB = proj_excA x H x trans(proj_excB)
ub::project( _S_dimer, ub::range (_bseA_exc, _bseA_exc + _bseB_exc ), ub::range ( _bseA_exc, _bseA_exc + _bseB_exc) ) = ub::prod( _proj_excB, ub::trans(_proj_excB) ); // J_BB = proj_excB x H x trans(proj_excB)
LOG(logDEBUG, *_pLog) << TimeStamp() << " setup S (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
ub::vector<real> _S_eigenvalues;
linalg_eigenvalues( _S_eigenvalues, _S_dimer);
ub::matrix<real> _diagS = ub::zero_matrix<real>( _bseA_exc + _bseB_exc , _bseA_exc + _bseB_exc );
for ( int _i =0; _i < _bseA_exc + _bseB_exc ; _i++){
_diagS(_i,_i) = 1.0/sqrt(_S_eigenvalues[_i]);
}
_temp=ub::prod( _diagS, ub::trans(_S_dimer) ) ;
ub::matrix<real> _transform = ub::prod( _S_dimer, _temp );
LOG(logDEBUG, *_pLog) << TimeStamp() << " transformation matrix (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
// final coupling elements
_temp=ub::prod(_J_dimer, _transform);
ub::matrix<real> _J_eff = ub::prod( _transform, _temp);
LOG(logDEBUG, *_pLog) << TimeStamp() << " effective couplings (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(0,_bseA_exc+1)*13.6058 << " and " << _J_eff(_bseA_exc+1, 0) * 13.6058 << endl;
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(0,_bseA_exc)*13.6058 << " and " << _J_eff(_bseA_exc, 0) * 13.6058 << endl;
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _J_eff(1,_bseA_exc+1)*13.6058 << " and " << _J_eff(_bseA_exc+1, 1) * 13.6058 << endl;
LOG(logDEBUG, *_pLog) << TimeStamp() << " (" << t.elapsed() - _st << "s) " << flush; _st = t.elapsed();
LOG(logDEBUG, *_pLog) << TimeStamp() << "Done with exciton couplings" << flush;
return true;
}
/**
* \brief evaluates electronic couplings
*
* This is a different version with not diagonalized BSE Hamiltonian
*
* @param _orbitalsA molecular orbitals of molecule A
* @param _orbitalsB molecular orbitals of molecule B
* @param _orbitalsAB molecular orbitals of the dimer AB
* @param _JAB matrix with electronic couplings
* @return false if failed
*/
bool BSECoupling::CalculateCouplings(Orbitals* _orbitalsA, Orbitals* _orbitalsB, Orbitals* _orbitalsAB) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " Calculating exciton couplings" << flush;
// set the parallelization
#ifdef _OPENMP
if ( _openmp_threads > 0 ) omp_set_num_threads(_openmp_threads);
LOG(logDEBUG, *_pLog) << TimeStamp() << " Using "<< omp_get_max_threads()<<" threads" << flush;
#endif
_orbitalsAB->setCoupledExcitonsA(_levA);
_orbitalsAB->setCoupledExcitonsB(_levB);
//check to see if ordering of atoms agrees
const std::vector<QMAtom*> atomsA=_orbitalsA->QMAtoms();
const std::vector<QMAtom*> atomsB=_orbitalsB->QMAtoms();
const std::vector<QMAtom*> atomsAB=_orbitalsAB->QMAtoms();
for (unsigned i=0;i<atomsAB.size();i++){
QMAtom* dimer=atomsAB[i];
QMAtom* monomer=NULL;
if (i<atomsA.size()){
monomer=atomsA[i];
}
else if (i<atomsB.size()+atomsA.size() ){
monomer=atomsB[i-atomsA.size()];
}
else{
throw runtime_error((boost::format("Number of Atoms in dimer %3i and the two monomers A:%3i B:%3i does not agree") %atomsAB.size() %atomsA.size() %atomsB.size()).str());
}
if(monomer->type != dimer->type){
throw runtime_error("\nERROR: Atom types do not agree in dimer and monomers\n");
}
if(std::abs(monomer->x-dimer->x)>0.001 || std::abs(monomer->y-dimer->y)>0.001 || std::abs(monomer->z-dimer->z)>0.001){
LOG(logERROR,*_pLog) << "======WARNING=======\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\n " << flush;
break;
}
}
// constructing the direct product orbA x orbB
int _basisA = _orbitalsA->getBasisSetSize();
int _basisB = _orbitalsB->getBasisSetSize();
if ( ( _basisA == 0 ) || ( _basisB == 0 ) ) {
LOG(logERROR,*_pLog) << "Basis set size is not stored in monomers" << flush;
return false;
}
// number of levels stored in monomers
int _levelsA = _orbitalsA->getNumberOfLevels();
int _levelsB = _orbitalsB->getNumberOfLevels();
boost::timer t; // start timing
//double _st = t.elapsed();
// get exciton information of molecule A
int _bseA_cmax = _orbitalsA->getBSEcmax();
int _bseA_cmin = _orbitalsA->getBSEcmin();
int _bseA_vmax = _orbitalsA->getBSEvmax();
int _bseA_vmin = _orbitalsA->getBSEvmin();
int _bseA_vtotal = _bseA_vmax - _bseA_vmin +1 ;
int _bseA_ctotal = _bseA_cmax - _bseA_cmin +1 ;
int _bseA_size = _bseA_vtotal * _bseA_ctotal;
int _bseA_singlet_exc = _orbitalsA->BSESingletCoefficients().size2();
int _bseA_triplet_exc = _orbitalsA->BSETripletCoefficients().size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_singlet_exc << " singlet excitons with dimension " << _bseA_size << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule A has " << _bseA_triplet_exc << " triplet excitons with dimension " << _bseA_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combA;
_combA.resize(_bseA_size,2);
int _cnt = 0;
for ( int _v = 0; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c < _bseA_ctotal; _c++){
_combA(_cnt,0) = _v;
_combA(_cnt,1) = _bseA_vtotal + _c;
_cnt++;
}
}
// get exciton information of molecule B
int _bseB_cmax = _orbitalsB->getBSEcmax();
int _bseB_cmin = _orbitalsB->getBSEcmin();
int _bseB_vmax = _orbitalsB->getBSEvmax();
int _bseB_vmin = _orbitalsB->getBSEvmin();
int _bseB_vtotal = _bseB_vmax - _bseB_vmin +1 ;
int _bseB_ctotal = _bseB_cmax - _bseB_cmin +1 ;
int _bseB_size = _bseB_vtotal * _bseB_ctotal;
int _bseB_singlet_exc = _orbitalsB->BSESingletCoefficients().size2();
int _bseB_triplet_exc = _orbitalsB->BSETripletCoefficients().size2();
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_singlet_exc << " singlet excitons with dimension " << _bseB_size << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " molecule B has " << _bseB_triplet_exc << " triplet excitons with dimension " << _bseB_size << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combB;
_combB.resize(_bseB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c < _bseB_ctotal; _c++){
_combB(_cnt,0) = _bseA_vtotal + _bseA_ctotal + _v;
_combB(_cnt,1) = _bseA_vtotal + _bseA_ctotal + _bseB_vtotal + _c;
_cnt++;
}
}
if(_levA>_bseA_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of excitons you want is greater than stored for molecule B. Setting to max number available" << flush;
_levA=_bseA_singlet_exc;
}
if(_levB>_bseB_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of excitons you want is greater than stored for molecule B. Setting to max number available" << flush;
_levB=_bseB_singlet_exc;
}
if(_FeA>_bseA_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of Frenkel states you want is greater than stored for molecule B. Setting to max number available" << flush;
_FeA=_bseA_singlet_exc;
}
if(_FeB>_bseB_singlet_exc){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of Frenkel states you want is greater than stored for molecule B. Setting to max number available" << flush;
_FeB=_bseB_singlet_exc;
}
if(_unoccA>_bseA_ctotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of occupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE" << flush;
_unoccA=_bseA_ctotal;
}
else if (_unoccA<0){
_unoccA=_bseA_ctotal;
}
if(_unoccB>_bseB_ctotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of occupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE" << flush;
_unoccB=_bseB_ctotal;
}
else if (_unoccB<0){
_unoccB=_bseB_ctotal;
}
if(_occA>_bseA_vtotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of unoccupied orbitals in molecule A for CT creation exceeds number of KS-orbitals in BSE" << flush;
_occA=_bseA_vtotal;
}
else if (_occA<0){
_occA=_bseA_vtotal;
}
if(_occB>_bseB_vtotal){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Number of unoccupied orbitals in molecule B for CT creation exceeds number of KS-orbitals in BSE" << flush;
_occB=_bseB_vtotal;
}else if (_occB<0){
_occB=_bseB_vtotal;
}
// get exciton information of pair AB
int _bseAB_cmax = _orbitalsAB->getBSEcmax();
int _bseAB_cmin = _orbitalsAB->getBSEcmin();
int _bseAB_vmax = _orbitalsAB->getBSEvmax();
int _bseAB_vmin = _orbitalsAB->getBSEvmin();
int _bseAB_vtotal = _bseAB_vmax - _bseAB_vmin +1 ;
int _bseAB_ctotal = _bseAB_cmax - _bseAB_cmin +1 ;
int _bseAB_size = _bseAB_vtotal * _bseAB_ctotal;
// check if electron-hole interaction matrices are stored
if ( ! _orbitalsAB->hasEHinteraction() ){
LOG(logERROR,*_pLog) << "BSE EH int not stored in dimer " << flush;
return false;
}
ub::matrix<real>& _eh_d = _orbitalsAB->eh_d();
ub::matrix<real>& _eh_x = _orbitalsAB->eh_x();
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has BSE EH interaction (direct) with dimension " << _eh_d.size1() << " x " << _eh_d.size2() << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " dimer AB has BSE EH interaction (exchange) with dimension " << _eh_x.size1() << " x " << _eh_x.size2() << flush;
// now, two storage assignment matrices for two-particle functions
ub::matrix<int> _combAB;
_combAB.resize(_bseAB_size,2);
_cnt = 0;
for ( int _v = 0; _v < _bseAB_vtotal; _v++){
for ( int _c = 0; _c < _bseAB_ctotal; _c++){
//_combAB(_cnt,0) = _v;
//_combAB(_cnt,1) = _bseAB_vtotal + _c;
_combAB(_cnt,0) = _bseAB_vmin + _v;
_combAB(_cnt,1) = _bseAB_vmin + _bseAB_vtotal + _c;
_cnt++;
}
}
// DFT levels of monomers can be reduced to those used in BSE
_levelsA = _bseA_vtotal + _bseA_ctotal;
_levelsB = _bseB_vtotal + _bseB_ctotal;
LOG(logDEBUG, *_pLog) << TimeStamp() << " levels used in BSE of molA: " << _bseA_vmin << " to " << _bseA_cmax << " total: " << _bseA_vtotal + _bseA_ctotal << flush;
LOG(logDEBUG, *_pLog) << TimeStamp() << " levels used in BSE of molB: " << _bseB_vmin << " to " << _bseB_cmax << " total: " << _bseB_vtotal + _bseB_ctotal << flush;
if ( ( _levelsA == 0 ) || (_levelsB == 0) ) {
LOG(logERROR,*_pLog) << "No information about number of occupied/unoccupied levels is stored" << flush;
return false;
}
// | Orbitals_A 0 | | Overlap_A |
// | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )
ub::zero_matrix<double> zeroB( _levelsA, _basisB ) ;
ub::zero_matrix<double> zeroA( _levelsB, _basisA ) ;
ub::matrix<double> _psi_AxB ( _levelsA + _levelsB, _basisA + _basisB );
// constructing merged orbitals
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( _basisA, _basisA +_basisB ) ) = zeroB;
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( 0, _basisA ) ) = zeroA;
ub::project( _psi_AxB, ub::range (0, _levelsA ), ub::range ( 0, _basisA ) ) = ub::project( *_orbitalsA->getOrbitals() , ub::range(_bseA_vmin, _bseA_cmax+1) , ub::range ( 0, _basisA ));
ub::project( _psi_AxB, ub::range (_levelsA, _levelsA + _levelsB ), ub::range ( _basisA, _basisA + _basisB ) ) = ub::project( *_orbitalsB->getOrbitals(), ub::range(_bseB_vmin, _bseB_cmax+1) , ub::range ( 0, _basisB ));
// psi_AxB * S_AB * psi_AB
LOG(logDEBUG, *_pLog) << TimeStamp() << " projecting monomer onto dimer orbitals" << flush;
ub::matrix<double> _orbitalsAB_Transposed = ub::trans( *_orbitalsAB->getOrbitals() );
if ( (*_orbitalsAB->getOverlap()).size1() == 0 ) {
LOG(logERROR,*_pLog) << "Overlap matrix is not stored";
return false;
}
ub::matrix<double> _psi_AB = ub::prod( *_orbitalsAB->getOverlap(), _orbitalsAB_Transposed );
ub::matrix<double> _psi_AxB_dimer_basis = ub::prod( _psi_AxB, _psi_AB );
_psi_AB.clear();
//cout<< "_psi_AxB_dimer"<<endl;
unsigned int LevelsA = _levelsA;
for (unsigned i=0;i<_psi_AxB_dimer_basis.size1();i++){
double mag=0.0;
for (unsigned j=0;j<_psi_AxB_dimer_basis.size2();j++){
mag+=_psi_AxB_dimer_basis(i,j)*_psi_AxB_dimer_basis(i,j);
}
if (mag<0.95){
int monomer = 0;
int level = 0;
if ( i < LevelsA ) {
monomer = 1;
level = _bseA_vmin + i;
} else {
monomer = 2;
level = _bseB_vmin + i -_levelsA;
}
LOG(logERROR,*_pLog) << "\nERROR: " << i << " Projection of orbital " << level << " of monomer " << monomer << " on dimer is insufficient,mag="<<mag<<" maybe the orbital order is screwed up, otherwise increase dimer basis.\n"<<flush;
}
}
//exit(0);
// _psi_AxB_dimer_basis = T in notes, dimension ( LA + LB, LD)
// cout << "Size of _psi_AxB_dimer_basis " << _psi_AxB_dimer_basis.size1() << " : " << _psi_AxB_dimer_basis.size2() << flush;
//notation AB is CT states with A+B-, BA is the counterpart
//Setting up CT-states:
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up CT-states" << flush;
//Number of A+B- states
int noAB=_occA*_unoccB;
//Number of A-B+ states
int noBA=_unoccA*_occB;
ub::matrix<int> comb_CTAB;
comb_CTAB.resize(noAB,2);
_cnt = 0;
// iterate A over occupied, B over unoccupied
int v_start=_bseA_vtotal-_occA;
for ( int _v = v_start; _v < _bseA_vtotal; _v++){
for ( int _c = 0; _c <_unoccB; _c++){
comb_CTAB(_cnt,0) =_v;
comb_CTAB(_cnt,1) = _bseA_vtotal+_bseA_ctotal+_bseB_vtotal + _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() <<" "<<noAB <<" CT states A+B- created" << flush;
//cout << "comb_CTAB" << endl;
//cout << comb_CTAB << endl;
ub::matrix<int> comb_CTBA;
comb_CTBA.resize(noBA,2);
_cnt = 0;
// iterate A over unoccupied, B over occupied
v_start=_bseB_vtotal-_occB;
for ( int _v = v_start; _v < _bseB_vtotal; _v++){
for ( int _c = 0; _c <_unoccA; _c++){
comb_CTBA(_cnt,0) =_bseA_vtotal+_bseA_ctotal+_v;
comb_CTBA(_cnt,1) = _bseA_vtotal+ _c;
_cnt++;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() <<" "<<noBA <<" CT states B+A- created" << flush;
//cout << "comb_CTBA" << endl;
//cout << comb_CTBA << endl;
// these 4 matrixes, matrix(i,j) contains the j-th dimer MO component of the i-th excitation
ub::matrix<real> ctAB;
ctAB.resize(noAB,_bseAB_size);
#pragma omp parallel for
for ( int _i_CT = 0 ; _i_CT < noAB ; _i_CT++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
ctAB(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTAB(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTAB(_i_CT,1), _combAB( _i_bseAB,1) );
}
}
ub::matrix<real>ctBA;
ctBA.resize(noBA,_bseAB_size);
#pragma omp parallel for
for ( int _i_CT = 0 ; _i_CT < noBA ; _i_CT++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
ctBA(_i_CT,_i_bseAB)=_psi_AxB_dimer_basis( comb_CTBA(_i_CT,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( comb_CTBA(_i_CT,1), _combAB( _i_bseAB,1) );
}
}
// some more convenient storage
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
#pragma omp parallel for
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) );
}
}
//ub::matrix<real> check;
//check.resize(_bseA_size,_bseA_size);
//check= ub::prod(_kap,ub::trans(_kap));
//cout << "check"<<endl;
//cout <<ub::project(check, ub::range (0, 10 ), ub::range ( 0, 10 ) ) <<endl;
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
#pragma omp parallel for
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) );
}
}
// Same routines but also take <v|c'> <c|v'> projections into account
/*
ub::matrix<real> _kap;
_kap.resize(_bseA_size,_bseAB_size);
for ( int _i_bseA = 0 ; _i_bseA < _bseA_size ; _i_bseA++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kap(_i_bseA,_i_bseAB) = _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,1) )+
_psi_AxB_dimer_basis( _combA(_i_bseA,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combA(_i_bseA,0), _combAB( _i_bseAB,1) ) ;
}
}
ub::matrix<real> _kbp;
_kbp.resize(_bseB_size,_bseAB_size);
for ( int _i_bseB = 0 ; _i_bseB < _bseB_size ; _i_bseB++){
for ( int _i_bseAB = 0 ; _i_bseAB < _bseAB_size ; _i_bseAB++){
_kbp(_i_bseB,_i_bseAB) = _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,1) )+
_psi_AxB_dimer_basis( _combB(_i_bseB,1), _combAB( _i_bseAB,0) ) * _psi_AxB_dimer_basis( _combB(_i_bseB,0), _combAB( _i_bseAB,1) );
}
}
*/
LOG(logDEBUG, *_pLog) << TimeStamp() << " construct projection of product functions " << flush;
// cout << "Size of _kap " << _kap.size1() << " : " << _kap.size2() << "\n" << flush;
// cout << "Size of _kbp " << _kbp.size1() << " : " << _kbp.size2() << "\n" << flush;
// now the different spin types
if ( _doSinglets){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Evaluating singlets" << flush;
// get singlet BSE Hamiltonian from _orbitalsAB
ub::matrix<real> _Hamiltonian_AB = _eh_d + 2.0 * _eh_x;
const ub::matrix<real>& _bseA = ub::project( _orbitalsA->BSESingletCoefficients(),
ub::range (0, _orbitalsA->BSESingletCoefficients().size1() ), ub::range ( 0, _FeA ) );
const ub::matrix<real>& _bseB = ub::project( _orbitalsB->BSESingletCoefficients(),
ub::range (0, _orbitalsB->BSESingletCoefficients().size1() ), ub::range ( 0, _FeB ) );
// cout << "Size of _Hamiltonian_AB " << _Hamiltonian_AB.size1() << " : " << _Hamiltonian_AB.size2() << flush;
// cout << "Size of _bseA " << _bseA.size1() << " : " << _bseA.size2() << flush;
// cout << "Size of _bseB " << _bseB.size1() << " : " << _bseB.size2() << flush;
bool _singlets = ProjectExcitons( _kap, _kbp,ctAB,ctBA, _bseA, _bseB, _Hamiltonian_AB, JAB_singlet);
if ( _singlets ) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated singlet couplings " << flush;
}
/*
// diagonalize the effective Hamiltonian?
ub::vector<real> _coupled_energies;
ub::matrix<real> _coupled_coefficients;
std::vector< std::vector<double> >& _free_dipolesA = _orbitalsA->TransitionDipoles();
std::vector< std::vector<double> >& _free_dipolesB = _orbitalsB->TransitionDipoles();
linalg_eigenvalues(*_JAB_singlet, _coupled_energies, _coupled_coefficients,_JAB_singlet->size1() );
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated EVs of coupling matrix " << flush;
cout << "\n" << endl;
for ( int i =0 ; i< _JAB_singlet->size1(); i++){
std::vector<double> tdipole(3,0.0);
for ( int j = 0; j < 50; j++){
tdipole[0] += _coupled_coefficients(j,i)*_free_dipolesA[j][0] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][0];
tdipole[1] += _coupled_coefficients(j,i)*_free_dipolesA[j][1] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][1];
tdipole[2] += _coupled_coefficients(j,i)*_free_dipolesA[j][2] + _coupled_coefficients(j+50,i)*_free_dipolesB[j][2];
}
double tdipole_strength = tdipole[0]*tdipole[0] + tdipole[1]*tdipole[1] + tdipole[2]*tdipole[2];
double oscillator_strength = tdipole_strength * _coupled_energies(i) /3.0;
LOG(logINFO, *_pLog) << (format(" S = %1$4d Omega = %2$+1.4f eV lamdba = %3$+3.2f nm ") % (i + 1) % (13.6058 * _coupled_energies(i)) % (1240.0/(13.6058 * _coupled_energies(i))) ).str() << flush;
LOG(logINFO, *_pLog) << (format(" TrDipole length gauge dx = %1$+1.4f dy = %2$+1.4f dz = %3$+1.4f |d|^2 = %4$+1.4f f = %5$+1.4f") % (tdipole[0]) % (tdipole[1]) % (tdipole[2]) % (tdipole_strength) % (oscillator_strength)).str() << flush;
for (int _i_bse = 0; _i_bse < _JAB_singlet->size1(); _i_bse++) {
// if contribution is larger than 0.2, print
double _weight = pow(_coupled_coefficients(_i_bse, i), 2);
if (_weight > 0.2) {
if ( _i_bse < 50) {
LOG(logINFO, *_pLog) << (format(" EXCITON A %1$-3d : %2$3.1f%%") % _i_bse % (100.0 * _weight)).str() << flush;
} else
{
LOG(logINFO, *_pLog) << (format(" EXCITON B %1$-3d : %2$3.1f%%") % (_i_bse-50) % (100.0 * _weight)).str() << flush;
}
}
}
LOG(logINFO, *_pLog) << (format(" ")).str() << flush;
cout << " E" << i << " : " << _coupled_energies(i)*13.605 << " TD " << tdipole[0] << " " << tdipole[1] << " " << tdipole[2] << endl;
}
//LOG(logDEBUG, *_pLog) << TimeStamp() << " singlet coupling: " << _JAB_singlet->at_element(0,_bseA_singlet_exc)*13.6058 << " and " << _JAB_singlet->at_element(_bseA_singlet_exc, 0) * 13.6058 << endl;
*/
}
if ( _doTriplets){
LOG(logDEBUG, *_pLog) << TimeStamp() << " Evaluating triplets" << flush;
// get triplet BSE Hamiltonian from _orbitalsAB
ub::matrix<real> _Hamiltonian_AB = _eh_d;
//ub::matrix<real>& _bseA= _orbitalsA->BSETripletCoefficients();
const ub::matrix<real>& _bseA = ub::project( _orbitalsA->BSETripletCoefficients(),
ub::range (0, _orbitalsA->BSETripletCoefficients().size1() ), ub::range ( 0, _FeA ) );
const ub::matrix<real>& _bseB = ub::project( _orbitalsB->BSETripletCoefficients(),
ub::range (0, _orbitalsB->BSETripletCoefficients().size1() ), ub::range ( 0, _FeB ) );
//ub::matrix<real>& _bseB = _orbitalsB->BSETripletCoefficients();
bool _triplets = ProjectExcitons( _kap, _kbp,ctAB,ctBA, _bseA, _bseB, _Hamiltonian_AB, JAB_triplet);
if ( _triplets ) {
LOG(logDEBUG, *_pLog) << TimeStamp() << " calculated triplet couplings " << flush;
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Done with exciton couplings" << flush;
return true;
};
bool BSECoupling::ProjectExcitons(const ub::matrix<real>& _kap,const ub::matrix<real>& _kbp,
const ub::matrix<real>& ctAB,const ub::matrix<real>& ctBA,
const ub::matrix<real>& _bseA, const ub::matrix<real>& _bseB,
const ub::matrix<real>& _H, ub::matrix<real>& _J){
//cout << " Dimensions of _bseA " << _bseA.size1() << " : " << _bseA.size2() << endl;
// get projection of monomer excitons on dimer product functions
ub::matrix<real> _proj_excA = ub::prod( ub::trans( _bseA ), _kap);
ub::matrix<real> _proj_excB = ub::prod( ub::trans( _bseB ), _kbp);
//cout << "_proj_excA"<<_proj_excA.size1()<<"x"<<_proj_excA.size2()<<endl;
//cout << "_proj_excB"<<_proj_excB.size1()<<"x"<<_proj_excB.size2()<<endl;
//cout << "_ctAB"<<ctAB.size1()<<"x"<<ctAB.size2()<<endl;
//cout << "_ctBA"<<ctBA.size1()<<"x"<<ctBA.size2()<<endl;
unsigned _bseA_exc = _proj_excA.size1();
unsigned _bseB_exc = _proj_excB.size1();
unsigned _bse_exc=_bseA_exc+_bseB_exc;
_J=ub::zero_matrix<real>(_bse_exc,_bse_exc);
unsigned _ctAB=ctAB.size1();
unsigned _ctBA=ctBA.size1();
unsigned _ct=_ctAB+_ctBA;
unsigned nobasisfunc=_H.size1();
//cout << _ctAB <<_ctBA<<endl;
//ub::matrix<double> _J_dimer = ub::zero_matrix<double>( _bse_exc +_ct, _bse_exc+_ct );
//ub::matrix<double> _S_dimer = ub::zero_matrix<double>( _bse_exc +_ct, _bse_exc +_ct);
//cout << _J_dimer.size1()<< " : "<<_J_dimer.size2()<<endl;
//cout << _S_dimer.size1()<< " : "<<_S_dimer.size2()<<endl;
LOG(logDEBUG, *_pLog) << TimeStamp() << " casting Hamiltonian to double " << flush;
ub::matrix<double> projection =ub::zero_matrix<double>(_bse_exc+_ct,nobasisfunc);
ub::matrix<double> Htemp=_H;
LOG(logDEBUG, *_pLog) << TimeStamp() << " merging projections into one vector " << flush;
ub::project(projection, ub::range ( 0, _bseA_exc ),ub::range (0, nobasisfunc ) )=_proj_excA;
ub::project(projection, ub::range ( _bseA_exc, _bse_exc ),ub::range (0, nobasisfunc ) )=_proj_excB;
if(_ctAB>0){
ub::project(projection, ub::range ( _bse_exc , _bse_exc+_ctAB ) ,ub::range (0,nobasisfunc ) )=ctAB;
}
if(_ctBA>0){
ub::project(projection, ub::range ( _bse_exc+_ctAB, _bse_exc+_ct ),ub::range (0, nobasisfunc ) )=ctBA;
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up coupling matrix size "<< _bse_exc +_ct<<"x"<<_bse_exc +_ct << flush;
// matrix _J
// E_A J_AB J_A_ABCT J_A_BACT
// J_BA E_B J_B_ABCT J_B_BACT
// J_ABCT_A J_ABCT_B E_ABCT J_ABCT_BACT
// J_BACT_A J_BACT_B J_BACT_ABCT E_BACT
// I think this only works for hermitian/symmetric H so only in TDA
// setup J
ub::matrix<double> _temp=ub::prod(Htemp,ub::trans(projection));
ub::matrix<double> _J_dimer=ub::prod(projection,_temp);
Htemp.resize(0,0);
_temp.resize(0,0);
LOG(logDEBUG, *_pLog) << TimeStamp() << " Setting up overlap matrix size "<< _bse_exc +_ct<<"x"<<_bse_exc +_ct << flush;
// setup S
ub::matrix<double> _S_dimer=ub::prod(projection,ub::trans(projection));
if(tools::globals::verbose){
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
LOG(logDEBUG, *_pLog) << "_J_dimer[Ryd]"<<flush;
LOG(logDEBUG, *_pLog) << _J_dimer<<flush;
LOG(logDEBUG, *_pLog) << "_S_dimer"<<flush;
LOG(logDEBUG, *_pLog) << _S_dimer<<flush;
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
}
//LOG(logDEBUG, *_pLog) << TimeStamp() << " Diagonlaize overlap "<< flush;
//ub::vector<double> _S_eigenvalues;
//cout << "_J_ortho"<<endl;
//cout << _J_dimer<<endl;
//linalg_eigenvalues(_S_eigenvalues,_S_dimer);
//LOG(logDEBUG, *_pLog) << TimeStamp() << " done "<< flush;
double small=linalg_loewdin(_J_dimer,_S_dimer);
if(tools::globals::verbose){
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
LOG(logDEBUG, *_pLog) << "_J_ortho[Ryd]"<<flush;
LOG(logDEBUG, *_pLog) << _J_dimer<<flush;
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Smallest value of dimer overlapmatrix is "<< small<< flush;
ub::vector<double> _J_eigenvalues;
//cout << "_J_ortho"<<endl;
//cout << _J_dimer<<endl;
linalg_eigenvalues(_J_eigenvalues,_J_dimer);
if(tools::globals::verbose){
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
LOG(logDEBUG, *_pLog) << "Eigenvectors of J"<<flush;
LOG(logDEBUG, *_pLog) << _J_dimer<<flush;
LOG(logDEBUG, *_pLog) << "J_eigenvalues[Ryd]"<< flush;
LOG(logDEBUG, *_pLog) << _J_eigenvalues<< flush;
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
}
//Calculate projection on subspace for every pair of excitons separately
for (int stateA=0;stateA<_levA; stateA++){
for (int stateB=0;stateB<_levB; stateB++){
int stateBd=stateB+_bseA_exc;
LOG(logDEBUG, *_pLog) << TimeStamp() << " Calculating coupling between exciton A"<< stateA+1<<" and exciton B"<<stateB+1 << flush;
std::vector<unsigned> index;
for (unsigned i = 0; i < _bse_exc+_ct; i++) {
if (i == unsigned(stateA) || i == unsigned(stateBd)) {
double close = 0.0;
unsigned ind = 0;
//row
for (unsigned j = 0; j < _bse_exc+_ct; j++) {
bool check = true;
// if index i is already in index
// should not happen but if one vector was similar to two others.
for (unsigned l = 0; l < index.size(); l++) {
if (j == index[l]) {
check = false;
break;
}
}
if (check && std::abs(_J_dimer(i, j)) > close) {
ind = j;
close = std::abs(_J_dimer(i, j));
}
}
index.push_back(ind);
}
}
LOG(logDEBUG, *_pLog) << TimeStamp() << " Order is: [Initial state n->nth eigenvalue]"<<flush;
LOG(logDEBUG, *_pLog) << " A" << stateA+1<<":"<<stateA+1<<"->"<<index[0]+1<<" " ;
LOG(logDEBUG, *_pLog) << " B" << stateB+1<<":"<<stateBd+1<<"->"<<index[1]+1<<" "<<flush ;
//setting up transformation matrix _T and diagonal matrix _E for the eigenvalues;
ub::matrix<double> _E=ub::zero_matrix<double>(2,2);
ub::matrix<double> _T=ub::zero_matrix<double>(2,2);
ub::matrix<double> _Tinv;
//find the eigenvectors which are most similar to the initial states
//row
for (unsigned i = 0; i < 2; i++) {
unsigned k=index[i];
double normr =1/std::sqrt(_J_dimer(stateA, k)*_J_dimer(stateA, k)+_J_dimer(stateBd, k)*_J_dimer(stateBd, k)) ;
_T(i,0 ) = _J_dimer(stateA,k)* normr;
_T(i,1 ) = _J_dimer(stateBd,k)*normr;
_E(i,i)=_J_eigenvalues(k);
}
//Transformation TET-1
linalg_invert(_T,_Tinv);
//cout << ub::prod(_T,_Tinv)<<endl;
_temp=ub::prod(_T,_E);
ub::matrix<double> _J_small=ub::prod(_temp,_Tinv);
_J(stateA,stateBd)=_J_small(0,1);
//_J(stateA,stateBd)=_J_small(0,0);
// _J(stateBd,stateBd)=_J_small(1,1);
_J(stateBd,stateA)=_J_small(1,0);
//cout << _temp2<<endl;
if(tools::globals::verbose){
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
LOG(logDEBUG, *_pLog) << "Jeff[Ryd]"<<flush;
LOG(logDEBUG, *_pLog) << _J<<flush;
LOG(logDEBUG, *_pLog) << "---------------------------------------"<<flush;
}
//cout <<_J_small*conv::ryd2ev_f<<endl;
}
}
return true;
}
}}
|
/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
*/
#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>
namespace ti
{
void NetworkStatus::InitializeLoop()
{
}
void NetworkStatus::CleanupLoop()
{
}
bool NetworkStatus::GetStatus()
{
static SCNetworkReachabilityRef primaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.google.com");
if (!primaryTarget)
return true;
SCNetworkConnectionFlags flags;
SCNetworkReachabilityGetFlags(primaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
static SCNetworkReachabilityRef secondaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.google.com");
if (!secondaryTarget)
return true;
SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
return false;
}
}
The secondary target should actually be a different host.
/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
*/
#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>
namespace ti
{
void NetworkStatus::InitializeLoop()
{
}
void NetworkStatus::CleanupLoop()
{
}
bool NetworkStatus::GetStatus()
{
static SCNetworkReachabilityRef primaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.google.com");
if (!primaryTarget)
return true;
SCNetworkConnectionFlags flags;
SCNetworkReachabilityGetFlags(primaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
static SCNetworkReachabilityRef secondaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
if (!secondaryTarget)
return true;
SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
return false;
}
}
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "cppeditor.h"
#include "cppeditorplugin.h"
#include "cppelementevaluator.h"
#include "cppvirtualfunctionassistprovider.h"
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <utils/fileutils.h>
#include <QDebug>
#include <QDir>
#include <QtTest>
/*!
Tests for Follow Symbol Under Cursor and Switch Between Function Declaration/Definition
Section numbers refer to
Working Draft, Standard for Programming Language C++
Document Number: N3242=11-0012
You can find potential test code for Follow Symbol Under Cursor on the bottom of this file.
*/
using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
using namespace TextEditor;
using namespace Core;
namespace {
/// A fake virtual functions assist provider that runs processor->perform() already in configure()
class VirtualFunctionTestAssistProvider : public VirtualFunctionAssistProvider
{
public:
VirtualFunctionTestAssistProvider(CPPEditorWidget *editorWidget)
: m_editorWidget(editorWidget)
{}
// Invoke the processor already here to calculate the proposals. Return false in order to
// indicate that configure failed, so the actual code assist invocation leading to a pop-up
// will not happen.
bool configure(CPlusPlus::Class *startClass, CPlusPlus::Function *function,
const CPlusPlus::Snapshot &snapshot, bool openInNextSplit)
{
VirtualFunctionAssistProvider::configure(startClass, function, snapshot, openInNextSplit);
IAssistProcessor *processor = createProcessor();
IAssistInterface *assistInterface = m_editorWidget->createAssistInterface(FollowSymbol,
ExplicitlyInvoked);
IAssistProposal *immediateProposal = processor->immediateProposal(assistInterface);
IAssistProposal *finalProposal = processor->perform(assistInterface);
m_immediateItems = itemList(immediateProposal->model());
m_finalItems = itemList(finalProposal->model());
return false;
}
static QStringList itemList(IAssistProposalModel *imodel)
{
QStringList immediateItems;
BasicProposalItemListModel *model = dynamic_cast<BasicProposalItemListModel *>(imodel);
if (!model)
return immediateItems;
if (model->isSortable(QString()))
model->sort(QString());
model->removeDuplicates();
for (int i = 0, size = model->size(); i < size; ++i) {
const QString text = model->text(i);
immediateItems.append(text);
}
return immediateItems;
}
public:
QStringList m_immediateItems;
QStringList m_finalItems;
private:
CPPEditorWidget *m_editorWidget;
};
class TestDocument;
typedef QSharedPointer<TestDocument> TestDocumentPtr;
/**
* Represents a test document.
*
* A TestDocument's source can contain special characters:
* - a '@' character denotes the initial text cursor position
* - a '$' character denotes the target text cursor position
*/
class TestDocument
{
public:
TestDocument(const QByteArray &theSource, const QString &fileName)
: source(theSource)
, fileName(fileName)
, initialCursorPosition(source.indexOf('@'))
, targetCursorPosition(source.indexOf('$'))
, editor(0)
, editorWidget(0)
{
QVERIFY(initialCursorPosition != targetCursorPosition);
if (initialCursorPosition > targetCursorPosition) {
source.remove(initialCursorPosition, 1);
if (targetCursorPosition != -1) {
source.remove(targetCursorPosition, 1);
--initialCursorPosition;
}
} else {
source.remove(targetCursorPosition, 1);
if (initialCursorPosition != -1) {
source.remove(initialCursorPosition, 1);
--targetCursorPosition;
}
}
}
static TestDocumentPtr create(const QByteArray &theOriginalSource, const QString &fileName)
{
return TestDocumentPtr(new TestDocument(theOriginalSource, fileName));
}
bool hasInitialCursorMarker() const { return initialCursorPosition != -1; }
bool hasTargetCursorMarker() const { return targetCursorPosition != -1; }
QString filePath() const
{
if (directoryPath.isEmpty())
qDebug() << "directoryPath not set!";
return directoryPath + QLatin1Char('/') + fileName;
}
void writeToDisk() const
{
Utils::FileSaver srcSaver(filePath());
srcSaver.write(source);
srcSaver.finalize();
}
QByteArray source;
const QString fileName;
QString directoryPath;
int initialCursorPosition;
int targetCursorPosition;
CPPEditor *editor;
CPPEditorWidget *editorWidget;
};
/**
* Encapsulates the whole process of setting up several editors, positioning the cursor,
* executing Follow Symbol Under Cursor or Switch Between Function Declaration/Definition
* and checking the result.
*/
class TestCase
{
public:
enum CppEditorAction {
FollowSymbolUnderCursorAction,
SwitchBetweenMethodDeclarationDefinitionAction
};
TestCase(CppEditorAction action, const QByteArray &source,
const QStringList &expectedVirtualFunctionImmediateProposal = QStringList(),
const QStringList &expectedVirtualFunctionFinalProposal = QStringList());
TestCase(CppEditorAction action, const QList<TestDocumentPtr> theTestFiles,
const QStringList &expectedVirtualSymbolsImmediateProposal = QStringList(),
const QStringList &expectedVirtualSymbolsFinalProposal = QStringList());
~TestCase();
void run(bool expectedFail = false);
private:
TestCase(const TestCase &);
TestCase &operator=(const TestCase &);
void init();
TestDocumentPtr testFileWithInitialCursorMarker();
TestDocumentPtr testFileWithTargetCursorMarker();
private:
CppEditorAction m_action;
QList<TestDocumentPtr> m_testFiles;
QStringList m_expectedVirtualSymbolsImmediateProposal; // for virtual functions
QStringList m_expectedVirtualSymbolsFinalProposals; // for virtual functions
};
/// Convenience function for creating a TestDocument.
/// See TestDocument.
TestCase::TestCase(CppEditorAction action, const QByteArray &source,
const QStringList &expectedVirtualFunctionImmediateProposal,
const QStringList &expectedVirtualFunctionFinalProposal)
: m_action(action)
, m_expectedVirtualSymbolsImmediateProposal(expectedVirtualFunctionImmediateProposal)
, m_expectedVirtualSymbolsFinalProposals(expectedVirtualFunctionFinalProposal)
{
m_testFiles << TestDocument::create(source, QLatin1String("file.cpp"));
init();
}
/// Creates a test case with multiple test files.
/// Exactly one test document must be provided that contains '@', the initial position marker.
/// Exactly one test document must be provided that contains '$', the target position marker.
/// It can be the same document.
TestCase::TestCase(CppEditorAction action, const QList<TestDocumentPtr> theTestFiles,
const QStringList &expectedVirtualSymbolsImmediateProposal,
const QStringList &expectedVirtualSymbolsFinalProposal)
: m_action(action)
, m_testFiles(theTestFiles)
, m_expectedVirtualSymbolsImmediateProposal(expectedVirtualSymbolsImmediateProposal)
, m_expectedVirtualSymbolsFinalProposals(expectedVirtualSymbolsFinalProposal)
{
init();
}
void TestCase::init()
{
// Check if there are initial and target position markers
QVERIFY2(testFileWithInitialCursorMarker(),
"No test file with initial cursor marker is provided.");
QVERIFY2(testFileWithTargetCursorMarker(),
"No test file with target cursor marker is provided.");
// Write files to disk
const QString directoryPath = QDir::tempPath();
foreach (TestDocumentPtr testFile, m_testFiles) {
testFile->directoryPath = directoryPath;
testFile->writeToDisk();
}
// Update Code Model
QStringList filePaths;
foreach (const TestDocumentPtr &testFile, m_testFiles)
filePaths << testFile->filePath();
CppTools::CppModelManagerInterface::instance()->updateSourceFiles(filePaths);
// Wait for the indexer to process all files.
// All these files are "Fast Checked", that is the function bodies are not processed.
QStringList filePathsNotYetInSnapshot(filePaths);
forever {
Snapshot snapshot = CppTools::CppModelManagerInterface::instance()->snapshot();
foreach (const QString &filePath, filePathsNotYetInSnapshot) {
if (snapshot.contains(filePath))
filePathsNotYetInSnapshot.removeOne(filePath);
}
if (filePathsNotYetInSnapshot.isEmpty())
break;
QCoreApplication::processEvents();
}
// Open Files
foreach (TestDocumentPtr testFile, m_testFiles) {
testFile->editor
= dynamic_cast<CPPEditor *>(EditorManager::openEditor(testFile->filePath()));
QVERIFY(testFile->editor);
testFile->editorWidget = dynamic_cast<CPPEditorWidget *>(testFile->editor->editorWidget());
QVERIFY(testFile->editorWidget);
// Wait until the indexer processed the just opened file.
// The file is "Full Checked" since it is in the working copy now,
// that is the function bodies are processed.
forever {
Snapshot snapshot = CppTools::CppModelManagerInterface::instance()->snapshot();
if (Document::Ptr document = snapshot.document(testFile->filePath())) {
if (document->checkMode() == Document::FullCheck)
break;
QCoreApplication::processEvents();
}
}
// Rehighlight
testFile->editorWidget->semanticRehighlight(true);
// Wait for the semantic info from the future
while (testFile->editorWidget->semanticInfo().doc.isNull())
QCoreApplication::processEvents();
}
}
TestCase::~TestCase()
{
// Close editors
QList<Core::IEditor *> editorsToClose;
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->editor)
editorsToClose << testFile->editor;
}
EditorManager::closeEditors(editorsToClose, false);
QCoreApplication::processEvents(); // process any pending events
// Remove the test files from the code-model
CppModelManagerInterface *mmi = CppTools::CppModelManagerInterface::instance();
mmi->GC();
QCOMPARE(mmi->snapshot().size(), 0);
}
TestDocumentPtr TestCase::testFileWithInitialCursorMarker()
{
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->hasInitialCursorMarker())
return testFile;
}
return TestDocumentPtr();
}
TestDocumentPtr TestCase::testFileWithTargetCursorMarker()
{
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->hasTargetCursorMarker())
return testFile;
}
return TestDocumentPtr();
}
void TestCase::run(bool expectedFail)
{
TestDocumentPtr initialTestFile = testFileWithInitialCursorMarker();
QVERIFY(initialTestFile);
TestDocumentPtr targetTestFile = testFileWithTargetCursorMarker();
QVERIFY(targetTestFile);
// Activate editor of initial test file
EditorManager::activateEditor(initialTestFile->editor);
initialTestFile->editor->setCursorPosition(initialTestFile->initialCursorPosition);
// qDebug() << "Initial line:" << initialTestFile->editor->currentLine();
// qDebug() << "Initial column:" << initialTestFile->editor->currentColumn() - 1;
QStringList immediateVirtualSymbolResults;
QStringList finalVirtualSymbolResults;
// Trigger the action
switch (m_action) {
case FollowSymbolUnderCursorAction: {
CPPEditorWidget *widget = initialTestFile->editorWidget;
FollowSymbolUnderCursor *delegate = widget->followSymbolUnderCursorDelegate();
VirtualFunctionAssistProvider *original = delegate->virtualFunctionAssistProvider();
// Set test provider, run and get results
QScopedPointer<VirtualFunctionTestAssistProvider> testProvider(
new VirtualFunctionTestAssistProvider(widget));
delegate->setVirtualFunctionAssistProvider(testProvider.data());
initialTestFile->editorWidget->openLinkUnderCursor();
immediateVirtualSymbolResults = testProvider->m_immediateItems;
finalVirtualSymbolResults = testProvider->m_finalItems;
// Restore original test provider
delegate->setVirtualFunctionAssistProvider(original);
break;
}
case SwitchBetweenMethodDeclarationDefinitionAction:
CppEditorPlugin::instance()->switchDeclarationDefinition();
break;
default:
QFAIL("Unknown test action");
break;
}
QCoreApplication::processEvents();
// Compare
IEditor *currentEditor = EditorManager::currentEditor();
BaseTextEditor *currentTextEditor = dynamic_cast<BaseTextEditor*>(currentEditor);
QVERIFY(currentTextEditor);
QCOMPARE(currentTextEditor->document()->filePath(), targetTestFile->filePath());
int expectedLine, expectedColumn;
currentTextEditor->convertPosition(targetTestFile->targetCursorPosition,
&expectedLine, &expectedColumn);
// qDebug() << "Expected line:" << expectedLine;
// qDebug() << "Expected column:" << expectedColumn;
if (expectedFail)
QEXPECT_FAIL("", "Contributor works on a fix.", Abort);
QCOMPARE(currentTextEditor->currentLine(), expectedLine);
QCOMPARE(currentTextEditor->currentColumn() - 1, expectedColumn);
// qDebug() << immediateVirtualSymbolResults;
// qDebug() << finalVirtualSymbolResults;
QCOMPARE(immediateVirtualSymbolResults, m_expectedVirtualSymbolsImmediateProposal);
QCOMPARE(finalVirtualSymbolResults, m_expectedVirtualSymbolsFinalProposals);
}
} // anonymous namespace
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionDeclarationSymbol()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int @function();\n" // Line 5
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"int C::$function()\n"
"{\n"
" return 1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionDefinitionSymbol()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n"
"\n"
"int C::@function()\n"
"{\n"
" return 1 + 1;\n"
"}\n"
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionBody()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"int C::function()\n"
"{\n"
" return @1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromReturnType()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"@int C::function()\n"
"{\n"
" return 1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
/// Check ...
void CppEditorPlugin::test_FollowSymbolUnderCursor_globalVarFromFunction()
{
const QByteArray source =
"int $j;\n"
"int main()\n"
"{\n"
" @j = 2;\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesClassMember()
{
// 3.3.10 Name hiding (par 3.), from text
const QByteArray source =
"struct C {\n"
" void f()\n"
" {\n"
" int $member; // hides C::member\n"
" ++@member;\n" // Line 5
" }\n"
" int member;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesNamespaceMemberIntroducedByUsingDirective()
{
// 3.3.10 Name hiding (par 4.), from text
const QByteArray source =
"namespace N {\n"
" int i;\n"
"}\n"
"\n"
"int main()\n" // Line 5
"{\n"
" using namespace N;\n"
" int $i;\n"
" ++i@; // refers to local i;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_loopLocalVarHidesOuterScopeVariable1()
{
// 3.3.3 Block scope (par. 4), from text
// Same for if, while, switch
const QByteArray source =
"int main()\n"
"{\n"
" int i = 1;\n"
" for (int $i = 0; i < 10; ++i) { // 'i' refers to for's i\n"
" i = @i; // same\n" // Line 5
" }\n"
"}\n";
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_loopLocalVarHidesOuterScopeVariable2()
{
// 3.3.3 Block scope (par. 4), from text
// Same for if, while, switch
const QByteArray source =
"int main()\n"
"{\n"
" int i = 1;\n"
" for (int $i = 0; @i < 10; ++i) { // 'i' refers to for's i\n"
" i = i; // same\n" // Line 5
" }\n"
"}\n";
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_subsequentDefinedClassMember()
{
// 3.3.7 Class scope, part of the example
const QByteArray source =
"class X {\n"
" int f() { return @i; } // i refers to class's i\n"
" int $i;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classMemberHidesOuterTypeDef()
{
// 3.3.7 Class scope, part of the example
// Variable name hides type name.
const QByteArray source =
"typedef int c;\n"
"class X {\n"
" int f() { return @c; } // c refers to class' c\n"
" int $c; // hides typedef name\n"
"};\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_globalVarFromEnum()
{
// 3.3.2 Point of declaration (par. 1), copy-paste
const QByteArray source =
"const int $x = 12;\n"
"int main()\n"
"{\n"
" enum { x = @x }; // x refers to global x\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run(/*expectedFail =*/ true);
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_selfInitialization()
{
// 3.3.2 Point of declaration
const QByteArray source =
"int x = 12;\n"
"int main()\n"
"{\n"
" int $x = @x; // Second x refers to local x\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_pointerToClassInClassDefinition()
{
// 3.3.2 Point of declaration (par. 3), from text
const QByteArray source =
"class $Foo {\n"
" @Foo *p; // Refers to above Foo\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_previouslyDefinedMemberFromArrayDefinition()
{
// 3.3.2 Point of declaration (par. 5), copy-paste
const QByteArray source =
"struct X {\n"
" enum E { $z = 16 };\n"
" int b[X::@z]; // z refers to defined z\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_outerStaticMemberVariableFromInsideSubclass()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" struct I\n"
" {\n"
" void f()\n" // Line 5
" {\n"
" int i = @c; // refers to C's c\n"
" }\n"
" };\n"
"\n" // Line 10
" static int $c;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_memberVariableFollowingDotOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C c;\n"
" c.@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_memberVariableFollowingArrowOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C* c;\n"
" c->@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingScopeOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C::@member++;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingDotOperator()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C c;\n"
" c.@member;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingArrowOperator()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C *c;\n"
" c->@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_previouslyDefinedEnumValueFromInsideEnum()
{
// 3.3.8 Enumeration scope
const QByteArray source =
"enum {\n"
" $i = 0,\n"
" j = @i // refers to i above\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_nsMemberHidesNsMemberIntroducedByUsingDirective()
{
// 3.3.8 Enumeration scope
const QByteArray source =
"namespace A {\n"
" char x;\n"
"}\n"
"\n"
"namespace B {\n" // Line 5
" using namespace A;\n"
" int $x; // hides A::x\n"
"}\n"
"\n"
"int main()\n" // Line 10
"{\n"
" B::@x++; // refers to B's X, not A::x\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_baseClassFunctionIntroducedByUsingDeclaration()
{
// 3.3.10 Name hiding, from text
// www.stroustrup.com/bs_faq2.html#overloadderived
const QByteArray source =
"struct B {\n"
" int $f(int) {}\n"
"};\n"
"\n"
"class D : public B {\n" // Line 5
"public:\n"
" using B::f; // make every f from B available\n"
" double f(double) {}\n"
"};\n"
"\n" // Line 10
"int main()\n"
"{\n"
" D* pd = new D;\n"
" pd->@f(2); // refers to B::f\n"
" pd->f(2.3); // refers to D::f\n" // Line 15
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funWithSameNameAsBaseClassFunIntroducedByUsingDeclaration()
{
// 3.3.10 Name hiding, from text
// www.stroustrup.com/bs_faq2.html#overloadderived
const QByteArray source =
"struct B {\n"
" int f(int) {}\n"
"};\n"
"\n"
"class D : public B {\n" // Line 5
"public:\n"
" using B::f; // make every f from B available\n"
" double $f(double) {}\n"
"};\n"
"\n" // Line 10
"int main()\n"
"{\n"
" D* pd = new D;\n"
" pd->f(2); // refers to B::f\n"
" pd->@f(2.3); // refers to D::f\n" // Line 15
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesOuterClass()
{
// 3.3.10 Name hiding (par 2.), from text
// A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member,
// function, or enumerator declared in the same scope.
const QByteArray source =
"struct C {};\n"
"\n"
"int main()\n"
"{\n"
" int $C; // hides type C\n" // Line 5
" ++@C;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classConstructor()
{
const QByteArray source =
"class Foo {\n"
" F@oo();"
" ~Foo();"
"};\n\n"
"Foo::$Foo()\n"
"{\n"
"}\n\n"
"Foo::~Foo()\n"
"{\n"
"}\n";
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classDestructor()
{
const QByteArray source =
"class Foo {\n"
" Foo();"
" ~@Foo();"
"};\n\n"
"Foo::Foo()\n"
"{\n"
"}\n\n"
"Foo::~$Foo()\n"
"{\n"
"}\n";
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_QObject_connect_data()
{
#define TAG(str) secondQObjectParam ? str : str ", no 2nd QObject"
QTest::addColumn<char>("start");
QTest::addColumn<char>("target");
QTest::addColumn<bool>("secondQObjectParam");
for (int i = 0; i < 2; ++i) {
bool secondQObjectParam = (i == 0);
QTest::newRow(TAG("SIGNAL: before keyword"))
<< '1' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: in keyword"))
<< '2' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before parenthesis"))
<< '3' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before identifier"))
<< '4' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: in identifier"))
<< '5' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before identifier parenthesis"))
<< '6' << '1' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before keyword"))
<< '7' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: in keyword"))
<< '8' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before parenthesis"))
<< '9' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before identifier"))
<< 'A' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: in identifier"))
<< 'B' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before identifier parenthesis"))
<< 'C' << '2' << secondQObjectParam;
}
#undef TAG
}
static void selectMarker(QByteArray *source, char marker, char number)
{
int idx = 0;
forever {
idx = source->indexOf(marker, idx);
if (idx == -1)
break;
if (source->at(idx + 1) == number) {
++idx;
source->remove(idx, 1);
} else {
source->remove(idx, 2);
}
}
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_QObject_connect()
{
QFETCH(char, start);
QFETCH(char, target);
QFETCH(bool, secondQObjectParam);
QByteArray source =
"class Foo : public QObject\n"
"{\n"
"signals:\n"
" void $1endOfWorld();\n"
"public slots:\n"
" void $2onWorldEnded()\n"
" {\n"
" }\n"
"};\n"
"\n"
"void bla()\n"
"{\n"
" Foo foo;\n"
" connect(&foo, @1SI@2GNAL@3(@4end@5OfWorld@6()),\n"
" &foo, @7SL@8OT@9(@Aon@BWorldEnded@C()));\n"
"}\n";
selectMarker(&source, '@', start);
selectMarker(&source, '$', target);
if (!secondQObjectParam)
source.replace(" &foo, ", QByteArray());
if (start >= '7' && !secondQObjectParam) {
qWarning("SLOT jump triggers QTCREATORBUG-10265. Skipping.");
return;
}
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data()
{
QTest::addColumn<bool>("toDeclaration");
QTest::newRow("forward") << false;
QTest::newRow("backward") << true;
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_onOperatorToken()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void @operator[](size_t idx);\n"
"};\n\n"
"void Foo::$operator[](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace('@', '#').replace('$', '@').replace('#', '$');
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_data()
{
test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void $2operator@1[](size_t idx);\n"
"};\n\n"
"void Foo::$1operator@2[](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace("@1", QByteArray()).replace("$1", QByteArray())
.replace("@2", "@").replace("$2", "$");
else
source.replace("@2", QByteArray()).replace("$2", QByteArray())
.replace("@1", "@").replace("$1", "$");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_inOp_data()
{
test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_inOp()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void $2operator[@1](size_t idx);\n"
"};\n\n"
"void Foo::$1operator[@2](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace("@1", QByteArray()).replace("$1", QByteArray())
.replace("@2", "@").replace("$2", "$");
else
source.replace("@2", QByteArray()).replace("$2", QByteArray())
.replace("@1", "@").replace("$1", "$");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_globalNamespace()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"using NS::$Foo;\n"
"void fun()\n"
"{\n"
" @Foo foo;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_namespace()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"namespace NS1 {\n"
"void fun()\n"
"{\n"
" using NS::$Foo;\n"
" @Foo foo;\n"
"}\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_insideFunction()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"void fun()\n"
"{\n"
" using NS::$Foo;\n"
" @Foo foo;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Static type is base class pointer, all overrides are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_allOverrides()
{
const QByteArray source =
"struct A { virtual void virt() = 0; };\n"
"void A::virt() {}\n"
"\n"
"struct B : A { void virt(); };\n"
"void B::virt() {}\n"
"\n"
"struct C : B { void virt(); };\n"
"void C::virt() {}\n"
"\n"
"struct CD1 : C { void virt(); };\n"
"void CD1::virt() {}\n"
"\n"
"struct CD2 : C { void virt(); };\n"
"void CD2::virt() {}\n"
"\n"
"int f(A *o)\n"
"{\n"
" o->$@virt();\n"
"}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("A::virt")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("A::virt")
<< QLatin1String("B::virt")
<< QLatin1String("C::virt")
<< QLatin1String("CD1::virt")
<< QLatin1String("CD2::virt");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Static type is derived class pointer, only overrides of sub classes are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_possibleOverrides1()
{
const QByteArray source =
"struct A { virtual void virt() = 0; };\n"
"void A::virt() {}\n"
"\n"
"struct B : A { void virt(); };\n"
"void B::virt() {}\n"
"\n"
"struct C : B { void virt(); };\n"
"void C::virt() {}\n"
"\n"
"struct CD1 : C { void virt(); };\n"
"void CD1::virt() {}\n"
"\n"
"struct CD2 : C { void virt(); };\n"
"void CD2::virt() {}\n"
"\n"
"int f(B *o)\n"
"{\n"
" o->$@virt();\n"
"}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("C::virt")
<< QLatin1String("CD1::virt")
<< QLatin1String("CD2::virt");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Virtual function call in member of class hierarchy, only possible overrides are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_possibleOverrides2()
{
const QByteArray source =
"struct A { virtual void f(); };\n"
"void A::f() {}\n"
"\n"
"struct B : public A { void f(); };\n"
"void B::f() {}\n"
"\n"
"struct C : public B { void g() { f$@(); } }; \n"
"\n"
"struct D : public C { void f(); };\n"
"void D::f() {}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("B::f")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("B::f")
<< QLatin1String("D::f");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Do not trigger on qualified function calls.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnQualified()
{
const QByteArray source =
"struct A { virtual void f(); };\n"
"void A::$f() {}\n"
"\n"
"struct B : public A {\n"
" void f();\n"
" void g() { A::@f(); }\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Do not trigger on member function declaration.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnDeclaration()
{
const QByteArray source =
"struct A { virtual void f(); };\n"
"void A::f() {}\n"
"\n"
"struct B : public A { void f@(); };\n"
"void B::$f() {}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Do not trigger on function definition.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnDefinition()
{
const QByteArray source =
"struct A { virtual void f(); };\n"
"void A::f() {}\n"
"\n"
"struct B : public A { void $f(); };\n"
"void B::@f() {}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnNonPointerNonReference()
{
const QByteArray source =
"struct A { virtual void f(); };\n"
"void A::f() {}\n"
"\n"
"struct B : public A { void f(); };\n"
"void B::$f() {}\n"
"\n"
"void client(B b) { b.@f(); }\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/*
Potential test cases improving name lookup.
If you fix one, add a test and remove the example from here.
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.1 Declarative regions and scopes, copy-paste (main added)
int j = 24;
int main()
{
int i = j, j; // First j refers to global j, second j refers to just locally defined j
j = 42; // Refers to locally defined j
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.2 Point of declaration (par. 2), copy-paste (main added)
const int i = 2;
int main()
{
int i[i]; // Second i refers to global
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.2 Point of declaration (par. 9), copy-paste (main added)
typedef unsigned char T;
template<class T
= T // lookup finds the typedef name of unsigned char
, T // lookup finds the template parameter
N = 0> struct A { };
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 3), copy-paste (main added), part 1
template<class T, T* p, class U = T> class X {}; // second and third T refers to first one
template<class T> void f(T* p = new T);
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 3), copy-paste (main added), part 2
template<class T> class X : public Array<T> {};
template<class T> class Y : public T {};
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 4), copy-paste (main added), part 2
typedef int N;
template<N X, typename N, template<N Y> class T> struct A; // N refers to N above
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.10 Name hiding (par 1.), from text, example 2a
// www.stroustrup.com/bs_faq2.html#overloadderived
// "In C++, there is no overloading across scopes - derived class scopes are not
// an exception to this general rule. (See D&E or TC++PL3 for details)."
struct B {
int f(int) {}
};
struct D : public B {
double f(double) {} // hides B::f
};
int main()
{
D* pd = new D;
pd->f(2); // refers to D::f
pd->f(2.3); // refers to D::f
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.10 Name hiding (par 2.), from text
int C; // hides following type C, order is not important
struct C {};
int main()
{
++C;
}
*/
CppEditor: Clean up followsymbol_switchmethoddecldef_test.cpp
with respect to test_FollowSymbolUnderCursor_virtualFunctionCall*
functions:
- Use same function names in test code
- Shorten test code
- Mimic GenericProposalWidget::showProposal() calls more completely
VirtualFunctionTestAssistProvider::itemList()
Change-Id: Ie1bae5f00d550a9a61981945de41daf6bfeee5ff
Reviewed-by: Erik Verbruggen <5edfe905d082749f2ac3f4e6b42937f39f083771@digia.com>
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "cppeditor.h"
#include "cppeditorplugin.h"
#include "cppelementevaluator.h"
#include "cppvirtualfunctionassistprovider.h"
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <utils/fileutils.h>
#include <QDebug>
#include <QDir>
#include <QtTest>
/*!
Tests for Follow Symbol Under Cursor and Switch Between Function Declaration/Definition
Section numbers refer to
Working Draft, Standard for Programming Language C++
Document Number: N3242=11-0012
You can find potential test code for Follow Symbol Under Cursor on the bottom of this file.
*/
using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
using namespace TextEditor;
using namespace Core;
namespace {
/// A fake virtual functions assist provider that runs processor->perform() already in configure()
class VirtualFunctionTestAssistProvider : public VirtualFunctionAssistProvider
{
public:
VirtualFunctionTestAssistProvider(CPPEditorWidget *editorWidget)
: m_editorWidget(editorWidget)
{}
// Invoke the processor already here to calculate the proposals. Return false in order to
// indicate that configure failed, so the actual code assist invocation leading to a pop-up
// will not happen.
bool configure(CPlusPlus::Class *startClass, CPlusPlus::Function *function,
const CPlusPlus::Snapshot &snapshot, bool openInNextSplit)
{
VirtualFunctionAssistProvider::configure(startClass, function, snapshot, openInNextSplit);
IAssistProcessor *processor = createProcessor();
IAssistInterface *assistInterface = m_editorWidget->createAssistInterface(FollowSymbol,
ExplicitlyInvoked);
IAssistProposal *immediateProposal = processor->immediateProposal(assistInterface);
IAssistProposal *finalProposal = processor->perform(assistInterface);
m_immediateItems = itemList(immediateProposal->model());
m_finalItems = itemList(finalProposal->model());
return false;
}
static QStringList itemList(IAssistProposalModel *imodel)
{
QStringList immediateItems;
BasicProposalItemListModel *model = dynamic_cast<BasicProposalItemListModel *>(imodel);
if (!model)
return immediateItems;
// Mimic relevant GenericProposalWidget::showProposal() calls
model->removeDuplicates();
model->reset();
if (model->isSortable(QString()))
model->sort(QString());
for (int i = 0, size = model->size(); i < size; ++i) {
const QString text = model->text(i);
immediateItems.append(text);
}
return immediateItems;
}
public:
QStringList m_immediateItems;
QStringList m_finalItems;
private:
CPPEditorWidget *m_editorWidget;
};
class TestDocument;
typedef QSharedPointer<TestDocument> TestDocumentPtr;
/**
* Represents a test document.
*
* A TestDocument's source can contain special characters:
* - a '@' character denotes the initial text cursor position
* - a '$' character denotes the target text cursor position
*/
class TestDocument
{
public:
TestDocument(const QByteArray &theSource, const QString &fileName)
: source(theSource)
, fileName(fileName)
, initialCursorPosition(source.indexOf('@'))
, targetCursorPosition(source.indexOf('$'))
, editor(0)
, editorWidget(0)
{
QVERIFY(initialCursorPosition != targetCursorPosition);
if (initialCursorPosition > targetCursorPosition) {
source.remove(initialCursorPosition, 1);
if (targetCursorPosition != -1) {
source.remove(targetCursorPosition, 1);
--initialCursorPosition;
}
} else {
source.remove(targetCursorPosition, 1);
if (initialCursorPosition != -1) {
source.remove(initialCursorPosition, 1);
--targetCursorPosition;
}
}
}
static TestDocumentPtr create(const QByteArray &theOriginalSource, const QString &fileName)
{
return TestDocumentPtr(new TestDocument(theOriginalSource, fileName));
}
bool hasInitialCursorMarker() const { return initialCursorPosition != -1; }
bool hasTargetCursorMarker() const { return targetCursorPosition != -1; }
QString filePath() const
{
if (directoryPath.isEmpty())
qDebug() << "directoryPath not set!";
return directoryPath + QLatin1Char('/') + fileName;
}
void writeToDisk() const
{
Utils::FileSaver srcSaver(filePath());
srcSaver.write(source);
srcSaver.finalize();
}
QByteArray source;
const QString fileName;
QString directoryPath;
int initialCursorPosition;
int targetCursorPosition;
CPPEditor *editor;
CPPEditorWidget *editorWidget;
};
/**
* Encapsulates the whole process of setting up several editors, positioning the cursor,
* executing Follow Symbol Under Cursor or Switch Between Function Declaration/Definition
* and checking the result.
*/
class TestCase
{
public:
enum CppEditorAction {
FollowSymbolUnderCursorAction,
SwitchBetweenMethodDeclarationDefinitionAction
};
TestCase(CppEditorAction action, const QByteArray &source,
const QStringList &expectedVirtualFunctionImmediateProposal = QStringList(),
const QStringList &expectedVirtualFunctionFinalProposal = QStringList());
TestCase(CppEditorAction action, const QList<TestDocumentPtr> theTestFiles,
const QStringList &expectedVirtualSymbolsImmediateProposal = QStringList(),
const QStringList &expectedVirtualSymbolsFinalProposal = QStringList());
~TestCase();
void run(bool expectedFail = false);
private:
TestCase(const TestCase &);
TestCase &operator=(const TestCase &);
void init();
TestDocumentPtr testFileWithInitialCursorMarker();
TestDocumentPtr testFileWithTargetCursorMarker();
private:
CppEditorAction m_action;
QList<TestDocumentPtr> m_testFiles;
QStringList m_expectedVirtualSymbolsImmediateProposal; // for virtual functions
QStringList m_expectedVirtualSymbolsFinalProposals; // for virtual functions
};
/// Convenience function for creating a TestDocument.
/// See TestDocument.
TestCase::TestCase(CppEditorAction action, const QByteArray &source,
const QStringList &expectedVirtualFunctionImmediateProposal,
const QStringList &expectedVirtualFunctionFinalProposal)
: m_action(action)
, m_expectedVirtualSymbolsImmediateProposal(expectedVirtualFunctionImmediateProposal)
, m_expectedVirtualSymbolsFinalProposals(expectedVirtualFunctionFinalProposal)
{
m_testFiles << TestDocument::create(source, QLatin1String("file.cpp"));
init();
}
/// Creates a test case with multiple test files.
/// Exactly one test document must be provided that contains '@', the initial position marker.
/// Exactly one test document must be provided that contains '$', the target position marker.
/// It can be the same document.
TestCase::TestCase(CppEditorAction action, const QList<TestDocumentPtr> theTestFiles,
const QStringList &expectedVirtualSymbolsImmediateProposal,
const QStringList &expectedVirtualSymbolsFinalProposal)
: m_action(action)
, m_testFiles(theTestFiles)
, m_expectedVirtualSymbolsImmediateProposal(expectedVirtualSymbolsImmediateProposal)
, m_expectedVirtualSymbolsFinalProposals(expectedVirtualSymbolsFinalProposal)
{
init();
}
void TestCase::init()
{
// Check if there are initial and target position markers
QVERIFY2(testFileWithInitialCursorMarker(),
"No test file with initial cursor marker is provided.");
QVERIFY2(testFileWithTargetCursorMarker(),
"No test file with target cursor marker is provided.");
// Write files to disk
const QString directoryPath = QDir::tempPath();
foreach (TestDocumentPtr testFile, m_testFiles) {
testFile->directoryPath = directoryPath;
testFile->writeToDisk();
}
// Update Code Model
QStringList filePaths;
foreach (const TestDocumentPtr &testFile, m_testFiles)
filePaths << testFile->filePath();
CppTools::CppModelManagerInterface::instance()->updateSourceFiles(filePaths);
// Wait for the indexer to process all files.
// All these files are "Fast Checked", that is the function bodies are not processed.
QStringList filePathsNotYetInSnapshot(filePaths);
forever {
Snapshot snapshot = CppTools::CppModelManagerInterface::instance()->snapshot();
foreach (const QString &filePath, filePathsNotYetInSnapshot) {
if (snapshot.contains(filePath))
filePathsNotYetInSnapshot.removeOne(filePath);
}
if (filePathsNotYetInSnapshot.isEmpty())
break;
QCoreApplication::processEvents();
}
// Open Files
foreach (TestDocumentPtr testFile, m_testFiles) {
testFile->editor
= dynamic_cast<CPPEditor *>(EditorManager::openEditor(testFile->filePath()));
QVERIFY(testFile->editor);
testFile->editorWidget = dynamic_cast<CPPEditorWidget *>(testFile->editor->editorWidget());
QVERIFY(testFile->editorWidget);
// Wait until the indexer processed the just opened file.
// The file is "Full Checked" since it is in the working copy now,
// that is the function bodies are processed.
forever {
Snapshot snapshot = CppTools::CppModelManagerInterface::instance()->snapshot();
if (Document::Ptr document = snapshot.document(testFile->filePath())) {
if (document->checkMode() == Document::FullCheck)
break;
QCoreApplication::processEvents();
}
}
// Rehighlight
testFile->editorWidget->semanticRehighlight(true);
// Wait for the semantic info from the future
while (testFile->editorWidget->semanticInfo().doc.isNull())
QCoreApplication::processEvents();
}
}
TestCase::~TestCase()
{
// Close editors
QList<Core::IEditor *> editorsToClose;
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->editor)
editorsToClose << testFile->editor;
}
EditorManager::closeEditors(editorsToClose, false);
QCoreApplication::processEvents(); // process any pending events
// Remove the test files from the code-model
CppModelManagerInterface *mmi = CppTools::CppModelManagerInterface::instance();
mmi->GC();
QCOMPARE(mmi->snapshot().size(), 0);
}
TestDocumentPtr TestCase::testFileWithInitialCursorMarker()
{
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->hasInitialCursorMarker())
return testFile;
}
return TestDocumentPtr();
}
TestDocumentPtr TestCase::testFileWithTargetCursorMarker()
{
foreach (const TestDocumentPtr testFile, m_testFiles) {
if (testFile->hasTargetCursorMarker())
return testFile;
}
return TestDocumentPtr();
}
void TestCase::run(bool expectedFail)
{
TestDocumentPtr initialTestFile = testFileWithInitialCursorMarker();
QVERIFY(initialTestFile);
TestDocumentPtr targetTestFile = testFileWithTargetCursorMarker();
QVERIFY(targetTestFile);
// Activate editor of initial test file
EditorManager::activateEditor(initialTestFile->editor);
initialTestFile->editor->setCursorPosition(initialTestFile->initialCursorPosition);
// qDebug() << "Initial line:" << initialTestFile->editor->currentLine();
// qDebug() << "Initial column:" << initialTestFile->editor->currentColumn() - 1;
QStringList immediateVirtualSymbolResults;
QStringList finalVirtualSymbolResults;
// Trigger the action
switch (m_action) {
case FollowSymbolUnderCursorAction: {
CPPEditorWidget *widget = initialTestFile->editorWidget;
FollowSymbolUnderCursor *delegate = widget->followSymbolUnderCursorDelegate();
VirtualFunctionAssistProvider *original = delegate->virtualFunctionAssistProvider();
// Set test provider, run and get results
QScopedPointer<VirtualFunctionTestAssistProvider> testProvider(
new VirtualFunctionTestAssistProvider(widget));
delegate->setVirtualFunctionAssistProvider(testProvider.data());
initialTestFile->editorWidget->openLinkUnderCursor();
immediateVirtualSymbolResults = testProvider->m_immediateItems;
finalVirtualSymbolResults = testProvider->m_finalItems;
// Restore original test provider
delegate->setVirtualFunctionAssistProvider(original);
break;
}
case SwitchBetweenMethodDeclarationDefinitionAction:
CppEditorPlugin::instance()->switchDeclarationDefinition();
break;
default:
QFAIL("Unknown test action");
break;
}
QCoreApplication::processEvents();
// Compare
IEditor *currentEditor = EditorManager::currentEditor();
BaseTextEditor *currentTextEditor = dynamic_cast<BaseTextEditor*>(currentEditor);
QVERIFY(currentTextEditor);
QCOMPARE(currentTextEditor->document()->filePath(), targetTestFile->filePath());
int expectedLine, expectedColumn;
currentTextEditor->convertPosition(targetTestFile->targetCursorPosition,
&expectedLine, &expectedColumn);
// qDebug() << "Expected line:" << expectedLine;
// qDebug() << "Expected column:" << expectedColumn;
if (expectedFail)
QEXPECT_FAIL("", "Contributor works on a fix.", Abort);
QCOMPARE(currentTextEditor->currentLine(), expectedLine);
QCOMPARE(currentTextEditor->currentColumn() - 1, expectedColumn);
// qDebug() << immediateVirtualSymbolResults;
// qDebug() << finalVirtualSymbolResults;
QCOMPARE(immediateVirtualSymbolResults, m_expectedVirtualSymbolsImmediateProposal);
QCOMPARE(finalVirtualSymbolResults, m_expectedVirtualSymbolsFinalProposals);
}
} // anonymous namespace
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionDeclarationSymbol()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int @function();\n" // Line 5
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"int C::$function()\n"
"{\n"
" return 1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionDefinitionSymbol()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n"
"\n"
"int C::@function()\n"
"{\n"
" return 1 + 1;\n"
"}\n"
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromFunctionBody()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"int C::function()\n"
"{\n"
" return @1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
void CppEditorPlugin::test_SwitchMethodDeclarationDefinition_fromReturnType()
{
QList<TestDocumentPtr> testFiles;
const QByteArray headerContents =
"class C\n"
"{\n"
"public:\n"
" C();\n"
" int $function();\n"
"};\n"
;
testFiles << TestDocument::create(headerContents, QLatin1String("file.h"));
const QByteArray sourceContents =
"#include \"file.h\"\n"
"\n"
"C::C()\n"
"{\n"
"}\n" // Line 5
"\n"
"@int C::function()\n"
"{\n"
" return 1 + 1;\n"
"}\n" // Line 10
;
testFiles << TestDocument::create(sourceContents, QLatin1String("file.cpp"));
TestCase test(TestCase::SwitchBetweenMethodDeclarationDefinitionAction, testFiles);
test.run();
}
/// Check ...
void CppEditorPlugin::test_FollowSymbolUnderCursor_globalVarFromFunction()
{
const QByteArray source =
"int $j;\n"
"int main()\n"
"{\n"
" @j = 2;\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesClassMember()
{
// 3.3.10 Name hiding (par 3.), from text
const QByteArray source =
"struct C {\n"
" void f()\n"
" {\n"
" int $member; // hides C::member\n"
" ++@member;\n" // Line 5
" }\n"
" int member;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesNamespaceMemberIntroducedByUsingDirective()
{
// 3.3.10 Name hiding (par 4.), from text
const QByteArray source =
"namespace N {\n"
" int i;\n"
"}\n"
"\n"
"int main()\n" // Line 5
"{\n"
" using namespace N;\n"
" int $i;\n"
" ++i@; // refers to local i;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_loopLocalVarHidesOuterScopeVariable1()
{
// 3.3.3 Block scope (par. 4), from text
// Same for if, while, switch
const QByteArray source =
"int main()\n"
"{\n"
" int i = 1;\n"
" for (int $i = 0; i < 10; ++i) { // 'i' refers to for's i\n"
" i = @i; // same\n" // Line 5
" }\n"
"}\n";
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_loopLocalVarHidesOuterScopeVariable2()
{
// 3.3.3 Block scope (par. 4), from text
// Same for if, while, switch
const QByteArray source =
"int main()\n"
"{\n"
" int i = 1;\n"
" for (int $i = 0; @i < 10; ++i) { // 'i' refers to for's i\n"
" i = i; // same\n" // Line 5
" }\n"
"}\n";
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_subsequentDefinedClassMember()
{
// 3.3.7 Class scope, part of the example
const QByteArray source =
"class X {\n"
" int f() { return @i; } // i refers to class's i\n"
" int $i;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classMemberHidesOuterTypeDef()
{
// 3.3.7 Class scope, part of the example
// Variable name hides type name.
const QByteArray source =
"typedef int c;\n"
"class X {\n"
" int f() { return @c; } // c refers to class' c\n"
" int $c; // hides typedef name\n"
"};\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_globalVarFromEnum()
{
// 3.3.2 Point of declaration (par. 1), copy-paste
const QByteArray source =
"const int $x = 12;\n"
"int main()\n"
"{\n"
" enum { x = @x }; // x refers to global x\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run(/*expectedFail =*/ true);
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_selfInitialization()
{
// 3.3.2 Point of declaration
const QByteArray source =
"int x = 12;\n"
"int main()\n"
"{\n"
" int $x = @x; // Second x refers to local x\n"
"}\n" // Line 5
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_pointerToClassInClassDefinition()
{
// 3.3.2 Point of declaration (par. 3), from text
const QByteArray source =
"class $Foo {\n"
" @Foo *p; // Refers to above Foo\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_previouslyDefinedMemberFromArrayDefinition()
{
// 3.3.2 Point of declaration (par. 5), copy-paste
const QByteArray source =
"struct X {\n"
" enum E { $z = 16 };\n"
" int b[X::@z]; // z refers to defined z\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_outerStaticMemberVariableFromInsideSubclass()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" struct I\n"
" {\n"
" void f()\n" // Line 5
" {\n"
" int i = @c; // refers to C's c\n"
" }\n"
" };\n"
"\n" // Line 10
" static int $c;\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_memberVariableFollowingDotOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C c;\n"
" c.@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_memberVariableFollowingArrowOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C* c;\n"
" c->@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingScopeOperator()
{
// 3.3.7 Class scope (par. 1), part of point 5
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C::@member++;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingDotOperator()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C c;\n"
" c.@member;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_staticMemberVariableFollowingArrowOperator()
{
// 3.3.7 Class scope (par. 2), from text
const QByteArray source =
"struct C\n"
"{\n"
" static int $member;\n"
"};\n"
"\n" // Line 5
"int main()\n"
"{\n"
" C *c;\n"
" c->@member++;\n"
"}\n" // Line 10
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_previouslyDefinedEnumValueFromInsideEnum()
{
// 3.3.8 Enumeration scope
const QByteArray source =
"enum {\n"
" $i = 0,\n"
" j = @i // refers to i above\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_nsMemberHidesNsMemberIntroducedByUsingDirective()
{
// 3.3.8 Enumeration scope
const QByteArray source =
"namespace A {\n"
" char x;\n"
"}\n"
"\n"
"namespace B {\n" // Line 5
" using namespace A;\n"
" int $x; // hides A::x\n"
"}\n"
"\n"
"int main()\n" // Line 10
"{\n"
" B::@x++; // refers to B's X, not A::x\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_baseClassFunctionIntroducedByUsingDeclaration()
{
// 3.3.10 Name hiding, from text
// www.stroustrup.com/bs_faq2.html#overloadderived
const QByteArray source =
"struct B {\n"
" int $f(int) {}\n"
"};\n"
"\n"
"class D : public B {\n" // Line 5
"public:\n"
" using B::f; // make every f from B available\n"
" double f(double) {}\n"
"};\n"
"\n" // Line 10
"int main()\n"
"{\n"
" D* pd = new D;\n"
" pd->@f(2); // refers to B::f\n"
" pd->f(2.3); // refers to D::f\n" // Line 15
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funWithSameNameAsBaseClassFunIntroducedByUsingDeclaration()
{
// 3.3.10 Name hiding, from text
// www.stroustrup.com/bs_faq2.html#overloadderived
const QByteArray source =
"struct B {\n"
" int f(int) {}\n"
"};\n"
"\n"
"class D : public B {\n" // Line 5
"public:\n"
" using B::f; // make every f from B available\n"
" double $f(double) {}\n"
"};\n"
"\n" // Line 10
"int main()\n"
"{\n"
" D* pd = new D;\n"
" pd->f(2); // refers to B::f\n"
" pd->@f(2.3); // refers to D::f\n" // Line 15
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesOuterClass()
{
// 3.3.10 Name hiding (par 2.), from text
// A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member,
// function, or enumerator declared in the same scope.
const QByteArray source =
"struct C {};\n"
"\n"
"int main()\n"
"{\n"
" int $C; // hides type C\n" // Line 5
" ++@C;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classConstructor()
{
const QByteArray source =
"class Foo {\n"
" F@oo();"
" ~Foo();"
"};\n\n"
"Foo::$Foo()\n"
"{\n"
"}\n\n"
"Foo::~Foo()\n"
"{\n"
"}\n";
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classDestructor()
{
const QByteArray source =
"class Foo {\n"
" Foo();"
" ~@Foo();"
"};\n\n"
"Foo::Foo()\n"
"{\n"
"}\n\n"
"Foo::~$Foo()\n"
"{\n"
"}\n";
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_QObject_connect_data()
{
#define TAG(str) secondQObjectParam ? str : str ", no 2nd QObject"
QTest::addColumn<char>("start");
QTest::addColumn<char>("target");
QTest::addColumn<bool>("secondQObjectParam");
for (int i = 0; i < 2; ++i) {
bool secondQObjectParam = (i == 0);
QTest::newRow(TAG("SIGNAL: before keyword"))
<< '1' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: in keyword"))
<< '2' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before parenthesis"))
<< '3' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before identifier"))
<< '4' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: in identifier"))
<< '5' << '1' << secondQObjectParam;
QTest::newRow(TAG("SIGNAL: before identifier parenthesis"))
<< '6' << '1' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before keyword"))
<< '7' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: in keyword"))
<< '8' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before parenthesis"))
<< '9' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before identifier"))
<< 'A' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: in identifier"))
<< 'B' << '2' << secondQObjectParam;
QTest::newRow(TAG("SLOT: before identifier parenthesis"))
<< 'C' << '2' << secondQObjectParam;
}
#undef TAG
}
static void selectMarker(QByteArray *source, char marker, char number)
{
int idx = 0;
forever {
idx = source->indexOf(marker, idx);
if (idx == -1)
break;
if (source->at(idx + 1) == number) {
++idx;
source->remove(idx, 1);
} else {
source->remove(idx, 2);
}
}
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_QObject_connect()
{
QFETCH(char, start);
QFETCH(char, target);
QFETCH(bool, secondQObjectParam);
QByteArray source =
"class Foo : public QObject\n"
"{\n"
"signals:\n"
" void $1endOfWorld();\n"
"public slots:\n"
" void $2onWorldEnded()\n"
" {\n"
" }\n"
"};\n"
"\n"
"void bla()\n"
"{\n"
" Foo foo;\n"
" connect(&foo, @1SI@2GNAL@3(@4end@5OfWorld@6()),\n"
" &foo, @7SL@8OT@9(@Aon@BWorldEnded@C()));\n"
"}\n";
selectMarker(&source, '@', start);
selectMarker(&source, '$', target);
if (!secondQObjectParam)
source.replace(" &foo, ", QByteArray());
if (start >= '7' && !secondQObjectParam) {
qWarning("SLOT jump triggers QTCREATORBUG-10265. Skipping.");
return;
}
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data()
{
QTest::addColumn<bool>("toDeclaration");
QTest::newRow("forward") << false;
QTest::newRow("backward") << true;
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_onOperatorToken()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void @operator[](size_t idx);\n"
"};\n\n"
"void Foo::$operator[](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace('@', '#').replace('$', '@').replace('#', '$');
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_data()
{
test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void $2operator@1[](size_t idx);\n"
"};\n\n"
"void Foo::$1operator@2[](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace("@1", QByteArray()).replace("$1", QByteArray())
.replace("@2", "@").replace("$2", "$");
else
source.replace("@2", QByteArray()).replace("$2", QByteArray())
.replace("@1", "@").replace("$1", "$");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_inOp_data()
{
test_FollowSymbolUnderCursor_classOperator_onOperatorToken_data();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_classOperator_inOp()
{
QFETCH(bool, toDeclaration);
QByteArray source =
"class Foo {\n"
" void $2operator[@1](size_t idx);\n"
"};\n\n"
"void Foo::$1operator[@2](size_t idx)\n"
"{\n"
"}\n";
if (toDeclaration)
source.replace("@1", QByteArray()).replace("$1", QByteArray())
.replace("@2", "@").replace("$2", "$");
else
source.replace("@2", QByteArray()).replace("$2", QByteArray())
.replace("@1", "@").replace("$1", "$");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_globalNamespace()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"using NS::$Foo;\n"
"void fun()\n"
"{\n"
" @Foo foo;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_namespace()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"namespace NS1 {\n"
"void fun()\n"
"{\n"
" using NS::$Foo;\n"
" @Foo foo;\n"
"}\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_insideFunction()
{
const QByteArray source =
"namespace NS {\n"
"class Foo {};\n"
"}\n"
"void fun()\n"
"{\n"
" using NS::$Foo;\n"
" @Foo foo;\n"
"}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Static type is base class pointer, all overrides are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_allOverrides()
{
const QByteArray source =
"struct A { virtual void virt() = 0; };\n"
"void A::virt() {}\n"
"\n"
"struct B : A { void virt(); };\n"
"void B::virt() {}\n"
"\n"
"struct C : B { void virt(); };\n"
"void C::virt() {}\n"
"\n"
"struct CD1 : C { void virt(); };\n"
"void CD1::virt() {}\n"
"\n"
"struct CD2 : C { void virt(); };\n"
"void CD2::virt() {}\n"
"\n"
"int f(A *o) { o->$@virt(); }\n"
"}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("A::virt")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("A::virt")
<< QLatin1String("B::virt")
<< QLatin1String("C::virt")
<< QLatin1String("CD1::virt")
<< QLatin1String("CD2::virt");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Static type is derived class pointer, only overrides of sub classes are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_possibleOverrides1()
{
const QByteArray source =
"struct A { virtual void virt() = 0; };\n"
"void A::virt() {}\n"
"\n"
"struct B : A { void virt(); };\n"
"void B::virt() {}\n"
"\n"
"struct C : B { void virt(); };\n"
"void C::virt() {}\n"
"\n"
"struct CD1 : C { void virt(); };\n"
"void CD1::virt() {}\n"
"\n"
"struct CD2 : C { void virt(); };\n"
"void CD2::virt() {}\n"
"\n"
"int f(B *o) { o->$@virt(); }\n"
"}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("C::virt")
<< QLatin1String("CD1::virt")
<< QLatin1String("CD2::virt");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Virtual function call in member of class hierarchy, only possible overrides are presented.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_possibleOverrides2()
{
const QByteArray source =
"struct A { virtual void virt(); };\n"
"void A::virt() {}\n"
"\n"
"struct B : public A { void virt(); };\n"
"void B::virt() {}\n"
"\n"
"struct C : public B { void g() { virt$@(); } }; \n"
"\n"
"struct D : public C { void virt(); };\n"
"void D::virt() {}\n"
;
const QStringList immediateResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("...searching overrides");
const QStringList finalResults = QStringList()
<< QLatin1String("B::virt")
<< QLatin1String("D::virt");
TestCase test(TestCase::FollowSymbolUnderCursorAction, source, immediateResults, finalResults);
test.run();
}
/// Check: Do not trigger on qualified function calls.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnQualified()
{
const QByteArray source =
"struct A { virtual void virt(); };\n"
"void A::$virt() {}\n"
"\n"
"struct B : public A {\n"
" void virt();\n"
" void g() { A::@virt(); }\n"
"};\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Do not trigger on member function declaration.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnDeclaration()
{
const QByteArray source =
"struct A { virtual void virt(); };\n"
"void A::virt() {}\n"
"\n"
"struct B : public A { void virt@(); };\n"
"void B::$virt() {}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/// Check: Do not trigger on function definition.
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnDefinition()
{
const QByteArray source =
"struct A { virtual void virt(); };\n"
"void A::virt() {}\n"
"\n"
"struct B : public A { void $virt(); };\n"
"void B::@virt() {}\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_virtualFunctionCall_notOnNonPointerNonReference()
{
const QByteArray source =
"struct A { virtual void virt(); };\n"
"void A::virt() {}\n"
"\n"
"struct B : public A { void virt(); };\n"
"void B::$virt() {}\n"
"\n"
"void client(B b) { b.@virt(); }\n"
;
TestCase test(TestCase::FollowSymbolUnderCursorAction, source);
test.run();
}
/*
Potential test cases improving name lookup.
If you fix one, add a test and remove the example from here.
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.1 Declarative regions and scopes, copy-paste (main added)
int j = 24;
int main()
{
int i = j, j; // First j refers to global j, second j refers to just locally defined j
j = 42; // Refers to locally defined j
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.2 Point of declaration (par. 2), copy-paste (main added)
const int i = 2;
int main()
{
int i[i]; // Second i refers to global
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.2 Point of declaration (par. 9), copy-paste (main added)
typedef unsigned char T;
template<class T
= T // lookup finds the typedef name of unsigned char
, T // lookup finds the template parameter
N = 0> struct A { };
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 3), copy-paste (main added), part 1
template<class T, T* p, class U = T> class X {}; // second and third T refers to first one
template<class T> void f(T* p = new T);
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 3), copy-paste (main added), part 2
template<class T> class X : public Array<T> {};
template<class T> class Y : public T {};
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.9 Template parameter scope (par. 4), copy-paste (main added), part 2
typedef int N;
template<N X, typename N, template<N Y> class T> struct A; // N refers to N above
int main() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.10 Name hiding (par 1.), from text, example 2a
// www.stroustrup.com/bs_faq2.html#overloadderived
// "In C++, there is no overloading across scopes - derived class scopes are not
// an exception to this general rule. (See D&E or TC++PL3 for details)."
struct B {
int f(int) {}
};
struct D : public B {
double f(double) {} // hides B::f
};
int main()
{
D* pd = new D;
pd->f(2); // refers to D::f
pd->f(2.3); // refers to D::f
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// 3.3.10 Name hiding (par 2.), from text
int C; // hides following type C, order is not important
struct C {};
int main()
{
++C;
}
*/
|
/**
@file LMS7002M.cpp
@author Lime Microsystems (www.limemicro.com)
@brief Implementation of LMS7002M transceiver configuring
*/
#include "LMS7002M.h"
#include <stdio.h>
#include <set>
#include "lmsComms.h"
#include "INI.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include "LMS7002M_RegistersMap.h"
#include <chrono>
#include <thread>
float_type LMS7002M::gVCO_frequency_table[3][2] = { { 3800, 5222 }, { 4961, 6754 }, {6306, 7714} };
float_type LMS7002M::gCGEN_VCO_frequencies[2] = {2000, 2700};
///define for parameter enumeration if prefix might be needed
#define LMS7param(id) id
//module addresses needs to be sorted in ascending order
const uint16_t LMS7002M::readOnlyRegisters[] = { 0x002F, 0x008C, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x0123, 0x0209, 0x020A, 0x020B, 0x040E, 0x040F };
const uint16_t LMS7002M::readOnlyRegistersMasks[] = { 0x0000, 0x0FFF, 0x007F, 0x0000, 0x0000, 0x0000, 0x0000, 0x003F, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 };
/** @brief Simple logging function to print status messages
@param text message to print
@param type message type for filtering specific information
*/
void LMS7002M::Log(const char* text, LogType type)
{
switch(type)
{
case LOG_INFO:
printf("%s\n", text);
break;
case LOG_WARNING:
printf("Warning: %s\n", text);
break;
case LOG_ERROR:
printf("ERROR: %s\n", text);
break;
case LOG_DATA:
printf("DATA: %s\n", text);
break;
}
}
LMS7002M::LMS7002M() : controlPort(NULL), mRegistersMap(new LMS7002M_RegistersMap())
{
mRefClkSXR_MHz = 30.72;
mRefClkSXT_MHz = 30.72;
}
/** @brief Creates LMS7002M main control object, it requires LMScomms to communicate with chip
@param controlPort data connection for controlling LMS7002 chip registers
*/
LMS7002M::LMS7002M(LMScomms* controlPort) :
controlPort(controlPort), mRegistersMap(new LMS7002M_RegistersMap())
{
mRefClkSXR_MHz = 30.72;
mRefClkSXT_MHz = 30.72;
//memory intervals for registers tests and calibration algorithms
MemorySectionAddresses[LimeLight][0] = 0x0020;
MemorySectionAddresses[LimeLight][1] = 0x002F;
MemorySectionAddresses[EN_DIR][0] = 0x0081;
MemorySectionAddresses[EN_DIR][1] = 0x0081;
MemorySectionAddresses[AFE][0] = 0x0082;
MemorySectionAddresses[AFE][1] = 0x0082;
MemorySectionAddresses[BIAS][0] = 0x0084;
MemorySectionAddresses[BIAS][1] = 0x0084;
MemorySectionAddresses[XBUF][0] = 0x0085;
MemorySectionAddresses[XBUF][1] = 0x0085;
MemorySectionAddresses[CGEN][0] = 0x0086;
MemorySectionAddresses[CGEN][1] = 0x008C;
MemorySectionAddresses[LDO][0] = 0x0092;
MemorySectionAddresses[LDO][1] = 0x00A7;
MemorySectionAddresses[BIST][0] = 0x00A8;
MemorySectionAddresses[BIST][1] = 0x00AC;
MemorySectionAddresses[CDS][0] = 0x00AD;
MemorySectionAddresses[CDS][1] = 0x00AE;
MemorySectionAddresses[TRF][0] = 0x0100;
MemorySectionAddresses[TRF][1] = 0x0104;
MemorySectionAddresses[TBB][0] = 0x0105;
MemorySectionAddresses[TBB][1] = 0x010A;
MemorySectionAddresses[RFE][0] = 0x010C;
MemorySectionAddresses[RFE][1] = 0x0114;
MemorySectionAddresses[RBB][0] = 0x0115;
MemorySectionAddresses[RBB][1] = 0x011A;
MemorySectionAddresses[SX][0] = 0x011C;
MemorySectionAddresses[SX][1] = 0x0124;
MemorySectionAddresses[TxTSP][0] = 0x0200;
MemorySectionAddresses[TxTSP][1] = 0x020C;
MemorySectionAddresses[TxNCO][0] = 0x0240;
MemorySectionAddresses[TxNCO][1] = 0x0261;
MemorySectionAddresses[TxGFIR1][0] = 0x0280;
MemorySectionAddresses[TxGFIR1][1] = 0x02A7;
MemorySectionAddresses[TxGFIR2][0] = 0x02C0;
MemorySectionAddresses[TxGFIR2][1] = 0x02E7;
MemorySectionAddresses[TxGFIR3a][0] = 0x0300;
MemorySectionAddresses[TxGFIR3a][1] = 0x0327;
MemorySectionAddresses[TxGFIR3b][0] = 0x0340;
MemorySectionAddresses[TxGFIR3b][1] = 0x0367;
MemorySectionAddresses[TxGFIR3c][0] = 0x0380;
MemorySectionAddresses[TxGFIR3c][1] = 0x03A7;
MemorySectionAddresses[RxTSP][0] = 0x0400;
MemorySectionAddresses[RxTSP][1] = 0x040F;
MemorySectionAddresses[RxNCO][0] = 0x0440;
MemorySectionAddresses[RxNCO][1] = 0x0461;
MemorySectionAddresses[RxGFIR1][0] = 0x0480;
MemorySectionAddresses[RxGFIR1][1] = 0x04A7;
MemorySectionAddresses[RxGFIR2][0] = 0x04C0;
MemorySectionAddresses[RxGFIR2][1] = 0x04E7;
MemorySectionAddresses[RxGFIR3a][0] = 0x0500;
MemorySectionAddresses[RxGFIR3a][1] = 0x0527;
MemorySectionAddresses[RxGFIR3b][0] = 0x0540;
MemorySectionAddresses[RxGFIR3b][1] = 0x0567;
MemorySectionAddresses[RxGFIR3c][0] = 0x0580;
MemorySectionAddresses[RxGFIR3c][1] = 0x05A7;
mRegistersMap->InitializeDefaultValues(LMS7parameterList);
}
LMS7002M::~LMS7002M()
{
}
/** @brief Sends reset signal to chip, after reset enables B channel controls
@return 0-success, other-failure
*/
liblms7_status LMS7002M::ResetChip()
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_RST;
pkt.outBuffer.push_back(LMS_RST_PULSE);
controlPort->TransferPacket(pkt);
if (pkt.status == STATUS_COMPLETED_CMD)
{
Modify_SPI_Reg_bits(LMS7param(MIMO_SISO), 0); //enable B channel after reset
return LIBLMS7_SUCCESS;
}
else
return LIBLMS7_FAILURE;
}
liblms7_status LMS7002M::LoadConfigLegacyFile(const char* filename)
{
ifstream f(filename);
if (f.good() == false) //file not found
{
f.close();
return LIBLMS7_FILE_NOT_FOUND;
}
f.close();
uint16_t addr = 0;
uint16_t value = 0;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
typedef INI<string, string, string> ini_t;
ini_t parser(filename, true);
if (parser.select("FILE INFO") == false)
return LIBLMS7_FILE_INVALID_FORMAT;
string type = "";
type = parser.get("type", "undefined");
stringstream ss;
if (type.find("LMS7002 configuration") == string::npos)
{
ss << "File " << filename << " not recognized" << endl;
return LIBLMS7_FILE_INVALID_FORMAT;
}
int fileVersion = 0;
fileVersion = parser.get("version", 0);
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
if (fileVersion == 1)
{
if (parser.select("Reference clocks"))
{
mRefClkSXR_MHz = parser.get("SXR reference frequency MHz", 30.72);
mRefClkSXT_MHz = parser.get("SXT reference frequency MHz", 30.72);
}
if (parser.select("LMS7002 registers ch.A") == true)
{
ini_t::sectionsit_t section = parser.sections.find("LMS7002 registers ch.A");
uint16_t x0020_value = 0;
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
if (addr == LMS7param(MAC).address) //skip register containing channel selection
{
x0020_value = value;
continue;
}
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
//parse FCW or PHO
if (parser.select("NCO Rx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_RX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
}
if (parser.select("NCO Tx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_TX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
}
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (parser.select("LMS7002 registers ch.B") == true)
{
addrToWrite.clear();
dataToWrite.clear();
ini_t::sectionsit_t section = parser.sections.find("LMS7002 registers ch.B");
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
//parse FCW or PHO
if (parser.select("NCO Rx ch.B") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_RX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
}
if (parser.select("NCO Tx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_TX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
}
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
return LIBLMS7_SUCCESS;
}
else
return LIBLMS7_FILE_INVALID_FORMAT;
return LIBLMS7_FAILURE;
}
/** @brief Reads configuration file and uploads registers to chip
@param filename Configuration source file
@return 0-success, other-failure
*/
liblms7_status LMS7002M::LoadConfig(const char* filename)
{
ifstream f(filename);
if (f.good() == false) //file not found
{
f.close();
return LIBLMS7_FILE_NOT_FOUND;
}
f.close();
uint16_t addr = 0;
uint16_t value = 0;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
typedef INI<string, string, string> ini_t;
ini_t parser(filename, true);
if (parser.select("file_info") == false)
{
//try loading as legacy format
status = LoadConfigLegacyFile(filename);
Modify_SPI_Reg_bits(MAC, 1);
return status;
}
string type = "";
type = parser.get("type", "undefined");
stringstream ss;
if (type.find("lms7002m_minimal_config") == string::npos)
{
ss << "File " << filename << " not recognized" << endl;
return LIBLMS7_FILE_INVALID_FORMAT;
}
int fileVersion = 0;
fileVersion = parser.get("version", 0);
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
if (fileVersion == 1)
{
if(parser.select("lms7002_registers_a") == true)
{
ini_t::sectionsit_t section = parser.sections.find("lms7002_registers_a");
uint16_t x0020_value = 0;
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
if (addr == LMS7param(MAC).address) //skip register containing channel selection
{
x0020_value = value;
continue;
}
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
if (parser.select("lms7002_registers_b") == true)
{
addrToWrite.clear();
dataToWrite.clear();
ini_t::sectionsit_t section = parser.sections.find("lms7002_registers_b");
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
parser.select("reference_clocks");
mRefClkSXR_MHz = parser.get("sxr_ref_clk_mhz", 30.72);
mRefClkSXT_MHz = parser.get("sxt_ref_clk_mhz", 30.72);
}
Modify_SPI_Reg_bits(MAC, 1);
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
return LIBLMS7_SUCCESS;
}
/** @brief Reads all registers from chip and saves to file
@param filename destination filename
@return 0-success, other failure
*/
liblms7_status LMS7002M::SaveConfig(const char* filename)
{
liblms7_status status;
typedef INI<> ini_t;
ini_t parser(filename, true);
parser.create("file_info");
parser.set("type", "lms7002m_minimal_config");
parser.set("version", 1);
char addr[80];
char value[80];
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
vector<uint16_t> addrToRead;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
addrToRead.push_back(addr);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
parser.create("lms7002_registers_a");
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
dataReceived[i] = Get_SPI_Reg_bits(addrToRead[i], 15, 0, false);
sprintf(addr, "0x%04X", addrToRead[i]);
sprintf(value, "0x%04X", dataReceived[i]);
parser.set(addr, value);
}
parser.create("lms7002_registers_b");
addrToRead.clear(); //add only B channel addresses
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
if (addr >= 0x0100)
addrToRead.push_back(addr);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
dataReceived[i] = Get_SPI_Reg_bits(addrToRead[i], 15, 0, false);
sprintf(addr, "0x%04X", addrToRead[i]);
sprintf(value, "0x%04X", dataReceived[i]);
parser.set(addr, value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //retore previously used channel
parser.create("reference_clocks");
parser.set("sxt_ref_clk_mhz", mRefClkSXT_MHz);
parser.set("sxr_ref_clk_mhz", mRefClkSXR_MHz);
parser.save(filename);
return LIBLMS7_SUCCESS;
}
/** @brief Returns reference clock in MHz used for SXT or SXR
@param Tx transmitter or receiver selection
*/
float_type LMS7002M::GetReferenceClk_SX(bool tx)
{
return tx ? mRefClkSXT_MHz : mRefClkSXR_MHz;
}
/** @return Current CLKGEN frequency in MHz
Returned frequency depends on reference clock used for Receiver
*/
float_type LMS7002M::GetFrequencyCGEN_MHz()
{
float_type dMul = (mRefClkSXR_MHz/2.0)/(Get_SPI_Reg_bits(LMS7param(DIV_OUTCH_CGEN))+1); //DIV_OUTCH_CGEN
uint16_t gINT = Get_SPI_Reg_bits(0x0088, 13, 0); //read whole register to reduce SPI transfers
uint32_t gFRAC = ((gINT & 0xF) * 65536) | Get_SPI_Reg_bits(0x0087, 15, 0);
return dMul * (((gINT>>4) + 1 + gFRAC/1048576.0));
}
/** @brief Returns TSP reference frequency
@param tx TxTSP or RxTSP selection
@return TSP reference frequency in MHz
*/
float_type LMS7002M::GetReferenceClk_TSP_MHz(bool tx)
{
float_type cgenFreq = GetFrequencyCGEN_MHz();
float_type clklfreq = cgenFreq/pow(2.0, Get_SPI_Reg_bits(LMS7param(CLKH_OV_CLKL_CGEN)));
if(Get_SPI_Reg_bits(LMS7param(EN_ADCCLKH_CLKGN)) == 0)
return tx ? clklfreq : cgenFreq/4.0;
else
return tx ? cgenFreq : clklfreq/4.0;
}
/** @brief Sets CLKGEN frequency, calculations use receiver'r reference clock
@param freq_MHz desired frequency in MHz
@return 0-succes, other-cannot deliver desired frequency
*/
liblms7_status LMS7002M::SetFrequencyCGEN(const float_type freq_MHz)
{
float_type dFvco;
float_type dFrac;
int16_t iHdiv;
//VCO frequency selection according to F_CLKH
iHdiv = (int16_t)((gCGEN_VCO_frequencies[1]/ 2) / freq_MHz) - 1;
dFvco = 2*(iHdiv+1) * freq_MHz;
//Integer division
uint16_t gINT = (uint16_t)(dFvco/mRefClkSXR_MHz - 1);
//Fractional division
dFrac = dFvco/mRefClkSXR_MHz - (uint32_t)(dFvco/mRefClkSXR_MHz);
uint32_t gFRAC = (uint32_t)(dFrac * 1048576);
Modify_SPI_Reg_bits(LMS7param(INT_SDM_CGEN), gINT); //INT_SDM_CGEN
Modify_SPI_Reg_bits(0x0087, 15, 0, gFRAC&0xFFFF); //INT_SDM_CGEN[15:0]
Modify_SPI_Reg_bits(0x0088, 3, 0, gFRAC>>16); //INT_SDM_CGEN[19:16]
Modify_SPI_Reg_bits(LMS7param(DIV_OUTCH_CGEN), iHdiv); //DIV_OUTCH_CGEN
return TuneVCO(VCO_CGEN);
}
/** @brief Performs VCO tuning operations for CLKGEN, SXR, SXT modules
@param module module selection for tuning 0-cgen, 1-SXR, 2-SXT
@return 0-success, other-failure
*/
liblms7_status LMS7002M::TuneVCO(VCO_Module module) // 0-cgen, 1-SXR, 2-SXT
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
int8_t i;
uint8_t cmphl; //comparators
int16_t csw_lowest = -1;
uint16_t addrVCOpd; // VCO power down address
uint16_t addrCSW_VCO;
uint16_t addrCMP; //comparator address
uint8_t lsb; //SWC lsb index
uint8_t msb; //SWC msb index
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
if(module != VCO_CGEN) //set addresses to SX module
{
Modify_SPI_Reg_bits(LMS7param(MAC), module);
addrVCOpd = LMS7param(PD_VCO).address;
addrCSW_VCO = LMS7param(CSW_VCO).address;
lsb = LMS7param(CSW_VCO).lsb;
msb = LMS7param(CSW_VCO).msb;
addrCMP = LMS7param(VCO_CMPHO).address;
}
else //set addresses to CGEN module
{
addrVCOpd = LMS7param(PD_VCO_CGEN).address;
addrCSW_VCO = LMS7param(CSW_VCO_CGEN).address;
lsb = LMS7param(CSW_VCO_CGEN).lsb;
msb = LMS7param(CSW_VCO_CGEN).msb;
addrCMP = LMS7param(VCO_CMPHO_CGEN).address;
}
// Initialization
Modify_SPI_Reg_bits (addrVCOpd, 2, 1, 0); //activate VCO and comparator
if (Get_SPI_Reg_bits(addrVCOpd, 2, 1) != 0)
return LIBLMS7_VCO_IS_POWERED_DOWN;
if(module == VCO_CGEN)
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO_CGEN), 1); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
else
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO), 1); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
Modify_SPI_Reg_bits (addrCSW_VCO , msb, lsb , 0); //Set SWC_VCO<7:0>=<00000000>
i=7;
while(i>=0)
{
Modify_SPI_Reg_bits (addrCSW_VCO, lsb + i, lsb + i, 1); // CSW_VCO<i>=1
std::this_thread::sleep_for(std::chrono::milliseconds(5));
cmphl = (uint8_t)Get_SPI_Reg_bits(addrCMP, 13, 12);
if ( (cmphl&0x01) == 1) // reduce CSW
Modify_SPI_Reg_bits (addrCSW_VCO, lsb + i, lsb + i, 0); // CSW_VCO<i>=0
if( cmphl == 2 && csw_lowest < 0)
csw_lowest = Get_SPI_Reg_bits(addrCSW_VCO, msb, lsb);
--i;
}
if(csw_lowest >= 0)
{
uint16_t csw_highest = Get_SPI_Reg_bits(addrCSW_VCO, msb, lsb);
if(csw_lowest == csw_highest)
{
while(csw_lowest>=0)
{
Modify_SPI_Reg_bits(addrCSW_VCO, msb, lsb, csw_lowest);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
if(Get_SPI_Reg_bits(addrCMP, 13, 12) == 0)
{
++csw_lowest;
break;
}
else
--csw_lowest;
}
}
Modify_SPI_Reg_bits(addrCSW_VCO, msb, lsb, csw_lowest+(csw_highest-csw_lowest)/2);
}
if (module == VCO_CGEN)
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO_CGEN), 0); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
else
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO), 0); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
cmphl = (uint8_t)Get_SPI_Reg_bits(addrCMP, 13, 12);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore previously used channel
if(cmphl == 2)
return LIBLMS7_SUCCESS;
else
return LIBLMS7_FAILURE;
}
/** @brief Returns given parameter value from chip register
@param param LMS7002M control parameter
@param fromChip read directly from chip
@return parameter value
*/
uint16_t LMS7002M::Get_SPI_Reg_bits(const LMS7Parameter ¶m, bool fromChip)
{
return Get_SPI_Reg_bits(param.address, param.msb, param.lsb, fromChip);
}
/** @brief Returns given parameter value from chip register
@param address register address
@param msb most significant bit index
@param lsb least significant bit index
@param fromChip read directly from chip
@return register bits from selected interval, shifted to right by lsb bits
*/
uint16_t LMS7002M::Get_SPI_Reg_bits(uint16_t address, uint8_t msb, uint8_t lsb, bool fromChip)
{
return (SPI_read(address, fromChip) & (~(~0<<(msb+1)))) >> lsb; //shift bits to LSB
}
/** @brief Change given parameter value
@param param LMS7002M control parameter
@param fromChip read initial value directly from chip
@param value new parameter value
*/
liblms7_status LMS7002M::Modify_SPI_Reg_bits(const LMS7Parameter ¶m, const uint16_t value, bool fromChip)
{
return Modify_SPI_Reg_bits(param.address, param.msb, param.lsb, value, fromChip);
}
/** @brief Change given parameter value
@param address register address
@param value new bits value, the value is shifted left by lsb bits
@param fromChip read initial value directly from chip
*/
liblms7_status LMS7002M::Modify_SPI_Reg_bits(const uint16_t address, const uint8_t msb, const uint8_t lsb, const uint16_t value, bool fromChip)
{
uint16_t spiDataReg = SPI_read(address, fromChip); //read current SPI reg data
uint16_t spiMask = (~(~0 << (msb - lsb + 1))) << (lsb); // creates bit mask
spiDataReg = (spiDataReg & (~spiMask)) | ((value << lsb) & spiMask);//clear bits
return SPI_write(address, spiDataReg); //write modified data back to SPI reg
}
/** @brief Modifies given registers with values applied using masks
@param addr array of register addresses
@param masks array of applied masks
@param values array of values to be written
@param start starting index of given arrays
@param stop end index of given arrays
*/
liblms7_status LMS7002M::Modify_SPI_Reg_mask(const uint16_t *addr, const uint16_t *masks, const uint16_t *values, uint8_t start, uint8_t stop)
{
liblms7_status status;
uint16_t reg_data;
vector<uint16_t> addresses;
vector<uint16_t> data;
while (start <= stop)
{
reg_data = SPI_read(addr[start], true, &status); //read current SPI reg data
reg_data &= ~masks[start];//clear bits
reg_data |= (values[start] & masks[start]);
addresses.push_back(addr[start]);
data.push_back(reg_data);
++start;
}
if (status != LIBLMS7_SUCCESS)
return status;
SPI_write_batch(&addresses[0], &data[0], addresses.size());
return status;
}
/** @brief Sets SX frequency
@param Tx Rx/Tx module selection
@param freq_MHz desired frequency in MHz
@param refClk_MHz reference clock in MHz
@return 0-success, other-cannot deliver requested frequency
*/
liblms7_status LMS7002M::SetFrequencySX(bool tx, float_type freq_MHz, float_type refClk_MHz)
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
const uint8_t sxVCO_N = 2; //number of entries in VCO frequencies
const float_type m_dThrF = 5500; //threshold to enable additional divider
uint8_t ch; //remember used channel
float_type VCOfreq;
int8_t div_loch;
int8_t sel_vco;
bool canDeliverFrequency = false;
uint16_t integerPart;
uint32_t fractionalPart;
int8_t i;
//find required VCO frequency
for (div_loch = 6; div_loch >= 0; --div_loch)
{
VCOfreq = (1 << (div_loch + 1)) * freq_MHz;
if ((VCOfreq >= gVCO_frequency_table[0][0]) && (VCOfreq <= gVCO_frequency_table[2][sxVCO_N - 1]))
{
canDeliverFrequency = true;
break;
}
}
if (canDeliverFrequency == false)
return LIBLMS7_CANNOT_DELIVER_FREQUENCY;
integerPart = (uint16_t)(VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))) - 4);
fractionalPart = (uint32_t)((VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))) - (uint32_t)(VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))))) * 1048576);
ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
Modify_SPI_Reg_bits(LMS7param(MAC), tx + 1);
Modify_SPI_Reg_bits(LMS7param(INT_SDM), integerPart); //INT_SDM
Modify_SPI_Reg_bits(0x011D, 15, 0, fractionalPart & 0xFFFF); //FRAC_SDM[15:0]
Modify_SPI_Reg_bits(0x011E, 3, 0, (fractionalPart >> 16)); //FRAC_SDM[19:16]
Modify_SPI_Reg_bits(LMS7param(DIV_LOCH), div_loch); //DIV_LOCH
Modify_SPI_Reg_bits(LMS7param(EN_DIV2_DIVPROG), (VCOfreq > m_dThrF)); //EN_DIV2_DIVPROG
//find which VCO supports required frequency
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0); //
Modify_SPI_Reg_bits(LMS7param(PD_VCO_COMP), 0); //
int cswBackup = Get_SPI_Reg_bits(LMS7param(CSW_VCO)); //remember to restore previous tune value
canDeliverFrequency = false;
int tuneScore[] = { -128, -128, -128 }; //best is closest to 0
for (sel_vco = 0; sel_vco < 3; ++sel_vco)
{
Modify_SPI_Reg_bits(LMS7param(SEL_VCO), sel_vco);
liblms7_status status = TuneVCO(tx ? VCO_SXT : VCO_SXR);
int csw = Get_SPI_Reg_bits(LMS7param(CSW_VCO), true);
tuneScore[sel_vco] = -128 + csw;
if (status == LIBLMS7_SUCCESS)
canDeliverFrequency = true;
}
if (abs(tuneScore[0]) < abs(tuneScore[1]))
{
if (abs(tuneScore[0]) < abs(tuneScore[2]))
sel_vco = 0;
else
sel_vco = 2;
}
else
{
if (abs(tuneScore[1]) < abs(tuneScore[2]))
sel_vco = 1;
else
sel_vco = 2;
}
Modify_SPI_Reg_bits(LMS7param(SEL_VCO), sel_vco);
Modify_SPI_Reg_bits(LMS7param(CSW_VCO), cswBackup);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore used channel
if (tx)
mRefClkSXT_MHz = refClk_MHz;
else
mRefClkSXR_MHz = refClk_MHz;
if (canDeliverFrequency == false)
return LIBLMS7_CANNOT_DELIVER_FREQUENCY;
return TuneVCO( tx ? VCO_SXT : VCO_SXR); //Rx-1, Tx-2
}
/** @brief Returns currently set SXR/SXT frequency
@return SX frequency MHz
*/
float_type LMS7002M::GetFrequencySX_MHz(bool Tx, float_type refClk_MHz)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember previously used channel
float_type dMul;
if(Tx)
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // Rx mac = 1, Tx max = 2
else
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // Rx mac = 1, Tx max = 2
uint16_t gINT = Get_SPI_Reg_bits(0x011E, 13, 0); // read whole register to reduce SPI transfers
uint32_t gFRAC = ((gINT&0xF) * 65536) | Get_SPI_Reg_bits(0x011D, 15, 0);
dMul = (float_type)refClk_MHz / (1 << (Get_SPI_Reg_bits(LMS7param(DIV_LOCH)) + 1));
//Calculate real frequency according to the calculated parameters
dMul = dMul * ((gINT >> 4) + 4 + (float_type)gFRAC / 1048576.0) * (Get_SPI_Reg_bits(LMS7param(EN_DIV2_DIVPROG)) + 1);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore used channel
return dMul;
}
/** @brief Loads given DC_REG values into registers
@param tx TxTSP or RxTSP selection
@param I DC_REG I value
@param Q DC_REG Q value
*/
liblms7_status LMS7002M::LoadDC_REG_IQ(bool tx, int16_t I, int16_t Q)
{
if(tx)
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
}
else
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_RXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); //DC_BYP
}
return LIBLMS7_SUCCESS;
}
/** @brief Sets chosen NCO's frequency
@param tx transmitter or receiver selection
@param index NCO index from 0 to 15
@param freq_MHz desired NCO frequency
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOFrequency(bool tx, uint8_t index, float_type freq_MHz)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
float_type refClk_MHz = GetReferenceClk_TSP_MHz(tx);
uint16_t addr = tx ? 0x0240 : 0x0440;
uint32_t fcw = (uint32_t)((freq_MHz/refClk_MHz)*4294967296);
SPI_write(addr+2+index*2, (fcw >> 16)); //NCO frequency control word register MSB part.
SPI_write(addr+3+index*2, fcw); //NCO frequency control word register LSB part.
return LIBLMS7_SUCCESS;
}
/** @brief Returns chosen NCO's frequency in MHz
@param tx transmitter or receiver selection
@param index NCO index from 0 to 15
@param fromChip read frequency directly from chip or local registers
@return NCO frequency in MHz
*/
float_type LMS7002M::GetNCOFrequency_MHz(bool tx, uint8_t index, const float_type refClk_MHz, bool fromChip)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
uint16_t addr = tx ? 0x0240 : 0x0440;
uint32_t fcw = 0;
fcw |= SPI_read(addr + 2 + index * 2, fromChip) << 16; //NCO frequency control word register MSB part.
fcw |= SPI_read(addr + 3 + index * 2, fromChip); //NCO frequency control word register LSB part.
return refClk_MHz*(fcw/4294967296.0);
}
/** @brief Sets chosen NCO phase offset angle when memory table MODE is 0
@param tx transmitter or receiver selection
@param angle_deg phase offset angle in degrees
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOPhaseOffsetForMode0(bool tx, float_type angle_deg)
{
uint16_t addr = tx ? 0x0241 : 0x0441;
uint16_t pho = (uint16_t)(65536 * (angle_deg / 360 ));
SPI_write(addr, pho);
return LIBLMS7_SUCCESS;
}
/** @brief Sets chosen NCO's phase offset angle
@param tx transmitter or receiver selection
@param index PHO index from 0 to 15
@param angle_deg phase offset angle in degrees
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOPhaseOffset(bool tx, uint8_t index, float_type angle_deg)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
uint16_t addr = tx ? 0x0244 : 0x0444;
uint16_t pho = (uint16_t)(65536*(angle_deg / 360));
SPI_write(addr+index, pho);
return LIBLMS7_SUCCESS;
}
/** @brief Returns chosen NCO's phase offset angle in radians
@param tx transmitter or receiver selection
@param index PHO index from 0 to 15
@return phase offset angle in degrees
*/
float_type LMS7002M::GetNCOPhaseOffset_Deg(bool tx, uint8_t index)
{
uint16_t addr = tx ? 0x0244 : 0x0444;
uint16_t pho = SPI_read(addr+index);
float_type angle = 360*pho/65536.0;
return angle;
}
/** @brief Uploads given FIR coefficients to chip
@param tx Transmitter or receiver selection
@param GFIR_index GIR index from 0 to 2
@param coef array of coefficients
@param coefCount number of coefficients
@return 0-success, other-failure
This function does not change GFIR*_L or GFIR*_N parameters, they have to be set manually
*/
liblms7_status LMS7002M::SetGFIRCoefficients(bool tx, uint8_t GFIR_index, const int16_t *coef, uint8_t coefCount)
{
uint8_t index;
uint8_t coefLimit;
uint16_t startAddr;
if (GFIR_index == 0)
startAddr = 0x0280;
else if (GFIR_index == 1)
startAddr = 0x02C0;
else
startAddr = 0x0300;
if (tx == false)
startAddr += 0x0200;
if (GFIR_index < 2)
coefLimit = 40;
else
coefLimit = 120;
if (coefCount > coefLimit)
return LIBLMS7_TOO_MANY_VALUES;
vector<uint16_t> addresses;
for (index = 0; index < coefCount; ++index)
addresses.push_back(startAddr + index + 24 * (index / 40));
SPI_write_batch(&addresses[0], (uint16_t*)coef, coefCount);
return LIBLMS7_SUCCESS;
}
/** @brief Returns currently loaded FIR coefficients
@param tx Transmitter or receiver selection
@param GFIR_index GIR index from 0 to 2
@param coef array of returned coefficients
@param coefCount number of coefficients to read
@return 0-success, other-failure
*/
liblms7_status LMS7002M::GetGFIRCoefficients(bool tx, uint8_t GFIR_index, int16_t *coef, uint8_t coefCount)
{
liblms7_status status = LIBLMS7_FAILURE;
uint8_t index;
uint8_t coefLimit;
uint16_t startAddr;
if(GFIR_index == 0)
startAddr = 0x0280;
else if (GFIR_index == 1)
startAddr = 0x02C0;
else
startAddr = 0x0300;
if (tx == false)
startAddr += 0x0200;
if (GFIR_index < 2)
coefLimit = 40;
else
coefLimit = 120;
if (coefCount > coefLimit)
return LIBLMS7_TOO_MANY_VALUES;
std::vector<uint16_t> addresses;
for (index = 0; index < coefCount; ++index)
addresses.push_back(startAddr + index + 24 * (index / 40));
uint16_t spiData[120];
memset(spiData, 0, 120 * sizeof(uint16_t));
if (controlPort->IsOpen())
{
status = SPI_read_batch(&addresses[0], spiData, coefCount);
for (index = 0; index < coefCount; ++index)
coef[index] = spiData[index];
}
else
{
const int channel = Get_SPI_Reg_bits(LMS7param(MAC), false) > 1 ? 1 : 0;
for (index = 0; index < coefCount; ++index)
coef[index] = mRegistersMap->GetValue(channel, addresses[index]);
status = LIBLMS7_SUCCESS;
}
return status;
}
/** @brief Write given data value to whole register
@param address SPI address
@param data new register value
@return 0-succes, other-failure
*/
liblms7_status LMS7002M::SPI_write(uint16_t address, uint16_t data)
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1 && address >= 0x0100)
mRegistersMap->SetValue(1, address, data);
else
mRegistersMap->SetValue(0, address, data);
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_WR;
pkt.outBuffer.push_back(address >> 8);
pkt.outBuffer.push_back(address & 0xFF);
pkt.outBuffer.push_back(data >> 8);
pkt.outBuffer.push_back(data & 0xFF);
controlPort->TransferPacket(pkt);
if (pkt.status == STATUS_COMPLETED_CMD)
return LIBLMS7_SUCCESS;
else
return LIBLMS7_FAILURE;
}
/** @brief Reads whole register value from given address
@param address SPI address
@param status operation status(optional)
@param fromChip read value directly from chip
@return register value
*/
uint16_t LMS7002M::SPI_read(uint16_t address, bool fromChip, liblms7_status *status)
{
if (controlPort == NULL)
{
if (status)
*status = LIBLMS7_NO_CONNECTION_MANAGER;
}
if (controlPort->IsOpen() == false || fromChip == false)
{
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1 && address >= 0x0100)
return mRegistersMap->GetValue(1, address);
else
return mRegistersMap->GetValue(0, address);
}
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_RD;
pkt.outBuffer.push_back(address >> 8);
pkt.outBuffer.push_back(address & 0xFF);
if (controlPort->TransferPacket(pkt) == LMScomms::TRANSFER_SUCCESS)
{
if (status)
*status = (pkt.status == STATUS_COMPLETED_CMD ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE);
return (pkt.inBuffer[2] << 8) | pkt.inBuffer[3];
}
else
return 0;
}
/** @brief Batches multiple register writes into least ammount of transactions
@param spiAddr spi register addresses to be written
@param spiData registers data to be written
@param cnt number of registers to write
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SPI_write_batch(const uint16_t* spiAddr, const uint16_t* spiData, uint16_t cnt)
{
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_WR;
uint32_t index = 0;
for (uint32_t i = 0; i < cnt; ++i)
{
pkt.outBuffer.push_back(spiAddr[i] >> 8);
pkt.outBuffer.push_back(spiAddr[i] & 0xFF);
pkt.outBuffer.push_back(spiData[i] >> 8);
pkt.outBuffer.push_back(spiData[i] & 0xFF);
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
controlPort->TransferPacket(pkt);
if (pkt.status == STATUS_COMPLETED_CMD)
return LIBLMS7_SUCCESS;
else
return LIBLMS7_FAILURE;
}
/** @brief Batches multiple register reads into least amount of transactions
@param spiAddr SPI addresses to read
@param spiData array for read data
@param cnt number of registers to read
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SPI_read_batch(const uint16_t* spiAddr, uint16_t* spiData, uint16_t cnt)
{
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_RD;
uint32_t index = 0;
for (uint32_t i = 0; i < cnt; ++i)
{
pkt.outBuffer.push_back(spiAddr[i] >> 8);
pkt.outBuffer.push_back(spiAddr[i] & 0xFF);
}
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
LMScomms::TransferStatus status = controlPort->TransferPacket(pkt);
if (status != LMScomms::TRANSFER_SUCCESS)
return LIBLMS7_FAILURE;
for (uint32_t i = 0; i < cnt; ++i)
{
spiData[i] = (pkt.inBuffer[2*sizeof(uint16_t)*i + 2] << 8) | pkt.inBuffer[2*sizeof(uint16_t)*i + 3];
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
return pkt.status == STATUS_COMPLETED_CMD ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
/*
for(int i=0; i<cnt; ++i)
{
spiData[i] = Get_SPI_Reg_bits(spiAddr[i], 15, 0);
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
return LIBLMS7_SUCCESS;*/
}
/** @brief Performs registers test by writing known data and confirming readback data
@return 0-registers test passed, other-failure
*/
liblms7_status LMS7002M::RegistersTest()
{
char chex[16];
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//backup both channel data for restoration after test
vector<uint16_t> ch1Addresses;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
ch1Addresses.push_back(addr);
vector<uint16_t> ch1Data;
ch1Data.resize(ch1Addresses.size(), 0);
//backup A channel
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&ch1Addresses[0], &ch1Data[0], ch1Addresses.size());
if (status != LIBLMS7_SUCCESS)
return status;
vector<uint16_t> ch2Addresses;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
if (addr >= 0x0100)
ch2Addresses.push_back(addr);
vector<uint16_t> ch2Data;
ch2Data.resize(ch2Addresses.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&ch2Addresses[0], &ch2Data[0], ch2Addresses.size());
if (status != LIBLMS7_SUCCESS)
return status;
//test registers
ResetChip();
Modify_SPI_Reg_bits(LMS7param(MIMO_SISO), 0);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
stringstream ss;
//check single channel memory sections
vector<MemorySection> modulesToCheck = { AFE, BIAS, XBUF, CGEN, LDO, BIST, CDS, TRF, TBB, RFE, RBB, SX,
TxTSP, TxNCO, TxGFIR1, TxGFIR2, TxGFIR3a, TxGFIR3b, TxGFIR3c,
RxTSP, RxNCO, RxGFIR1, RxGFIR2, RxGFIR3a, RxGFIR3b, RxGFIR3c, LimeLight };
const char* moduleNames[] = { "AFE", "BIAS", "XBUF", "CGEN", "LDO", "BIST", "CDS", "TRF", "TBB", "RFE", "RBB", "SX",
"TxTSP", "TxNCO", "TxGFIR1", "TxGFIR2", "TxGFIR3a", "TxGFIR3b", "TxGFIR3c",
"RxTSP", "RxNCO", "RxGFIR1", "RxGFIR2", "RxGFIR3a", "RxGFIR3b", "RxGFIR3c", "LimeLight" };
const uint16_t patterns[] = { 0xAAAA, 0x5555 };
const uint8_t patternsCount = 2;
bool allTestSuccess = true;
for (unsigned i = 0; i < modulesToCheck.size(); ++i)
{
bool moduleTestsSuccess = true;
uint16_t startAddr = MemorySectionAddresses[modulesToCheck[i]][0];
uint16_t endAddr = MemorySectionAddresses[modulesToCheck[i]][1];
uint8_t channelCount = startAddr >= 0x0100 ? 2 : 1;
for (int cc = 1; cc <= channelCount; ++cc)
{
Modify_SPI_Reg_bits(LMS7param(MAC), cc);
sprintf(chex, "0x%04X", startAddr);
ss << moduleNames[i] << " [" << chex << ":";
sprintf(chex, "0x%04X", endAddr);
ss << chex << "]";
if (startAddr >= 0x0100)
ss << " Ch." << (cc == 1 ? "A" : "B");
ss << endl;
for (uint8_t p = 0; p < patternsCount; ++p)
moduleTestsSuccess &= RegistersTestInterval(startAddr, endAddr, patterns[p], ss) == LIBLMS7_SUCCESS;
}
allTestSuccess &= moduleTestsSuccess;
}
//restore register values
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SPI_write_batch(&ch1Addresses[0], &ch1Data[0], ch1Addresses.size());
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
SPI_write_batch(&ch2Addresses[0], &ch2Data[0], ch2Addresses.size());
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
fstream fout;
fout.open("registersTest.txt", ios::out);
fout << ss.str() << endl;
fout.close();
return allTestSuccess ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
/** @brief Performs registers test for given address interval by writing given pattern data
@param startAddr first register address
@param endAddr last reigster address
@param pattern data to be written into registers
@return 0-register test passed, other-failure
*/
liblms7_status LMS7002M::RegistersTestInterval(uint16_t startAddr, uint16_t endAddr, uint16_t pattern, stringstream &ss)
{
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
vector<uint16_t> dataReceived;
vector<uint16_t> dataMasks;
for (uint16_t addr = startAddr; addr <= endAddr; ++addr)
{
addrToWrite.push_back(addr);
}
dataMasks.resize(addrToWrite.size(), 0xFFFF);
for (uint16_t j = 0; j < sizeof(readOnlyRegisters)/sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToWrite.size(); ++k)
if (readOnlyRegisters[j] == addrToWrite[k])
{
dataMasks[k] = readOnlyRegistersMasks[j];
break;
}
dataToWrite.clear();
dataReceived.clear();
for (uint16_t j = 0; j < addrToWrite.size(); ++j)
{
if (addrToWrite[j] == 0x00A6)
dataToWrite.push_back(0x1 | pattern & ~0x2);
else if (addrToWrite[j] == 0x0084)
dataToWrite.push_back(pattern & ~0x19);
else
dataToWrite.push_back(pattern & dataMasks[j]);
}
dataReceived.resize(addrToWrite.size(), 0);
liblms7_status status;
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
status = SPI_read_batch(&addrToWrite[0], &dataReceived[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
bool registersMatch = true;
char ctemp[16];
for (uint16_t j = 0; j < dataToWrite.size(); ++j)
{
if (dataToWrite[j] != (dataReceived[j] & dataMasks[j]))
{
registersMatch = false;
sprintf(ctemp, "0x%04X", addrToWrite[j]);
ss << "\t" << ctemp << "(wr/rd): ";
sprintf(ctemp, "0x%04X", dataToWrite[j]);
ss << ctemp << "/";
sprintf(ctemp, "0x%04X", dataReceived[j]);
ss << ctemp << endl;
}
}
if (registersMatch)
{
sprintf(ctemp, "0x%04X", pattern);
ss << "\tRegisters OK (" << ctemp << ")\n";
}
return registersMatch ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
/** @brief Parameters setup instructions for Tx calibration
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateTxSetup(float_type bandwidth_MHz)
{
//Stage 2
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//rfe
//reset RFE to defaults
SetDefaults(RFE);
if (sel_band1_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 3); //SEL_PATH_RFE 3
else if (sel_band2_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 2);
else
return LIBLMS7_BAND_NOT_SELECTED;
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1); // EN_NEXTTX_RFE 1
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 8); //G_RXLOOPB_RFE 8
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 10); //CCOMP_TIA_RFE 10
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 2600); //CFB_TIA_RFE 2600
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
Modify_SPI_Reg_bits(LMS7param(PD_LNA_RFE), 1);
//RBB
//reset RBB to defaults
SetDefaults(RBB);
Modify_SPI_Reg_bits(LMS7param(PD_LPFL_RBB), 0); //PD_LPFL_RBB 0
Modify_SPI_Reg_bits(LMS7param(RCC_CTL_LPFL_RBB), 0); //RCC_CTL_LPFL_RBB 0
Modify_SPI_Reg_bits(LMS7param(C_CTL_LPFL_RBB), 1500); //C_CTL_LPFL_RBB 1500
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), 22); //G_PGA_RBB 22
//TRF
//reset TRF to defaults
//SetDefaults(TRF);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0); //EN_G_TRF 0
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(LMS7param(LOSS_LIN_TXPAD_TRF), 0); //LOSS_LIN_TXPAD_TRF 5
Modify_SPI_Reg_bits(LMS7param(LOSS_MAIN_TXPAD_TRF), 0); //LOSS_MAIN_TXPAD_TRF 5
//TBB
//reset TBB to defaults
/*SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 9); //CG_IAMP_TBB 9
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
Modify_SPI_Reg_bits(LMS7param(RCAL_LPFH_TBB), 125); //RCAL_LPFH_TBB 0
*/
//AFE
//reset AFE to defaults
uint8_t isel_dac_afe =(uint8_t) Get_SPI_Reg_bits(LMS7param(ISEL_DAC_AFE));
SetDefaults(AFE);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2 0
Modify_SPI_Reg_bits(LMS7param(ISEL_DAC_AFE), isel_dac_afe);
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
//BIAS
uint16_t backup = Get_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS));
SetDefaults(BIAS);
Modify_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS), backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
SetDefaults(CGEN);
//power up VCO
Modify_SPI_Reg_bits(LMS7param(PD_VCO_CGEN), 0);
if (SetFrequencyCGEN(122.88) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_CGEN) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
float_type SXTfreqMHz = GetFrequencySX_MHz(Tx, mRefClkSXT_MHz);
float_type SXRfreqMHz = SXTfreqMHz - bandwidth_MHz / 4 - 1;
if (SetFrequencySX(Rx, SXRfreqMHz, mRefClkSXR_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_SXR) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(LMS7param(PD_LOCH_T2RBUF), 1); //PD_LOCH_T2RBUF 1
if (SetFrequencySX(Tx, SXTfreqMHz, mRefClkSXT_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_SXT) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
Modify_SPI_Reg_bits(0x0200, 3, 2, 0x3); //TSGMODE 1, INSEL 1
Modify_SPI_Reg_bits(0x0208, 6, 4, 0x7); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(0x0440, 4, 0, 0); //TX SEL[3:0] = 0 & MODE = 0
float_type offset = 0.2;
if (bandwidth_MHz == 8)
{
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
float_type SXTfreqMHz = GetFrequencySX_MHz(Tx, mRefClkSXT_MHz);
float_type sxrFreq = SXTfreqMHz - bandwidth_MHz / 4 - 1 - offset;
if (SetFrequencySX(Rx, sxrFreq, mRefClkSXR_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
SetNCOFrequency(Tx, 0, bandwidth_MHz / 4 + offset);
}
else
SetNCOFrequency(Tx, 0, bandwidth_MHz / 4);
//RXTSP
SetDefaults(RxTSP);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 0, 0xBF);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 0); //Decimation HBD ratio
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x7); //agc_avg iq corr
return LIBLMS7_SUCCESS;
}
/** @brief Flips the CAPTURE bit and returns digital RSSI value
*/
uint32_t LMS7002M::GetRSSI()
{
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 0);
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 1);
return (Get_SPI_Reg_bits(0x040F, 15, 0) << 2) | Get_SPI_Reg_bits(0x040E, 1, 0);
}
/** @brief Sets Rx Dc offsets by converting two's complementary numbers to sign and magnitude
*/
void LMS7002M::SetRxDCOFF(int8_t offsetI, int8_t offsetQ)
{
uint16_t valToSend = 0;
if (offsetI < 0)
valToSend |= 0x40;
valToSend |= labs(offsetI);
valToSend = valToSend << 7;
if (offsetQ < 0)
valToSend |= 0x40;
valToSend |= labs(offsetQ);
SPI_write(0x010E, valToSend);
}
/** @brief Calibrates Transmitter. DC correction, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateTx(float_type bandwidth_MHz)
{
liblms7_status status;
Log("Tx calibration started", LOG_INFO);
BackupAllRegisters();
int16_t iqcorr = 0;
uint16_t gcorrq = 0;
uint16_t gcorri = 0;
uint16_t dccorri;
uint16_t dccorrq;
int16_t corrI = 0;
int16_t corrQ = 0;
uint32_t minRSSI_i;
uint32_t minRSSI_q;
uint32_t minRSSI_iq;
int16_t i;
int16_t offsetI = 0;
int16_t offsetQ = 0;
const short firCoefs[] =
{
-2531,
-517,
2708,
188,
-3059,
216,
3569,
-770,
-4199,
1541,
4886,
-2577,
-5552,
3909,
6108,
-5537,
-6457,
7440,
6507,
-9566,
-6174,
11845,
5391,
-14179,
-4110,
16457,
2310,
-18561,
0,
20369,
-2780,
-21752,
5963,
22610,
-9456,
-22859,
13127,
22444,
-16854,
-21319,
20489,
19492,
-23883,
-17002,
26881,
13902,
-29372,
-10313,
31226,
6345,
-32380,
-2141,
32767,
-2141,
-32380,
6345,
31226,
-10313,
-29372,
13902,
26881,
-17002,
-23883,
19492,
20489,
-21319,
-16854,
22444,
13127,
-22859,
-9456,
22610,
5963,
-21752,
-2780,
20369,
0,
-18561,
2310,
16457,
-4110,
-14179,
5391,
11845,
-6174,
-9566,
6507,
7440,
-6457,
-5537,
6108,
3909,
-5552,
-2577,
4886,
1541,
-4199,
-770,
3569,
216,
-3059,
188,
2708,
-517,
-2531
};
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//Stage 1
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
Log("Setup stage", LOG_INFO);
status = CalibrateTxSetup(bandwidth_MHz);
if (status != LIBLMS7_SUCCESS)
goto TxCalibrationEnd; //go to ending stage to restore registers
//Stage 3
//Calibrate Rx DC
Log("Rx DC calibration", LOG_INFO);
{
uint16_t requiredRegs[] = { 0x0400, 0x040A, 0x010D, 0x040C };
uint16_t requiredMask[] = { 0x6000, 0x3007, 0x0040, 0x00FF }; //CAPSEL, AGC_MODE, AGC_AVG, EN_DCOFF, Bypasses
uint16_t requiredValue[] = { 0x0000, 0x1007, 0x0040, 0x00BD };
Modify_SPI_Reg_mask(requiredRegs, requiredMask, requiredValue, 0, 3);
}
for (i = 0; i<6; ++i)
{
FindMinRSSI(LMS7param(DCOFFI_RFE), offsetI, &offsetI, 3, 2, 32 >> i);
FindMinRSSI(LMS7param(DCOFFQ_RFE), offsetQ, &offsetQ, 3, 2, 32 >> i);
}
SetRxDCOFF((int8_t)offsetI, (int8_t)offsetQ);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); // DC_BYP 0
sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//B
Modify_SPI_Reg_bits(0x0100, 0, 0, 1); //EN_G_TRF 1
if (sel_band1_trf == 1)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0); //PD_RLOOPB_1_RFE 0
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0); //EN_INSHSW_LB1 0
}
if (sel_band2_trf == 1)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0); //PD_RLOOPB_2_RFE 0
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0); // EN_INSHSW_LB2 0
}
FixRXSaturation();
Modify_SPI_Reg_bits(LMS7param(GFIR3_BYP_RXTSP), 0); //GFIR3_BYP 0
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 7);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
Log("IQ correction stage", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), 0);
Log("I gain", LOG_INFO);
minRSSI_i = FindMinRSSI_Gain(LMS7param(GCORRI_TXTSP), &gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), 2047);
Log("Q gain", LOG_INFO);
minRSSI_q = FindMinRSSI_Gain(LMS7param(GCORRQ_TXTSP), &gcorrq);
if (minRSSI_i < minRSSI_q)
gcorrq = 2047;
else
gcorri = 2047;
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Log("Phase", LOG_INFO);
iqcorr = 0;
for (uint8_t i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_TXTSP), iqcorr, &iqcorr, 3, 1, 256 >> i);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), iqcorr);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SetFrequencySX(Rx, GetFrequencySX_MHz(Tx, mRefClkSXT_MHz)-1, mRefClkSXR_MHz);
if (status != LIBLMS7_SUCCESS)
goto TxCalibrationEnd; //go to ending stage to restore registers
//C
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Log("TX LO calibration", LOG_INFO);
//Calibrate Tx DC
for (uint8_t i = 0; i<7; ++i)
{
FindMinRSSI(LMS7param(DCCORRI_TXTSP), corrI, &corrI, 3, 1, 64 >> i);
FindMinRSSI(LMS7param(DCCORRQ_TXTSP), corrQ, &corrQ, 3, 1, 64 >> i);
}
dccorri = Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP));
dccorrq = Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP));
// Stage 4
TxCalibrationEnd:
Log("Restoring registers state", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
RestoreAllRegisters();
if (status != LIBLMS7_SUCCESS)
{
Log("Tx calibration failed", LOG_WARNING);
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dccorri);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dccorrq);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), iqcorr);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
Log("Tx calibration finished", LOG_INFO);
return LIBLMS7_SUCCESS;
}
/** @brief Performs Rx DC offsets calibration
*/
void LMS7002M::CalibrateRxDC_RSSI()
{
int16_t i;
int16_t offsetI = 0;
int16_t offsetQ = 0;
uint16_t requiredRegs[] = { 0x0400, 0x040A, 0x010D, 0x040C };
uint16_t requiredMask[] = { 0x6000, 0x3007, 0x0040, 0x00FF }; //CAPSEL, AGC_MODE, AGC_AVG, EN_DCOFF, Bypasses
uint16_t requiredValue[] = { 0x0000, 0x1007, 0x0040, 0x00BD };
Modify_SPI_Reg_mask(requiredRegs, requiredMask, requiredValue, 0, 3);
for (i = 0; i<6; ++i)
{
FindMinRSSI(LMS7param(DCOFFI_RFE), offsetI, &offsetI, 3, 2, 32 >> i);
FindMinRSSI(LMS7param(DCOFFQ_RFE), offsetQ, &offsetQ, 3, 2, 32 >> i);
}
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
SetRxDCOFF((int8_t)offsetI, (int8_t)offsetQ);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); // DC_BYP 0
}
/** @brief Tries to detect and fix gains if Rx is saturated
@return 0-success, other-failure
*/
liblms7_status LMS7002M::FixRXSaturation()
{
uint8_t g_rxloopb = 0;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 3);
int8_t lLoopb = 3;
const uint32_t rssi_saturation_level = 0xD000;
while (g_rxloopb < 15)
{
g_rxloopb += 1;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 3);
if (GetRSSI() < rssi_saturation_level)
{
for (lLoopb = 3; lLoopb >= 0; --lLoopb)
{
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), lLoopb);
if (GetRSSI() > rssi_saturation_level)
{
++lLoopb;
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), lLoopb);
goto finished;
}
}
}
else
{
g_rxloopb -= 1;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
break;
}
}
finished:
return GetRSSI() < rssi_saturation_level ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
uint32_t LMS7002M::FindMinRSSI(const LMS7Parameter ¶m, const int16_t startValue, int16_t *result, const uint8_t scanWidth, const uint8_t twoCompl, int8_t stepMult)
{
return FindMinRSSI(param.address, param.msb, param.lsb, startValue, result, scanWidth, twoCompl, stepMult);
}
/** @brief Searches for minimal RSSI value while changing given address bits
@param addr address of parameter being changed
@param msb most significant bit index
@param lsb least significant bit index
@param startValue initial value where to start search
@param result found minimal parameter value will be set here
@param twoCompl varying parameter value is treated as two's complement
@return found minimal RSSI value
*/
uint32_t LMS7002M::FindMinRSSI(const uint16_t addr, const uint8_t msb, const uint8_t lsb, const int16_t startValue, int16_t *result, const uint8_t scanWidth, const uint8_t twoCompl, int8_t stepMult)
{
if (scanWidth < 1)
return ~0;
int minI;
int min = startValue;
int globMin = 0;
uint32_t minRSSI = ~0;
unsigned int *rssiField = new unsigned int[scanWidth];
int minRSSIindex;
int i;
int maxVal;
int minVal = 0;
if (twoCompl)
{
maxVal = (~(~0x0 << (msb - lsb + 1))) / 2;
minVal = -(~(~0x0 << (msb - lsb + 1))) / 2 - 1;
}
else
maxVal = (~(~0x0 << (msb - lsb + 1)));
Modify_SPI_Reg_bits(addr, msb, lsb, startValue);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
minRSSIindex = 0;
for (i = 0; i<scanWidth; ++i)
{
short currentValue = min + (i - scanWidth / 2)*stepMult;
if (currentValue < minVal)
currentValue = minVal;
else if (currentValue > maxVal)
currentValue = maxVal;
if (twoCompl == 2)
{
uint16_t valToSend = 0;
if (currentValue < 0)
valToSend |= 0x40;
valToSend |= labs(currentValue);
Modify_SPI_Reg_bits(addr, msb, lsb, valToSend);
}
else
Modify_SPI_Reg_bits(addr, msb, lsb, currentValue);
rssiField[i] = GetRSSI();
}
minI = min;
minRSSIindex = 0;
for (i = 0; i<scanWidth; ++i)
if (rssiField[i] < minRSSI)
{
minRSSI = rssiField[i];
minRSSIindex = i;
minI = min + (i - scanWidth / 2)*stepMult;
if (minI > maxVal)
minI = maxVal;
else if (minI < minVal)
minI = minVal;
globMin = minI;
}
min = minI;
Modify_SPI_Reg_bits(addr, msb, lsb, min);
*result = min;
return minRSSI;
}
/** @brief Sets given module registers to default values
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetDefaults(MemorySection module)
{
liblms7_status status = LIBLMS7_SUCCESS;
vector<uint16_t> addrs;
vector<uint16_t> values;
for(uint32_t address = MemorySectionAddresses[module][0]; address <= MemorySectionAddresses[module][1]; ++address)
{
addrs.push_back(address);
values.push_back(mRegistersMap->GetDefaultValue(address));
}
status = SPI_write_batch(&addrs[0], &values[0], addrs.size());
return status;
}
/** @brief Parameters setup instructions for Rx calibration
@param bandwidth_MHz filter bandwidth in MHz
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateRxSetup(float_type bandwidth_MHz)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//rfe
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); // EN_NEXTTX_TRF 0
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 15); //G_RXLOOPB_RFE 15
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(0x010C, 1, 1, 0); //PD_TIA 0
Modify_SPI_Reg_bits(0x010C, 7, 7, 1); //PD_LNA 1
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Modify_SPI_Reg_bits(0x010D, 4, 1, 0xFF); // all short switches are enabled
//RBB
Modify_SPI_Reg_bits(0x0115, 15, 14, 0); //Loopback switches disable
Modify_SPI_Reg_bits(0x0119, 15, 15, 0); //OSW_PGA 0
//TRF
//reset TRF to defaults
SetDefaults(TRF);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0); //EN_G_TRF 0
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(LMS7param(LOSS_LIN_TXPAD_TRF), 0); //LOSS_LIN_TXPAD_TRF 5
Modify_SPI_Reg_bits(LMS7param(LOSS_MAIN_TXPAD_TRF), 0); //LOSS_MAIN_TXPAD_TRF 5
//TBB
//reset TBB to defaults
SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 9); //CG_IAMP_TBB 9
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
//AFE
//reset AFE to defaults
SetDefaults(AFE);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2
if (ch == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0); //PD_TX_AFE2
}
//BIAS
uint16_t backup = Get_SPI_Reg_bits(0x0084, 10, 6);
SetDefaults(BIAS);
Modify_SPI_Reg_bits(0x0084, 10, 6, backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
SetDefaults(CGEN);
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
liblms7_status status = SetFrequencyCGEN(122.88);
if (status != LIBLMS7_SUCCESS)
return status;
// //SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
float_type SXRfreqMHz = GetFrequencySX_MHz(Rx, mRefClkSXR_MHz);
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(LMS7param(PD_LOCH_T2RBUF), 1); //PD_LOCH_t2RBUF 1
status = SetFrequencySX(Tx, SXRfreqMHz + bandwidth_MHz / 4, mRefClkSXT_MHz);
if ( status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
Modify_SPI_Reg_bits(0x0200, 3, 2, 0x3); //TSGMODE 1, INSEL 1
//Modify_SPI_Reg_bits(0x0208, 6, 4, 0xFFFF); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 6, 6, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 5, 5, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 4, 4, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, 0);
//RXTSP
SetDefaults(RxTSP);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 7, 0x1); //CMIX_BYP 1
Modify_SPI_Reg_bits(0x040C, 6, 6, 0x0); //AGC_BYP 0
Modify_SPI_Reg_bits(0x040C, 5, 5, 1); //
Modify_SPI_Reg_bits(0x040C, 4, 4, 1); //
Modify_SPI_Reg_bits(0x040C, 3, 3, 1); //
Modify_SPI_Reg_bits(0x040C, 2, 2, 1); // DC_BYP
Modify_SPI_Reg_bits(0x040C, 1, 1, 1); //
Modify_SPI_Reg_bits(0x040C, 0, 0, 1); //
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x7); //agc_avg iq corr
return LIBLMS7_SUCCESS;
}
/** @brief Calibrates Receiver. DC offset, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateRx(float_type bandwidth_MHz)
{
liblms7_status status;
uint32_t minRSSI_i;
uint32_t minRSSI_q;
int16_t iqcorr_rx = 0;
uint32_t minRSSI_iq;
int16_t dcoffi;
int16_t dcoffq;
const int16_t firCoefs[] =
{
-2531,
-517,
2708,
188,
-3059,
216,
3569,
-770,
-4199,
1541,
4886,
-2577,
-5552,
3909,
6108,
-5537,
-6457,
7440,
6507,
-9566,
-6174,
11845,
5391,
-14179,
-4110,
16457,
2310,
-18561,
0,
20369,
-2780,
-21752,
5963,
22610,
-9456,
-22859,
13127,
22444,
-16854,
-21319,
20489,
19492,
-23883,
-17002,
26881,
13902,
-29372,
-10313,
31226,
6345,
-32380,
-2141,
32767,
-2141,
-32380,
6345,
31226,
-10313,
-29372,
13902,
26881,
-17002,
-23883,
19492,
20489,
-21319,
-16854,
22444,
13127,
-22859,
-9456,
22610,
5963,
-21752,
-2780,
20369,
0,
-18561,
2310,
16457,
-4110,
-14179,
5391,
11845,
-6174,
-9566,
6507,
7440,
-6457,
-5537,
6108,
3909,
-5552,
-2577,
4886,
1541,
-4199,
-770,
3569,
216,
-3059,
188,
2708,
-517,
-2531
};
Log("Rx calibration started", LOG_INFO);
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
Log("Saving registers state", LOG_INFO);
BackupAllRegisters();
uint8_t sel_path_rfe = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE));
if (sel_path_rfe == 1 || sel_path_rfe == 0)
return LIBLMS7_BAD_SEL_PATH;
Log("Setup stage", LOG_INFO);
status = CalibrateRxSetup(bandwidth_MHz);
if (status != LIBLMS7_SUCCESS)
goto RxCalibrationEndStage;
Log("Rx DC calibration", LOG_INFO);
CalibrateRxDC_RSSI();
dcoffi = Get_SPI_Reg_bits(LMS7param(DCOFFI_RFE));
dcoffq = Get_SPI_Reg_bits(LMS7param(DCOFFQ_RFE));
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
if (sel_path_rfe == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(0x0103, 10, 10, 1);
Modify_SPI_Reg_bits(0x0103, 11, 11, 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
if (sel_path_rfe == 3)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(0x0103, 11, 11, 1);
Modify_SPI_Reg_bits(0x0103, 10, 10, 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
}
Modify_SPI_Reg_bits(0x040C, 7, 7, 0); //CMIX_BYP 0
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(LMS7param(CMIX_GAIN_RXTSP), 1); //CMIX_GAIN 1 +6 db
Modify_SPI_Reg_bits(0x040C, 13, 13, 1); //CMIX_SC 1
FixRXSaturation();
Modify_SPI_Reg_bits(0x040C, 5, 5, 0); //GFIR3_BYP 0
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 7);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
SetNCOFrequency(Rx, 0, bandwidth_MHz / 4 + 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), 2047);
Log("IQ correction stage", LOG_INFO);
iqcorr_rx = 0;
for (int i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_RXTSP), iqcorr_rx, &iqcorr_rx, 3, 1, 256 >> i);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), iqcorr_rx);
uint16_t mingcorri;
Log("I gain", LOG_INFO);
minRSSI_i = FindMinRSSI_Gain(LMS7param(GCORRI_RXTSP), &mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), 2047);
Log("Q gain", LOG_INFO);
uint16_t mingcorrq;
minRSSI_q = FindMinRSSI_Gain(LMS7param(GCORRQ_RXTSP), &mingcorrq);
if (minRSSI_i < minRSSI_q)
mingcorrq = 2047;
else
mingcorri = 2047;
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Log("Phase", LOG_INFO);
for (int i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_RXTSP), iqcorr_rx, &iqcorr_rx, 3, 1, 256 >> i);
RxCalibrationEndStage:
Log("Restoring registers state", LOG_INFO);
RestoreAllRegisters();
if (status != LIBLMS7_SUCCESS)
{
Log("Rx calibration failed", LOG_WARNING);
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
SetRxDCOFF((int8_t)dcoffi, (int8_t)dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), iqcorr_rx);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Log("Rx calibration finished", LOG_INFO);
return LIBLMS7_SUCCESS;
}
const uint16_t backupAddrs[] = {
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028,
0x0029, 0x002A, 0x002B, 0x002C, 0x002E, 0x0081, 0x0082, 0x0084, 0x0085,
0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x0092, 0x0093, 0x0094,
0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E,
0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8,
0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0100, 0x0101, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010C, 0x010D, 0x010E,
0x010F, 0x0110, 0x0111, 0x0112, 0x0113, 0x0114, 0x0115, 0x0116, 0x0117, 0x0118,
0x0119, 0x011A, 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, 0x0121, 0x0122, 0x0123,
0x0124, 0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207, 0x0208,
0x0240, 0x0242, 0x0243, 0x0400, 0x0401, 0x0402,
0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040A, 0x040B, 0x040C,
0x0440, 0x0442, 0x0443 };
uint16_t backupRegs[sizeof(backupAddrs) / 2];
const uint16_t backupSXAddr[] = { 0x011C, 0x011D, 0x011E, 0x011F, 0x01200, 0x0121, 0x0122, 0x0123, 0x0124 };
uint16_t backupRegsSXR[sizeof(backupSXAddr) / 2];
uint16_t backupRegsSXT[sizeof(backupSXAddr) / 2];
/** @brief Stores chip current registers state into memory for later restoration
*/
void LMS7002M::BackupAllRegisters()
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
SPI_read_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // channel A
SPI_read_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // channel B
SPI_read_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
}
/** @brief Sets chip registers to state that was stored in memory using BackupAllRegisters()
*/
void LMS7002M::RestoreAllRegisters()
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
SPI_write_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // channel A
SPI_write_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // channel B
SPI_write_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
}
/** @brief Searches for minimal digital RSSI value by changing given gain parameter
@param param LMS7002M gain correction parameter
@param foundValue returns value which achieved minimal RSSI
@return minimal found RSSI value
*/
uint32_t LMS7002M::FindMinRSSI_Gain(const LMS7Parameter ¶m, uint16_t *foundValue)
{
uint32_t RSSI = ~0 - 2;
uint32_t prevRSSI = RSSI + 1;
uint8_t decrement = 2;
uint16_t gcorr = 2047;
while (gcorr > 1024)
{
Modify_SPI_Reg_bits(param, gcorr);
RSSI = GetRSSI();
if (RSSI < prevRSSI)
{
prevRSSI = RSSI;
*foundValue = gcorr;
gcorr -= decrement;
decrement *= 2;
}
else
{
if (decrement == 2)
break;
gcorr -= decrement;
decrement = 2;
}
}
return prevRSSI;
}
/** @brief Reads all chip configuration and checks if it matches with local registers copy
*/
bool LMS7002M::IsSynced()
{
if (controlPort->IsOpen() == false)
return false;
bool isSynced = true;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
vector<uint16_t> addrToRead = mRegistersMap->GetUsedAddresses(0);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
{
isSynced = false;
goto isSyncedEnding;
}
//mask out readonly bits
for (uint16_t j = 0; j < sizeof(readOnlyRegisters) / sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToRead.size(); ++k)
if (readOnlyRegisters[j] == addrToRead[k])
{
dataReceived[k] &= readOnlyRegistersMasks[j];
break;
}
//check if local copy matches chip
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
if (dataReceived[i] != mRegistersMap->GetValue(0, addrToRead[i]))
{
isSynced = false;
goto isSyncedEnding;
}
}
addrToRead.clear(); //add only B channel addresses
addrToRead = mRegistersMap->GetUsedAddresses(1);
//mask out readonly bits
for (uint16_t j = 0; j < sizeof(readOnlyRegisters) / sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToRead.size(); ++k)
if (readOnlyRegisters[j] == addrToRead[k])
{
dataReceived[k] &= readOnlyRegistersMasks[j];
break;
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return false;
//check if local copy matches chip
for (uint16_t i = 0; i < addrToRead.size(); ++i)
if (dataReceived[i] != mRegistersMap->GetValue(1, addrToRead[i]))
{
isSynced = false;
break;
}
isSyncedEnding:
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore previously used channel
return isSynced;
}
/** @brief Writes all registers from host to chip
When used on Novena board, also changes gpios to match rx path and tx band selections
*/
liblms7_status LMS7002M::UploadAll()
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
uint16_t x0020_value = mRegistersMap->GetValue(0, 0x0020);
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
addrToWrite = mRegistersMap->GetUsedAddresses(0);
//remove 0x0020 register from list, to not change MAC
addrToWrite.erase( find(addrToWrite.begin(), addrToWrite.end(), 0x0020) );
for (auto address : addrToWrite)
dataToWrite.push_back(mRegistersMap->GetValue(0, address));
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
status = LIBLMS7_SUCCESS;
if (status != LIBLMS7_SUCCESS)
return status;
//after all channel A registers have been written, update 0x0020 register value
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (status != LIBLMS7_SUCCESS)
return status;
addrToWrite = mRegistersMap->GetUsedAddresses(1);
dataToWrite.clear();
for (auto address : addrToWrite)
{
dataToWrite.push_back(mRegistersMap->GetValue(1, address));
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore last used channel
//in case of Novena board, need to update GPIO
if(controlPort->GetInfo().device == LMS_DEV_NOVENA)
{
uint16_t regValue = SPI_read(0x0706) & 0xFFF8;
//lms_gpio2 - tx output selection:
// 0 - TX1_A and TX1_B (Band 1),
// 1 - TX2_A and TX2_B (Band 2)
regValue |= Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF)) << 2; //gpio2
//RX active paths
//lms_gpio0 | lms_gpio1 RX_A RX_B
// 0 0 => no active path
// 1 0 => LNAW_A LNAW_B
// 0 1 => LNAH_A LNAH_B
// 1 1 => LNAL_A LNAL_B
switch(Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE)))
{
//set gpio1:gpio0
case 0: regValue |= 0x0; break;
case 1: regValue |= 0x2; break;
case 2: regValue |= 0x3; break;
case 3: regValue |= 0x1; break;
}
SPI_write(0x0706, regValue);
}
return LIBLMS7_SUCCESS;
}
/** @brief Reads all registers from the chip to host
When used on Novena board, also updates gpios to match rx path and tx band selections
*/
liblms7_status LMS7002M::DownloadAll()
{
if (controlPort == nullptr)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC), false);
vector<uint16_t> addrToRead = mRegistersMap->GetUsedAddresses(0);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return status;
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
uint16_t adr = addrToRead[i];
uint16_t val = dataReceived[i];
mRegistersMap->SetValue(0, addrToRead[i], dataReceived[i]);
}
addrToRead.clear(); //add only B channel addresses
addrToRead = mRegistersMap->GetUsedAddresses(1);
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return status;
for (uint16_t i = 0; i < addrToRead.size(); ++i)
mRegistersMap->SetValue(1, addrToRead[i], dataReceived[i]);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //retore previously used channel
//in case of Novena board, update GPIO
if(controlPort->GetInfo().device == LMS_DEV_NOVENA)
{
uint16_t regValue = SPI_read(0x0706) & 0xFFF8;
//lms_gpio2 - tx output selection:
// 0 - TX1_A and TX1_B (Band 1),
// 1 - TX2_A and TX2_B (Band 2)
regValue |= Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF)) << 2; //gpio2
//RX active paths
//lms_gpio0 | lms_gpio1 RX_A RX_B
// 0 0 => no active path
// 1 0 => LNAW_A LNAW_B
// 0 1 => LNAH_A LNAH_B
// 1 1 => LNAL_A LNAL_B
switch(Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE)))
{
//set gpio1:gpio0
case 0: regValue |= 0x0; break;
case 1: regValue |= 0x2; break;
case 2: regValue |= 0x3; break;
case 3: regValue |= 0x1; break;
}
SPI_write(0x0706, regValue);
}
return LIBLMS7_SUCCESS;
}
/** @brief Configures interfaces for desired frequency
Sets interpolation and decimation, changes MCLK sources and TSP clock dividers accordingly to selected interpolation and decimation
*/
liblms7_status LMS7002M::SetInterfaceFrequency(float_type cgen_freq_MHz, const uint8_t interpolation, const uint8_t decimation)
{
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), decimation);
Modify_SPI_Reg_bits(LMS7param(HBI_OVR_TXTSP), interpolation);
liblms7_status status = SetFrequencyCGEN(cgen_freq_MHz);
if (status != LIBLMS7_SUCCESS)
return status;
if (decimation == 7 || decimation == 0) //bypass
{
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(RXDIVEN), false);
Modify_SPI_Reg_bits(LMS7param(MCLK2SRC), 3);
}
else
{
uint8_t divider = (uint8_t)pow(2.0, decimation);
if (divider > 1)
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), (divider / 2) - 1);
else
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(RXDIVEN), true);
Modify_SPI_Reg_bits(LMS7param(MCLK2SRC), 1);
}
if (interpolation == 7 || interpolation == 0) //bypass
{
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(TXDIVEN), false);
Modify_SPI_Reg_bits(LMS7param(MCLK1SRC), 2);
}
else
{
uint8_t divider = (uint8_t)pow(2.0, interpolation);
if (divider > 1)
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), (divider / 2) - 1);
else
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(TXDIVEN), true);
Modify_SPI_Reg_bits(LMS7param(MCLK1SRC), 0);
}
return status;
}
spi read and write implemented over batch
/**
@file LMS7002M.cpp
@author Lime Microsystems (www.limemicro.com)
@brief Implementation of LMS7002M transceiver configuring
*/
#include "LMS7002M.h"
#include <stdio.h>
#include <set>
#include "lmsComms.h"
#include "INI.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include "LMS7002M_RegistersMap.h"
#include <chrono>
#include <thread>
float_type LMS7002M::gVCO_frequency_table[3][2] = { { 3800, 5222 }, { 4961, 6754 }, {6306, 7714} };
float_type LMS7002M::gCGEN_VCO_frequencies[2] = {2000, 2700};
///define for parameter enumeration if prefix might be needed
#define LMS7param(id) id
//module addresses needs to be sorted in ascending order
const uint16_t LMS7002M::readOnlyRegisters[] = { 0x002F, 0x008C, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x0123, 0x0209, 0x020A, 0x020B, 0x040E, 0x040F };
const uint16_t LMS7002M::readOnlyRegistersMasks[] = { 0x0000, 0x0FFF, 0x007F, 0x0000, 0x0000, 0x0000, 0x0000, 0x003F, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 };
/** @brief Simple logging function to print status messages
@param text message to print
@param type message type for filtering specific information
*/
void LMS7002M::Log(const char* text, LogType type)
{
switch(type)
{
case LOG_INFO:
printf("%s\n", text);
break;
case LOG_WARNING:
printf("Warning: %s\n", text);
break;
case LOG_ERROR:
printf("ERROR: %s\n", text);
break;
case LOG_DATA:
printf("DATA: %s\n", text);
break;
}
}
LMS7002M::LMS7002M() : controlPort(NULL), mRegistersMap(new LMS7002M_RegistersMap())
{
mRefClkSXR_MHz = 30.72;
mRefClkSXT_MHz = 30.72;
}
/** @brief Creates LMS7002M main control object, it requires LMScomms to communicate with chip
@param controlPort data connection for controlling LMS7002 chip registers
*/
LMS7002M::LMS7002M(LMScomms* controlPort) :
controlPort(controlPort), mRegistersMap(new LMS7002M_RegistersMap())
{
mRefClkSXR_MHz = 30.72;
mRefClkSXT_MHz = 30.72;
//memory intervals for registers tests and calibration algorithms
MemorySectionAddresses[LimeLight][0] = 0x0020;
MemorySectionAddresses[LimeLight][1] = 0x002F;
MemorySectionAddresses[EN_DIR][0] = 0x0081;
MemorySectionAddresses[EN_DIR][1] = 0x0081;
MemorySectionAddresses[AFE][0] = 0x0082;
MemorySectionAddresses[AFE][1] = 0x0082;
MemorySectionAddresses[BIAS][0] = 0x0084;
MemorySectionAddresses[BIAS][1] = 0x0084;
MemorySectionAddresses[XBUF][0] = 0x0085;
MemorySectionAddresses[XBUF][1] = 0x0085;
MemorySectionAddresses[CGEN][0] = 0x0086;
MemorySectionAddresses[CGEN][1] = 0x008C;
MemorySectionAddresses[LDO][0] = 0x0092;
MemorySectionAddresses[LDO][1] = 0x00A7;
MemorySectionAddresses[BIST][0] = 0x00A8;
MemorySectionAddresses[BIST][1] = 0x00AC;
MemorySectionAddresses[CDS][0] = 0x00AD;
MemorySectionAddresses[CDS][1] = 0x00AE;
MemorySectionAddresses[TRF][0] = 0x0100;
MemorySectionAddresses[TRF][1] = 0x0104;
MemorySectionAddresses[TBB][0] = 0x0105;
MemorySectionAddresses[TBB][1] = 0x010A;
MemorySectionAddresses[RFE][0] = 0x010C;
MemorySectionAddresses[RFE][1] = 0x0114;
MemorySectionAddresses[RBB][0] = 0x0115;
MemorySectionAddresses[RBB][1] = 0x011A;
MemorySectionAddresses[SX][0] = 0x011C;
MemorySectionAddresses[SX][1] = 0x0124;
MemorySectionAddresses[TxTSP][0] = 0x0200;
MemorySectionAddresses[TxTSP][1] = 0x020C;
MemorySectionAddresses[TxNCO][0] = 0x0240;
MemorySectionAddresses[TxNCO][1] = 0x0261;
MemorySectionAddresses[TxGFIR1][0] = 0x0280;
MemorySectionAddresses[TxGFIR1][1] = 0x02A7;
MemorySectionAddresses[TxGFIR2][0] = 0x02C0;
MemorySectionAddresses[TxGFIR2][1] = 0x02E7;
MemorySectionAddresses[TxGFIR3a][0] = 0x0300;
MemorySectionAddresses[TxGFIR3a][1] = 0x0327;
MemorySectionAddresses[TxGFIR3b][0] = 0x0340;
MemorySectionAddresses[TxGFIR3b][1] = 0x0367;
MemorySectionAddresses[TxGFIR3c][0] = 0x0380;
MemorySectionAddresses[TxGFIR3c][1] = 0x03A7;
MemorySectionAddresses[RxTSP][0] = 0x0400;
MemorySectionAddresses[RxTSP][1] = 0x040F;
MemorySectionAddresses[RxNCO][0] = 0x0440;
MemorySectionAddresses[RxNCO][1] = 0x0461;
MemorySectionAddresses[RxGFIR1][0] = 0x0480;
MemorySectionAddresses[RxGFIR1][1] = 0x04A7;
MemorySectionAddresses[RxGFIR2][0] = 0x04C0;
MemorySectionAddresses[RxGFIR2][1] = 0x04E7;
MemorySectionAddresses[RxGFIR3a][0] = 0x0500;
MemorySectionAddresses[RxGFIR3a][1] = 0x0527;
MemorySectionAddresses[RxGFIR3b][0] = 0x0540;
MemorySectionAddresses[RxGFIR3b][1] = 0x0567;
MemorySectionAddresses[RxGFIR3c][0] = 0x0580;
MemorySectionAddresses[RxGFIR3c][1] = 0x05A7;
mRegistersMap->InitializeDefaultValues(LMS7parameterList);
}
LMS7002M::~LMS7002M()
{
}
/** @brief Sends reset signal to chip, after reset enables B channel controls
@return 0-success, other-failure
*/
liblms7_status LMS7002M::ResetChip()
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_RST;
pkt.outBuffer.push_back(LMS_RST_PULSE);
controlPort->TransferPacket(pkt);
if (pkt.status == STATUS_COMPLETED_CMD)
{
Modify_SPI_Reg_bits(LMS7param(MIMO_SISO), 0); //enable B channel after reset
return LIBLMS7_SUCCESS;
}
else
return LIBLMS7_FAILURE;
}
liblms7_status LMS7002M::LoadConfigLegacyFile(const char* filename)
{
ifstream f(filename);
if (f.good() == false) //file not found
{
f.close();
return LIBLMS7_FILE_NOT_FOUND;
}
f.close();
uint16_t addr = 0;
uint16_t value = 0;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
typedef INI<string, string, string> ini_t;
ini_t parser(filename, true);
if (parser.select("FILE INFO") == false)
return LIBLMS7_FILE_INVALID_FORMAT;
string type = "";
type = parser.get("type", "undefined");
stringstream ss;
if (type.find("LMS7002 configuration") == string::npos)
{
ss << "File " << filename << " not recognized" << endl;
return LIBLMS7_FILE_INVALID_FORMAT;
}
int fileVersion = 0;
fileVersion = parser.get("version", 0);
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
if (fileVersion == 1)
{
if (parser.select("Reference clocks"))
{
mRefClkSXR_MHz = parser.get("SXR reference frequency MHz", 30.72);
mRefClkSXT_MHz = parser.get("SXT reference frequency MHz", 30.72);
}
if (parser.select("LMS7002 registers ch.A") == true)
{
ini_t::sectionsit_t section = parser.sections.find("LMS7002 registers ch.A");
uint16_t x0020_value = 0;
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
if (addr == LMS7param(MAC).address) //skip register containing channel selection
{
x0020_value = value;
continue;
}
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
//parse FCW or PHO
if (parser.select("NCO Rx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_RX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
}
if (parser.select("NCO Tx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_TX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
}
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (parser.select("LMS7002 registers ch.B") == true)
{
addrToWrite.clear();
dataToWrite.clear();
ini_t::sectionsit_t section = parser.sections.find("LMS7002 registers ch.B");
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
//parse FCW or PHO
if (parser.select("NCO Rx ch.B") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_RX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Rx, i, parser.get(varname, 0.0));
}
}
}
if (parser.select("NCO Tx ch.A") == true)
{
char varname[64];
int mode = Get_SPI_Reg_bits(LMS7param(MODE_TX));
if (mode == 0) //FCW
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "FCW%02i", i);
SetNCOFrequency(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
else
{
for (int i = 0; i < 16; ++i)
{
sprintf(varname, "PHO%02i", i);
SetNCOPhaseOffset(LMS7002M::Tx, i, parser.get(varname, 0.0));
}
}
}
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
return LIBLMS7_SUCCESS;
}
else
return LIBLMS7_FILE_INVALID_FORMAT;
return LIBLMS7_FAILURE;
}
/** @brief Reads configuration file and uploads registers to chip
@param filename Configuration source file
@return 0-success, other-failure
*/
liblms7_status LMS7002M::LoadConfig(const char* filename)
{
ifstream f(filename);
if (f.good() == false) //file not found
{
f.close();
return LIBLMS7_FILE_NOT_FOUND;
}
f.close();
uint16_t addr = 0;
uint16_t value = 0;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
typedef INI<string, string, string> ini_t;
ini_t parser(filename, true);
if (parser.select("file_info") == false)
{
//try loading as legacy format
status = LoadConfigLegacyFile(filename);
Modify_SPI_Reg_bits(MAC, 1);
return status;
}
string type = "";
type = parser.get("type", "undefined");
stringstream ss;
if (type.find("lms7002m_minimal_config") == string::npos)
{
ss << "File " << filename << " not recognized" << endl;
return LIBLMS7_FILE_INVALID_FORMAT;
}
int fileVersion = 0;
fileVersion = parser.get("version", 0);
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
if (fileVersion == 1)
{
if(parser.select("lms7002_registers_a") == true)
{
ini_t::sectionsit_t section = parser.sections.find("lms7002_registers_a");
uint16_t x0020_value = 0;
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
if (addr == LMS7param(MAC).address) //skip register containing channel selection
{
x0020_value = value;
continue;
}
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
if (parser.select("lms7002_registers_b") == true)
{
addrToWrite.clear();
dataToWrite.clear();
ini_t::sectionsit_t section = parser.sections.find("lms7002_registers_b");
for (ini_t::keysit_t pairs = section->second->begin(); pairs != section->second->end(); pairs++)
{
sscanf(pairs->first.c_str(), "%hx", &addr);
sscanf(pairs->second.c_str(), "%hx", &value);
addrToWrite.push_back(addr);
dataToWrite.push_back(value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS && status != LIBLMS7_NOT_CONNECTED)
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
parser.select("reference_clocks");
mRefClkSXR_MHz = parser.get("sxr_ref_clk_mhz", 30.72);
mRefClkSXT_MHz = parser.get("sxt_ref_clk_mhz", 30.72);
}
Modify_SPI_Reg_bits(MAC, 1);
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
return LIBLMS7_SUCCESS;
}
/** @brief Reads all registers from chip and saves to file
@param filename destination filename
@return 0-success, other failure
*/
liblms7_status LMS7002M::SaveConfig(const char* filename)
{
liblms7_status status;
typedef INI<> ini_t;
ini_t parser(filename, true);
parser.create("file_info");
parser.set("type", "lms7002m_minimal_config");
parser.set("version", 1);
char addr[80];
char value[80];
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
vector<uint16_t> addrToRead;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
addrToRead.push_back(addr);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
parser.create("lms7002_registers_a");
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
dataReceived[i] = Get_SPI_Reg_bits(addrToRead[i], 15, 0, false);
sprintf(addr, "0x%04X", addrToRead[i]);
sprintf(value, "0x%04X", dataReceived[i]);
parser.set(addr, value);
}
parser.create("lms7002_registers_b");
addrToRead.clear(); //add only B channel addresses
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
if (addr >= 0x0100)
addrToRead.push_back(addr);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
dataReceived[i] = Get_SPI_Reg_bits(addrToRead[i], 15, 0, false);
sprintf(addr, "0x%04X", addrToRead[i]);
sprintf(value, "0x%04X", dataReceived[i]);
parser.set(addr, value);
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //retore previously used channel
parser.create("reference_clocks");
parser.set("sxt_ref_clk_mhz", mRefClkSXT_MHz);
parser.set("sxr_ref_clk_mhz", mRefClkSXR_MHz);
parser.save(filename);
return LIBLMS7_SUCCESS;
}
/** @brief Returns reference clock in MHz used for SXT or SXR
@param Tx transmitter or receiver selection
*/
float_type LMS7002M::GetReferenceClk_SX(bool tx)
{
return tx ? mRefClkSXT_MHz : mRefClkSXR_MHz;
}
/** @return Current CLKGEN frequency in MHz
Returned frequency depends on reference clock used for Receiver
*/
float_type LMS7002M::GetFrequencyCGEN_MHz()
{
float_type dMul = (mRefClkSXR_MHz/2.0)/(Get_SPI_Reg_bits(LMS7param(DIV_OUTCH_CGEN))+1); //DIV_OUTCH_CGEN
uint16_t gINT = Get_SPI_Reg_bits(0x0088, 13, 0); //read whole register to reduce SPI transfers
uint32_t gFRAC = ((gINT & 0xF) * 65536) | Get_SPI_Reg_bits(0x0087, 15, 0);
return dMul * (((gINT>>4) + 1 + gFRAC/1048576.0));
}
/** @brief Returns TSP reference frequency
@param tx TxTSP or RxTSP selection
@return TSP reference frequency in MHz
*/
float_type LMS7002M::GetReferenceClk_TSP_MHz(bool tx)
{
float_type cgenFreq = GetFrequencyCGEN_MHz();
float_type clklfreq = cgenFreq/pow(2.0, Get_SPI_Reg_bits(LMS7param(CLKH_OV_CLKL_CGEN)));
if(Get_SPI_Reg_bits(LMS7param(EN_ADCCLKH_CLKGN)) == 0)
return tx ? clklfreq : cgenFreq/4.0;
else
return tx ? cgenFreq : clklfreq/4.0;
}
/** @brief Sets CLKGEN frequency, calculations use receiver'r reference clock
@param freq_MHz desired frequency in MHz
@return 0-succes, other-cannot deliver desired frequency
*/
liblms7_status LMS7002M::SetFrequencyCGEN(const float_type freq_MHz)
{
float_type dFvco;
float_type dFrac;
int16_t iHdiv;
//VCO frequency selection according to F_CLKH
iHdiv = (int16_t)((gCGEN_VCO_frequencies[1]/ 2) / freq_MHz) - 1;
dFvco = 2*(iHdiv+1) * freq_MHz;
//Integer division
uint16_t gINT = (uint16_t)(dFvco/mRefClkSXR_MHz - 1);
//Fractional division
dFrac = dFvco/mRefClkSXR_MHz - (uint32_t)(dFvco/mRefClkSXR_MHz);
uint32_t gFRAC = (uint32_t)(dFrac * 1048576);
Modify_SPI_Reg_bits(LMS7param(INT_SDM_CGEN), gINT); //INT_SDM_CGEN
Modify_SPI_Reg_bits(0x0087, 15, 0, gFRAC&0xFFFF); //INT_SDM_CGEN[15:0]
Modify_SPI_Reg_bits(0x0088, 3, 0, gFRAC>>16); //INT_SDM_CGEN[19:16]
Modify_SPI_Reg_bits(LMS7param(DIV_OUTCH_CGEN), iHdiv); //DIV_OUTCH_CGEN
return TuneVCO(VCO_CGEN);
}
/** @brief Performs VCO tuning operations for CLKGEN, SXR, SXT modules
@param module module selection for tuning 0-cgen, 1-SXR, 2-SXT
@return 0-success, other-failure
*/
liblms7_status LMS7002M::TuneVCO(VCO_Module module) // 0-cgen, 1-SXR, 2-SXT
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
int8_t i;
uint8_t cmphl; //comparators
int16_t csw_lowest = -1;
uint16_t addrVCOpd; // VCO power down address
uint16_t addrCSW_VCO;
uint16_t addrCMP; //comparator address
uint8_t lsb; //SWC lsb index
uint8_t msb; //SWC msb index
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
if(module != VCO_CGEN) //set addresses to SX module
{
Modify_SPI_Reg_bits(LMS7param(MAC), module);
addrVCOpd = LMS7param(PD_VCO).address;
addrCSW_VCO = LMS7param(CSW_VCO).address;
lsb = LMS7param(CSW_VCO).lsb;
msb = LMS7param(CSW_VCO).msb;
addrCMP = LMS7param(VCO_CMPHO).address;
}
else //set addresses to CGEN module
{
addrVCOpd = LMS7param(PD_VCO_CGEN).address;
addrCSW_VCO = LMS7param(CSW_VCO_CGEN).address;
lsb = LMS7param(CSW_VCO_CGEN).lsb;
msb = LMS7param(CSW_VCO_CGEN).msb;
addrCMP = LMS7param(VCO_CMPHO_CGEN).address;
}
// Initialization
Modify_SPI_Reg_bits (addrVCOpd, 2, 1, 0); //activate VCO and comparator
if (Get_SPI_Reg_bits(addrVCOpd, 2, 1) != 0)
return LIBLMS7_VCO_IS_POWERED_DOWN;
if(module == VCO_CGEN)
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO_CGEN), 1); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
else
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO), 1); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
Modify_SPI_Reg_bits (addrCSW_VCO , msb, lsb , 0); //Set SWC_VCO<7:0>=<00000000>
i=7;
while(i>=0)
{
Modify_SPI_Reg_bits (addrCSW_VCO, lsb + i, lsb + i, 1); // CSW_VCO<i>=1
std::this_thread::sleep_for(std::chrono::milliseconds(5));
cmphl = (uint8_t)Get_SPI_Reg_bits(addrCMP, 13, 12);
if ( (cmphl&0x01) == 1) // reduce CSW
Modify_SPI_Reg_bits (addrCSW_VCO, lsb + i, lsb + i, 0); // CSW_VCO<i>=0
if( cmphl == 2 && csw_lowest < 0)
csw_lowest = Get_SPI_Reg_bits(addrCSW_VCO, msb, lsb);
--i;
}
if(csw_lowest >= 0)
{
uint16_t csw_highest = Get_SPI_Reg_bits(addrCSW_VCO, msb, lsb);
if(csw_lowest == csw_highest)
{
while(csw_lowest>=0)
{
Modify_SPI_Reg_bits(addrCSW_VCO, msb, lsb, csw_lowest);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
if(Get_SPI_Reg_bits(addrCMP, 13, 12) == 0)
{
++csw_lowest;
break;
}
else
--csw_lowest;
}
}
Modify_SPI_Reg_bits(addrCSW_VCO, msb, lsb, csw_lowest+(csw_highest-csw_lowest)/2);
}
if (module == VCO_CGEN)
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO_CGEN), 0); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
else
Modify_SPI_Reg_bits(LMS7param(SPDUP_VCO), 0); //SHORT_NOISEFIL=1 SPDUP_VCO_ Short the noise filter resistor to speed up the settling time
cmphl = (uint8_t)Get_SPI_Reg_bits(addrCMP, 13, 12);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore previously used channel
if(cmphl == 2)
return LIBLMS7_SUCCESS;
else
return LIBLMS7_FAILURE;
}
/** @brief Returns given parameter value from chip register
@param param LMS7002M control parameter
@param fromChip read directly from chip
@return parameter value
*/
uint16_t LMS7002M::Get_SPI_Reg_bits(const LMS7Parameter ¶m, bool fromChip)
{
return Get_SPI_Reg_bits(param.address, param.msb, param.lsb, fromChip);
}
/** @brief Returns given parameter value from chip register
@param address register address
@param msb most significant bit index
@param lsb least significant bit index
@param fromChip read directly from chip
@return register bits from selected interval, shifted to right by lsb bits
*/
uint16_t LMS7002M::Get_SPI_Reg_bits(uint16_t address, uint8_t msb, uint8_t lsb, bool fromChip)
{
return (SPI_read(address, fromChip) & (~(~0<<(msb+1)))) >> lsb; //shift bits to LSB
}
/** @brief Change given parameter value
@param param LMS7002M control parameter
@param fromChip read initial value directly from chip
@param value new parameter value
*/
liblms7_status LMS7002M::Modify_SPI_Reg_bits(const LMS7Parameter ¶m, const uint16_t value, bool fromChip)
{
return Modify_SPI_Reg_bits(param.address, param.msb, param.lsb, value, fromChip);
}
/** @brief Change given parameter value
@param address register address
@param value new bits value, the value is shifted left by lsb bits
@param fromChip read initial value directly from chip
*/
liblms7_status LMS7002M::Modify_SPI_Reg_bits(const uint16_t address, const uint8_t msb, const uint8_t lsb, const uint16_t value, bool fromChip)
{
uint16_t spiDataReg = SPI_read(address, fromChip); //read current SPI reg data
uint16_t spiMask = (~(~0 << (msb - lsb + 1))) << (lsb); // creates bit mask
spiDataReg = (spiDataReg & (~spiMask)) | ((value << lsb) & spiMask);//clear bits
return SPI_write(address, spiDataReg); //write modified data back to SPI reg
}
/** @brief Modifies given registers with values applied using masks
@param addr array of register addresses
@param masks array of applied masks
@param values array of values to be written
@param start starting index of given arrays
@param stop end index of given arrays
*/
liblms7_status LMS7002M::Modify_SPI_Reg_mask(const uint16_t *addr, const uint16_t *masks, const uint16_t *values, uint8_t start, uint8_t stop)
{
liblms7_status status;
uint16_t reg_data;
vector<uint16_t> addresses;
vector<uint16_t> data;
while (start <= stop)
{
reg_data = SPI_read(addr[start], true, &status); //read current SPI reg data
reg_data &= ~masks[start];//clear bits
reg_data |= (values[start] & masks[start]);
addresses.push_back(addr[start]);
data.push_back(reg_data);
++start;
}
if (status != LIBLMS7_SUCCESS)
return status;
SPI_write_batch(&addresses[0], &data[0], addresses.size());
return status;
}
/** @brief Sets SX frequency
@param Tx Rx/Tx module selection
@param freq_MHz desired frequency in MHz
@param refClk_MHz reference clock in MHz
@return 0-success, other-cannot deliver requested frequency
*/
liblms7_status LMS7002M::SetFrequencySX(bool tx, float_type freq_MHz, float_type refClk_MHz)
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
const uint8_t sxVCO_N = 2; //number of entries in VCO frequencies
const float_type m_dThrF = 5500; //threshold to enable additional divider
uint8_t ch; //remember used channel
float_type VCOfreq;
int8_t div_loch;
int8_t sel_vco;
bool canDeliverFrequency = false;
uint16_t integerPart;
uint32_t fractionalPart;
int8_t i;
//find required VCO frequency
for (div_loch = 6; div_loch >= 0; --div_loch)
{
VCOfreq = (1 << (div_loch + 1)) * freq_MHz;
if ((VCOfreq >= gVCO_frequency_table[0][0]) && (VCOfreq <= gVCO_frequency_table[2][sxVCO_N - 1]))
{
canDeliverFrequency = true;
break;
}
}
if (canDeliverFrequency == false)
return LIBLMS7_CANNOT_DELIVER_FREQUENCY;
integerPart = (uint16_t)(VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))) - 4);
fractionalPart = (uint32_t)((VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))) - (uint32_t)(VCOfreq / (refClk_MHz * (1 + (VCOfreq > m_dThrF))))) * 1048576);
ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
Modify_SPI_Reg_bits(LMS7param(MAC), tx + 1);
Modify_SPI_Reg_bits(LMS7param(INT_SDM), integerPart); //INT_SDM
Modify_SPI_Reg_bits(0x011D, 15, 0, fractionalPart & 0xFFFF); //FRAC_SDM[15:0]
Modify_SPI_Reg_bits(0x011E, 3, 0, (fractionalPart >> 16)); //FRAC_SDM[19:16]
Modify_SPI_Reg_bits(LMS7param(DIV_LOCH), div_loch); //DIV_LOCH
Modify_SPI_Reg_bits(LMS7param(EN_DIV2_DIVPROG), (VCOfreq > m_dThrF)); //EN_DIV2_DIVPROG
//find which VCO supports required frequency
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0); //
Modify_SPI_Reg_bits(LMS7param(PD_VCO_COMP), 0); //
int cswBackup = Get_SPI_Reg_bits(LMS7param(CSW_VCO)); //remember to restore previous tune value
canDeliverFrequency = false;
int tuneScore[] = { -128, -128, -128 }; //best is closest to 0
for (sel_vco = 0; sel_vco < 3; ++sel_vco)
{
Modify_SPI_Reg_bits(LMS7param(SEL_VCO), sel_vco);
liblms7_status status = TuneVCO(tx ? VCO_SXT : VCO_SXR);
int csw = Get_SPI_Reg_bits(LMS7param(CSW_VCO), true);
tuneScore[sel_vco] = -128 + csw;
if (status == LIBLMS7_SUCCESS)
canDeliverFrequency = true;
}
if (abs(tuneScore[0]) < abs(tuneScore[1]))
{
if (abs(tuneScore[0]) < abs(tuneScore[2]))
sel_vco = 0;
else
sel_vco = 2;
}
else
{
if (abs(tuneScore[1]) < abs(tuneScore[2]))
sel_vco = 1;
else
sel_vco = 2;
}
Modify_SPI_Reg_bits(LMS7param(SEL_VCO), sel_vco);
Modify_SPI_Reg_bits(LMS7param(CSW_VCO), cswBackup);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore used channel
if (tx)
mRefClkSXT_MHz = refClk_MHz;
else
mRefClkSXR_MHz = refClk_MHz;
if (canDeliverFrequency == false)
return LIBLMS7_CANNOT_DELIVER_FREQUENCY;
return TuneVCO( tx ? VCO_SXT : VCO_SXR); //Rx-1, Tx-2
}
/** @brief Returns currently set SXR/SXT frequency
@return SX frequency MHz
*/
float_type LMS7002M::GetFrequencySX_MHz(bool Tx, float_type refClk_MHz)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember previously used channel
float_type dMul;
if(Tx)
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // Rx mac = 1, Tx max = 2
else
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // Rx mac = 1, Tx max = 2
uint16_t gINT = Get_SPI_Reg_bits(0x011E, 13, 0); // read whole register to reduce SPI transfers
uint32_t gFRAC = ((gINT&0xF) * 65536) | Get_SPI_Reg_bits(0x011D, 15, 0);
dMul = (float_type)refClk_MHz / (1 << (Get_SPI_Reg_bits(LMS7param(DIV_LOCH)) + 1));
//Calculate real frequency according to the calculated parameters
dMul = dMul * ((gINT >> 4) + 4 + (float_type)gFRAC / 1048576.0) * (Get_SPI_Reg_bits(LMS7param(EN_DIV2_DIVPROG)) + 1);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore used channel
return dMul;
}
/** @brief Loads given DC_REG values into registers
@param tx TxTSP or RxTSP selection
@param I DC_REG I value
@param Q DC_REG Q value
*/
liblms7_status LMS7002M::LoadDC_REG_IQ(bool tx, int16_t I, int16_t Q)
{
if(tx)
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
}
else
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_RXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); //DC_BYP
}
return LIBLMS7_SUCCESS;
}
/** @brief Sets chosen NCO's frequency
@param tx transmitter or receiver selection
@param index NCO index from 0 to 15
@param freq_MHz desired NCO frequency
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOFrequency(bool tx, uint8_t index, float_type freq_MHz)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
float_type refClk_MHz = GetReferenceClk_TSP_MHz(tx);
uint16_t addr = tx ? 0x0240 : 0x0440;
uint32_t fcw = (uint32_t)((freq_MHz/refClk_MHz)*4294967296);
SPI_write(addr+2+index*2, (fcw >> 16)); //NCO frequency control word register MSB part.
SPI_write(addr+3+index*2, fcw); //NCO frequency control word register LSB part.
return LIBLMS7_SUCCESS;
}
/** @brief Returns chosen NCO's frequency in MHz
@param tx transmitter or receiver selection
@param index NCO index from 0 to 15
@param fromChip read frequency directly from chip or local registers
@return NCO frequency in MHz
*/
float_type LMS7002M::GetNCOFrequency_MHz(bool tx, uint8_t index, const float_type refClk_MHz, bool fromChip)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
uint16_t addr = tx ? 0x0240 : 0x0440;
uint32_t fcw = 0;
fcw |= SPI_read(addr + 2 + index * 2, fromChip) << 16; //NCO frequency control word register MSB part.
fcw |= SPI_read(addr + 3 + index * 2, fromChip); //NCO frequency control word register LSB part.
return refClk_MHz*(fcw/4294967296.0);
}
/** @brief Sets chosen NCO phase offset angle when memory table MODE is 0
@param tx transmitter or receiver selection
@param angle_deg phase offset angle in degrees
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOPhaseOffsetForMode0(bool tx, float_type angle_deg)
{
uint16_t addr = tx ? 0x0241 : 0x0441;
uint16_t pho = (uint16_t)(65536 * (angle_deg / 360 ));
SPI_write(addr, pho);
return LIBLMS7_SUCCESS;
}
/** @brief Sets chosen NCO's phase offset angle
@param tx transmitter or receiver selection
@param index PHO index from 0 to 15
@param angle_deg phase offset angle in degrees
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetNCOPhaseOffset(bool tx, uint8_t index, float_type angle_deg)
{
if(index > 15)
return LIBLMS7_INDEX_OUT_OF_RANGE;
uint16_t addr = tx ? 0x0244 : 0x0444;
uint16_t pho = (uint16_t)(65536*(angle_deg / 360));
SPI_write(addr+index, pho);
return LIBLMS7_SUCCESS;
}
/** @brief Returns chosen NCO's phase offset angle in radians
@param tx transmitter or receiver selection
@param index PHO index from 0 to 15
@return phase offset angle in degrees
*/
float_type LMS7002M::GetNCOPhaseOffset_Deg(bool tx, uint8_t index)
{
uint16_t addr = tx ? 0x0244 : 0x0444;
uint16_t pho = SPI_read(addr+index);
float_type angle = 360*pho/65536.0;
return angle;
}
/** @brief Uploads given FIR coefficients to chip
@param tx Transmitter or receiver selection
@param GFIR_index GIR index from 0 to 2
@param coef array of coefficients
@param coefCount number of coefficients
@return 0-success, other-failure
This function does not change GFIR*_L or GFIR*_N parameters, they have to be set manually
*/
liblms7_status LMS7002M::SetGFIRCoefficients(bool tx, uint8_t GFIR_index, const int16_t *coef, uint8_t coefCount)
{
uint8_t index;
uint8_t coefLimit;
uint16_t startAddr;
if (GFIR_index == 0)
startAddr = 0x0280;
else if (GFIR_index == 1)
startAddr = 0x02C0;
else
startAddr = 0x0300;
if (tx == false)
startAddr += 0x0200;
if (GFIR_index < 2)
coefLimit = 40;
else
coefLimit = 120;
if (coefCount > coefLimit)
return LIBLMS7_TOO_MANY_VALUES;
vector<uint16_t> addresses;
for (index = 0; index < coefCount; ++index)
addresses.push_back(startAddr + index + 24 * (index / 40));
SPI_write_batch(&addresses[0], (uint16_t*)coef, coefCount);
return LIBLMS7_SUCCESS;
}
/** @brief Returns currently loaded FIR coefficients
@param tx Transmitter or receiver selection
@param GFIR_index GIR index from 0 to 2
@param coef array of returned coefficients
@param coefCount number of coefficients to read
@return 0-success, other-failure
*/
liblms7_status LMS7002M::GetGFIRCoefficients(bool tx, uint8_t GFIR_index, int16_t *coef, uint8_t coefCount)
{
liblms7_status status = LIBLMS7_FAILURE;
uint8_t index;
uint8_t coefLimit;
uint16_t startAddr;
if(GFIR_index == 0)
startAddr = 0x0280;
else if (GFIR_index == 1)
startAddr = 0x02C0;
else
startAddr = 0x0300;
if (tx == false)
startAddr += 0x0200;
if (GFIR_index < 2)
coefLimit = 40;
else
coefLimit = 120;
if (coefCount > coefLimit)
return LIBLMS7_TOO_MANY_VALUES;
std::vector<uint16_t> addresses;
for (index = 0; index < coefCount; ++index)
addresses.push_back(startAddr + index + 24 * (index / 40));
uint16_t spiData[120];
memset(spiData, 0, 120 * sizeof(uint16_t));
if (controlPort->IsOpen())
{
status = SPI_read_batch(&addresses[0], spiData, coefCount);
for (index = 0; index < coefCount; ++index)
coef[index] = spiData[index];
}
else
{
const int channel = Get_SPI_Reg_bits(LMS7param(MAC), false) > 1 ? 1 : 0;
for (index = 0; index < coefCount; ++index)
coef[index] = mRegistersMap->GetValue(channel, addresses[index]);
status = LIBLMS7_SUCCESS;
}
return status;
}
/** @brief Write given data value to whole register
@param address SPI address
@param data new register value
@return 0-succes, other-failure
*/
liblms7_status LMS7002M::SPI_write(uint16_t address, uint16_t data)
{
return this->SPI_write_batch(&address, &data, 1);
}
/** @brief Reads whole register value from given address
@param address SPI address
@param status operation status(optional)
@param fromChip read value directly from chip
@return register value
*/
uint16_t LMS7002M::SPI_read(uint16_t address, bool fromChip, liblms7_status *status)
{
if (controlPort == NULL)
{
if (status)
*status = LIBLMS7_NO_CONNECTION_MANAGER;
}
if (controlPort->IsOpen() == false || fromChip == false)
{
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1 && address >= 0x0100)
return mRegistersMap->GetValue(1, address);
else
return mRegistersMap->GetValue(0, address);
}
uint16_t data = 0;
liblms7_status st = this->SPI_read_batch(&address, &data, 1);
if (status != nullptr) *status = st;
return data;
}
/** @brief Batches multiple register writes into least ammount of transactions
@param spiAddr spi register addresses to be written
@param spiData registers data to be written
@param cnt number of registers to write
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SPI_write_batch(const uint16_t* spiAddr, const uint16_t* spiData, uint16_t cnt)
{
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_WR;
uint32_t index = 0;
for (uint32_t i = 0; i < cnt; ++i)
{
pkt.outBuffer.push_back(spiAddr[i] >> 8);
pkt.outBuffer.push_back(spiAddr[i] & 0xFF);
pkt.outBuffer.push_back(spiData[i] >> 8);
pkt.outBuffer.push_back(spiData[i] & 0xFF);
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
controlPort->TransferPacket(pkt);
if (pkt.status == STATUS_COMPLETED_CMD)
return LIBLMS7_SUCCESS;
else
return LIBLMS7_FAILURE;
}
/** @brief Batches multiple register reads into least amount of transactions
@param spiAddr SPI addresses to read
@param spiData array for read data
@param cnt number of registers to read
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SPI_read_batch(const uint16_t* spiAddr, uint16_t* spiData, uint16_t cnt)
{
LMScomms::GenericPacket pkt;
pkt.cmd = CMD_LMS7002_RD;
uint32_t index = 0;
for (uint32_t i = 0; i < cnt; ++i)
{
pkt.outBuffer.push_back(spiAddr[i] >> 8);
pkt.outBuffer.push_back(spiAddr[i] & 0xFF);
}
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
LMScomms::TransferStatus status = controlPort->TransferPacket(pkt);
if (status != LMScomms::TRANSFER_SUCCESS)
return LIBLMS7_FAILURE;
for (uint32_t i = 0; i < cnt; ++i)
{
spiData[i] = (pkt.inBuffer[2*sizeof(uint16_t)*i + 2] << 8) | pkt.inBuffer[2*sizeof(uint16_t)*i + 3];
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
return pkt.status == STATUS_COMPLETED_CMD ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
/*
for(int i=0; i<cnt; ++i)
{
spiData[i] = Get_SPI_Reg_bits(spiAddr[i], 15, 0);
if ((mRegistersMap->GetValue(0, LMS7param(MAC).address) & 0x0003) > 1)
mRegistersMap->SetValue(1, spiAddr[i], spiData[i]);
else
mRegistersMap->SetValue(0, spiAddr[i], spiData[i]);
}
return LIBLMS7_SUCCESS;*/
}
/** @brief Performs registers test by writing known data and confirming readback data
@return 0-registers test passed, other-failure
*/
liblms7_status LMS7002M::RegistersTest()
{
char chex[16];
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//backup both channel data for restoration after test
vector<uint16_t> ch1Addresses;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
ch1Addresses.push_back(addr);
vector<uint16_t> ch1Data;
ch1Data.resize(ch1Addresses.size(), 0);
//backup A channel
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&ch1Addresses[0], &ch1Data[0], ch1Addresses.size());
if (status != LIBLMS7_SUCCESS)
return status;
vector<uint16_t> ch2Addresses;
for (uint8_t i = 0; i < MEMORY_SECTIONS_COUNT; ++i)
for (uint16_t addr = MemorySectionAddresses[i][0]; addr <= MemorySectionAddresses[i][1]; ++addr)
if (addr >= 0x0100)
ch2Addresses.push_back(addr);
vector<uint16_t> ch2Data;
ch2Data.resize(ch2Addresses.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&ch2Addresses[0], &ch2Data[0], ch2Addresses.size());
if (status != LIBLMS7_SUCCESS)
return status;
//test registers
ResetChip();
Modify_SPI_Reg_bits(LMS7param(MIMO_SISO), 0);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
stringstream ss;
//check single channel memory sections
vector<MemorySection> modulesToCheck = { AFE, BIAS, XBUF, CGEN, LDO, BIST, CDS, TRF, TBB, RFE, RBB, SX,
TxTSP, TxNCO, TxGFIR1, TxGFIR2, TxGFIR3a, TxGFIR3b, TxGFIR3c,
RxTSP, RxNCO, RxGFIR1, RxGFIR2, RxGFIR3a, RxGFIR3b, RxGFIR3c, LimeLight };
const char* moduleNames[] = { "AFE", "BIAS", "XBUF", "CGEN", "LDO", "BIST", "CDS", "TRF", "TBB", "RFE", "RBB", "SX",
"TxTSP", "TxNCO", "TxGFIR1", "TxGFIR2", "TxGFIR3a", "TxGFIR3b", "TxGFIR3c",
"RxTSP", "RxNCO", "RxGFIR1", "RxGFIR2", "RxGFIR3a", "RxGFIR3b", "RxGFIR3c", "LimeLight" };
const uint16_t patterns[] = { 0xAAAA, 0x5555 };
const uint8_t patternsCount = 2;
bool allTestSuccess = true;
for (unsigned i = 0; i < modulesToCheck.size(); ++i)
{
bool moduleTestsSuccess = true;
uint16_t startAddr = MemorySectionAddresses[modulesToCheck[i]][0];
uint16_t endAddr = MemorySectionAddresses[modulesToCheck[i]][1];
uint8_t channelCount = startAddr >= 0x0100 ? 2 : 1;
for (int cc = 1; cc <= channelCount; ++cc)
{
Modify_SPI_Reg_bits(LMS7param(MAC), cc);
sprintf(chex, "0x%04X", startAddr);
ss << moduleNames[i] << " [" << chex << ":";
sprintf(chex, "0x%04X", endAddr);
ss << chex << "]";
if (startAddr >= 0x0100)
ss << " Ch." << (cc == 1 ? "A" : "B");
ss << endl;
for (uint8_t p = 0; p < patternsCount; ++p)
moduleTestsSuccess &= RegistersTestInterval(startAddr, endAddr, patterns[p], ss) == LIBLMS7_SUCCESS;
}
allTestSuccess &= moduleTestsSuccess;
}
//restore register values
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SPI_write_batch(&ch1Addresses[0], &ch1Data[0], ch1Addresses.size());
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
SPI_write_batch(&ch2Addresses[0], &ch2Data[0], ch2Addresses.size());
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
fstream fout;
fout.open("registersTest.txt", ios::out);
fout << ss.str() << endl;
fout.close();
return allTestSuccess ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
/** @brief Performs registers test for given address interval by writing given pattern data
@param startAddr first register address
@param endAddr last reigster address
@param pattern data to be written into registers
@return 0-register test passed, other-failure
*/
liblms7_status LMS7002M::RegistersTestInterval(uint16_t startAddr, uint16_t endAddr, uint16_t pattern, stringstream &ss)
{
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
vector<uint16_t> dataReceived;
vector<uint16_t> dataMasks;
for (uint16_t addr = startAddr; addr <= endAddr; ++addr)
{
addrToWrite.push_back(addr);
}
dataMasks.resize(addrToWrite.size(), 0xFFFF);
for (uint16_t j = 0; j < sizeof(readOnlyRegisters)/sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToWrite.size(); ++k)
if (readOnlyRegisters[j] == addrToWrite[k])
{
dataMasks[k] = readOnlyRegistersMasks[j];
break;
}
dataToWrite.clear();
dataReceived.clear();
for (uint16_t j = 0; j < addrToWrite.size(); ++j)
{
if (addrToWrite[j] == 0x00A6)
dataToWrite.push_back(0x1 | pattern & ~0x2);
else if (addrToWrite[j] == 0x0084)
dataToWrite.push_back(pattern & ~0x19);
else
dataToWrite.push_back(pattern & dataMasks[j]);
}
dataReceived.resize(addrToWrite.size(), 0);
liblms7_status status;
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
status = SPI_read_batch(&addrToWrite[0], &dataReceived[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
bool registersMatch = true;
char ctemp[16];
for (uint16_t j = 0; j < dataToWrite.size(); ++j)
{
if (dataToWrite[j] != (dataReceived[j] & dataMasks[j]))
{
registersMatch = false;
sprintf(ctemp, "0x%04X", addrToWrite[j]);
ss << "\t" << ctemp << "(wr/rd): ";
sprintf(ctemp, "0x%04X", dataToWrite[j]);
ss << ctemp << "/";
sprintf(ctemp, "0x%04X", dataReceived[j]);
ss << ctemp << endl;
}
}
if (registersMatch)
{
sprintf(ctemp, "0x%04X", pattern);
ss << "\tRegisters OK (" << ctemp << ")\n";
}
return registersMatch ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
/** @brief Parameters setup instructions for Tx calibration
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateTxSetup(float_type bandwidth_MHz)
{
//Stage 2
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//rfe
//reset RFE to defaults
SetDefaults(RFE);
if (sel_band1_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 3); //SEL_PATH_RFE 3
else if (sel_band2_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 2);
else
return LIBLMS7_BAND_NOT_SELECTED;
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1); // EN_NEXTTX_RFE 1
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 8); //G_RXLOOPB_RFE 8
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 10); //CCOMP_TIA_RFE 10
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 2600); //CFB_TIA_RFE 2600
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
Modify_SPI_Reg_bits(LMS7param(PD_LNA_RFE), 1);
//RBB
//reset RBB to defaults
SetDefaults(RBB);
Modify_SPI_Reg_bits(LMS7param(PD_LPFL_RBB), 0); //PD_LPFL_RBB 0
Modify_SPI_Reg_bits(LMS7param(RCC_CTL_LPFL_RBB), 0); //RCC_CTL_LPFL_RBB 0
Modify_SPI_Reg_bits(LMS7param(C_CTL_LPFL_RBB), 1500); //C_CTL_LPFL_RBB 1500
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), 22); //G_PGA_RBB 22
//TRF
//reset TRF to defaults
//SetDefaults(TRF);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0); //EN_G_TRF 0
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(LMS7param(LOSS_LIN_TXPAD_TRF), 0); //LOSS_LIN_TXPAD_TRF 5
Modify_SPI_Reg_bits(LMS7param(LOSS_MAIN_TXPAD_TRF), 0); //LOSS_MAIN_TXPAD_TRF 5
//TBB
//reset TBB to defaults
/*SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 9); //CG_IAMP_TBB 9
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
Modify_SPI_Reg_bits(LMS7param(RCAL_LPFH_TBB), 125); //RCAL_LPFH_TBB 0
*/
//AFE
//reset AFE to defaults
uint8_t isel_dac_afe =(uint8_t) Get_SPI_Reg_bits(LMS7param(ISEL_DAC_AFE));
SetDefaults(AFE);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2 0
Modify_SPI_Reg_bits(LMS7param(ISEL_DAC_AFE), isel_dac_afe);
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
//BIAS
uint16_t backup = Get_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS));
SetDefaults(BIAS);
Modify_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS), backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
SetDefaults(CGEN);
//power up VCO
Modify_SPI_Reg_bits(LMS7param(PD_VCO_CGEN), 0);
if (SetFrequencyCGEN(122.88) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_CGEN) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
float_type SXTfreqMHz = GetFrequencySX_MHz(Tx, mRefClkSXT_MHz);
float_type SXRfreqMHz = SXTfreqMHz - bandwidth_MHz / 4 - 1;
if (SetFrequencySX(Rx, SXRfreqMHz, mRefClkSXR_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_SXR) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(LMS7param(PD_LOCH_T2RBUF), 1); //PD_LOCH_T2RBUF 1
if (SetFrequencySX(Tx, SXTfreqMHz, mRefClkSXT_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
if (TuneVCO(VCO_SXT) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
Modify_SPI_Reg_bits(0x0200, 3, 2, 0x3); //TSGMODE 1, INSEL 1
Modify_SPI_Reg_bits(0x0208, 6, 4, 0x7); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(0x0440, 4, 0, 0); //TX SEL[3:0] = 0 & MODE = 0
float_type offset = 0.2;
if (bandwidth_MHz == 8)
{
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
float_type SXTfreqMHz = GetFrequencySX_MHz(Tx, mRefClkSXT_MHz);
float_type sxrFreq = SXTfreqMHz - bandwidth_MHz / 4 - 1 - offset;
if (SetFrequencySX(Rx, sxrFreq, mRefClkSXR_MHz) != LIBLMS7_SUCCESS)
return LIBLMS7_FAILURE;
SetNCOFrequency(Tx, 0, bandwidth_MHz / 4 + offset);
}
else
SetNCOFrequency(Tx, 0, bandwidth_MHz / 4);
//RXTSP
SetDefaults(RxTSP);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 0, 0xBF);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 0); //Decimation HBD ratio
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x7); //agc_avg iq corr
return LIBLMS7_SUCCESS;
}
/** @brief Flips the CAPTURE bit and returns digital RSSI value
*/
uint32_t LMS7002M::GetRSSI()
{
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 0);
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 1);
return (Get_SPI_Reg_bits(0x040F, 15, 0) << 2) | Get_SPI_Reg_bits(0x040E, 1, 0);
}
/** @brief Sets Rx Dc offsets by converting two's complementary numbers to sign and magnitude
*/
void LMS7002M::SetRxDCOFF(int8_t offsetI, int8_t offsetQ)
{
uint16_t valToSend = 0;
if (offsetI < 0)
valToSend |= 0x40;
valToSend |= labs(offsetI);
valToSend = valToSend << 7;
if (offsetQ < 0)
valToSend |= 0x40;
valToSend |= labs(offsetQ);
SPI_write(0x010E, valToSend);
}
/** @brief Calibrates Transmitter. DC correction, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateTx(float_type bandwidth_MHz)
{
liblms7_status status;
Log("Tx calibration started", LOG_INFO);
BackupAllRegisters();
int16_t iqcorr = 0;
uint16_t gcorrq = 0;
uint16_t gcorri = 0;
uint16_t dccorri;
uint16_t dccorrq;
int16_t corrI = 0;
int16_t corrQ = 0;
uint32_t minRSSI_i;
uint32_t minRSSI_q;
uint32_t minRSSI_iq;
int16_t i;
int16_t offsetI = 0;
int16_t offsetQ = 0;
const short firCoefs[] =
{
-2531,
-517,
2708,
188,
-3059,
216,
3569,
-770,
-4199,
1541,
4886,
-2577,
-5552,
3909,
6108,
-5537,
-6457,
7440,
6507,
-9566,
-6174,
11845,
5391,
-14179,
-4110,
16457,
2310,
-18561,
0,
20369,
-2780,
-21752,
5963,
22610,
-9456,
-22859,
13127,
22444,
-16854,
-21319,
20489,
19492,
-23883,
-17002,
26881,
13902,
-29372,
-10313,
31226,
6345,
-32380,
-2141,
32767,
-2141,
-32380,
6345,
31226,
-10313,
-29372,
13902,
26881,
-17002,
-23883,
19492,
20489,
-21319,
-16854,
22444,
13127,
-22859,
-9456,
22610,
5963,
-21752,
-2780,
20369,
0,
-18561,
2310,
16457,
-4110,
-14179,
5391,
11845,
-6174,
-9566,
6507,
7440,
-6457,
-5537,
6108,
3909,
-5552,
-2577,
4886,
1541,
-4199,
-770,
3569,
216,
-3059,
188,
2708,
-517,
-2531
};
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//Stage 1
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
Log("Setup stage", LOG_INFO);
status = CalibrateTxSetup(bandwidth_MHz);
if (status != LIBLMS7_SUCCESS)
goto TxCalibrationEnd; //go to ending stage to restore registers
//Stage 3
//Calibrate Rx DC
Log("Rx DC calibration", LOG_INFO);
{
uint16_t requiredRegs[] = { 0x0400, 0x040A, 0x010D, 0x040C };
uint16_t requiredMask[] = { 0x6000, 0x3007, 0x0040, 0x00FF }; //CAPSEL, AGC_MODE, AGC_AVG, EN_DCOFF, Bypasses
uint16_t requiredValue[] = { 0x0000, 0x1007, 0x0040, 0x00BD };
Modify_SPI_Reg_mask(requiredRegs, requiredMask, requiredValue, 0, 3);
}
for (i = 0; i<6; ++i)
{
FindMinRSSI(LMS7param(DCOFFI_RFE), offsetI, &offsetI, 3, 2, 32 >> i);
FindMinRSSI(LMS7param(DCOFFQ_RFE), offsetQ, &offsetQ, 3, 2, 32 >> i);
}
SetRxDCOFF((int8_t)offsetI, (int8_t)offsetQ);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); // DC_BYP 0
sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//B
Modify_SPI_Reg_bits(0x0100, 0, 0, 1); //EN_G_TRF 1
if (sel_band1_trf == 1)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0); //PD_RLOOPB_1_RFE 0
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0); //EN_INSHSW_LB1 0
}
if (sel_band2_trf == 1)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0); //PD_RLOOPB_2_RFE 0
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0); // EN_INSHSW_LB2 0
}
FixRXSaturation();
Modify_SPI_Reg_bits(LMS7param(GFIR3_BYP_RXTSP), 0); //GFIR3_BYP 0
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 7);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
Log("IQ correction stage", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), 0);
Log("I gain", LOG_INFO);
minRSSI_i = FindMinRSSI_Gain(LMS7param(GCORRI_TXTSP), &gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), 2047);
Log("Q gain", LOG_INFO);
minRSSI_q = FindMinRSSI_Gain(LMS7param(GCORRQ_TXTSP), &gcorrq);
if (minRSSI_i < minRSSI_q)
gcorrq = 2047;
else
gcorri = 2047;
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Log("Phase", LOG_INFO);
iqcorr = 0;
for (uint8_t i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_TXTSP), iqcorr, &iqcorr, 3, 1, 256 >> i);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), iqcorr);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SetFrequencySX(Rx, GetFrequencySX_MHz(Tx, mRefClkSXT_MHz)-1, mRefClkSXR_MHz);
if (status != LIBLMS7_SUCCESS)
goto TxCalibrationEnd; //go to ending stage to restore registers
//C
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Log("TX LO calibration", LOG_INFO);
//Calibrate Tx DC
for (uint8_t i = 0; i<7; ++i)
{
FindMinRSSI(LMS7param(DCCORRI_TXTSP), corrI, &corrI, 3, 1, 64 >> i);
FindMinRSSI(LMS7param(DCCORRQ_TXTSP), corrQ, &corrQ, 3, 1, 64 >> i);
}
dccorri = Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP));
dccorrq = Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP));
// Stage 4
TxCalibrationEnd:
Log("Restoring registers state", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
RestoreAllRegisters();
if (status != LIBLMS7_SUCCESS)
{
Log("Tx calibration failed", LOG_WARNING);
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dccorri);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dccorrq);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), iqcorr);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
Log("Tx calibration finished", LOG_INFO);
return LIBLMS7_SUCCESS;
}
/** @brief Performs Rx DC offsets calibration
*/
void LMS7002M::CalibrateRxDC_RSSI()
{
int16_t i;
int16_t offsetI = 0;
int16_t offsetQ = 0;
uint16_t requiredRegs[] = { 0x0400, 0x040A, 0x010D, 0x040C };
uint16_t requiredMask[] = { 0x6000, 0x3007, 0x0040, 0x00FF }; //CAPSEL, AGC_MODE, AGC_AVG, EN_DCOFF, Bypasses
uint16_t requiredValue[] = { 0x0000, 0x1007, 0x0040, 0x00BD };
Modify_SPI_Reg_mask(requiredRegs, requiredMask, requiredValue, 0, 3);
for (i = 0; i<6; ++i)
{
FindMinRSSI(LMS7param(DCOFFI_RFE), offsetI, &offsetI, 3, 2, 32 >> i);
FindMinRSSI(LMS7param(DCOFFQ_RFE), offsetQ, &offsetQ, 3, 2, 32 >> i);
}
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
SetRxDCOFF((int8_t)offsetI, (int8_t)offsetQ);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0); // DC_BYP 0
}
/** @brief Tries to detect and fix gains if Rx is saturated
@return 0-success, other-failure
*/
liblms7_status LMS7002M::FixRXSaturation()
{
uint8_t g_rxloopb = 0;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 3);
int8_t lLoopb = 3;
const uint32_t rssi_saturation_level = 0xD000;
while (g_rxloopb < 15)
{
g_rxloopb += 1;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 3);
if (GetRSSI() < rssi_saturation_level)
{
for (lLoopb = 3; lLoopb >= 0; --lLoopb)
{
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), lLoopb);
if (GetRSSI() > rssi_saturation_level)
{
++lLoopb;
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), lLoopb);
goto finished;
}
}
}
else
{
g_rxloopb -= 1;
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), g_rxloopb);
break;
}
}
finished:
return GetRSSI() < rssi_saturation_level ? LIBLMS7_SUCCESS : LIBLMS7_FAILURE;
}
uint32_t LMS7002M::FindMinRSSI(const LMS7Parameter ¶m, const int16_t startValue, int16_t *result, const uint8_t scanWidth, const uint8_t twoCompl, int8_t stepMult)
{
return FindMinRSSI(param.address, param.msb, param.lsb, startValue, result, scanWidth, twoCompl, stepMult);
}
/** @brief Searches for minimal RSSI value while changing given address bits
@param addr address of parameter being changed
@param msb most significant bit index
@param lsb least significant bit index
@param startValue initial value where to start search
@param result found minimal parameter value will be set here
@param twoCompl varying parameter value is treated as two's complement
@return found minimal RSSI value
*/
uint32_t LMS7002M::FindMinRSSI(const uint16_t addr, const uint8_t msb, const uint8_t lsb, const int16_t startValue, int16_t *result, const uint8_t scanWidth, const uint8_t twoCompl, int8_t stepMult)
{
if (scanWidth < 1)
return ~0;
int minI;
int min = startValue;
int globMin = 0;
uint32_t minRSSI = ~0;
unsigned int *rssiField = new unsigned int[scanWidth];
int minRSSIindex;
int i;
int maxVal;
int minVal = 0;
if (twoCompl)
{
maxVal = (~(~0x0 << (msb - lsb + 1))) / 2;
minVal = -(~(~0x0 << (msb - lsb + 1))) / 2 - 1;
}
else
maxVal = (~(~0x0 << (msb - lsb + 1)));
Modify_SPI_Reg_bits(addr, msb, lsb, startValue);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
minRSSIindex = 0;
for (i = 0; i<scanWidth; ++i)
{
short currentValue = min + (i - scanWidth / 2)*stepMult;
if (currentValue < minVal)
currentValue = minVal;
else if (currentValue > maxVal)
currentValue = maxVal;
if (twoCompl == 2)
{
uint16_t valToSend = 0;
if (currentValue < 0)
valToSend |= 0x40;
valToSend |= labs(currentValue);
Modify_SPI_Reg_bits(addr, msb, lsb, valToSend);
}
else
Modify_SPI_Reg_bits(addr, msb, lsb, currentValue);
rssiField[i] = GetRSSI();
}
minI = min;
minRSSIindex = 0;
for (i = 0; i<scanWidth; ++i)
if (rssiField[i] < minRSSI)
{
minRSSI = rssiField[i];
minRSSIindex = i;
minI = min + (i - scanWidth / 2)*stepMult;
if (minI > maxVal)
minI = maxVal;
else if (minI < minVal)
minI = minVal;
globMin = minI;
}
min = minI;
Modify_SPI_Reg_bits(addr, msb, lsb, min);
*result = min;
return minRSSI;
}
/** @brief Sets given module registers to default values
@return 0-success, other-failure
*/
liblms7_status LMS7002M::SetDefaults(MemorySection module)
{
liblms7_status status = LIBLMS7_SUCCESS;
vector<uint16_t> addrs;
vector<uint16_t> values;
for(uint32_t address = MemorySectionAddresses[module][0]; address <= MemorySectionAddresses[module][1]; ++address)
{
addrs.push_back(address);
values.push_back(mRegistersMap->GetDefaultValue(address));
}
status = SPI_write_batch(&addrs[0], &values[0], addrs.size());
return status;
}
/** @brief Parameters setup instructions for Rx calibration
@param bandwidth_MHz filter bandwidth in MHz
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateRxSetup(float_type bandwidth_MHz)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//rfe
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); // EN_NEXTTX_TRF 0
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 15); //G_RXLOOPB_RFE 15
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(0x010C, 1, 1, 0); //PD_TIA 0
Modify_SPI_Reg_bits(0x010C, 7, 7, 1); //PD_LNA 1
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Modify_SPI_Reg_bits(0x010D, 4, 1, 0xFF); // all short switches are enabled
//RBB
Modify_SPI_Reg_bits(0x0115, 15, 14, 0); //Loopback switches disable
Modify_SPI_Reg_bits(0x0119, 15, 15, 0); //OSW_PGA 0
//TRF
//reset TRF to defaults
SetDefaults(TRF);
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0); //EN_G_TRF 0
if (ch == 2)
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(LMS7param(LOSS_LIN_TXPAD_TRF), 0); //LOSS_LIN_TXPAD_TRF 5
Modify_SPI_Reg_bits(LMS7param(LOSS_MAIN_TXPAD_TRF), 0); //LOSS_MAIN_TXPAD_TRF 5
//TBB
//reset TBB to defaults
SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 9); //CG_IAMP_TBB 9
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
//AFE
//reset AFE to defaults
SetDefaults(AFE);
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2
if (ch == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0); //PD_TX_AFE2
}
//BIAS
uint16_t backup = Get_SPI_Reg_bits(0x0084, 10, 6);
SetDefaults(BIAS);
Modify_SPI_Reg_bits(0x0084, 10, 6, backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
SetDefaults(CGEN);
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
liblms7_status status = SetFrequencyCGEN(122.88);
if (status != LIBLMS7_SUCCESS)
return status;
// //SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
float_type SXRfreqMHz = GetFrequencySX_MHz(Rx, mRefClkSXR_MHz);
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(LMS7param(PD_LOCH_T2RBUF), 1); //PD_LOCH_t2RBUF 1
status = SetFrequencySX(Tx, SXRfreqMHz + bandwidth_MHz / 4, mRefClkSXT_MHz);
if ( status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
Modify_SPI_Reg_bits(0x0200, 3, 2, 0x3); //TSGMODE 1, INSEL 1
//Modify_SPI_Reg_bits(0x0208, 6, 4, 0xFFFF); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 6, 6, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 5, 5, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(0x0208, 4, 4, 1); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, 0);
//RXTSP
SetDefaults(RxTSP);
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 7, 0x1); //CMIX_BYP 1
Modify_SPI_Reg_bits(0x040C, 6, 6, 0x0); //AGC_BYP 0
Modify_SPI_Reg_bits(0x040C, 5, 5, 1); //
Modify_SPI_Reg_bits(0x040C, 4, 4, 1); //
Modify_SPI_Reg_bits(0x040C, 3, 3, 1); //
Modify_SPI_Reg_bits(0x040C, 2, 2, 1); // DC_BYP
Modify_SPI_Reg_bits(0x040C, 1, 1, 1); //
Modify_SPI_Reg_bits(0x040C, 0, 0, 1); //
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x7); //agc_avg iq corr
return LIBLMS7_SUCCESS;
}
/** @brief Calibrates Receiver. DC offset, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
liblms7_status LMS7002M::CalibrateRx(float_type bandwidth_MHz)
{
liblms7_status status;
uint32_t minRSSI_i;
uint32_t minRSSI_q;
int16_t iqcorr_rx = 0;
uint32_t minRSSI_iq;
int16_t dcoffi;
int16_t dcoffq;
const int16_t firCoefs[] =
{
-2531,
-517,
2708,
188,
-3059,
216,
3569,
-770,
-4199,
1541,
4886,
-2577,
-5552,
3909,
6108,
-5537,
-6457,
7440,
6507,
-9566,
-6174,
11845,
5391,
-14179,
-4110,
16457,
2310,
-18561,
0,
20369,
-2780,
-21752,
5963,
22610,
-9456,
-22859,
13127,
22444,
-16854,
-21319,
20489,
19492,
-23883,
-17002,
26881,
13902,
-29372,
-10313,
31226,
6345,
-32380,
-2141,
32767,
-2141,
-32380,
6345,
31226,
-10313,
-29372,
13902,
26881,
-17002,
-23883,
19492,
20489,
-21319,
-16854,
22444,
13127,
-22859,
-9456,
22610,
5963,
-21752,
-2780,
20369,
0,
-18561,
2310,
16457,
-4110,
-14179,
5391,
11845,
-6174,
-9566,
6507,
7440,
-6457,
-5537,
6108,
3909,
-5552,
-2577,
4886,
1541,
-4199,
-770,
3569,
216,
-3059,
188,
2708,
-517,
-2531
};
Log("Rx calibration started", LOG_INFO);
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
Log("Saving registers state", LOG_INFO);
BackupAllRegisters();
uint8_t sel_path_rfe = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE));
if (sel_path_rfe == 1 || sel_path_rfe == 0)
return LIBLMS7_BAD_SEL_PATH;
Log("Setup stage", LOG_INFO);
status = CalibrateRxSetup(bandwidth_MHz);
if (status != LIBLMS7_SUCCESS)
goto RxCalibrationEndStage;
Log("Rx DC calibration", LOG_INFO);
CalibrateRxDC_RSSI();
dcoffi = Get_SPI_Reg_bits(LMS7param(DCOFFI_RFE));
dcoffq = Get_SPI_Reg_bits(LMS7param(DCOFFQ_RFE));
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
if (sel_path_rfe == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(0x0103, 10, 10, 1);
Modify_SPI_Reg_bits(0x0103, 11, 11, 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
if (sel_path_rfe == 3)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(0x0103, 11, 11, 1);
Modify_SPI_Reg_bits(0x0103, 10, 10, 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
}
Modify_SPI_Reg_bits(0x040C, 7, 7, 0); //CMIX_BYP 0
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(LMS7param(CMIX_GAIN_RXTSP), 1); //CMIX_GAIN 1 +6 db
Modify_SPI_Reg_bits(0x040C, 13, 13, 1); //CMIX_SC 1
FixRXSaturation();
Modify_SPI_Reg_bits(0x040C, 5, 5, 0); //GFIR3_BYP 0
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 2);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 7);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
SetNCOFrequency(Rx, 0, bandwidth_MHz / 4 + 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), 2047);
Log("IQ correction stage", LOG_INFO);
iqcorr_rx = 0;
for (int i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_RXTSP), iqcorr_rx, &iqcorr_rx, 3, 1, 256 >> i);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), iqcorr_rx);
uint16_t mingcorri;
Log("I gain", LOG_INFO);
minRSSI_i = FindMinRSSI_Gain(LMS7param(GCORRI_RXTSP), &mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), 2047);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), 2047);
Log("Q gain", LOG_INFO);
uint16_t mingcorrq;
minRSSI_q = FindMinRSSI_Gain(LMS7param(GCORRQ_RXTSP), &mingcorrq);
if (minRSSI_i < minRSSI_q)
mingcorrq = 2047;
else
mingcorri = 2047;
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Log("Phase", LOG_INFO);
for (int i = 0; i<9; ++i)
minRSSI_iq = FindMinRSSI(LMS7param(IQCORR_RXTSP), iqcorr_rx, &iqcorr_rx, 3, 1, 256 >> i);
RxCalibrationEndStage:
Log("Restoring registers state", LOG_INFO);
RestoreAllRegisters();
if (status != LIBLMS7_SUCCESS)
{
Log("Rx calibration failed", LOG_WARNING);
return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
SetRxDCOFF((int8_t)dcoffi, (int8_t)dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), iqcorr_rx);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Log("Rx calibration finished", LOG_INFO);
return LIBLMS7_SUCCESS;
}
const uint16_t backupAddrs[] = {
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028,
0x0029, 0x002A, 0x002B, 0x002C, 0x002E, 0x0081, 0x0082, 0x0084, 0x0085,
0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x0092, 0x0093, 0x0094,
0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E,
0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8,
0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0100, 0x0101, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010C, 0x010D, 0x010E,
0x010F, 0x0110, 0x0111, 0x0112, 0x0113, 0x0114, 0x0115, 0x0116, 0x0117, 0x0118,
0x0119, 0x011A, 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, 0x0121, 0x0122, 0x0123,
0x0124, 0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207, 0x0208,
0x0240, 0x0242, 0x0243, 0x0400, 0x0401, 0x0402,
0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040A, 0x040B, 0x040C,
0x0440, 0x0442, 0x0443 };
uint16_t backupRegs[sizeof(backupAddrs) / 2];
const uint16_t backupSXAddr[] = { 0x011C, 0x011D, 0x011E, 0x011F, 0x01200, 0x0121, 0x0122, 0x0123, 0x0124 };
uint16_t backupRegsSXR[sizeof(backupSXAddr) / 2];
uint16_t backupRegsSXT[sizeof(backupSXAddr) / 2];
/** @brief Stores chip current registers state into memory for later restoration
*/
void LMS7002M::BackupAllRegisters()
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
SPI_read_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // channel A
SPI_read_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // channel B
SPI_read_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
}
/** @brief Sets chip registers to state that was stored in memory using BackupAllRegisters()
*/
void LMS7002M::RestoreAllRegisters()
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
SPI_write_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 1); // channel A
SPI_write_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), 2); // channel B
SPI_write_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
}
/** @brief Searches for minimal digital RSSI value by changing given gain parameter
@param param LMS7002M gain correction parameter
@param foundValue returns value which achieved minimal RSSI
@return minimal found RSSI value
*/
uint32_t LMS7002M::FindMinRSSI_Gain(const LMS7Parameter ¶m, uint16_t *foundValue)
{
uint32_t RSSI = ~0 - 2;
uint32_t prevRSSI = RSSI + 1;
uint8_t decrement = 2;
uint16_t gcorr = 2047;
while (gcorr > 1024)
{
Modify_SPI_Reg_bits(param, gcorr);
RSSI = GetRSSI();
if (RSSI < prevRSSI)
{
prevRSSI = RSSI;
*foundValue = gcorr;
gcorr -= decrement;
decrement *= 2;
}
else
{
if (decrement == 2)
break;
gcorr -= decrement;
decrement = 2;
}
}
return prevRSSI;
}
/** @brief Reads all chip configuration and checks if it matches with local registers copy
*/
bool LMS7002M::IsSynced()
{
if (controlPort->IsOpen() == false)
return false;
bool isSynced = true;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
vector<uint16_t> addrToRead = mRegistersMap->GetUsedAddresses(0);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
{
isSynced = false;
goto isSyncedEnding;
}
//mask out readonly bits
for (uint16_t j = 0; j < sizeof(readOnlyRegisters) / sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToRead.size(); ++k)
if (readOnlyRegisters[j] == addrToRead[k])
{
dataReceived[k] &= readOnlyRegistersMasks[j];
break;
}
//check if local copy matches chip
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
if (dataReceived[i] != mRegistersMap->GetValue(0, addrToRead[i]))
{
isSynced = false;
goto isSyncedEnding;
}
}
addrToRead.clear(); //add only B channel addresses
addrToRead = mRegistersMap->GetUsedAddresses(1);
//mask out readonly bits
for (uint16_t j = 0; j < sizeof(readOnlyRegisters) / sizeof(uint16_t); ++j)
for (uint16_t k = 0; k < addrToRead.size(); ++k)
if (readOnlyRegisters[j] == addrToRead[k])
{
dataReceived[k] &= readOnlyRegistersMasks[j];
break;
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return false;
//check if local copy matches chip
for (uint16_t i = 0; i < addrToRead.size(); ++i)
if (dataReceived[i] != mRegistersMap->GetValue(1, addrToRead[i]))
{
isSynced = false;
break;
}
isSyncedEnding:
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore previously used channel
return isSynced;
}
/** @brief Writes all registers from host to chip
When used on Novena board, also changes gpios to match rx path and tx band selections
*/
liblms7_status LMS7002M::UploadAll()
{
if (controlPort == NULL)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC)); //remember used channel
liblms7_status status;
vector<uint16_t> addrToWrite;
vector<uint16_t> dataToWrite;
uint16_t x0020_value = mRegistersMap->GetValue(0, 0x0020);
Modify_SPI_Reg_bits(LMS7param(MAC), 1); //select A channel
addrToWrite = mRegistersMap->GetUsedAddresses(0);
//remove 0x0020 register from list, to not change MAC
addrToWrite.erase( find(addrToWrite.begin(), addrToWrite.end(), 0x0020) );
for (auto address : addrToWrite)
dataToWrite.push_back(mRegistersMap->GetValue(0, address));
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
status = LIBLMS7_SUCCESS;
if (status != LIBLMS7_SUCCESS)
return status;
//after all channel A registers have been written, update 0x0020 register value
status = SPI_write(0x0020, x0020_value);
if (status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
if (status != LIBLMS7_SUCCESS)
return status;
addrToWrite = mRegistersMap->GetUsedAddresses(1);
dataToWrite.clear();
for (auto address : addrToWrite)
{
dataToWrite.push_back(mRegistersMap->GetValue(1, address));
}
Modify_SPI_Reg_bits(LMS7param(MAC), 2); //select B channel
status = SPI_write_batch(&addrToWrite[0], &dataToWrite[0], addrToWrite.size());
if (status != LIBLMS7_SUCCESS)
return status;
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //restore last used channel
//in case of Novena board, need to update GPIO
if(controlPort->GetInfo().device == LMS_DEV_NOVENA)
{
uint16_t regValue = SPI_read(0x0706) & 0xFFF8;
//lms_gpio2 - tx output selection:
// 0 - TX1_A and TX1_B (Band 1),
// 1 - TX2_A and TX2_B (Band 2)
regValue |= Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF)) << 2; //gpio2
//RX active paths
//lms_gpio0 | lms_gpio1 RX_A RX_B
// 0 0 => no active path
// 1 0 => LNAW_A LNAW_B
// 0 1 => LNAH_A LNAH_B
// 1 1 => LNAL_A LNAL_B
switch(Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE)))
{
//set gpio1:gpio0
case 0: regValue |= 0x0; break;
case 1: regValue |= 0x2; break;
case 2: regValue |= 0x3; break;
case 3: regValue |= 0x1; break;
}
SPI_write(0x0706, regValue);
}
return LIBLMS7_SUCCESS;
}
/** @brief Reads all registers from the chip to host
When used on Novena board, also updates gpios to match rx path and tx band selections
*/
liblms7_status LMS7002M::DownloadAll()
{
if (controlPort == nullptr)
return LIBLMS7_NO_CONNECTION_MANAGER;
if (controlPort->IsOpen() == false)
return LIBLMS7_NOT_CONNECTED;
liblms7_status status;
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC), false);
vector<uint16_t> addrToRead = mRegistersMap->GetUsedAddresses(0);
vector<uint16_t> dataReceived;
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return status;
for (uint16_t i = 0; i < addrToRead.size(); ++i)
{
uint16_t adr = addrToRead[i];
uint16_t val = dataReceived[i];
mRegistersMap->SetValue(0, addrToRead[i], dataReceived[i]);
}
addrToRead.clear(); //add only B channel addresses
addrToRead = mRegistersMap->GetUsedAddresses(1);
dataReceived.resize(addrToRead.size(), 0);
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
status = SPI_read_batch(&addrToRead[0], &dataReceived[0], addrToRead.size());
if (status != LIBLMS7_SUCCESS)
return status;
for (uint16_t i = 0; i < addrToRead.size(); ++i)
mRegistersMap->SetValue(1, addrToRead[i], dataReceived[i]);
Modify_SPI_Reg_bits(LMS7param(MAC), ch); //retore previously used channel
//in case of Novena board, update GPIO
if(controlPort->GetInfo().device == LMS_DEV_NOVENA)
{
uint16_t regValue = SPI_read(0x0706) & 0xFFF8;
//lms_gpio2 - tx output selection:
// 0 - TX1_A and TX1_B (Band 1),
// 1 - TX2_A and TX2_B (Band 2)
regValue |= Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF)) << 2; //gpio2
//RX active paths
//lms_gpio0 | lms_gpio1 RX_A RX_B
// 0 0 => no active path
// 1 0 => LNAW_A LNAW_B
// 0 1 => LNAH_A LNAH_B
// 1 1 => LNAL_A LNAL_B
switch(Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE)))
{
//set gpio1:gpio0
case 0: regValue |= 0x0; break;
case 1: regValue |= 0x2; break;
case 2: regValue |= 0x3; break;
case 3: regValue |= 0x1; break;
}
SPI_write(0x0706, regValue);
}
return LIBLMS7_SUCCESS;
}
/** @brief Configures interfaces for desired frequency
Sets interpolation and decimation, changes MCLK sources and TSP clock dividers accordingly to selected interpolation and decimation
*/
liblms7_status LMS7002M::SetInterfaceFrequency(float_type cgen_freq_MHz, const uint8_t interpolation, const uint8_t decimation)
{
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), decimation);
Modify_SPI_Reg_bits(LMS7param(HBI_OVR_TXTSP), interpolation);
liblms7_status status = SetFrequencyCGEN(cgen_freq_MHz);
if (status != LIBLMS7_SUCCESS)
return status;
if (decimation == 7 || decimation == 0) //bypass
{
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(RXDIVEN), false);
Modify_SPI_Reg_bits(LMS7param(MCLK2SRC), 3);
}
else
{
uint8_t divider = (uint8_t)pow(2.0, decimation);
if (divider > 1)
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), (divider / 2) - 1);
else
Modify_SPI_Reg_bits(LMS7param(RXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(RXDIVEN), true);
Modify_SPI_Reg_bits(LMS7param(MCLK2SRC), 1);
}
if (interpolation == 7 || interpolation == 0) //bypass
{
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(TXDIVEN), false);
Modify_SPI_Reg_bits(LMS7param(MCLK1SRC), 2);
}
else
{
uint8_t divider = (uint8_t)pow(2.0, interpolation);
if (divider > 1)
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), (divider / 2) - 1);
else
Modify_SPI_Reg_bits(LMS7param(TXTSPCLKA_DIV), 0);
Modify_SPI_Reg_bits(LMS7param(TXDIVEN), true);
Modify_SPI_Reg_bits(LMS7param(MCLK1SRC), 0);
}
return status;
}
|
/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010-2011 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "uri_capture.h"
#include "uc_configuration.h"
#include "db_uri_record.h"
#include "seeks_proxy.h" // for user_db.
#include "proxy_configuration.h"
#include "user_db.h"
#include "proxy_dts.h"
#include "urlmatch.h"
#include "miscutil.h"
#include "charset_conv.h"
#include "curl_mget.h"
#include "errlog.h"
#include <sys/time.h>
#include <sys/stat.h>
#include <algorithm>
#include <iterator>
#include <iostream>
using sp::seeks_proxy;
using sp::user_db;
using sp::db_record;
using sp::urlmatch;
using sp::miscutil;
using sp::charset_conv;
using sp::errlog;
namespace seeks_plugins
{
/*- uri_db_sweepable -*/
uri_db_sweepable::uri_db_sweepable()
:user_db_sweepable()
{
// set last sweep to now.
// sweeping is done when plugin starts.
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
_last_sweep = tv_now.tv_sec;
}
uri_db_sweepable::~uri_db_sweepable()
{
}
bool uri_db_sweepable::sweep_me()
{
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
if ((tv_now.tv_sec - _last_sweep)
> uc_configuration::_config->_sweep_cycle)
{
_last_sweep = tv_now.tv_sec;
return true;
}
else return false;
}
int uri_db_sweepable::sweep_records()
{
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
if (uc_configuration::_config->_retention > 0)
{
time_t sweep_date = tv_now.tv_sec - uc_configuration::_config->_retention;
return seeks_proxy::_user_db->prune_db("uri-capture",sweep_date);
}
return SP_ERR_OK;
}
/*- uri_capture -*/
uri_capture::uri_capture()
: plugin(),_nr(0)
{
_name = "uri-capture";
_version_major = "0";
_version_minor = "1";
_configuration = NULL;
if (seeks_proxy::_datadir.empty())
_config_filename = plugin_manager::_plugin_repository + "uri_capture/uri-capture-config";
else
_config_filename = seeks_proxy::_datadir + "/plugins/uri_capture/uri-capture-config";
#ifdef SEEKS_CONFIGDIR
struct stat stFileInfo;
if (!stat(_config_filename.c_str(), &stFileInfo) == 0)
{
_config_filename = SEEKS_CONFIGDIR "/uri-capture-config";
}
#endif
if (uc_configuration::_config == NULL)
uc_configuration::_config = new uc_configuration(_config_filename);
_configuration = uc_configuration::_config;
_interceptor_plugin = new uri_capture_element(this);
}
uri_capture::~uri_capture()
{
uc_configuration::_config = NULL; // configuration is deleted in parent class.
}
void uri_capture::start()
{
// check for user db.
if (!seeks_proxy::_user_db || !seeks_proxy::_user_db->_opened)
{
errlog::log_error(LOG_LEVEL_ERROR,"user db is not opened for URI capture plugin to work with it");
return;
}
else if (seeks_proxy::_config->_user_db_startup_check)
{
// preventive sweep of records.
static_cast<uri_capture_element*>(_interceptor_plugin)->_uds.sweep_records();
}
// get number of captured URI already in user_db.
_nr = seeks_proxy::_user_db->number_records(_name);
errlog::log_error(LOG_LEVEL_INFO,"uri_capture plugin: %u records",_nr);
}
void uri_capture::stop()
{
}
sp::db_record* uri_capture::create_db_record()
{
return new db_uri_record();
}
int uri_capture::remove_all_uri_records()
{
return seeks_proxy::_user_db->prune_db(_name);
}
uc_err uri_capture::fetch_uri_html_title(const std::vector<std::string> &uris,
std::vector<std::string> &titles,
const long &timeout,
const std::vector<std::list<const char*>*> *headers)
{
curl_mget cmg(uris.size(),timeout,0,timeout,0);
std::vector<int> status;
cmg.www_mget(uris,uris.size(),headers,"",0,status);
uc_err err = uri_capture::parse_uri_html_title(uris,titles,cmg._outputs);
delete[] cmg._outputs;
return err;
}
uc_err uri_capture::parse_uri_html_title(const std::vector<std::string> &uris,
std::vector<std::string> &titles,
std::string **outputs)
{
static std::string pattern_b = "<title>";
static std::string pattern_e = "</title>";
static std::list<const char*> cheaders; // empty, for charset conv.
size_t err = 0;
for (size_t i=0; i<uris.size(); i++)
{
std::string title;
if (outputs[i])
{
std::string *pageptr = outputs[i];
size_t pos_b = 0;
std::string::const_iterator sit = pageptr->begin();
if ((pos_b = miscutil::ci_find(*pageptr,pattern_b,sit))!=std::string::npos)
{
size_t pos_e = 0;
if ((pos_e = miscutil::ci_find(*pageptr,pattern_e,sit))!=std::string::npos)
{
title = pageptr->substr(pos_b+pattern_b.size(),pos_e-pos_b-pattern_e.size()+1);
}
}
delete outputs[i];
}
if (title.empty())
{
titles.push_back("");
errlog::log_error(LOG_LEVEL_ERROR,"Failed fetching or parsing title of uri %s",uris.at(i).c_str());
err++;
}
else if (title.find("404")!=std::string::npos)
{
titles.push_back("404");
}
else if (title.find("400")!=std::string::npos)
{
titles.push_back("");
}
else
{
title = encode::html_decode(miscutil::chomp_cpp(title));
miscutil::replace_in_string(title,"\n","");
miscutil::replace_in_string(title,"\r","");
std::string titlec = charset_conv::charset_check_and_conversion(title,cheaders);
if (titlec.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for title %s or uri %s",
title.c_str(),uris.at(i).c_str());
titles.push_back("");
}
else
{
errlog::log_error(LOG_LEVEL_DEBUG,"fetched title of uri %s\n%s",uris.at(i).c_str(),titlec.c_str());
titles.push_back(titlec);
}
}
}
if (err == uris.size())
return UC_ERR_CONNECT;
else return SP_ERR_OK;
}
/*- uri_capture_element -*/
std::string uri_capture_element::_capt_filename = "uri_capture/uri-patterns";
std::string uri_capture_element::_cgi_site_host = CGI_SITE_1_HOST;
uri_capture_element::uri_capture_element(plugin *parent)
: interceptor_plugin((seeks_proxy::_datadir.empty() ? std::string(plugin_manager::_plugin_repository
+ uri_capture_element::_capt_filename).c_str()
: std::string(seeks_proxy::_datadir + "/plugins/" + uri_capture_element::_capt_filename).c_str()),
parent)
{
if (seeks_proxy::_user_db && uc_configuration::_config->_sweep_cycle > 0)
seeks_proxy::_user_db->register_sweeper(&_uds);
}
uri_capture_element::~uri_capture_element()
{
}
http_response* uri_capture_element::plugin_response(client_state *csp)
{
// store domain names.
/* std::cerr << "[uri_capture]: headers:\n";
std::copy(csp->_headers.begin(),csp->_headers.end(),
std::ostream_iterator<const char*>(std::cout,"\n"));
std::cerr << std::endl; */
std::string host, referer, accept, get;
bool connect = false;
uri_capture_element::get_useful_headers(csp->_headers,
host,referer,
accept,get,connect);
/**
* URI domain name is stored in two cases:
* - there is no referer in the HTTP request headers.
* - the host domain is different than the referer, indicating a move
* to a different website.
*
* We do not record:
* - 'CONNECT' requests.
* - paths to images.
*/
std::string uri;
bool store = true;
if (connect)
{
store = false;
}
else if (store)
{
size_t p = accept.find("image");
if (p!=std::string::npos)
store = false;
else
{
p = miscutil::replace_in_string(get," HTTP/1.1","");
if (p == 0)
miscutil::replace_in_string(get," HTTP/1.0","");
}
}
host = uri_capture_element::prepare_uri(host);
std::transform(get.begin(),get.end(),get.begin(),tolower);
if (host == uri_capture_element::_cgi_site_host) // if proxy domain.
store = false;
if (store && referer.empty())
{
if (get != "/")
uri = host + get;
}
else if (store)
{
if (get != "/")
uri = host + get;
}
// check charset encoding.
if (store)
{
if (!uri.empty())
{
std::string uric = charset_conv::charset_check_and_conversion(uri,csp->_headers);
if (uric.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for URI %s",
uri.c_str());
store = false;
}
}
else if (!host.empty())
{
std::string hostc = charset_conv::charset_check_and_conversion(host,csp->_headers);
if (hostc.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for host %s",
host.c_str());
store = false;
}
}
}
if (store)
{
try
{
store_uri(uri,host);
}
catch (sp_exception &e)
{
errlog::log_error(LOG_LEVEL_ERROR,e.to_string().c_str());
}
}
return NULL; // no response, so the proxy does not crunch this HTTP request.
}
void uri_capture_element::store_uri(const std::string &uri, const std::string &host) const throw (sp_exception)
{
// add record to user db.
db_uri_record dbur(_parent->get_name());
if (!uri.empty())
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(uri,_parent->get_name());
db_err err = seeks_proxy::_user_db->add_dbr(uri,dbur);
if (err != SP_ERR_OK)
{
if (dbr)
delete dbr;
std::string msg = "failed storage of captured URI " + uri;
throw sp_exception(err,msg);
}
if (!dbr)
static_cast<uri_capture*>(_parent)->_nr++;
else delete dbr;
}
if (!host.empty() && uri != host)
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(host,_parent->get_name());
db_err err = seeks_proxy::_user_db->add_dbr(host,dbur);
if (err != SP_ERR_OK)
{
if (dbr)
delete dbr;
std::string msg = "failed storage of captured host " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
if (!dbr)
static_cast<uri_capture*>(_parent)->_nr++;
else delete dbr;
}
}
void uri_capture_element::remove_uri(const std::string &uri, const std::string &host) const throw (sp_exception)
{
int uri_hits = 1;
if (!uri.empty())
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(uri,_parent->get_name());
if (dbr)
{
uri_hits = static_cast<db_uri_record*>(dbr)->_hits;
delete dbr;
db_err err = seeks_proxy::_user_db->remove_dbr(uri,_parent->get_name());
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured URI " + uri;
throw sp_exception(err,msg);
}
static_cast<uri_capture*>(_parent)->_nr--;
}
}
if (!host.empty() && uri != host)
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(host,_parent->get_name());
if (dbr)
{
if (static_cast<db_uri_record*>(dbr)->_hits - uri_hits <= 0)
{
db_err err = seeks_proxy::_user_db->remove_dbr(host,_parent->get_name());
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured host " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
static_cast<uri_capture*>(_parent)->_nr--;
}
else
{
db_uri_record dbur(_parent->get_name(),-uri_hits);
db_err err = seeks_proxy::_user_db->add_dbr(host,dbur);
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured host hits " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
}
delete dbr;
}
}
}
std::string uri_capture_element::prepare_uri(const std::string &uri)
{
std::string prep_uri = urlmatch::strip_url(uri);
miscutil::to_lower(prep_uri);
return prep_uri;
}
void uri_capture_element::get_useful_headers(const std::list<const char*> &headers,
std::string &host, std::string &referer,
std::string &accept, std::string &get,
bool &connect)
{
std::list<const char*>::const_iterator lit = headers.begin();
while (lit!=headers.end())
{
if (miscutil::strncmpic((*lit),"get ",4) == 0)
{
get = (*lit);
get = get.substr(4);
}
else if (miscutil::strncmpic((*lit),"host:",5) == 0)
{
host = (*lit);
host = host.substr(6);
}
else if (miscutil::strncmpic((*lit),"referer:",8) == 0)
{
referer = (*lit);
referer = referer.substr(9);
}
else if (miscutil::strncmpic((*lit),"accept:",7) == 0)
{
accept = (*lit);
accept = accept.substr(8);
}
else if (miscutil::strncmpic((*lit),"connect ",8) == 0) // XXX: could grab GET and negate the test.
connect = true;
++lit;
}
}
/* auto-registration */
extern "C"
{
plugin* maker()
{
return new uri_capture;
}
}
} /* end of namespace. */
adding encode functions header
/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010-2011 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "uri_capture.h"
#include "uc_configuration.h"
#include "db_uri_record.h"
#include "seeks_proxy.h" // for user_db.
#include "proxy_configuration.h"
#include "user_db.h"
#include "proxy_dts.h"
#include "urlmatch.h"
#include "miscutil.h"
#include "charset_conv.h"
#include "curl_mget.h"
#include "encode.h"
#include "errlog.h"
#include <sys/time.h>
#include <sys/stat.h>
#include <algorithm>
#include <iterator>
#include <iostream>
using sp::seeks_proxy;
using sp::user_db;
using sp::db_record;
using sp::urlmatch;
using sp::miscutil;
using sp::charset_conv;
using sp::encode;
using sp::errlog;
namespace seeks_plugins
{
/*- uri_db_sweepable -*/
uri_db_sweepable::uri_db_sweepable()
:user_db_sweepable()
{
// set last sweep to now.
// sweeping is done when plugin starts.
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
_last_sweep = tv_now.tv_sec;
}
uri_db_sweepable::~uri_db_sweepable()
{
}
bool uri_db_sweepable::sweep_me()
{
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
if ((tv_now.tv_sec - _last_sweep)
> uc_configuration::_config->_sweep_cycle)
{
_last_sweep = tv_now.tv_sec;
return true;
}
else return false;
}
int uri_db_sweepable::sweep_records()
{
struct timeval tv_now;
gettimeofday(&tv_now,NULL);
if (uc_configuration::_config->_retention > 0)
{
time_t sweep_date = tv_now.tv_sec - uc_configuration::_config->_retention;
return seeks_proxy::_user_db->prune_db("uri-capture",sweep_date);
}
return SP_ERR_OK;
}
/*- uri_capture -*/
uri_capture::uri_capture()
: plugin(),_nr(0)
{
_name = "uri-capture";
_version_major = "0";
_version_minor = "1";
_configuration = NULL;
if (seeks_proxy::_datadir.empty())
_config_filename = plugin_manager::_plugin_repository + "uri_capture/uri-capture-config";
else
_config_filename = seeks_proxy::_datadir + "/plugins/uri_capture/uri-capture-config";
#ifdef SEEKS_CONFIGDIR
struct stat stFileInfo;
if (!stat(_config_filename.c_str(), &stFileInfo) == 0)
{
_config_filename = SEEKS_CONFIGDIR "/uri-capture-config";
}
#endif
if (uc_configuration::_config == NULL)
uc_configuration::_config = new uc_configuration(_config_filename);
_configuration = uc_configuration::_config;
_interceptor_plugin = new uri_capture_element(this);
}
uri_capture::~uri_capture()
{
uc_configuration::_config = NULL; // configuration is deleted in parent class.
}
void uri_capture::start()
{
// check for user db.
if (!seeks_proxy::_user_db || !seeks_proxy::_user_db->_opened)
{
errlog::log_error(LOG_LEVEL_ERROR,"user db is not opened for URI capture plugin to work with it");
return;
}
else if (seeks_proxy::_config->_user_db_startup_check)
{
// preventive sweep of records.
static_cast<uri_capture_element*>(_interceptor_plugin)->_uds.sweep_records();
}
// get number of captured URI already in user_db.
_nr = seeks_proxy::_user_db->number_records(_name);
errlog::log_error(LOG_LEVEL_INFO,"uri_capture plugin: %u records",_nr);
}
void uri_capture::stop()
{
}
sp::db_record* uri_capture::create_db_record()
{
return new db_uri_record();
}
int uri_capture::remove_all_uri_records()
{
return seeks_proxy::_user_db->prune_db(_name);
}
uc_err uri_capture::fetch_uri_html_title(const std::vector<std::string> &uris,
std::vector<std::string> &titles,
const long &timeout,
const std::vector<std::list<const char*>*> *headers)
{
curl_mget cmg(uris.size(),timeout,0,timeout,0);
std::vector<int> status;
cmg.www_mget(uris,uris.size(),headers,"",0,status);
uc_err err = uri_capture::parse_uri_html_title(uris,titles,cmg._outputs);
delete[] cmg._outputs;
return err;
}
uc_err uri_capture::parse_uri_html_title(const std::vector<std::string> &uris,
std::vector<std::string> &titles,
std::string **outputs)
{
static std::string pattern_b = "<title>";
static std::string pattern_e = "</title>";
static std::list<const char*> cheaders; // empty, for charset conv.
size_t err = 0;
for (size_t i=0; i<uris.size(); i++)
{
std::string title;
if (outputs[i])
{
std::string *pageptr = outputs[i];
size_t pos_b = 0;
std::string::const_iterator sit = pageptr->begin();
if ((pos_b = miscutil::ci_find(*pageptr,pattern_b,sit))!=std::string::npos)
{
size_t pos_e = 0;
if ((pos_e = miscutil::ci_find(*pageptr,pattern_e,sit))!=std::string::npos)
{
title = pageptr->substr(pos_b+pattern_b.size(),pos_e-pos_b-pattern_e.size()+1);
}
}
delete outputs[i];
}
if (title.empty())
{
titles.push_back("");
errlog::log_error(LOG_LEVEL_ERROR,"Failed fetching or parsing title of uri %s",uris.at(i).c_str());
err++;
}
else if (title.find("404")!=std::string::npos)
{
titles.push_back("404");
}
else if (title.find("400")!=std::string::npos)
{
titles.push_back("");
}
else
{
title = encode::html_decode(miscutil::chomp_cpp(title));
miscutil::replace_in_string(title,"\n","");
miscutil::replace_in_string(title,"\r","");
std::string titlec = charset_conv::charset_check_and_conversion(title,cheaders);
if (titlec.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for title %s or uri %s",
title.c_str(),uris.at(i).c_str());
titles.push_back("");
}
else
{
errlog::log_error(LOG_LEVEL_DEBUG,"fetched title of uri %s\n%s",uris.at(i).c_str(),titlec.c_str());
titles.push_back(titlec);
}
}
}
if (err == uris.size())
return UC_ERR_CONNECT;
else return SP_ERR_OK;
}
/*- uri_capture_element -*/
std::string uri_capture_element::_capt_filename = "uri_capture/uri-patterns";
std::string uri_capture_element::_cgi_site_host = CGI_SITE_1_HOST;
uri_capture_element::uri_capture_element(plugin *parent)
: interceptor_plugin((seeks_proxy::_datadir.empty() ? std::string(plugin_manager::_plugin_repository
+ uri_capture_element::_capt_filename).c_str()
: std::string(seeks_proxy::_datadir + "/plugins/" + uri_capture_element::_capt_filename).c_str()),
parent)
{
if (seeks_proxy::_user_db && uc_configuration::_config->_sweep_cycle > 0)
seeks_proxy::_user_db->register_sweeper(&_uds);
}
uri_capture_element::~uri_capture_element()
{
}
http_response* uri_capture_element::plugin_response(client_state *csp)
{
// store domain names.
/* std::cerr << "[uri_capture]: headers:\n";
std::copy(csp->_headers.begin(),csp->_headers.end(),
std::ostream_iterator<const char*>(std::cout,"\n"));
std::cerr << std::endl; */
std::string host, referer, accept, get;
bool connect = false;
uri_capture_element::get_useful_headers(csp->_headers,
host,referer,
accept,get,connect);
/**
* URI domain name is stored in two cases:
* - there is no referer in the HTTP request headers.
* - the host domain is different than the referer, indicating a move
* to a different website.
*
* We do not record:
* - 'CONNECT' requests.
* - paths to images.
*/
std::string uri;
bool store = true;
if (connect)
{
store = false;
}
else if (store)
{
size_t p = accept.find("image");
if (p!=std::string::npos)
store = false;
else
{
p = miscutil::replace_in_string(get," HTTP/1.1","");
if (p == 0)
miscutil::replace_in_string(get," HTTP/1.0","");
}
}
host = uri_capture_element::prepare_uri(host);
std::transform(get.begin(),get.end(),get.begin(),tolower);
if (host == uri_capture_element::_cgi_site_host) // if proxy domain.
store = false;
if (store && referer.empty())
{
if (get != "/")
uri = host + get;
}
else if (store)
{
if (get != "/")
uri = host + get;
}
// check charset encoding.
if (store)
{
if (!uri.empty())
{
std::string uric = charset_conv::charset_check_and_conversion(uri,csp->_headers);
if (uric.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for URI %s",
uri.c_str());
store = false;
}
}
else if (!host.empty())
{
std::string hostc = charset_conv::charset_check_and_conversion(host,csp->_headers);
if (hostc.empty())
{
errlog::log_error(LOG_LEVEL_ERROR,"bad charset encoding for host %s",
host.c_str());
store = false;
}
}
}
if (store)
{
try
{
store_uri(uri,host);
}
catch (sp_exception &e)
{
errlog::log_error(LOG_LEVEL_ERROR,e.to_string().c_str());
}
}
return NULL; // no response, so the proxy does not crunch this HTTP request.
}
void uri_capture_element::store_uri(const std::string &uri, const std::string &host) const throw (sp_exception)
{
// add record to user db.
db_uri_record dbur(_parent->get_name());
if (!uri.empty())
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(uri,_parent->get_name());
db_err err = seeks_proxy::_user_db->add_dbr(uri,dbur);
if (err != SP_ERR_OK)
{
if (dbr)
delete dbr;
std::string msg = "failed storage of captured URI " + uri;
throw sp_exception(err,msg);
}
if (!dbr)
static_cast<uri_capture*>(_parent)->_nr++;
else delete dbr;
}
if (!host.empty() && uri != host)
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(host,_parent->get_name());
db_err err = seeks_proxy::_user_db->add_dbr(host,dbur);
if (err != SP_ERR_OK)
{
if (dbr)
delete dbr;
std::string msg = "failed storage of captured host " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
if (!dbr)
static_cast<uri_capture*>(_parent)->_nr++;
else delete dbr;
}
}
void uri_capture_element::remove_uri(const std::string &uri, const std::string &host) const throw (sp_exception)
{
int uri_hits = 1;
if (!uri.empty())
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(uri,_parent->get_name());
if (dbr)
{
uri_hits = static_cast<db_uri_record*>(dbr)->_hits;
delete dbr;
db_err err = seeks_proxy::_user_db->remove_dbr(uri,_parent->get_name());
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured URI " + uri;
throw sp_exception(err,msg);
}
static_cast<uri_capture*>(_parent)->_nr--;
}
}
if (!host.empty() && uri != host)
{
db_record *dbr = seeks_proxy::_user_db->find_dbr(host,_parent->get_name());
if (dbr)
{
if (static_cast<db_uri_record*>(dbr)->_hits - uri_hits <= 0)
{
db_err err = seeks_proxy::_user_db->remove_dbr(host,_parent->get_name());
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured host " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
static_cast<uri_capture*>(_parent)->_nr--;
}
else
{
db_uri_record dbur(_parent->get_name(),-uri_hits);
db_err err = seeks_proxy::_user_db->add_dbr(host,dbur);
if (err != SP_ERR_OK)
{
std::string msg = "failed removal of captured host hits " + host + " for URI " + uri;
throw sp_exception(err,msg);
}
}
delete dbr;
}
}
}
std::string uri_capture_element::prepare_uri(const std::string &uri)
{
std::string prep_uri = urlmatch::strip_url(uri);
miscutil::to_lower(prep_uri);
return prep_uri;
}
void uri_capture_element::get_useful_headers(const std::list<const char*> &headers,
std::string &host, std::string &referer,
std::string &accept, std::string &get,
bool &connect)
{
std::list<const char*>::const_iterator lit = headers.begin();
while (lit!=headers.end())
{
if (miscutil::strncmpic((*lit),"get ",4) == 0)
{
get = (*lit);
get = get.substr(4);
}
else if (miscutil::strncmpic((*lit),"host:",5) == 0)
{
host = (*lit);
host = host.substr(6);
}
else if (miscutil::strncmpic((*lit),"referer:",8) == 0)
{
referer = (*lit);
referer = referer.substr(9);
}
else if (miscutil::strncmpic((*lit),"accept:",7) == 0)
{
accept = (*lit);
accept = accept.substr(8);
}
else if (miscutil::strncmpic((*lit),"connect ",8) == 0) // XXX: could grab GET and negate the test.
connect = true;
++lit;
}
}
/* auto-registration */
extern "C"
{
plugin* maker()
{
return new uri_capture;
}
}
} /* end of namespace. */
|
#include "helpers/MovementGenerator.hpp"
#include "../src/controller/Controller.hpp"
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Start profile_control" << std::endl;
/*
* TODO: needs to be initialized
* Controller instead of DummyPositionReceiver
*/
Controller *receiver = new Controller();
std::vector<Vector> from;
std::vector<Vector> to;
from.push_back(Vector(0, 0, 0));
to.push_back(Vector(1, 1, 1));
from.push_back(Vector(0, 0, 1));
to.push_back(Vector(1, 1, 2));
from.push_back(Vector(0, 1, 0));
to.push_back(Vector(1, 2, 1));
from.push_back(Vector(1, 0, 0));
to.push_back(Vector(2, 1, 1));
from.push_back(Vector(1, 1, 1));
to.push_back(Vector(2, 2, 2));
// See MovementGenerator.hpp
MovementGenerator generator(receiver, from, to, 0.05, 0.1, 0.01, 150, 30);
generator.run();
}
a start - once again
#include "helpers/MovementGenerator.hpp"
#include "../src/controller/Controller.hpp"
#include <iostream>
int main(int argc, char** argv) {
ros::init(argc, argv, "profile_control_node");
std::cout << "Start profile_control" << std::endl;
/*
* TODO: needs to be initialized
* Controller instead of DummyPositionReceiver
*/
Controller *receiver = new Controller();
std::vector<Vector> from;
std::vector<Vector> to;
from.push_back(Vector(0, 0, 0));
to.push_back(Vector(1, 1, 1));
from.push_back(Vector(0, 0, 1));
to.push_back(Vector(1, 1, 2));
from.push_back(Vector(0, 1, 0));
to.push_back(Vector(1, 2, 1));
from.push_back(Vector(1, 0, 0));
to.push_back(Vector(2, 1, 1));
from.push_back(Vector(1, 1, 1));
to.push_back(Vector(2, 2, 2));
ros::spin();
// See MovementGenerator.hpp
MovementGenerator generator(receiver, from, to, 0.05, 0.1, 0.01, 150, 30);
generator.run();
} |
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <fstream>
#include <math.h>
#include "SubImageRecognition/ImgRecAlgorithm.h"
#include "SubImageRecognition/ImgRecObject.h"
#include "SubImageRecognition/ImgRecThreshold.h"
#include "SubImageRecognition/ListAlgorithms.h"
#include "SubImageRecognition/UpdateAlgorithm.h"
#include "SubImageRecognition/SwitchAlgorithm.h"
#include "DLT.h"
using namespace cv;
using namespace std;
// CONSTANTS
const int SAMPLE_SIZE = 4;
const unsigned int MIN_POINTS = 75;
const float MIN_CONFIDENCE = 0.5;
const char NAMESPACE_ROOT[] = "img_rec/";
const int FLAG_ENABLED = 1;
const int FLAG_PUBLISH_THRESHOLD = 2;
const int CAMERA_FORWARD = 0;
const int CAMERA_DOWNWARD = 1;
const int ANALYSIS_RECTANGLE = 0;
const int CONFIDENCE_RECTANGLE = 0;
const int CONFIDENCE_CIRCLE = 1;
const int ANNOTATION_ROTATION = 0;
const int ANNOTATION_RADIUS = 1;
const int FRAME_MARGIN_OF_ERROR=3;
const int TRACKING_MOVEMENT_TOLERANCE=300;
// DEFINITIONS
typedef vector<Point> Points;
class Object {
public:
string name;
int flags;
int camera;
int analysisType;
int maxBlobs;
int confidenceType;
Scalar annotationColor;
int annotationType;
int enumType;
ros::Publisher publisher;
Object(string name, int flags, int camera, int analysisType, int maxBlobs, int confidenceType, Scalar annotationColor, int annotationType, int enumType):
name(name)
,flags(flags)
,camera(camera)
,analysisType(analysisType)
,maxBlobs(maxBlobs)
,confidenceType(confidenceType)
,annotationColor(annotationColor)
,annotationType(annotationType)
,enumType(enumType)
{
ros::NodeHandle nodeHandle;
string topic(NAMESPACE_ROOT);
topic += name;
publisher = nodeHandle.advertise<SubImageRecognition::ImgRecObject>(topic, 1);
};
};
class BlobAnalysis {
public:
int center_x;
int center_y;
float rotation;
unsigned int width;
unsigned int height;
unsigned int size;
BlobAnalysis() {}
// Constructor for use with ANALYSIS_RECTANGLE
BlobAnalysis(Points& blob, RotatedRect rectangle) {
center_x = (int) rectangle.center.x;
center_y = (int) rectangle.center.y;
rotation = rectangle.angle;
width = (unsigned int) rectangle.size.width;
height = (unsigned int) rectangle.size.height;
size = blob.size();
// Convert rotation from degrees to radians
rotation *= M_PI / 180.0;
// Correct dimensions and rotation so that height is always larger
if (height < width) {
unsigned int temp = height;
height = width;
width = temp;
} else {
rotation -= M_PI / 2.0;
}
}
};
class BlobTrack
{
public:
int x;
int y;
int lifetime;
int lastSeen;
int objType;
BlobTrack(int x, int y, int lastSeen, int objType):
x(x)
,y(y)
,lastSeen(lastSeen)
,objType(objType)
,lifetime(0)
{
}
};
// GLOBALS :/ HA HA AH WELL
vector<Object> objects;
vector<BlobTrack> trackBlobs;
int curFrame=0;
int forwardOffset = 0, downwardOffset = 0;
image_transport::Publisher forwardPublisher, downwardPublisher, forwardThresh, downwardThresh;
cv_bridge::CvImage forwardRotated, downwardRotated;
Mat forwardSegmented, downwardSegmented;
Mat forwardThreshold, downwardThreshold;
DLT* pTree;
int lastAvgHue=0, lastAvgSat=0, lastAvgBright=0;
// FUNCTIONS
//Need to add enumTypes to Objects
void initObjects() {
objects.push_back(Object(
"gate",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
2,
CONFIDENCE_RECTANGLE,
Scalar(0, 128, 255), // Orange
ANNOTATION_ROTATION,
1
));
objects.push_back(Object(
"buoys/red",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
1,
CONFIDENCE_CIRCLE,
Scalar(0, 0, 255), // Red
ANNOTATION_RADIUS,
2
));
// objects.push_back(Object(
// "buoys/green",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_CIRCLE,
// Scalar(0, 255, 0), // Green
// ANNOTATION_RADIUS,
// 3
// ));
// objects.push_back(Object(
// "buoys/yellow",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_CIRCLE,
// Scalar(0, 255, 255), // Yellow
// ANNOTATION_RADIUS,
// 4
// ));
objects.push_back(Object(
"paths",
1,
CAMERA_DOWNWARD,
ANALYSIS_RECTANGLE,
2,
CONFIDENCE_RECTANGLE,
Scalar(0, 128, 255), // Orange
ANNOTATION_ROTATION,
3
));
objects.push_back(Object(
"driving",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
3,
CONFIDENCE_RECTANGLE,
Scalar(255, 0, 0), // Blue
ANNOTATION_ROTATION,
4
));
// objects.push_back(Object(
// "red led buoy",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_RECTANGLE,
// Scalar(255, 0, 0), // Blue
// ANNOTATION_ROTATION,
// 7
// ));
}
/*void normalizeValue(Mat& image, Mat& temp) {
const static int valueOut[] = {2, 0};
const static int valueIn[] = {0, 2};
temp.create(image.rows, image.cols, CV_8UC1);
mixChannels(&image, 1, &temp, 1, valueOut, 1);
normalize(temp, temp, 0, 255, CV_MINMAX);
mixChannels(&temp, 1, &image, 1, valueIn, 1);
}*/
void reduceNoise(Mat& image) {
const static Size size(3, 3);
const static Point point(1, 1);
const static Mat elementRect = getStructuringElement(
MORPH_RECT, size, point);
erode(image, image, elementRect, point, 5);
dilate(image, image, elementRect, point, 2);
}
Points findBlob(Mat& image, int i, int j, int obj) {
unsigned int index = 0;
Points blob;
Point point(j, i);
blob.push_back(point);
image.at<uint8_t>(i, j, 0) = 0;
while (index < blob.size()) {
point = blob[index];
i = point.y;
j = point.x;
if (i+SAMPLE_SIZE < image.rows
&& image.at<uint8_t>(i+SAMPLE_SIZE, j, 0) == obj) {
blob.push_back(Point(j, i+SAMPLE_SIZE));
image.at<uint8_t>(i+SAMPLE_SIZE, j, 0) = 0;
}
if (i-SAMPLE_SIZE >= 0
&& image.at<uint8_t>(i-SAMPLE_SIZE, j, 0) == obj) {
blob.push_back(Point(j, i-SAMPLE_SIZE));
image.at<uint8_t>(i-SAMPLE_SIZE, j, 0) = 0;
}
if (j+SAMPLE_SIZE < image.cols
&& image.at<uint8_t>(i, j+SAMPLE_SIZE, 0) == obj) {
blob.push_back(Point(j+SAMPLE_SIZE, i));
image.at<uint8_t>(i, j+SAMPLE_SIZE, 0) = 0;
}
if (j-SAMPLE_SIZE >= 0 &&
image.at<uint8_t>(i, j-SAMPLE_SIZE, 0) == obj) {
blob.push_back(Point(j-SAMPLE_SIZE, i));
image.at<uint8_t>(i, j-SAMPLE_SIZE, 0) = 0;
}
index++;
}
return blob;
}
bool compareBlobs(Points& blob0, Points& blob1) {
return blob0.size() < blob1.size();
}
vector<Points> findBlobs(Mat& image,
const int offset, const unsigned int maxBlobs, int obj) {
// First get all blobs that are at least the minimum size
vector<Points> allBlobs;
for (int i = offset; i < image.rows; i += SAMPLE_SIZE) {
for (int j = offset; j < image.cols; j += SAMPLE_SIZE) {
if ((int)image.at<uint8_t>(i, j, 0) == obj) {
Points blob = findBlob(image, i, j, obj);
if (blob.size() >= MIN_POINTS) {
allBlobs.push_back(blob);
}
}
}
}
// Stop now if there are 'maxBlobs' or fewer blobs
if (allBlobs.size() <= maxBlobs) {
return allBlobs;
}
// Otherwise limit to the biggest 'maxBlobs' blobs
make_heap(allBlobs.begin(), allBlobs.end(), compareBlobs);
vector<Points> blobs = vector<Points>();
blobs.push_back(allBlobs.front());
for (unsigned int i = 1; i < maxBlobs && allBlobs.size() > 1; i++) {
pop_heap(allBlobs.begin(), allBlobs.end(), compareBlobs);
blobs.push_back(allBlobs.front());
}
return blobs;
}
vector<BlobAnalysis> analyzeBlob(Object& object,
Points& blob, Mat& image) {
vector<BlobAnalysis> analysisList;
RotatedRect rectangle;
switch (object.analysisType) {
case ANALYSIS_RECTANGLE:
analysisList.push_back(BlobAnalysis(blob, minAreaRect(Mat(blob))));
break;
}
return analysisList;
}
float computeConfidence(Object& object, BlobAnalysis& a) {
// A return value of -1 indicates 'divide by zero' error
// A return value of -2 indicates 'unknown confidence type' error
int expectedPoints;
switch (object.confidenceType) {
case CONFIDENCE_RECTANGLE:
expectedPoints = (a.width * a.height) / (SAMPLE_SIZE * SAMPLE_SIZE);
break;
case CONFIDENCE_CIRCLE:
expectedPoints =
(M_PI * a.width * a.height) / (4 * SAMPLE_SIZE * SAMPLE_SIZE);
break;
default:
return -2; // Unknown confidence type
}
if (expectedPoints <= 0) {
return -1; // Divide by zero
} else {
float confidence = ((float) a.size) / ((float) expectedPoints);
if (confidence > 1) {
return 1;
} else {
return confidence;
}
}
}
void annotateImage(Mat& image, Object& object, BlobAnalysis& a) {
int r, x, y;
switch (object.annotationType) {
case ANNOTATION_ROTATION:
x = (int) (a.height / 2.0 * cos(a.rotation));
y = (int) (a.height / 2.0 * sin(a.rotation));
circle(image, Point(a.center_x, a.center_y), 1,
object.annotationColor, 5, CV_AA);
line(image, Point(a.center_x, a.center_y),
Point(a.center_x + x, a.center_y + y),
object.annotationColor, 1, CV_AA);
break;
case ANNOTATION_RADIUS:
r = (int) ((a.width + a.height) / 4.0);
circle(image, Point(a.center_x, a.center_y), r,
object.annotationColor, 2, CV_AA);
break;
}
}
//assuming i=y and j=x
void objInRange(const Mat& segmented, Mat& threshold, const int offset)
{ int count=0, hue=0, sat=0, bright=0;
if (threshold.total() == 0) {
threshold.create(segmented.rows, segmented.cols, CV_8U);
}
for (int i = offset; i < threshold.rows; i += SAMPLE_SIZE) {
for (int j = offset; j < threshold.cols; j += SAMPLE_SIZE) {
Sample sample;
Vec3b hsv = segmented.at<cv::Vec3b>(i, j);
sample.type=0;
sample.iAttr[0]=lastAvgHue;
sample.iAttr[1]=lastAvgSat;
sample.iAttr[2]=lastAvgBright;
sample.iAttr[3]=hsv[0];
sample.iAttr[4]=hsv[1];
sample.iAttr[5]=hsv[2];
hue+=hsv[0];
sat+=hsv[1];
bright+=hsv[2];
++count;
int temp=pTree->Classify(sample);
threshold.at<uint8_t>(i,j,0)=(temp ? (temp*30+123) : 0);
}
}
lastAvgHue=hue/count;
lastAvgSat=sat/count;
lastAvgBright=bright/count;
}
bool inCircle(BlobAnalysis analysis, BlobTrack track)
{
int deltaX=analysis.center_x-track.x;
int deltaY=analysis.center_y-track.y;
return (sqrt((float)deltaX * deltaX + deltaY * deltaY)) <= TRACKING_MOVEMENT_TOLERANCE;
}
bool trackBlob(BlobAnalysis analysis, int type)
{
for(int i=0;i<trackBlobs.size();++i)
{
if(type==trackBlobs[i].objType)
{
if(inCircle(analysis, trackBlobs[i]))
{
trackBlobs[i].x=analysis.center_x;
trackBlobs[i].y=analysis.center_y;
trackBlobs[i].lastSeen=curFrame;
++trackBlobs[i].lifetime;
return FRAME_MARGIN_OF_ERROR>=trackBlobs[i].lifetime;
}
}
}
trackBlobs.push_back(BlobTrack(analysis.center_x, analysis.center_y, curFrame, type));
return false;
}
void updateBlobTracking()
{
for(int i=0;i<trackBlobs.size();++i)
{
if(trackBlobs[i].lastSeen < (curFrame - FRAME_MARGIN_OF_ERROR))
{
trackBlobs.erase(trackBlobs.begin()+i);
--i;
}
}
++curFrame;
}
void genericCallback(
const int camera,
const sensor_msgs::ImageConstPtr& rosImage,
cv_bridge::CvImage& rotated,
Mat& segmented,
Mat& threshold,
const int offset,
const image_transport::Publisher& publisher,
const image_transport::Publisher& threshPublisher) {
// Copy image from ROS format to OpenCV format
cv_bridge::CvImageConstPtr cvImage = cv_bridge::toCvShare(rosImage, "bgr8");
// Rotate image upright
//TODO: find a better way to stop forward camera rotation
if (camera == CAMERA_DOWNWARD) {
transpose(cvImage->image, rotated.image);
flip(rotated.image, rotated.image, 0); // 0=ccw, 1=cw
rotated.encoding = cvImage->encoding;
}
else{
rotated = *cvImage;
}
// Segment into HSV
cvtColor(rotated.image, segmented, CV_BGR2HSV);
// Normalize brightness and copy back to BGR
//normalizeValue(segmented, threshold);
//cvtColor(segmented, rotated.image, CV_HSV2BGR);
// Iterate through all objects
objInRange(segmented, threshold, offset);
for (unsigned int i = 0; i < objects.size(); i++) {
Object object = objects[i];
// Run applicable algorithms
if ((object.flags & FLAG_ENABLED) && object.camera == camera) {
//reduceNoise(threshold);
if (true) {
cv_bridge::CvImage temp;
temp.encoding = "mono8";
temp.image = threshold;
threshPublisher.publish(temp.toImageMsg());
}
int tempenum=object.enumType;
vector<Points> blobs = findBlobs(
threshold, offset, object.maxBlobs, (tempenum ? (tempenum*30+123) : 0));
// Iterate through all blobs
for (unsigned int j = 0; j < blobs.size(); j++) {
vector<BlobAnalysis> analysisList =
analyzeBlob(object, blobs[j], rotated.image);
// Iterate through all blob analysis objects
ros::Time time = ros::Time::now();
for (unsigned int k = 0; k < analysisList.size(); k++) {
BlobAnalysis analysis = analysisList[k];
// if (trackBlob(analysis, object.enumType))
if(true)
{
// Publish information
SubImageRecognition::ImgRecObject msg;
msg.stamp = time;
msg.id = k;
msg.center_x = analysis.center_x - rotated.image.cols / 2;
msg.center_y = rotated.image.rows / 2 - analysis.center_y;
msg.rotation = (analysis.rotation + M_PI / 2.0) * 180.0 / M_PI;
msg.width = analysis.width;
msg.height = analysis.height;
msg.confidence = computeConfidence(object, analysis);
object.publisher.publish(msg);
// Annotate image
annotateImage(rotated.image, object, analysis);
}
}
}
// cout<<"Blobs: "<<blobs.size()<<" Tracks: "<<trackBlobs.size()<<endl;
}
}
// Publish annotated image
publisher.publish(rotated.toImageMsg());
updateBlobTracking();
}
void forwardCallback(const sensor_msgs::ImageConstPtr& rosImage) {
genericCallback(CAMERA_FORWARD, rosImage, forwardRotated, forwardSegmented,
forwardThreshold, forwardOffset, forwardPublisher, forwardThresh);
forwardOffset = (forwardOffset + 1) % SAMPLE_SIZE;
}
void downwardCallback(const sensor_msgs::ImageConstPtr& rosImage) {
genericCallback(CAMERA_DOWNWARD, rosImage, downwardRotated, downwardSegmented,
downwardThreshold, downwardOffset, downwardPublisher, downwardThresh);
downwardOffset = (downwardOffset + 1) % SAMPLE_SIZE;
}
int main(int argc, char **argv) {
fstream file("/opt/robosub/rosWorkspace/SubImageRecognition/tree.tree");
pTree = new DLT(file);
ros::init(argc, argv, "ImageRecognition");
ros::NodeHandle nodeHandle;
image_transport::ImageTransport imageTransport(nodeHandle);
forwardPublisher = imageTransport.advertise("forward_camera/image_raw", 1);
downwardPublisher = imageTransport.advertise("downward_camera/image_raw", 1);
forwardThresh = imageTransport.advertise("forward_camera/threshold", 1);
downwardThresh = imageTransport.advertise("downward_camera/threshold", 1);
image_transport::Subscriber forwardSubscriber = imageTransport.subscribe("/stereo/left/image_raw", 1, forwardCallback);
image_transport::Subscriber downwardSubscriber = imageTransport.subscribe("image_raw", 1, downwardCallback);
initObjects();
ros::spin();
return 0;
}
Thresholding in technicolor
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <fstream>
#include <math.h>
#include "SubImageRecognition/ImgRecAlgorithm.h"
#include "SubImageRecognition/ImgRecObject.h"
#include "SubImageRecognition/ImgRecThreshold.h"
#include "SubImageRecognition/ListAlgorithms.h"
#include "SubImageRecognition/UpdateAlgorithm.h"
#include "SubImageRecognition/SwitchAlgorithm.h"
#include "DLT.h"
using namespace cv;
using namespace std;
// CONSTANTS
const int SAMPLE_SIZE = 4;
const unsigned int MIN_POINTS = 75;
const float MIN_CONFIDENCE = 0.5;
const char NAMESPACE_ROOT[] = "img_rec/";
const int FLAG_ENABLED = 1;
const int FLAG_PUBLISH_THRESHOLD = 2;
const int CAMERA_FORWARD = 0;
const int CAMERA_DOWNWARD = 1;
const int ANALYSIS_RECTANGLE = 0;
const int CONFIDENCE_RECTANGLE = 0;
const int CONFIDENCE_CIRCLE = 1;
const int ANNOTATION_ROTATION = 0;
const int ANNOTATION_RADIUS = 1;
const int FRAME_MARGIN_OF_ERROR=3;
const int TRACKING_MOVEMENT_TOLERANCE=300;
// DEFINITIONS
typedef vector<Point> Points;
class Object {
public:
string name;
int flags;
int camera;
int analysisType;
int maxBlobs;
int confidenceType;
Scalar annotationColor;
int annotationType;
int enumType;
ros::Publisher publisher;
Object(string name, int flags, int camera, int analysisType, int maxBlobs, int confidenceType, Scalar annotationColor, int annotationType, int enumType):
name(name)
,flags(flags)
,camera(camera)
,analysisType(analysisType)
,maxBlobs(maxBlobs)
,confidenceType(confidenceType)
,annotationColor(annotationColor)
,annotationType(annotationType)
,enumType(enumType)
{
ros::NodeHandle nodeHandle;
string topic(NAMESPACE_ROOT);
topic += name;
publisher = nodeHandle.advertise<SubImageRecognition::ImgRecObject>(topic, 1);
};
};
class BlobAnalysis {
public:
int center_x;
int center_y;
float rotation;
unsigned int width;
unsigned int height;
unsigned int size;
BlobAnalysis() {}
// Constructor for use with ANALYSIS_RECTANGLE
BlobAnalysis(Points& blob, RotatedRect rectangle) {
center_x = (int) rectangle.center.x;
center_y = (int) rectangle.center.y;
rotation = rectangle.angle;
width = (unsigned int) rectangle.size.width;
height = (unsigned int) rectangle.size.height;
size = blob.size();
// Convert rotation from degrees to radians
rotation *= M_PI / 180.0;
// Correct dimensions and rotation so that height is always larger
if (height < width) {
unsigned int temp = height;
height = width;
width = temp;
} else {
rotation -= M_PI / 2.0;
}
}
};
class BlobTrack
{
public:
int x;
int y;
int lifetime;
int lastSeen;
int objType;
BlobTrack(int x, int y, int lastSeen, int objType):
x(x)
,y(y)
,lastSeen(lastSeen)
,objType(objType)
,lifetime(0)
{
}
};
// GLOBALS :/ HA HA AH WELL
vector<Object> objects;
vector<BlobTrack> trackBlobs;
int curFrame=0;
int forwardOffset = 0, downwardOffset = 0;
image_transport::Publisher forwardPublisher, downwardPublisher, forwardThresh, downwardThresh;
cv_bridge::CvImage forwardRotated, downwardRotated;
Mat forwardSegmented, downwardSegmented;
Mat forwardThreshold, downwardThreshold;
DLT* pTree;
int lastAvgHue=0, lastAvgSat=0, lastAvgBright=0;
// FUNCTIONS
//Need to add enumTypes to Objects
void initObjects() {
objects.push_back(Object(
"gate",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
2,
CONFIDENCE_RECTANGLE,
Scalar(0, 255, 0), // Green
ANNOTATION_ROTATION,
1
));
objects.push_back(Object(
"buoys/red",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
1,
CONFIDENCE_CIRCLE,
Scalar(0, 0, 255), // Red
ANNOTATION_RADIUS,
2
));
// objects.push_back(Object(
// "buoys/green",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_CIRCLE,
// Scalar(0, 255, 0), // Green
// ANNOTATION_RADIUS,
// 3
// ));
// objects.push_back(Object(
// "buoys/yellow",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_CIRCLE,
// Scalar(0, 255, 255), // Yellow
// ANNOTATION_RADIUS,
// 4
// ));
objects.push_back(Object(
"paths",
1,
CAMERA_DOWNWARD,
ANALYSIS_RECTANGLE,
2,
CONFIDENCE_RECTANGLE,
Scalar(0, 128, 255), // Orange
ANNOTATION_ROTATION,
3
));
objects.push_back(Object(
"driving",
1,
CAMERA_FORWARD,
ANALYSIS_RECTANGLE,
3,
CONFIDENCE_RECTANGLE,
Scalar(255, 0, 0), // Blue
ANNOTATION_ROTATION,
4
));
// objects.push_back(Object(
// "red led buoy",
// 1,
// CAMERA_FORWARD,
// ANALYSIS_RECTANGLE,
// 1,
// CONFIDENCE_RECTANGLE,
// Scalar(255, 0, 0), // Blue
// ANNOTATION_ROTATION,
// 7
// ));
}
/*void normalizeValue(Mat& image, Mat& temp) {
const static int valueOut[] = {2, 0};
const static int valueIn[] = {0, 2};
temp.create(image.rows, image.cols, CV_8UC1);
mixChannels(&image, 1, &temp, 1, valueOut, 1);
normalize(temp, temp, 0, 255, CV_MINMAX);
mixChannels(&temp, 1, &image, 1, valueIn, 1);
}*/
void reduceNoise(Mat& image) {
const static Size size(3, 3);
const static Point point(1, 1);
const static Mat elementRect = getStructuringElement(
MORPH_RECT, size, point);
erode(image, image, elementRect, point, 5);
dilate(image, image, elementRect, point, 2);
}
Points findBlob(Mat& image, int i, int j, Scalar obj) {
unsigned int index = 0;
Points blob;
Point point(j, i);
blob.push_back(point);
image.at<Scalar>(i, j) = Scalar(0,0,0);
while (index < blob.size()) {
point = blob[index];
i = point.y;
j = point.x;
if (i+SAMPLE_SIZE < image.rows
&& image.at<Scalar>(i+SAMPLE_SIZE, j) == obj) {
blob.push_back(Point(j, i+SAMPLE_SIZE));
image.at<Scalar>(i+SAMPLE_SIZE, j) = Scalar(0,0,0);
}
if (i-SAMPLE_SIZE >= 0
&& image.at<Scalar>(i-SAMPLE_SIZE, j) == obj) {
blob.push_back(Point(j, i-SAMPLE_SIZE));
image.at<Scalar>(i-SAMPLE_SIZE, j) = Scalar(0,0,0);
}
if (j+SAMPLE_SIZE < image.cols
&& image.at<Scalar>(i, j+SAMPLE_SIZE) == obj) {
blob.push_back(Point(j+SAMPLE_SIZE, i));
image.at<Scalar>(i, j+SAMPLE_SIZE) = Scalar(0,0,0);
}
if (j-SAMPLE_SIZE >= 0 &&
image.at<Scalar>(i, j-SAMPLE_SIZE) == obj) {
blob.push_back(Point(j-SAMPLE_SIZE, i));
image.at<Scalar>(i, j-SAMPLE_SIZE) = Scalar(0,0,0);
}
index++;
}
return blob;
}
bool compareBlobs(Points& blob0, Points& blob1) {
return blob0.size() < blob1.size();
}
vector<Points> findBlobs(Mat& image,
const int offset, const unsigned int maxBlobs, Scalar obj) {
// First get all blobs that are at least the minimum size
vector<Points> allBlobs;
for (int i = offset; i < image.rows; i += SAMPLE_SIZE) {
for (int j = offset; j < image.cols; j += SAMPLE_SIZE) {
if (image.at<Scalar>(i, j) == obj) {
Points blob = findBlob(image, i, j, obj);
if (blob.size() >= MIN_POINTS) {
allBlobs.push_back(blob);
}
}
}
}
// Stop now if there are 'maxBlobs' or fewer blobs
if (allBlobs.size() <= maxBlobs) {
return allBlobs;
}
// Otherwise limit to the biggest 'maxBlobs' blobs
make_heap(allBlobs.begin(), allBlobs.end(), compareBlobs);
vector<Points> blobs = vector<Points>();
blobs.push_back(allBlobs.front());
for (unsigned int i = 1; i < maxBlobs && allBlobs.size() > 1; i++) {
pop_heap(allBlobs.begin(), allBlobs.end(), compareBlobs);
blobs.push_back(allBlobs.front());
}
return blobs;
}
vector<BlobAnalysis> analyzeBlob(Object& object,
Points& blob, Mat& image) {
vector<BlobAnalysis> analysisList;
RotatedRect rectangle;
switch (object.analysisType) {
case ANALYSIS_RECTANGLE:
analysisList.push_back(BlobAnalysis(blob, minAreaRect(Mat(blob))));
break;
}
return analysisList;
}
float computeConfidence(Object& object, BlobAnalysis& a) {
// A return value of -1 indicates 'divide by zero' error
// A return value of -2 indicates 'unknown confidence type' error
int expectedPoints;
switch (object.confidenceType) {
case CONFIDENCE_RECTANGLE:
expectedPoints = (a.width * a.height) / (SAMPLE_SIZE * SAMPLE_SIZE);
break;
case CONFIDENCE_CIRCLE:
expectedPoints =
(M_PI * a.width * a.height) / (4 * SAMPLE_SIZE * SAMPLE_SIZE);
break;
default:
return -2; // Unknown confidence type
}
if (expectedPoints <= 0) {
return -1; // Divide by zero
} else {
float confidence = ((float) a.size) / ((float) expectedPoints);
if (confidence > 1) {
return 1;
} else {
return confidence;
}
}
}
void annotateImage(Mat& image, Object& object, BlobAnalysis& a) {
int r, x, y;
switch (object.annotationType) {
case ANNOTATION_ROTATION:
x = (int) (a.height / 2.0 * cos(a.rotation));
y = (int) (a.height / 2.0 * sin(a.rotation));
circle(image, Point(a.center_x, a.center_y), 1,
object.annotationColor, 5, CV_AA);
line(image, Point(a.center_x, a.center_y),
Point(a.center_x + x, a.center_y + y),
object.annotationColor, 1, CV_AA);
break;
case ANNOTATION_RADIUS:
r = (int) ((a.width + a.height) / 4.0);
circle(image, Point(a.center_x, a.center_y), r,
object.annotationColor, 2, CV_AA);
break;
}
}
//assuming i=y and j=x
void objInRange(const Mat& segmented, Mat& threshold, const int offset)
{ int count=0, hue=0, sat=0, bright=0;
if (threshold.total() == 0) {
threshold.create(segmented.rows, segmented.cols, CV_8U);
}
for (int i = offset; i < threshold.rows; i += SAMPLE_SIZE) {
for (int j = offset; j < threshold.cols; j += SAMPLE_SIZE) {
Sample sample;
Vec3b hsv = segmented.at<cv::Vec3b>(i, j);
sample.type=0;
sample.iAttr[0]=lastAvgHue;
sample.iAttr[1]=lastAvgSat;
sample.iAttr[2]=lastAvgBright;
sample.iAttr[3]=hsv[0];
sample.iAttr[4]=hsv[1];
sample.iAttr[5]=hsv[2];
hue+=hsv[0];
sat+=hsv[1];
bright+=hsv[2];
++count;
int temp=pTree->Classify(sample);
threshold.at<Scalar>(i,j)= temp ? objects[temp-1].annotationColor : Scalar(0,0,0);
}
}
lastAvgHue=hue/count;
lastAvgSat=sat/count;
lastAvgBright=bright/count;
}
bool inCircle(BlobAnalysis analysis, BlobTrack track)
{
int deltaX=analysis.center_x-track.x;
int deltaY=analysis.center_y-track.y;
return (sqrt((float)deltaX * deltaX + deltaY * deltaY)) <= TRACKING_MOVEMENT_TOLERANCE;
}
bool trackBlob(BlobAnalysis analysis, int type)
{
for(int i=0;i<trackBlobs.size();++i)
{
if(type==trackBlobs[i].objType)
{
if(inCircle(analysis, trackBlobs[i]))
{
trackBlobs[i].x=analysis.center_x;
trackBlobs[i].y=analysis.center_y;
trackBlobs[i].lastSeen=curFrame;
++trackBlobs[i].lifetime;
return FRAME_MARGIN_OF_ERROR>=trackBlobs[i].lifetime;
}
}
}
trackBlobs.push_back(BlobTrack(analysis.center_x, analysis.center_y, curFrame, type));
return false;
}
void updateBlobTracking()
{
for(int i=0;i<trackBlobs.size();++i)
{
if(trackBlobs[i].lastSeen < (curFrame - FRAME_MARGIN_OF_ERROR))
{
trackBlobs.erase(trackBlobs.begin()+i);
--i;
}
}
++curFrame;
}
void genericCallback(
const int camera,
const sensor_msgs::ImageConstPtr& rosImage,
cv_bridge::CvImage& rotated,
Mat& segmented,
Mat& threshold,
const int offset,
const image_transport::Publisher& publisher,
const image_transport::Publisher& threshPublisher) {
// Copy image from ROS format to OpenCV format
cv_bridge::CvImageConstPtr cvImage = cv_bridge::toCvShare(rosImage, "bgr8");
// Rotate image upright
//TODO: find a better way to stop forward camera rotation
if (camera == CAMERA_DOWNWARD) {
transpose(cvImage->image, rotated.image);
flip(rotated.image, rotated.image, 0); // 0=ccw, 1=cw
rotated.encoding = cvImage->encoding;
}
else{
rotated = *cvImage;
}
// Segment into HSV
cvtColor(rotated.image, segmented, CV_BGR2HSV);
// Normalize brightness and copy back to BGR
//normalizeValue(segmented, threshold);
//cvtColor(segmented, rotated.image, CV_HSV2BGR);
// Iterate through all objects
objInRange(segmented, threshold, offset);
for (unsigned int i = 0; i < objects.size(); i++) {
Object object = objects[i];
// Run applicable algorithms
if ((object.flags & FLAG_ENABLED) && object.camera == camera) {
//reduceNoise(threshold);
if (true) {
cv_bridge::CvImage temp;
temp.encoding = "8U3C";
temp.image = threshold;
threshPublisher.publish(temp.toImageMsg());
}
int tempenum=object.enumType;
vector<Points> blobs = findBlobs(
threshold, offset, object.maxBlobs, object.annotationColor);
// Iterate through all blobs
for (unsigned int j = 0; j < blobs.size(); j++) {
vector<BlobAnalysis> analysisList =
analyzeBlob(object, blobs[j], rotated.image);
// Iterate through all blob analysis objects
ros::Time time = ros::Time::now();
for (unsigned int k = 0; k < analysisList.size(); k++) {
BlobAnalysis analysis = analysisList[k];
// if (trackBlob(analysis, object.enumType))
if(true)
{
// Publish information
SubImageRecognition::ImgRecObject msg;
msg.stamp = time;
msg.id = k;
msg.center_x = analysis.center_x - rotated.image.cols / 2;
msg.center_y = rotated.image.rows / 2 - analysis.center_y;
msg.rotation = (analysis.rotation + M_PI / 2.0) * 180.0 / M_PI;
msg.width = analysis.width;
msg.height = analysis.height;
msg.confidence = computeConfidence(object, analysis);
object.publisher.publish(msg);
// Annotate image
annotateImage(rotated.image, object, analysis);
}
}
}
// cout<<"Blobs: "<<blobs.size()<<" Tracks: "<<trackBlobs.size()<<endl;
}
}
// Publish annotated image
publisher.publish(rotated.toImageMsg());
updateBlobTracking();
}
void forwardCallback(const sensor_msgs::ImageConstPtr& rosImage) {
genericCallback(CAMERA_FORWARD, rosImage, forwardRotated, forwardSegmented,
forwardThreshold, forwardOffset, forwardPublisher, forwardThresh);
forwardOffset = (forwardOffset + 1) % SAMPLE_SIZE;
}
void downwardCallback(const sensor_msgs::ImageConstPtr& rosImage) {
genericCallback(CAMERA_DOWNWARD, rosImage, downwardRotated, downwardSegmented,
downwardThreshold, downwardOffset, downwardPublisher, downwardThresh);
downwardOffset = (downwardOffset + 1) % SAMPLE_SIZE;
}
int main(int argc, char **argv) {
fstream file("/opt/robosub/rosWorkspace/SubImageRecognition/tree.tree");
pTree = new DLT(file);
ros::init(argc, argv, "ImageRecognition");
ros::NodeHandle nodeHandle;
image_transport::ImageTransport imageTransport(nodeHandle);
forwardPublisher = imageTransport.advertise("forward_camera/image_raw", 1);
downwardPublisher = imageTransport.advertise("downward_camera/image_raw", 1);
forwardThresh = imageTransport.advertise("forward_camera/threshold", 1);
downwardThresh = imageTransport.advertise("downward_camera/threshold", 1);
image_transport::Subscriber forwardSubscriber = imageTransport.subscribe("/stereo/left/image_raw", 1, forwardCallback);
image_transport::Subscriber downwardSubscriber = imageTransport.subscribe("image_raw", 1, downwardCallback);
initObjects();
ros::spin();
return 0;
}
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "submitfilemodel.h"
#include "vcsbaseconstants.h"
#include <QtGui/QStandardItem>
#include <QtCore/QDebug>
namespace VCSBase {
// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------
static QList<QStandardItem *> createFileRow(const QString &fileName, const QString &status,
bool checked, const QVariant &v)
{
QStandardItem *statusItem = new QStandardItem(status);
statusItem->setCheckable(true);
statusItem->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
statusItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
statusItem->setData(v);
QStandardItem *fileItem = new QStandardItem(fileName);
fileItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
QList<QStandardItem *> row;
row << statusItem << fileItem;
return row;
}
// --------------------------------------------------------------------------
// SubmitFileModel:
// --------------------------------------------------------------------------
/*!
\class VCSBase::SubmitFileModel
\brief A 2-column (checkable, state, file name) model to be used to list the files
in the submit editor. Provides header items and a convience to add files.
*/
SubmitFileModel::SubmitFileModel(QObject *parent) :
QStandardItemModel(0, 2, parent)
{
// setColumnCount(2);
QStringList headerLabels;
headerLabels << tr("State") << tr("File");
setHorizontalHeaderLabels(headerLabels);
}
QList<QStandardItem *> SubmitFileModel::addFile(const QString &fileName, const QString &status, bool checked,
const QVariant &v)
{
const QList<QStandardItem *> row = createFileRow(fileName, status, checked, v);
appendRow(row);
return row;
}
QList<QStandardItem *> SubmitFileModel::rowAt(int row) const
{
const int colCount = columnCount();
QList<QStandardItem *> rc;
for (int c = 0; c < colCount; c++)
rc.push_back(item(row, c));
return rc;
}
QString SubmitFileModel::state(int row) const
{
if (row < 0 || row >= rowCount())
return QString();
return item(row)->text();
}
QString SubmitFileModel::file(int row) const
{
if (row < 0 || row >= rowCount())
return QString();
return item(row, 1)->text();
}
bool SubmitFileModel::checked(int row) const
{
if (row < 0 || row >= rowCount())
return false;
return (item(row)->checkState() == Qt::Checked);
}
QVariant SubmitFileModel::data(int row) const
{
if (row < 0 || row >= rowCount())
return false;
return item(row)->data();
}
bool SubmitFileModel::hasCheckedFiles() const
{
for (int i = 0; i < rowCount(); ++i) {
if (checked(i))
return true;
}
return false;
}
QList<QStandardItem *> SubmitFileModel::findRow(const QString &text, int column) const
{
// Single item
const QList<QStandardItem *> items = findItems(text, Qt::MatchExactly, column);
if (items.empty())
return items;
// Compile row
return rowAt(items.front()->row());
}
unsigned SubmitFileModel::filter(const QStringList &filter, int column)
{
unsigned rc = 0;
for (int r = rowCount() - 1; r >= 0; r--)
if (const QStandardItem *i = item(r, column))
if (!filter.contains(i->text())) {
qDeleteAll(takeRow(r));
rc++;
}
if (VCSBase::Constants::Internal::debug)
qDebug() << Q_FUNC_INFO << " deleted " << rc << " items using " << filter << " , remaining " << rowCount();
return rc;
}
}
VcsBase: show icons for the files in the submit editor
Change-Id: I0c7704a20a4b9a2ceef814f78d5d52297b8cc4f6
Reviewed-by: Tobias Hunger <012f8d714267bccc9d4766fbeace9f175fcc70c4@nokia.com>
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "submitfilemodel.h"
#include "vcsbaseconstants.h"
#include <coreplugin/fileiconprovider.h>
#include <QtGui/QStandardItem>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
namespace VCSBase {
// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------
static QList<QStandardItem *> createFileRow(const QString &fileName, const QString &status,
bool checked, const QVariant &v)
{
QStandardItem *statusItem = new QStandardItem(status);
statusItem->setCheckable(true);
statusItem->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
statusItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
statusItem->setData(v);
QStandardItem *fileItem = new QStandardItem(fileName);
fileItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
fileItem->setIcon(Core::FileIconProvider::instance()->icon(QFileInfo(fileName)));
QList<QStandardItem *> row;
row << statusItem << fileItem;
return row;
}
// --------------------------------------------------------------------------
// SubmitFileModel:
// --------------------------------------------------------------------------
/*!
\class VCSBase::SubmitFileModel
\brief A 2-column (checkable, state, file name) model to be used to list the files
in the submit editor. Provides header items and a convience to add files.
*/
SubmitFileModel::SubmitFileModel(QObject *parent) :
QStandardItemModel(0, 2, parent)
{
// setColumnCount(2);
QStringList headerLabels;
headerLabels << tr("State") << tr("File");
setHorizontalHeaderLabels(headerLabels);
}
QList<QStandardItem *> SubmitFileModel::addFile(const QString &fileName, const QString &status, bool checked,
const QVariant &v)
{
const QList<QStandardItem *> row = createFileRow(fileName, status, checked, v);
appendRow(row);
return row;
}
QList<QStandardItem *> SubmitFileModel::rowAt(int row) const
{
const int colCount = columnCount();
QList<QStandardItem *> rc;
for (int c = 0; c < colCount; c++)
rc.push_back(item(row, c));
return rc;
}
QString SubmitFileModel::state(int row) const
{
if (row < 0 || row >= rowCount())
return QString();
return item(row)->text();
}
QString SubmitFileModel::file(int row) const
{
if (row < 0 || row >= rowCount())
return QString();
return item(row, 1)->text();
}
bool SubmitFileModel::checked(int row) const
{
if (row < 0 || row >= rowCount())
return false;
return (item(row)->checkState() == Qt::Checked);
}
QVariant SubmitFileModel::data(int row) const
{
if (row < 0 || row >= rowCount())
return false;
return item(row)->data();
}
bool SubmitFileModel::hasCheckedFiles() const
{
for (int i = 0; i < rowCount(); ++i) {
if (checked(i))
return true;
}
return false;
}
QList<QStandardItem *> SubmitFileModel::findRow(const QString &text, int column) const
{
// Single item
const QList<QStandardItem *> items = findItems(text, Qt::MatchExactly, column);
if (items.empty())
return items;
// Compile row
return rowAt(items.front()->row());
}
unsigned SubmitFileModel::filter(const QStringList &filter, int column)
{
unsigned rc = 0;
for (int r = rowCount() - 1; r >= 0; r--)
if (const QStandardItem *i = item(r, column))
if (!filter.contains(i->text())) {
qDeleteAll(takeRow(r));
rc++;
}
if (VCSBase::Constants::Internal::debug)
qDebug() << Q_FUNC_INFO << " deleted " << rc << " items using " << filter << " , remaining " << rowCount();
return rc;
}
}
|
/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009-2011 Emmanuel Benazera <ebenazer@seeks-project.info>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query_context.h"
#include "websearch.h"
#include "stl_hash.h"
#include "mem_utils.h"
#include "miscutil.h"
#include "mutexes.h"
#include "urlmatch.h"
#include "mrf.h"
#include "errlog.h"
#include "se_handler.h"
#include "iso639.h"
#include "encode.h"
#include "charset_conv.h"
#include <sys/time.h>
#include <algorithm>
#include <iostream>
using sp::sweeper;
using sp::miscutil;
using sp::urlmatch;
using sp::errlog;
using sp::iso639;
using sp::encode;
using lsh::mrf;
namespace seeks_plugins
{
std::string query_context::_default_alang = "en";
std::string query_context::_default_alang_reg = "en-US";
query_context::query_context()
:sweepable(),_page_expansion(0),_lsh_ham(NULL),_ulsh_ham(NULL),_compute_tfidf_features(true),
_registered(false),_npeers(0),_lfilter(NULL)
{
mutex_init(&_qc_mutex);
mutex_init(&_feeds_ack_mutex);
cond_init(&_feeds_ack_cond);
}
query_context::query_context(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
const std::list<const char*> &http_headers)
:sweepable(),_page_expansion(0),_blekko(false),_lsh_ham(NULL),_ulsh_ham(NULL),_compute_tfidf_features(true),
_registered(false),_npeers(0),_lfilter(NULL)
{
mutex_init(&_qc_mutex);
mutex_init(&_feeds_ack_mutex);
cond_init(&_feeds_ack_cond);
// set query.
const char *q = miscutil::lookup(parameters,"q");
if (!q)
{
// this should not happen.
errlog::log_error(LOG_LEVEL_ERROR,"creating context with empty query string");
q = "";
}
_query = q;
_lc_query = _query;
miscutil::to_lower(_lc_query);
// set timestamp.
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
_creation_time = _last_time_of_use = tv_now.tv_sec;
grab_useful_headers(http_headers);
// sets auto_lang & auto_lang_reg.
const char *alang = miscutil::lookup(parameters,"lang");
if (!alang)
{
// this should not happen.
alang = query_context::_default_alang.c_str();
}
const char *alang_reg = miscutil::lookup(parameters,"lreg");
if (!alang_reg)
{
// this should not happen.
alang_reg = query_context::_default_alang_reg.c_str();
}
_auto_lang = alang;
_auto_lang_reg = alang_reg;
// query hashing, with the language included.
_query_key = query_context::assemble_query(_lc_query,_auto_lang);
_query_hash = query_context::hash_query_for_context(_query_key);
// encoded query.
char *url_enc_query_str = encode::url_encode(_query.c_str());
_url_enc_query = url_enc_query_str;
free(url_enc_query_str);
// lookup requested engines, if any.
query_context::fillup_engines(parameters,_engines);
sweeper::register_sweepable(this);
}
query_context::~query_context()
{
unregister(); // unregister from websearch plugin.
_unordered_snippets.clear();
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator chit;
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit
= _unordered_snippets_title.begin();
while (hit!=_unordered_snippets_title.end())
{
chit = hit;
++hit;
const char *k = (*chit).first;
_unordered_snippets_title.erase(chit);
free_const(k);
}
std::for_each(_cached_snippets.begin(),_cached_snippets.end(),
delete_object());
// clears the LSH hashtable.
if (_ulsh_ham)
delete _ulsh_ham;
if (_lsh_ham)
delete _lsh_ham;
for (std::list<const char*>::iterator lit=_useful_http_headers.begin();
lit!=_useful_http_headers.end(); lit++)
free_const((*lit));
if (_lfilter)
delete _lfilter;
}
std::string query_context::sort_query(const std::string &query)
{
std::string clean_query = query;
std::vector<std::string> tokens;
mrf::tokenize(clean_query,tokens," ");
std::sort(tokens.begin(),tokens.end(),std::less<std::string>());
std::string sorted_query;
size_t ntokens = tokens.size();
for (size_t i=0; i<ntokens; i++)
sorted_query += tokens.at(i);
return sorted_query;
}
uint32_t query_context::hash_query_for_context(const std::string &query_key)
{
std::string sorted_query = query_context::sort_query(query_key);
return mrf::mrf_single_feature(sorted_query);
}
void query_context::reset_expansion_parameter(hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
// reset expansion parameter.
miscutil::unmap(parameters,"expansion");
std::string exp_str = miscutil::to_string(_page_expansion);
miscutil::add_map_entry(parameters,"expansion",1,exp_str.c_str(),1);
}
void query_context::reset_p2p_data()
{
std::vector<search_snippet*>::iterator vit = _cached_snippets.begin();
while (vit!=_cached_snippets.end())
{
(*vit)->reset_p2p_data();
++vit;
}
}
bool query_context::sweep_me()
{
// check last_time_of_use + delay against current time.
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
double dt = difftime(tv_now.tv_sec,_last_time_of_use);
//debug
/* std::cout << "[Debug]:query_context #" << _query_hash
<< ": sweep_me time difference: " << dt << std::endl; */
//debug
if (dt >= websearch::_wconfig->_query_context_delay)
return true;
else return false;
}
void query_context::update_last_time()
{
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
_last_time_of_use = tv_now.tv_sec;
}
void query_context::register_qc()
{
if (_registered)
return;
websearch::_active_qcontexts.insert(std::pair<uint32_t,query_context*>(_query_hash,this));
_registered = true;
}
void query_context::unregister()
{
if (!_registered)
return;
hash_map<uint32_t,query_context*,id_hash_uint>::iterator hit;
if ((hit = websearch::_active_qcontexts.find(_query_hash))==websearch::_active_qcontexts.end())
{
/**
* We should not reach here, unless the destructor is called by a derived class.
*/
/* errlog::log_error(LOG_LEVEL_ERROR,"Cannot find query context when unregistering for query %s",
_query.c_str()); */
return;
}
else
{
websearch::_active_qcontexts.erase(hit); // deletion is controlled elsewhere.
_registered = false;
}
}
void query_context::generate(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
bool &expanded) throw (sp_exception)
{
expanded = false;
const char *expansion = miscutil::lookup(parameters,"expansion");
if (!expansion)
{
throw sp_exception(SP_ERR_CGI_PARAMS,"no expansion given in call parameters");
}
char* endptr;
int horizon = strtol(expansion, &endptr, 0);
if (*endptr)
{
throw sp_exception(SP_ERR_CGI_PARAMS,std::string("wrong expansion value ") + std::string(expansion));
}
if (horizon == 0)
horizon = 1;
if (horizon > websearch::_wconfig->_max_expansions) // max expansion protection.
horizon = websearch::_wconfig->_max_expansions;
const char *cache_check = miscutil::lookup(parameters,"ccheck");
// grab requested engines, if any.
// if the list is not included in that of the context, update existing results and perform requested expansion.
// if the list is included in that of the context, perform expansion, results will be filtered later on.
if (!cache_check || strcasecmp(cache_check,"yes") == 0)
{
feeds beng;
const char *eng = miscutil::lookup(parameters,"engines");
if (eng)
{
query_context::fillup_engines(parameters,beng);
}
else beng = feeds(websearch::_wconfig->_se_default);
// test inclusion.
feeds inc = _engines.inter(beng);
//TODO: unit test the whole engine selection.
if (!beng.equal(inc))
{
// union of beng and fdiff.
feeds fdiff = _engines.diff(beng);
feeds fint = _engines.diff(fdiff);
// catch up expansion with the newly activated engines.
if (fint.size() > 1 || !fint.has_feed("seeks"))
{
try
{
expand(csp,rsp,parameters,0,_page_expansion,fint);
}
catch (sp_exception &e)
{
expanded = false;
throw e;
}
}
expanded = true;
// union engines & fint.
_engines = _engines.sunion(fint);
}
// whether we need to move forward.
if (_page_expansion > 0 && horizon <= (int)_page_expansion)
{
// reset expansion parameter.
query_context::reset_expansion_parameter(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters));
return;
}
}
// perform requested expansion.
if (_engines.size() > 1 || (!_engines.has_feed("seeks") && !_engines.has_feed("dummy")))
{
try
{
if (!cache_check)
expand(csp,rsp,parameters,_page_expansion,horizon,_engines);
else if (strcasecmp(cache_check,"no") == 0)
expand(csp,rsp,parameters,0,horizon,_engines);
}
catch (sp_exception &e)
{
expanded = false;
throw e;
}
}
expanded = true;
// update horizon.
_page_expansion = horizon;
}
void query_context::expand(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
const int &page_start, const int &page_end,
const feeds &se_enabled) throw (sp_exception)
{
for (int i=page_start; i<page_end; i++) // catches up with requested horizon.
{
// resets expansion parameter.
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"expansion");
std::string i_str = miscutil::to_string(i+1);
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),
"expansion",1,i_str.c_str(),1);
// query SEs.
int nresults = 0;
std::string **outputs = NULL;
try
{
outputs = se_handler::query_to_ses(parameters,nresults,this,se_enabled);
}
catch (sp_exception &e)
{
throw e; // no engine found or connection error.
}
feed_parser fp = se_enabled.find_feed("blekko");
if (!fp._name.empty())
_blekko = true; // call once.
// parse the output and create result search snippets.
int rank_offset = (i > 0) ? i * websearch::_wconfig->_Nr : 0;
se_handler::parse_ses_output(outputs,nresults,_cached_snippets,rank_offset,this,se_enabled);
for (int j=0; j<nresults; j++)
if (outputs[j])
delete outputs[j];
delete[] outputs;
}
}
void query_context::add_to_cache(search_snippet *sr)
{
_cached_snippets.push_back(sr);
}
void query_context::remove_from_cache(search_snippet *sr)
{
std::vector<search_snippet*>::iterator vit
= _cached_snippets.begin();
while(vit!=_cached_snippets.end())
{
if ((*vit)->_id == sr->_id)
vit = _cached_snippets.erase(vit);
else ++vit;
}
}
void query_context::add_to_unordered_cache(search_snippet *sr)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(sr->_id))!=_unordered_snippets.end())
{
// do nothing.
}
else _unordered_snippets.insert(std::pair<uint32_t,search_snippet*>(sr->_id,sr));
}
void query_context::remove_from_unordered_cache(const uint32_t &id)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(id))!=_unordered_snippets.end())
{
_unordered_snippets.erase(hit);
}
}
void query_context::update_unordered_cache()
{
size_t cs_size = _cached_snippets.size();
for (size_t i=0; i<cs_size; i++)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(_cached_snippets[i]->_id))!=_unordered_snippets.end())
{
// for now, do nothing. TODO: may merge snippets here.
}
else
_unordered_snippets.insert(std::pair<uint32_t,search_snippet*>(_cached_snippets[i]->_id,
_cached_snippets[i]));
}
}
search_snippet* query_context::get_cached_snippet(const std::string &url) const
{
std::string url_lc(url);
miscutil::to_lower(url_lc);
std::string surl = urlmatch::strip_url(url_lc);
uint32_t id = mrf::mrf_single_feature(surl);
return get_cached_snippet(id);
}
search_snippet* query_context::get_cached_snippet(const uint32_t &id) const
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::const_iterator hit;
if ((hit = _unordered_snippets.find(id))==_unordered_snippets.end())
return NULL;
else return (*hit).second;
}
void query_context::add_to_unordered_cache_title(search_snippet *sr)
{
std::string lctitle = sr->_title;
miscutil::to_lower(lctitle);
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit=_unordered_snippets_title.find(lctitle.c_str()))!=_unordered_snippets_title.end())
{
// do nothing.
}
else _unordered_snippets_title.insert(std::pair<const char*,search_snippet*>(strdup(lctitle.c_str()),sr));
}
void query_context::remove_from_unordered_cache_title(search_snippet *sr)
{
std::string lctitle = sr->_title;
miscutil::to_lower(lctitle);
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit=_unordered_snippets_title.find(lctitle.c_str()))!=_unordered_snippets_title.end())
{
const char *key = (*hit).first;
_unordered_snippets_title.erase(hit);
free_const(key);
}
}
search_snippet* query_context::get_cached_snippet_title(const char *lctitle)
{
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit = _unordered_snippets_title.find(lctitle))==_unordered_snippets_title.end())
return NULL;
else return (*hit).second;
}
bool query_context::has_lang(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
std::string &qlang)
{
const char *alang = miscutil::lookup(parameters,"lang");
if (alang)
{
qlang = alang;
miscutil::to_lower(qlang);
return true;
}
else return false;
}
bool query_context::has_query_lang(const std::string &query,
std::string &qlang)
{
if (query.empty() || query[0] != ':') // XXX: could chomp the query.
{
qlang = "";
return false;
}
try
{
qlang = query.substr(1,2); // : + 2 characters for the language.
miscutil::to_lower(qlang);
}
catch (std::exception &e)
{
qlang = "";
}
// check whether the language is known ! -> XXX: language table...
if (iso639::has_code(qlang.c_str()))
{
return true;
}
else
{
errlog::log_error(LOG_LEVEL_INFO,"in query command test: language code not found: %s",qlang.c_str());
qlang = "";
return false;
}
}
// static.
void query_context::detect_query_lang_http(const std::list<const char*> &http_headers,
std::string &lang, std::string &lang_reg)
{
std::list<const char*>::const_iterator sit = http_headers.begin();
while (sit!=http_headers.end())
{
if (miscutil::strncmpic((*sit),"accept-language:",16) == 0)
{
// detect language.
std::string lang_head = (*sit);
size_t pos = lang_head.find_first_of(" ");
if (pos != std::string::npos && pos+6<=lang_head.length() && lang_head[pos+3] == '-')
{
try
{
lang = lang_head.substr(pos+1,2);
lang_reg = lang_head.substr(pos+1,5);
}
catch (std::exception &e)
{
lang = query_context::_default_alang;
lang_reg = query_context::_default_alang_reg; // default.
}
errlog::log_error(LOG_LEVEL_DEBUG,"Query language detection: %s",lang_reg.c_str());
return;
}
else if (pos != std::string::npos && pos+3<=lang_head.length())
{
try
{
lang = lang_head.substr(pos+1,2);
}
catch (std::exception &e)
{
lang = query_context::_default_alang; // default.
}
lang_reg = query_context::lang_forced_region(lang);
errlog::log_error(LOG_LEVEL_DEBUG,"Forced query language region at detection: %s",lang_reg.c_str());
return;
}
}
++sit;
}
lang_reg = query_context::_default_alang_reg; // beware, returning hardcoded default (since config value is most likely "auto").
lang = query_context::_default_alang;
}
std::string query_context::detect_base_url_http(client_state *csp)
{
std::list<const char*> headers = csp->_headers;
// first we try to get base_url from a custom header
std::string base_url;
std::list<const char*>::const_iterator sit = headers.begin();
while (sit!=headers.end())
{
if (miscutil::strncmpic((*sit),"Seeks-Remote-Location:",22) == 0)
{
base_url = (*sit);
size_t pos = base_url.find_first_of(" ");
try
{
base_url = base_url.substr(pos+1);
}
catch (std::exception &e)
{
base_url = "";
break;
}
break;
}
++sit;
}
if (base_url.empty())
{
// if no custom header, we build base_url from the generic Host header
std::list<const char*>::const_iterator sit = headers.begin();
while (sit!=headers.end())
{
if (miscutil::strncmpic((*sit),"Host:",5) == 0)
{
base_url = (*sit);
size_t pos = base_url.find_first_of(" ");
try
{
base_url = base_url.substr(pos+1);
}
catch (std::exception &e)
{
base_url = "";
return base_url;
}
break;
}
++sit;
}
base_url = csp->_http._ssl ? "https://" : "http://" + base_url;
}
return base_url;
}
std::string query_context::assemble_query(const std::string &query,
const std::string &lang)
{
if (!lang.empty())
{
return ":" + lang + " " + query;
}
else return query;
}
void query_context::grab_useful_headers(const std::list<const char*> &http_headers)
{
std::list<const char*>::const_iterator sit = http_headers.begin();
while (sit!=http_headers.end())
{
// user-agent
if (miscutil::strncmpic((*sit),"user-agent:",11) == 0)
{
const char *ua = strdup((*sit));
_useful_http_headers.push_back(ua);
}
else if (miscutil::strncmpic((*sit),"accept-charset:",15) == 0)
{
const char *ac = strdup((*sit));
/* std::string ac_str = "accept-charset: utf-8";
const char *ac = strdup(ac_str.c_str()); */
_useful_http_headers.push_back(ac);
}
else if (miscutil::strncmpic((*sit),"accept:",7) == 0)
{
const char *aa = strdup((*sit));
_useful_http_headers.push_back(aa);
}
// XXX: other useful headers should be detected and stored here.
++sit;
}
}
std::string query_context::lang_forced_region(const std::string &auto_lang)
{
// XXX: in-query language commands force the query language to the search engine.
// As such, we have to decide which region we attach to every of the most common
// language forced queries.
// Evidently, this is not a robust nor fast solution. Full support of locales etc... should
// appear in the future. As for now, this is a simple scheme for a simple need.
// Unsupported languages default to american english, that's how the world is right
// now...
std::string region_lang = query_context::_default_alang_reg; // default.
if (auto_lang == "en")
{
}
else if (auto_lang == "fr")
region_lang = "fr-FR";
else if (auto_lang == "de")
region_lang = "de-DE";
else if (auto_lang == "it")
region_lang = "it-IT";
else if (auto_lang == "es")
region_lang = "es-ES";
else if (auto_lang == "pt")
region_lang = "es-PT"; // so long for Brazil (BR)...
else if (auto_lang == "nl")
region_lang = "nl-NL";
else if (auto_lang == "ja")
region_lang = "ja-JP";
else if (auto_lang == "no")
region_lang = "no-NO";
else if (auto_lang == "pl")
region_lang = "pl-PL";
else if (auto_lang == "ru")
region_lang = "ru-RU";
else if (auto_lang == "ro")
region_lang = "ro-RO";
else if (auto_lang == "sh")
region_lang = "sh-RS"; // Serbia.
else if (auto_lang == "sl")
region_lang = "sl-SL";
else if (auto_lang == "sk")
region_lang = "sk-SK";
else if (auto_lang == "sv")
region_lang = "sv-SE";
else if (auto_lang == "th")
region_lang = "th-TH";
else if (auto_lang == "uk")
region_lang = "uk-UA";
else if (auto_lang == "zh")
region_lang = "zh-CN";
else if (auto_lang == "ko")
region_lang = "ko-KR";
else if (auto_lang == "ar")
region_lang = "ar-EG"; // Egypt, with _NO_ reasons. In most cases, the search engines will decide based on the 'ar' code.
else if (auto_lang == "be")
region_lang = "be-BY";
else if (auto_lang == "bg")
region_lang = "bg-BG";
else if (auto_lang == "bs")
region_lang = "bs-BA";
else if (auto_lang == "cs")
region_lang = "cs-CZ";
else if (auto_lang == "fi")
region_lang = "fi-FI";
else if (auto_lang == "he")
region_lang = "he-IL";
else if (auto_lang == "hi")
region_lang = "hi-IN";
else if (auto_lang == "hr")
region_lang = "hr-HR";
return region_lang;
}
std::string query_context::generate_lang_http_header() const
{
return "accept-language: " + _auto_lang + "," + _auto_lang_reg + ";q=0.5";
}
void query_context::in_query_command_forced_region(std::string &auto_lang,
std::string ®ion_lang)
{
region_lang = query_context::lang_forced_region(auto_lang);
if (region_lang == query_context::_default_alang_reg) // in case we are on the default language.
auto_lang = query_context::_default_alang;
}
void query_context::fillup_engines(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
feeds &engines)
{
const char *eng = miscutil::lookup(parameters,"engines");
if (eng)
{
std::string engines_str = std::string(eng);
std::vector<std::string> vec_engines;
miscutil::tokenize(engines_str,vec_engines,",");
for (size_t i=0; i<vec_engines.size(); i++)
{
std::string engine = vec_engines.at(i);
std::vector<std::string> vec_names;
miscutil::tokenize(engine,vec_names,":");
if (vec_names.size()==1)
engines.add_feed(engine,websearch::_wconfig);
else engines.add_feed(vec_names,
websearch::_wconfig);
}
}
else engines = feeds(websearch::_wconfig->_se_default);
}
void query_context::reset_snippets_personalization_flags()
{
std::vector<search_snippet*>::iterator vit = _cached_snippets.begin();
while (vit!=_cached_snippets.end())
{
if ((*vit)->_personalized)
{
// XXX: change of behavior.
// may want to remove seeks results when using a user db.
(*vit)->_personalized = false;
if ((*vit)->_engine.count() == 1
&& (*vit)->_engine.has_feed("seeks"))
{
remove_from_unordered_cache((*vit)->_id);
remove_from_unordered_cache_title((*vit));
delete (*vit);
vit = _cached_snippets.erase(vit);
continue;
}
else if ((*vit)->_engine.has_feed("seeks"))
(*vit)->_engine.remove_feed("seeks");
(*vit)->_meta_rank = (*vit)->_engine.size(); //TODO: wrong, every feed_parser may refer to several urls.
//TODO: don't reset in cache.
(*vit)->_seeks_rank = 0;
(*vit)->bing_yahoo_us_merge();
(*vit)->_npeers = 0;
(*vit)->_hits = 0;
}
else (*vit)->_seeks_rank = 0; // reset.
++vit;
}
_npeers = 0; // reset query context peers.
}
} /* end of namespace. */
added title check before title-based cache insertion in query_context
/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009-2011 Emmanuel Benazera <ebenazer@seeks-project.info>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query_context.h"
#include "websearch.h"
#include "stl_hash.h"
#include "mem_utils.h"
#include "miscutil.h"
#include "mutexes.h"
#include "urlmatch.h"
#include "mrf.h"
#include "errlog.h"
#include "se_handler.h"
#include "iso639.h"
#include "encode.h"
#include "charset_conv.h"
#include <sys/time.h>
#include <algorithm>
#include <iostream>
using sp::sweeper;
using sp::miscutil;
using sp::urlmatch;
using sp::errlog;
using sp::iso639;
using sp::encode;
using lsh::mrf;
namespace seeks_plugins
{
std::string query_context::_default_alang = "en";
std::string query_context::_default_alang_reg = "en-US";
query_context::query_context()
:sweepable(),_page_expansion(0),_lsh_ham(NULL),_ulsh_ham(NULL),_compute_tfidf_features(true),
_registered(false),_npeers(0),_lfilter(NULL)
{
mutex_init(&_qc_mutex);
mutex_init(&_feeds_ack_mutex);
cond_init(&_feeds_ack_cond);
}
query_context::query_context(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
const std::list<const char*> &http_headers)
:sweepable(),_page_expansion(0),_blekko(false),_lsh_ham(NULL),_ulsh_ham(NULL),_compute_tfidf_features(true),
_registered(false),_npeers(0),_lfilter(NULL)
{
mutex_init(&_qc_mutex);
mutex_init(&_feeds_ack_mutex);
cond_init(&_feeds_ack_cond);
// set query.
const char *q = miscutil::lookup(parameters,"q");
if (!q)
{
// this should not happen.
errlog::log_error(LOG_LEVEL_ERROR,"creating context with empty query string");
q = "";
}
_query = q;
_lc_query = _query;
miscutil::to_lower(_lc_query);
// set timestamp.
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
_creation_time = _last_time_of_use = tv_now.tv_sec;
grab_useful_headers(http_headers);
// sets auto_lang & auto_lang_reg.
const char *alang = miscutil::lookup(parameters,"lang");
if (!alang)
{
// this should not happen.
alang = query_context::_default_alang.c_str();
}
const char *alang_reg = miscutil::lookup(parameters,"lreg");
if (!alang_reg)
{
// this should not happen.
alang_reg = query_context::_default_alang_reg.c_str();
}
_auto_lang = alang;
_auto_lang_reg = alang_reg;
// query hashing, with the language included.
_query_key = query_context::assemble_query(_lc_query,_auto_lang);
_query_hash = query_context::hash_query_for_context(_query_key);
// encoded query.
char *url_enc_query_str = encode::url_encode(_query.c_str());
_url_enc_query = url_enc_query_str;
free(url_enc_query_str);
// lookup requested engines, if any.
query_context::fillup_engines(parameters,_engines);
sweeper::register_sweepable(this);
}
query_context::~query_context()
{
unregister(); // unregister from websearch plugin.
_unordered_snippets.clear();
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator chit;
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit
= _unordered_snippets_title.begin();
while (hit!=_unordered_snippets_title.end())
{
chit = hit;
++hit;
const char *k = (*chit).first;
_unordered_snippets_title.erase(chit);
free_const(k);
}
std::for_each(_cached_snippets.begin(),_cached_snippets.end(),
delete_object());
// clears the LSH hashtable.
if (_ulsh_ham)
delete _ulsh_ham;
if (_lsh_ham)
delete _lsh_ham;
for (std::list<const char*>::iterator lit=_useful_http_headers.begin();
lit!=_useful_http_headers.end(); lit++)
free_const((*lit));
if (_lfilter)
delete _lfilter;
}
std::string query_context::sort_query(const std::string &query)
{
std::string clean_query = query;
std::vector<std::string> tokens;
mrf::tokenize(clean_query,tokens," ");
std::sort(tokens.begin(),tokens.end(),std::less<std::string>());
std::string sorted_query;
size_t ntokens = tokens.size();
for (size_t i=0; i<ntokens; i++)
sorted_query += tokens.at(i);
return sorted_query;
}
uint32_t query_context::hash_query_for_context(const std::string &query_key)
{
std::string sorted_query = query_context::sort_query(query_key);
return mrf::mrf_single_feature(sorted_query);
}
void query_context::reset_expansion_parameter(hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
{
// reset expansion parameter.
miscutil::unmap(parameters,"expansion");
std::string exp_str = miscutil::to_string(_page_expansion);
miscutil::add_map_entry(parameters,"expansion",1,exp_str.c_str(),1);
}
void query_context::reset_p2p_data()
{
std::vector<search_snippet*>::iterator vit = _cached_snippets.begin();
while (vit!=_cached_snippets.end())
{
(*vit)->reset_p2p_data();
++vit;
}
}
bool query_context::sweep_me()
{
// check last_time_of_use + delay against current time.
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
double dt = difftime(tv_now.tv_sec,_last_time_of_use);
//debug
/* std::cout << "[Debug]:query_context #" << _query_hash
<< ": sweep_me time difference: " << dt << std::endl; */
//debug
if (dt >= websearch::_wconfig->_query_context_delay)
return true;
else return false;
}
void query_context::update_last_time()
{
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
_last_time_of_use = tv_now.tv_sec;
}
void query_context::register_qc()
{
if (_registered)
return;
websearch::_active_qcontexts.insert(std::pair<uint32_t,query_context*>(_query_hash,this));
_registered = true;
}
void query_context::unregister()
{
if (!_registered)
return;
hash_map<uint32_t,query_context*,id_hash_uint>::iterator hit;
if ((hit = websearch::_active_qcontexts.find(_query_hash))==websearch::_active_qcontexts.end())
{
/**
* We should not reach here, unless the destructor is called by a derived class.
*/
/* errlog::log_error(LOG_LEVEL_ERROR,"Cannot find query context when unregistering for query %s",
_query.c_str()); */
return;
}
else
{
websearch::_active_qcontexts.erase(hit); // deletion is controlled elsewhere.
_registered = false;
}
}
void query_context::generate(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
bool &expanded) throw (sp_exception)
{
expanded = false;
const char *expansion = miscutil::lookup(parameters,"expansion");
if (!expansion)
{
throw sp_exception(SP_ERR_CGI_PARAMS,"no expansion given in call parameters");
}
char* endptr;
int horizon = strtol(expansion, &endptr, 0);
if (*endptr)
{
throw sp_exception(SP_ERR_CGI_PARAMS,std::string("wrong expansion value ") + std::string(expansion));
}
if (horizon == 0)
horizon = 1;
if (horizon > websearch::_wconfig->_max_expansions) // max expansion protection.
horizon = websearch::_wconfig->_max_expansions;
const char *cache_check = miscutil::lookup(parameters,"ccheck");
// grab requested engines, if any.
// if the list is not included in that of the context, update existing results and perform requested expansion.
// if the list is included in that of the context, perform expansion, results will be filtered later on.
if (!cache_check || strcasecmp(cache_check,"yes") == 0)
{
feeds beng;
const char *eng = miscutil::lookup(parameters,"engines");
if (eng)
{
query_context::fillup_engines(parameters,beng);
}
else beng = feeds(websearch::_wconfig->_se_default);
// test inclusion.
feeds inc = _engines.inter(beng);
//TODO: unit test the whole engine selection.
if (!beng.equal(inc))
{
// union of beng and fdiff.
feeds fdiff = _engines.diff(beng);
feeds fint = _engines.diff(fdiff);
// catch up expansion with the newly activated engines.
if (fint.size() > 1 || !fint.has_feed("seeks"))
{
try
{
expand(csp,rsp,parameters,0,_page_expansion,fint);
}
catch (sp_exception &e)
{
expanded = false;
throw e;
}
}
expanded = true;
// union engines & fint.
_engines = _engines.sunion(fint);
}
// whether we need to move forward.
if (_page_expansion > 0 && horizon <= (int)_page_expansion)
{
// reset expansion parameter.
query_context::reset_expansion_parameter(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters));
return;
}
}
// perform requested expansion.
if (_engines.size() > 1 || (!_engines.has_feed("seeks") && !_engines.has_feed("dummy")))
{
try
{
if (!cache_check)
expand(csp,rsp,parameters,_page_expansion,horizon,_engines);
else if (strcasecmp(cache_check,"no") == 0)
expand(csp,rsp,parameters,0,horizon,_engines);
}
catch (sp_exception &e)
{
expanded = false;
throw e;
}
}
expanded = true;
// update horizon.
_page_expansion = horizon;
}
void query_context::expand(client_state *csp,
http_response *rsp,
const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
const int &page_start, const int &page_end,
const feeds &se_enabled) throw (sp_exception)
{
for (int i=page_start; i<page_end; i++) // catches up with requested horizon.
{
// resets expansion parameter.
miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"expansion");
std::string i_str = miscutil::to_string(i+1);
miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),
"expansion",1,i_str.c_str(),1);
// query SEs.
int nresults = 0;
std::string **outputs = NULL;
try
{
outputs = se_handler::query_to_ses(parameters,nresults,this,se_enabled);
}
catch (sp_exception &e)
{
throw e; // no engine found or connection error.
}
feed_parser fp = se_enabled.find_feed("blekko");
if (!fp._name.empty())
_blekko = true; // call once.
// parse the output and create result search snippets.
int rank_offset = (i > 0) ? i * websearch::_wconfig->_Nr : 0;
se_handler::parse_ses_output(outputs,nresults,_cached_snippets,rank_offset,this,se_enabled);
for (int j=0; j<nresults; j++)
if (outputs[j])
delete outputs[j];
delete[] outputs;
}
}
void query_context::add_to_cache(search_snippet *sr)
{
_cached_snippets.push_back(sr);
}
void query_context::remove_from_cache(search_snippet *sr)
{
std::vector<search_snippet*>::iterator vit
= _cached_snippets.begin();
while(vit!=_cached_snippets.end())
{
if ((*vit)->_id == sr->_id)
vit = _cached_snippets.erase(vit);
else ++vit;
}
}
void query_context::add_to_unordered_cache(search_snippet *sr)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(sr->_id))!=_unordered_snippets.end())
{
// do nothing.
}
else _unordered_snippets.insert(std::pair<uint32_t,search_snippet*>(sr->_id,sr));
}
void query_context::remove_from_unordered_cache(const uint32_t &id)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(id))!=_unordered_snippets.end())
{
_unordered_snippets.erase(hit);
}
}
void query_context::update_unordered_cache()
{
size_t cs_size = _cached_snippets.size();
for (size_t i=0; i<cs_size; i++)
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::iterator hit;
if ((hit=_unordered_snippets.find(_cached_snippets[i]->_id))!=_unordered_snippets.end())
{
// for now, do nothing. TODO: may merge snippets here.
}
else
_unordered_snippets.insert(std::pair<uint32_t,search_snippet*>(_cached_snippets[i]->_id,
_cached_snippets[i]));
}
}
search_snippet* query_context::get_cached_snippet(const std::string &url) const
{
std::string url_lc(url);
miscutil::to_lower(url_lc);
std::string surl = urlmatch::strip_url(url_lc);
uint32_t id = mrf::mrf_single_feature(surl);
return get_cached_snippet(id);
}
search_snippet* query_context::get_cached_snippet(const uint32_t &id) const
{
hash_map<uint32_t,search_snippet*,id_hash_uint>::const_iterator hit;
if ((hit = _unordered_snippets.find(id))==_unordered_snippets.end())
return NULL;
else return (*hit).second;
}
void query_context::add_to_unordered_cache_title(search_snippet *sr)
{
std::string lctitle = sr->_title;
if (sr->_title.empty())
return; // do nothing.
miscutil::to_lower(lctitle);
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit=_unordered_snippets_title.find(lctitle.c_str()))!=_unordered_snippets_title.end())
{
// do nothing.
}
else _unordered_snippets_title.insert(std::pair<const char*,search_snippet*>(strdup(lctitle.c_str()),sr));
}
void query_context::remove_from_unordered_cache_title(search_snippet *sr)
{
std::string lctitle = sr->_title;
miscutil::to_lower(lctitle);
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit=_unordered_snippets_title.find(lctitle.c_str()))!=_unordered_snippets_title.end())
{
const char *key = (*hit).first;
_unordered_snippets_title.erase(hit);
free_const(key);
}
}
search_snippet* query_context::get_cached_snippet_title(const char *lctitle)
{
hash_map<const char*,search_snippet*,hash<const char*>,eqstr>::iterator hit;
if ((hit = _unordered_snippets_title.find(lctitle))==_unordered_snippets_title.end())
return NULL;
else return (*hit).second;
}
bool query_context::has_lang(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
std::string &qlang)
{
const char *alang = miscutil::lookup(parameters,"lang");
if (alang)
{
qlang = alang;
miscutil::to_lower(qlang);
return true;
}
else return false;
}
bool query_context::has_query_lang(const std::string &query,
std::string &qlang)
{
if (query.empty() || query[0] != ':') // XXX: could chomp the query.
{
qlang = "";
return false;
}
try
{
qlang = query.substr(1,2); // : + 2 characters for the language.
miscutil::to_lower(qlang);
}
catch (std::exception &e)
{
qlang = "";
}
// check whether the language is known ! -> XXX: language table...
if (iso639::has_code(qlang.c_str()))
{
return true;
}
else
{
errlog::log_error(LOG_LEVEL_INFO,"in query command test: language code not found: %s",qlang.c_str());
qlang = "";
return false;
}
}
// static.
void query_context::detect_query_lang_http(const std::list<const char*> &http_headers,
std::string &lang, std::string &lang_reg)
{
std::list<const char*>::const_iterator sit = http_headers.begin();
while (sit!=http_headers.end())
{
if (miscutil::strncmpic((*sit),"accept-language:",16) == 0)
{
// detect language.
std::string lang_head = (*sit);
size_t pos = lang_head.find_first_of(" ");
if (pos != std::string::npos && pos+6<=lang_head.length() && lang_head[pos+3] == '-')
{
try
{
lang = lang_head.substr(pos+1,2);
lang_reg = lang_head.substr(pos+1,5);
}
catch (std::exception &e)
{
lang = query_context::_default_alang;
lang_reg = query_context::_default_alang_reg; // default.
}
errlog::log_error(LOG_LEVEL_DEBUG,"Query language detection: %s",lang_reg.c_str());
return;
}
else if (pos != std::string::npos && pos+3<=lang_head.length())
{
try
{
lang = lang_head.substr(pos+1,2);
}
catch (std::exception &e)
{
lang = query_context::_default_alang; // default.
}
lang_reg = query_context::lang_forced_region(lang);
errlog::log_error(LOG_LEVEL_DEBUG,"Forced query language region at detection: %s",lang_reg.c_str());
return;
}
}
++sit;
}
lang_reg = query_context::_default_alang_reg; // beware, returning hardcoded default (since config value is most likely "auto").
lang = query_context::_default_alang;
}
std::string query_context::detect_base_url_http(client_state *csp)
{
std::list<const char*> headers = csp->_headers;
// first we try to get base_url from a custom header
std::string base_url;
std::list<const char*>::const_iterator sit = headers.begin();
while (sit!=headers.end())
{
if (miscutil::strncmpic((*sit),"Seeks-Remote-Location:",22) == 0)
{
base_url = (*sit);
size_t pos = base_url.find_first_of(" ");
try
{
base_url = base_url.substr(pos+1);
}
catch (std::exception &e)
{
base_url = "";
break;
}
break;
}
++sit;
}
if (base_url.empty())
{
// if no custom header, we build base_url from the generic Host header
std::list<const char*>::const_iterator sit = headers.begin();
while (sit!=headers.end())
{
if (miscutil::strncmpic((*sit),"Host:",5) == 0)
{
base_url = (*sit);
size_t pos = base_url.find_first_of(" ");
try
{
base_url = base_url.substr(pos+1);
}
catch (std::exception &e)
{
base_url = "";
return base_url;
}
break;
}
++sit;
}
base_url = csp->_http._ssl ? "https://" : "http://" + base_url;
}
return base_url;
}
std::string query_context::assemble_query(const std::string &query,
const std::string &lang)
{
if (!lang.empty())
{
return ":" + lang + " " + query;
}
else return query;
}
void query_context::grab_useful_headers(const std::list<const char*> &http_headers)
{
std::list<const char*>::const_iterator sit = http_headers.begin();
while (sit!=http_headers.end())
{
// user-agent
if (miscutil::strncmpic((*sit),"user-agent:",11) == 0)
{
const char *ua = strdup((*sit));
_useful_http_headers.push_back(ua);
}
else if (miscutil::strncmpic((*sit),"accept-charset:",15) == 0)
{
const char *ac = strdup((*sit));
/* std::string ac_str = "accept-charset: utf-8";
const char *ac = strdup(ac_str.c_str()); */
_useful_http_headers.push_back(ac);
}
else if (miscutil::strncmpic((*sit),"accept:",7) == 0)
{
const char *aa = strdup((*sit));
_useful_http_headers.push_back(aa);
}
// XXX: other useful headers should be detected and stored here.
++sit;
}
}
std::string query_context::lang_forced_region(const std::string &auto_lang)
{
// XXX: in-query language commands force the query language to the search engine.
// As such, we have to decide which region we attach to every of the most common
// language forced queries.
// Evidently, this is not a robust nor fast solution. Full support of locales etc... should
// appear in the future. As for now, this is a simple scheme for a simple need.
// Unsupported languages default to american english, that's how the world is right
// now...
std::string region_lang = query_context::_default_alang_reg; // default.
if (auto_lang == "en")
{
}
else if (auto_lang == "fr")
region_lang = "fr-FR";
else if (auto_lang == "de")
region_lang = "de-DE";
else if (auto_lang == "it")
region_lang = "it-IT";
else if (auto_lang == "es")
region_lang = "es-ES";
else if (auto_lang == "pt")
region_lang = "es-PT"; // so long for Brazil (BR)...
else if (auto_lang == "nl")
region_lang = "nl-NL";
else if (auto_lang == "ja")
region_lang = "ja-JP";
else if (auto_lang == "no")
region_lang = "no-NO";
else if (auto_lang == "pl")
region_lang = "pl-PL";
else if (auto_lang == "ru")
region_lang = "ru-RU";
else if (auto_lang == "ro")
region_lang = "ro-RO";
else if (auto_lang == "sh")
region_lang = "sh-RS"; // Serbia.
else if (auto_lang == "sl")
region_lang = "sl-SL";
else if (auto_lang == "sk")
region_lang = "sk-SK";
else if (auto_lang == "sv")
region_lang = "sv-SE";
else if (auto_lang == "th")
region_lang = "th-TH";
else if (auto_lang == "uk")
region_lang = "uk-UA";
else if (auto_lang == "zh")
region_lang = "zh-CN";
else if (auto_lang == "ko")
region_lang = "ko-KR";
else if (auto_lang == "ar")
region_lang = "ar-EG"; // Egypt, with _NO_ reasons. In most cases, the search engines will decide based on the 'ar' code.
else if (auto_lang == "be")
region_lang = "be-BY";
else if (auto_lang == "bg")
region_lang = "bg-BG";
else if (auto_lang == "bs")
region_lang = "bs-BA";
else if (auto_lang == "cs")
region_lang = "cs-CZ";
else if (auto_lang == "fi")
region_lang = "fi-FI";
else if (auto_lang == "he")
region_lang = "he-IL";
else if (auto_lang == "hi")
region_lang = "hi-IN";
else if (auto_lang == "hr")
region_lang = "hr-HR";
return region_lang;
}
std::string query_context::generate_lang_http_header() const
{
return "accept-language: " + _auto_lang + "," + _auto_lang_reg + ";q=0.5";
}
void query_context::in_query_command_forced_region(std::string &auto_lang,
std::string ®ion_lang)
{
region_lang = query_context::lang_forced_region(auto_lang);
if (region_lang == query_context::_default_alang_reg) // in case we are on the default language.
auto_lang = query_context::_default_alang;
}
void query_context::fillup_engines(const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters,
feeds &engines)
{
const char *eng = miscutil::lookup(parameters,"engines");
if (eng)
{
std::string engines_str = std::string(eng);
std::vector<std::string> vec_engines;
miscutil::tokenize(engines_str,vec_engines,",");
for (size_t i=0; i<vec_engines.size(); i++)
{
std::string engine = vec_engines.at(i);
std::vector<std::string> vec_names;
miscutil::tokenize(engine,vec_names,":");
if (vec_names.size()==1)
engines.add_feed(engine,websearch::_wconfig);
else engines.add_feed(vec_names,
websearch::_wconfig);
}
}
else engines = feeds(websearch::_wconfig->_se_default);
}
void query_context::reset_snippets_personalization_flags()
{
std::vector<search_snippet*>::iterator vit = _cached_snippets.begin();
while (vit!=_cached_snippets.end())
{
if ((*vit)->_personalized)
{
// XXX: change of behavior.
// may want to remove seeks results when using a user db.
(*vit)->_personalized = false;
if ((*vit)->_engine.count() == 1
&& (*vit)->_engine.has_feed("seeks"))
{
remove_from_unordered_cache((*vit)->_id);
remove_from_unordered_cache_title((*vit));
delete (*vit);
vit = _cached_snippets.erase(vit);
continue;
}
else if ((*vit)->_engine.has_feed("seeks"))
(*vit)->_engine.remove_feed("seeks");
(*vit)->_meta_rank = (*vit)->_engine.size(); //TODO: wrong, every feed_parser may refer to several urls.
//TODO: don't reset in cache.
(*vit)->_seeks_rank = 0;
(*vit)->bing_yahoo_us_merge();
(*vit)->_npeers = 0;
(*vit)->_hits = 0;
}
else (*vit)->_seeks_rank = 0; // reset.
++vit;
}
_npeers = 0; // reset query context peers.
}
} /* end of namespace. */
|
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "IncrementalRedstoneSimulator.h"
#include "BoundingBox.h"
#include "../BlockEntities/RedstonePoweredEntity.h"
#include "../BlockEntities/ChestEntity.h"
#include "../BlockEntities/CommandBlockEntity.h"
#include "../Entities/Pickup.h"
#include "../Blocks/BlockTorch.h"
#include "../Blocks/BlockDoor.h"
#include "../Blocks/BlockButton.h"
#include "../Blocks/BlockLever.h"
#include "../Blocks/BlockPiston.h"
#include "../Blocks/BlockTripwireHook.h"
cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulator(cWorld & a_World) :
super(a_World),
m_RedstoneSimulatorChunkData(),
m_PoweredBlocks(),
m_LinkedPoweredBlocks(),
m_SimulatedPlayerToggleableBlocks(),
m_RepeatersDelayList(),
m_Chunk()
{
}
cIncrementalRedstoneSimulator::~cIncrementalRedstoneSimulator()
{
}
void cIncrementalRedstoneSimulator::RedstoneAddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk, cChunk * a_OtherChunk)
{
if ((a_Chunk == NULL) || !a_Chunk->IsValid())
{
return;
}
else if ((a_BlockY < 0) || (a_BlockY > cChunkDef::Height))
{
return;
}
// We may be called with coordinates in a chunk that is not the first chunk parameter
// In that case, the actual chunk (which the coordinates are in), will be passed as the second parameter
// Use that Chunk pointer to get a relative position
int RelX = 0;
int RelZ = 0;
BLOCKTYPE Block;
NIBBLETYPE Meta;
if (a_OtherChunk != NULL)
{
RelX = a_BlockX - a_OtherChunk->GetPosX() * cChunkDef::Width;
RelZ = a_BlockZ - a_OtherChunk->GetPosZ() * cChunkDef::Width;
a_OtherChunk->GetBlockTypeMeta(RelX, a_BlockY, RelZ, Block, Meta);
// If a_OtherChunk is passed (not NULL), it is the chunk that had a block change, and a_Chunk will be the neighbouring chunk of that block
// Because said neighbouring chunk does not know of this change but still needs to update its redstone, we set it to dirty
a_Chunk->SetIsRedstoneDirty(true);
}
else
{
RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width;
RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width;
a_Chunk->GetBlockTypeMeta(RelX, a_BlockY, RelZ, Block, Meta);
}
// Every time a block is changed (AddBlock called), we want to go through all lists and check to see if the coordiantes stored within are still valid
// Checking only when a block is changed, as opposed to every tick, also improves performance
PoweredBlocksList * PoweredBlocks = a_Chunk->GetRedstoneSimulatorPoweredBlocksList();
for (PoweredBlocksList::iterator itr = PoweredBlocks->begin(); itr != PoweredBlocks->end();)
{
if (!itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
++itr;
continue;
}
if (!IsPotentialSource(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from powered blocks list as it no longer connected to a source", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = PoweredBlocks->erase(itr);
continue;
}
else if (
// Changeable sources
((Block == E_BLOCK_REDSTONE_WIRE) && (Meta == 0)) ||
((Block == E_BLOCK_LEVER) && !IsLeverOn(Meta)) ||
((Block == E_BLOCK_DETECTOR_RAIL) && ((Meta & 0x08) == 0)) ||
(((Block == E_BLOCK_STONE_BUTTON) || (Block == E_BLOCK_WOODEN_BUTTON)) && (!IsButtonOn(Meta))) ||
((Block == E_BLOCK_TRIPWIRE_HOOK) && ((Meta & 0x08) == 0))
)
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from powered blocks list due to present/past metadata mismatch", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = PoweredBlocks->erase(itr);
continue;
}
++itr;
}
LinkedBlocksList * LinkedPoweredBlocks = a_Chunk->GetRedstoneSimulatorLinkedBlocksList();
// We loop through all values (insteading of breaking out at the first) to make sure everything is gone, as there can be multiple SourceBlock entries for one AddBlock coordinate
for (LinkedBlocksList::iterator itr = LinkedPoweredBlocks->begin(); itr != LinkedPoweredBlocks->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
if (!IsPotentialSource(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list as it is no longer connected to a source", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
else if (
// Things that can send power through a block but which depends on meta
((Block == E_BLOCK_REDSTONE_WIRE) && (Meta == 0)) ||
((Block == E_BLOCK_LEVER) && !IsLeverOn(Meta)) ||
(((Block == E_BLOCK_STONE_BUTTON) || (Block == E_BLOCK_WOODEN_BUTTON)) && (!IsButtonOn(Meta)))
)
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list due to present/past metadata mismatch", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
}
else if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
if (!IsViableMiddleBlock(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list as it is no longer powered through a valid middle block", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
}
++itr;
}
SimulatedPlayerToggleableList * SimulatedPlayerToggleableBlocks = a_Chunk->GetRedstoneSimulatorSimulatedPlayerToggleableList();
for (SimulatedPlayerToggleableList::iterator itr = SimulatedPlayerToggleableBlocks->begin(); itr != SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
if (!IsAllowedBlock(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from toggleable simulated list as it is no longer redstone", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z);
SimulatedPlayerToggleableBlocks->erase(itr);
break;
}
}
RepeatersDelayList * RepeatersDelayList = a_Chunk->GetRedstoneSimulatorRepeatersDelayList();
for (RepeatersDelayList::iterator itr = RepeatersDelayList->begin(); itr != RepeatersDelayList->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
if ((Block != E_BLOCK_REDSTONE_REPEATER_ON) && (Block != E_BLOCK_REDSTONE_REPEATER_OFF))
{
RepeatersDelayList->erase(itr);
break;
}
}
if (a_OtherChunk != NULL)
{
// DO NOT touch our chunk's data structure if we are being called with coordinates from another chunk - this one caused me massive grief :P
return;
}
cRedstoneSimulatorChunkData * RedstoneSimulatorChunkData = a_Chunk->GetRedstoneSimulatorData();
for (cRedstoneSimulatorChunkData::iterator itr = RedstoneSimulatorChunkData->begin(); itr != RedstoneSimulatorChunkData->end(); ++itr)
{
if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) // We are at an entry matching the current (changed) block
{
if (!IsAllowedBlock(Block))
{
itr->DataTwo = true; // The new blocktype is not redstone; it must be queued to be removed from this list
}
else
{
itr->DataTwo = false;
itr->Data = Block; // Update block information
}
return;
}
}
if (!IsAllowedBlock(Block))
{
return;
}
for (cRedstoneSimulatorChunkData::iterator itr = a_Chunk->GetRedstoneSimulatorQueuedData()->begin(); itr != a_Chunk->GetRedstoneSimulatorQueuedData()->end(); ++itr)
{
if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ))
{
// Can't have duplicates in here either, in case something adds the block again before the structure can written to the main chunk data
return;
}
}
a_Chunk->GetRedstoneSimulatorQueuedData()->push_back(cCoordWithBlockAndBool(RelX, a_BlockY, RelZ, Block, false));
}
void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)
{
m_RedstoneSimulatorChunkData = a_Chunk->GetRedstoneSimulatorData();
if (m_RedstoneSimulatorChunkData->empty() && a_Chunk->GetRedstoneSimulatorQueuedData()->empty())
{
return;
}
m_RedstoneSimulatorChunkData->insert(m_RedstoneSimulatorChunkData->end(), a_Chunk->GetRedstoneSimulatorQueuedData()->begin(), a_Chunk->GetRedstoneSimulatorQueuedData()->end());
a_Chunk->GetRedstoneSimulatorQueuedData()->clear();
m_PoweredBlocks = a_Chunk->GetRedstoneSimulatorPoweredBlocksList();
m_RepeatersDelayList = a_Chunk->GetRedstoneSimulatorRepeatersDelayList();
m_SimulatedPlayerToggleableBlocks = a_Chunk->GetRedstoneSimulatorSimulatedPlayerToggleableList();
m_LinkedPoweredBlocks = a_Chunk->GetRedstoneSimulatorLinkedBlocksList();
m_Chunk = a_Chunk;
bool ShouldUpdateSimulateOnceBlocks = false;
if (a_Chunk->IsRedstoneDirty())
{
// Simulate the majority of devices only if something (blockwise or power-wise) has changed
// Make sure to allow the chunk to resimulate after the initial run if there was a power change (ShouldUpdateSimulateOnceBlocks helps to do this)
a_Chunk->SetIsRedstoneDirty(false);
ShouldUpdateSimulateOnceBlocks = true;
}
HandleRedstoneRepeaterDelays();
for (cRedstoneSimulatorChunkData::iterator dataitr = m_RedstoneSimulatorChunkData->begin(); dataitr != m_RedstoneSimulatorChunkData->end();)
{
if (dataitr->DataTwo)
{
dataitr = m_RedstoneSimulatorChunkData->erase(dataitr);
continue;
}
switch (dataitr->Data)
{
case E_BLOCK_DAYLIGHT_SENSOR: HandleDaylightSensor(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRIPWIRE: HandleTripwire(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRIPWIRE_HOOK: HandleTripwireHook(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_WOODEN_PRESSURE_PLATE:
case E_BLOCK_STONE_PRESSURE_PLATE:
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
{
HandlePressurePlate(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
default: break;
}
if (ShouldUpdateSimulateOnceBlocks)
{
switch (dataitr->Data)
{
case E_BLOCK_REDSTONE_WIRE: HandleRedstoneWire(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_COMMAND_BLOCK: HandleCommandBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_NOTE_BLOCK: HandleNoteBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_BLOCK_OF_REDSTONE: HandleRedstoneBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_LEVER: HandleRedstoneLever(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TNT: HandleTNT(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRAPDOOR: HandleTrapdoor(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRAPPED_CHEST: HandleTrappedChest(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_DETECTOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
HandleRail(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_WOODEN_DOOR:
case E_BLOCK_IRON_DOOR:
{
HandleDoor(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_LAMP_OFF:
case E_BLOCK_REDSTONE_LAMP_ON:
{
HandleRedstoneLamp(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_DISPENSER:
case E_BLOCK_DROPPER:
{
HandleDropSpenser(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_PISTON:
case E_BLOCK_STICKY_PISTON:
{
HandlePiston(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_REPEATER_OFF:
case E_BLOCK_REDSTONE_REPEATER_ON:
{
HandleRedstoneRepeater(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_REDSTONE_TORCH_OFF:
case E_BLOCK_REDSTONE_TORCH_ON:
{
HandleRedstoneTorch(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_STONE_BUTTON:
case E_BLOCK_WOODEN_BUTTON:
{
HandleRedstoneButton(dataitr->x, dataitr->y, dataitr->z);
break;
}
default: break;
}
}
++dataitr;
}
}
void cIncrementalRedstoneSimulator::WakeUp(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk)
{
if (AreCoordsOnChunkBoundary(a_BlockX, a_BlockY, a_BlockZ))
{
// On a chunk boundary, alert all four sides (i.e. at least one neighbouring chunk)
AddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk);
// Pass the original coordinates, because when adding things to our simulator lists, we get the chunk that they are in, and therefore any updates need to preseve their position
// RedstoneAddBlock to pass both the neighbouring chunk and the chunk which the coordinates are in and +- 2 in GetNeighbour() to accomodate for LinkedPowered blocks being 2 away from chunk boundaries
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX - 2, a_BlockZ), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX + 2, a_BlockZ), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ - 2), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ + 2), a_Chunk);
return;
}
// Not on boundary, just alert this chunk for speed
AddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk);
}
void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
static const struct // Define which directions the torch can power
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0},
{-1, 0, 0},
{ 0, 0, 1},
{ 0, 0, -1},
{ 0, 1, 0},
} ;
if (a_MyState == E_BLOCK_REDSTONE_TORCH_ON)
{
// Check if the block the torch is on is powered
int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
cChunk * Neighbour = m_Chunk->GetRelNeighborChunk(X, Z);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
if (AreCoordsDirectlyPowered(X, Y, Z, Neighbour))
{
// There was a match, torch goes off
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_OFF, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
return;
}
// Torch still on, make all 4(X, Z) + 1(Y) sides powered
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (i + 1 < ARRAYCOUNT(gCrossCoords)) // Sides of torch, not top (top is last)
{
if (
IsMechanism(Type) && // Is it a mechanism? Not block/other torch etc.
(!Vector3i(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z).Equals(Vector3i(X, Y, Z))) // CAN'T power block is that it is on
)
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
else
{
// Top side, power whatever is there, including blocks
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Power all blocks surrounding block above torch
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YP);
}
}
if (m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) != 0x5) // Is torch standing on ground? If NOT (i.e. on wall), power block beneath
{
BLOCKTYPE Type = m_Chunk->GetBlock(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ);
if (IsMechanism(Type)) // Still can't make a normal block powered though!
{
SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
}
else
{
// Check if the block the torch is on is powered
int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
cChunk * Neighbour = m_Chunk->GetRelNeighborChunk(X, Z);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
// See if off state torch can be turned on again
if (AreCoordsDirectlyPowered(X, Y, Z, Neighbour))
{
return; // Something matches, torch still powered
}
// Block torch on not powered, can be turned on again!
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_ON, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ); // Set self as powered
}
void cIncrementalRedstoneSimulator::HandleRedstoneLever(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (IsLeverOn(Meta))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
eBlockFace Dir = cBlockLeverHandler::BlockMetaDataToBlockFace(Meta);
Dir = ReverseBlockFace(Dir);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Dir);
}
}
void cIncrementalRedstoneSimulator::HandleFenceGate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
NIBBLETYPE MetaData = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
if ((MetaData & 0x4) == 0)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData | 0x4);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
if ((MetaData & 0x4) != 0)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData & ~0x04);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneButton(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (IsButtonOn(Meta))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
eBlockFace Dir = cBlockButtonHandler::BlockMetaDataToBlockFace(Meta);
Dir = ReverseBlockFace(Dir);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Dir);
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
static const struct // Define which directions the wire can receive power from
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0}, /* Wires on same level start */
{-1, 0, 0},
{ 0, 0, 1},
{ 0, 0, -1}, /* Wires on same level stop */
{ 1, 1, 0}, /* Wires one higher, surrounding self start */
{-1, 1, 0},
{ 0, 1, 1},
{ 0, 1, -1}, /* Wires one higher, surrounding self stop */
{ 1, -1, 0}, /* Wires one lower, surrounding self start */
{-1, -1, 0},
{ 0, -1, 1},
{ 0, -1, -1}, /* Wires one lower, surrounding self stop */
} ;
static const struct // Define which directions the wire will check for repeater prescence
{
int x, y, z;
} gSideCoords[] =
{
{ 1, 0, 0 },
{-1, 0, 0 },
{ 0, 0, 1 },
{ 0, 0, -1 },
{ 0, 1, 0 },
};
// Check to see if directly beside a power source
unsigned char MyPower;
if (!IsWirePowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower))
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0);
m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
return;
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
if (MyPower < 1)
{
return;
}
MyPower--;
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) // Loop through all directions to transfer or receive power
{
if ((i >= 4) && (i <= 7)) // If we are currently checking for wire surrounding ourself one block above...
{
BLOCKTYPE Type = 0;
if (a_RelBlockY + 1 >= cChunkDef::Height)
{
continue;
}
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, Type))
{
continue;
}
if (cBlockInfo::IsSolid(Type)) // If there is something solid above us (wire cut off)...
{
continue; // We don't receive power from that wire
}
}
else if ((i >= 8) && (i <= 11)) // See above, but this is for wire below us
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (cBlockInfo::IsSolid(Type))
{
continue;
}
}
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (Type == E_BLOCK_REDSTONE_WIRE)
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
for (size_t i = 0; i < ARRAYCOUNT(gSideCoords); i++) // Look for repeaters immediately surrounding self and try to power them
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, Type))
{
continue;
}
if (Type == E_BLOCK_REDSTONE_REPEATER_OFF)
{
SetBlockPowered(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
// Wire still powered, power blocks beneath
SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, MyPower);
switch (GetWireDirection(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
case REDSTONE_NONE:
{
SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_X_POS:
{
SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
break;
}
case REDSTONE_X_NEG:
{
SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
break;
}
case REDSTONE_Z_POS:
{
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_Z_NEG:
{
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
break;
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
/* Repeater Orientation Mini Guide:
===================================
|
| Z Axis
V
X Axis ---->
Repeater directions, values from a cWorld::GetBlockMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) lookup:
East (Right) (X+): 0x1
West (Left) (X-): 0x3
North (Up) (Z-): 0x2
South (Down) (Z+): 0x0
// TODO: Add E_META_XXX enum entries for all meta values and update project with them
Sun rises from East (X+)
*/
// Create a variable holding my meta to avoid multiple lookups.
NIBBLETYPE a_Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
bool IsOn = (a_MyState == E_BLOCK_REDSTONE_REPEATER_ON);
if (!IsRepeaterLocked(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta)) // If we're locked, change nothing. Otherwise:
{
bool IsSelfPowered = IsRepeaterPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta);
if (IsSelfPowered && !IsOn) // Queue a power change if powered, but not on and not locked.
{
QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, true);
}
else if (!IsSelfPowered && IsOn) // Queue a power change if unpowered, on, and not locked.
{
QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneRepeaterDelays()
{
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end();)
{
if (itr->a_ElapsedTicks >= itr->a_DelayTicks) // Has the elapsed ticks reached the target ticks?
{
int RelBlockX = itr->a_RelBlockPos.x;
int RelBlockY = itr->a_RelBlockPos.y;
int RelBlockZ = itr->a_RelBlockPos.z;
BLOCKTYPE Block;
NIBBLETYPE Meta;
m_Chunk->GetBlockTypeMeta(RelBlockX, RelBlockY, RelBlockZ, Block, Meta);
if (itr->ShouldPowerOn)
{
if (Block != E_BLOCK_REDSTONE_REPEATER_ON) // For performance
{
m_Chunk->SetBlock(itr->a_RelBlockPos, E_BLOCK_REDSTONE_REPEATER_ON, Meta);
}
switch (Meta & 0x3) // We only want the direction (bottom) bits
{
case 0x0:
{
SetBlockPowered(RelBlockX, RelBlockY, RelBlockZ - 1, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_ZM);
break;
}
case 0x1:
{
SetBlockPowered(RelBlockX + 1, RelBlockY, RelBlockZ, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_XP);
break;
}
case 0x2:
{
SetBlockPowered(RelBlockX, RelBlockY, RelBlockZ + 1, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_ZP);
break;
}
case 0x3:
{
SetBlockPowered(RelBlockX - 1, RelBlockY, RelBlockZ, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_XM);
break;
}
}
}
else if (Block != E_BLOCK_REDSTONE_REPEATER_OFF)
{
m_Chunk->SetBlock(RelBlockX, RelBlockY, RelBlockZ, E_BLOCK_REDSTONE_REPEATER_OFF, Meta);
}
itr = m_RepeatersDelayList->erase(itr);
}
else
{
LOGD("Incremented a repeater @ {%i %i %i} | Elapsed ticks: %i | Target delay: %i", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z, itr->a_ElapsedTicks, itr->a_DelayTicks);
itr->a_ElapsedTicks++;
itr++;
}
}
}
void cIncrementalRedstoneSimulator::HandlePiston(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (IsPistonPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x7)) // We only want the bottom three bits (4th controls extended-ness)
{
cBlockPistonHandler::ExtendPiston(BlockX, a_RelBlockY, BlockZ, &m_World);
}
else
{
cBlockPistonHandler::RetractPiston(BlockX, a_RelBlockY, BlockZ, &m_World);
}
}
void cIncrementalRedstoneSimulator::HandleDropSpenser(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToDropSpenser :
public cRedstonePoweredCallback
{
bool m_IsPowered;
public:
cSetPowerToDropSpenser(bool a_IsPowered) : m_IsPowered(a_IsPowered) {}
virtual bool Item(cRedstonePoweredEntity * a_DropSpenser) override
{
a_DropSpenser->SetRedstonePower(m_IsPowered);
return false;
}
} DrSpSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithRedstonePoweredEntityAt(BlockX, a_RelBlockY, BlockZ, DrSpSP);
}
void cIncrementalRedstoneSimulator::HandleRedstoneLamp(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
if (a_MyState == E_BLOCK_REDSTONE_LAMP_OFF)
{
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_ON, 0);
}
}
else
{
if (!AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_OFF, 0);
}
}
}
void cIncrementalRedstoneSimulator::HandleTNT(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->BroadcastSoundEffect("game.tnt.primed", (double)BlockX, (double)a_RelBlockY, (double)BlockZ, 0.5f, 0.6f);
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_AIR, 0);
m_World.SpawnPrimedTNT(BlockX + 0.5, a_RelBlockY + 0.5, BlockZ + 0.5); // 80 ticks to boom
}
}
void cIncrementalRedstoneSimulator::HandleDoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
if (!cBlockDoorHandler::IsOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ))
{
cBlockDoorHandler::SetOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ, true);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
if (cBlockDoorHandler::IsOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ))
{
cBlockDoorHandler::SetOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ, false);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleCommandBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToCommandBlock :
public cCommandBlockCallback
{
bool m_IsPowered;
public:
cSetPowerToCommandBlock(bool a_IsPowered) : m_IsPowered(a_IsPowered) {}
virtual bool Item(cCommandBlockEntity * a_CommandBlock) override
{
a_CommandBlock->SetRedstonePower(m_IsPowered);
return false;
}
} CmdBlockSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithCommandBlockAt(BlockX, a_RelBlockY, BlockZ, CmdBlockSP);
}
void cIncrementalRedstoneSimulator::HandleRail(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
switch (a_MyType)
{
case E_BLOCK_DETECTOR_RAIL:
{
if ((m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x08) == 0x08)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_MyType);
}
break;
}
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) | 0x08);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x07);
}
break;
}
default: LOGD("Unhandled type of rail in %s", __FUNCTION__);
}
}
void cIncrementalRedstoneSimulator::HandleTrapdoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, true);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, false);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
bool m_bAreCoordsPowered = AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (m_bAreCoordsPowered)
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
class cSetPowerToNoteBlock :
public cRedstonePoweredCallback
{
public:
cSetPowerToNoteBlock() {}
virtual bool Item(cRedstonePoweredEntity * a_NoteBlock) override
{
a_NoteBlock->SetRedstonePower(true);
return false;
}
} NoteBlockSP;
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithRedstonePoweredEntityAt(BlockX, a_RelBlockY, BlockZ, NoteBlockSP);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX, BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(BlockX, BlockZ, ChunkX, ChunkZ);
if (!m_World.IsChunkLighted(ChunkX, ChunkZ))
{
m_World.QueueLightChunk(ChunkX, ChunkZ);
}
else
{
if (m_Chunk->GetTimeAlteredLight(m_World.GetBlockSkyLight(BlockX, a_RelBlockY + 1, BlockZ)) > 8)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
WakeUp(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
}
void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
switch (a_MyType)
{
case E_BLOCK_STONE_PRESSURE_PLATE:
{
// MCS feature - stone pressure plates can only be triggered by players :D
cPlayer * a_Player = m_World.FindClosestPlayer(Vector3f(BlockX + 0.5f, (float)a_RelBlockY, BlockZ + 0.5f), 0.5f, false);
if (a_Player != NULL)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x1);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x0);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_NumberOfEntities(0),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_NumberOfEntities++;
}
return false;
}
bool GetPowerLevel(unsigned char & a_PowerLevel) const
{
a_PowerLevel = std::min(m_NumberOfEntities, MAX_POWER_LEVEL);
return (a_PowerLevel > 0);
}
protected:
int m_NumberOfEntities;
int m_X;
int m_Y;
int m_Z;
};
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
unsigned char Power;
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.GetPowerLevel(Power))
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_NumberOfEntities(0),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_NumberOfEntities++;
}
return false;
}
bool GetPowerLevel(unsigned char & a_PowerLevel) const
{
a_PowerLevel = std::min((int)ceil(m_NumberOfEntities / 10.f), MAX_POWER_LEVEL);
return (a_PowerLevel > 0);
}
protected:
int m_NumberOfEntities;
int m_X;
int m_Y;
int m_Z;
};
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
unsigned char Power;
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.GetPowerLevel(Power))
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_WOODEN_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_FoundEntity(false),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_FoundEntity = true;
return true; // Break out, we only need to know for plates that at least one entity is on top
}
return false;
}
bool FoundEntity(void) const
{
return m_FoundEntity;
}
protected:
bool m_FoundEntity;
int m_X;
int m_Y;
int m_Z;
} ;
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.FoundEntity())
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
default:
{
LOGD("Unimplemented pressure plate type %s in cRedstoneSimulator", ItemToFullString(a_MyType).c_str());
break;
}
}
}
void cIncrementalRedstoneSimulator::HandleTripwireHook(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
int RelX = a_RelBlockX, RelZ = a_RelBlockZ;
bool FoundActivated = false;
eBlockFace FaceToGoTowards = cBlockTripwireHookHandler::MetadataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
for (int i = 0; i < 40; ++i) // Tripwires can be connected up to 40 blocks
{
BLOCKTYPE Type;
NIBBLETYPE Meta;
AddFaceDirection(RelX, a_RelBlockY, RelZ, FaceToGoTowards);
m_Chunk->UnboundedRelGetBlock(RelX, a_RelBlockY, RelZ, Type, Meta);
if (Type == E_BLOCK_TRIPWIRE)
{
if (Meta == 0x1)
{
FoundActivated = true;
}
}
else if (Type == E_BLOCK_TRIPWIRE_HOOK)
{
if (ReverseBlockFace(cBlockTripwireHookHandler::MetadataToDirection(Meta)) == FaceToGoTowards)
{
// Other hook facing in opposite direction - circuit completed!
break;
}
else
{
// Tripwire hook not connected at all, AND away all the power state bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x3);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
return;
}
}
else
{
// Tripwire hook not connected at all, AND away all the power state bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x3);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
return;
}
}
if (FoundActivated)
{
// Connected and activated, set the 3rd and 4th highest bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) | 0xC);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
// Connected but not activated, AND away the highest bit
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, (m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x7) | 0x4);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
void cIncrementalRedstoneSimulator::HandleTrappedChest(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cGetTrappedChestPlayers :
public cChestCallback
{
public:
cGetTrappedChestPlayers(void) :
m_NumberOfPlayers(0)
{
}
virtual bool Item(cChestEntity * a_Chest) override
{
ASSERT(a_Chest->GetBlockType() == E_BLOCK_TRAPPED_CHEST);
m_NumberOfPlayers = a_Chest->GetNumberOfPlayers();
return (m_NumberOfPlayers <= 0);
}
unsigned char GetPowerLevel(void) const
{
return std::min(m_NumberOfPlayers, MAX_POWER_LEVEL);
}
private:
int m_NumberOfPlayers;
} GTCP;
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
if (m_Chunk->DoWithChestAt(BlockX, a_RelBlockY, BlockZ, GTCP))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, GTCP.GetPowerLevel());
}
else
{
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
void cIncrementalRedstoneSimulator::HandleTripwire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
class cTripwireCallback :
public cEntityCallback
{
public:
cTripwireCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_FoundEntity(false),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
cBoundingBox bbWire(m_X, m_X + 1, m_Y, m_Y + 0.1, m_Z, m_Z + 1);
cBoundingBox bbEntity(a_Entity->GetPosition(), a_Entity->GetWidth() / 2, a_Entity->GetHeight());
if (bbEntity.DoesIntersect(bbWire))
{
m_FoundEntity = true;
return true; // One entity is sufficient to trigger the wire
}
return false;
}
bool FoundEntity(void) const
{
return m_FoundEntity;
}
protected:
bool m_FoundEntity;
int m_X;
int m_Y;
int m_Z;
};
cTripwireCallback TripwireCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), TripwireCallback);
if (TripwireCallback.FoundEntity())
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x1);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x0);
}
}
bool cIncrementalRedstoneSimulator::AreCoordsDirectlyPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, cChunk * a_Chunk)
{
// Torches want to access neighbour's data when on a wall, hence the extra chunk parameter
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->end(); ++itr) // Check powered list
{
if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
}
return false;
}
bool cIncrementalRedstoneSimulator::AreCoordsLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
}
return false;
}
bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Repeaters cannot be powered by any face except their back; verify that this is true for a source
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
// Flip the coords to check the back of the repeater
if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
}
return false; // Couldn't find power source behind repeater
}
bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x3) // We only want the 'direction' part of our metadata
{
// If the repeater is looking up or down (If parallel to the Z axis)
case 0x0:
case 0x2:
{
// Check if eastern(right) neighbor is a powered on repeater who is facing us
BLOCKTYPE Block = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON)) // Is right neighbor a powered repeater?
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x3) { return true; } // If so, I am latched/locked
}
// Check if western(left) neighbor is a powered on repeater who is facing us
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX -1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x1) { return true; } // If so, I am latched/locked
}
break;
}
// If the repeater is looking left or right (If parallel to the x axis)
case 0x1:
case 0x3:
{
// Check if southern(down) neighbor is a powered on repeater who is facing us
BLOCKTYPE Block = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1) & 0x3;
if (OtherRepeaterDir == 0x0) { return true; } // If so, am latched/locked
}
// Check if northern(up) neighbor is a powered on repeater who is facing us
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1) & 0x3;
if (OtherRepeaterDir == 0x2) { return true; } // If so, I am latched/locked
}
break;
}
}
return false; // None of the checks succeeded, I am not a locked repeater
}
bool cIncrementalRedstoneSimulator::IsPistonPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Pistons cannot be powered through their front face; this function verifies that a source meets this requirement
eBlockFace Face = cBlockPistonHandler::MetaDataToDirection(a_Meta);
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face);
if (!itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face, true);
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face);
if (!itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face, true);
}
return false; // Source was in front of the piston's front face
}
bool cIncrementalRedstoneSimulator::IsWirePowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char & a_PowerLevel)
{
a_PowerLevel = 0;
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr) // Check powered list
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
a_PowerLevel = std::max(itr->a_PowerLevel, a_PowerLevel); // Get the highest power level (a_PowerLevel is initialised already and there CAN be multiple levels for one block)
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
BLOCKTYPE Type = E_BLOCK_AIR;
int RelSourceX = itr->a_SourcePos.x - m_Chunk->GetPosX() * cChunkDef::Width;
int RelSourceZ = itr->a_SourcePos.z - m_Chunk->GetPosZ() * cChunkDef::Width;
if (!m_Chunk->UnboundedRelGetBlockType(RelSourceX, itr->a_SourcePos.y, RelSourceZ, Type) || (Type == E_BLOCK_REDSTONE_WIRE))
{
continue;
}
a_PowerLevel = std::max(itr->a_PowerLevel, a_PowerLevel);
}
return (a_PowerLevel != 0); // Answer the inital question: is the wire powered?
}
bool cIncrementalRedstoneSimulator::AreCoordsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool IsCurrentStatePowered)
{
for (SimulatedPlayerToggleableList::const_iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (itr->WasLastStatePowered != IsCurrentStatePowered) // Was the last power state different to the current?
{
return false; // It was, coordinates are no longer simulated
}
else
{
return true; // It wasn't, don't resimulate block, and allow players to toggle
}
}
}
return false; // Block wasn't even in the list, not simulated
}
void cIncrementalRedstoneSimulator::SetDirectionLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, char a_Direction, unsigned char a_PowerLevel)
{
BLOCKTYPE MiddleBlock = 0;
switch (a_Direction)
{
case BLOCK_FACE_XM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX - 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_XP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX + 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
default:
{
ASSERT(!"Unhandled face direction when attempting to set blocks as linked powered!"); // Zombies, that wasn't supposed to happen...
break;
}
}
}
void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char a_PowerLevel)
{
static const struct
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0 },
{ -1, 0, 0 },
{ 0, 0, 1 },
{ 0, 0, -1 },
{ 0, 1, 0 },
{ 0, -1, 0 }
};
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) // Loop through struct to power all directions
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_PowerLevel);
}
}
void cIncrementalRedstoneSimulator::SetBlockPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ, unsigned char a_PowerLevel)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
cChunk * Neighbour = m_Chunk->GetRelNeighborChunkAdjustCoords(a_RelBlockX, a_RelBlockZ); // Adjust coordinates for the later call using these values
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
PoweredBlocksList * Powered = Neighbour->GetRedstoneSimulatorPoweredBlocksList(); // We need to insert the value into the chunk who owns the block position
for (PoweredBlocksList::iterator itr = Powered->begin(); itr != Powered->end(); ++itr)
{
if (
itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
)
{
// Check for duplicates, update power level, don't add a new listing
itr->a_PowerLevel = a_PowerLevel;
return;
}
}
// No need to get neighbouring chunk as we can guarantee that when something is powering us, the entry will be in our chunk
// TODO: on C++11 support, change this to a llama function pased to a std::remove_if
for (PoweredBlocksList::iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (
itr->a_BlockPos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ)) &&
itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
(m_Chunk->GetBlock(a_RelSourceX, a_RelSourceY, a_RelSourceZ) == E_BLOCK_REDSTONE_WIRE)
)
{
BLOCKTYPE Block;
NIBBLETYPE Meta;
Neighbour->GetBlockTypeMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Block, Meta);
if (Block == E_BLOCK_REDSTONE_WIRE)
{
if (Meta < a_PowerLevel)
{
m_PoweredBlocks->erase(itr); // Powering source with higher power level, allow it
break;
}
else
{
// Powered wires try to power their source - don't let them!
return;
}
}
}
}
sPoweredBlocks RC;
RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Powered->push_back(RC);
Neighbour->SetIsRedstoneDirty(true);
m_Chunk->SetIsRedstoneDirty(true);
}
void cIncrementalRedstoneSimulator::SetBlockLinkedPowered(
int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ,
int a_RelMiddleX, int a_RelMiddleY, int a_RelMiddleZ,
int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ,
BLOCKTYPE a_MiddleBlock, unsigned char a_PowerLevel
)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int MiddleX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelMiddleX;
int MiddleZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelMiddleZ;
int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
if (!IsViableMiddleBlock(a_MiddleBlock))
{
return;
}
cChunk * Neighbour = m_Chunk->GetNeighborChunk(BlockX, BlockZ);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
LinkedBlocksList * Linked = Neighbour->GetRedstoneSimulatorLinkedBlocksList();
for (LinkedBlocksList::iterator itr = Linked->begin(); itr != Linked->end(); ++itr) // Check linked powered list
{
if (
itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
itr->a_MiddlePos.Equals(Vector3i(MiddleX, a_RelMiddleY, MiddleZ)) &&
itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
)
{
// Check for duplicates, update power level, don't add a new listing
itr->a_PowerLevel = a_PowerLevel;
return;
}
}
sLinkedPoweredBlocks RC;
RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
RC.a_MiddlePos = Vector3i(MiddleX, a_RelMiddleY, MiddleZ);
RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Linked->push_back(RC);
Neighbour->SetIsRedstoneDirty(true);
m_Chunk->SetIsRedstoneDirty(true);
}
void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool WasLastStatePowered)
{
for (SimulatedPlayerToggleableList::iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
continue;
}
if (itr->WasLastStatePowered != WasLastStatePowered)
{
// If power states different, update listing
itr->WasLastStatePowered = WasLastStatePowered;
return;
}
else
{
// If states the same, just ignore
return;
}
}
// We have arrive here; no block must be in list - add one
sSimulatedPlayerToggleableList RC;
RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
RC.WasLastStatePowered = WasLastStatePowered;
m_SimulatedPlayerToggleableBlocks->push_back(RC);
}
bool cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn)
{
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end(); ++itr)
{
if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (ShouldPowerOn == itr->ShouldPowerOn) // We are queued already for the same thing, don't replace entry
{
return false;
}
// Already in here (normal to allow repeater to continue on powering and updating blocks in front) - just update info and quit
itr->a_DelayTicks = (((a_Meta & 0xC) >> 0x2) + 1) * 2; // See below for description
itr->a_ElapsedTicks = 0;
itr->ShouldPowerOn = ShouldPowerOn;
return false;
}
}
// Self not in list, add self to list
sRepeatersDelayList RC;
RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Gets the top two bits (delay time), shifts them into the lower two bits, and adds one (meta 0 = 1 tick; 1 = 2 etc.)
// Multiply by 2 because in MCS, 1 redstone tick = 1 world tick, but in Vanilla, 1 redstone tick = 2 world ticks, and we need to maintain compatibility
RC.a_DelayTicks = (((a_Meta & 0xC) >> 0x2) + 1) * 2;
RC.a_ElapsedTicks = 0;
RC.ShouldPowerOn = ShouldPowerOn;
m_RepeatersDelayList->push_back(RC);
return true;
}
void cIncrementalRedstoneSimulator::SetSourceUnpowered(int a_SourceX, int a_SourceY, int a_SourceZ, cChunk * a_Chunk, bool a_IsFirstCall)
{
if (!a_IsFirstCall) // The neighbouring chunks passed when this parameter is false may be invalid
{
if ((a_Chunk == NULL) || !a_Chunk->IsValid())
{
return;
}
}
// TODO: on C++11 support, change both of these to llama functions pased to a std::remove_if
for (PoweredBlocksList::iterator itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ)))
{
itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->erase(itr);
a_Chunk->SetIsRedstoneDirty(true);
continue;
}
++itr;
}
for (LinkedBlocksList::iterator itr = a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ)))
{
itr = a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->erase(itr);
a_Chunk->SetIsRedstoneDirty(true);
continue;
}
++itr;
}
if (a_IsFirstCall && AreCoordsOnChunkBoundary(a_SourceX, a_SourceY, a_SourceZ))
{
// +- 2 to accomodate linked powered blocks
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX - 2, a_SourceZ), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX + 2, a_SourceZ), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX, a_SourceZ - 2), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX, a_SourceZ + 2), false);
}
}
cIncrementalRedstoneSimulator::eRedstoneDirection cIncrementalRedstoneSimulator::GetWireDirection(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int Dir = REDSTONE_NONE;
BLOCKTYPE NegX = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, NegX))
{
if (IsPotentialSource(NegX))
{
Dir |= (REDSTONE_X_POS);
}
}
BLOCKTYPE PosX = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, PosX))
{
if (IsPotentialSource(PosX))
{
Dir |= (REDSTONE_X_NEG);
}
}
BLOCKTYPE NegZ = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, NegZ))
{
if (IsPotentialSource(NegZ))
{
if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
{
Dir ^= REDSTONE_X_POS;
Dir |= REDSTONE_X_NEG;
}
if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
{
Dir ^= REDSTONE_X_NEG;
Dir |= REDSTONE_X_POS;
}
Dir |= REDSTONE_Z_POS;
}
}
BLOCKTYPE PosZ = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, PosZ))
{
if (IsPotentialSource(PosZ))
{
if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
{
Dir ^= REDSTONE_X_POS;
Dir |= REDSTONE_X_NEG;
}
if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
{
Dir ^= REDSTONE_X_NEG;
Dir |= REDSTONE_X_POS;
}
Dir |= REDSTONE_Z_NEG;
}
}
return (eRedstoneDirection)Dir;
}
bool cIncrementalRedstoneSimulator::IsLeverOn(NIBBLETYPE a_BlockMeta)
{
// Extract the ON bit from metadata and return if true if it is set:
return ((a_BlockMeta & 0x8) == 0x8);
}
Added iron trapdoor, fence gates and doors to the redstone simulator
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "IncrementalRedstoneSimulator.h"
#include "BoundingBox.h"
#include "../BlockEntities/RedstonePoweredEntity.h"
#include "../BlockEntities/ChestEntity.h"
#include "../BlockEntities/CommandBlockEntity.h"
#include "../Entities/Pickup.h"
#include "../Blocks/BlockTorch.h"
#include "../Blocks/BlockDoor.h"
#include "../Blocks/BlockButton.h"
#include "../Blocks/BlockLever.h"
#include "../Blocks/BlockPiston.h"
#include "../Blocks/BlockTripwireHook.h"
cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulator(cWorld & a_World) :
super(a_World),
m_RedstoneSimulatorChunkData(),
m_PoweredBlocks(),
m_LinkedPoweredBlocks(),
m_SimulatedPlayerToggleableBlocks(),
m_RepeatersDelayList(),
m_Chunk()
{
}
cIncrementalRedstoneSimulator::~cIncrementalRedstoneSimulator()
{
}
void cIncrementalRedstoneSimulator::RedstoneAddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk, cChunk * a_OtherChunk)
{
if ((a_Chunk == NULL) || !a_Chunk->IsValid())
{
return;
}
else if ((a_BlockY < 0) || (a_BlockY > cChunkDef::Height))
{
return;
}
// We may be called with coordinates in a chunk that is not the first chunk parameter
// In that case, the actual chunk (which the coordinates are in), will be passed as the second parameter
// Use that Chunk pointer to get a relative position
int RelX = 0;
int RelZ = 0;
BLOCKTYPE Block;
NIBBLETYPE Meta;
if (a_OtherChunk != NULL)
{
RelX = a_BlockX - a_OtherChunk->GetPosX() * cChunkDef::Width;
RelZ = a_BlockZ - a_OtherChunk->GetPosZ() * cChunkDef::Width;
a_OtherChunk->GetBlockTypeMeta(RelX, a_BlockY, RelZ, Block, Meta);
// If a_OtherChunk is passed (not NULL), it is the chunk that had a block change, and a_Chunk will be the neighbouring chunk of that block
// Because said neighbouring chunk does not know of this change but still needs to update its redstone, we set it to dirty
a_Chunk->SetIsRedstoneDirty(true);
}
else
{
RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width;
RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width;
a_Chunk->GetBlockTypeMeta(RelX, a_BlockY, RelZ, Block, Meta);
}
// Every time a block is changed (AddBlock called), we want to go through all lists and check to see if the coordiantes stored within are still valid
// Checking only when a block is changed, as opposed to every tick, also improves performance
PoweredBlocksList * PoweredBlocks = a_Chunk->GetRedstoneSimulatorPoweredBlocksList();
for (PoweredBlocksList::iterator itr = PoweredBlocks->begin(); itr != PoweredBlocks->end();)
{
if (!itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
++itr;
continue;
}
if (!IsPotentialSource(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from powered blocks list as it no longer connected to a source", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = PoweredBlocks->erase(itr);
continue;
}
else if (
// Changeable sources
((Block == E_BLOCK_REDSTONE_WIRE) && (Meta == 0)) ||
((Block == E_BLOCK_LEVER) && !IsLeverOn(Meta)) ||
((Block == E_BLOCK_DETECTOR_RAIL) && ((Meta & 0x08) == 0)) ||
(((Block == E_BLOCK_STONE_BUTTON) || (Block == E_BLOCK_WOODEN_BUTTON)) && (!IsButtonOn(Meta))) ||
((Block == E_BLOCK_TRIPWIRE_HOOK) && ((Meta & 0x08) == 0))
)
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from powered blocks list due to present/past metadata mismatch", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = PoweredBlocks->erase(itr);
continue;
}
++itr;
}
LinkedBlocksList * LinkedPoweredBlocks = a_Chunk->GetRedstoneSimulatorLinkedBlocksList();
// We loop through all values (insteading of breaking out at the first) to make sure everything is gone, as there can be multiple SourceBlock entries for one AddBlock coordinate
for (LinkedBlocksList::iterator itr = LinkedPoweredBlocks->begin(); itr != LinkedPoweredBlocks->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
if (!IsPotentialSource(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list as it is no longer connected to a source", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
else if (
// Things that can send power through a block but which depends on meta
((Block == E_BLOCK_REDSTONE_WIRE) && (Meta == 0)) ||
((Block == E_BLOCK_LEVER) && !IsLeverOn(Meta)) ||
(((Block == E_BLOCK_STONE_BUTTON) || (Block == E_BLOCK_WOODEN_BUTTON)) && (!IsButtonOn(Meta)))
)
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list due to present/past metadata mismatch", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
}
else if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
{
if (!IsViableMiddleBlock(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from linked powered blocks list as it is no longer powered through a valid middle block", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
itr = LinkedPoweredBlocks->erase(itr);
continue;
}
}
++itr;
}
SimulatedPlayerToggleableList * SimulatedPlayerToggleableBlocks = a_Chunk->GetRedstoneSimulatorSimulatedPlayerToggleableList();
for (SimulatedPlayerToggleableList::iterator itr = SimulatedPlayerToggleableBlocks->begin(); itr != SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
if (!IsAllowedBlock(Block))
{
LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from toggleable simulated list as it is no longer redstone", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z);
SimulatedPlayerToggleableBlocks->erase(itr);
break;
}
}
RepeatersDelayList * RepeatersDelayList = a_Chunk->GetRedstoneSimulatorRepeatersDelayList();
for (RepeatersDelayList::iterator itr = RepeatersDelayList->begin(); itr != RepeatersDelayList->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
if ((Block != E_BLOCK_REDSTONE_REPEATER_ON) && (Block != E_BLOCK_REDSTONE_REPEATER_OFF))
{
RepeatersDelayList->erase(itr);
break;
}
}
if (a_OtherChunk != NULL)
{
// DO NOT touch our chunk's data structure if we are being called with coordinates from another chunk - this one caused me massive grief :P
return;
}
cRedstoneSimulatorChunkData * RedstoneSimulatorChunkData = a_Chunk->GetRedstoneSimulatorData();
for (cRedstoneSimulatorChunkData::iterator itr = RedstoneSimulatorChunkData->begin(); itr != RedstoneSimulatorChunkData->end(); ++itr)
{
if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) // We are at an entry matching the current (changed) block
{
if (!IsAllowedBlock(Block))
{
itr->DataTwo = true; // The new blocktype is not redstone; it must be queued to be removed from this list
}
else
{
itr->DataTwo = false;
itr->Data = Block; // Update block information
}
return;
}
}
if (!IsAllowedBlock(Block))
{
return;
}
for (cRedstoneSimulatorChunkData::iterator itr = a_Chunk->GetRedstoneSimulatorQueuedData()->begin(); itr != a_Chunk->GetRedstoneSimulatorQueuedData()->end(); ++itr)
{
if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ))
{
// Can't have duplicates in here either, in case something adds the block again before the structure can written to the main chunk data
return;
}
}
a_Chunk->GetRedstoneSimulatorQueuedData()->push_back(cCoordWithBlockAndBool(RelX, a_BlockY, RelZ, Block, false));
}
void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)
{
m_RedstoneSimulatorChunkData = a_Chunk->GetRedstoneSimulatorData();
if (m_RedstoneSimulatorChunkData->empty() && a_Chunk->GetRedstoneSimulatorQueuedData()->empty())
{
return;
}
m_RedstoneSimulatorChunkData->insert(m_RedstoneSimulatorChunkData->end(), a_Chunk->GetRedstoneSimulatorQueuedData()->begin(), a_Chunk->GetRedstoneSimulatorQueuedData()->end());
a_Chunk->GetRedstoneSimulatorQueuedData()->clear();
m_PoweredBlocks = a_Chunk->GetRedstoneSimulatorPoweredBlocksList();
m_RepeatersDelayList = a_Chunk->GetRedstoneSimulatorRepeatersDelayList();
m_SimulatedPlayerToggleableBlocks = a_Chunk->GetRedstoneSimulatorSimulatedPlayerToggleableList();
m_LinkedPoweredBlocks = a_Chunk->GetRedstoneSimulatorLinkedBlocksList();
m_Chunk = a_Chunk;
bool ShouldUpdateSimulateOnceBlocks = false;
if (a_Chunk->IsRedstoneDirty())
{
// Simulate the majority of devices only if something (blockwise or power-wise) has changed
// Make sure to allow the chunk to resimulate after the initial run if there was a power change (ShouldUpdateSimulateOnceBlocks helps to do this)
a_Chunk->SetIsRedstoneDirty(false);
ShouldUpdateSimulateOnceBlocks = true;
}
HandleRedstoneRepeaterDelays();
for (cRedstoneSimulatorChunkData::iterator dataitr = m_RedstoneSimulatorChunkData->begin(); dataitr != m_RedstoneSimulatorChunkData->end();)
{
if (dataitr->DataTwo)
{
dataitr = m_RedstoneSimulatorChunkData->erase(dataitr);
continue;
}
switch (dataitr->Data)
{
case E_BLOCK_DAYLIGHT_SENSOR: HandleDaylightSensor(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRIPWIRE: HandleTripwire(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRIPWIRE_HOOK: HandleTripwireHook(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_WOODEN_PRESSURE_PLATE:
case E_BLOCK_STONE_PRESSURE_PLATE:
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
{
HandlePressurePlate(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
default: break;
}
if (ShouldUpdateSimulateOnceBlocks)
{
switch (dataitr->Data)
{
case E_BLOCK_REDSTONE_WIRE: HandleRedstoneWire(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_COMMAND_BLOCK: HandleCommandBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_NOTE_BLOCK: HandleNoteBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_BLOCK_OF_REDSTONE: HandleRedstoneBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_LEVER: HandleRedstoneLever(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_SPRUCE_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_BIRCH_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_JUNGLE_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_DARK_OAK_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_ACACIA_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TNT: HandleTNT(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRAPDOOR: HandleTrapdoor(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_IRON_TRAPDOOR: HandleTrapdoor(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_TRAPPED_CHEST: HandleTrappedChest(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_DETECTOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
HandleRail(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_WOODEN_DOOR:
case E_BLOCK_SPRUCE_DOOR:
case E_BLOCK_BIRCH_DOOR:
case E_BLOCK_JUNGLE_DOOR:
case E_BLOCK_DARK_OAK_DOOR:
case E_BLOCK_ACACIA_DOOR:
case E_BLOCK_IRON_DOOR:
{
HandleDoor(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_LAMP_OFF:
case E_BLOCK_REDSTONE_LAMP_ON:
{
HandleRedstoneLamp(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_DISPENSER:
case E_BLOCK_DROPPER:
{
HandleDropSpenser(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_PISTON:
case E_BLOCK_STICKY_PISTON:
{
HandlePiston(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_REPEATER_OFF:
case E_BLOCK_REDSTONE_REPEATER_ON:
{
HandleRedstoneRepeater(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_REDSTONE_TORCH_OFF:
case E_BLOCK_REDSTONE_TORCH_ON:
{
HandleRedstoneTorch(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_STONE_BUTTON:
case E_BLOCK_WOODEN_BUTTON:
{
HandleRedstoneButton(dataitr->x, dataitr->y, dataitr->z);
break;
}
default: break;
}
}
++dataitr;
}
}
void cIncrementalRedstoneSimulator::WakeUp(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk)
{
if (AreCoordsOnChunkBoundary(a_BlockX, a_BlockY, a_BlockZ))
{
// On a chunk boundary, alert all four sides (i.e. at least one neighbouring chunk)
AddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk);
// Pass the original coordinates, because when adding things to our simulator lists, we get the chunk that they are in, and therefore any updates need to preseve their position
// RedstoneAddBlock to pass both the neighbouring chunk and the chunk which the coordinates are in and +- 2 in GetNeighbour() to accomodate for LinkedPowered blocks being 2 away from chunk boundaries
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX - 2, a_BlockZ), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX + 2, a_BlockZ), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ - 2), a_Chunk);
RedstoneAddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ + 2), a_Chunk);
return;
}
// Not on boundary, just alert this chunk for speed
AddBlock(a_BlockX, a_BlockY, a_BlockZ, a_Chunk);
}
void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
static const struct // Define which directions the torch can power
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0},
{-1, 0, 0},
{ 0, 0, 1},
{ 0, 0, -1},
{ 0, 1, 0},
} ;
if (a_MyState == E_BLOCK_REDSTONE_TORCH_ON)
{
// Check if the block the torch is on is powered
int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
cChunk * Neighbour = m_Chunk->GetRelNeighborChunk(X, Z);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
if (AreCoordsDirectlyPowered(X, Y, Z, Neighbour))
{
// There was a match, torch goes off
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_OFF, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
return;
}
// Torch still on, make all 4(X, Z) + 1(Y) sides powered
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (i + 1 < ARRAYCOUNT(gCrossCoords)) // Sides of torch, not top (top is last)
{
if (
IsMechanism(Type) && // Is it a mechanism? Not block/other torch etc.
(!Vector3i(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z).Equals(Vector3i(X, Y, Z))) // CAN'T power block is that it is on
)
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
else
{
// Top side, power whatever is there, including blocks
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Power all blocks surrounding block above torch
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YP);
}
}
if (m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) != 0x5) // Is torch standing on ground? If NOT (i.e. on wall), power block beneath
{
BLOCKTYPE Type = m_Chunk->GetBlock(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ);
if (IsMechanism(Type)) // Still can't make a normal block powered though!
{
SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
}
else
{
// Check if the block the torch is on is powered
int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
cChunk * Neighbour = m_Chunk->GetRelNeighborChunk(X, Z);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
// See if off state torch can be turned on again
if (AreCoordsDirectlyPowered(X, Y, Z, Neighbour))
{
return; // Something matches, torch still powered
}
// Block torch on not powered, can be turned on again!
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_ON, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ); // Set self as powered
}
void cIncrementalRedstoneSimulator::HandleRedstoneLever(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (IsLeverOn(Meta))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
eBlockFace Dir = cBlockLeverHandler::BlockMetaDataToBlockFace(Meta);
Dir = ReverseBlockFace(Dir);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Dir);
}
}
void cIncrementalRedstoneSimulator::HandleFenceGate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
NIBBLETYPE MetaData = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
if ((MetaData & 0x4) == 0)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData | 0x4);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
if ((MetaData & 0x4) != 0)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData & ~0x04);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneButton(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (IsButtonOn(Meta))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
eBlockFace Dir = cBlockButtonHandler::BlockMetaDataToBlockFace(Meta);
Dir = ReverseBlockFace(Dir);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Dir);
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
static const struct // Define which directions the wire can receive power from
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0}, /* Wires on same level start */
{-1, 0, 0},
{ 0, 0, 1},
{ 0, 0, -1}, /* Wires on same level stop */
{ 1, 1, 0}, /* Wires one higher, surrounding self start */
{-1, 1, 0},
{ 0, 1, 1},
{ 0, 1, -1}, /* Wires one higher, surrounding self stop */
{ 1, -1, 0}, /* Wires one lower, surrounding self start */
{-1, -1, 0},
{ 0, -1, 1},
{ 0, -1, -1}, /* Wires one lower, surrounding self stop */
} ;
static const struct // Define which directions the wire will check for repeater prescence
{
int x, y, z;
} gSideCoords[] =
{
{ 1, 0, 0 },
{-1, 0, 0 },
{ 0, 0, 1 },
{ 0, 0, -1 },
{ 0, 1, 0 },
};
// Check to see if directly beside a power source
unsigned char MyPower;
if (!IsWirePowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower))
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0);
m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
return;
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
if (MyPower < 1)
{
return;
}
MyPower--;
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) // Loop through all directions to transfer or receive power
{
if ((i >= 4) && (i <= 7)) // If we are currently checking for wire surrounding ourself one block above...
{
BLOCKTYPE Type = 0;
if (a_RelBlockY + 1 >= cChunkDef::Height)
{
continue;
}
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, Type))
{
continue;
}
if (cBlockInfo::IsSolid(Type)) // If there is something solid above us (wire cut off)...
{
continue; // We don't receive power from that wire
}
}
else if ((i >= 8) && (i <= 11)) // See above, but this is for wire below us
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (cBlockInfo::IsSolid(Type))
{
continue;
}
}
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
{
continue;
}
if (Type == E_BLOCK_REDSTONE_WIRE)
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
for (size_t i = 0; i < ARRAYCOUNT(gSideCoords); i++) // Look for repeaters immediately surrounding self and try to power them
{
BLOCKTYPE Type = 0;
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, Type))
{
continue;
}
if (Type == E_BLOCK_REDSTONE_REPEATER_OFF)
{
SetBlockPowered(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
// Wire still powered, power blocks beneath
SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, MyPower);
switch (GetWireDirection(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
case REDSTONE_NONE:
{
SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_X_POS:
{
SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
break;
}
case REDSTONE_X_NEG:
{
SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
break;
}
case REDSTONE_Z_POS:
{
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_Z_NEG:
{
SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
break;
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
/* Repeater Orientation Mini Guide:
===================================
|
| Z Axis
V
X Axis ---->
Repeater directions, values from a cWorld::GetBlockMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) lookup:
East (Right) (X+): 0x1
West (Left) (X-): 0x3
North (Up) (Z-): 0x2
South (Down) (Z+): 0x0
// TODO: Add E_META_XXX enum entries for all meta values and update project with them
Sun rises from East (X+)
*/
// Create a variable holding my meta to avoid multiple lookups.
NIBBLETYPE a_Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
bool IsOn = (a_MyState == E_BLOCK_REDSTONE_REPEATER_ON);
if (!IsRepeaterLocked(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta)) // If we're locked, change nothing. Otherwise:
{
bool IsSelfPowered = IsRepeaterPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta);
if (IsSelfPowered && !IsOn) // Queue a power change if powered, but not on and not locked.
{
QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, true);
}
else if (!IsSelfPowered && IsOn) // Queue a power change if unpowered, on, and not locked.
{
QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleRedstoneRepeaterDelays()
{
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end();)
{
if (itr->a_ElapsedTicks >= itr->a_DelayTicks) // Has the elapsed ticks reached the target ticks?
{
int RelBlockX = itr->a_RelBlockPos.x;
int RelBlockY = itr->a_RelBlockPos.y;
int RelBlockZ = itr->a_RelBlockPos.z;
BLOCKTYPE Block;
NIBBLETYPE Meta;
m_Chunk->GetBlockTypeMeta(RelBlockX, RelBlockY, RelBlockZ, Block, Meta);
if (itr->ShouldPowerOn)
{
if (Block != E_BLOCK_REDSTONE_REPEATER_ON) // For performance
{
m_Chunk->SetBlock(itr->a_RelBlockPos, E_BLOCK_REDSTONE_REPEATER_ON, Meta);
}
switch (Meta & 0x3) // We only want the direction (bottom) bits
{
case 0x0:
{
SetBlockPowered(RelBlockX, RelBlockY, RelBlockZ - 1, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_ZM);
break;
}
case 0x1:
{
SetBlockPowered(RelBlockX + 1, RelBlockY, RelBlockZ, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_XP);
break;
}
case 0x2:
{
SetBlockPowered(RelBlockX, RelBlockY, RelBlockZ + 1, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_ZP);
break;
}
case 0x3:
{
SetBlockPowered(RelBlockX - 1, RelBlockY, RelBlockZ, RelBlockX, RelBlockY, RelBlockZ);
SetDirectionLinkedPowered(RelBlockX, RelBlockY, RelBlockZ, BLOCK_FACE_XM);
break;
}
}
}
else if (Block != E_BLOCK_REDSTONE_REPEATER_OFF)
{
m_Chunk->SetBlock(RelBlockX, RelBlockY, RelBlockZ, E_BLOCK_REDSTONE_REPEATER_OFF, Meta);
}
itr = m_RepeatersDelayList->erase(itr);
}
else
{
LOGD("Incremented a repeater @ {%i %i %i} | Elapsed ticks: %i | Target delay: %i", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z, itr->a_ElapsedTicks, itr->a_DelayTicks);
itr->a_ElapsedTicks++;
itr++;
}
}
}
void cIncrementalRedstoneSimulator::HandlePiston(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (IsPistonPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x7)) // We only want the bottom three bits (4th controls extended-ness)
{
cBlockPistonHandler::ExtendPiston(BlockX, a_RelBlockY, BlockZ, &m_World);
}
else
{
cBlockPistonHandler::RetractPiston(BlockX, a_RelBlockY, BlockZ, &m_World);
}
}
void cIncrementalRedstoneSimulator::HandleDropSpenser(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToDropSpenser :
public cRedstonePoweredCallback
{
bool m_IsPowered;
public:
cSetPowerToDropSpenser(bool a_IsPowered) : m_IsPowered(a_IsPowered) {}
virtual bool Item(cRedstonePoweredEntity * a_DropSpenser) override
{
a_DropSpenser->SetRedstonePower(m_IsPowered);
return false;
}
} DrSpSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithRedstonePoweredEntityAt(BlockX, a_RelBlockY, BlockZ, DrSpSP);
}
void cIncrementalRedstoneSimulator::HandleRedstoneLamp(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
if (a_MyState == E_BLOCK_REDSTONE_LAMP_OFF)
{
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_ON, 0);
}
}
else
{
if (!AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_OFF, 0);
}
}
}
void cIncrementalRedstoneSimulator::HandleTNT(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->BroadcastSoundEffect("game.tnt.primed", (double)BlockX, (double)a_RelBlockY, (double)BlockZ, 0.5f, 0.6f);
m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_AIR, 0);
m_World.SpawnPrimedTNT(BlockX + 0.5, a_RelBlockY + 0.5, BlockZ + 0.5); // 80 ticks to boom
}
}
void cIncrementalRedstoneSimulator::HandleDoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
if (!cBlockDoorHandler::IsOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ))
{
cBlockDoorHandler::SetOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ, true);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
if (cBlockDoorHandler::IsOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ))
{
cBlockDoorHandler::SetOpen(ChunkInterface, BlockX, a_RelBlockY, BlockZ, false);
m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
}
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleCommandBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToCommandBlock :
public cCommandBlockCallback
{
bool m_IsPowered;
public:
cSetPowerToCommandBlock(bool a_IsPowered) : m_IsPowered(a_IsPowered) {}
virtual bool Item(cCommandBlockEntity * a_CommandBlock) override
{
a_CommandBlock->SetRedstonePower(m_IsPowered);
return false;
}
} CmdBlockSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithCommandBlockAt(BlockX, a_RelBlockY, BlockZ, CmdBlockSP);
}
void cIncrementalRedstoneSimulator::HandleRail(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
switch (a_MyType)
{
case E_BLOCK_DETECTOR_RAIL:
{
if ((m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x08) == 0x08)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_MyType);
}
break;
}
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) | 0x08);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x07);
}
break;
}
default: LOGD("Unhandled type of rail in %s", __FUNCTION__);
}
}
void cIncrementalRedstoneSimulator::HandleTrapdoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, true);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, false);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
bool m_bAreCoordsPowered = AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (m_bAreCoordsPowered)
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
class cSetPowerToNoteBlock :
public cRedstonePoweredCallback
{
public:
cSetPowerToNoteBlock() {}
virtual bool Item(cRedstonePoweredEntity * a_NoteBlock) override
{
a_NoteBlock->SetRedstonePower(true);
return false;
}
} NoteBlockSP;
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
m_Chunk->DoWithRedstonePoweredEntityAt(BlockX, a_RelBlockY, BlockZ, NoteBlockSP);
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX, BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(BlockX, BlockZ, ChunkX, ChunkZ);
if (!m_World.IsChunkLighted(ChunkX, ChunkZ))
{
m_World.QueueLightChunk(ChunkX, ChunkZ);
}
else
{
if (m_Chunk->GetTimeAlteredLight(m_World.GetBlockSkyLight(BlockX, a_RelBlockY + 1, BlockZ)) > 8)
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
WakeUp(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
}
void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
switch (a_MyType)
{
case E_BLOCK_STONE_PRESSURE_PLATE:
{
// MCS feature - stone pressure plates can only be triggered by players :D
cPlayer * a_Player = m_World.FindClosestPlayer(Vector3f(BlockX + 0.5f, (float)a_RelBlockY, BlockZ + 0.5f), 0.5f, false);
if (a_Player != NULL)
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x1);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x0);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_NumberOfEntities(0),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_NumberOfEntities++;
}
return false;
}
bool GetPowerLevel(unsigned char & a_PowerLevel) const
{
a_PowerLevel = std::min(m_NumberOfEntities, MAX_POWER_LEVEL);
return (a_PowerLevel > 0);
}
protected:
int m_NumberOfEntities;
int m_X;
int m_Y;
int m_Z;
};
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
unsigned char Power;
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.GetPowerLevel(Power))
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_NumberOfEntities(0),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_NumberOfEntities++;
}
return false;
}
bool GetPowerLevel(unsigned char & a_PowerLevel) const
{
a_PowerLevel = std::min((int)ceil(m_NumberOfEntities / 10.f), MAX_POWER_LEVEL);
return (a_PowerLevel > 0);
}
protected:
int m_NumberOfEntities;
int m_X;
int m_Y;
int m_Z;
};
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
unsigned char Power;
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.GetPowerLevel(Power))
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
case E_BLOCK_WOODEN_PRESSURE_PLATE:
{
class cPressurePlateCallback :
public cEntityCallback
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_FoundEntity(false),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
Vector3f EntityPos = a_Entity->GetPosition();
Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
double Distance = (EntityPos - BlockPos).Length();
if (Distance <= 0.5)
{
m_FoundEntity = true;
return true; // Break out, we only need to know for plates that at least one entity is on top
}
return false;
}
bool FoundEntity(void) const
{
return m_FoundEntity;
}
protected:
bool m_FoundEntity;
int m_X;
int m_Y;
int m_Z;
} ;
cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), PressurePlateCallback);
NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.FoundEntity())
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.5F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, a_MyType);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
m_Chunk->BroadcastSoundEffect("random.click", (double)BlockX + 0.5, (double)a_RelBlockY + 0.1, (double)BlockZ + 0.5, 0.3F, 0.6F);
}
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
break;
}
default:
{
LOGD("Unimplemented pressure plate type %s in cRedstoneSimulator", ItemToFullString(a_MyType).c_str());
break;
}
}
}
void cIncrementalRedstoneSimulator::HandleTripwireHook(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
int RelX = a_RelBlockX, RelZ = a_RelBlockZ;
bool FoundActivated = false;
eBlockFace FaceToGoTowards = cBlockTripwireHookHandler::MetadataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
for (int i = 0; i < 40; ++i) // Tripwires can be connected up to 40 blocks
{
BLOCKTYPE Type;
NIBBLETYPE Meta;
AddFaceDirection(RelX, a_RelBlockY, RelZ, FaceToGoTowards);
m_Chunk->UnboundedRelGetBlock(RelX, a_RelBlockY, RelZ, Type, Meta);
if (Type == E_BLOCK_TRIPWIRE)
{
if (Meta == 0x1)
{
FoundActivated = true;
}
}
else if (Type == E_BLOCK_TRIPWIRE_HOOK)
{
if (ReverseBlockFace(cBlockTripwireHookHandler::MetadataToDirection(Meta)) == FaceToGoTowards)
{
// Other hook facing in opposite direction - circuit completed!
break;
}
else
{
// Tripwire hook not connected at all, AND away all the power state bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x3);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
return;
}
}
else
{
// Tripwire hook not connected at all, AND away all the power state bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x3);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
return;
}
}
if (FoundActivated)
{
// Connected and activated, set the 3rd and 4th highest bits
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) | 0xC);
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
// Connected but not activated, AND away the highest bit
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, (m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x7) | 0x4);
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
void cIncrementalRedstoneSimulator::HandleTrappedChest(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cGetTrappedChestPlayers :
public cChestCallback
{
public:
cGetTrappedChestPlayers(void) :
m_NumberOfPlayers(0)
{
}
virtual bool Item(cChestEntity * a_Chest) override
{
ASSERT(a_Chest->GetBlockType() == E_BLOCK_TRAPPED_CHEST);
m_NumberOfPlayers = a_Chest->GetNumberOfPlayers();
return (m_NumberOfPlayers <= 0);
}
unsigned char GetPowerLevel(void) const
{
return std::min(m_NumberOfPlayers, MAX_POWER_LEVEL);
}
private:
int m_NumberOfPlayers;
} GTCP;
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
if (m_Chunk->DoWithChestAt(BlockX, a_RelBlockY, BlockZ, GTCP))
{
SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, GTCP.GetPowerLevel());
}
else
{
SetSourceUnpowered(BlockX, a_RelBlockY, BlockZ, m_Chunk);
}
}
void cIncrementalRedstoneSimulator::HandleTripwire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
class cTripwireCallback :
public cEntityCallback
{
public:
cTripwireCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
m_FoundEntity(false),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
{
}
virtual bool Item(cEntity * a_Entity) override
{
cBoundingBox bbWire(m_X, m_X + 1, m_Y, m_Y + 0.1, m_Z, m_Z + 1);
cBoundingBox bbEntity(a_Entity->GetPosition(), a_Entity->GetWidth() / 2, a_Entity->GetHeight());
if (bbEntity.DoesIntersect(bbWire))
{
m_FoundEntity = true;
return true; // One entity is sufficient to trigger the wire
}
return false;
}
bool FoundEntity(void) const
{
return m_FoundEntity;
}
protected:
bool m_FoundEntity;
int m_X;
int m_Y;
int m_Z;
};
cTripwireCallback TripwireCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntityInChunk(m_Chunk->GetPosX(), m_Chunk->GetPosZ(), TripwireCallback);
if (TripwireCallback.FoundEntity())
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x1);
}
else
{
m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x0);
}
}
bool cIncrementalRedstoneSimulator::AreCoordsDirectlyPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, cChunk * a_Chunk)
{
// Torches want to access neighbour's data when on a wall, hence the extra chunk parameter
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->end(); ++itr) // Check powered list
{
if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
}
return false;
}
bool cIncrementalRedstoneSimulator::AreCoordsLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
}
return false;
}
bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Repeaters cannot be powered by any face except their back; verify that this is true for a source
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
// Flip the coords to check the back of the repeater
if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
if (itr->a_SourcePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
if (itr->a_MiddlePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
}
return false; // Couldn't find power source behind repeater
}
bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x3) // We only want the 'direction' part of our metadata
{
// If the repeater is looking up or down (If parallel to the Z axis)
case 0x0:
case 0x2:
{
// Check if eastern(right) neighbor is a powered on repeater who is facing us
BLOCKTYPE Block = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON)) // Is right neighbor a powered repeater?
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x3) { return true; } // If so, I am latched/locked
}
// Check if western(left) neighbor is a powered on repeater who is facing us
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX -1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x1) { return true; } // If so, I am latched/locked
}
break;
}
// If the repeater is looking left or right (If parallel to the x axis)
case 0x1:
case 0x3:
{
// Check if southern(down) neighbor is a powered on repeater who is facing us
BLOCKTYPE Block = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1) & 0x3;
if (OtherRepeaterDir == 0x0) { return true; } // If so, am latched/locked
}
// Check if northern(up) neighbor is a powered on repeater who is facing us
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1) & 0x3;
if (OtherRepeaterDir == 0x2) { return true; } // If so, I am latched/locked
}
break;
}
}
return false; // None of the checks succeeded, I am not a locked repeater
}
bool cIncrementalRedstoneSimulator::IsPistonPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Pistons cannot be powered through their front face; this function verifies that a source meets this requirement
eBlockFace Face = cBlockPistonHandler::MetaDataToDirection(a_Meta);
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face);
if (!itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face, true);
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face);
if (!itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
AddFaceDirection(BlockX, a_RelBlockY, BlockZ, Face, true);
}
return false; // Source was in front of the piston's front face
}
bool cIncrementalRedstoneSimulator::IsWirePowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char & a_PowerLevel)
{
a_PowerLevel = 0;
int BlockX = m_Chunk->GetPosX() * cChunkDef::Width + a_RelBlockX;
int BlockZ = m_Chunk->GetPosZ() * cChunkDef::Width + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr) // Check powered list
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
a_PowerLevel = std::max(itr->a_PowerLevel, a_PowerLevel); // Get the highest power level (a_PowerLevel is initialised already and there CAN be multiple levels for one block)
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
BLOCKTYPE Type = E_BLOCK_AIR;
int RelSourceX = itr->a_SourcePos.x - m_Chunk->GetPosX() * cChunkDef::Width;
int RelSourceZ = itr->a_SourcePos.z - m_Chunk->GetPosZ() * cChunkDef::Width;
if (!m_Chunk->UnboundedRelGetBlockType(RelSourceX, itr->a_SourcePos.y, RelSourceZ, Type) || (Type == E_BLOCK_REDSTONE_WIRE))
{
continue;
}
a_PowerLevel = std::max(itr->a_PowerLevel, a_PowerLevel);
}
return (a_PowerLevel != 0); // Answer the inital question: is the wire powered?
}
bool cIncrementalRedstoneSimulator::AreCoordsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool IsCurrentStatePowered)
{
for (SimulatedPlayerToggleableList::const_iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (itr->WasLastStatePowered != IsCurrentStatePowered) // Was the last power state different to the current?
{
return false; // It was, coordinates are no longer simulated
}
else
{
return true; // It wasn't, don't resimulate block, and allow players to toggle
}
}
}
return false; // Block wasn't even in the list, not simulated
}
void cIncrementalRedstoneSimulator::SetDirectionLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, char a_Direction, unsigned char a_PowerLevel)
{
BLOCKTYPE MiddleBlock = 0;
switch (a_Direction)
{
case BLOCK_FACE_XM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX - 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_XP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX + 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZM:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZP:
{
if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, MiddleBlock))
{
return;
}
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
default:
{
ASSERT(!"Unhandled face direction when attempting to set blocks as linked powered!"); // Zombies, that wasn't supposed to happen...
break;
}
}
}
void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char a_PowerLevel)
{
static const struct
{
int x, y, z;
} gCrossCoords[] =
{
{ 1, 0, 0 },
{ -1, 0, 0 },
{ 0, 0, 1 },
{ 0, 0, -1 },
{ 0, 1, 0 },
{ 0, -1, 0 }
};
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) // Loop through struct to power all directions
{
SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_PowerLevel);
}
}
void cIncrementalRedstoneSimulator::SetBlockPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ, unsigned char a_PowerLevel)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
cChunk * Neighbour = m_Chunk->GetRelNeighborChunkAdjustCoords(a_RelBlockX, a_RelBlockZ); // Adjust coordinates for the later call using these values
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
PoweredBlocksList * Powered = Neighbour->GetRedstoneSimulatorPoweredBlocksList(); // We need to insert the value into the chunk who owns the block position
for (PoweredBlocksList::iterator itr = Powered->begin(); itr != Powered->end(); ++itr)
{
if (
itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
)
{
// Check for duplicates, update power level, don't add a new listing
itr->a_PowerLevel = a_PowerLevel;
return;
}
}
// No need to get neighbouring chunk as we can guarantee that when something is powering us, the entry will be in our chunk
// TODO: on C++11 support, change this to a llama function pased to a std::remove_if
for (PoweredBlocksList::iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
if (
itr->a_BlockPos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ)) &&
itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
(m_Chunk->GetBlock(a_RelSourceX, a_RelSourceY, a_RelSourceZ) == E_BLOCK_REDSTONE_WIRE)
)
{
BLOCKTYPE Block;
NIBBLETYPE Meta;
Neighbour->GetBlockTypeMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Block, Meta);
if (Block == E_BLOCK_REDSTONE_WIRE)
{
if (Meta < a_PowerLevel)
{
m_PoweredBlocks->erase(itr); // Powering source with higher power level, allow it
break;
}
else
{
// Powered wires try to power their source - don't let them!
return;
}
}
}
}
sPoweredBlocks RC;
RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Powered->push_back(RC);
Neighbour->SetIsRedstoneDirty(true);
m_Chunk->SetIsRedstoneDirty(true);
}
void cIncrementalRedstoneSimulator::SetBlockLinkedPowered(
int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ,
int a_RelMiddleX, int a_RelMiddleY, int a_RelMiddleZ,
int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ,
BLOCKTYPE a_MiddleBlock, unsigned char a_PowerLevel
)
{
int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
int MiddleX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelMiddleX;
int MiddleZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelMiddleZ;
int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
if (!IsViableMiddleBlock(a_MiddleBlock))
{
return;
}
cChunk * Neighbour = m_Chunk->GetNeighborChunk(BlockX, BlockZ);
if ((Neighbour == NULL) || !Neighbour->IsValid())
{
return;
}
LinkedBlocksList * Linked = Neighbour->GetRedstoneSimulatorLinkedBlocksList();
for (LinkedBlocksList::iterator itr = Linked->begin(); itr != Linked->end(); ++itr) // Check linked powered list
{
if (
itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
itr->a_MiddlePos.Equals(Vector3i(MiddleX, a_RelMiddleY, MiddleZ)) &&
itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
)
{
// Check for duplicates, update power level, don't add a new listing
itr->a_PowerLevel = a_PowerLevel;
return;
}
}
sLinkedPoweredBlocks RC;
RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
RC.a_MiddlePos = Vector3i(MiddleX, a_RelMiddleY, MiddleZ);
RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Linked->push_back(RC);
Neighbour->SetIsRedstoneDirty(true);
m_Chunk->SetIsRedstoneDirty(true);
}
void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool WasLastStatePowered)
{
for (SimulatedPlayerToggleableList::iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
if (!itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
continue;
}
if (itr->WasLastStatePowered != WasLastStatePowered)
{
// If power states different, update listing
itr->WasLastStatePowered = WasLastStatePowered;
return;
}
else
{
// If states the same, just ignore
return;
}
}
// We have arrive here; no block must be in list - add one
sSimulatedPlayerToggleableList RC;
RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
RC.WasLastStatePowered = WasLastStatePowered;
m_SimulatedPlayerToggleableBlocks->push_back(RC);
}
bool cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn)
{
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end(); ++itr)
{
if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (ShouldPowerOn == itr->ShouldPowerOn) // We are queued already for the same thing, don't replace entry
{
return false;
}
// Already in here (normal to allow repeater to continue on powering and updating blocks in front) - just update info and quit
itr->a_DelayTicks = (((a_Meta & 0xC) >> 0x2) + 1) * 2; // See below for description
itr->a_ElapsedTicks = 0;
itr->ShouldPowerOn = ShouldPowerOn;
return false;
}
}
// Self not in list, add self to list
sRepeatersDelayList RC;
RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Gets the top two bits (delay time), shifts them into the lower two bits, and adds one (meta 0 = 1 tick; 1 = 2 etc.)
// Multiply by 2 because in MCS, 1 redstone tick = 1 world tick, but in Vanilla, 1 redstone tick = 2 world ticks, and we need to maintain compatibility
RC.a_DelayTicks = (((a_Meta & 0xC) >> 0x2) + 1) * 2;
RC.a_ElapsedTicks = 0;
RC.ShouldPowerOn = ShouldPowerOn;
m_RepeatersDelayList->push_back(RC);
return true;
}
void cIncrementalRedstoneSimulator::SetSourceUnpowered(int a_SourceX, int a_SourceY, int a_SourceZ, cChunk * a_Chunk, bool a_IsFirstCall)
{
if (!a_IsFirstCall) // The neighbouring chunks passed when this parameter is false may be invalid
{
if ((a_Chunk == NULL) || !a_Chunk->IsValid())
{
return;
}
}
// TODO: on C++11 support, change both of these to llama functions pased to a std::remove_if
for (PoweredBlocksList::iterator itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ)))
{
itr = a_Chunk->GetRedstoneSimulatorPoweredBlocksList()->erase(itr);
a_Chunk->SetIsRedstoneDirty(true);
continue;
}
++itr;
}
for (LinkedBlocksList::iterator itr = a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->begin(); itr != a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->end();)
{
if (itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ)))
{
itr = a_Chunk->GetRedstoneSimulatorLinkedBlocksList()->erase(itr);
a_Chunk->SetIsRedstoneDirty(true);
continue;
}
++itr;
}
if (a_IsFirstCall && AreCoordsOnChunkBoundary(a_SourceX, a_SourceY, a_SourceZ))
{
// +- 2 to accomodate linked powered blocks
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX - 2, a_SourceZ), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX + 2, a_SourceZ), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX, a_SourceZ - 2), false);
SetSourceUnpowered(a_SourceX, a_SourceY, a_SourceZ, a_Chunk->GetNeighborChunk(a_SourceX, a_SourceZ + 2), false);
}
}
cIncrementalRedstoneSimulator::eRedstoneDirection cIncrementalRedstoneSimulator::GetWireDirection(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int Dir = REDSTONE_NONE;
BLOCKTYPE NegX = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, NegX))
{
if (IsPotentialSource(NegX))
{
Dir |= (REDSTONE_X_POS);
}
}
BLOCKTYPE PosX = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, PosX))
{
if (IsPotentialSource(PosX))
{
Dir |= (REDSTONE_X_NEG);
}
}
BLOCKTYPE NegZ = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, NegZ))
{
if (IsPotentialSource(NegZ))
{
if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
{
Dir ^= REDSTONE_X_POS;
Dir |= REDSTONE_X_NEG;
}
if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
{
Dir ^= REDSTONE_X_NEG;
Dir |= REDSTONE_X_POS;
}
Dir |= REDSTONE_Z_POS;
}
}
BLOCKTYPE PosZ = 0;
if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, PosZ))
{
if (IsPotentialSource(PosZ))
{
if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
{
Dir ^= REDSTONE_X_POS;
Dir |= REDSTONE_X_NEG;
}
if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
{
Dir ^= REDSTONE_X_NEG;
Dir |= REDSTONE_X_POS;
}
Dir |= REDSTONE_Z_NEG;
}
}
return (eRedstoneDirection)Dir;
}
bool cIncrementalRedstoneSimulator::IsLeverOn(NIBBLETYPE a_BlockMeta)
{
// Extract the ON bit from metadata and return if true if it is set:
return ((a_BlockMeta & 0x8) == 0x8);
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/client.h"
#include <signal.h>
#include <thread>
#include <vector>
#include "perfetto/base/thread_utils.h"
#include "perfetto/ext/base/unix_socket.h"
#include "src/profiling/memory/wire_protocol.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace profiling {
namespace {
TEST(ClientTest, GetThreadStackRangeBase) {
std::thread th([] {
StackRange stackrange = GetThreadStackRange();
ASSERT_NE(stackrange.begin, nullptr);
ASSERT_NE(stackrange.end, nullptr);
// The implementation assumes the stack grows from higher addresses to
// lower. We will need to rework once we encounter architectures where the
// stack grows the other way.
EXPECT_LT(stackrange.begin, __builtin_frame_address(0));
EXPECT_GT(stackrange.end, __builtin_frame_address(0));
});
th.join();
}
#if defined(ADDRESS_SANITIZER)
#define MAYBE_GetSigaltStackRange DISABLED_GetSigaltStackRange
#else
#define MAYBE_GetSigaltStackRange GetSigaltStackRange
#endif
TEST(ClientTest, MAYBE_GetSigaltStackRange) {
std::vector<char> stack(MINSIGSTKSZ);
stack_t altstack{};
stack_t old_altstack{};
altstack.ss_sp = stack.data();
altstack.ss_size = stack.size();
ASSERT_NE(sigaltstack(&altstack, &old_altstack), -1) << strerror(errno);
struct sigaction oldact;
struct sigaction newact {};
static StackRange stackrange;
static const char* stackptr;
newact.sa_handler = [](int) {
stackrange = GetSigAltStackRange();
stackptr = static_cast<char*>(__builtin_frame_address(0));
};
newact.sa_flags = SA_ONSTACK;
int res = sigaction(SIGUSR1, &newact, &oldact);
ASSERT_NE(res, -1);
raise(SIGUSR1);
PERFETTO_CHECK(sigaction(SIGUSR1, &oldact, nullptr) != -1);
PERFETTO_CHECK(sigaltstack(&old_altstack, nullptr) != -1);
ASSERT_EQ(stackrange.begin, stack.data());
ASSERT_EQ(stackrange.end, &stack[MINSIGSTKSZ]);
ASSERT_LT(stackrange.begin, stackptr);
ASSERT_GT(stackrange.end, stackptr);
}
TEST(ClientTest, GetMainThreadStackRange) {
if (getpid() != base::GetThreadId())
GTEST_SKIP() << "This test has to run on the main thread.";
StackRange stackrange = GetMainThreadStackRange();
ASSERT_NE(stackrange.begin, nullptr);
ASSERT_NE(stackrange.end, nullptr);
// The implementation assumes the stack grows from higher addresses to
// lower. We will need to rework once we encounter architectures where the
// stack grows the other way.
EXPECT_LT(stackrange.begin, __builtin_frame_address(0));
EXPECT_GT(stackrange.end, __builtin_frame_address(0));
}
TEST(ClientTest, IsMainThread) {
// Our code relies on the fact that getpid() == GetThreadId() if this
// process/thread is the main thread of the process. This test ensures that is
// true.
auto pid = getpid();
auto main_thread_id = base::GetThreadId();
EXPECT_EQ(pid, main_thread_id);
std::thread th(
[main_thread_id] { EXPECT_NE(main_thread_id, base::GetThreadId()); });
th.join();
}
TEST(ClientTest, GetMaxTriesBlock) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 200;
EXPECT_EQ(GetMaxTries(cfg), 2u);
}
TEST(ClientTest, GetMaxTriesBlockSmall) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 99;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
TEST(ClientTest, GetMaxTriesBlockVerySmall) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 1;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
TEST(ClientTest, GetMaxTriesBlockInfinite) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 0;
EXPECT_EQ(GetMaxTries(cfg), kInfiniteTries);
}
TEST(ClientTest, GetMaxTriesNoBlock) {
ClientConfiguration cfg = {};
cfg.block_client = false;
cfg.block_client_timeout_us = 200;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
} // namespace
} // namespace profiling
} // namespace perfetto
Revert "Fix some unittests."
This reverts commit b09f1bb2fdc2d2217b50100be6102a3b05c1ba0f.
Reason for revert: Tests are broken
Change-Id: Ifd77ddd0c1a4c218f1a14d4afdc32e3f87c657f6
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/client.h"
#include <signal.h>
#include <thread>
#include "perfetto/base/thread_utils.h"
#include "perfetto/ext/base/unix_socket.h"
#include "src/profiling/memory/wire_protocol.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace profiling {
namespace {
TEST(ClientTest, GetThreadStackRangeBase) {
std::thread th([] {
StackRange stackrange = GetThreadStackRange();
ASSERT_NE(stackrange.begin, nullptr);
ASSERT_NE(stackrange.end, nullptr);
// The implementation assumes the stack grows from higher addresses to
// lower. We will need to rework once we encounter architectures where the
// stack grows the other way.
EXPECT_LT(stackrange.begin, __builtin_frame_address(0));
EXPECT_GT(stackrange.end, __builtin_frame_address(0));
});
th.join();
}
#if defined(ADDRESS_SANITIZER)
#define MAYBE_GetSigaltStackRange DISABLED_GetSigaltStackRange
#else
#define MAYBE_GetSigaltStackRange GetSigaltStackRange
#endif
TEST(ClientTest, MAYBE_GetSigaltStackRange) {
char stack[4096];
stack_t altstack{};
stack_t old_altstack{};
altstack.ss_sp = stack;
altstack.ss_size = sizeof(stack);
ASSERT_NE(sigaltstack(&altstack, &old_altstack), -1);
struct sigaction oldact;
struct sigaction newact {};
static StackRange stackrange;
static const char* stackptr;
newact.sa_handler = [](int) {
stackrange = GetSigAltStackRange();
stackptr = static_cast<char*>(__builtin_frame_address(0));
};
newact.sa_flags = SA_ONSTACK;
int res = sigaction(SIGUSR1, &newact, &oldact);
ASSERT_NE(res, -1);
raise(SIGUSR1);
PERFETTO_CHECK(sigaction(SIGUSR1, &oldact, nullptr) != -1);
PERFETTO_CHECK(sigaltstack(&old_altstack, nullptr) != -1);
ASSERT_EQ(stackrange.begin, stack);
ASSERT_EQ(stackrange.end, &stack[4096]);
ASSERT_LT(stackrange.begin, stackptr);
ASSERT_GT(stackrange.end, stackptr);
}
TEST(ClientTest, GetMainThreadStackRange) {
if (getpid() != base::GetThreadId())
GTEST_SKIP() << "This test has to run on the main thread.";
StackRange stackrange = GetMainThreadStackRange();
ASSERT_NE(stackrange.begin, nullptr);
ASSERT_NE(stackrange.end, nullptr);
// The implementation assumes the stack grows from higher addresses to
// lower. We will need to rework once we encounter architectures where the
// stack grows the other way.
EXPECT_LT(stackrange.begin, __builtin_frame_address(0));
EXPECT_GT(stackrange.end, __builtin_frame_address(0));
}
TEST(ClientTest, IsMainThread) {
// Our code relies on the fact that getpid() == GetThreadId() if this
// process/thread is the main thread of the process. This test ensures that is
// true.
auto pid = getpid();
auto main_thread_id = base::GetThreadId();
EXPECT_EQ(pid, main_thread_id);
std::thread th(
[main_thread_id] { EXPECT_NE(main_thread_id, base::GetThreadId()); });
th.join();
}
TEST(ClientTest, GetMaxTriesBlock) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 200;
EXPECT_EQ(GetMaxTries(cfg), 2u);
}
TEST(ClientTest, GetMaxTriesBlockSmall) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 99;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
TEST(ClientTest, GetMaxTriesBlockVerySmall) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 1;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
TEST(ClientTest, GetMaxTriesBlockInfinite) {
ClientConfiguration cfg = {};
cfg.block_client = true;
cfg.block_client_timeout_us = 0;
EXPECT_EQ(GetMaxTries(cfg), kInfiniteTries);
}
TEST(ClientTest, GetMaxTriesNoBlock) {
ClientConfiguration cfg = {};
cfg.block_client = false;
cfg.block_client_timeout_us = 200;
EXPECT_EQ(GetMaxTries(cfg), 1u);
}
} // namespace
} // namespace profiling
} // namespace perfetto
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <tools/diagnose_ex.h>
#include <osl/mutex.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/NoSupportException.hpp>
#include <toolkit/helper/vclunohelper.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include "cairo_spritecanvas.hxx"
using namespace ::cairo;
using namespace ::com::sun::star;
namespace cairocanvas
{
SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >& aArguments,
const uno::Reference< uno::XComponentContext >& rxContext ) :
maArguments(aArguments),
mxComponentContext( rxContext )
{
}
void SpriteCanvas::initialize()
{
VERBOSE_TRACE("CairoSpriteCanvas created %p\n", this);
// #i64742# Only call initialize when not in probe mode
if( maArguments.getLength() == 0 )
return;
/* maArguments:
0: ptr to creating instance (Window or VirtualDevice)
1: SystemEnvData as a streamed Any (or empty for VirtualDevice)
2: current bounds of creating instance
3: bool, denoting always on top state for Window (always false for VirtualDevice)
4: XWindow for creating Window (or empty for VirtualDevice)
5: SystemGraphicsData as a streamed Any
*/
ENSURE_ARG_OR_THROW( maArguments.getLength() >= 4 &&
maArguments[0].getValueTypeClass() == uno::TypeClass_HYPER &&
maArguments[4].getValueTypeClass() == uno::TypeClass_INTERFACE,
"CairoSpriteCanvas::initialize: wrong number of arguments, or wrong types" );
awt::Rectangle aRect;
maArguments[2] >>= aRect;
bool bIsFullscreen( false );
maArguments[3] >>= bIsFullscreen;
uno::Reference< awt::XWindow > xParentWindow;
maArguments[4] >>= xParentWindow;
Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if( !pParentWindow )
throw lang::NoSupportException(
"Parent window not VCL window, or canvas out-of-process!", NULL);
bool bHasXRender = IsCairoWorking(pParentWindow);
ENSURE_ARG_OR_THROW( bHasXRender == true,
"CairoSpriteCanvas::SpriteCanvas: No RENDER extension" );
Size aPixelSize( pParentWindow->GetOutputSizePixel() );
const ::basegfx::B2ISize aSize( aPixelSize.Width(),
aPixelSize.Height() );
ENSURE_ARG_OR_THROW( pParentWindow != NULL,
"CairoSpriteCanvas::initialize: invalid Window pointer" );
// setup helper
maDeviceHelper.init( *pParentWindow,
*this,
aSize,
bIsFullscreen );
setWindow(uno::Reference<awt::XWindow2>(xParentWindow, uno::UNO_QUERY_THROW));
maCanvasHelper.init( maRedrawManager,
*this,
aSize );
maArguments.realloc(0);
}
void SpriteCanvas::disposeThis()
{
::osl::MutexGuard aGuard( m_aMutex );
mxComponentContext.clear();
// forward to parent
SpriteCanvasBaseT::disposeThis();
}
sal_Bool SAL_CALL SpriteCanvas::showBuffer( sal_Bool bUpdateAll ) throw (uno::RuntimeException, std::exception)
{
return updateScreen( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::switchBuffer( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
return updateScreen( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException, std::exception)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(
::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
bUpdateAll,
mbSurfaceDirty);
}
OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (uno::RuntimeException, std::exception)
{
return OUString( SPRITECANVAS_SERVICE_NAME );
}
SurfaceSharedPtr SpriteCanvas::getSurface()
{
return maDeviceHelper.getBufferSurface();
}
SurfaceSharedPtr SpriteCanvas::createSurface( const ::basegfx::B2ISize& rSize, Content aContent )
{
return maDeviceHelper.createSurface( rSize, aContent );
}
SurfaceSharedPtr SpriteCanvas::createSurface( ::Bitmap& rBitmap )
{
BitmapSystemData aData;
if( rBitmap.GetSystemData( aData ) ) {
const Size& rSize = rBitmap.GetSizePixel();
return maDeviceHelper.createSurface( aData, rSize );
}
return SurfaceSharedPtr();
}
SurfaceSharedPtr SpriteCanvas::changeSurface( bool, bool )
{
// non-modifiable surface here
return SurfaceSharedPtr();
}
OutputDevice* SpriteCanvas::getOutputDevice()
{
return maDeviceHelper.getOutputDevice();
}
SurfaceSharedPtr SpriteCanvas::getBufferSurface()
{
return maDeviceHelper.getBufferSurface();
}
SurfaceSharedPtr SpriteCanvas::getWindowSurface()
{
return maDeviceHelper.getWindowSurface();
}
const ::basegfx::B2ISize& SpriteCanvas::getSizePixel()
{
return maDeviceHelper.getSizePixel();
}
void SpriteCanvas::setSizePixel( const ::basegfx::B2ISize& rSize )
{
maCanvasHelper.setSize( rSize );
// re-set background surface, in case it needed recreation
maCanvasHelper.setSurface( maDeviceHelper.getBufferSurface(),
false );
}
void SpriteCanvas::flush()
{
maDeviceHelper.flush();
}
bool SpriteCanvas::repaint( const SurfaceSharedPtr& pSurface,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState )
{
return maCanvasHelper.repaint( pSurface, viewState, renderState );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
coverity#735401 Logically dead code
Change-Id: I62f278dfd5df7485f809d642789951ab450ea458
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <tools/diagnose_ex.h>
#include <osl/mutex.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/NoSupportException.hpp>
#include <toolkit/helper/vclunohelper.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include "cairo_spritecanvas.hxx"
using namespace ::cairo;
using namespace ::com::sun::star;
namespace cairocanvas
{
SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >& aArguments,
const uno::Reference< uno::XComponentContext >& rxContext ) :
maArguments(aArguments),
mxComponentContext( rxContext )
{
}
void SpriteCanvas::initialize()
{
VERBOSE_TRACE("CairoSpriteCanvas created %p\n", this);
// #i64742# Only call initialize when not in probe mode
if( maArguments.getLength() == 0 )
return;
/* maArguments:
0: ptr to creating instance (Window or VirtualDevice)
1: SystemEnvData as a streamed Any (or empty for VirtualDevice)
2: current bounds of creating instance
3: bool, denoting always on top state for Window (always false for VirtualDevice)
4: XWindow for creating Window (or empty for VirtualDevice)
5: SystemGraphicsData as a streamed Any
*/
ENSURE_ARG_OR_THROW( maArguments.getLength() >= 4 &&
maArguments[0].getValueTypeClass() == uno::TypeClass_HYPER &&
maArguments[4].getValueTypeClass() == uno::TypeClass_INTERFACE,
"CairoSpriteCanvas::initialize: wrong number of arguments, or wrong types" );
awt::Rectangle aRect;
maArguments[2] >>= aRect;
bool bIsFullscreen( false );
maArguments[3] >>= bIsFullscreen;
uno::Reference< awt::XWindow > xParentWindow;
maArguments[4] >>= xParentWindow;
Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if( !pParentWindow )
throw lang::NoSupportException(
"Parent window not VCL window, or canvas out-of-process!", NULL);
bool bHasXRender = IsCairoWorking(pParentWindow);
ENSURE_ARG_OR_THROW( bHasXRender == true,
"CairoSpriteCanvas::SpriteCanvas: No RENDER extension" );
Size aPixelSize( pParentWindow->GetOutputSizePixel() );
const ::basegfx::B2ISize aSize( aPixelSize.Width(),
aPixelSize.Height() );
// setup helper
maDeviceHelper.init( *pParentWindow,
*this,
aSize,
bIsFullscreen );
setWindow(uno::Reference<awt::XWindow2>(xParentWindow, uno::UNO_QUERY_THROW));
maCanvasHelper.init( maRedrawManager,
*this,
aSize );
maArguments.realloc(0);
}
void SpriteCanvas::disposeThis()
{
::osl::MutexGuard aGuard( m_aMutex );
mxComponentContext.clear();
// forward to parent
SpriteCanvasBaseT::disposeThis();
}
sal_Bool SAL_CALL SpriteCanvas::showBuffer( sal_Bool bUpdateAll ) throw (uno::RuntimeException, std::exception)
{
return updateScreen( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::switchBuffer( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
return updateScreen( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException, std::exception)
{
::osl::MutexGuard aGuard( m_aMutex );
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(
::basegfx::unotools::b2IRectangleFromAwtRectangle(maBounds),
bUpdateAll,
mbSurfaceDirty);
}
OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (uno::RuntimeException, std::exception)
{
return OUString( SPRITECANVAS_SERVICE_NAME );
}
SurfaceSharedPtr SpriteCanvas::getSurface()
{
return maDeviceHelper.getBufferSurface();
}
SurfaceSharedPtr SpriteCanvas::createSurface( const ::basegfx::B2ISize& rSize, Content aContent )
{
return maDeviceHelper.createSurface( rSize, aContent );
}
SurfaceSharedPtr SpriteCanvas::createSurface( ::Bitmap& rBitmap )
{
BitmapSystemData aData;
if( rBitmap.GetSystemData( aData ) ) {
const Size& rSize = rBitmap.GetSizePixel();
return maDeviceHelper.createSurface( aData, rSize );
}
return SurfaceSharedPtr();
}
SurfaceSharedPtr SpriteCanvas::changeSurface( bool, bool )
{
// non-modifiable surface here
return SurfaceSharedPtr();
}
OutputDevice* SpriteCanvas::getOutputDevice()
{
return maDeviceHelper.getOutputDevice();
}
SurfaceSharedPtr SpriteCanvas::getBufferSurface()
{
return maDeviceHelper.getBufferSurface();
}
SurfaceSharedPtr SpriteCanvas::getWindowSurface()
{
return maDeviceHelper.getWindowSurface();
}
const ::basegfx::B2ISize& SpriteCanvas::getSizePixel()
{
return maDeviceHelper.getSizePixel();
}
void SpriteCanvas::setSizePixel( const ::basegfx::B2ISize& rSize )
{
maCanvasHelper.setSize( rSize );
// re-set background surface, in case it needed recreation
maCanvasHelper.setSurface( maDeviceHelper.getBufferSurface(),
false );
}
void SpriteCanvas::flush()
{
maDeviceHelper.flush();
}
bool SpriteCanvas::repaint( const SurfaceSharedPtr& pSurface,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState )
{
return maCanvasHelper.repaint( pSurface, viewState, renderState );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
// This is a sample code that constructs general kinetic terms!
#include <iostream>
#include <iomanip> // to set output precision.
#include <cmath>
#include <string>
#include <sstream>
#include <complex>
#include <random>
#include <cstring> // should be replaced by using sstream
#include "generic_vector.h"
#include "verbosity.h"
#include "generic_bicgstab.h"
#include "generic_cg.h"
#include "generic_cr.h"
#include "generic_gcr.h"
#include "generic_minres.h"
#include "generic_cg_flex_precond.h"
#include "generic_gcr_var_precond.h"
#include "mg.h"
#include "mg_complex.h"
#include "u1_utils.h"
#include "lattice.h"
#include "operators.h"
// Are we checking eigenvalues?
#define EIGEN_TEST
#ifdef EIGEN_TEST
#include "arpack_interface.h"
#endif
// Do restrict/prolong test?
//#define PDAGP_TEST
// Do two vector restrict/prolong?
//#define PDAGP_2TEST
// Try solving just the coarse solver.
//#define COARSE_ONLY
using namespace std;
// Define pi.
#define PI 3.141592653589793
// Print null vectors?
//#define PRINT_NULL_VECTOR
// Do null vector generation? Currently uses BiCGStab
#define GEN_NULL_VECTOR
// What type of test should we do?
enum mg_test_types
{
TOP_LEVEL_ONLY = 0, // only test the top level solver.
SMOOTHER_ONLY = 1, // Top level + smoother
TWO_LEVEL = 2, // Two level MG
THREE_LEVEL = 3 // Three level MG
};
// How should we generate null vectors?
enum mg_null_gen_type
{
NULL_GCR = 0, // Generate null vectors with GCR
NULL_BICGSTAB = 1, // Generate null vectors with BiCGStab
NULL_CG = 2, // Generate null vectors with CG
NULL_MINRES = 3, // Generate null vectors with MinRes
};
// What gauge field do we use? Load, random, unit?
enum gauge_create_type
{
GAUGE_LOAD = 0, // Load a gauge field.
GAUGE_RANDOM = 1, // Create a gauge field with deviation 1/sqrt(beta)
GAUGE_UNIT = 2 // Use a unit gauge field.
};
// What structure are we preserving when we block? None, E/O, Corners?
enum blocking_strategy
{
BLOCK_NONE = 0, // Block fully.
BLOCK_EO = 1, // Even/odd
BLOCK_CORNER = 2, // Corners
BLOCK_TOPO = 3 // Chirality defined by taste singlet
};
// Custom routine to load gauge field.
void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA);
enum op_type
{
STAGGERED = 0,
LAPLACE = 1,
LAPLACE_NC2 = 2,
G5_STAGGERED = 3,
STAGGERED_NORMAL = 4,
STAGGERED_INDEX = 5
};
enum src_type
{
POINT = 0,
RANDOM_GAUSSIAN = 1,
ORIGIN_POINT = 2 // for correlator test.
};
/*struct staggered_u1_op
{
complex<double> *lattice;
double mass;
int x_fine;
int y_fine;
Lattice* Lat;
int Nc; // only relevant for square laplace.
};*/
// Print usage.
void display_usage()
{
cout << "--help\n";
cout << "--lattice-size [32, 64, 128] {##} (default 32x32)\n";
cout << "--operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--null-operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--null-solver [gcr, bicgstab, cg, minres] (default bicgstab)\n";
cout << "--null-precision [null prec] (default 5e-5)\n";
cout << "--null-eo [corner, yes, no, topo] (default yes)\n";
cout << "--null-global-ortho-conj [yes, no] (default yes)\n";
cout << "--mass [mass] (default 1e-2)\n";
cout << "--blocksize [blocksize] (default 4)\n";
cout << "--nvec [nvec] (default 4)\n";
cout << "--nrefine [number coarse] (default 1)\n";
cout << "--multi-strategy [smooth, recursive] (default smooth)\n";
cout << "--gauge [unit, load, random] (default load)\n";
cout << "--gauge-transform [yes, no] (default no)\n";
cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n";
cout << "--npre-smooth [presmooth steps] (default 6)\n";
cout << "--npost-smooth [postsmooth steps] (default 6)\n";
cout << "--load-cfg [path] (default do not load, overrides beta)\n";
#ifdef EIGEN_TEST
cout << "--do-eigentest [yes, no] (default no)\n";
#endif // EIGEN_TEST
}
int main(int argc, char** argv)
{
// Declare some variables.
cout << setiosflags(ios::scientific) << setprecision(6);
int i, j, k, x, y;
complex<double> *lattice; // Holds the gauge field.
complex<double> *lhs, *rhs, *check; // For some Kinetic terms.
complex<double> *tmp, *tmp2; // For temporary space.
double explicit_resid = 0.0;
double bnorm = 0.0;
std::mt19937 generator (1337u); // RNG, 1337u is the seed.
inversion_info invif;
staggered_u1_op stagif;
// Introducing coordinate functions slowly.
int nd = 2;
int* coord = new int[nd];
for (i = 0; i < nd; i++)
{
coord[i] = 0;
}
int lattice_size[nd];
int color = 0;
// Set parameters.
// How are we creating the gauge field? Load it, random, unit? Can set on command line.
gauge_create_type gauge_load = GAUGE_LOAD; // GAUGE_LOAD, GAUGE_UNIT, GAUGE_RANDOM
// Should we do a random gauge rotation? Can set on command line.
bool do_gauge_transform = false;
// What operator are we using for the solve? (Laplace is free only.) Can set on command line.
op_type opt = STAGGERED; // STAGGERED, LAPLACE, LAPLACE_NC2, G5_STAGGERED
// What operator are we using for null vector generation? Can set on command line.
op_type opt_null = STAGGERED;
// What test are we performing?
mg_test_types my_test = TWO_LEVEL; //THREE_LEVEL; // TWO_LEVEL is the default which won't override anything.
// How are we generating null vectors?
mg_null_gen_type null_gen = NULL_BICGSTAB; // NULL_BICGSTAB, NULL_GCR, NULL_CG, NULL_MINRES
// Do we globally orthogonalize null vectors both against previous null vectors and their conjugate?
bool do_global_ortho_conj = true;
// L_x = L_y = Dimension for a lattice.
int lattice_size_x = 32; // Can be set on command line with --lattice-size.
int lattice_size_y = 32;
// Describe the staggered fermions.
double MASS = 0.01; // Can be overridden on command line with --mass
// Describe the source type.
src_type source = RANDOM_GAUSSIAN; // POINT, RANDOM_GAUSSIAN, or ORIGIN_POINT (for correlator test).
// Outer Inverter information.
double outer_precision = 5e-7;
int outer_restart = 64;
// Multigrid information.
int n_refine = 1; // 1 = two level V cycle, 2 = three level V cycle, etc.
// Can be set on command line with --nrefine
if (my_test == THREE_LEVEL) // FOR TEST ONLY
{
n_refine = 2;
}
int X_BLOCKSIZE = 4; // Can be overrided with below arg on command line
int Y_BLOCKSIZE = 4; // with --blocksize
blocking_strategy bstrat = BLOCK_EO; // BLOCK_NONE, BLOCK_EO, BLOCK_CORNER
int null_partitions = 2;
// Null vector generation
// If GEN_NULL_VECTOR isn't defined:
// 1 for just const vector, 2 for const + even/odd vector, 4 for each corner
// of the hypercube.
// If GEN_NULL_VECTOR is defined and eo = 0:
// Generate "n_null_vector" null vectors which are block orthogonalized.
// IF GEN_NULL_VECTOR is defined and eo = 1:
// Generate "n_null_vector" null vectors, partition into even and odd.
// Total number of null vectors is 2*VECTOR_COUNT.
// IF GEN_NULL_VECTOR is defined and eo = 3:
// Generate "n_null_vector" null vectors, partition into four corners.
// Total number of null vectors is 4*VECTOR_COUNT.
int n_null_vector = 4; // Note: Gets multiplied by 2 for LAPLACE_NC2 test.
// Can be overriden on command line with --nvec
int null_max_iter = 500;
double null_precision = 5e-5; //5e-4; // Can be overriden on command line with --null-precision
// Inner solver.
mg_multilevel_type mlevel_type = MLEVEL_SMOOTH; // MLEVEL_SMOOTH, MLEVEL_RECURSIVE --- do we smooth then go down, or smooth then krylov?
inner_solver in_solve = GCR; //CR; //GCR;
double inner_precision = 1e-3;
int inner_restart = 64;
int inner_max = 1000;
if (my_test == SMOOTHER_ONLY)
{
in_solve = NONE;
}
// Smoother
inner_solver in_smooth = GCR; //NONE; //GCR; BICGSTAB
double omega_smooth = 0.67; // for MINRES only.
int pre_smooth = 6; // Can set on command line.
int post_smooth = 6; // Can set on command line.
// Gauge field information.
double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta).
// For heatbath gauge field, corresponds to non-compact beta.
// Can be set on command line with --beta.
// Load an external cfg?
char* load_cfg = NULL;
bool do_load = false;
#ifdef EIGEN_TEST
bool do_eigentest = false;
#endif // EIGEN_TEST
/////////////////////////////////////////////
// Get a few parameters from command line. //
/////////////////////////////////////////////
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0)
{
display_usage();
return 0;
}
if (i+1 != argc)
{
if (strcmp(argv[i], "--mass") == 0)
{
MASS = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
opt = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
opt = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
opt = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
opt = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
opt = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
opt = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--null-operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
opt_null = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
opt_null = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
opt_null = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
opt_null = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
opt_null = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
opt_null = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--blocksize") == 0)
{
X_BLOCKSIZE = atoi(argv[i+1]);
Y_BLOCKSIZE = X_BLOCKSIZE;
i++;
}
else if (strcmp(argv[i], "--nvec") == 0)
{
n_null_vector = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-precision") == 0)
{
null_precision = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-solver") == 0)
{
if (strcmp(argv[i+1], "gcr") == 0)
{
null_gen = NULL_GCR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
null_gen = NULL_BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
null_gen = NULL_CG;
}
else if (strcmp(argv[i+1], "minres") == 0)
{
null_gen = NULL_MINRES;
}
i++;
}
else if (strcmp(argv[i], "--null-eo") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
bstrat = BLOCK_EO; // even/odd
}
else if (strcmp(argv[i+1], "corner") == 0)
{
bstrat = BLOCK_CORNER; // corners
}
else if (strcmp(argv[i+1], "topo") == 0)
{
bstrat = BLOCK_TOPO; // chirality as defined by taste singlet.
}
else // none.
{
bstrat = BLOCK_NONE; // fully reduce.
}
i++;
}
else if (strcmp(argv[i], "--null-global-ortho-conj") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_global_ortho_conj = true; // yes, globally orthogonalize null vectors against previous and conj.
}
else if (strcmp(argv[i+1], "no") == 0)
{
do_global_ortho_conj = false;
}
i++;
}
else if (strcmp(argv[i], "--nrefine") == 0)
{
n_refine = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--multi-strategy") == 0)
{
if (strcmp(argv[i+1], "smooth") == 0)
{
mlevel_type = MLEVEL_SMOOTH;
}
else if (strcmp(argv[i+1], "recursive") == 0)
{
mlevel_type = MLEVEL_RECURSIVE;
}
i++;
}
else if (strcmp(argv[i], "--gauge") == 0)
{
if (strcmp(argv[i+1], "unit") == 0)
{
gauge_load = GAUGE_UNIT;
}
else if (strcmp(argv[i+1], "random") == 0)
{
gauge_load = GAUGE_RANDOM;
}
else
{
gauge_load = GAUGE_LOAD;
}
i++;
}
else if (strcmp(argv[i], "--gauge-transform") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_gauge_transform = true;
}
else
{
do_gauge_transform = false;
}
i++;
}
else if (strcmp(argv[i], "--beta") == 0)
{
BETA = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--lattice-size") == 0)
{
lattice_size_x = atoi(argv[i+1]);
if (i+2 != argc)
{
if (argv[i+2][0] == '-' && argv[i+2][1] == '-') // look for --
{
lattice_size_y = lattice_size_x;
}
else // assume number
{
lattice_size_y = atoi(argv[i+2]);
i++;
}
}
else
{
lattice_size_y = lattice_size_x; // At the end, don't try to grab the next element!
}
i++;
}
else if (strcmp(argv[i], "--npre-smooth") == 0)
{
pre_smooth = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--npost-smooth") == 0)
{
post_smooth = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--load-cfg") == 0)
{
load_cfg = argv[i+1];
do_load = true;
i++;
}
#ifdef EIGEN_TEST
else if (strcmp(argv[i], "--do-eigentest") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_eigentest = true;
}
else
{
do_eigentest = false;
}
i++;
}
#endif // EIGENTEST
else
{
display_usage();
return 0;
}
}
}
//printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector);
//return 0;
///////////////////////////////////////
// End of human-readable parameters! //
///////////////////////////////////////
string op_name;
void (*op)(complex<double>*, complex<double>*, void*);
switch (opt)
{
case STAGGERED:
op = square_staggered_u1;
op_name = "Staggered U(1)";
break;
case LAPLACE:
op_name = "Free Laplace";
op = square_laplace;
break;
case LAPLACE_NC2:
op_name = "Free Laplace Nc = 2";
op = square_laplace;
break;
case G5_STAGGERED:
op_name = "Gamma_5 Staggered U(1)";
op = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_name = "Staggered U(1) Normal";
op = square_staggered_normal_u1;
break;
case STAGGERED_INDEX:
op_name = "Staggered U(1) Index Operator";
op = staggered_index_operator;
break;
}
cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n";
// Only relevant for free laplace test.
int Nc = 1; // Only value that matters for staggered
if (opt == LAPLACE_NC2)
{
Nc = 2;
}
// Unset eo for Laplace.
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
bstrat = BLOCK_NONE;
}
// Describe the fine lattice.
lattice_size[0] = lattice_size_x;
lattice_size[1] = lattice_size_y;
// Create a lattice object.
Lattice Lat(nd, lattice_size, Nc);
cout << "[VOL]: X " << lattice_size[0] << " Y " << lattice_size[1] << " Volume " << Lat.get_volume();
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
cout << " Nc " << Nc;
}
cout << "\n";
// Do some allocation.
// Initialize the lattice. Indexing: index = y*N + x.
lattice = new complex<double>[2*Lat.get_lattice_size()];
lhs = new complex<double>[Lat.get_lattice_size()];
rhs = new complex<double>[Lat.get_lattice_size()];
check = new complex<double>[Lat.get_lattice_size()];
tmp = new complex<double>[Lat.get_lattice_size()];
tmp2 = new complex<double>[Lat.get_lattice_size()];
// In case we need a gauge transform.
complex<double>* gauge_trans = new complex<double>[Lat.get_lattice_size()];
// Zero it out.
zero<double>(lattice, 2*Lat.get_lattice_size());
zero<double>(rhs, Lat.get_lattice_size());
zero<double>(lhs, Lat.get_lattice_size());
zero<double>(check, Lat.get_lattice_size());
zero<double>(gauge_trans, Lat.get_lattice_size());
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
//
// Fill stagif.
stagif.lattice = lattice;
stagif.mass = MASS;
stagif.x_fine = Lat.get_lattice_dimension(0); // DEPRECIATE
stagif.y_fine = Lat.get_lattice_dimension(1); // DEPRECIATE
//stagif.Lat = &Lat;
stagif.Nc = Nc; // Only relevant for laplace test only.
// Create the verbosity structure.
inversion_verbose_struct verb;
verb.verbosity = VERB_DETAIL;
verb.verb_prefix = "[L1]: ";
verb.precond_verbosity = VERB_NONE; //VERB_DETAIL;
verb.precond_verb_prefix = "Prec ";
// Describe the gauge field.
cout << "[GAUGE]: Creating a gauge field.\n";
switch (gauge_load)
{
case GAUGE_UNIT:
unit_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
break;
case GAUGE_RANDOM:
gauss_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), generator, BETA);
cout << "[GAUGE]: Created a U(1) gauge field with angle standard deviation " << 1.0/sqrt(BETA) << "\n";
break;
case GAUGE_LOAD:
// Unit first in case loading fails.
unit_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
// Load the gauge field.
if (do_load)
{
read_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), load_cfg);
cout << "[GAUGE]: Loaded a U(1) gauge field from " << load_cfg << "\n";
}
else // various predefined cfgs.
{
internal_load_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), BETA); // defined at end of file.
}
break;
}
if (do_gauge_transform)
{
// Generate and perform a random gauge transformation.
rand_trans_u1(gauge_trans, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), generator);
apply_gauge_trans_u1(lattice, gauge_trans, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
cout << "[GAUGE]: Performed a random gauge rotation.\n";
}
cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1)) << ".\n";
// Sanity check if we're doing a multigrid solve.
if (n_refine == 0)
{
my_test = TOP_LEVEL_ONLY;
}
string op_null_name;
void (*op_null)(complex<double>*, complex<double>*, void*) = square_staggered_u1;
switch (opt_null)
{
case STAGGERED:
op_null = square_staggered_u1;
op_null_name = "Staggered U(1)";
break;
case LAPLACE:
op_null_name = "Free Laplace";
op_null = square_laplace;
break;
case LAPLACE_NC2:
op_null_name = "Free Laplace Nc = 2";
op_null = square_laplace;
break;
case G5_STAGGERED:
op_null_name = "Gamma_5 Staggered U(1)";
op_null = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_null_name = "Staggered U(1) Normal";
op_null = square_staggered_normal_u1;
break;
case STAGGERED_INDEX:
op_name = "Staggered U(1) Index Operator";
op = staggered_index_operator;
break;
}
cout << "[OP]: Null Gen Operator " << op_null_name << "\n";
// Build an mg_struct.
mg_operator_struct_complex mgstruct;
mgstruct.x_fine = Lat.get_lattice_dimension(0);
mgstruct.y_fine = Lat.get_lattice_dimension(1);
mgstruct.Nc = Nc; // only matters for square laplace.
mgstruct.n_refine = n_refine;
mgstruct.blocksize_x = new int[n_refine];
mgstruct.blocksize_y = new int[n_refine];
for (i = 0; i < n_refine; i++)
{
mgstruct.blocksize_x[i] = X_BLOCKSIZE;
mgstruct.blocksize_y[i] = Y_BLOCKSIZE;
}
switch (bstrat)
{
case BLOCK_NONE:
mgstruct.n_vector = n_null_vector;
null_partitions = 1;
break;
case BLOCK_EO:
case BLOCK_TOPO:
mgstruct.n_vector = 2*n_null_vector;
null_partitions = 2;
break;
case BLOCK_CORNER:
mgstruct.n_vector = 4*n_null_vector;
null_partitions = 4;
break;
}
mgstruct.matrix_vector = op; //square_staggered_u1;
mgstruct.matrix_extra_data = (void*)&stagif;
cout << "[MG]: X_Block " << X_BLOCKSIZE << " Y_Block " << Y_BLOCKSIZE << " NullVectors " << n_null_vector << "\n";
// Set the starting mg_struct state.
mgstruct.curr_level = 0; // Ready to do top level -> second level.
mgstruct.curr_dof_fine = Nc; // Top level has only one d.o.f. per site.
mgstruct.curr_x_fine = mgstruct.x_fine;
mgstruct.curr_y_fine = mgstruct.y_fine;
mgstruct.curr_fine_size = mgstruct.curr_y_fine*mgstruct.curr_x_fine*mgstruct.curr_dof_fine;
mgstruct.curr_dof_coarse = mgstruct.n_vector;
mgstruct.curr_x_coarse = mgstruct.x_fine/mgstruct.blocksize_x[0];
mgstruct.curr_y_coarse = mgstruct.y_fine/mgstruct.blocksize_y[0];
mgstruct.curr_coarse_size = mgstruct.curr_y_coarse*mgstruct.curr_x_coarse*mgstruct.curr_dof_coarse;
// Build the mg inverter structure.
// Set up the MG preconditioner.
mg_precond_struct_complex mgprecond;
mgprecond.in_smooth_type = in_smooth; // What inner smoother? MinRes or GCR.
mgprecond.omega_smooth = omega_smooth; // What relaxation parameter should we use (MinRes only!)
mgprecond.n_pre_smooth = pre_smooth; // 6 MinRes smoother steps before coarsening.
mgprecond.n_post_smooth = post_smooth; // 6 MinRes smoother steps after refining.
mgprecond.mlevel_type = mlevel_type; // Do we smooth then go down, or smooth then start a new Krylov?
mgprecond.in_solve_type = in_solve; // What inner solver? NONE, MINRES, CG, GCR, BICGSTAB
mgprecond.n_max = inner_max; // max number of steps to use for inner solver.
mgprecond.n_restart = inner_restart; // frequency of restart (relevant for CG, GCR).
mgprecond.rel_res = inner_precision; // Maximum relative residual for inner solver.
mgprecond.mgstruct = &mgstruct; // Contains null vectors, fine operator. (Since we don't construct the fine op.)
mgprecond.coarse_matrix_vector = coarse_square_staggered; // Function which applies the coarse operator.
mgprecond.fine_matrix_vector = fine_square_staggered; // Function which applies the fine operator.
mgprecond.matrix_extra_data = (void*)&mgstruct; // What extra_data the coarse operator expects.
// Set right hand side.
switch (source)
{
case POINT: // Set a point.
for (i = 0; i < Nc; i++)
{
rhs[(Lat.get_lattice_dimension(0)/2+(Lat.get_lattice_dimension(1)/2)*Lat.get_lattice_dimension(0))*Nc+i] = 1.0;
}
break;
case RANDOM_GAUSSIAN: // Random rhs.
gaussian<double>(rhs, Lat.get_lattice_size(), generator);
break;
case ORIGIN_POINT: // Set a point for correlator computation.
for (i = 0; i < Nc; i++)
{
rhs[i] = 1.0;
}
}
// Get norm for rhs.
bnorm = sqrt(norm2sq<double>(rhs, Lat.get_lattice_size()));
// Set a point on the lhs.
//lhs[x_fine/2+(y_fine/2)*x_fine+1] = 1.0;
// Create a projector.
mgstruct.null_vectors = new complex<double>**[mgstruct.n_refine];
// The top level is special since there are no color indices.
mgstruct.null_vectors[0] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[0][j] = new complex<double>[Lat.get_lattice_size()];
zero<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}
// Higher levels are different.
if (mgstruct.n_refine > 1)
{
for (i = 1; i < mgstruct.n_refine; i++)
{
level_down(&mgstruct);
mgstruct.null_vectors[i] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[i][j] = new complex<double>[mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine];
zero<double>(mgstruct.null_vectors[i][j], mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine);
}
}
// Come back up!
for (i = mgstruct.n_refine; i > 1; i--)
{
level_up(&mgstruct);
}
}
cout << "[MG]: Creating " << mgstruct.n_vector << " projector(s).\n";
#ifndef GEN_NULL_VECTOR
// Make a constant projector.
if (mgstruct.n_vector == 1)
{
cout << "[MG]: Null vector 1 is a constant.\n";
for (i = 0; i < Lat.get_lattice_size(); i++)
{
mgstruct.null_vectors[0][0][i] = 1;
if (do_gauge_transform)
{
mgstruct.null_vectors[0][0][i] *= gauge_trans[i];
}
}
}
else if (mgstruct.n_vector == 2) // constant, even/odd phase.
{
cout << "[MG]: Null vector 1 is a constant.\n";
cout << "[MG]: Null vector 2 is an even/odd phase.\n";
for (i = 0; i < Lat.get_lattice_size(); i++)
{
mgstruct.null_vectors[0][0][i] = 1;
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][1][i] = ((x+y)%2 == 0) ? complex<double>(0.0,1.0) : complex<double>(0.0,-1.0);
if (do_gauge_transform)
{
mgstruct.null_vectors[0][0][i] *= (gauge_trans[i]);
mgstruct.null_vectors[0][1][i] *= (gauge_trans[i]);
}
}
}
else if (mgstruct.n_vector == 4) // 4 corners of hypercube.
{
cout << "[MG]: Null vector 1 is a constant on unit corner (0,0).\n";
cout << "[MG]: Null vector 2 is a constant on unit corner (1,0).\n";
cout << "[MG]: Null vector 3 is a constant on unit corner (0,1).\n";
cout << "[MG]: Null vector 4 is a constant on unit corner (1,1).\n";
// Generate a normal distribution.
std::normal_distribution<> dist(1.0, 0.1);
for (i = 0; i < Lat.get_lattice_size(); i++)
{
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = 1.0;
//mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = dist(generator);
if (do_gauge_transform)
{
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] *= (gauge_trans[i]);
}
}
}
else // invalid.
{
cout << "Unless you are generating null vectors, you can only use 1, 2, or 4 null vectors.\n";
return 0;
}
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
#ifdef PRINT_NULL_VECTOR
cout << "[MG]: Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#else // generate null vector
// Skip this depending on our test!
if (!(my_test == TOP_LEVEL_ONLY || my_test == SMOOTHER_ONLY))
{
// Generate top level!
printf("About to generate null vector.\n"); fflush(stdout);
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* rand_guess = new complex<double>[Lat.get_lattice_size()];
complex<double>* Arand_guess = new complex<double>[Lat.get_lattice_size()];
// Temporarily set the mass to zero for the null vector generation.
stagif.mass = stagif.mass*1e-2;
for (i = 0; i < mgstruct.n_vector/null_partitions; i++)
{
// Create a gaussian random source.
gaussian<double>(rand_guess, Lat.get_lattice_size(), generator);
// Make orthogonal to previous solutions.
if (i > 0) // If there are vectors to orthogonalize against...
{
for (j = 0; j < i; j++) // Iterate over all of them...
{
for (k = 0; k < null_partitions; k++) // And then iterate over even/odd or corners!
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
}
}
/*if (mgstruct.eo == 1)
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/2], Lat.get_lattice_size());
}
else if (mgstruct.eo == 3) // corner.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/4], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], Lat.get_lattice_size());
}
else // no eo.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}*/
}
}
// Solve the residual equation.
zero<double>(Arand_guess, Lat.get_lattice_size());
(*op_null)(Arand_guess, rand_guess, (void*)&stagif);
//square_staggered_u1(Arand_guess, rand_guess, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
Arand_guess[j] = -Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[0][null_partitions*i], Lat.get_lattice_size());
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_MINRES:
minv_vector_minres(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
}
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][null_partitions*i][j] += rand_guess[j];
}
// Aggregate in chirality (or corners) as needed, orthogonalize against previous vectors.
switch (bstrat)
{
case BLOCK_EO:
for (j = 0; j < Lat.get_lattice_size(); j++)
{
if (Lat.index_is_even(j))
{
mgstruct.null_vectors[0][2*i+1][j] = mgstruct.null_vectors[0][2*i][j];
mgstruct.null_vectors[0][2*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
// Orthogonalize against previous vectors.
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j+1],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
break;
case BLOCK_TOPO:
// Form vectors from (1 \pm \Gamma_5)/2.
// Form \Gamma_5 null.
// i/2 \Gamma_1 \Gamma_2
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
staggered_symmshift_y(tmp, mgstruct.null_vectors[0][2*i], (void*)&stagif);
staggered_symmshift_x(tmp2, tmp, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i+1][j] += complex<double>(0.0,0.5)*tmp2[j];
}
// -i/2 \Gamma_2 \Gamma_1
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
staggered_symmshift_x(tmp, mgstruct.null_vectors[0][2*i], (void*)&stagif);
staggered_symmshift_y(tmp2, tmp, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i+1][j] -= complex<double>(0.0,0.5)*tmp2[j];
}
// Form the two projectors.
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i][j] = 0.5*(mgstruct.null_vectors[0][2*i][j]+mgstruct.null_vectors[0][2*i+1][j]);
mgstruct.null_vectors[0][2*i+1][j] = mgstruct.null_vectors[0][2*i][j]-mgstruct.null_vectors[0][2*i+1][j];
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
// Orthogonalize against previous vectors.
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j+1],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
break;
case BLOCK_CORNER:
for (j = 0; j < Lat.get_lattice_size(); j++)
{
// Find x and y component.
Lat.index_to_coord(j, coord, nd);
if (coord[0]%2 == 1 && coord[1]%2 == 0)
{
mgstruct.null_vectors[0][4*i+1][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
else if (coord[0]%2 == 0 && coord[1]%2 == 1)
{
mgstruct.null_vectors[0][4*i+2][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
else if (coord[0]%2 == 1 && coord[1]%2 == 1)
{
mgstruct.null_vectors[0][4*i+3][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][4*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+1], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+2], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+3], Lat.get_lattice_size());
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+1],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+2],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+2],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+3],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+3],Lat.get_lattice_size()))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][4*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+1], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+2], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+3], Lat.get_lattice_size());
break;
case BLOCK_NONE:
normalize(mgstruct.null_vectors[0][i], Lat.get_lattice_size());
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][j],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][i], Lat.get_lattice_size());
break;
}
}
delete[] rand_guess;
delete[] Arand_guess;
#ifdef PRINT_NULL_VECTOR
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
// Do we need to generate more levels?
if (mgstruct.n_refine > 1)
{
mgstruct.matrix_vector = op_null; // Trick op to null gen op.
for (int n = 1; n < mgstruct.n_refine; n++)
{
level_down(&mgstruct);
cout << "curr_fine_size: " << mgstruct.curr_fine_size << "\n";
// Let's give it a whirl?!
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* c_rand_guess = new complex<double>[mgstruct.curr_fine_size];
complex<double>* c_Arand_guess = new complex<double>[mgstruct.curr_fine_size];
// Generate null vectors with the current level.
for (i = 0; i < mgstruct.n_vector/null_partitions; i++)
{
gaussian<double>(c_rand_guess, mgstruct.curr_fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
for (k = 0; k < null_partitions; k++) // And then iterate over even/odd or corners!
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
}
}
/*
if (mgstruct.eo == 1)
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else // no eo.
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}*/
}
}
zero<double>(c_Arand_guess, mgstruct.curr_fine_size);
fine_square_staggered(c_Arand_guess, c_rand_guess, (void*)&mgstruct);
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
c_Arand_guess[j] = -c_Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], mgstruct.curr_fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_MINRES:
minv_vector_minres(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
}
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i][j] += c_rand_guess[j];
}
// Aggregate in chirality, orthogonalize against previous vectors.
switch (bstrat)
{
case BLOCK_EO:
case BLOCK_TOPO:
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
int c = j % mgstruct.n_vector; // What color index do we have?
// 0 to mgstruct.n_vector/2-1 is even, else is odd.
//int x_coord = (i - c)/mgstruct.n_vector % mgstruct.curr_x_fine;
//int y_coord = ((i - c)/mgstruct.n_vector - x_coord)/mgstruct.curr_x_fine;
// If c is even, it's from an even vector, otherwise it's from an odd vector!
if (c%2 == 1)
{
mgstruct.null_vectors[mgstruct.curr_level][2*i+1][j] = mgstruct.null_vectors[mgstruct.curr_level][2*i][j];
mgstruct.null_vectors[mgstruct.curr_level][2*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
}
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.curr_fine_size);
break;
case BLOCK_CORNER:
cout << "ERROR! Need to implement corner aggregation for coarse levels.\n";
return 0;
break;
case BLOCK_NONE:
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
break;
}
}
delete[] c_rand_guess;
delete[] c_Arand_guess;
block_orthonormalize(&mgstruct);
// Print vector.
/*
cout << "\n\nPrinting null vectors:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "\nVector " << n << "\n";
for (int y = 0; y < mgstruct.curr_y_fine; y++)
{
for (int x = 0; x < mgstruct.curr_x_fine; x++)
{
cout << "(";
for (int c = 0; c < mgstruct.n_vector; c++)
{
cout << mgstruct.null_vectors[mgstruct.curr_level][n][y*mgstruct.curr_x_fine*mgstruct.curr_dof_fine+x*mgstruct.curr_dof_fine+c] << ",";
}
cout << ") ";
}
cout << "\n";
}
}*/
}
// Un-pop to the finest level.
for (i = 1; i < mgstruct.n_refine; i++)
{
level_up(&mgstruct);
}
mgstruct.matrix_vector = op; // Reset op to solved op.
}
// Reset the mass.
stagif.mass = MASS;
} // end skipping generation if we're only doing a top level or smoother test.
#endif // generate null vector.
#ifdef PRINT_NULL_VECTOR
cout << "\nCheck projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#ifdef EIGEN_TEST
if (do_eigentest)
{
for (int lev = 0; lev < mgstruct.n_refine; lev++)
{
// Test some eigenvectors!
// Generate min(volume/4, 128) eigenvectors.
int n_eigen = mgstruct.curr_fine_size/2;//min(mgstruct.curr_fine_size/4, 128);
int n_cv = mgstruct.curr_fine_size; //n_eigen*2 + n_eigen/2;
complex<double>* evals = new complex<double>[mgstruct.curr_fine_size];
complex<double>** evecs = new complex<double>*[mgstruct.curr_fine_size];
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
evecs[i] = new complex<double>[mgstruct.curr_fine_size];
}
// Get low mag half
arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen, n_cv); // max eigenvectors, internal vecs
char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues.
arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals, evecs, mgstruct.curr_fine_size, n_eigen, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct);
//arpack_dcn_free(&ar_strc);
// Print info about the eigensolve.
cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n";
// Get high mag half
//arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen, n_cv); // max eigenvectors, internal vecs
strcpy(eigtype, "LM"); // Smallest magnitude eigenvalues.
info_solve = arpack_dcn_getev(ar_strc, evals+(mgstruct.curr_fine_size/2), evecs+(mgstruct.curr_fine_size/2), mgstruct.curr_fine_size, n_eigen, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct);
arpack_dcn_free(&ar_strc);
// Print info about the eigensolve.
cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n";
// End of arpack bindings!
// Sort eigenvalues (done differently depending on the operator).
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
for (j = 0; j < mgstruct.curr_fine_size /*n_eigen*/ -1; j++)
{
switch (opt)
{
case STAGGERED:
if (abs(imag(evals[j])) > abs(imag(evals[j+1])))
{
complex<double> teval = evals[j]; evals[j] = evals[j+1]; evals[j+1] = teval;
complex<double>* tevec = evecs[j]; evecs[j] = evecs[j+1]; evecs[j+1] = tevec;
}
break;
case LAPLACE:
case LAPLACE_NC2:
case G5_STAGGERED:
case STAGGERED_NORMAL:
case STAGGERED_INDEX:
if (abs(real(evals[j])) > abs(real(evals[j+1])))
{
complex<double> teval = evals[j]; evals[j] = evals[j+1]; evals[j+1] = teval;
complex<double>* tevec = evecs[j]; evecs[j] = evecs[j+1]; evecs[j+1] = tevec;
}
break;
}
}
}
cout << "\n\nAll eigenvalues:\n";
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
cout << "[L" << lev+1 << "_FINEVAL]: Mass " << MASS << " Num " << i << " Eval " << evals[i] << "\n";
normalize<double>(evecs[i], mgstruct.curr_fine_size);
}
complex<double>* evec_Pdag = new complex<double>[mgstruct.curr_coarse_size];
complex<double>* evec_Pdag2 = new complex<double>[mgstruct.curr_coarse_size];
complex<double>* evec_PPdag = new complex<double>[mgstruct.curr_fine_size];
// Test overlap of null vectors with eigenvectors.
// Formally, this is looking at the magnitude of (1 - P P^\dag) eigenvector.
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
// Zero out.
zero<double>(evec_Pdag, mgstruct.curr_coarse_size);
zero<double>(evec_PPdag, mgstruct.curr_fine_size);
// Restrict eigenvector.
restrict(evec_Pdag, evecs[i], &mgstruct);
// Prolong.
prolong(evec_PPdag, evec_Pdag, &mgstruct);
// Subtract off eigenvector, take norm.
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
evec_PPdag[j] -= evecs[i][j];
}
cout << "[L" << lev+1 << "_1mPPDAG]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n";
}
// Test how good of a preconditioner the coarse operator is.
// Formally, this is looking at the magnitude of (1 - P ( P^\dag A P )^(-1) P^\dag A) eigenvector.
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
// Zero out.
zero<double>(evec_Pdag, mgstruct.curr_coarse_size);
zero<double>(evec_Pdag2, mgstruct.curr_coarse_size);
zero<double>(evec_PPdag, mgstruct.curr_fine_size);
// Apply A.
fine_square_staggered(evec_PPdag, evecs[i], (void*)&mgstruct);
// Restrict.
restrict(evec_Pdag, evec_PPdag, &mgstruct);
// Invert A_coarse against it.
invif = minv_vector_gcr_restart(evec_Pdag2, evec_Pdag, mgstruct.curr_coarse_size, 10000, 1e-7, 64, coarse_square_staggered, (void*)&mgstruct);
// Prolong.
zero<double>(evec_PPdag, mgstruct.curr_coarse_size);
prolong(evec_PPdag, evec_Pdag2, &mgstruct);
// Subtract off eigenvector, take norm.
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
evec_PPdag[j] -= evecs[i][j];
}
cout << "[L" << lev+1 << "_1mP_Ac_PDAG_A]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n";
}
delete[] evec_Pdag;
delete[] evec_PPdag;
delete[] evec_Pdag2;
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
delete[] evecs[i];
}
delete[] evecs;
delete[] evals;
if (lev < mgstruct.n_refine-1)
{
level_down(&mgstruct);
}
}
for (int lev = mgstruct.n_refine-2; lev >= 0; lev--)
{
level_up(&mgstruct);
}
} // do_eigentest
#endif // EIGEN_TEST
#ifdef PDAGP_TEST
{
// Begin PdagP test.
// Describe the coarse lattice.
int x_coarse = x_fine/mgstruct.blocksize_x[0]; // how many coarse sites are there in the x dir?
int y_coarse = y_fine/mgstruct.blocksize_y[0]; // how many coarse sites are there in the y dir?
int coarse_size = x_coarse*y_coarse;
// Print the fine rhs.
cout << "Check fine point src:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs[x+y*x_fine] << " ";
}
cout << "\n";
}
cout << "Check projector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double> *rhs_PdagP = new complex<double>[Lat.get_lattice_size()];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
// Try applying the coarse Laplace operator!
complex<double>* rhs_A_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_A_coarse, coarse_size*mgstruct.n_vector);
cout << "Applying the coarse Laplace operator to coarse source.\n";
coarse_square_laplace(rhs_A_coarse, rhs_coarse, (void*)&mgstruct);
// Check A coarse source.
cout << "Check A times coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_A_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong rhs_A_coarse.
cout << "Prolong A times coarse source.\n";
complex<double>* rhs_PAP_fine = new complex<double>[Lat.get_lattice_size()];
zero<double>(rhs_PAP_fine, Lat.get_lattice_size());
prolong(rhs_PAP_fine, rhs_A_coarse, &mgstruct);
// Check PAP.
cout << "Check PAP on source.\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PAP_fine[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_A_coarse;
delete[] rhs_PdagP;
delete[] rhs_PAP_fine;
}
#endif
#ifdef PDAGP_2TEST
// Test adding a second projector.
{
mgstruct.n_vector = 2;
complex<double>* tmp_store = mgstruct.null_vectors[0];
delete[] mgstruct.null_vectors;
mgstruct.null_vectors = new complex<double>*[mgstruct.n_vector];
mgstruct.null_vectors[0] = tmp_store;
mgstruct.null_vectors[1] = new complex<double>[Lat.get_lattice_size()];
// Add an even/odd vector.
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
if ((x+y)%2 == 0)
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,1.0);
else
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,-1.0);
}
}
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << "(";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << rhs_coarse[(x+y*x_coarse)*mgstruct.n_vector+n] << ",";
}
cout << ") ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double>* rhs_PdagP = new complex<double>[Lat.get_lattice_size()];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_PdagP;
}
#endif
#ifdef COARSE_ONLY
cout << "[COARSE]: Solving coarse system only.\n";
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_coarse, coarse_size*mgstruct.n_vector);
restrict(rhs_coarse, rhs, &mgstruct);
cout << "[COARSE]: Norm of coarse rhs " << sqrt(norm2sq<double>(rhs_coarse, coarse_size*mgstruct.n_vector)) << ".\n";
complex<double>* lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(lhs_coarse, coarse_size*mgstruct.n_vector);
invif = minv_vector_gcr_restart(lhs_coarse, rhs_coarse, coarse_size*mgstruct.n_vector, 10000, 1e-6, 16, coarse_square_staggered, (void*)&mgstruct);
if (invif.success == true)
{
printf("[COARSE]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[COARSE]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[COARSE]: This may be because the max iterations was reached.\n");
}
printf("[COARSE]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
complex<double>* A_lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(A_lhs_coarse, coarse_size*mgstruct.n_vector);
coarse_square_laplace(A_lhs_coarse, lhs_coarse, (void*)&mgstruct);
for (i = 0; i < coarse_size*mgstruct.n_vector; i++)
{
explicit_resid += real(conj(A_lhs_coarse[i] - rhs_coarse[i])*(A_lhs_coarse[i] - rhs_coarse[i]));
}
explicit_resid = sqrt(explicit_resid);
printf("[COARSE]: [check] should equal [rhs]. The residual is %15.20e.\n", explicit_resid);
complex<double>* pro_lhs_coarse = new complex<double>[N*N];
zero<double>(pro_lhs_coarse, N*N);
prolong(pro_lhs_coarse, lhs_coarse, &mgstruct);
complex<double>* pro_rhs_coarse = new complex<double>[N*N];
zero<double>(pro_rhs_coarse, N*N);
square_staggered_u1(pro_rhs_coarse, pro_lhs_coarse, (void*)&stagif);
#endif // COARSE_ONLY
if (my_test == TOP_LEVEL_ONLY)
{
// Try a direct solve.
cout << "\n[ORIG]: Solve fine system.\n";
invif = minv_vector_gcr_restart(lhs, rhs, Lat.get_lattice_size(), 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb);
//invif = minv_vector_gcr_restart(lhs, rhs, Lat.get_lattice_size(), 100000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif);
if (invif.success == true)
{
printf("[ORIG]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[ORIG]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[ORIG]: This may be because the max iterations was reached.\n");
}
printf("[ORIG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
zero<double>(check, Lat.get_lattice_size());
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < Lat.get_lattice_size(); i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[ORIG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // TOP_LEVEL_ONLY
#ifdef COARSE_ONLY
// Compare PAP solution to real solution.
cout << "\n[COARSE]: Compare solutions.\n";
double comparison = 0;
double resid_comparison = 0;
for (i = 0; i < Lat.get_lattice_size(); i++)
{
comparison += real(conj(pro_lhs_coarse[i]-lhs[i])*(pro_lhs_coarse[i]-lhs[i]));
resid_comparison += real(conj(pro_rhs_coarse[i]-rhs[i])*(pro_rhs_coarse[i]-rhs[i]));
}
comparison = sqrt(explicit_resid);
printf("[COARSE]: The solutions deviate by %15.20e.\n", comparison);
printf("[COARSE]: The projected residual has a rel res of %15.20e.\n", sqrt(resid_comparison)/bnorm);
delete[] rhs_coarse;
delete[] lhs_coarse;
delete[] A_lhs_coarse;
delete[] pro_lhs_coarse;
delete[] pro_rhs_coarse;
#endif // COARSE_ONLY
if (my_test == SMOOTHER_ONLY || my_test == TWO_LEVEL || my_test == THREE_LEVEL)
{
// Let's actually test a multigrid solve!
cout << "\n[MG]: Test MG solve.\n";
// Block normalize the null vectors.
block_normalize(&mgstruct);
// Well, maybe this will work?
zero<double>(lhs, Lat.get_lattice_size());
//invif = minv_vector_cg_flex_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
invif = minv_vector_gcr_var_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
//invif = minv_vector_gcr_var_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif, mg_preconditioner, (void*)&mgprecond);
if (invif.success == true)
{
printf("[L1]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[L1]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[L1]: This may be because the max iterations was reached.\n");
}
printf("[MG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = diffnorm2sq(rhs, check, Lat.get_lattice_size())/bnorm;
printf("[MG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // SMOOTHER_ONLY or TWO_LEVEL
// Look at the two point function!
if (source == ORIGIN_POINT)
{
double* corr = new double[Lat.get_lattice_dimension(1)];
cout << "BEGIN_GOLDSTONE\n";
for (i = 0; i < Lat.get_lattice_dimension(1); i++)
{
corr[i] = 0.0;
for (j = 0; j < Lat.get_lattice_dimension(0); j++)
{
corr[i] += real(conj(lhs[i*Lat.get_lattice_dimension(0)+j])*lhs[i*Lat.get_lattice_dimension(0)+j]);
}
cout << i << " " << corr[i] << "\n";
}
cout << "END_GOLDSTONE\n";
cout << "BEGIN_EFFMASS\n";
for (i = 0; i < Lat.get_lattice_dimension(1); i++)
{
cout << i << " " << log(corr[i]/corr[(i+1)%Lat.get_lattice_dimension(1)]) << "\n";
}
cout << "END_EFFMASS\n";
}
// Free the lattice.
delete[] lattice;
delete[] lhs;
delete[] rhs;
delete[] check;
delete[] tmp;
delete[] tmp2;
delete[] gauge_trans;
// Clean up!
delete[] coord;
delete[] mgstruct.blocksize_x;
delete[] mgstruct.blocksize_y;
for (i = 0; i < mgstruct.n_refine; i++)
{
for (j = 0; j < mgstruct.n_vector; j++)
{
delete[] mgstruct.null_vectors[i][j];
}
delete[] mgstruct.null_vectors[i];
}
delete[] mgstruct.null_vectors;
return 0;
}
// Custom routine to load gauge field.
void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA)
{
if (x_fine == 32 && y_fine == 32)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 64 && y_fine == 64)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 128 && y_fine == 128)
{
if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist. Using unit gauge.\n";
}
}
Added corner orthogonalization to next level.
// This is a sample code that constructs general kinetic terms!
#include <iostream>
#include <iomanip> // to set output precision.
#include <cmath>
#include <string>
#include <sstream>
#include <complex>
#include <random>
#include <cstring> // should be replaced by using sstream
#include "generic_vector.h"
#include "verbosity.h"
#include "generic_bicgstab.h"
#include "generic_cg.h"
#include "generic_cr.h"
#include "generic_gcr.h"
#include "generic_minres.h"
#include "generic_cg_flex_precond.h"
#include "generic_gcr_var_precond.h"
#include "mg.h"
#include "mg_complex.h"
#include "u1_utils.h"
#include "lattice.h"
#include "operators.h"
// Are we checking eigenvalues?
#define EIGEN_TEST
#ifdef EIGEN_TEST
#include "arpack_interface.h"
#endif
// Do restrict/prolong test?
//#define PDAGP_TEST
// Do two vector restrict/prolong?
//#define PDAGP_2TEST
// Try solving just the coarse solver.
//#define COARSE_ONLY
using namespace std;
// Define pi.
#define PI 3.141592653589793
// Print null vectors?
//#define PRINT_NULL_VECTOR
// Do null vector generation? Currently uses BiCGStab
#define GEN_NULL_VECTOR
// What type of test should we do?
enum mg_test_types
{
TOP_LEVEL_ONLY = 0, // only test the top level solver.
SMOOTHER_ONLY = 1, // Top level + smoother
TWO_LEVEL = 2, // Two level MG
THREE_LEVEL = 3 // Three level MG
};
// How should we generate null vectors?
enum mg_null_gen_type
{
NULL_GCR = 0, // Generate null vectors with GCR
NULL_BICGSTAB = 1, // Generate null vectors with BiCGStab
NULL_CG = 2, // Generate null vectors with CG
NULL_MINRES = 3, // Generate null vectors with MinRes
};
// What gauge field do we use? Load, random, unit?
enum gauge_create_type
{
GAUGE_LOAD = 0, // Load a gauge field.
GAUGE_RANDOM = 1, // Create a gauge field with deviation 1/sqrt(beta)
GAUGE_UNIT = 2 // Use a unit gauge field.
};
// What structure are we preserving when we block? None, E/O, Corners?
enum blocking_strategy
{
BLOCK_NONE = 0, // Block fully.
BLOCK_EO = 1, // Even/odd
BLOCK_CORNER = 2, // Corners
BLOCK_TOPO = 3 // Chirality defined by taste singlet
};
// Custom routine to load gauge field.
void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA);
enum op_type
{
STAGGERED = 0,
LAPLACE = 1,
LAPLACE_NC2 = 2,
G5_STAGGERED = 3,
STAGGERED_NORMAL = 4,
STAGGERED_INDEX = 5
};
enum src_type
{
POINT = 0,
RANDOM_GAUSSIAN = 1,
ORIGIN_POINT = 2 // for correlator test.
};
/*struct staggered_u1_op
{
complex<double> *lattice;
double mass;
int x_fine;
int y_fine;
Lattice* Lat;
int Nc; // only relevant for square laplace.
};*/
// Print usage.
void display_usage()
{
cout << "--help\n";
cout << "--lattice-size [32, 64, 128] {##} (default 32x32)\n";
cout << "--operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--null-operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--null-solver [gcr, bicgstab, cg, minres] (default bicgstab)\n";
cout << "--null-precision [null prec] (default 5e-5)\n";
cout << "--null-eo [corner, yes, no, topo] (default yes)\n";
cout << "--null-global-ortho-conj [yes, no] (default no, it only helps in some weird fluke cases)\n";
cout << "--mass [mass] (default 1e-2)\n";
cout << "--blocksize [blocksize] (default 4)\n";
cout << "--nvec [nvec] (default 4)\n";
cout << "--nrefine [number coarse] (default 1)\n";
cout << "--multi-strategy [smooth, recursive] (default smooth)\n";
cout << "--gauge [unit, load, random] (default load)\n";
cout << "--gauge-transform [yes, no] (default no)\n";
cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n";
cout << "--npre-smooth [presmooth steps] (default 6)\n";
cout << "--npost-smooth [postsmooth steps] (default 6)\n";
cout << "--load-cfg [path] (default do not load, overrides beta)\n";
#ifdef EIGEN_TEST
cout << "--do-eigentest [yes, no] (default no)\n";
#endif // EIGEN_TEST
}
int main(int argc, char** argv)
{
// Declare some variables.
cout << setiosflags(ios::scientific) << setprecision(6);
int i, j, k, x, y;
complex<double> *lattice; // Holds the gauge field.
complex<double> *lhs, *rhs, *check; // For some Kinetic terms.
complex<double> *tmp, *tmp2; // For temporary space.
double explicit_resid = 0.0;
double bnorm = 0.0;
std::mt19937 generator (1337u); // RNG, 1337u is the seed.
inversion_info invif;
staggered_u1_op stagif;
// Introducing coordinate functions slowly.
int nd = 2;
int* coord = new int[nd];
for (i = 0; i < nd; i++)
{
coord[i] = 0;
}
int lattice_size[nd];
int color = 0;
// Set parameters.
// How are we creating the gauge field? Load it, random, unit? Can set on command line.
gauge_create_type gauge_load = GAUGE_LOAD; // GAUGE_LOAD, GAUGE_UNIT, GAUGE_RANDOM
// Should we do a random gauge rotation? Can set on command line.
bool do_gauge_transform = false;
// What operator are we using for the solve? (Laplace is free only.) Can set on command line.
op_type opt = STAGGERED; // STAGGERED, LAPLACE, LAPLACE_NC2, G5_STAGGERED
// What operator are we using for null vector generation? Can set on command line.
op_type opt_null = STAGGERED;
// What test are we performing?
mg_test_types my_test = TWO_LEVEL; //THREE_LEVEL; // TWO_LEVEL is the default which won't override anything.
// How are we generating null vectors?
mg_null_gen_type null_gen = NULL_BICGSTAB; // NULL_BICGSTAB, NULL_GCR, NULL_CG, NULL_MINRES
// L_x = L_y = Dimension for a lattice.
int lattice_size_x = 32; // Can be set on command line with --lattice-size.
int lattice_size_y = 32;
// Describe the staggered fermions.
double MASS = 0.01; // Can be overridden on command line with --mass
// Describe the source type.
src_type source = RANDOM_GAUSSIAN; // POINT, RANDOM_GAUSSIAN, or ORIGIN_POINT (for correlator test).
// Outer Inverter information.
double outer_precision = 5e-7;
int outer_restart = 64;
// Multigrid information.
int n_refine = 1; // 1 = two level V cycle, 2 = three level V cycle, etc.
// Can be set on command line with --nrefine
if (my_test == THREE_LEVEL) // FOR TEST ONLY
{
n_refine = 2;
}
int X_BLOCKSIZE = 4; // Can be overrided with below arg on command line
int Y_BLOCKSIZE = 4; // with --blocksize
blocking_strategy bstrat = BLOCK_EO; // BLOCK_NONE, BLOCK_EO, BLOCK_CORNER
int null_partitions = 2;
// Null vector generation
// If GEN_NULL_VECTOR isn't defined:
// 1 for just const vector, 2 for const + even/odd vector, 4 for each corner
// of the hypercube.
// If GEN_NULL_VECTOR is defined and eo = 0:
// Generate "n_null_vector" null vectors which are block orthogonalized.
// IF GEN_NULL_VECTOR is defined and eo = 1:
// Generate "n_null_vector" null vectors, partition into even and odd.
// Total number of null vectors is 2*VECTOR_COUNT.
// IF GEN_NULL_VECTOR is defined and eo = 3:
// Generate "n_null_vector" null vectors, partition into four corners.
// Total number of null vectors is 4*VECTOR_COUNT.
int n_null_vector = 4; // Note: Gets multiplied by 2 for LAPLACE_NC2 test.
// Can be overriden on command line with --nvec
int null_max_iter = 500;
double null_precision = 5e-5; //5e-4; // Can be overriden on command line with --null-precision
// Do we globally orthogonalize null vectors both against previous null vectors and their conjugate?
bool do_global_ortho_conj = false;
// Inner solver.
mg_multilevel_type mlevel_type = MLEVEL_SMOOTH; // MLEVEL_SMOOTH, MLEVEL_RECURSIVE --- do we smooth then go down, or smooth then krylov?
inner_solver in_solve = GCR; //CR; //GCR;
double inner_precision = 1e-3;
int inner_restart = 64;
int inner_max = 1000;
if (my_test == SMOOTHER_ONLY)
{
in_solve = NONE;
}
// Smoother
inner_solver in_smooth = GCR; //NONE; //GCR; BICGSTAB
double omega_smooth = 0.67; // for MINRES only.
int pre_smooth = 6; // Can set on command line.
int post_smooth = 6; // Can set on command line.
// Gauge field information.
double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta).
// For heatbath gauge field, corresponds to non-compact beta.
// Can be set on command line with --beta.
// Load an external cfg?
char* load_cfg = NULL;
bool do_load = false;
#ifdef EIGEN_TEST
bool do_eigentest = false;
#endif // EIGEN_TEST
/////////////////////////////////////////////
// Get a few parameters from command line. //
/////////////////////////////////////////////
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0)
{
display_usage();
return 0;
}
if (i+1 != argc)
{
if (strcmp(argv[i], "--mass") == 0)
{
MASS = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
opt = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
opt = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
opt = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
opt = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
opt = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
opt = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--null-operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
opt_null = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
opt_null = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
opt_null = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
opt_null = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
opt_null = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
opt_null = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--blocksize") == 0)
{
X_BLOCKSIZE = atoi(argv[i+1]);
Y_BLOCKSIZE = X_BLOCKSIZE;
i++;
}
else if (strcmp(argv[i], "--nvec") == 0)
{
n_null_vector = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-precision") == 0)
{
null_precision = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-solver") == 0)
{
if (strcmp(argv[i+1], "gcr") == 0)
{
null_gen = NULL_GCR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
null_gen = NULL_BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
null_gen = NULL_CG;
}
else if (strcmp(argv[i+1], "minres") == 0)
{
null_gen = NULL_MINRES;
}
i++;
}
else if (strcmp(argv[i], "--null-eo") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
bstrat = BLOCK_EO; // even/odd
}
else if (strcmp(argv[i+1], "corner") == 0)
{
bstrat = BLOCK_CORNER; // corners
}
else if (strcmp(argv[i+1], "topo") == 0)
{
bstrat = BLOCK_TOPO; // chirality as defined by taste singlet.
}
else // none.
{
bstrat = BLOCK_NONE; // fully reduce.
}
i++;
}
else if (strcmp(argv[i], "--null-global-ortho-conj") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_global_ortho_conj = true; // yes, globally orthogonalize null vectors against previous and conj.
}
else if (strcmp(argv[i+1], "no") == 0)
{
do_global_ortho_conj = false;
}
i++;
}
else if (strcmp(argv[i], "--nrefine") == 0)
{
n_refine = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--multi-strategy") == 0)
{
if (strcmp(argv[i+1], "smooth") == 0)
{
mlevel_type = MLEVEL_SMOOTH;
}
else if (strcmp(argv[i+1], "recursive") == 0)
{
mlevel_type = MLEVEL_RECURSIVE;
}
i++;
}
else if (strcmp(argv[i], "--gauge") == 0)
{
if (strcmp(argv[i+1], "unit") == 0)
{
gauge_load = GAUGE_UNIT;
}
else if (strcmp(argv[i+1], "random") == 0)
{
gauge_load = GAUGE_RANDOM;
}
else
{
gauge_load = GAUGE_LOAD;
}
i++;
}
else if (strcmp(argv[i], "--gauge-transform") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_gauge_transform = true;
}
else
{
do_gauge_transform = false;
}
i++;
}
else if (strcmp(argv[i], "--beta") == 0)
{
BETA = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--lattice-size") == 0)
{
lattice_size_x = atoi(argv[i+1]);
if (i+2 != argc)
{
if (argv[i+2][0] == '-' && argv[i+2][1] == '-') // look for --
{
lattice_size_y = lattice_size_x;
}
else // assume number
{
lattice_size_y = atoi(argv[i+2]);
i++;
}
}
else
{
lattice_size_y = lattice_size_x; // At the end, don't try to grab the next element!
}
i++;
}
else if (strcmp(argv[i], "--npre-smooth") == 0)
{
pre_smooth = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--npost-smooth") == 0)
{
post_smooth = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--load-cfg") == 0)
{
load_cfg = argv[i+1];
do_load = true;
i++;
}
#ifdef EIGEN_TEST
else if (strcmp(argv[i], "--do-eigentest") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
do_eigentest = true;
}
else
{
do_eigentest = false;
}
i++;
}
#endif // EIGENTEST
else
{
display_usage();
return 0;
}
}
}
//printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector);
//return 0;
///////////////////////////////////////
// End of human-readable parameters! //
///////////////////////////////////////
string op_name;
void (*op)(complex<double>*, complex<double>*, void*);
switch (opt)
{
case STAGGERED:
op = square_staggered_u1;
op_name = "Staggered U(1)";
break;
case LAPLACE:
op_name = "Free Laplace";
op = square_laplace;
break;
case LAPLACE_NC2:
op_name = "Free Laplace Nc = 2";
op = square_laplace;
break;
case G5_STAGGERED:
op_name = "Gamma_5 Staggered U(1)";
op = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_name = "Staggered U(1) Normal";
op = square_staggered_normal_u1;
break;
case STAGGERED_INDEX:
op_name = "Staggered U(1) Index Operator";
op = staggered_index_operator;
break;
}
cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n";
// Only relevant for free laplace test.
int Nc = 1; // Only value that matters for staggered
if (opt == LAPLACE_NC2)
{
Nc = 2;
}
// Unset eo for Laplace.
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
bstrat = BLOCK_NONE;
}
// Describe the fine lattice.
lattice_size[0] = lattice_size_x;
lattice_size[1] = lattice_size_y;
// Create a lattice object.
Lattice Lat(nd, lattice_size, Nc);
cout << "[VOL]: X " << lattice_size[0] << " Y " << lattice_size[1] << " Volume " << Lat.get_volume();
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
cout << " Nc " << Nc;
}
cout << "\n";
// Do some allocation.
// Initialize the lattice. Indexing: index = y*N + x.
lattice = new complex<double>[2*Lat.get_lattice_size()];
lhs = new complex<double>[Lat.get_lattice_size()];
rhs = new complex<double>[Lat.get_lattice_size()];
check = new complex<double>[Lat.get_lattice_size()];
tmp = new complex<double>[Lat.get_lattice_size()];
tmp2 = new complex<double>[Lat.get_lattice_size()];
// In case we need a gauge transform.
complex<double>* gauge_trans = new complex<double>[Lat.get_lattice_size()];
// Zero it out.
zero<double>(lattice, 2*Lat.get_lattice_size());
zero<double>(rhs, Lat.get_lattice_size());
zero<double>(lhs, Lat.get_lattice_size());
zero<double>(check, Lat.get_lattice_size());
zero<double>(gauge_trans, Lat.get_lattice_size());
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
//
// Fill stagif.
stagif.lattice = lattice;
stagif.mass = MASS;
stagif.x_fine = Lat.get_lattice_dimension(0); // DEPRECIATE
stagif.y_fine = Lat.get_lattice_dimension(1); // DEPRECIATE
//stagif.Lat = &Lat;
stagif.Nc = Nc; // Only relevant for laplace test only.
// Create the verbosity structure.
inversion_verbose_struct verb;
verb.verbosity = VERB_DETAIL;
verb.verb_prefix = "[L1]: ";
verb.precond_verbosity = VERB_NONE; //VERB_DETAIL;
verb.precond_verb_prefix = "Prec ";
// Describe the gauge field.
cout << "[GAUGE]: Creating a gauge field.\n";
switch (gauge_load)
{
case GAUGE_UNIT:
unit_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
break;
case GAUGE_RANDOM:
gauss_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), generator, BETA);
cout << "[GAUGE]: Created a U(1) gauge field with angle standard deviation " << 1.0/sqrt(BETA) << "\n";
break;
case GAUGE_LOAD:
// Unit first in case loading fails.
unit_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
// Load the gauge field.
if (do_load)
{
read_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), load_cfg);
cout << "[GAUGE]: Loaded a U(1) gauge field from " << load_cfg << "\n";
}
else // various predefined cfgs.
{
internal_load_gauge_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), BETA); // defined at end of file.
}
break;
}
if (do_gauge_transform)
{
// Generate and perform a random gauge transformation.
rand_trans_u1(gauge_trans, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1), generator);
apply_gauge_trans_u1(lattice, gauge_trans, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1));
cout << "[GAUGE]: Performed a random gauge rotation.\n";
}
cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, Lat.get_lattice_dimension(0), Lat.get_lattice_dimension(1)) << ".\n";
// Sanity check if we're doing a multigrid solve.
if (n_refine == 0)
{
my_test = TOP_LEVEL_ONLY;
}
string op_null_name;
void (*op_null)(complex<double>*, complex<double>*, void*) = square_staggered_u1;
switch (opt_null)
{
case STAGGERED:
op_null = square_staggered_u1;
op_null_name = "Staggered U(1)";
break;
case LAPLACE:
op_null_name = "Free Laplace";
op_null = square_laplace;
break;
case LAPLACE_NC2:
op_null_name = "Free Laplace Nc = 2";
op_null = square_laplace;
break;
case G5_STAGGERED:
op_null_name = "Gamma_5 Staggered U(1)";
op_null = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_null_name = "Staggered U(1) Normal";
op_null = square_staggered_normal_u1;
break;
case STAGGERED_INDEX:
op_name = "Staggered U(1) Index Operator";
op = staggered_index_operator;
break;
}
cout << "[OP]: Null Gen Operator " << op_null_name << "\n";
// Build an mg_struct.
mg_operator_struct_complex mgstruct;
mgstruct.x_fine = Lat.get_lattice_dimension(0);
mgstruct.y_fine = Lat.get_lattice_dimension(1);
mgstruct.Nc = Nc; // only matters for square laplace.
mgstruct.n_refine = n_refine;
mgstruct.blocksize_x = new int[n_refine];
mgstruct.blocksize_y = new int[n_refine];
for (i = 0; i < n_refine; i++)
{
mgstruct.blocksize_x[i] = X_BLOCKSIZE;
mgstruct.blocksize_y[i] = Y_BLOCKSIZE;
}
switch (bstrat)
{
case BLOCK_NONE:
mgstruct.n_vector = n_null_vector;
null_partitions = 1;
break;
case BLOCK_EO:
case BLOCK_TOPO:
mgstruct.n_vector = 2*n_null_vector;
null_partitions = 2;
break;
case BLOCK_CORNER:
mgstruct.n_vector = 4*n_null_vector;
null_partitions = 4;
break;
}
mgstruct.matrix_vector = op; //square_staggered_u1;
mgstruct.matrix_extra_data = (void*)&stagif;
cout << "[MG]: X_Block " << X_BLOCKSIZE << " Y_Block " << Y_BLOCKSIZE << " NullVectors " << n_null_vector << "\n";
// Set the starting mg_struct state.
mgstruct.curr_level = 0; // Ready to do top level -> second level.
mgstruct.curr_dof_fine = Nc; // Top level has only one d.o.f. per site.
mgstruct.curr_x_fine = mgstruct.x_fine;
mgstruct.curr_y_fine = mgstruct.y_fine;
mgstruct.curr_fine_size = mgstruct.curr_y_fine*mgstruct.curr_x_fine*mgstruct.curr_dof_fine;
mgstruct.curr_dof_coarse = mgstruct.n_vector;
mgstruct.curr_x_coarse = mgstruct.x_fine/mgstruct.blocksize_x[0];
mgstruct.curr_y_coarse = mgstruct.y_fine/mgstruct.blocksize_y[0];
mgstruct.curr_coarse_size = mgstruct.curr_y_coarse*mgstruct.curr_x_coarse*mgstruct.curr_dof_coarse;
// Build the mg inverter structure.
// Set up the MG preconditioner.
mg_precond_struct_complex mgprecond;
mgprecond.in_smooth_type = in_smooth; // What inner smoother? MinRes or GCR.
mgprecond.omega_smooth = omega_smooth; // What relaxation parameter should we use (MinRes only!)
mgprecond.n_pre_smooth = pre_smooth; // 6 MinRes smoother steps before coarsening.
mgprecond.n_post_smooth = post_smooth; // 6 MinRes smoother steps after refining.
mgprecond.mlevel_type = mlevel_type; // Do we smooth then go down, or smooth then start a new Krylov?
mgprecond.in_solve_type = in_solve; // What inner solver? NONE, MINRES, CG, GCR, BICGSTAB
mgprecond.n_max = inner_max; // max number of steps to use for inner solver.
mgprecond.n_restart = inner_restart; // frequency of restart (relevant for CG, GCR).
mgprecond.rel_res = inner_precision; // Maximum relative residual for inner solver.
mgprecond.mgstruct = &mgstruct; // Contains null vectors, fine operator. (Since we don't construct the fine op.)
mgprecond.coarse_matrix_vector = coarse_square_staggered; // Function which applies the coarse operator.
mgprecond.fine_matrix_vector = fine_square_staggered; // Function which applies the fine operator.
mgprecond.matrix_extra_data = (void*)&mgstruct; // What extra_data the coarse operator expects.
// Set right hand side.
switch (source)
{
case POINT: // Set a point.
for (i = 0; i < Nc; i++)
{
rhs[(Lat.get_lattice_dimension(0)/2+(Lat.get_lattice_dimension(1)/2)*Lat.get_lattice_dimension(0))*Nc+i] = 1.0;
}
break;
case RANDOM_GAUSSIAN: // Random rhs.
gaussian<double>(rhs, Lat.get_lattice_size(), generator);
break;
case ORIGIN_POINT: // Set a point for correlator computation.
for (i = 0; i < Nc; i++)
{
rhs[i] = 1.0;
}
}
// Get norm for rhs.
bnorm = sqrt(norm2sq<double>(rhs, Lat.get_lattice_size()));
// Set a point on the lhs.
//lhs[x_fine/2+(y_fine/2)*x_fine+1] = 1.0;
// Create a projector.
mgstruct.null_vectors = new complex<double>**[mgstruct.n_refine];
// The top level is special since there are no color indices.
mgstruct.null_vectors[0] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[0][j] = new complex<double>[Lat.get_lattice_size()];
zero<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}
// Higher levels are different.
if (mgstruct.n_refine > 1)
{
for (i = 1; i < mgstruct.n_refine; i++)
{
level_down(&mgstruct);
mgstruct.null_vectors[i] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[i][j] = new complex<double>[mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine];
zero<double>(mgstruct.null_vectors[i][j], mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine);
}
}
// Come back up!
for (i = mgstruct.n_refine; i > 1; i--)
{
level_up(&mgstruct);
}
}
cout << "[MG]: Creating " << mgstruct.n_vector << " projector(s).\n";
#ifndef GEN_NULL_VECTOR
// Make a constant projector.
if (mgstruct.n_vector == 1)
{
cout << "[MG]: Null vector 1 is a constant.\n";
for (i = 0; i < Lat.get_lattice_size(); i++)
{
mgstruct.null_vectors[0][0][i] = 1;
if (do_gauge_transform)
{
mgstruct.null_vectors[0][0][i] *= gauge_trans[i];
}
}
}
else if (mgstruct.n_vector == 2) // constant, even/odd phase.
{
cout << "[MG]: Null vector 1 is a constant.\n";
cout << "[MG]: Null vector 2 is an even/odd phase.\n";
for (i = 0; i < Lat.get_lattice_size(); i++)
{
mgstruct.null_vectors[0][0][i] = 1;
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][1][i] = ((x+y)%2 == 0) ? complex<double>(0.0,1.0) : complex<double>(0.0,-1.0);
if (do_gauge_transform)
{
mgstruct.null_vectors[0][0][i] *= (gauge_trans[i]);
mgstruct.null_vectors[0][1][i] *= (gauge_trans[i]);
}
}
}
else if (mgstruct.n_vector == 4) // 4 corners of hypercube.
{
cout << "[MG]: Null vector 1 is a constant on unit corner (0,0).\n";
cout << "[MG]: Null vector 2 is a constant on unit corner (1,0).\n";
cout << "[MG]: Null vector 3 is a constant on unit corner (0,1).\n";
cout << "[MG]: Null vector 4 is a constant on unit corner (1,1).\n";
// Generate a normal distribution.
std::normal_distribution<> dist(1.0, 0.1);
for (i = 0; i < Lat.get_lattice_size(); i++)
{
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = 1.0;
//mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = dist(generator);
if (do_gauge_transform)
{
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] *= (gauge_trans[i]);
}
}
}
else // invalid.
{
cout << "Unless you are generating null vectors, you can only use 1, 2, or 4 null vectors.\n";
return 0;
}
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
#ifdef PRINT_NULL_VECTOR
cout << "[MG]: Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#else // generate null vector
// Skip this depending on our test!
if (!(my_test == TOP_LEVEL_ONLY || my_test == SMOOTHER_ONLY))
{
// Generate top level!
printf("About to generate null vector.\n"); fflush(stdout);
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* rand_guess = new complex<double>[Lat.get_lattice_size()];
complex<double>* Arand_guess = new complex<double>[Lat.get_lattice_size()];
// Temporarily set the mass to zero for the null vector generation.
stagif.mass = stagif.mass*1e-2;
for (i = 0; i < mgstruct.n_vector/null_partitions; i++)
{
// Create a gaussian random source.
gaussian<double>(rand_guess, Lat.get_lattice_size(), generator);
// Make orthogonal to previous solutions.
if (i > 0) // If there are vectors to orthogonalize against...
{
for (j = 0; j < i; j++) // Iterate over all of them...
{
for (k = 0; k < null_partitions; k++) // And then iterate over even/odd or corners!
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][j*null_partitions+k], Lat.get_lattice_size());
}
}
/*if (mgstruct.eo == 1)
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/2], Lat.get_lattice_size());
}
else if (mgstruct.eo == 3) // corner.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/4], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], Lat.get_lattice_size());
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], Lat.get_lattice_size());
}
else // no eo.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}*/
}
}
// Solve the residual equation.
zero<double>(Arand_guess, Lat.get_lattice_size());
(*op_null)(Arand_guess, rand_guess, (void*)&stagif);
//square_staggered_u1(Arand_guess, rand_guess, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
Arand_guess[j] = -Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[0][null_partitions*i], Lat.get_lattice_size());
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_MINRES:
minv_vector_minres(mgstruct.null_vectors[0][null_partitions*i], Arand_guess, Lat.get_lattice_size(), null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
}
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][null_partitions*i][j] += rand_guess[j];
}
// Aggregate in chirality (or corners) as needed, orthogonalize against previous vectors.
switch (bstrat)
{
case BLOCK_EO:
for (j = 0; j < Lat.get_lattice_size(); j++)
{
if (Lat.index_is_even(j))
{
mgstruct.null_vectors[0][2*i+1][j] = mgstruct.null_vectors[0][2*i][j];
mgstruct.null_vectors[0][2*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
// Orthogonalize against previous vectors.
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j+1],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
break;
case BLOCK_TOPO:
// Form vectors from (1 \pm \Gamma_5)/2.
// Form \Gamma_5 null.
// i/2 \Gamma_1 \Gamma_2
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
staggered_symmshift_y(tmp, mgstruct.null_vectors[0][2*i], (void*)&stagif);
staggered_symmshift_x(tmp2, tmp, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i+1][j] += complex<double>(0.0,0.5)*tmp2[j];
}
// -i/2 \Gamma_2 \Gamma_1
zero<double>(tmp, Lat.get_lattice_size());
zero<double>(tmp2, Lat.get_lattice_size());
staggered_symmshift_x(tmp, mgstruct.null_vectors[0][2*i], (void*)&stagif);
staggered_symmshift_y(tmp2, tmp, (void*)&stagif);
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i+1][j] -= complex<double>(0.0,0.5)*tmp2[j];
}
// Form the two projectors.
for (j = 0; j < Lat.get_lattice_size(); j++)
{
mgstruct.null_vectors[0][2*i][j] = 0.5*(mgstruct.null_vectors[0][2*i][j]+mgstruct.null_vectors[0][2*i+1][j]);
mgstruct.null_vectors[0][2*i+1][j] = mgstruct.null_vectors[0][2*i][j]-mgstruct.null_vectors[0][2*i+1][j];
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
// Orthogonalize against previous vectors.
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][2*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][2*j+1],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i], mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][2*i+1], mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][2*j+1], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][2*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][2*i+1], Lat.get_lattice_size());
break;
case BLOCK_CORNER:
for (j = 0; j < Lat.get_lattice_size(); j++)
{
// Find x and y component.
Lat.index_to_coord(j, coord, nd);
if (coord[0]%2 == 1 && coord[1]%2 == 0)
{
mgstruct.null_vectors[0][4*i+1][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
else if (coord[0]%2 == 0 && coord[1]%2 == 1)
{
mgstruct.null_vectors[0][4*i+2][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
else if (coord[0]%2 == 1 && coord[1]%2 == 1)
{
mgstruct.null_vectors[0][4*i+3][j] = mgstruct.null_vectors[0][4*i][j];
mgstruct.null_vectors[0][4*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][4*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+1], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+2], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+3], Lat.get_lattice_size());
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+1],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+1],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+2],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+2],Lat.get_lattice_size()))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][4*i+3],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][4*j+3],Lat.get_lattice_size()))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i], mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+1], mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+2], mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][4*i+3], mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+1], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+2], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][4*j+3], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][4*i], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+1], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+2], Lat.get_lattice_size());
normalize(mgstruct.null_vectors[0][4*i+3], Lat.get_lattice_size());
break;
case BLOCK_NONE:
normalize(mgstruct.null_vectors[0][i], Lat.get_lattice_size());
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size())/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],Lat.get_lattice_size())*norm2sq<double>(mgstruct.null_vectors[0][j],Lat.get_lattice_size()))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size());
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], Lat.get_lattice_size());
conj<double>(mgstruct.null_vectors[0][j], Lat.get_lattice_size());
}
}
}
normalize(mgstruct.null_vectors[0][i], Lat.get_lattice_size());
break;
}
}
delete[] rand_guess;
delete[] Arand_guess;
#ifdef PRINT_NULL_VECTOR
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
// Do we need to generate more levels?
if (mgstruct.n_refine > 1)
{
mgstruct.matrix_vector = op_null; // Trick op to null gen op.
for (int n = 1; n < mgstruct.n_refine; n++)
{
level_down(&mgstruct);
cout << "curr_fine_size: " << mgstruct.curr_fine_size << "\n";
// Let's give it a whirl?!
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* c_rand_guess = new complex<double>[mgstruct.curr_fine_size];
complex<double>* c_Arand_guess = new complex<double>[mgstruct.curr_fine_size];
// Generate null vectors with the current level.
for (i = 0; i < mgstruct.n_vector/null_partitions; i++)
{
gaussian<double>(c_rand_guess, mgstruct.curr_fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
for (k = 0; k < null_partitions; k++) // And then iterate over even/odd or corners!
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j*null_partitions+k], mgstruct.curr_fine_size);
}
}
/*
if (mgstruct.eo == 1)
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else // no eo.
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}*/
}
}
zero<double>(c_Arand_guess, mgstruct.curr_fine_size);
fine_square_staggered(c_Arand_guess, c_rand_guess, (void*)&mgstruct);
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
c_Arand_guess[j] = -c_Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], mgstruct.curr_fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_MINRES:
minv_vector_minres(mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
}
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
mgstruct.null_vectors[mgstruct.curr_level][null_partitions*i][j] += c_rand_guess[j];
}
// Aggregate in chirality, orthogonalize against previous vectors.
switch (bstrat)
{
case BLOCK_EO:
case BLOCK_TOPO:
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
int c = j % mgstruct.n_vector; // What color index do we have?
// 0 to mgstruct.n_vector/2-1 is even, else is odd.
//int x_coord = (i - c)/mgstruct.n_vector % mgstruct.curr_x_fine;
//int y_coord = ((i - c)/mgstruct.n_vector - x_coord)/mgstruct.curr_x_fine;
// If c is even, it's from an even vector, otherwise it's from an odd vector!
if (c%2 == 1)
{
mgstruct.null_vectors[mgstruct.curr_level][2*i+1][j] = mgstruct.null_vectors[mgstruct.curr_level][2*i][j];
mgstruct.null_vectors[mgstruct.curr_level][2*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
}
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][2*i+1], mgstruct.curr_fine_size);
break;
case BLOCK_CORNER:
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
int c = j % mgstruct.n_vector; // What color index do we have?
// 0 to mgstruct.n_vector/2-1 is even, else is odd.
//int x_coord = (i - c)/mgstruct.n_vector % mgstruct.curr_x_fine;
//int y_coord = ((i - c)/mgstruct.n_vector - x_coord)/mgstruct.curr_x_fine;
// If c is even, it's from an even vector, otherwise it's from an odd vector!
if (c%4 == 1)
{
mgstruct.null_vectors[mgstruct.curr_level][4*i+1][j] = mgstruct.null_vectors[mgstruct.curr_level][4*i][j];
mgstruct.null_vectors[mgstruct.curr_level][4*i][j] = 0.0;
}
else if (c%4 == 2)
{
mgstruct.null_vectors[mgstruct.curr_level][4*i+2][j] = mgstruct.null_vectors[mgstruct.curr_level][4*i][j];
mgstruct.null_vectors[mgstruct.curr_level][4*i][j] = 0.0;
}
else if (c%4 == 3)
{
mgstruct.null_vectors[mgstruct.curr_level][4*i+3][j] = mgstruct.null_vectors[mgstruct.curr_level][4*i][j];
mgstruct.null_vectors[mgstruct.curr_level][4*i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+1], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+2], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+3], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i], mgstruct.null_vectors[mgstruct.curr_level][4*j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+1], mgstruct.null_vectors[mgstruct.curr_level][4*j+1], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+1],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+1],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+2], mgstruct.null_vectors[mgstruct.curr_level][4*j+2], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+2],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+2],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+3], mgstruct.null_vectors[mgstruct.curr_level][4*j+3], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+3],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+3],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i], mgstruct.null_vectors[mgstruct.curr_level][4*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+1], mgstruct.null_vectors[mgstruct.curr_level][4*j+1], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+2], mgstruct.null_vectors[mgstruct.curr_level][4*j+2], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+3], mgstruct.null_vectors[mgstruct.curr_level][4*j+3], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+1], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+2], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+3], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+1], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+2], mgstruct.null_vectors[mgstruct.curr_level][2*j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][4*i+3], mgstruct.null_vectors[mgstruct.curr_level][2*j+1], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+1], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+2], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][4*j+3], mgstruct.curr_fine_size);
}
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+1], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+2], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][4*i+3], mgstruct.curr_fine_size);
break;
case BLOCK_NONE:
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
if (do_global_ortho_conj)
if (do_global_ortho_conj)
{
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
conj<double>(mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
break;
}
}
delete[] c_rand_guess;
delete[] c_Arand_guess;
block_orthonormalize(&mgstruct);
// Print vector.
/*
cout << "\n\nPrinting null vectors:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "\nVector " << n << "\n";
for (int y = 0; y < mgstruct.curr_y_fine; y++)
{
for (int x = 0; x < mgstruct.curr_x_fine; x++)
{
cout << "(";
for (int c = 0; c < mgstruct.n_vector; c++)
{
cout << mgstruct.null_vectors[mgstruct.curr_level][n][y*mgstruct.curr_x_fine*mgstruct.curr_dof_fine+x*mgstruct.curr_dof_fine+c] << ",";
}
cout << ") ";
}
cout << "\n";
}
}*/
}
// Un-pop to the finest level.
for (i = 1; i < mgstruct.n_refine; i++)
{
level_up(&mgstruct);
}
mgstruct.matrix_vector = op; // Reset op to solved op.
}
// Reset the mass.
stagif.mass = MASS;
} // end skipping generation if we're only doing a top level or smoother test.
#endif // generate null vector.
#ifdef PRINT_NULL_VECTOR
cout << "\nCheck projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#ifdef EIGEN_TEST
if (do_eigentest)
{
for (int lev = 0; lev < mgstruct.n_refine; lev++)
{
// Test some eigenvectors!
// Generate min(volume/4, 128) eigenvectors.
int n_eigen = mgstruct.curr_fine_size/2;//min(mgstruct.curr_fine_size/4, 128);
int n_cv = mgstruct.curr_fine_size; //n_eigen*2 + n_eigen/2;
complex<double>* evals = new complex<double>[mgstruct.curr_fine_size];
complex<double>** evecs = new complex<double>*[mgstruct.curr_fine_size];
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
evecs[i] = new complex<double>[mgstruct.curr_fine_size];
}
// Get low mag half
arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen, n_cv); // max eigenvectors, internal vecs
char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues.
arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals, evecs, mgstruct.curr_fine_size, n_eigen, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct);
//arpack_dcn_free(&ar_strc);
// Print info about the eigensolve.
cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n";
// Get high mag half
//arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen, n_cv); // max eigenvectors, internal vecs
strcpy(eigtype, "LM"); // Smallest magnitude eigenvalues.
info_solve = arpack_dcn_getev(ar_strc, evals+(mgstruct.curr_fine_size/2), evecs+(mgstruct.curr_fine_size/2), mgstruct.curr_fine_size, n_eigen, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct);
arpack_dcn_free(&ar_strc);
// Print info about the eigensolve.
cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n";
cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n";
// End of arpack bindings!
// Sort eigenvalues (done differently depending on the operator).
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
for (j = 0; j < mgstruct.curr_fine_size /*n_eigen*/ -1; j++)
{
switch (opt)
{
case STAGGERED:
if (abs(imag(evals[j])) > abs(imag(evals[j+1])))
{
complex<double> teval = evals[j]; evals[j] = evals[j+1]; evals[j+1] = teval;
complex<double>* tevec = evecs[j]; evecs[j] = evecs[j+1]; evecs[j+1] = tevec;
}
break;
case LAPLACE:
case LAPLACE_NC2:
case G5_STAGGERED:
case STAGGERED_NORMAL:
case STAGGERED_INDEX:
if (abs(real(evals[j])) > abs(real(evals[j+1])))
{
complex<double> teval = evals[j]; evals[j] = evals[j+1]; evals[j+1] = teval;
complex<double>* tevec = evecs[j]; evecs[j] = evecs[j+1]; evecs[j+1] = tevec;
}
break;
}
}
}
cout << "\n\nAll eigenvalues:\n";
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
cout << "[L" << lev+1 << "_FINEVAL]: Mass " << MASS << " Num " << i << " Eval " << evals[i] << "\n";
normalize<double>(evecs[i], mgstruct.curr_fine_size);
}
complex<double>* evec_Pdag = new complex<double>[mgstruct.curr_coarse_size];
complex<double>* evec_Pdag2 = new complex<double>[mgstruct.curr_coarse_size];
complex<double>* evec_PPdag = new complex<double>[mgstruct.curr_fine_size];
// Test overlap of null vectors with eigenvectors.
// Formally, this is looking at the magnitude of (1 - P P^\dag) eigenvector.
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
// Zero out.
zero<double>(evec_Pdag, mgstruct.curr_coarse_size);
zero<double>(evec_PPdag, mgstruct.curr_fine_size);
// Restrict eigenvector.
restrict(evec_Pdag, evecs[i], &mgstruct);
// Prolong.
prolong(evec_PPdag, evec_Pdag, &mgstruct);
// Subtract off eigenvector, take norm.
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
evec_PPdag[j] -= evecs[i][j];
}
cout << "[L" << lev+1 << "_1mPPDAG]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n";
}
// Test how good of a preconditioner the coarse operator is.
// Formally, this is looking at the magnitude of (1 - P ( P^\dag A P )^(-1) P^\dag A) eigenvector.
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
// Zero out.
zero<double>(evec_Pdag, mgstruct.curr_coarse_size);
zero<double>(evec_Pdag2, mgstruct.curr_coarse_size);
zero<double>(evec_PPdag, mgstruct.curr_fine_size);
// Apply A.
fine_square_staggered(evec_PPdag, evecs[i], (void*)&mgstruct);
// Restrict.
restrict(evec_Pdag, evec_PPdag, &mgstruct);
// Invert A_coarse against it.
invif = minv_vector_gcr_restart(evec_Pdag2, evec_Pdag, mgstruct.curr_coarse_size, 10000, 1e-7, 64, coarse_square_staggered, (void*)&mgstruct);
// Prolong.
zero<double>(evec_PPdag, mgstruct.curr_coarse_size);
prolong(evec_PPdag, evec_Pdag2, &mgstruct);
// Subtract off eigenvector, take norm.
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
evec_PPdag[j] -= evecs[i][j];
}
cout << "[L" << lev+1 << "_1mP_Ac_PDAG_A]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n";
}
delete[] evec_Pdag;
delete[] evec_PPdag;
delete[] evec_Pdag2;
for (i = 0; i < mgstruct.curr_fine_size /*n_eigen*/; i++)
{
delete[] evecs[i];
}
delete[] evecs;
delete[] evals;
if (lev < mgstruct.n_refine-1)
{
level_down(&mgstruct);
}
}
for (int lev = mgstruct.n_refine-2; lev >= 0; lev--)
{
level_up(&mgstruct);
}
} // do_eigentest
#endif // EIGEN_TEST
#ifdef PDAGP_TEST
{
// Begin PdagP test.
// Describe the coarse lattice.
int x_coarse = x_fine/mgstruct.blocksize_x[0]; // how many coarse sites are there in the x dir?
int y_coarse = y_fine/mgstruct.blocksize_y[0]; // how many coarse sites are there in the y dir?
int coarse_size = x_coarse*y_coarse;
// Print the fine rhs.
cout << "Check fine point src:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs[x+y*x_fine] << " ";
}
cout << "\n";
}
cout << "Check projector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double> *rhs_PdagP = new complex<double>[Lat.get_lattice_size()];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
// Try applying the coarse Laplace operator!
complex<double>* rhs_A_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_A_coarse, coarse_size*mgstruct.n_vector);
cout << "Applying the coarse Laplace operator to coarse source.\n";
coarse_square_laplace(rhs_A_coarse, rhs_coarse, (void*)&mgstruct);
// Check A coarse source.
cout << "Check A times coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_A_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong rhs_A_coarse.
cout << "Prolong A times coarse source.\n";
complex<double>* rhs_PAP_fine = new complex<double>[Lat.get_lattice_size()];
zero<double>(rhs_PAP_fine, Lat.get_lattice_size());
prolong(rhs_PAP_fine, rhs_A_coarse, &mgstruct);
// Check PAP.
cout << "Check PAP on source.\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PAP_fine[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_A_coarse;
delete[] rhs_PdagP;
delete[] rhs_PAP_fine;
}
#endif
#ifdef PDAGP_2TEST
// Test adding a second projector.
{
mgstruct.n_vector = 2;
complex<double>* tmp_store = mgstruct.null_vectors[0];
delete[] mgstruct.null_vectors;
mgstruct.null_vectors = new complex<double>*[mgstruct.n_vector];
mgstruct.null_vectors[0] = tmp_store;
mgstruct.null_vectors[1] = new complex<double>[Lat.get_lattice_size()];
// Add an even/odd vector.
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
if ((x+y)%2 == 0)
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,1.0);
else
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,-1.0);
}
}
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << "(";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << rhs_coarse[(x+y*x_coarse)*mgstruct.n_vector+n] << ",";
}
cout << ") ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double>* rhs_PdagP = new complex<double>[Lat.get_lattice_size()];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_PdagP;
}
#endif
#ifdef COARSE_ONLY
cout << "[COARSE]: Solving coarse system only.\n";
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_coarse, coarse_size*mgstruct.n_vector);
restrict(rhs_coarse, rhs, &mgstruct);
cout << "[COARSE]: Norm of coarse rhs " << sqrt(norm2sq<double>(rhs_coarse, coarse_size*mgstruct.n_vector)) << ".\n";
complex<double>* lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(lhs_coarse, coarse_size*mgstruct.n_vector);
invif = minv_vector_gcr_restart(lhs_coarse, rhs_coarse, coarse_size*mgstruct.n_vector, 10000, 1e-6, 16, coarse_square_staggered, (void*)&mgstruct);
if (invif.success == true)
{
printf("[COARSE]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[COARSE]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[COARSE]: This may be because the max iterations was reached.\n");
}
printf("[COARSE]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
complex<double>* A_lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(A_lhs_coarse, coarse_size*mgstruct.n_vector);
coarse_square_laplace(A_lhs_coarse, lhs_coarse, (void*)&mgstruct);
for (i = 0; i < coarse_size*mgstruct.n_vector; i++)
{
explicit_resid += real(conj(A_lhs_coarse[i] - rhs_coarse[i])*(A_lhs_coarse[i] - rhs_coarse[i]));
}
explicit_resid = sqrt(explicit_resid);
printf("[COARSE]: [check] should equal [rhs]. The residual is %15.20e.\n", explicit_resid);
complex<double>* pro_lhs_coarse = new complex<double>[N*N];
zero<double>(pro_lhs_coarse, N*N);
prolong(pro_lhs_coarse, lhs_coarse, &mgstruct);
complex<double>* pro_rhs_coarse = new complex<double>[N*N];
zero<double>(pro_rhs_coarse, N*N);
square_staggered_u1(pro_rhs_coarse, pro_lhs_coarse, (void*)&stagif);
#endif // COARSE_ONLY
if (my_test == TOP_LEVEL_ONLY)
{
// Try a direct solve.
cout << "\n[ORIG]: Solve fine system.\n";
invif = minv_vector_gcr_restart(lhs, rhs, Lat.get_lattice_size(), 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb);
//invif = minv_vector_gcr_restart(lhs, rhs, Lat.get_lattice_size(), 100000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif);
if (invif.success == true)
{
printf("[ORIG]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[ORIG]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[ORIG]: This may be because the max iterations was reached.\n");
}
printf("[ORIG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
zero<double>(check, Lat.get_lattice_size());
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < Lat.get_lattice_size(); i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[ORIG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // TOP_LEVEL_ONLY
#ifdef COARSE_ONLY
// Compare PAP solution to real solution.
cout << "\n[COARSE]: Compare solutions.\n";
double comparison = 0;
double resid_comparison = 0;
for (i = 0; i < Lat.get_lattice_size(); i++)
{
comparison += real(conj(pro_lhs_coarse[i]-lhs[i])*(pro_lhs_coarse[i]-lhs[i]));
resid_comparison += real(conj(pro_rhs_coarse[i]-rhs[i])*(pro_rhs_coarse[i]-rhs[i]));
}
comparison = sqrt(explicit_resid);
printf("[COARSE]: The solutions deviate by %15.20e.\n", comparison);
printf("[COARSE]: The projected residual has a rel res of %15.20e.\n", sqrt(resid_comparison)/bnorm);
delete[] rhs_coarse;
delete[] lhs_coarse;
delete[] A_lhs_coarse;
delete[] pro_lhs_coarse;
delete[] pro_rhs_coarse;
#endif // COARSE_ONLY
if (my_test == SMOOTHER_ONLY || my_test == TWO_LEVEL || my_test == THREE_LEVEL)
{
// Let's actually test a multigrid solve!
cout << "\n[MG]: Test MG solve.\n";
// Block normalize the null vectors.
block_normalize(&mgstruct);
// Well, maybe this will work?
zero<double>(lhs, Lat.get_lattice_size());
//invif = minv_vector_cg_flex_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
invif = minv_vector_gcr_var_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
//invif = minv_vector_gcr_var_precond_restart(lhs, rhs, Lat.get_lattice_size(), 10000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif, mg_preconditioner, (void*)&mgprecond);
if (invif.success == true)
{
printf("[L1]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[L1]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[L1]: This may be because the max iterations was reached.\n");
}
printf("[MG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = diffnorm2sq(rhs, check, Lat.get_lattice_size())/bnorm;
printf("[MG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // SMOOTHER_ONLY or TWO_LEVEL
// Look at the two point function!
if (source == ORIGIN_POINT)
{
double* corr = new double[Lat.get_lattice_dimension(1)];
cout << "BEGIN_GOLDSTONE\n";
for (i = 0; i < Lat.get_lattice_dimension(1); i++)
{
corr[i] = 0.0;
for (j = 0; j < Lat.get_lattice_dimension(0); j++)
{
corr[i] += real(conj(lhs[i*Lat.get_lattice_dimension(0)+j])*lhs[i*Lat.get_lattice_dimension(0)+j]);
}
cout << i << " " << corr[i] << "\n";
}
cout << "END_GOLDSTONE\n";
cout << "BEGIN_EFFMASS\n";
for (i = 0; i < Lat.get_lattice_dimension(1); i++)
{
cout << i << " " << log(corr[i]/corr[(i+1)%Lat.get_lattice_dimension(1)]) << "\n";
}
cout << "END_EFFMASS\n";
}
// Free the lattice.
delete[] lattice;
delete[] lhs;
delete[] rhs;
delete[] check;
delete[] tmp;
delete[] tmp2;
delete[] gauge_trans;
// Clean up!
delete[] coord;
delete[] mgstruct.blocksize_x;
delete[] mgstruct.blocksize_y;
for (i = 0; i < mgstruct.n_refine; i++)
{
for (j = 0; j < mgstruct.n_vector; j++)
{
delete[] mgstruct.null_vectors[i][j];
}
delete[] mgstruct.null_vectors[i];
}
delete[] mgstruct.null_vectors;
return 0;
}
// Custom routine to load gauge field.
void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA)
{
if (x_fine == 32 && y_fine == 32)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 64 && y_fine == 64)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 128 && y_fine == 128)
{
if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist. Using unit gauge.\n";
}
}
|
// This is a sample code that constructs general kinetic terms!
#include <iostream>
#include <iomanip> // to set output precision.
#include <cmath>
#include <string>
#include <sstream>
#include <complex>
#include <random>
#include <cstring> // should be replaced by using sstream
#include "generic_inverters.h"
#include "generic_inverters_precond.h"
#include "generic_vector.h"
#include "verbosity.h"
#include "mg.h"
#include "mg_real.h"
#include "mg_complex.h"
#include "u1_utils.h"
// Do restrict/prolong test?
//#define PDAGP_TEST
// Do two vector restrict/prolong?
//#define PDAGP_2TEST
// Try solving just the coarse solver.
//#define COARSE_ONLY
using namespace std;
// Define pi.
#define PI 3.141592653589793
// Print null vectors?
//#define PRINT_NULL_VECTOR
// Do null vector generation? Currently uses BiCGStab
#define GEN_NULL_VECTOR
// How many GCR iterations do we use?
//#define GEN_NULL_VECTOR_STEP 300
//#define GEN_NULL_VECTOR_REL_RESID 1e-4
//#define AGGREGATE_FOUR
//#define AGGREGATE_EOCONJ
// Are we testing a random gauge rotation?
//#define TEST_RANDOM_GAUGE
// Are we testing a random field?
//#define TEST_RANDOM_FIELD
// Are we loading a gauge field?
#define LOAD_GAUGE_FIELD
// What type of test should we do?
enum mg_test_types
{
TOP_LEVEL_ONLY = 0, // only test the top level solver.
SMOOTHER_ONLY = 1, // Top level + smoother
TWO_LEVEL = 2, // Two level MG
THREE_LEVEL = 3 // Three level MG
};
// How should we generate null vectors?
enum mg_null_gen_type
{
NULL_GCR = 0, // Generate null vectors with GCR
NULL_BICGSTAB = 1, // Generate null vectors with BiCGStab
NULL_CG = 2, // Generate null vectors with CG
};
// Square laplace 2d operator w/out u1 function.
void square_laplace(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square staggered 2d operator w/out u1 function.
void square_staggered(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square staggered 2d operator w/ u1 function.
void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// \gamma_5
void gamma_5(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square \gamma_5 staggered 2d operator w/ u1 function.
void square_staggered_gamma5_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Staggered normal equations.
void square_staggered_normal_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
enum op_type
{
STAGGERED = 0,
LAPLACE = 1,
LAPLACE_NC2 = 2,
G5_STAGGERED = 3,
STAGGERED_NORMAL = 4
};
enum src_type
{
POINT = 0,
RANDOM_GAUSSIAN = 1,
ORIGIN_POINT = 2 // for correlator test.
};
struct staggered_u1_op
{
complex<double> *lattice;
double mass;
int x_fine;
int y_fine;
int Nc; // only relevant for square laplace.
};
int main(int argc, char** argv)
{
// Declare some variables.
cout << setiosflags(ios::scientific) << setprecision(6);
int i, j, x, y;
complex<double> *lattice; // Holds the gauge field.
complex<double> *lhs, *rhs, *check; // For some Kinetic terms.
double explicit_resid = 0.0;
double bnorm = 0.0;
std::mt19937 generator (1337u); // RNG, 1337u is the seed.
inversion_info invif;
staggered_u1_op stagif;
// Set parameters.
// What operator are we using for the solve? (Laplace is free only.)
op_type opt = G5_STAGGERED; // STAGGERED, LAPLACE, LAPLACE_NC2, G5_STAGGERED
// What operator are we using for null vector generation?
op_type opt_null = STAGGERED_NORMAL;
// What test are we performing?
mg_test_types my_test = TWO_LEVEL; //THREE_LEVEL; // TWO_LEVEL is the default which won't override anything.
// How are we generating null vectors?
mg_null_gen_type null_gen = NULL_CG; // NULL_BICGSTAB, NULL_GCR, NULL_CG
// L_x = L_y = Dimension for a square lattice.
int square_size = 32; // Can be set on command line with --square_size.
// Describe the staggered fermions.
double MASS = 0.01; // Can be overridden on command line with --mass
// Describe the source type.
src_type source = RANDOM_GAUSSIAN; // POINT, RANDOM_GAUSSIAN, or ORIGIN_POINT (for correlator test).
// Outer Inverter information.
double outer_precision = 5e-7;
int outer_restart = 64;
// Multigrid information.
int n_refine = 1; // 1 = two level V cycle, 2 = three level V cycle, etc.
// Can be set on command line with --nrefine
if (my_test == THREE_LEVEL) // FOR TEST ONLY
{
n_refine = 2;
}
int X_BLOCKSIZE = 4; // Can be overrided with below arg on command line
int Y_BLOCKSIZE = 4; // with --blocksize
int eo = 1; // 0 for no even/odd aggregation, 1 for even/odd aggregation.
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
eo = 0;
}
// Null vector generation
// If GEN_NULL_VECTOR isn't defined:
// 1 for just const vector, 2 for const + even/odd vector, 4 for each corner
// of the hypercube.
// If GEN_NULL_VECTOR is defined and eo = 0:
// Generate "n_null_vector" null vectors which are block orthogonalized.
// IF GEN_NULL_VECTOR is defined and eo = 1:
// Generate "n_null_vector" null vectors, partition into even and odd.
// Total number of null vectors is 2*VECTOR_COUNT.
int n_null_vector = 4; // Note: Gets multiplied by 2 for LAPLACE_NC2 test.
// Can be override on command line with --nvec
int null_max_iter = 500;
double null_precision = 5e-5; //5e-4;
// Advanced:
// IF GEN_NULL_VECTOR is defined and AGGREGATE_EOCONJ is defined:
// Generate VECTOR_COUNT null vectors, partition into even and odd, duplicate complex conj.
// Total number of null vectors is 4*VECTOR_COUNT.
// IF GEN_NULL_VECTOR is defined and AGGREGATE_EO is defined:
// Generate VECTOR_COUNT null vectors, partition into corners of hypercube.
// Total number of null vectors is 4*VECTOR_COUNT.
// Inner solver.
inner_solver in_solve = GCR; //CR; //GCR;
double inner_precision = 1e-3;
int inner_restart = 64;
int inner_max = 1000;
if (my_test == SMOOTHER_ONLY)
{
in_solve = NONE;
}
// Smoother
inner_solver in_smooth = GCR; //NONE; //GCR; BICGSTAB
double omega_smooth = 0.67; // for MR only.
int pre_smooth = 6;
int post_smooth = 6;
// Gauge field information.
double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta).
// For heatbath gauge field, corresponds to non-compact beta.
// Can be set on command line with --beta.
/////////////////////////////////////////////
// Get a few parameters from command line. //
/////////////////////////////////////////////
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0)
{
cout << "--mass [mass] (default 1e-2)\n";
cout << "--blocksize [blocksize] (default 4)\n";
cout << "--nvec [nvec] (default 4)\n";
cout << "--nrefine [number coarse] (default 1)\n";
cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n";
cout << "--square_size [32, 64, 128] (default 32)\n";
return 0;
}
if (i+1 != argc)
{
if (strcmp(argv[i], "--mass") == 0)
{
MASS = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--blocksize") == 0)
{
X_BLOCKSIZE = atoi(argv[i+1]);
Y_BLOCKSIZE = X_BLOCKSIZE;
i++;
}
else if (strcmp(argv[i], "--nvec") == 0)
{
n_null_vector = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--nrefine") == 0)
{
n_refine = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--beta") == 0)
{
BETA = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--square_size") == 0)
{
square_size = atoi(argv[i+1]);
i++;
}
}
}
//printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector);
//return 0;
///////////////////////////////////////
// End of human-readable parameters! //
///////////////////////////////////////
string op_name;
void (*op)(complex<double>*, complex<double>*, void*);
switch (opt)
{
case STAGGERED:
op = square_staggered_u1;
op_name = "Staggered U(1)";
break;
case LAPLACE:
op_name = "Free Laplace";
op = square_laplace;
break;
case LAPLACE_NC2:
op_name = "Free Laplace Nc = 2";
op = square_laplace;
break;
case G5_STAGGERED:
op_name = "Gamma_5 Staggered U(1)";
op = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_name = "Staggered U(1) Normal";
op = square_staggered_normal_u1;
}
cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n";
// Only relevant for free laplace test.
int Nc = 1; // Only value that matters for staggered
if (opt == LAPLACE_NC2)
{
Nc = 2;
}
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
n_null_vector *= Nc;
}
// Describe the fine lattice.
int x_fine = square_size;
int y_fine = square_size;
int fine_size = x_fine*y_fine*Nc;
cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine;
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
cout << " Nc " << Nc;
}
cout << "\n";
// Do some allocation.
// Initialize the lattice. Indexing: index = y*N + x.
lattice = new complex<double>[2*fine_size];
lhs = new complex<double>[fine_size];
rhs = new complex<double>[fine_size];
check = new complex<double>[fine_size];
// Zero it out.
zero<double>(lattice, 2*fine_size);
zero<double>(rhs, fine_size);
zero<double>(lhs, fine_size);
zero<double>(check, fine_size);
//
// Fill stagif.
stagif.lattice = lattice;
stagif.mass = MASS;
stagif.x_fine = x_fine;
stagif.y_fine = y_fine;
stagif.Nc = Nc; // Only relevant for laplace test only.
// Create the verbosity structure.
inversion_verbose_struct verb;
verb.verbosity = VERB_DETAIL;
verb.verb_prefix = "[L1]: ";
verb.precond_verbosity = VERB_NONE;
verb.precond_verb_prefix = "Prec ";
// Describe the gauge field.
cout << "[GAUGE]: Creating a gauge field.\n";
unit_gauge_u1(lattice, x_fine, y_fine);
#ifdef TEST_RANDOM_FIELD
gauss_gauge_u1(lattice, x_fine, y_fine, generator, BETA);
cout << "[GAUGE]: Created a U(1) gauge field with angle standard deviation " << 1.0/sqrt(BETA) << "\n";
#endif
#ifdef LOAD_GAUGE_FIELD
if (x_fine == 32 && y_fine == 32)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 64 && y_fine == 64)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 128 && y_fine == 128)
{
if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
#endif // LOAD_GAUGE_FIELD
#ifdef TEST_RANDOM_GAUGE
// Generate and perform a random gauge transformation.
complex<double>* gauge_trans = new complex<double>[fine_size];
rand_trans_u1(gauge_trans, x_fine, y_fine, generator);
apply_gauge_trans_u1(lattice, gauge_trans, x_fine, y_fine);
cout << "[GAUGE]: Performed a random gauge rotation.\n";
#endif
cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, x_fine, y_fine) << ".\n";
// Sanity check if we're doing a multigrid solve.
if (n_refine == 0)
{
my_test = TOP_LEVEL_ONLY;
}
string op_null_name;
void (*op_null)(complex<double>*, complex<double>*, void*);
switch (opt_null)
{
case STAGGERED:
op_null = square_staggered_u1;
op_null_name = "Staggered U(1)";
break;
case LAPLACE:
op_null_name = "Free Laplace";
op_null = square_laplace;
break;
case LAPLACE_NC2:
op_null_name = "Free Laplace Nc = 2";
op_null = square_laplace;
break;
case G5_STAGGERED:
op_null_name = "Gamma_5 Staggered U(1)";
op_null = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_null_name = "Staggered U(1) Normal";
op_null = square_staggered_normal_u1;
break;
}
cout << "[OP]: Null Gen Operator " << op_null_name << "\n";
// Build an mg_struct.
mg_operator_struct_complex mgstruct;
mgstruct.x_fine = x_fine;
mgstruct.y_fine = y_fine;
mgstruct.Nc = Nc; // only matters for square laplace.
mgstruct.n_refine = n_refine;
mgstruct.blocksize_x = new int[n_refine];
mgstruct.blocksize_y = new int[n_refine];
for (i = 0; i < n_refine; i++)
{
mgstruct.blocksize_x[i] = X_BLOCKSIZE;
mgstruct.blocksize_y[i] = Y_BLOCKSIZE;
}
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
mgstruct.n_vector = 4*n_null_vector;
mgstruct.eo = 1;
#elif defined GEN_NULL_VECTOR
mgstruct.eo = eo;
mgstruct.n_vector = (eo+1)*n_null_vector;
#else
mgstruct.eo = eo;
mgstruct.n_vector = (eo+1)*n_null_vector;
#endif
mgstruct.matrix_vector = op; //square_staggered_u1;
mgstruct.matrix_extra_data = (void*)&stagif;
cout << "[MG]: X_Block " << X_BLOCKSIZE << " Y_Block " << Y_BLOCKSIZE << " NullVectors " << n_null_vector << "\n";
// Set the starting mg_struct state.
mgstruct.curr_level = 0; // Ready to do top level -> second level.
mgstruct.curr_dof_fine = Nc; // Top level has only one d.o.f. per site.
mgstruct.curr_x_fine = mgstruct.x_fine;
mgstruct.curr_y_fine = mgstruct.y_fine;
mgstruct.curr_fine_size = mgstruct.curr_y_fine*mgstruct.curr_x_fine*mgstruct.curr_dof_fine;
mgstruct.curr_dof_coarse = mgstruct.n_vector;
mgstruct.curr_x_coarse = mgstruct.x_fine/mgstruct.blocksize_x[0];
mgstruct.curr_y_coarse = mgstruct.y_fine/mgstruct.blocksize_y[0];
mgstruct.curr_coarse_size = mgstruct.curr_y_coarse*mgstruct.curr_x_coarse*mgstruct.curr_dof_coarse;
// Build the mg inverter structure.
// Set up the MG preconditioner.
mg_precond_struct_complex mgprecond;
mgprecond.in_smooth_type = in_smooth; // What inner smoother? MR or GCR.
mgprecond.omega_smooth = omega_smooth; // What relaxation parameter should we use (MR only!)
mgprecond.n_pre_smooth = pre_smooth; // 6 MR smoother steps before coarsening.
mgprecond.n_post_smooth = post_smooth; // 6 MR smoother steps after refining.
mgprecond.in_solve_type = in_solve; // What inner solver? NONE, MR, CG, GCR, BICGSTAB
mgprecond.n_max = inner_max; // max number of steps to use for inner solver.
mgprecond.n_restart = inner_restart; // frequency of restart (relevant for CG, GCR).
mgprecond.rel_res = inner_precision; // Maximum relative residual for inner solver.
mgprecond.mgstruct = &mgstruct; // Contains null vectors, fine operator. (Since we don't construct the fine op.)
mgprecond.coarse_matrix_vector = coarse_square_staggered; // Function which applies the coarse operator.
mgprecond.fine_matrix_vector = fine_square_staggered; // Function which applies the fine operator.
mgprecond.matrix_extra_data = (void*)&mgstruct; // What extra_data the coarse operator expects.
// Set right hand side.
switch (source)
{
case POINT: // Set a point.
for (i = 0; i < Nc; i++)
{
rhs[(x_fine/2+(y_fine/2)*x_fine)*Nc+i] = 1.0;
}
break;
case RANDOM_GAUSSIAN: // Random rhs.
gaussian<double>(rhs, fine_size, generator);
break;
case ORIGIN_POINT: // Set a point for correlator computation.
for (i = 0; i < Nc; i++)
{
rhs[i] = 1.0;
}
}
// Get norm for rhs.
bnorm = sqrt(norm2sq<double>(rhs, fine_size));
// Set a point on the lhs.
//lhs[x_fine/2+(y_fine/2)*x_fine+1] = 1.0;
// Create a projector.
mgstruct.null_vectors = new complex<double>**[mgstruct.n_refine];
// The top level is special since there are no color indices.
mgstruct.null_vectors[0] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[0][j] = new complex<double>[fine_size];
zero<double>(mgstruct.null_vectors[0][j], fine_size);
}
// Higher levels are different.
if (mgstruct.n_refine > 1)
{
for (i = 1; i < mgstruct.n_refine; i++)
{
level_down(&mgstruct);
mgstruct.null_vectors[i] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[i][j] = new complex<double>[mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine];
zero<double>(mgstruct.null_vectors[i][j], mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine);
}
}
// Come back up!
for (i = mgstruct.n_refine; i > 1; i--)
{
level_up(&mgstruct);
}
}
cout << "[MG]: Creating " << mgstruct.n_vector << " projector(s).\n";
#ifndef GEN_NULL_VECTOR
// Make a constant projector.
if (mgstruct.n_vector == 1)
{
cout << "[MG]: Null vector 1 is a constant.\n";
for (i = 0; i < fine_size; i++)
{
mgstruct.null_vectors[0][0][i] = 1;
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][0][i] *= gauge_trans[i];
#endif
}
}
else if (mgstruct.n_vector == 2) // constant, even/odd phase.
{
cout << "[MG]: Null vector 1 is a constant.\n";
cout << "[MG]: Null vector 2 is an even/odd phase.\n";
for (i = 0; i < fine_size; i++)
{
mgstruct.null_vectors[0][0][i] = 1;
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][1][i] = ((x+y)%2 == 0) ? complex<double>(0.0,1.0) : complex<double>(0.0,-1.0);
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][0][i] *= (gauge_trans[i]);
mgstruct.null_vectors[0][1][i] *= (gauge_trans[i]);
#endif
}
}
else if (mgstruct.n_vector == 4) // 4 corners of hypercube.
{
cout << "[MG]: Null vector 1 is a constant on unit corner (0,0).\n";
cout << "[MG]: Null vector 2 is a constant on unit corner (1,0).\n";
cout << "[MG]: Null vector 3 is a constant on unit corner (0,1).\n";
cout << "[MG]: Null vector 4 is a constant on unit corner (1,1).\n";
// Generate a normal distribution.
std::normal_distribution<> dist(1.0, 0.1);
for (i = 0; i < fine_size; i++)
{
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = 1.0;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = dist(generator);
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] *= (gauge_trans[i]);
#endif
}
}
else // invalid.
{
cout << "Unless you are generating null vectors, you can only use 1, 2, or 4 null vectors.\n";
return 0;
}
#ifdef TEST_RANDOM_GAUGE
delete[] gauge_trans;
#endif
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
#ifdef PRINT_NULL_VECTOR
cout << "[MG]: Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#else // generate null vector
// Skip this depending on our test!
if (!(my_test == TOP_LEVEL_ONLY || my_test == SMOOTHER_ONLY))
{
// Generate top level!
printf("About to generate null vector.\n"); fflush(stdout);
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* rand_guess = new complex<double>[fine_size];
complex<double>* Arand_guess = new complex<double>[fine_size];
// Temporarily set the mass to zero for the null vector generation.
stagif.mass = stagif.mass*1e-2;
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
for (i = 0; i < mgstruct.n_vector/4; i++) // Because we partition fourfold afterwards.
#else // GEN_NULL_VECTOR is defined.
for (i = 0; i < mgstruct.n_vector/(mgstruct.eo+1); i++)
#endif
{
gaussian<double>(rand_guess, fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
#else
if (mgstruct.eo == 1)
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size);
}
else // no eo.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
}
#endif
}
}
// If we're using the staggered normal to generate, multiply the random source by gamma_5 D.
/*if (opt_null == STAGGERED_NORMAL)
{
copy<double>(Arand_guess, rand_guess, fine_size);
square_staggered_gamma5_u1(rand_guess, Arand_guess, (void*)&stagif);
zero<double>(Arand_guess, fine_size);
}*/
zero<double>(Arand_guess, fine_size);
(*op_null)(Arand_guess, rand_guess, (void*)&stagif);
//square_staggered_u1(Arand_guess, rand_guess, (void*)&stagif);
for (j = 0; j < fine_size; j++)
{
Arand_guess[j] = -Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[0][i], fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
}
for (j = 0; j < fine_size; j++)
{
mgstruct.null_vectors[0][i][j] += rand_guess[j];
}
// Aggregate in chirality (or corners) as needed, orthogonalize against previous vectors.
#if defined GEN_NULL_VECTOR && defined AGGREGATE_FOUR
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / x_fine;
if (x%2 == 1 && y%2 == 0)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
else if (x%2 == 0 && y%2 == 1)
{
mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
else if (x%2 == 1 && y%2 == 1)
{
mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4],fine_size))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
#elif defined GEN_NULL_VECTOR && defined AGGREGATE_EOCONJ
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / y_fine;
if ((x+y)%2 == 1)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
copy<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][i], fine_size);
copy<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
conj(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
conj(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4],fine_size))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
#else // even/odd
if (mgstruct.eo == 1)
{
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / y_fine;
if ((x+y)%2 == 1)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/2][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/2],fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], fine_size);
}
else
{
normalize(mgstruct.null_vectors[0][i], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
}
#endif // defined GEN_NULL_VECTOR && defined AGGREGATE_FOUR
}
// This causes a segfault related to the RNG when
// the vector is initialized.
delete[] rand_guess;
delete[] Arand_guess;
#ifdef PRINT_NULL_VECTOR
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
// Do we need to generate more levels?
if (mgstruct.n_refine > 1)
{
mgstruct.matrix_vector = op_null; // Trick op to null gen op.
for (int n = 1; n < mgstruct.n_refine; n++)
{
level_down(&mgstruct);
cout << "curr_fine_size: " << mgstruct.curr_fine_size << "\n";
// Let's give it a whirl?!
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* c_rand_guess = new complex<double>[mgstruct.curr_fine_size];
complex<double>* c_Arand_guess = new complex<double>[mgstruct.curr_fine_size];
// Generate null vectors with the current level.
for (i = 0; i < mgstruct.n_vector/(mgstruct.eo+1); i++)
{
gaussian<double>(c_rand_guess, mgstruct.curr_fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
if (mgstruct.eo == 1)
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else // no eo.
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
}
zero<double>(c_Arand_guess, mgstruct.curr_fine_size);
fine_square_staggered(c_Arand_guess, c_rand_guess, (void*)&mgstruct);
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
c_Arand_guess[j] = -c_Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
}
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
mgstruct.null_vectors[mgstruct.curr_level][i][j] += c_rand_guess[j];
}
// Aggregate in chirality, orthogonalize against previous vectors.
if (mgstruct.eo == 1)
{
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
int c = j % mgstruct.n_vector; // What color index do we have?
// 0 to mgstruct.n_vector/2-1 is even, else is odd.
//int x_coord = (i - c)/mgstruct.n_vector % mgstruct.curr_x_fine;
//int y_coord = ((i - c)/mgstruct.n_vector - x_coord)/mgstruct.curr_x_fine;
if (c >= mgstruct.n_vector/2)
{
mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2][j] = mgstruct.null_vectors[mgstruct.curr_level][i][j];
mgstruct.null_vectors[mgstruct.curr_level][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else
{
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
}
}
delete[] c_rand_guess;
delete[] c_Arand_guess;
block_orthonormalize(&mgstruct);
// Print vector.
/*
cout << "\n\nPrinting null vectors:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "\nVector " << n << "\n";
for (int y = 0; y < mgstruct.curr_y_fine; y++)
{
for (int x = 0; x < mgstruct.curr_x_fine; x++)
{
cout << "(";
for (int c = 0; c < mgstruct.n_vector; c++)
{
cout << mgstruct.null_vectors[mgstruct.curr_level][n][y*mgstruct.curr_x_fine*mgstruct.curr_dof_fine+x*mgstruct.curr_dof_fine+c] << ",";
}
cout << ") ";
}
cout << "\n";
}
}*/
}
// Un-pop to the finest level.
for (i = 1; i < mgstruct.n_refine; i++)
{
level_up(&mgstruct);
}
mgstruct.matrix_vector = op; // Reset op to solved op.
}
// Reset the mass.
stagif.mass = MASS;
} // end skipping generation if we're only doing a top level or smoother test.
#endif // generate null vector.
#ifdef PRINT_NULL_VECTOR
cout << "\nCheck projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#ifdef PDAGP_TEST
{
// Begin PdagP test.
// Describe the coarse lattice.
int x_coarse = x_fine/mgstruct.blocksize_x[0]; // how many coarse sites are there in the x dir?
int y_coarse = y_fine/mgstruct.blocksize_y[0]; // how many coarse sites are there in the y dir?
int coarse_size = x_coarse*y_coarse;
// Print the fine rhs.
cout << "Check fine point src:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs[x+y*x_fine] << " ";
}
cout << "\n";
}
cout << "Check projector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double> *rhs_PdagP = new complex<double>[fine_size];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
// Try applying the coarse Laplace operator!
complex<double>* rhs_A_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_A_coarse, coarse_size*mgstruct.n_vector);
cout << "Applying the coarse Laplace operator to coarse source.\n";
coarse_square_laplace(rhs_A_coarse, rhs_coarse, (void*)&mgstruct);
// Check A coarse source.
cout << "Check A times coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_A_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong rhs_A_coarse.
cout << "Prolong A times coarse source.\n";
complex<double>* rhs_PAP_fine = new complex<double>[fine_size];
zero<double>(rhs_PAP_fine, fine_size);
prolong(rhs_PAP_fine, rhs_A_coarse, &mgstruct);
// Check PAP.
cout << "Check PAP on source.\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PAP_fine[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_A_coarse;
delete[] rhs_PdagP;
delete[] rhs_PAP_fine;
}
#endif
#ifdef PDAGP_2TEST
// Test adding a second projector.
{
mgstruct.n_vector = 2;
complex<double>* tmp_store = mgstruct.null_vectors[0];
delete[] mgstruct.null_vectors;
mgstruct.null_vectors = new complex<double>*[mgstruct.n_vector];
mgstruct.null_vectors[0] = tmp_store;
mgstruct.null_vectors[1] = new complex<double>[fine_size];
// Add an even/odd vector.
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
if ((x+y)%2 == 0)
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,1.0);
else
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,-1.0);
}
}
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << "(";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << rhs_coarse[(x+y*x_coarse)*mgstruct.n_vector+n] << ",";
}
cout << ") ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double>* rhs_PdagP = new complex<double>[fine_size];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_PdagP;
}
#endif
#ifdef COARSE_ONLY
cout << "[COARSE]: Solving coarse system only.\n";
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_coarse, coarse_size*mgstruct.n_vector);
restrict(rhs_coarse, rhs, &mgstruct);
cout << "[COARSE]: Norm of coarse rhs " << sqrt(norm2sq<double>(rhs_coarse, coarse_size*mgstruct.n_vector)) << ".\n";
complex<double>* lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(lhs_coarse, coarse_size*mgstruct.n_vector);
invif = minv_vector_gcr_restart(lhs_coarse, rhs_coarse, coarse_size*mgstruct.n_vector, 10000, 1e-6, 16, coarse_square_staggered, (void*)&mgstruct);
if (invif.success == true)
{
printf("[COARSE]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[COARSE]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[COARSE]: This may be because the max iterations was reached.\n");
}
printf("[COARSE]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
complex<double>* A_lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(A_lhs_coarse, coarse_size*mgstruct.n_vector);
coarse_square_laplace(A_lhs_coarse, lhs_coarse, (void*)&mgstruct);
for (i = 0; i < coarse_size*mgstruct.n_vector; i++)
{
explicit_resid += real(conj(A_lhs_coarse[i] - rhs_coarse[i])*(A_lhs_coarse[i] - rhs_coarse[i]));
}
explicit_resid = sqrt(explicit_resid);
printf("[COARSE]: [check] should equal [rhs]. The residual is %15.20e.\n", explicit_resid);
complex<double>* pro_lhs_coarse = new complex<double>[N*N];
zero<double>(pro_lhs_coarse, N*N);
prolong(pro_lhs_coarse, lhs_coarse, &mgstruct);
complex<double>* pro_rhs_coarse = new complex<double>[N*N];
zero<double>(pro_rhs_coarse, N*N);
square_staggered_u1(pro_rhs_coarse, pro_lhs_coarse, (void*)&stagif);
#endif // COARSE_ONLY
if (my_test == TOP_LEVEL_ONLY)
{
// Try a direct solve.
cout << "\n[ORIG]: Solve fine system.\n";
invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb);
//invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif);
if (invif.success == true)
{
printf("[ORIG]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[ORIG]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[ORIG]: This may be because the max iterations was reached.\n");
}
printf("[ORIG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
zero<double>(check, fine_size);
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < fine_size; i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[ORIG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // TOP_LEVEL_ONLY
#ifdef COARSE_ONLY
// Compare PAP solution to real solution.
cout << "\n[COARSE]: Compare solutions.\n";
double comparison = 0;
double resid_comparison = 0;
for (i = 0; i < fine_size; i++)
{
comparison += real(conj(pro_lhs_coarse[i]-lhs[i])*(pro_lhs_coarse[i]-lhs[i]));
resid_comparison += real(conj(pro_rhs_coarse[i]-rhs[i])*(pro_rhs_coarse[i]-rhs[i]));
}
comparison = sqrt(explicit_resid);
printf("[COARSE]: The solutions deviate by %15.20e.\n", comparison);
printf("[COARSE]: The projected residual has a rel res of %15.20e.\n", sqrt(resid_comparison)/bnorm);
delete[] rhs_coarse;
delete[] lhs_coarse;
delete[] A_lhs_coarse;
delete[] pro_lhs_coarse;
delete[] pro_rhs_coarse;
#endif // COARSE_ONLY
if (my_test == SMOOTHER_ONLY || my_test == TWO_LEVEL || my_test == THREE_LEVEL)
{
// Let's actually test a multigrid solve!
cout << "\n[MG]: Test MG solve.\n";
// Block normalize the null vectors.
block_normalize(&mgstruct);
// Well, maybe this will work?
zero<double>(lhs, fine_size);
invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
//invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 10000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif, mg_preconditioner, (void*)&mgprecond);
if (invif.success == true)
{
printf("[L1]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[L1]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[L1]: This may be because the max iterations was reached.\n");
}
printf("[MG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < fine_size; i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[MG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // SMOOTHER_ONLY or TWO_LEVEL
// Look at the two point function!
if (source == ORIGIN_POINT)
{
double* corr = new double[y_fine];
cout << "BEGIN_GOLDSTONE\n";
for (i = 0; i < y_fine; i++)
{
corr[i] = 0.0;
for (j = 0; j < x_fine; j++)
{
corr[i] += real(conj(lhs[i*x_fine+j])*lhs[i*x_fine+j]);
}
cout << i << " " << corr[i] << "\n";
}
cout << "END_GOLDSTONE\n";
cout << "BEGIN_EFFMASS\n";
for (i = 0; i < y_fine; i++)
{
cout << i << " " << log(corr[i]/corr[(i+1)%y_fine]) << "\n";
}
cout << "END_EFFMASS\n";
}
// Free the lattice.
delete[] lattice;
delete[] lhs;
delete[] rhs;
delete[] check;
// Clean up!
delete[] mgstruct.blocksize_x;
delete[] mgstruct.blocksize_y;
for (i = 0; i < mgstruct.n_refine; i++)
{
for (j = 0; j < mgstruct.n_vector; j++)
{
delete[] mgstruct.null_vectors[i][j];
}
delete[] mgstruct.null_vectors[i];
}
delete[] mgstruct.null_vectors;
return 0;
}
// Square lattice.
// Kinetic term for a 2D laplace w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
void square_laplace(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y,c;
int tmp;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
int Nc = stagif->Nc; // 1 is the trivial laplace.
// Apply the stencil.
for (i = 0; i < x_fine*y_fine*Nc; i++)
{
lhs[i] = 0.0;
c = i%Nc; // get color.
tmp = (i-c)/Nc;
x = tmp%x_fine; // integer mod.
y = tmp/x_fine; // integer divide.
// + e1.
lhs[i] = lhs[i]-rhs[y*x_fine*Nc+((x+1)%x_fine)*Nc+c];
// - e1.
lhs[i] = lhs[i]- rhs[y*x_fine*Nc+((x+x_fine-1)%x_fine)*Nc+c]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- rhs[((y+1)%y_fine)*x_fine*Nc+x*Nc+c];
// - e2.
lhs[i] = lhs[i]- rhs[((y+y_fine-1)%y_fine)*x_fine*Nc+x*Nc+c];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ (4+mass)*rhs[i];
}
}
// Square lattice.
// Kinetic term for a 2D staggered w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
// The "extra_data" doesn't include anything.
// Apsi[x][y] = m psi[x,y] - U[y][x,x+1]
void square_staggered(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
double eta1;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// For a 2D square lattice, the stencil is:
// 1 | 0 -eta1 0 |
// - | +1 0 -1 | , where eta1 = (-1)^x
// 2 | 0 +eta1 0 |
//
// e2 = yhat
// ^
// |
// |-> e1 = xhat
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
lhs[i] = 0.0;
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
eta1 = 1 - 2*(x%2);
// + e1.
lhs[i] = lhs[i]-rhs[y*x_fine+((x+1)%x_fine)];
// - e1.
lhs[i] = lhs[i]+ rhs[y*x_fine+((x+x_fine-1)%x_fine)]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- eta1*rhs[((y+1)%y_fine)*x_fine+x];
// - e2.
lhs[i] = lhs[i]+ eta1*rhs[((y+y_fine-1)%y_fine)*x_fine+x];
// Normalization.
lhs[i] = 0.5*lhs[i];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ mass*rhs[i];
}
}
// Square lattice.
// Kinetic term for a 2D staggered w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
// The "extra_data" is a cast to a complex gauge_field[N*N*2],
// loaded by the function read_lattice_u1.
// Apsi[x][y] = m psi[x,y] - U[y][x,x+1]
void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
double eta1;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* lattice = stagif->lattice;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// For a 2D square lattice, the stencil is:
// 1 | 0 -eta1 0 |
// - | +1 0 -1 | , where eta1 = (-1)^x
// 2 | 0 +eta1 0 |
//
// e2 = yhat
// ^
// |
// |-> e1 = xhat
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
lhs[i] = 0.0;
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
eta1 = 1 - 2*(x%2);
// + e1.
lhs[i] = lhs[i]-lattice[y*x_fine*2+x*2]*rhs[y*x_fine+((x+1)%x_fine)];
// - e1.
lhs[i] = lhs[i]+ conj(lattice[y*x_fine*2+((x+x_fine-1)%x_fine)*2])*rhs[y*x_fine+((x+x_fine-1)%x_fine)]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- eta1*lattice[y*x_fine*2+x*2+1]*rhs[((y+1)%y_fine)*x_fine+x];
// - e2.
lhs[i] = lhs[i]+ eta1*conj(lattice[((y+y_fine-1)%y_fine)*x_fine*2+x*2+1])*rhs[((y+y_fine-1)%y_fine)*x_fine+x];
// Normalization.
lhs[i] = 0.5*lhs[i];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ mass*rhs[i];
// Apply a gamma5.
/*if ((x+y)%2 == 1)
{
lhs[i] = -lhs[i];
}*/
}
}
// \gamma_5
void gamma_5(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
lhs[i] = ((double)(1 - 2*((x+y)%2)))*rhs[i];
}
}
// Square \gamma_5 staggered 2d operator w/ u1 function.
void square_staggered_gamma5_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* tmp = new complex<double>[stagif->x_fine*stagif->y_fine];
square_staggered_u1(tmp, rhs, extra_data);
gamma_5(lhs, tmp, extra_data);
delete[] tmp;
}
// Staggered normal equations.
void square_staggered_normal_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* tmp = new complex<double>[stagif->x_fine*stagif->y_fine];
square_staggered_u1(tmp, rhs, extra_data);
gamma_5(lhs, tmp, extra_data);
square_staggered_u1(tmp, lhs, extra_data);
gamma_5(lhs, tmp, extra_data);
delete[] tmp;
}
Various MG tweaks.
// This is a sample code that constructs general kinetic terms!
#include <iostream>
#include <iomanip> // to set output precision.
#include <cmath>
#include <string>
#include <sstream>
#include <complex>
#include <random>
#include <cstring> // should be replaced by using sstream
#include "generic_inverters.h"
#include "generic_inverters_precond.h"
#include "generic_vector.h"
#include "verbosity.h"
#include "mg.h"
#include "mg_real.h"
#include "mg_complex.h"
#include "u1_utils.h"
// Do restrict/prolong test?
//#define PDAGP_TEST
// Do two vector restrict/prolong?
//#define PDAGP_2TEST
// Try solving just the coarse solver.
//#define COARSE_ONLY
using namespace std;
// Define pi.
#define PI 3.141592653589793
// Print null vectors?
//#define PRINT_NULL_VECTOR
// Do null vector generation? Currently uses BiCGStab
#define GEN_NULL_VECTOR
// How many GCR iterations do we use?
//#define GEN_NULL_VECTOR_STEP 300
//#define GEN_NULL_VECTOR_REL_RESID 1e-4
//#define AGGREGATE_FOUR
//#define AGGREGATE_EOCONJ
// Are we testing a random gauge rotation?
//#define TEST_RANDOM_GAUGE
// Are we testing a random field?
//#define TEST_RANDOM_FIELD
// Are we loading a gauge field?
#define LOAD_GAUGE_FIELD
// What type of test should we do?
enum mg_test_types
{
TOP_LEVEL_ONLY = 0, // only test the top level solver.
SMOOTHER_ONLY = 1, // Top level + smoother
TWO_LEVEL = 2, // Two level MG
THREE_LEVEL = 3 // Three level MG
};
// How should we generate null vectors?
enum mg_null_gen_type
{
NULL_GCR = 0, // Generate null vectors with GCR
NULL_BICGSTAB = 1, // Generate null vectors with BiCGStab
NULL_CG = 2, // Generate null vectors with CG
};
// Square laplace 2d operator w/out u1 function.
void square_laplace(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square staggered 2d operator w/out u1 function.
void square_staggered(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square staggered 2d operator w/ u1 function.
void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// \gamma_5
void gamma_5(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Square \gamma_5 staggered 2d operator w/ u1 function.
void square_staggered_gamma5_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
// Staggered normal equations.
void square_staggered_normal_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data);
enum op_type
{
STAGGERED = 0,
LAPLACE = 1,
LAPLACE_NC2 = 2,
G5_STAGGERED = 3,
STAGGERED_NORMAL = 4
};
enum src_type
{
POINT = 0,
RANDOM_GAUSSIAN = 1,
ORIGIN_POINT = 2 // for correlator test.
};
struct staggered_u1_op
{
complex<double> *lattice;
double mass;
int x_fine;
int y_fine;
int Nc; // only relevant for square laplace.
};
int main(int argc, char** argv)
{
// Declare some variables.
cout << setiosflags(ios::scientific) << setprecision(6);
int i, j, x, y;
complex<double> *lattice; // Holds the gauge field.
complex<double> *lhs, *rhs, *check; // For some Kinetic terms.
double explicit_resid = 0.0;
double bnorm = 0.0;
std::mt19937 generator (1337u); // RNG, 1337u is the seed.
inversion_info invif;
staggered_u1_op stagif;
// Set parameters.
// What operator are we using for the solve? (Laplace is free only.)
op_type opt = G5_STAGGERED; // STAGGERED, LAPLACE, LAPLACE_NC2, G5_STAGGERED
// What operator are we using for null vector generation?
op_type opt_null = STAGGERED_NORMAL;
// What test are we performing?
mg_test_types my_test = TWO_LEVEL; //THREE_LEVEL; // TWO_LEVEL is the default which won't override anything.
// How are we generating null vectors?
mg_null_gen_type null_gen = NULL_CG; // NULL_BICGSTAB, NULL_GCR, NULL_CG
// L_x = L_y = Dimension for a square lattice.
int square_size = 32; // Can be set on command line with --square_size.
// Describe the staggered fermions.
double MASS = 0.01; // Can be overridden on command line with --mass
// Describe the source type.
src_type source = RANDOM_GAUSSIAN; // POINT, RANDOM_GAUSSIAN, or ORIGIN_POINT (for correlator test).
// Outer Inverter information.
double outer_precision = 5e-7;
int outer_restart = 64;
// Multigrid information.
int n_refine = 1; // 1 = two level V cycle, 2 = three level V cycle, etc.
// Can be set on command line with --nrefine
if (my_test == THREE_LEVEL) // FOR TEST ONLY
{
n_refine = 2;
}
int X_BLOCKSIZE = 4; // Can be overrided with below arg on command line
int Y_BLOCKSIZE = 4; // with --blocksize
int eo = 1; // 0 for no even/odd aggregation, 1 for even/odd aggregation.
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
eo = 0;
}
// Null vector generation
// If GEN_NULL_VECTOR isn't defined:
// 1 for just const vector, 2 for const + even/odd vector, 4 for each corner
// of the hypercube.
// If GEN_NULL_VECTOR is defined and eo = 0:
// Generate "n_null_vector" null vectors which are block orthogonalized.
// IF GEN_NULL_VECTOR is defined and eo = 1:
// Generate "n_null_vector" null vectors, partition into even and odd.
// Total number of null vectors is 2*VECTOR_COUNT.
int n_null_vector = 4; // Note: Gets multiplied by 2 for LAPLACE_NC2 test.
// Can be overriden on command line with --nvec
int null_max_iter = 500;
double null_precision = 5e-5; //5e-4; // Can be overriden on command line with --null-precision
// Advanced:
// IF GEN_NULL_VECTOR is defined and AGGREGATE_EOCONJ is defined:
// Generate VECTOR_COUNT null vectors, partition into even and odd, duplicate complex conj.
// Total number of null vectors is 4*VECTOR_COUNT.
// IF GEN_NULL_VECTOR is defined and AGGREGATE_EO is defined:
// Generate VECTOR_COUNT null vectors, partition into corners of hypercube.
// Total number of null vectors is 4*VECTOR_COUNT.
// Inner solver.
inner_solver in_solve = GCR; //CR; //GCR;
double inner_precision = 1e-3;
int inner_restart = 64;
int inner_max = 1000;
if (my_test == SMOOTHER_ONLY)
{
in_solve = NONE;
}
// Smoother
inner_solver in_smooth = GCR; //NONE; //GCR; BICGSTAB
double omega_smooth = 0.67; // for MR only.
int pre_smooth = 6;
int post_smooth = 6;
// Gauge field information.
double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta).
// For heatbath gauge field, corresponds to non-compact beta.
// Can be set on command line with --beta.
/////////////////////////////////////////////
// Get a few parameters from command line. //
/////////////////////////////////////////////
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0)
{
cout << "--mass [mass] (default 1e-2)\n";
cout << "--blocksize [blocksize] (default 4)\n";
cout << "--nvec [nvec] (default 4)\n";
cout << "--null-precision [null prec] (default 5e-5)\n";
cout << "--nrefine [number coarse] (default 1)\n";
cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n";
cout << "--square-size [32, 64, 128] (default 32)\n";
return 0;
}
if (i+1 != argc)
{
if (strcmp(argv[i], "--mass") == 0)
{
MASS = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--blocksize") == 0)
{
X_BLOCKSIZE = atoi(argv[i+1]);
Y_BLOCKSIZE = X_BLOCKSIZE;
i++;
}
else if (strcmp(argv[i], "--nvec") == 0)
{
n_null_vector = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-precision") == 0)
{
null_precision = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--nrefine") == 0)
{
n_refine = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--beta") == 0)
{
BETA = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--square-size") == 0)
{
square_size = atoi(argv[i+1]);
i++;
}
}
}
//printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector);
//return 0;
///////////////////////////////////////
// End of human-readable parameters! //
///////////////////////////////////////
string op_name;
void (*op)(complex<double>*, complex<double>*, void*);
switch (opt)
{
case STAGGERED:
op = square_staggered_u1;
op_name = "Staggered U(1)";
break;
case LAPLACE:
op_name = "Free Laplace";
op = square_laplace;
break;
case LAPLACE_NC2:
op_name = "Free Laplace Nc = 2";
op = square_laplace;
break;
case G5_STAGGERED:
op_name = "Gamma_5 Staggered U(1)";
op = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_name = "Staggered U(1) Normal";
op = square_staggered_normal_u1;
}
cout << "[OP]: Operator " << op_name << " Mass " << MASS << "\n";
// Only relevant for free laplace test.
int Nc = 1; // Only value that matters for staggered
if (opt == LAPLACE_NC2)
{
Nc = 2;
}
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
n_null_vector *= Nc;
}
// Describe the fine lattice.
int x_fine = square_size;
int y_fine = square_size;
int fine_size = x_fine*y_fine*Nc;
cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine;
if (opt == LAPLACE || opt == LAPLACE_NC2) // FOR TEST ONLY
{
cout << " Nc " << Nc;
}
cout << "\n";
// Do some allocation.
// Initialize the lattice. Indexing: index = y*N + x.
lattice = new complex<double>[2*fine_size];
lhs = new complex<double>[fine_size];
rhs = new complex<double>[fine_size];
check = new complex<double>[fine_size];
// Zero it out.
zero<double>(lattice, 2*fine_size);
zero<double>(rhs, fine_size);
zero<double>(lhs, fine_size);
zero<double>(check, fine_size);
//
// Fill stagif.
stagif.lattice = lattice;
stagif.mass = MASS;
stagif.x_fine = x_fine;
stagif.y_fine = y_fine;
stagif.Nc = Nc; // Only relevant for laplace test only.
// Create the verbosity structure.
inversion_verbose_struct verb;
verb.verbosity = VERB_DETAIL;
verb.verb_prefix = "[L1]: ";
verb.precond_verbosity = VERB_NONE;
verb.precond_verb_prefix = "Prec ";
// Describe the gauge field.
cout << "[GAUGE]: Creating a gauge field.\n";
unit_gauge_u1(lattice, x_fine, y_fine);
#ifdef TEST_RANDOM_FIELD
gauss_gauge_u1(lattice, x_fine, y_fine, generator, BETA);
cout << "[GAUGE]: Created a U(1) gauge field with angle standard deviation " << 1.0/sqrt(BETA) << "\n";
#endif
#ifdef LOAD_GAUGE_FIELD
if (x_fine == 32 && y_fine == 32)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l32t32bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 64 && y_fine == 64)
{
if (abs(BETA - 3.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b30_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l64t64bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else if (x_fine == 128 && y_fine == 128)
{
if (abs(BETA - 6.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b60_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128b100_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else if (abs(BETA - 10000.0) < 1e-8)
{
read_gauge_u1(lattice, x_fine, y_fine, "./cfg/l128t128bperturb_heatbath.dat");
cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n";
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
}
else
{
cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n";
}
#endif // LOAD_GAUGE_FIELD
#ifdef TEST_RANDOM_GAUGE
// Generate and perform a random gauge transformation.
complex<double>* gauge_trans = new complex<double>[fine_size];
rand_trans_u1(gauge_trans, x_fine, y_fine, generator);
apply_gauge_trans_u1(lattice, gauge_trans, x_fine, y_fine);
cout << "[GAUGE]: Performed a random gauge rotation.\n";
#endif
cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(lattice, x_fine, y_fine) << ".\n";
// Sanity check if we're doing a multigrid solve.
if (n_refine == 0)
{
my_test = TOP_LEVEL_ONLY;
}
string op_null_name;
void (*op_null)(complex<double>*, complex<double>*, void*);
switch (opt_null)
{
case STAGGERED:
op_null = square_staggered_u1;
op_null_name = "Staggered U(1)";
break;
case LAPLACE:
op_null_name = "Free Laplace";
op_null = square_laplace;
break;
case LAPLACE_NC2:
op_null_name = "Free Laplace Nc = 2";
op_null = square_laplace;
break;
case G5_STAGGERED:
op_null_name = "Gamma_5 Staggered U(1)";
op_null = square_staggered_gamma5_u1;
break;
case STAGGERED_NORMAL:
op_null_name = "Staggered U(1) Normal";
op_null = square_staggered_normal_u1;
break;
}
cout << "[OP]: Null Gen Operator " << op_null_name << "\n";
// Build an mg_struct.
mg_operator_struct_complex mgstruct;
mgstruct.x_fine = x_fine;
mgstruct.y_fine = y_fine;
mgstruct.Nc = Nc; // only matters for square laplace.
mgstruct.n_refine = n_refine;
mgstruct.blocksize_x = new int[n_refine];
mgstruct.blocksize_y = new int[n_refine];
for (i = 0; i < n_refine; i++)
{
mgstruct.blocksize_x[i] = X_BLOCKSIZE;
mgstruct.blocksize_y[i] = Y_BLOCKSIZE;
}
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
mgstruct.n_vector = 4*n_null_vector;
mgstruct.eo = 1;
#elif defined GEN_NULL_VECTOR
mgstruct.eo = eo;
mgstruct.n_vector = (eo+1)*n_null_vector;
#else
mgstruct.eo = eo;
mgstruct.n_vector = (eo+1)*n_null_vector;
#endif
mgstruct.matrix_vector = op; //square_staggered_u1;
mgstruct.matrix_extra_data = (void*)&stagif;
cout << "[MG]: X_Block " << X_BLOCKSIZE << " Y_Block " << Y_BLOCKSIZE << " NullVectors " << n_null_vector << "\n";
// Set the starting mg_struct state.
mgstruct.curr_level = 0; // Ready to do top level -> second level.
mgstruct.curr_dof_fine = Nc; // Top level has only one d.o.f. per site.
mgstruct.curr_x_fine = mgstruct.x_fine;
mgstruct.curr_y_fine = mgstruct.y_fine;
mgstruct.curr_fine_size = mgstruct.curr_y_fine*mgstruct.curr_x_fine*mgstruct.curr_dof_fine;
mgstruct.curr_dof_coarse = mgstruct.n_vector;
mgstruct.curr_x_coarse = mgstruct.x_fine/mgstruct.blocksize_x[0];
mgstruct.curr_y_coarse = mgstruct.y_fine/mgstruct.blocksize_y[0];
mgstruct.curr_coarse_size = mgstruct.curr_y_coarse*mgstruct.curr_x_coarse*mgstruct.curr_dof_coarse;
// Build the mg inverter structure.
// Set up the MG preconditioner.
mg_precond_struct_complex mgprecond;
mgprecond.in_smooth_type = in_smooth; // What inner smoother? MR or GCR.
mgprecond.omega_smooth = omega_smooth; // What relaxation parameter should we use (MR only!)
mgprecond.n_pre_smooth = pre_smooth; // 6 MR smoother steps before coarsening.
mgprecond.n_post_smooth = post_smooth; // 6 MR smoother steps after refining.
mgprecond.in_solve_type = in_solve; // What inner solver? NONE, MR, CG, GCR, BICGSTAB
mgprecond.n_max = inner_max; // max number of steps to use for inner solver.
mgprecond.n_restart = inner_restart; // frequency of restart (relevant for CG, GCR).
mgprecond.rel_res = inner_precision; // Maximum relative residual for inner solver.
mgprecond.mgstruct = &mgstruct; // Contains null vectors, fine operator. (Since we don't construct the fine op.)
mgprecond.coarse_matrix_vector = coarse_square_staggered; // Function which applies the coarse operator.
mgprecond.fine_matrix_vector = fine_square_staggered; // Function which applies the fine operator.
mgprecond.matrix_extra_data = (void*)&mgstruct; // What extra_data the coarse operator expects.
// Set right hand side.
switch (source)
{
case POINT: // Set a point.
for (i = 0; i < Nc; i++)
{
rhs[(x_fine/2+(y_fine/2)*x_fine)*Nc+i] = 1.0;
}
break;
case RANDOM_GAUSSIAN: // Random rhs.
gaussian<double>(rhs, fine_size, generator);
break;
case ORIGIN_POINT: // Set a point for correlator computation.
for (i = 0; i < Nc; i++)
{
rhs[i] = 1.0;
}
}
// Get norm for rhs.
bnorm = sqrt(norm2sq<double>(rhs, fine_size));
// Set a point on the lhs.
//lhs[x_fine/2+(y_fine/2)*x_fine+1] = 1.0;
// Create a projector.
mgstruct.null_vectors = new complex<double>**[mgstruct.n_refine];
// The top level is special since there are no color indices.
mgstruct.null_vectors[0] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[0][j] = new complex<double>[fine_size];
zero<double>(mgstruct.null_vectors[0][j], fine_size);
}
// Higher levels are different.
if (mgstruct.n_refine > 1)
{
for (i = 1; i < mgstruct.n_refine; i++)
{
level_down(&mgstruct);
mgstruct.null_vectors[i] = new complex<double>*[mgstruct.n_vector];
for (j = 0; j < mgstruct.n_vector; j++)
{
mgstruct.null_vectors[i][j] = new complex<double>[mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine];
zero<double>(mgstruct.null_vectors[i][j], mgstruct.curr_x_fine*mgstruct.curr_y_fine*mgstruct.curr_dof_fine);
}
}
// Come back up!
for (i = mgstruct.n_refine; i > 1; i--)
{
level_up(&mgstruct);
}
}
cout << "[MG]: Creating " << mgstruct.n_vector << " projector(s).\n";
#ifndef GEN_NULL_VECTOR
// Make a constant projector.
if (mgstruct.n_vector == 1)
{
cout << "[MG]: Null vector 1 is a constant.\n";
for (i = 0; i < fine_size; i++)
{
mgstruct.null_vectors[0][0][i] = 1;
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][0][i] *= gauge_trans[i];
#endif
}
}
else if (mgstruct.n_vector == 2) // constant, even/odd phase.
{
cout << "[MG]: Null vector 1 is a constant.\n";
cout << "[MG]: Null vector 2 is an even/odd phase.\n";
for (i = 0; i < fine_size; i++)
{
mgstruct.null_vectors[0][0][i] = 1;
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][1][i] = ((x+y)%2 == 0) ? complex<double>(0.0,1.0) : complex<double>(0.0,-1.0);
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][0][i] *= (gauge_trans[i]);
mgstruct.null_vectors[0][1][i] *= (gauge_trans[i]);
#endif
}
}
else if (mgstruct.n_vector == 4) // 4 corners of hypercube.
{
cout << "[MG]: Null vector 1 is a constant on unit corner (0,0).\n";
cout << "[MG]: Null vector 2 is a constant on unit corner (1,0).\n";
cout << "[MG]: Null vector 3 is a constant on unit corner (0,1).\n";
cout << "[MG]: Null vector 4 is a constant on unit corner (1,1).\n";
// Generate a normal distribution.
std::normal_distribution<> dist(1.0, 0.1);
for (i = 0; i < fine_size; i++)
{
x = i % x_fine;
y = i / x_fine;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = 1.0;
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] = dist(generator);
#ifdef TEST_RANDOM_GAUGE
mgstruct.null_vectors[0][2*(y%2)+(x%2)][i] *= (gauge_trans[i]);
#endif
}
}
else // invalid.
{
cout << "Unless you are generating null vectors, you can only use 1, 2, or 4 null vectors.\n";
return 0;
}
#ifdef TEST_RANDOM_GAUGE
delete[] gauge_trans;
#endif
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
#ifdef PRINT_NULL_VECTOR
cout << "[MG]: Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#else // generate null vector
// Skip this depending on our test!
if (!(my_test == TOP_LEVEL_ONLY || my_test == SMOOTHER_ONLY))
{
// Generate top level!
printf("About to generate null vector.\n"); fflush(stdout);
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* rand_guess = new complex<double>[fine_size];
complex<double>* Arand_guess = new complex<double>[fine_size];
// Temporarily set the mass to zero for the null vector generation.
stagif.mass = stagif.mass*1e-2;
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
for (i = 0; i < mgstruct.n_vector/4; i++) // Because we partition fourfold afterwards.
#else // GEN_NULL_VECTOR is defined.
for (i = 0; i < mgstruct.n_vector/(mgstruct.eo+1); i++)
#endif
{
gaussian<double>(rand_guess, fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
#if defined GEN_NULL_VECTOR && (defined AGGREGATE_FOUR || defined AGGREGATE_EOCONJ)
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
#else
if (mgstruct.eo == 1)
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size);
}
else // no eo.
{
orthogonal<double>(rand_guess, mgstruct.null_vectors[0][j], fine_size);
}
#endif
}
}
// If we're using the staggered normal to generate, multiply the random source by gamma_5 D.
/*if (opt_null == STAGGERED_NORMAL)
{
copy<double>(Arand_guess, rand_guess, fine_size);
square_staggered_gamma5_u1(rand_guess, Arand_guess, (void*)&stagif);
zero<double>(Arand_guess, fine_size);
}*/
zero<double>(Arand_guess, fine_size);
(*op_null)(Arand_guess, rand_guess, (void*)&stagif);
//square_staggered_u1(Arand_guess, rand_guess, (void*)&stagif);
for (j = 0; j < fine_size; j++)
{
Arand_guess[j] = -Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[0][i], fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[0][i], Arand_guess, fine_size, null_max_iter, null_precision, op_null, (void*)&stagif, &verb);
break;
}
for (j = 0; j < fine_size; j++)
{
mgstruct.null_vectors[0][i][j] += rand_guess[j];
}
// Aggregate in chirality (or corners) as needed, orthogonalize against previous vectors.
#if defined GEN_NULL_VECTOR && defined AGGREGATE_FOUR
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / x_fine;
if (x%2 == 1 && y%2 == 0)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
else if (x%2 == 0 && y%2 == 1)
{
mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
else if (x%2 == 1 && y%2 == 1)
{
mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4],fine_size))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
#elif defined GEN_NULL_VECTOR && defined AGGREGATE_EOCONJ
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / y_fine;
if ((x+y)%2 == 1)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/4][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
copy<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][i], fine_size);
copy<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
conj(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
conj(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4],fine_size))) << " " << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], mgstruct.null_vectors[0][j+mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+2*mgstruct.n_vector/4], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], mgstruct.null_vectors[0][j+3*mgstruct.n_vector/4], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+2*mgstruct.n_vector/4], fine_size);
normalize(mgstruct.null_vectors[0][i+3*mgstruct.n_vector/4], fine_size);
#else // even/odd
if (mgstruct.eo == 1)
{
for (j = 0; j < fine_size; j++)
{
x = j % x_fine;
y = j / y_fine;
if ((x+y)%2 == 1)
{
mgstruct.null_vectors[0][i+mgstruct.n_vector/2][j] = mgstruct.null_vectors[0][i][j];
mgstruct.null_vectors[0][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j+mgstruct.n_vector/2],fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
orthogonal<double>(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], mgstruct.null_vectors[0][j+mgstruct.n_vector/2], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
normalize(mgstruct.null_vectors[0][i+mgstruct.n_vector/2], fine_size);
}
else
{
normalize(mgstruct.null_vectors[0][i], fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[0][i],fine_size)*norm2sq<double>(mgstruct.null_vectors[0][j],fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[0][i], mgstruct.null_vectors[0][j], fine_size);
}
}
normalize(mgstruct.null_vectors[0][i], fine_size);
}
#endif // defined GEN_NULL_VECTOR && defined AGGREGATE_FOUR
}
// This causes a segfault related to the RNG when
// the vector is initialized.
delete[] rand_guess;
delete[] Arand_guess;
#ifdef PRINT_NULL_VECTOR
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
cout << "[MG]: Performing block orthonormalize of null vectors...\n";
block_orthonormalize(&mgstruct);
// Do we need to generate more levels?
if (mgstruct.n_refine > 1)
{
mgstruct.matrix_vector = op_null; // Trick op to null gen op.
for (int n = 1; n < mgstruct.n_refine; n++)
{
level_down(&mgstruct);
cout << "curr_fine_size: " << mgstruct.curr_fine_size << "\n";
// Let's give it a whirl?!
// We generate null vectors by solving Ax = 0, with a
// gaussian initial guess.
// For sanity with the residual, we really solve Ax = -Ax_0,
// where x has a zero initial guess, x_0 is a random vector.
complex<double>* c_rand_guess = new complex<double>[mgstruct.curr_fine_size];
complex<double>* c_Arand_guess = new complex<double>[mgstruct.curr_fine_size];
// Generate null vectors with the current level.
for (i = 0; i < mgstruct.n_vector/(mgstruct.eo+1); i++)
{
gaussian<double>(c_rand_guess, mgstruct.curr_fine_size, generator);
// Make orthogonal to previous solutions.
if (i > 0)
{
for (j = 0; j < i; j++)
{
if (mgstruct.eo == 1)
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else // no eo.
{
orthogonal<double>(c_rand_guess, mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
}
zero<double>(c_Arand_guess, mgstruct.curr_fine_size);
fine_square_staggered(c_Arand_guess, c_rand_guess, (void*)&mgstruct);
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
c_Arand_guess[j] = -c_Arand_guess[j];
}
zero<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
switch (null_gen)
{
case NULL_GCR:
minv_vector_gcr(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_BICGSTAB:
minv_vector_bicgstab(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
case NULL_CG:
minv_vector_cg(mgstruct.null_vectors[mgstruct.curr_level][i], c_Arand_guess, mgstruct.curr_fine_size, null_max_iter, null_precision, fine_square_staggered, &mgstruct, &verb);
break;
}
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
mgstruct.null_vectors[mgstruct.curr_level][i][j] += c_rand_guess[j];
}
// Aggregate in chirality, orthogonalize against previous vectors.
if (mgstruct.eo == 1)
{
for (j = 0; j < mgstruct.curr_fine_size; j++)
{
int c = j % mgstruct.n_vector; // What color index do we have?
// 0 to mgstruct.n_vector/2-1 is even, else is odd.
//int x_coord = (i - c)/mgstruct.n_vector % mgstruct.curr_x_fine;
//int y_coord = ((i - c)/mgstruct.n_vector - x_coord)/mgstruct.curr_x_fine;
if (c >= mgstruct.n_vector/2)
{
mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2][j] = mgstruct.null_vectors[mgstruct.curr_level][i][j];
mgstruct.null_vectors[mgstruct.curr_level][i][j] = 0.0;
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << " " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.null_vectors[mgstruct.curr_level][j+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
normalize(mgstruct.null_vectors[mgstruct.curr_level][i+mgstruct.n_vector/2], mgstruct.curr_fine_size);
}
else
{
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
if (i > 0)
{
for (j = 0; j < i; j++)
{
// Check dot product before normalization.
cout << "[NULLVEC]: Pre-orthog cosines of " << j << "," << i << " are: " <<
abs(dot<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size)/sqrt(norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][i],mgstruct.curr_fine_size)*norm2sq<double>(mgstruct.null_vectors[mgstruct.curr_level][j],mgstruct.curr_fine_size))) << "\n";
orthogonal<double>(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.null_vectors[mgstruct.curr_level][j], mgstruct.curr_fine_size);
}
}
normalize(mgstruct.null_vectors[mgstruct.curr_level][i], mgstruct.curr_fine_size);
}
}
delete[] c_rand_guess;
delete[] c_Arand_guess;
block_orthonormalize(&mgstruct);
// Print vector.
/*
cout << "\n\nPrinting null vectors:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "\nVector " << n << "\n";
for (int y = 0; y < mgstruct.curr_y_fine; y++)
{
for (int x = 0; x < mgstruct.curr_x_fine; x++)
{
cout << "(";
for (int c = 0; c < mgstruct.n_vector; c++)
{
cout << mgstruct.null_vectors[mgstruct.curr_level][n][y*mgstruct.curr_x_fine*mgstruct.curr_dof_fine+x*mgstruct.curr_dof_fine+c] << ",";
}
cout << ") ";
}
cout << "\n";
}
}*/
}
// Un-pop to the finest level.
for (i = 1; i < mgstruct.n_refine; i++)
{
level_up(&mgstruct);
}
mgstruct.matrix_vector = op; // Reset op to solved op.
}
// Reset the mass.
stagif.mass = MASS;
} // end skipping generation if we're only doing a top level or smoother test.
#endif // generate null vector.
#ifdef PRINT_NULL_VECTOR
cout << "\nCheck projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
#endif // PRINT_NULL_VECTOR
#ifdef PDAGP_TEST
{
// Begin PdagP test.
// Describe the coarse lattice.
int x_coarse = x_fine/mgstruct.blocksize_x[0]; // how many coarse sites are there in the x dir?
int y_coarse = y_fine/mgstruct.blocksize_y[0]; // how many coarse sites are there in the y dir?
int coarse_size = x_coarse*y_coarse;
// Print the fine rhs.
cout << "Check fine point src:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs[x+y*x_fine] << " ";
}
cout << "\n";
}
cout << "Check projector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][0][x+y*x_fine] << " ";
}
cout << "\n";
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double> *rhs_PdagP = new complex<double>[fine_size];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
// Try applying the coarse Laplace operator!
complex<double>* rhs_A_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_A_coarse, coarse_size*mgstruct.n_vector);
cout << "Applying the coarse Laplace operator to coarse source.\n";
coarse_square_laplace(rhs_A_coarse, rhs_coarse, (void*)&mgstruct);
// Check A coarse source.
cout << "Check A times coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << rhs_A_coarse[x+y*x_coarse] << " ";
}
cout << "\n";
}
// Prolong rhs_A_coarse.
cout << "Prolong A times coarse source.\n";
complex<double>* rhs_PAP_fine = new complex<double>[fine_size];
zero<double>(rhs_PAP_fine, fine_size);
prolong(rhs_PAP_fine, rhs_A_coarse, &mgstruct);
// Check PAP.
cout << "Check PAP on source.\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PAP_fine[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_A_coarse;
delete[] rhs_PdagP;
delete[] rhs_PAP_fine;
}
#endif
#ifdef PDAGP_2TEST
// Test adding a second projector.
{
mgstruct.n_vector = 2;
complex<double>* tmp_store = mgstruct.null_vectors[0];
delete[] mgstruct.null_vectors;
mgstruct.null_vectors = new complex<double>*[mgstruct.n_vector];
mgstruct.null_vectors[0] = tmp_store;
mgstruct.null_vectors[1] = new complex<double>[fine_size];
// Add an even/odd vector.
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
if ((x+y)%2 == 0)
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,1.0);
else
mgstruct.null_vectors[0][1][x+y*x_fine] = complex<double>(0.0,-1.0);
}
}
cout << "Check projector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Test block normalizing the projector.
cout << "Block normalize the projector(s). X blocks: " << x_coarse << " Y blocks: " << y_coarse << "\n";
block_normalize(&mgstruct);
cout << "Check block normalized vector:\n";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << "Vector " << n << "\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << mgstruct.null_vectors[0][n][x+y*x_fine] << " ";
}
cout << "\n";
}
}
// Restrict the original source.
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
cout << "Restricting the source.\n";
restrict(rhs_coarse, rhs, &mgstruct);
// Check coarse source.
cout << "Check coarse src:\n";
for (int y = 0; y < y_coarse; y++)
{
for (int x = 0; x < x_coarse; x++)
{
cout << "(";
for (int n = 0; n < mgstruct.n_vector; n++)
{
cout << rhs_coarse[(x+y*x_coarse)*mgstruct.n_vector+n] << ",";
}
cout << ") ";
}
cout << "\n";
}
// Prolong the restricted source.
complex<double>* rhs_PdagP = new complex<double>[fine_size];
cout << "Prolonging the restricted source.\n";
prolong(rhs_PdagP, rhs_coarse, &mgstruct);
cout << "Check re-prolonged source vector:\n";
for (int y = 0; y < y_fine; y++)
{
for (int x = 0; x < x_fine; x++)
{
cout << rhs_PdagP[x+y*x_fine] << " ";
}
cout << "\n";
}
delete[] rhs_coarse;
delete[] rhs_PdagP;
}
#endif
#ifdef COARSE_ONLY
cout << "[COARSE]: Solving coarse system only.\n";
complex<double>* rhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(rhs_coarse, coarse_size*mgstruct.n_vector);
restrict(rhs_coarse, rhs, &mgstruct);
cout << "[COARSE]: Norm of coarse rhs " << sqrt(norm2sq<double>(rhs_coarse, coarse_size*mgstruct.n_vector)) << ".\n";
complex<double>* lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(lhs_coarse, coarse_size*mgstruct.n_vector);
invif = minv_vector_gcr_restart(lhs_coarse, rhs_coarse, coarse_size*mgstruct.n_vector, 10000, 1e-6, 16, coarse_square_staggered, (void*)&mgstruct);
if (invif.success == true)
{
printf("[COARSE]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[COARSE]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[COARSE]: This may be because the max iterations was reached.\n");
}
printf("[COARSE]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
complex<double>* A_lhs_coarse = new complex<double>[coarse_size*mgstruct.n_vector];
zero<double>(A_lhs_coarse, coarse_size*mgstruct.n_vector);
coarse_square_laplace(A_lhs_coarse, lhs_coarse, (void*)&mgstruct);
for (i = 0; i < coarse_size*mgstruct.n_vector; i++)
{
explicit_resid += real(conj(A_lhs_coarse[i] - rhs_coarse[i])*(A_lhs_coarse[i] - rhs_coarse[i]));
}
explicit_resid = sqrt(explicit_resid);
printf("[COARSE]: [check] should equal [rhs]. The residual is %15.20e.\n", explicit_resid);
complex<double>* pro_lhs_coarse = new complex<double>[N*N];
zero<double>(pro_lhs_coarse, N*N);
prolong(pro_lhs_coarse, lhs_coarse, &mgstruct);
complex<double>* pro_rhs_coarse = new complex<double>[N*N];
zero<double>(pro_rhs_coarse, N*N);
square_staggered_u1(pro_rhs_coarse, pro_lhs_coarse, (void*)&stagif);
#endif // COARSE_ONLY
if (my_test == TOP_LEVEL_ONLY)
{
// Try a direct solve.
cout << "\n[ORIG]: Solve fine system.\n";
invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, op, (void*)&stagif, &verb);
//invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif);
if (invif.success == true)
{
printf("[ORIG]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[ORIG]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[ORIG]: This may be because the max iterations was reached.\n");
}
printf("[ORIG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
zero<double>(check, fine_size);
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < fine_size; i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[ORIG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // TOP_LEVEL_ONLY
#ifdef COARSE_ONLY
// Compare PAP solution to real solution.
cout << "\n[COARSE]: Compare solutions.\n";
double comparison = 0;
double resid_comparison = 0;
for (i = 0; i < fine_size; i++)
{
comparison += real(conj(pro_lhs_coarse[i]-lhs[i])*(pro_lhs_coarse[i]-lhs[i]));
resid_comparison += real(conj(pro_rhs_coarse[i]-rhs[i])*(pro_rhs_coarse[i]-rhs[i]));
}
comparison = sqrt(explicit_resid);
printf("[COARSE]: The solutions deviate by %15.20e.\n", comparison);
printf("[COARSE]: The projected residual has a rel res of %15.20e.\n", sqrt(resid_comparison)/bnorm);
delete[] rhs_coarse;
delete[] lhs_coarse;
delete[] A_lhs_coarse;
delete[] pro_lhs_coarse;
delete[] pro_rhs_coarse;
#endif // COARSE_ONLY
if (my_test == SMOOTHER_ONLY || my_test == TWO_LEVEL || my_test == THREE_LEVEL)
{
// Let's actually test a multigrid solve!
cout << "\n[MG]: Test MG solve.\n";
// Block normalize the null vectors.
block_normalize(&mgstruct);
// Well, maybe this will work?
zero<double>(lhs, fine_size);
invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 10000, outer_precision, outer_restart, op, (void*)&stagif, mg_preconditioner, (void*)&mgprecond, &verb);
//invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 10000, outer_precision, outer_restart, square_staggered_u1, (void*)&stagif, mg_preconditioner, (void*)&mgprecond);
if (invif.success == true)
{
printf("[L1]: Iterations %d RelRes %.8e Err N Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
}
else // failed, maybe.
{
printf("[L1]: Iterations %d RelRes %.8e Err Y Algorithm %s\n", invif.iter, sqrt(invif.resSq)/bnorm, invif.name.c_str());
printf("[L1]: This may be because the max iterations was reached.\n");
}
printf("[MG]: Computing [check] = A [lhs] as a confirmation.\n");
// Check and make sure we get the right answer.
(*op)(check, lhs, (void*)&stagif);
//square_staggered_u1(check, lhs, (void*)&stagif);
explicit_resid = 0.0;
for (i = 0; i < fine_size; i++)
{
explicit_resid += real(conj(rhs[i] - check[i])*(rhs[i] - check[i]));
}
explicit_resid = sqrt(explicit_resid)/bnorm;
printf("[MG]: [check] should equal [rhs]. The relative residual is %15.20e.\n", explicit_resid);
} // SMOOTHER_ONLY or TWO_LEVEL
// Look at the two point function!
if (source == ORIGIN_POINT)
{
double* corr = new double[y_fine];
cout << "BEGIN_GOLDSTONE\n";
for (i = 0; i < y_fine; i++)
{
corr[i] = 0.0;
for (j = 0; j < x_fine; j++)
{
corr[i] += real(conj(lhs[i*x_fine+j])*lhs[i*x_fine+j]);
}
cout << i << " " << corr[i] << "\n";
}
cout << "END_GOLDSTONE\n";
cout << "BEGIN_EFFMASS\n";
for (i = 0; i < y_fine; i++)
{
cout << i << " " << log(corr[i]/corr[(i+1)%y_fine]) << "\n";
}
cout << "END_EFFMASS\n";
}
// Free the lattice.
delete[] lattice;
delete[] lhs;
delete[] rhs;
delete[] check;
// Clean up!
delete[] mgstruct.blocksize_x;
delete[] mgstruct.blocksize_y;
for (i = 0; i < mgstruct.n_refine; i++)
{
for (j = 0; j < mgstruct.n_vector; j++)
{
delete[] mgstruct.null_vectors[i][j];
}
delete[] mgstruct.null_vectors[i];
}
delete[] mgstruct.null_vectors;
return 0;
}
// Square lattice.
// Kinetic term for a 2D laplace w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
void square_laplace(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y,c;
int tmp;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
int Nc = stagif->Nc; // 1 is the trivial laplace.
// Apply the stencil.
for (i = 0; i < x_fine*y_fine*Nc; i++)
{
lhs[i] = 0.0;
c = i%Nc; // get color.
tmp = (i-c)/Nc;
x = tmp%x_fine; // integer mod.
y = tmp/x_fine; // integer divide.
// + e1.
lhs[i] = lhs[i]-rhs[y*x_fine*Nc+((x+1)%x_fine)*Nc+c];
// - e1.
lhs[i] = lhs[i]- rhs[y*x_fine*Nc+((x+x_fine-1)%x_fine)*Nc+c]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- rhs[((y+1)%y_fine)*x_fine*Nc+x*Nc+c];
// - e2.
lhs[i] = lhs[i]- rhs[((y+y_fine-1)%y_fine)*x_fine*Nc+x*Nc+c];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ (4+mass)*rhs[i];
}
}
// Square lattice.
// Kinetic term for a 2D staggered w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
// The "extra_data" doesn't include anything.
// Apsi[x][y] = m psi[x,y] - U[y][x,x+1]
void square_staggered(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
double eta1;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// For a 2D square lattice, the stencil is:
// 1 | 0 -eta1 0 |
// - | +1 0 -1 | , where eta1 = (-1)^x
// 2 | 0 +eta1 0 |
//
// e2 = yhat
// ^
// |
// |-> e1 = xhat
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
lhs[i] = 0.0;
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
eta1 = 1 - 2*(x%2);
// + e1.
lhs[i] = lhs[i]-rhs[y*x_fine+((x+1)%x_fine)];
// - e1.
lhs[i] = lhs[i]+ rhs[y*x_fine+((x+x_fine-1)%x_fine)]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- eta1*rhs[((y+1)%y_fine)*x_fine+x];
// - e2.
lhs[i] = lhs[i]+ eta1*rhs[((y+y_fine-1)%y_fine)*x_fine+x];
// Normalization.
lhs[i] = 0.5*lhs[i];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ mass*rhs[i];
}
}
// Square lattice.
// Kinetic term for a 2D staggered w/ period bc. Applies lhs = A*rhs.
// The unit vectors are e_1 = xhat, e_2 = yhat.
// The "extra_data" is a cast to a complex gauge_field[N*N*2],
// loaded by the function read_lattice_u1.
// Apsi[x][y] = m psi[x,y] - U[y][x,x+1]
void square_staggered_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
double eta1;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* lattice = stagif->lattice;
double mass = stagif->mass;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// For a 2D square lattice, the stencil is:
// 1 | 0 -eta1 0 |
// - | +1 0 -1 | , where eta1 = (-1)^x
// 2 | 0 +eta1 0 |
//
// e2 = yhat
// ^
// |
// |-> e1 = xhat
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
lhs[i] = 0.0;
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
eta1 = 1 - 2*(x%2);
// + e1.
lhs[i] = lhs[i]-lattice[y*x_fine*2+x*2]*rhs[y*x_fine+((x+1)%x_fine)];
// - e1.
lhs[i] = lhs[i]+ conj(lattice[y*x_fine*2+((x+x_fine-1)%x_fine)*2])*rhs[y*x_fine+((x+x_fine-1)%x_fine)]; // The extra +N is because of the % sign convention.
// + e2.
lhs[i] = lhs[i]- eta1*lattice[y*x_fine*2+x*2+1]*rhs[((y+1)%y_fine)*x_fine+x];
// - e2.
lhs[i] = lhs[i]+ eta1*conj(lattice[((y+y_fine-1)%y_fine)*x_fine*2+x*2+1])*rhs[((y+y_fine-1)%y_fine)*x_fine+x];
// Normalization.
lhs[i] = 0.5*lhs[i];
// 0
// Added mass term here.
lhs[i] = lhs[i]+ mass*rhs[i];
// Apply a gamma5.
/*if ((x+y)%2 == 1)
{
lhs[i] = -lhs[i];
}*/
}
}
// \gamma_5
void gamma_5(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
// Declare variables.
int i;
int x,y;
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
int x_fine = stagif->x_fine;
int y_fine = stagif->y_fine;
// Apply the stencil.
for (i = 0; i < x_fine*y_fine; i++)
{
x = i%x_fine; // integer mod.
y = i/x_fine; // integer divide.
lhs[i] = ((double)(1 - 2*((x+y)%2)))*rhs[i];
}
}
// Square \gamma_5 staggered 2d operator w/ u1 function.
void square_staggered_gamma5_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* tmp = new complex<double>[stagif->x_fine*stagif->y_fine];
square_staggered_u1(tmp, rhs, extra_data);
gamma_5(lhs, tmp, extra_data);
delete[] tmp;
}
// Staggered normal equations.
void square_staggered_normal_u1(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
staggered_u1_op* stagif = (staggered_u1_op*)extra_data;
complex<double>* tmp = new complex<double>[stagif->x_fine*stagif->y_fine];
square_staggered_u1(tmp, rhs, extra_data);
gamma_5(lhs, tmp, extra_data);
square_staggered_u1(tmp, lhs, extra_data);
gamma_5(lhs, tmp, extra_data);
delete[] tmp;
}
|
/**
* The MIT License
*
* Copyright (C) 2017 Kiyofumi Kondoh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include "cef_scheme_handler.h"
#include "include/cef_scheme.h"
#include "include/wrapper/cef_helpers.h"
namespace {
const char kScheme[] = "local";
const char kDomain[] = "test";
} // namespace {
static
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory();
static
CefRefPtr<CefResourceHandler>
createClientSchemeHandler();
void registerSchemeHandlerFactory()
{
const bool bRet = CefRegisterSchemeHandlerFactory(
kScheme
, kDomain
, createClientSchemeHandlerFactory()
);
DCHECK(bRet);
}
void addCustomScheme( CefRawPtr<CefSchemeRegistrar> registrar )
{
const bool is_standard = true;
const bool is_local = false;
const bool is_display_isolated = false;
const bool is_secure = true;
const bool is_cors_enabled = false;
const bool is_csp_bypassing = false;
const bool bRet = registrar->AddCustomScheme(
kScheme
, is_standard
, is_local
, is_display_isolated
, is_secure
, is_cors_enabled
#if CHROME_VERSION_BUILD > 2987
, is_csp_bypassing
#endif // CHROME_VERSION_BUILD > 2987
);
DCHECK( bRet );
}
class ClientSchemeHandlerFactory
: public CefSchemeHandlerFactory
{
public:
ClientSchemeHandlerFactory() {}
CefRefPtr<CefResourceHandler>
Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) OVERRIDE;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandlerFactory);
};
CefRefPtr<CefResourceHandler>
ClientSchemeHandlerFactory::Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return createClientSchemeHandler();
}
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory()
{
return new ClientSchemeHandlerFactory();
}
class ClientSchemeHandler
: public CefResourceHandler
{
public:
ClientSchemeHandler()
: is_binary_(false)
, offset_(0)
{
}
bool
ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) OVERRIDE;
bool
ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
Cancel() OVERRIDE;
private:
std::string mime_type_;
std::vector<uint8_t> data_;
bool is_binary_;
size_t offset_;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandler);
};
bool
ClientSchemeHandler::ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return false;
}
void
ClientSchemeHandler::GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
bool
ClientSchemeHandler::ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return true;
}
void
ClientSchemeHandler::Cancel() // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
CefRefPtr<CefResourceHandler>
createClientSchemeHandler()
{
return new ClientSchemeHandler();
}
add parseURL and ends_with, handling my resource
/**
* The MIT License
*
* Copyright (C) 2017 Kiyofumi Kondoh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "stdafx.h"
#include "cef_scheme_handler.h"
#include "include/cef_scheme.h"
#include "include/wrapper/cef_helpers.h"
namespace {
const char kScheme[] = "local";
const char kDomain[] = "test";
} // namespace {
static
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory();
static
CefRefPtr<CefResourceHandler>
createClientSchemeHandler();
void registerSchemeHandlerFactory()
{
const bool bRet = CefRegisterSchemeHandlerFactory(
kScheme
, kDomain
, createClientSchemeHandlerFactory()
);
DCHECK(bRet);
}
void addCustomScheme( CefRawPtr<CefSchemeRegistrar> registrar )
{
const bool is_standard = true;
const bool is_local = false;
const bool is_display_isolated = false;
const bool is_secure = true;
const bool is_cors_enabled = false;
const bool is_csp_bypassing = false;
const bool bRet = registrar->AddCustomScheme(
kScheme
, is_standard
, is_local
, is_display_isolated
, is_secure
, is_cors_enabled
#if CHROME_VERSION_BUILD > 2987
, is_csp_bypassing
#endif // CHROME_VERSION_BUILD > 2987
);
DCHECK( bRet );
}
class ClientSchemeHandlerFactory
: public CefSchemeHandlerFactory
{
public:
ClientSchemeHandlerFactory() {}
CefRefPtr<CefResourceHandler>
Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) OVERRIDE;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandlerFactory);
};
CefRefPtr<CefResourceHandler>
ClientSchemeHandlerFactory::Create(
CefRefPtr<CefBrowser> browser
, CefRefPtr<CefFrame> frame
, const CefString& scheme_name
, CefRefPtr<CefRequest> request
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return createClientSchemeHandler();
}
CefRefPtr<CefSchemeHandlerFactory>
createClientSchemeHandlerFactory()
{
return new ClientSchemeHandlerFactory();
}
class ClientSchemeHandler
: public CefResourceHandler
{
public:
ClientSchemeHandler()
: is_binary_(false)
, offset_(0)
{
}
bool
ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) OVERRIDE;
bool
ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) OVERRIDE;
void
Cancel() OVERRIDE;
private:
std::string mime_type_;
std::vector<uint8_t> data_;
bool is_binary_;
size_t offset_;
private:
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
DISALLOW_COPY_AND_ASSIGN(ClientSchemeHandler);
};
static
bool
ends_with(const std::string& str, const std::string& suffix)
{
if ( str.size() < suffix.size() )
{
return false;
}
return std::equal( std::rbegin(suffix), std::rend(suffix), std::rbegin(str) );
//return ( 0 == str.compare( str.size() - suffix.size(), suffix.size(), suffix ));
}
static
bool
parseURL(std::string& scheme, std::string& domain, std::string& path, const std::string& url)
{
const size_t pos_scheme = url.find( "://" );
if ( std::string::npos == pos_scheme )
{
return false;
}
scheme = url.substr( 0, pos_scheme );
if ( url.size() <= (pos_scheme + 3/*strlen("://")*/) )
{
return false;
}
const size_t pos_domain = url.find( '/', (pos_scheme + 3/*strlen("://")*/) );
if ( std::string::npos == pos_domain )
{
return false;
}
domain = url.substr( (pos_scheme + 3/*strlen("://")*/), pos_domain - (pos_scheme + 3/*strlen("://")*/) );
if ( url.size() <= (pos_domain + 1/*strlen("/")*/) )
{
return false;
}
path = url.substr( (pos_domain + 1/*strlen("/")*/) );
return true;
}
//static
//bool
//readResource(
bool
ClientSchemeHandler::ProcessRequest(
CefRefPtr<CefRequest> request
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
bool handled = false;
std::string url = request->GetURL();
std::string scheme;
std::string domain;
std::string path;
{
const bool bRet = parseURL( scheme, domain, path, url );
}
if ( ends_with( url, ".html" ) )
{
}
return handled;
}
void
ClientSchemeHandler::GetResponseHeaders(
CefRefPtr<CefResponse> response
, int64& response_length
, CefString& redirectUrl
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
bool
ClientSchemeHandler::ReadResponse(
void* data_out
, int bytes_to_read
, int& bytes_read
, CefRefPtr<CefCallback> callback
) // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
return true;
}
void
ClientSchemeHandler::Cancel() // OVERRIDE
{
CEF_REQUIRE_IO_THREAD();
}
CefRefPtr<CefResourceHandler>
createClientSchemeHandler()
{
return new ClientSchemeHandler();
}
|
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "guldensendcoinsentry.h"
#include "_Gulden/forms/ui_guldensendcoinsentry.h"
#include "accounttablemodel.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "alert.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "nocksrequest.h"
#include "optionsmodel.h"
#include "units.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include <QApplication>
#include <QClipboard>
#include <QSortFilterProxyModel>
#include <QDialog>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QTimer>
#include "gui.h"
#include "validation/validation.h"//chainActive
#include "validation/witnessvalidation.h"
#include <consensus/validation.h>
#include "Gulden/util.h"
GuldenSendCoinsEntry::GuldenSendCoinsEntry(const QStyle *_platformStyle, QWidget *parent) :
QFrame(parent),
ui(new Ui::GuldenSendCoinsEntry),
model(0),
platformStyle(_platformStyle),
nocksQuote(nullptr)
{
ui->setupUi(this);
QList<QTabBar *> tabBar = this->ui->sendCoinsRecipientBook->findChildren<QTabBar *>();
tabBar.at(0)->setCursor(Qt::PointingHandCursor);
ui->searchLabel1->setText( GUIUtil::fontAwesomeSolid("\uf002") );
ui->searchLabel1->setTextFormat( Qt::RichText );
ui->searchLabel2->setText( GUIUtil::fontAwesomeSolid("\uf002") );
ui->searchLabel2->setTextFormat( Qt::RichText );
update();
ui->addressBookTabTable->horizontalHeader()->setStretchLastSection(true);
ui->addressBookTabTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->addressBookTabTable->horizontalHeader()->hide();
ui->myAccountsTabTable->horizontalHeader()->setStretchLastSection(true);
ui->myAccountsTabTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->myAccountsTabTable->horizontalHeader()->hide();
ui->sendCoinsRecipientStack->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsRecipientPage->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsWitnessPage->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsRecipientBook->setContentsMargins(0, 0, 0, 0);
ui->searchLabel1->setContentsMargins(0, 0, 0, 0);
ui->searchLabel2->setContentsMargins(0, 0, 0, 0);
ui->addressBookTabTable->setContentsMargins(0, 0, 0, 0);
ui->myAccountsTabTable->setContentsMargins(0, 0, 0, 0);
ui->sendAll->setContentsMargins(0, 0, 0, 0);
ui->sendAll->setIndent(0);
ui->sendAll->setCursor(Qt::PointingHandCursor);
ui->pow2LockFundsSlider->setMinimum(30);
ui->pow2LockFundsSlider->setMaximum(365*3);
ui->pow2LockFundsSlider->setValue(30);
ui->pow2LockFundsSlider->setCursor(Qt::PointingHandCursor);
connect(ui->searchBox1, SIGNAL(textEdited(QString)), this, SLOT(searchChangedAddressBook(QString)));
connect(ui->searchBox2, SIGNAL(textEdited(QString)), this, SLOT(searchChangedMyAccounts(QString)));
connect(ui->sendCoinsRecipientBook, SIGNAL(currentChanged(int)), this, SIGNAL(sendTabChanged()));
connect(ui->sendCoinsRecipientBook, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()));
connect(ui->receivingAddress, SIGNAL(textEdited(QString)), this, SLOT(addressChanged()));
connect(ui->pow2LockFundsSlider, SIGNAL(valueChanged(int)), this, SLOT(witnessSliderValueChanged(int)));
connect(ui->payAmount, SIGNAL(amountChanged()), this, SLOT(payAmountChanged()));
connect(ui->payAmount, SIGNAL(amountChanged()), this, SIGNAL(valueChanged()));
connect(ui->sendAll, SIGNAL(clicked()), this, SLOT(sendAllClicked()));
ui->receivingAddress->setProperty("valid", true);
//ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
nocksTimer = new QTimer(this);
nocksTimer->setInterval(60 * 1000); // if nothing changed update quote every 60s
connect(nocksTimer, SIGNAL(timeout()), this, SLOT(nocksTimeout()));
nocksTimer->start();
}
GuldenSendCoinsEntry::~GuldenSendCoinsEntry()
{
delete nocksTimer;
cancelNocksQuote();
delete ui;
}
bool GuldenSendCoinsEntry::isPoW2WitnessCreation()
{
return ui->sendCoinsRecipientStack->currentIndex() == 1;
}
void GuldenSendCoinsEntry::update()
{
if (isPoW2WitnessCreation())
{
ui->sendCoinsRecipientStack->setCurrentIndex(0);
ui->myAccountsTabTable->clearSelection();
}
}
void GuldenSendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
//ui->payTo->setText(QApplication::clipboard()->text());
}
void GuldenSendCoinsEntry::on_addressBookButton_clicked()
{
/*if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}*/
}
void GuldenSendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void GuldenSendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (model && model->getOptionsModel())
{
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
ui->payAmount->setOptionsModel(model->getOptionsModel());
}
if (model)
{
{
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model->getAddressTableModel());
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
proxyModelRecipients = new QSortFilterProxyModel(this);
proxyModelRecipients->setSourceModel(proxyModel);
proxyModelRecipients->setDynamicSortFilter(true);
proxyModelRecipients->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModelRecipients->setFilterFixedString("");
proxyModelRecipients->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModelRecipients->setFilterKeyColumn(AddressTableModel::ColumnIndex::Label);
ui->addressBookTabTable->setModel(proxyModelRecipients);
}
{
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model->getAccountTableModel());
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(AccountTableModel::StateRole);
proxyModel->setFilterFixedString(GetAccountStateString(AccountState::Normal).c_str());
QSortFilterProxyModel *proxyInactive = new QSortFilterProxyModel(this);
proxyInactive->setSourceModel(proxyModel);
proxyInactive->setDynamicSortFilter(true);
proxyInactive->setFilterRole(AccountTableModel::ActiveAccountRole);
proxyInactive->setFilterFixedString(AccountTableModel::Inactive);
QSortFilterProxyModel *proxyFilterBySubType = new QSortFilterProxyModel(this);
proxyFilterBySubType->setSourceModel(proxyInactive);
proxyFilterBySubType->setDynamicSortFilter(true);
proxyFilterBySubType->setFilterRole(AccountTableModel::TypeRole);
proxyFilterBySubType->setFilterRegExp(("^(?!"+GetAccountTypeString(AccountType::PoW2Witness)+").*$").c_str());
proxyModelAddresses = new QSortFilterProxyModel(this);
proxyModelAddresses->setSourceModel(proxyFilterBySubType);
proxyModelAddresses->setDynamicSortFilter(true);
proxyModelAddresses->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModelAddresses->setFilterFixedString("");
proxyModelAddresses->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModelAddresses->setFilterKeyColumn(AccountTableModel::ColumnIndex::Label);
proxyModelAddresses->setSortRole(Qt::DisplayRole);
proxyModelAddresses->sort(0);
connect(proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsInserted(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsRemoved(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(modelReset()), proxyModelAddresses, SLOT(invalidate()));
ui->myAccountsTabTable->setModel(proxyModelAddresses);
}
connect(ui->addressBookTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(sendTabChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->myAccountsTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(sendTabChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->addressBookTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(addressBookSelectionChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->myAccountsTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(myAccountsSelectionChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
}
clear();
}
void GuldenSendCoinsEntry::addressChanged()
{
SendCoinsRecipient val = getValue(false);
if (val.paymentType == SendCoinsRecipient::PaymentType::InvalidPayment)
{
}
else
{
ui->receivingAddress->setProperty("valid", true);
if (val.paymentType == SendCoinsRecipient::PaymentType::BitcoinPayment)
{
// ui->payAmount->setDisplayCurrency(GuldenAmountField::Currency::Bitcoin);
}
else if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Euro);
}
else
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Gulden);
}
}
payInfoUpdateRequired();
}
void GuldenSendCoinsEntry::tabChanged()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
{
addressChanged();
}
break;
case 1:
{
addressChanged();
}
break;
case 2:
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Gulden);
}
break;
}
}
void GuldenSendCoinsEntry::addressBookSelectionChanged()
{
tabChanged();
}
void GuldenSendCoinsEntry::myAccountsSelectionChanged()
{
QModelIndexList selection = ui->myAccountsTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
boost::uuids::uuid accountUUID = getUUIDFromString(index.data(AccountTableModel::AccountTableRoles::SelectedAccountRole).toString().toStdString());
LOCK(pactiveWallet->cs_wallet);
CAccount* pAccount = pactiveWallet->mapAccounts[accountUUID];
if ( pAccount->IsPoW2Witness() )
{
gotoWitnessTab(pAccount);
}
}
tabChanged();
}
void GuldenSendCoinsEntry::clear()
{
ui->receivingAddress->setProperty("valid", true);
ui->receivingAddress->setText("");
ui->payAmount->clear();
//fixme: (2.1) - implement the rest of this.
// clear UI elements for normal payment
/*ui->payTo->clear();
ui->addAsLabel->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();*/
// update the display unit, to not use the default ("NLG")
updateDisplayUnit();
}
void GuldenSendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
bool GuldenSendCoinsEntry::validate()
{
cancelNocksQuote();
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
ui->payAmount->setValid(true);
clearPayInfo();
if (isPoW2WitnessCreation())
{
int nDays = ui->pow2LockFundsSlider->value();
int64_t nOurWeight = GetPoW2RawWeightForAmount(ui->payAmount->amount(), nDays*576);
if (ui->payAmount->amount() < (gMinimumWitnessAmount*COIN) || nOurWeight <= gMinimumWitnessWeight)
{
setValid(ui->pow2LockFundsInfoLabel, false);
return false;
}
}
SendCoinsRecipient val = getValue(false);
if (val.paymentType == SendCoinsRecipient::PaymentType::InvalidPayment)
{
setValid(ui->receivingAddress, false);
retval = false;
}
else
{
setValid(ui->receivingAddress, false);
if (val.paymentType == SendCoinsRecipient::PaymentType::BitcoinPayment)
{
//ui->payAmount->setCurrency(NULL, NULL, GuldenAmountField::AmountFieldCurrency::CurrencyBitcoin);
CAmount currencyMax = model->getOptionsModel()->getNocksSettings()->getMaximumForCurrency("NLG-BTC");
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-BTC");
if ( ui->payAmount->amount() > currencyMax || ui->payAmount->amount() < currencyMin )
{
ui->payAmount->setValid(false);
return false;
}
}
else if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
{
CAmount currencyMax = model->getOptionsModel()->getNocksSettings()->getMaximumForCurrency("NLG-EUR");
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-EUR");
if (val.amount > currencyMax ) {
ui->payAmount->setValid(false);
setPayInfo(tr("Amount exceeds maximum for IBAN payment."), true);
return false;
}
if (val.amount < currencyMin)
{
ui->payAmount->setValid(false);
setPayInfo(tr("Amount below minimum for IBAN payment."), true);
return false;
}
}
else
{
//ui->payAmount->setCurrency(NULL, NULL, GuldenAmountField::AmountFieldCurrency::CurrencyGulden);
}
}
// Sending a zero amount is invalid
if (ui->payAmount->amount() <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
/*if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}*/
return retval;
}
SendCoinsRecipient::PaymentType GuldenSendCoinsEntry::getPaymentType(const QString& fromAddress)
{
SendCoinsRecipient::PaymentType ret = SendCoinsRecipient::PaymentType::InvalidPayment;
if (model->validateAddress(recipient.address))
{
ret = SendCoinsRecipient::PaymentType::NormalPayment;
}
else
{
QString compareModified = recipient.address;
#ifdef SUPPORT_BITCOIN_AS_FOREX
if (model->validateAddressBitcoin(compareModified))
{
ret = SendCoinsRecipient::PaymentType::BitcoinPayment;
}
else
#endif
{
// IBAN
if (model->validateAddressIBAN(recipient.address))
{
ret = SendCoinsRecipient::PaymentType::IBANPayment;
}
}
}
return ret;
}
SendCoinsRecipient GuldenSendCoinsEntry::getValue(bool showWarningDialogs)
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
recipient.addToAddressBook = false;
recipient.fSubtractFeeFromAmount = false;
recipient.amount = ui->payAmount->amount();
//fixme: (Post-2.1) - give user a choice here.
//fixme: (Post-2.1) Check if 'spend unconfirmed' is checked or not.
CAmount balanceToCheck = pactiveWallet->GetBalance(model->getActiveAccount(), false, true) + pactiveWallet->GetUnconfirmedBalance(model->getActiveAccount(), false, true);
if (recipient.amount >= balanceToCheck)
{
if (showWarningDialogs)
{
QString message = recipient.amount > balanceToCheck ?
tr("The amount you want to send exceeds your balance, amount has been automatically adjusted downwards to match your balance. Please ensure this is what you want before proceeding to avoid short payment of your recipient.")
: tr("The amount you want to send equals your balance, it will be adjusted for the transaction fee. Please ensure this is what you want before proceeding to avoid short payment of your recipient.");
QDialog* d = GUI::createDialog(this, message, tr("Okay"), "", 400, 180);
d->exec();
}
recipient.amount = balanceToCheck;
recipient.fSubtractFeeFromAmount = true;
}
//fixme: (Post-2.1) - Handle 'messages'
//recipient.message = ui->messageTextLabel->text();
recipient.destinationPoW2Witness.lockFromBlock = 0;
recipient.destinationPoW2Witness.lockUntilBlock = 0;
if (isPoW2WitnessCreation())
{
uint32_t nLockPeriodInBlocks = ui->pow2LockFundsSlider->value()*576;
// Add a small buffer to give us time to enter the blockchain
if (nLockPeriodInBlocks == 30*576)
nLockPeriodInBlocks += 50;
recipient.destinationPoW2Witness.lockUntilBlock = chainActive.Tip()->nHeight + nLockPeriodInBlocks;
CReserveKeyOrScript keySpending(pactiveWallet, targetWitnessAccount, KEYCHAIN_SPENDING);
CPubKey pubSpendingKey;
if (!keySpending.GetReservedKey(pubSpendingKey))
{
std::string strErrorMessage = "Failed to generate a spending key for witness funding.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf("%s", strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keySpending.ReturnKey();
CReserveKeyOrScript keyWitness(pactiveWallet, targetWitnessAccount, KEYCHAIN_WITNESS);
CPubKey pubWitnessKey;
if (!keySpending.GetReservedKey(pubWitnessKey))
{
std::string strErrorMessage = "Failed to generate a witness key for witness funding.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf(strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keyWitness.ReturnKey();
recipient.destinationPoW2Witness.spendingKey = pubSpendingKey.GetID();
recipient.destinationPoW2Witness.witnessKey = pubWitnessKey.GetID();
recipient.destinationPoW2Witness.failCount = 0;
recipient.destinationPoW2Witness.actionNonce = 0;
//NB! Setting this is -super- important, if we don't then encrypted wallets may fail to witness.
recipient.witnessForAccount = targetWitnessAccount;
recipient.address = QString::fromStdString(CGuldenAddress(CPoW2WitnessDestination(recipient.destinationPoW2Witness.spendingKey, recipient.destinationPoW2Witness.witnessKey)).ToString());
recipient.label = QString::fromStdString(pactiveWallet->mapAccountLabels[targetWitnessAccount->getUUID()]);
}
else
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
{
recipient.address = ui->receivingAddress->text();
recipient.label = ui->receivingAddressLabel->text();
recipient.addToAddressBook = ui->checkBoxAddToAddressBook->isChecked();
break;
}
case 1:
{
if (proxyModelRecipients)
{
QModelIndexList selection = ui->addressBookTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
recipient.address = index.sibling(index.row(), 1).data(Qt::DisplayRole).toString();
recipient.label = index.sibling(index.row(), 0).data(Qt::DisplayRole).toString();
}
}
break;
}
case 2:
{
if (proxyModelAddresses)
{
QModelIndexList selection = ui->myAccountsTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
boost::uuids::uuid accountUUID = getUUIDFromString(index.data(AccountTableModel::AccountTableRoles::SelectedAccountRole).toString().toStdString());
LOCK(pactiveWallet->cs_wallet);
CReserveKeyOrScript keySpending(pactiveWallet, pactiveWallet->mapAccounts[accountUUID], KEYCHAIN_EXTERNAL);
CPubKey pubSpendingKey;
if (!keySpending.GetReservedKey(pubSpendingKey))
{
std::string strErrorMessage = "Failed to generate a spending key for transaction.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf(strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keySpending.ReturnKey();
CKeyID keyID = pubSpendingKey.GetID();
recipient.address = QString::fromStdString(CGuldenAddress(keyID).ToString());
recipient.label = QString::fromStdString(pactiveWallet->mapAccountLabels[accountUUID]);
}
}
break;
}
}
}
// Strip all whitespace
recipient.address.replace(QRegularExpression("\\s"), "");
// Strip all punctuation
recipient.address.replace(QRegularExpression("\\p{P}"), "");
// Select payment type
recipient.paymentType = getPaymentType(recipient.address);
// For IBAN transactions adjust the final amount to Euro
if (recipient.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
recipient.amount = ui->payAmount->amount(GuldenAmountField::Currency::Euro);
return recipient;
}
QWidget *GuldenSendCoinsEntry::setupTabChain(QWidget *prev)
{
//fixme: (2.1) Implement.
return ui->payAmount;
}
void GuldenSendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
/*if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}*/
}
void GuldenSendCoinsEntry::setAmount(const CAmount amount)
{
ui->payAmount->setAmount(amount);
}
void GuldenSendCoinsEntry::setAddress(const QString &address)
{
/*ui->payTo->setText(address);
ui->payAmount->setFocus();*/
}
bool GuldenSendCoinsEntry::isClear()
{
//return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
return true;
}
void GuldenSendCoinsEntry::setFocus()
{
//ui->payTo->setFocus();
}
bool GuldenSendCoinsEntry::ShouldShowEditButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return false;
}
if (ui->addressBookTabTable->currentIndex().row() >= 0)
return true;
return false;
}
bool GuldenSendCoinsEntry::ShouldShowClearButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 1:
case 2:
return false;
}
return true;
}
bool GuldenSendCoinsEntry::ShouldShowDeleteButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return false;
}
if (ui->addressBookTabTable->currentIndex().row() >= 0)
return true;
return false;
}
void GuldenSendCoinsEntry::deleteAddressBookEntry()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return;
}
if (proxyModelRecipients && ui->addressBookTabTable->currentIndex().row() >= 0)
{
QModelIndexList indexes = ui->addressBookTabTable->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
QString message = tr("Are you sure you want to delete %1 from the address book?").arg(indexes.at(0).sibling(indexes.at(0).row(), 0).data(Qt::DisplayRole).toString());
QDialog* d = GUI::createDialog(this, message, tr("Delete"), tr("Cancel"), 400, 180);
int result = d->exec();
if(result == QDialog::Accepted)
{
ui->addressBookTabTable->model()->removeRow(indexes.at(0).row());
}
}
}
}
void GuldenSendCoinsEntry::editAddressBookEntry()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return;
}
if (proxyModelRecipients && ui->addressBookTabTable->currentIndex().row() >= 0)
{
QModelIndexList indexes = ui->addressBookTabTable->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
QDialog* d = new QDialog(this);
d->setMinimumSize(QSize(400,200));
QVBoxLayout* vbox = new QVBoxLayout();
vbox->setSpacing(0);
vbox->setContentsMargins( 0, 0, 0, 0 );
QLineEdit* lineEditAddress = new QLineEdit(d);
vbox->addWidget(lineEditAddress);
lineEditAddress->setText(indexes.at(0).sibling(indexes.at(0).row(), 0).data(Qt::DisplayRole).toString());
lineEditAddress->setObjectName("receivingAddress_dialog");
lineEditAddress->setContentsMargins( 0, 0, 0, 0 );
QLineEdit* lineEditLabel = new QLineEdit(d);
vbox->addWidget(lineEditLabel);
lineEditLabel->setText(indexes.at(0).sibling(indexes.at(0).row(), 1).data(Qt::DisplayRole).toString());
lineEditLabel->setObjectName("receivingAddressLabel_dialog");
lineEditLabel->setContentsMargins( 0, 0, 0, 0 );
QWidget* spacer = new QWidget(d);
spacer->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
vbox->addWidget(spacer);
QFrame* horizontalLine = new QFrame(d);
horizontalLine->setFrameStyle(QFrame::HLine);
horizontalLine->setFixedHeight(1);
horizontalLine->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
horizontalLine->setStyleSheet(GULDEN_DIALOG_HLINE_STYLE);
vbox->addWidget(horizontalLine);
//We use reset button because it shows on the left where we want it.
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Reset, d);
QObject::connect(buttonBox, SIGNAL(accepted()), d, SLOT(accept()));
QObject::connect(buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), d, SLOT(reject()));
vbox->addWidget(buttonBox);
buttonBox->setContentsMargins( 0, 0, 0, 0 );
buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Save"));
buttonBox->button(QDialogButtonBox::Ok)->setCursor(Qt::PointingHandCursor);
buttonBox->button(QDialogButtonBox::Ok)->setStyleSheet(GULDEN_DIALOG_CONFIRM_BUTTON_STYLE);
//buttonBox->button(QDialogButtonBox::Reset)->setObjectName("cancelButton");
buttonBox->button(QDialogButtonBox::Reset)->setText(tr("Cancel"));
buttonBox->button(QDialogButtonBox::Reset)->setCursor(Qt::PointingHandCursor);
buttonBox->button(QDialogButtonBox::Reset)->setStyleSheet(GULDEN_DIALOG_CANCEL_BUTTON_STYLE);
d->setLayout(vbox);
int result = d->exec();
if(result == QDialog::Accepted)
{
ui->addressBookTabTable->model()->setData(indexes.at(0).sibling(indexes.at(0).row(), 0), lineEditAddress->text(), Qt::EditRole);
ui->addressBookTabTable->model()->setData(indexes.at(0).sibling(indexes.at(0).row(), 1), lineEditLabel->text(), Qt::EditRole);
}
}
}
}
void GuldenSendCoinsEntry::gotoWitnessTab(CAccount* targetAccount)
{
targetWitnessAccount = targetAccount;
witnessSliderValueChanged(0);
ui->sendCoinsRecipientStack->setCurrentIndex(1);
}
void GuldenSendCoinsEntry::updateDisplayUnit()
{
/*if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}*/
}
void GuldenSendCoinsEntry::searchChangedAddressBook(const QString& searchString)
{
proxyModelRecipients->setFilterFixedString(searchString);
//fixme: (2.1) - Only if currently selected item not still visible
ui->addressBookTabTable->selectionModel()->clear();
ui->addressBookTabTable->selectionModel()->setCurrentIndex ( proxyModelRecipients->index(0, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
void GuldenSendCoinsEntry::searchChangedMyAccounts(const QString& searchString)
{
proxyModelAddresses->setFilterFixedString(searchString);
//fixme: (2.1) - Only if currently selected item not still visible
ui->myAccountsTabTable->selectionModel()->clear();
ui->myAccountsTabTable->selectionModel()->setCurrentIndex ( proxyModelAddresses->index(0, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
#define WITNESS_SUBSIDY 20
void GuldenSendCoinsEntry::witnessSliderValueChanged(int newValue)
{
setValid(ui->pow2LockFundsInfoLabel, true);
//fixme: (2.0) (POW2) (CLEANUP)
CAmount nAmount = ui->payAmount->amount();
ui->pow2WeightExceedsMaxPercentWarning->setVisible(false);
if (nAmount < CAmount(gMinimumWitnessAmount*COIN))
{
ui->pow2LockFundsInfoLabel->setText(tr("A minimum amount of %1 is required.").arg(gMinimumWitnessAmount));
return;
}
int nDays = newValue;
float fMonths = newValue/30.0;
float fYears = newValue/365.0;
int nEarnings = 0;
int64_t nOurWeight = GetPoW2RawWeightForAmount(nAmount, nDays*576);
static int64_t nNetworkWeight = gStartingWitnessNetworkWeightEstimate;
if (chainActive.Tip())
{
static uint64_t lastUpdate = GetTimeMillis();
// Only check this once a minute, no need to be constantly updating.
if (GetTimeMillis() - lastUpdate > 60000)
{
LOCK(cs_main);
lastUpdate = GetTimeMillis();
if (IsPow2WitnessingActive(chainActive.TipPrev(), Params(), chainActive))
{
CGetWitnessInfo witnessInfo;
CBlock block;
if (!ReadBlockFromDisk(block, chainActive.Tip(), Params()))
{
std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk";
LogPrintf(strErrorMessage.c_str());
CAlert::Notify(strErrorMessage, true, true);
return;
}
if (!GetWitnessInfo(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo, chainActive.Tip()->nHeight))
{
std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk";
LogPrintf(strErrorMessage.c_str());
CAlert::Notify(strErrorMessage, true, true);
return;
}
nNetworkWeight = witnessInfo.nTotalWeight;
}
}
}
if (nOurWeight < gMinimumWitnessWeight)
{
ui->pow2LockFundsInfoLabel->setText(tr("A minimum weight of %1 is required, but selected weight is only %2. Please increase the amount or lock time for a larger weight.").arg(gMinimumWitnessWeight).arg(nOurWeight));
return;
}
double fWeightPercent = nOurWeight/(double)nNetworkWeight;
if (fWeightPercent > 0.01)
{
ui->pow2WeightExceedsMaxPercentWarning->setVisible(true);
fWeightPercent = 0.01;
}
double fBlocksPerDay = 576 * fWeightPercent;
if (fBlocksPerDay > 5.76)
fBlocksPerDay = 5.76;
nEarnings = fBlocksPerDay * nDays * WITNESS_SUBSIDY;
float fPercent = (fBlocksPerDay * 30 * WITNESS_SUBSIDY)/((nAmount/100000000))*100;
QString sSecondTimeUnit = "";
if (fYears > 1)
{
sSecondTimeUnit = tr("1 year");
if (fYears > 1.0)
sSecondTimeUnit = tr("%1 years").arg(QString::number(fYears, 'f', 2).replace(".00",""));
}
else
{
sSecondTimeUnit = tr("1 month");
if (fMonths > 1.0)
sSecondTimeUnit = tr("%1 months").arg(QString::number(fMonths, 'f', 2).replace(".00",""));
}
ui->pow2LockFundsInfoLabel->setText(tr("Funds will be locked for %1 days (%2). It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.\n\nEstimated earnings: %3 (%4% per month)\n\nWitness weight: %5")
.arg(nDays)
.arg(sSecondTimeUnit)
.arg(nEarnings)
.arg(QString::number(fPercent, 'f', 2).replace(".00",""))
.arg(nOurWeight)
);
}
void GuldenSendCoinsEntry::payAmountChanged()
{
witnessSliderValueChanged(ui->pow2LockFundsSlider->value());
payInfoUpdateRequired();
}
bool GuldenSendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
//ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
void GuldenSendCoinsEntry::payInfoUpdateRequired()
{
// any outstanding quote request is now outdated
cancelNocksQuote();
// for IBAN payment that passes minimum amount request a quote
SendCoinsRecipient val = getValue(false);
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-EUR");
if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment && val.amount > currencyMin) {
nocksQuote = new NocksRequest(this);
connect(nocksQuote, SIGNAL(requestProcessed()), this, SLOT(nocksQuoteProcessed()));
nocksQuote->startRequest(NULL, NocksRequest::RequestType::Quotation, "NLG", "EUR",
GuldenUnits::format(GuldenUnits::NLG, val.amount, false, GuldenUnits::separatorNever, 2));
}
else
{
clearPayInfo();
}
}
void GuldenSendCoinsEntry::nocksQuoteProcessed()
{
if (nocksQuote->nativeAmount > 0) // for very small amounts, like EUR 0.01 Nocks will return a negative amount
{
QString msg = QString(tr("Will require approximately %1 Gulden including IBAN service fee")).arg(GuldenUnits::format(
GuldenUnits::NLG,
nocksQuote->nativeAmount,
false, GuldenUnits::separatorAlways, 2));
setPayInfo(msg);
}
else
{
clearPayInfo();
}
nocksQuote->deleteLater();
nocksQuote = nullptr;
}
void GuldenSendCoinsEntry::nocksTimeout()
{
// require an update of the payInfo to keep up with Nocks exchange rate changes
// if there is already a pending Nocks quote we can skip this timer update
if (!nocksQuote)
{
payInfoUpdateRequired();
}
}
void GuldenSendCoinsEntry::sendAllClicked()
{
//fixme: (Post-2.1) Check if 'spend unconfirmed' is checked or not.
ui->payAmount->setAmount(pactiveWallet->GetBalance(model->getActiveAccount(), false, true) + pactiveWallet->GetUnconfirmedBalance(model->getActiveAccount(), false, true));
payInfoUpdateRequired();
//Update witness value for amount.
witnessSliderValueChanged(ui->pow2LockFundsSlider->value());
}
void GuldenSendCoinsEntry::setPayInfo(const QString &msg, bool attention)
{
ui->payInfo->setText(msg);
if (attention)
ui->payInfo->setStyleSheet(STYLE_INVALID);
else
ui->payInfo->setStyleSheet("");
}
void GuldenSendCoinsEntry::clearPayInfo()
{
ui->payInfo->setText("");
ui->payInfo->setStyleSheet("");
}
void GuldenSendCoinsEntry::cancelNocksQuote()
{
if (nocksQuote) {
nocksQuote->cancel();
nocksQuote->deleteLater();
nocksQuote = nullptr;
}
}
Another potential deadlock fix.
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "guldensendcoinsentry.h"
#include "_Gulden/forms/ui_guldensendcoinsentry.h"
#include "accounttablemodel.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "alert.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "nocksrequest.h"
#include "optionsmodel.h"
#include "units.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include <QApplication>
#include <QClipboard>
#include <QSortFilterProxyModel>
#include <QDialog>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QTimer>
#include "gui.h"
#include "validation/validation.h"//chainActive
#include "validation/witnessvalidation.h"
#include <consensus/validation.h>
#include "Gulden/util.h"
GuldenSendCoinsEntry::GuldenSendCoinsEntry(const QStyle *_platformStyle, QWidget *parent) :
QFrame(parent),
ui(new Ui::GuldenSendCoinsEntry),
model(0),
platformStyle(_platformStyle),
nocksQuote(nullptr)
{
ui->setupUi(this);
QList<QTabBar *> tabBar = this->ui->sendCoinsRecipientBook->findChildren<QTabBar *>();
tabBar.at(0)->setCursor(Qt::PointingHandCursor);
ui->searchLabel1->setText( GUIUtil::fontAwesomeSolid("\uf002") );
ui->searchLabel1->setTextFormat( Qt::RichText );
ui->searchLabel2->setText( GUIUtil::fontAwesomeSolid("\uf002") );
ui->searchLabel2->setTextFormat( Qt::RichText );
update();
ui->addressBookTabTable->horizontalHeader()->setStretchLastSection(true);
ui->addressBookTabTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->addressBookTabTable->horizontalHeader()->hide();
ui->myAccountsTabTable->horizontalHeader()->setStretchLastSection(true);
ui->myAccountsTabTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->myAccountsTabTable->horizontalHeader()->hide();
ui->sendCoinsRecipientStack->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsRecipientPage->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsWitnessPage->setContentsMargins(0, 0, 0, 0);
ui->sendCoinsRecipientBook->setContentsMargins(0, 0, 0, 0);
ui->searchLabel1->setContentsMargins(0, 0, 0, 0);
ui->searchLabel2->setContentsMargins(0, 0, 0, 0);
ui->addressBookTabTable->setContentsMargins(0, 0, 0, 0);
ui->myAccountsTabTable->setContentsMargins(0, 0, 0, 0);
ui->sendAll->setContentsMargins(0, 0, 0, 0);
ui->sendAll->setIndent(0);
ui->sendAll->setCursor(Qt::PointingHandCursor);
ui->pow2LockFundsSlider->setMinimum(30);
ui->pow2LockFundsSlider->setMaximum(365*3);
ui->pow2LockFundsSlider->setValue(30);
ui->pow2LockFundsSlider->setCursor(Qt::PointingHandCursor);
connect(ui->searchBox1, SIGNAL(textEdited(QString)), this, SLOT(searchChangedAddressBook(QString)));
connect(ui->searchBox2, SIGNAL(textEdited(QString)), this, SLOT(searchChangedMyAccounts(QString)));
connect(ui->sendCoinsRecipientBook, SIGNAL(currentChanged(int)), this, SIGNAL(sendTabChanged()));
connect(ui->sendCoinsRecipientBook, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()));
connect(ui->receivingAddress, SIGNAL(textEdited(QString)), this, SLOT(addressChanged()));
connect(ui->pow2LockFundsSlider, SIGNAL(valueChanged(int)), this, SLOT(witnessSliderValueChanged(int)));
connect(ui->payAmount, SIGNAL(amountChanged()), this, SLOT(payAmountChanged()));
connect(ui->payAmount, SIGNAL(amountChanged()), this, SIGNAL(valueChanged()));
connect(ui->sendAll, SIGNAL(clicked()), this, SLOT(sendAllClicked()));
ui->receivingAddress->setProperty("valid", true);
//ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
nocksTimer = new QTimer(this);
nocksTimer->setInterval(60 * 1000); // if nothing changed update quote every 60s
connect(nocksTimer, SIGNAL(timeout()), this, SLOT(nocksTimeout()));
nocksTimer->start();
}
GuldenSendCoinsEntry::~GuldenSendCoinsEntry()
{
delete nocksTimer;
cancelNocksQuote();
delete ui;
}
bool GuldenSendCoinsEntry::isPoW2WitnessCreation()
{
return ui->sendCoinsRecipientStack->currentIndex() == 1;
}
void GuldenSendCoinsEntry::update()
{
if (isPoW2WitnessCreation())
{
ui->sendCoinsRecipientStack->setCurrentIndex(0);
ui->myAccountsTabTable->clearSelection();
}
}
void GuldenSendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
//ui->payTo->setText(QApplication::clipboard()->text());
}
void GuldenSendCoinsEntry::on_addressBookButton_clicked()
{
/*if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}*/
}
void GuldenSendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void GuldenSendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (model && model->getOptionsModel())
{
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
ui->payAmount->setOptionsModel(model->getOptionsModel());
}
if (model)
{
{
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model->getAddressTableModel());
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
proxyModelRecipients = new QSortFilterProxyModel(this);
proxyModelRecipients->setSourceModel(proxyModel);
proxyModelRecipients->setDynamicSortFilter(true);
proxyModelRecipients->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModelRecipients->setFilterFixedString("");
proxyModelRecipients->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModelRecipients->setFilterKeyColumn(AddressTableModel::ColumnIndex::Label);
ui->addressBookTabTable->setModel(proxyModelRecipients);
}
{
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model->getAccountTableModel());
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(AccountTableModel::StateRole);
proxyModel->setFilterFixedString(GetAccountStateString(AccountState::Normal).c_str());
QSortFilterProxyModel *proxyInactive = new QSortFilterProxyModel(this);
proxyInactive->setSourceModel(proxyModel);
proxyInactive->setDynamicSortFilter(true);
proxyInactive->setFilterRole(AccountTableModel::ActiveAccountRole);
proxyInactive->setFilterFixedString(AccountTableModel::Inactive);
QSortFilterProxyModel *proxyFilterBySubType = new QSortFilterProxyModel(this);
proxyFilterBySubType->setSourceModel(proxyInactive);
proxyFilterBySubType->setDynamicSortFilter(true);
proxyFilterBySubType->setFilterRole(AccountTableModel::TypeRole);
proxyFilterBySubType->setFilterRegExp(("^(?!"+GetAccountTypeString(AccountType::PoW2Witness)+").*$").c_str());
proxyModelAddresses = new QSortFilterProxyModel(this);
proxyModelAddresses->setSourceModel(proxyFilterBySubType);
proxyModelAddresses->setDynamicSortFilter(true);
proxyModelAddresses->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModelAddresses->setFilterFixedString("");
proxyModelAddresses->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModelAddresses->setFilterKeyColumn(AccountTableModel::ColumnIndex::Label);
proxyModelAddresses->setSortRole(Qt::DisplayRole);
proxyModelAddresses->sort(0);
connect(proxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsInserted(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsRemoved(QModelIndex,int,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)), proxyModelAddresses, SLOT(invalidate()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(proxyModel, SIGNAL(modelReset()), proxyModelAddresses, SLOT(invalidate()));
ui->myAccountsTabTable->setModel(proxyModelAddresses);
}
connect(ui->addressBookTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(sendTabChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->myAccountsTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(sendTabChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->addressBookTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(addressBookSelectionChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
connect(ui->myAccountsTabTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(myAccountsSelectionChanged()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection));
}
clear();
}
void GuldenSendCoinsEntry::addressChanged()
{
SendCoinsRecipient val = getValue(false);
if (val.paymentType == SendCoinsRecipient::PaymentType::InvalidPayment)
{
}
else
{
ui->receivingAddress->setProperty("valid", true);
if (val.paymentType == SendCoinsRecipient::PaymentType::BitcoinPayment)
{
// ui->payAmount->setDisplayCurrency(GuldenAmountField::Currency::Bitcoin);
}
else if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Euro);
}
else
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Gulden);
}
}
payInfoUpdateRequired();
}
void GuldenSendCoinsEntry::tabChanged()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
{
addressChanged();
}
break;
case 1:
{
addressChanged();
}
break;
case 2:
{
ui->payAmount->setPrimaryDisplayCurrency(GuldenAmountField::Currency::Gulden);
}
break;
}
}
void GuldenSendCoinsEntry::addressBookSelectionChanged()
{
tabChanged();
}
void GuldenSendCoinsEntry::myAccountsSelectionChanged()
{
QModelIndexList selection = ui->myAccountsTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
boost::uuids::uuid accountUUID = getUUIDFromString(index.data(AccountTableModel::AccountTableRoles::SelectedAccountRole).toString().toStdString());
LOCK(pactiveWallet->cs_wallet);
CAccount* pAccount = pactiveWallet->mapAccounts[accountUUID];
if ( pAccount->IsPoW2Witness() )
{
gotoWitnessTab(pAccount);
}
}
tabChanged();
}
void GuldenSendCoinsEntry::clear()
{
ui->receivingAddress->setProperty("valid", true);
ui->receivingAddress->setText("");
ui->payAmount->clear();
//fixme: (2.1) - implement the rest of this.
// clear UI elements for normal payment
/*ui->payTo->clear();
ui->addAsLabel->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();*/
// update the display unit, to not use the default ("NLG")
updateDisplayUnit();
}
void GuldenSendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
bool GuldenSendCoinsEntry::validate()
{
cancelNocksQuote();
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
ui->payAmount->setValid(true);
clearPayInfo();
if (isPoW2WitnessCreation())
{
int nDays = ui->pow2LockFundsSlider->value();
int64_t nOurWeight = GetPoW2RawWeightForAmount(ui->payAmount->amount(), nDays*576);
if (ui->payAmount->amount() < (gMinimumWitnessAmount*COIN) || nOurWeight <= gMinimumWitnessWeight)
{
setValid(ui->pow2LockFundsInfoLabel, false);
return false;
}
}
SendCoinsRecipient val = getValue(false);
if (val.paymentType == SendCoinsRecipient::PaymentType::InvalidPayment)
{
setValid(ui->receivingAddress, false);
retval = false;
}
else
{
setValid(ui->receivingAddress, false);
if (val.paymentType == SendCoinsRecipient::PaymentType::BitcoinPayment)
{
//ui->payAmount->setCurrency(NULL, NULL, GuldenAmountField::AmountFieldCurrency::CurrencyBitcoin);
CAmount currencyMax = model->getOptionsModel()->getNocksSettings()->getMaximumForCurrency("NLG-BTC");
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-BTC");
if ( ui->payAmount->amount() > currencyMax || ui->payAmount->amount() < currencyMin )
{
ui->payAmount->setValid(false);
return false;
}
}
else if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
{
CAmount currencyMax = model->getOptionsModel()->getNocksSettings()->getMaximumForCurrency("NLG-EUR");
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-EUR");
if (val.amount > currencyMax ) {
ui->payAmount->setValid(false);
setPayInfo(tr("Amount exceeds maximum for IBAN payment."), true);
return false;
}
if (val.amount < currencyMin)
{
ui->payAmount->setValid(false);
setPayInfo(tr("Amount below minimum for IBAN payment."), true);
return false;
}
}
else
{
//ui->payAmount->setCurrency(NULL, NULL, GuldenAmountField::AmountFieldCurrency::CurrencyGulden);
}
}
// Sending a zero amount is invalid
if (ui->payAmount->amount() <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
/*if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}*/
return retval;
}
SendCoinsRecipient::PaymentType GuldenSendCoinsEntry::getPaymentType(const QString& fromAddress)
{
SendCoinsRecipient::PaymentType ret = SendCoinsRecipient::PaymentType::InvalidPayment;
if (model->validateAddress(recipient.address))
{
ret = SendCoinsRecipient::PaymentType::NormalPayment;
}
else
{
QString compareModified = recipient.address;
#ifdef SUPPORT_BITCOIN_AS_FOREX
if (model->validateAddressBitcoin(compareModified))
{
ret = SendCoinsRecipient::PaymentType::BitcoinPayment;
}
else
#endif
{
// IBAN
if (model->validateAddressIBAN(recipient.address))
{
ret = SendCoinsRecipient::PaymentType::IBANPayment;
}
}
}
return ret;
}
SendCoinsRecipient GuldenSendCoinsEntry::getValue(bool showWarningDialogs)
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
recipient.addToAddressBook = false;
recipient.fSubtractFeeFromAmount = false;
recipient.amount = ui->payAmount->amount();
//fixme: (Post-2.1) - give user a choice here.
//fixme: (Post-2.1) Check if 'spend unconfirmed' is checked or not.
CAmount balanceToCheck = pactiveWallet->GetBalance(model->getActiveAccount(), false, true) + pactiveWallet->GetUnconfirmedBalance(model->getActiveAccount(), false, true);
if (recipient.amount >= balanceToCheck)
{
if (showWarningDialogs)
{
QString message = recipient.amount > balanceToCheck ?
tr("The amount you want to send exceeds your balance, amount has been automatically adjusted downwards to match your balance. Please ensure this is what you want before proceeding to avoid short payment of your recipient.")
: tr("The amount you want to send equals your balance, it will be adjusted for the transaction fee. Please ensure this is what you want before proceeding to avoid short payment of your recipient.");
QDialog* d = GUI::createDialog(this, message, tr("Okay"), "", 400, 180);
d->exec();
}
recipient.amount = balanceToCheck;
recipient.fSubtractFeeFromAmount = true;
}
//fixme: (Post-2.1) - Handle 'messages'
//recipient.message = ui->messageTextLabel->text();
recipient.destinationPoW2Witness.lockFromBlock = 0;
recipient.destinationPoW2Witness.lockUntilBlock = 0;
if (isPoW2WitnessCreation())
{
uint32_t nLockPeriodInBlocks = ui->pow2LockFundsSlider->value()*576;
// Add a small buffer to give us time to enter the blockchain
if (nLockPeriodInBlocks == 30*576)
nLockPeriodInBlocks += 50;
recipient.destinationPoW2Witness.lockUntilBlock = chainActive.Tip()->nHeight + nLockPeriodInBlocks;
CReserveKeyOrScript keySpending(pactiveWallet, targetWitnessAccount, KEYCHAIN_SPENDING);
CPubKey pubSpendingKey;
if (!keySpending.GetReservedKey(pubSpendingKey))
{
std::string strErrorMessage = "Failed to generate a spending key for witness funding.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf("%s", strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keySpending.ReturnKey();
CReserveKeyOrScript keyWitness(pactiveWallet, targetWitnessAccount, KEYCHAIN_WITNESS);
CPubKey pubWitnessKey;
if (!keySpending.GetReservedKey(pubWitnessKey))
{
std::string strErrorMessage = "Failed to generate a witness key for witness funding.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf(strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keyWitness.ReturnKey();
recipient.destinationPoW2Witness.spendingKey = pubSpendingKey.GetID();
recipient.destinationPoW2Witness.witnessKey = pubWitnessKey.GetID();
recipient.destinationPoW2Witness.failCount = 0;
recipient.destinationPoW2Witness.actionNonce = 0;
//NB! Setting this is -super- important, if we don't then encrypted wallets may fail to witness.
recipient.witnessForAccount = targetWitnessAccount;
recipient.address = QString::fromStdString(CGuldenAddress(CPoW2WitnessDestination(recipient.destinationPoW2Witness.spendingKey, recipient.destinationPoW2Witness.witnessKey)).ToString());
recipient.label = QString::fromStdString(pactiveWallet->mapAccountLabels[targetWitnessAccount->getUUID()]);
}
else
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
{
recipient.address = ui->receivingAddress->text();
recipient.label = ui->receivingAddressLabel->text();
recipient.addToAddressBook = ui->checkBoxAddToAddressBook->isChecked();
break;
}
case 1:
{
if (proxyModelRecipients)
{
QModelIndexList selection = ui->addressBookTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
recipient.address = index.sibling(index.row(), 1).data(Qt::DisplayRole).toString();
recipient.label = index.sibling(index.row(), 0).data(Qt::DisplayRole).toString();
}
}
break;
}
case 2:
{
if (proxyModelAddresses)
{
QModelIndexList selection = ui->myAccountsTabTable->selectionModel()->selectedRows();
if (selection.count() > 0)
{
QModelIndex index = selection.at(0);
boost::uuids::uuid accountUUID = getUUIDFromString(index.data(AccountTableModel::AccountTableRoles::SelectedAccountRole).toString().toStdString());
LOCK2(cs_main, pactiveWallet->cs_wallet);
CReserveKeyOrScript keySpending(pactiveWallet, pactiveWallet->mapAccounts[accountUUID], KEYCHAIN_EXTERNAL);
CPubKey pubSpendingKey;
if (!keySpending.GetReservedKey(pubSpendingKey))
{
std::string strErrorMessage = "Failed to generate a spending key for transaction.\nPlease unlock your wallet and try again.\nIf the problem persists please seek technical support.";
CAlert::Notify(strErrorMessage, true, true);
LogPrintf(strErrorMessage.c_str());
recipient.paymentType = SendCoinsRecipient::PaymentType::InvalidPayment;
recipient.address = QString("error");
return recipient;
}
//We delibritely return the key here, so that if we fail we won't leak the key.
//The key will be marked as used when the transaction is accepted anyway.
keySpending.ReturnKey();
CKeyID keyID = pubSpendingKey.GetID();
recipient.address = QString::fromStdString(CGuldenAddress(keyID).ToString());
recipient.label = QString::fromStdString(pactiveWallet->mapAccountLabels[accountUUID]);
}
}
break;
}
}
}
// Strip all whitespace
recipient.address.replace(QRegularExpression("\\s"), "");
// Strip all punctuation
recipient.address.replace(QRegularExpression("\\p{P}"), "");
// Select payment type
recipient.paymentType = getPaymentType(recipient.address);
// For IBAN transactions adjust the final amount to Euro
if (recipient.paymentType == SendCoinsRecipient::PaymentType::IBANPayment)
recipient.amount = ui->payAmount->amount(GuldenAmountField::Currency::Euro);
return recipient;
}
QWidget *GuldenSendCoinsEntry::setupTabChain(QWidget *prev)
{
//fixme: (2.1) Implement.
return ui->payAmount;
}
void GuldenSendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
/*if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}*/
}
void GuldenSendCoinsEntry::setAmount(const CAmount amount)
{
ui->payAmount->setAmount(amount);
}
void GuldenSendCoinsEntry::setAddress(const QString &address)
{
/*ui->payTo->setText(address);
ui->payAmount->setFocus();*/
}
bool GuldenSendCoinsEntry::isClear()
{
//return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
return true;
}
void GuldenSendCoinsEntry::setFocus()
{
//ui->payTo->setFocus();
}
bool GuldenSendCoinsEntry::ShouldShowEditButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return false;
}
if (ui->addressBookTabTable->currentIndex().row() >= 0)
return true;
return false;
}
bool GuldenSendCoinsEntry::ShouldShowClearButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 1:
case 2:
return false;
}
return true;
}
bool GuldenSendCoinsEntry::ShouldShowDeleteButton() const
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return false;
}
if (ui->addressBookTabTable->currentIndex().row() >= 0)
return true;
return false;
}
void GuldenSendCoinsEntry::deleteAddressBookEntry()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return;
}
if (proxyModelRecipients && ui->addressBookTabTable->currentIndex().row() >= 0)
{
QModelIndexList indexes = ui->addressBookTabTable->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
QString message = tr("Are you sure you want to delete %1 from the address book?").arg(indexes.at(0).sibling(indexes.at(0).row(), 0).data(Qt::DisplayRole).toString());
QDialog* d = GUI::createDialog(this, message, tr("Delete"), tr("Cancel"), 400, 180);
int result = d->exec();
if(result == QDialog::Accepted)
{
ui->addressBookTabTable->model()->removeRow(indexes.at(0).row());
}
}
}
}
void GuldenSendCoinsEntry::editAddressBookEntry()
{
switch(ui->sendCoinsRecipientBook->currentIndex())
{
case 0:
case 2:
return;
}
if (proxyModelRecipients && ui->addressBookTabTable->currentIndex().row() >= 0)
{
QModelIndexList indexes = ui->addressBookTabTable->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
QDialog* d = new QDialog(this);
d->setMinimumSize(QSize(400,200));
QVBoxLayout* vbox = new QVBoxLayout();
vbox->setSpacing(0);
vbox->setContentsMargins( 0, 0, 0, 0 );
QLineEdit* lineEditAddress = new QLineEdit(d);
vbox->addWidget(lineEditAddress);
lineEditAddress->setText(indexes.at(0).sibling(indexes.at(0).row(), 0).data(Qt::DisplayRole).toString());
lineEditAddress->setObjectName("receivingAddress_dialog");
lineEditAddress->setContentsMargins( 0, 0, 0, 0 );
QLineEdit* lineEditLabel = new QLineEdit(d);
vbox->addWidget(lineEditLabel);
lineEditLabel->setText(indexes.at(0).sibling(indexes.at(0).row(), 1).data(Qt::DisplayRole).toString());
lineEditLabel->setObjectName("receivingAddressLabel_dialog");
lineEditLabel->setContentsMargins( 0, 0, 0, 0 );
QWidget* spacer = new QWidget(d);
spacer->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
vbox->addWidget(spacer);
QFrame* horizontalLine = new QFrame(d);
horizontalLine->setFrameStyle(QFrame::HLine);
horizontalLine->setFixedHeight(1);
horizontalLine->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
horizontalLine->setStyleSheet(GULDEN_DIALOG_HLINE_STYLE);
vbox->addWidget(horizontalLine);
//We use reset button because it shows on the left where we want it.
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Reset, d);
QObject::connect(buttonBox, SIGNAL(accepted()), d, SLOT(accept()));
QObject::connect(buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), d, SLOT(reject()));
vbox->addWidget(buttonBox);
buttonBox->setContentsMargins( 0, 0, 0, 0 );
buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Save"));
buttonBox->button(QDialogButtonBox::Ok)->setCursor(Qt::PointingHandCursor);
buttonBox->button(QDialogButtonBox::Ok)->setStyleSheet(GULDEN_DIALOG_CONFIRM_BUTTON_STYLE);
//buttonBox->button(QDialogButtonBox::Reset)->setObjectName("cancelButton");
buttonBox->button(QDialogButtonBox::Reset)->setText(tr("Cancel"));
buttonBox->button(QDialogButtonBox::Reset)->setCursor(Qt::PointingHandCursor);
buttonBox->button(QDialogButtonBox::Reset)->setStyleSheet(GULDEN_DIALOG_CANCEL_BUTTON_STYLE);
d->setLayout(vbox);
int result = d->exec();
if(result == QDialog::Accepted)
{
ui->addressBookTabTable->model()->setData(indexes.at(0).sibling(indexes.at(0).row(), 0), lineEditAddress->text(), Qt::EditRole);
ui->addressBookTabTable->model()->setData(indexes.at(0).sibling(indexes.at(0).row(), 1), lineEditLabel->text(), Qt::EditRole);
}
}
}
}
void GuldenSendCoinsEntry::gotoWitnessTab(CAccount* targetAccount)
{
targetWitnessAccount = targetAccount;
witnessSliderValueChanged(0);
ui->sendCoinsRecipientStack->setCurrentIndex(1);
}
void GuldenSendCoinsEntry::updateDisplayUnit()
{
/*if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}*/
}
void GuldenSendCoinsEntry::searchChangedAddressBook(const QString& searchString)
{
proxyModelRecipients->setFilterFixedString(searchString);
//fixme: (2.1) - Only if currently selected item not still visible
ui->addressBookTabTable->selectionModel()->clear();
ui->addressBookTabTable->selectionModel()->setCurrentIndex ( proxyModelRecipients->index(0, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
void GuldenSendCoinsEntry::searchChangedMyAccounts(const QString& searchString)
{
proxyModelAddresses->setFilterFixedString(searchString);
//fixme: (2.1) - Only if currently selected item not still visible
ui->myAccountsTabTable->selectionModel()->clear();
ui->myAccountsTabTable->selectionModel()->setCurrentIndex ( proxyModelAddresses->index(0, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
#define WITNESS_SUBSIDY 20
void GuldenSendCoinsEntry::witnessSliderValueChanged(int newValue)
{
setValid(ui->pow2LockFundsInfoLabel, true);
//fixme: (2.0) (POW2) (CLEANUP)
CAmount nAmount = ui->payAmount->amount();
ui->pow2WeightExceedsMaxPercentWarning->setVisible(false);
if (nAmount < CAmount(gMinimumWitnessAmount*COIN))
{
ui->pow2LockFundsInfoLabel->setText(tr("A minimum amount of %1 is required.").arg(gMinimumWitnessAmount));
return;
}
int nDays = newValue;
float fMonths = newValue/30.0;
float fYears = newValue/365.0;
int nEarnings = 0;
int64_t nOurWeight = GetPoW2RawWeightForAmount(nAmount, nDays*576);
static int64_t nNetworkWeight = gStartingWitnessNetworkWeightEstimate;
if (chainActive.Tip())
{
static uint64_t lastUpdate = GetTimeMillis();
// Only check this once a minute, no need to be constantly updating.
if (GetTimeMillis() - lastUpdate > 60000)
{
LOCK(cs_main);
lastUpdate = GetTimeMillis();
if (IsPow2WitnessingActive(chainActive.TipPrev(), Params(), chainActive))
{
CGetWitnessInfo witnessInfo;
CBlock block;
if (!ReadBlockFromDisk(block, chainActive.Tip(), Params()))
{
std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk";
LogPrintf(strErrorMessage.c_str());
CAlert::Notify(strErrorMessage, true, true);
return;
}
if (!GetWitnessInfo(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo, chainActive.Tip()->nHeight))
{
std::string strErrorMessage = "GuldenSendCoinsEntry::witnessSliderValueChanged Failed to read block from disk";
LogPrintf(strErrorMessage.c_str());
CAlert::Notify(strErrorMessage, true, true);
return;
}
nNetworkWeight = witnessInfo.nTotalWeight;
}
}
}
if (nOurWeight < gMinimumWitnessWeight)
{
ui->pow2LockFundsInfoLabel->setText(tr("A minimum weight of %1 is required, but selected weight is only %2. Please increase the amount or lock time for a larger weight.").arg(gMinimumWitnessWeight).arg(nOurWeight));
return;
}
double fWeightPercent = nOurWeight/(double)nNetworkWeight;
if (fWeightPercent > 0.01)
{
ui->pow2WeightExceedsMaxPercentWarning->setVisible(true);
fWeightPercent = 0.01;
}
double fBlocksPerDay = 576 * fWeightPercent;
if (fBlocksPerDay > 5.76)
fBlocksPerDay = 5.76;
nEarnings = fBlocksPerDay * nDays * WITNESS_SUBSIDY;
float fPercent = (fBlocksPerDay * 30 * WITNESS_SUBSIDY)/((nAmount/100000000))*100;
QString sSecondTimeUnit = "";
if (fYears > 1)
{
sSecondTimeUnit = tr("1 year");
if (fYears > 1.0)
sSecondTimeUnit = tr("%1 years").arg(QString::number(fYears, 'f', 2).replace(".00",""));
}
else
{
sSecondTimeUnit = tr("1 month");
if (fMonths > 1.0)
sSecondTimeUnit = tr("%1 months").arg(QString::number(fMonths, 'f', 2).replace(".00",""));
}
ui->pow2LockFundsInfoLabel->setText(tr("Funds will be locked for %1 days (%2). It will not be possible under any circumstances to spend or move these funds for the duration of the lock period.\n\nEstimated earnings: %3 (%4% per month)\n\nWitness weight: %5")
.arg(nDays)
.arg(sSecondTimeUnit)
.arg(nEarnings)
.arg(QString::number(fPercent, 'f', 2).replace(".00",""))
.arg(nOurWeight)
);
}
void GuldenSendCoinsEntry::payAmountChanged()
{
witnessSliderValueChanged(ui->pow2LockFundsSlider->value());
payInfoUpdateRequired();
}
bool GuldenSendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
//ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
void GuldenSendCoinsEntry::payInfoUpdateRequired()
{
// any outstanding quote request is now outdated
cancelNocksQuote();
// for IBAN payment that passes minimum amount request a quote
SendCoinsRecipient val = getValue(false);
CAmount currencyMin = model->getOptionsModel()->getNocksSettings()->getMinimumForCurrency("NLG-EUR");
if (val.paymentType == SendCoinsRecipient::PaymentType::IBANPayment && val.amount > currencyMin) {
nocksQuote = new NocksRequest(this);
connect(nocksQuote, SIGNAL(requestProcessed()), this, SLOT(nocksQuoteProcessed()));
nocksQuote->startRequest(NULL, NocksRequest::RequestType::Quotation, "NLG", "EUR",
GuldenUnits::format(GuldenUnits::NLG, val.amount, false, GuldenUnits::separatorNever, 2));
}
else
{
clearPayInfo();
}
}
void GuldenSendCoinsEntry::nocksQuoteProcessed()
{
if (nocksQuote->nativeAmount > 0) // for very small amounts, like EUR 0.01 Nocks will return a negative amount
{
QString msg = QString(tr("Will require approximately %1 Gulden including IBAN service fee")).arg(GuldenUnits::format(
GuldenUnits::NLG,
nocksQuote->nativeAmount,
false, GuldenUnits::separatorAlways, 2));
setPayInfo(msg);
}
else
{
clearPayInfo();
}
nocksQuote->deleteLater();
nocksQuote = nullptr;
}
void GuldenSendCoinsEntry::nocksTimeout()
{
// require an update of the payInfo to keep up with Nocks exchange rate changes
// if there is already a pending Nocks quote we can skip this timer update
if (!nocksQuote)
{
payInfoUpdateRequired();
}
}
void GuldenSendCoinsEntry::sendAllClicked()
{
//fixme: (Post-2.1) Check if 'spend unconfirmed' is checked or not.
ui->payAmount->setAmount(pactiveWallet->GetBalance(model->getActiveAccount(), false, true) + pactiveWallet->GetUnconfirmedBalance(model->getActiveAccount(), false, true));
payInfoUpdateRequired();
//Update witness value for amount.
witnessSliderValueChanged(ui->pow2LockFundsSlider->value());
}
void GuldenSendCoinsEntry::setPayInfo(const QString &msg, bool attention)
{
ui->payInfo->setText(msg);
if (attention)
ui->payInfo->setStyleSheet(STYLE_INVALID);
else
ui->payInfo->setStyleSheet("");
}
void GuldenSendCoinsEntry::clearPayInfo()
{
ui->payInfo->setText("");
ui->payInfo->setStyleSheet("");
}
void GuldenSendCoinsEntry::cancelNocksQuote()
{
if (nocksQuote) {
nocksQuote->cancel();
nocksQuote->deleteLater();
nocksQuote = nullptr;
}
}
|
/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_INTERPROCESS_CONDVAR
#define REALM_UTIL_INTERPROCESS_CONDVAR
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#include <realm/util/interprocess_mutex.hpp>
#include <stdint.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
// Condvar Emulation is required if RobustMutex emulation is enabled
#ifdef REALM_ROBUST_MUTEX_EMULATION
#define REALM_CONDVAR_EMULATION
#endif
namespace realm {
namespace util {
/// Condition variable for use in synchronization monitors.
/// This condition variable uses emulation based on named pipes
/// for the inter-process case, if enabled by REALM_CONDVAR_EMULATION.
///
/// FIXME: This implementation will never release/delete pipes. This is unlikely
/// to be a problem as long as only a modest number of different database names
/// are in use
///
/// A InterprocessCondVar is always process shared.
class InterprocessCondVar {
public:
InterprocessCondVar();
~InterprocessCondVar() noexcept;
/// To use the InterprocessCondVar, you also must place a structure of type
/// InterprocessCondVar::SharedPart in memory shared by multiple processes
/// or in a memory mapped file, and use set_shared_part() to associate
/// the condition variable with it's shared part. You must initialize
/// the shared part using InterprocessCondVar::init_shared_part(), but only before
/// first use and only when you have exclusive access to the shared part.
#ifdef REALM_CONDVAR_EMULATION
struct SharedPart {
uint64_t signal_counter;
uint64_t wait_counter;
};
#else
typedef CondVar SharedPart;
#endif
/// You need to bind the emulation to a SharedPart in shared/mmapped memory.
/// The SharedPart is assumed to have been initialized (possibly by another process)
/// earlier through a call to init_shared_part.
void set_shared_part(SharedPart& shared_part, std::string path, size_t offset_of_condvar);
/// Initialize the shared part of a process shared condition variable.
/// A process shared condition variables may be represented by any number of
/// InterprocessCondVar instances in any number of different processes,
/// all sharing a common SharedPart instance, which must be in shared memory.
static void init_shared_part(SharedPart& shared_part);
/// Wait for someone to call notify() or notify_all() on this condition
/// variable. The call to wait() may return spuriously, so the caller should
/// always re-evaluate the condition on which to wait and loop on wait()
/// if necessary.
void wait(InterprocessMutex& m, const struct timespec* tp);
/// If any threads are waiting for this condition, wake up at least one.
/// (Current implementation may actually wake all :-O ). The caller must
/// hold the lock associated with the condvar at the time of calling notify()
void notify() noexcept;
/// Wake up every thread that is currently waiting on this condition.
/// The caller must hold the lock associated with the condvar at the time
/// of calling notify_all().
void notify_all() noexcept;
/// Cleanup and release system resources if possible.
void close() noexcept;
private:
// non-zero if a shared part has been registered (always 0 on process local instances)
SharedPart* m_shared_part = nullptr;
bool uses_emulation = false;
// pipe used for emulation
int m_fd_read = -1;
int m_fd_write = -1;
};
// Implementation:
} // namespace util
} // namespace realm
#endif
added forgotten include
/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_INTERPROCESS_CONDVAR
#define REALM_UTIL_INTERPROCESS_CONDVAR
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#include <realm/util/interprocess_mutex.hpp>
#include <stdint.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <mutex>
// Condvar Emulation is required if RobustMutex emulation is enabled
#ifdef REALM_ROBUST_MUTEX_EMULATION
#define REALM_CONDVAR_EMULATION
#endif
namespace realm {
namespace util {
/// Condition variable for use in synchronization monitors.
/// This condition variable uses emulation based on named pipes
/// for the inter-process case, if enabled by REALM_CONDVAR_EMULATION.
///
/// FIXME: This implementation will never release/delete pipes. This is unlikely
/// to be a problem as long as only a modest number of different database names
/// are in use
///
/// A InterprocessCondVar is always process shared.
class InterprocessCondVar {
public:
InterprocessCondVar();
~InterprocessCondVar() noexcept;
/// To use the InterprocessCondVar, you also must place a structure of type
/// InterprocessCondVar::SharedPart in memory shared by multiple processes
/// or in a memory mapped file, and use set_shared_part() to associate
/// the condition variable with it's shared part. You must initialize
/// the shared part using InterprocessCondVar::init_shared_part(), but only before
/// first use and only when you have exclusive access to the shared part.
#ifdef REALM_CONDVAR_EMULATION
struct SharedPart {
uint64_t signal_counter;
uint64_t wait_counter;
};
#else
typedef CondVar SharedPart;
#endif
/// You need to bind the emulation to a SharedPart in shared/mmapped memory.
/// The SharedPart is assumed to have been initialized (possibly by another process)
/// earlier through a call to init_shared_part.
void set_shared_part(SharedPart& shared_part, std::string path, size_t offset_of_condvar);
/// Initialize the shared part of a process shared condition variable.
/// A process shared condition variables may be represented by any number of
/// InterprocessCondVar instances in any number of different processes,
/// all sharing a common SharedPart instance, which must be in shared memory.
static void init_shared_part(SharedPart& shared_part);
/// Wait for someone to call notify() or notify_all() on this condition
/// variable. The call to wait() may return spuriously, so the caller should
/// always re-evaluate the condition on which to wait and loop on wait()
/// if necessary.
void wait(InterprocessMutex& m, const struct timespec* tp);
/// If any threads are waiting for this condition, wake up at least one.
/// (Current implementation may actually wake all :-O ). The caller must
/// hold the lock associated with the condvar at the time of calling notify()
void notify() noexcept;
/// Wake up every thread that is currently waiting on this condition.
/// The caller must hold the lock associated with the condvar at the time
/// of calling notify_all().
void notify_all() noexcept;
/// Cleanup and release system resources if possible.
void close() noexcept;
private:
// non-zero if a shared part has been registered (always 0 on process local instances)
SharedPart* m_shared_part = nullptr;
bool uses_emulation = false;
// pipe used for emulation
int m_fd_read = -1;
int m_fd_write = -1;
};
// Implementation:
} // namespace util
} // namespace realm
#endif
|
// This define MUST be before including vulkan_render_device.hpp
#define VMA_IMPLEMENTATION
#include "vulkan_render_device.hpp"
#include <sstream>
#include <minitrace.h>
#include <rx/core/abort.h>
#include <rx/core/algorithm/max.h>
#include <rx/core/log.h>
#include <rx/core/set.h>
#include <signal.h>
#include <string.h>
#include "nova_renderer/camera.hpp"
#include "nova_renderer/constants.hpp"
#include "nova_renderer/frame_context.hpp"
#include "nova_renderer/renderables.hpp"
#include "nova_renderer/rhi/pipeline_create_info.hpp"
#include "nova_renderer/window.hpp"
#include "vk_structs.hpp"
#include "vulkan_command_list.hpp"
#include "vulkan_utils.hpp"
// TODO: Move window creation out of the RHI
#ifdef NOVA_LINUX
#define NOVA_VK_XLIB
#include "../../util/linux_utils.hpp"
#elif defined(NOVA_WINDOWS)
#include "nova_renderer/util/windows.hpp"
#endif
using namespace nova::mem;
#if defined(NOVA_WINDOWS)
#define BREAK_ON_DEVICE_LOST(result) \
if((result) == VK_ERROR_DEVICE_LOST) { \
DebugBreak(); \
}
#elif defined(NOVA_LINUX)
#define BREAK_ON_DEVICE_LOST(result) \
if((result) == VK_ERROR_DEVICE_LOST) { \
raise(SIGINT); \
}
#endif
namespace nova::renderer::rhi {
RX_LOG("VulkanRenderDevice", logger);
void FencedTask::operator()() const { work_to_perform(); }
VulkanRenderDevice::VulkanRenderDevice(NovaSettingsAccessManager& settings, NovaWindow& window, rx::memory::allocator& allocator)
: RenderDevice{settings, window, allocator},
vk_internal_allocator{wrap_allocator(internal_allocator)},
command_pools_by_thread_idx{&internal_allocator},
fenced_tasks{&internal_allocator} {
MTR_SCOPE("VulkanRenderDevice", "VulkanRenderDevice");
create_instance();
if(settings.settings.debug.enabled) {
enable_debug_output();
}
create_surface();
create_device_and_queues();
save_device_info();
initialize_vma();
if(settings.settings.debug.enabled) {
// Late init, can only be used when the device has already been created
vkSetDebugUtilsObjectNameEXT = reinterpret_cast<PFN_vkSetDebugUtilsObjectNameEXT>(
vkGetDeviceProcAddr(device, "vkSetDebugUtilsObjectNameEXT"));
}
create_swapchain();
create_per_thread_command_pools();
create_standard_pipeline_layout();
}
void VulkanRenderDevice::set_num_renderpasses(uint32_t /* num_renderpasses */) {
// Pretty sure Vulkan doesn't need to do anything here
}
ntl::Result<RhiRenderpass*> VulkanRenderDevice::create_renderpass(const renderpack::RenderPassCreateInfo& data,
const glm::uvec2& framebuffer_size,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_renderpass");
auto* vk_swapchain = static_cast<VulkanSwapchain*>(swapchain);
VkExtent2D swapchain_extent = {swapchain_size.x, swapchain_size.y};
auto* renderpass = allocator.create<VulkanRenderpass>();
VkSubpassDescription subpass_description = {};
subpass_description.flags = 0;
subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass_description.inputAttachmentCount = 0;
subpass_description.pInputAttachments = nullptr;
subpass_description.preserveAttachmentCount = 0;
subpass_description.pPreserveAttachments = nullptr;
subpass_description.pResolveAttachments = nullptr;
subpass_description.pDepthStencilAttachment = nullptr;
VkSubpassDependency image_available_dependency = {};
image_available_dependency.dependencyFlags = 0;
image_available_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
image_available_dependency.dstSubpass = 0;
image_available_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.srcAccessMask = 0;
image_available_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_create_info = {};
render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_create_info.pNext = nullptr;
render_pass_create_info.flags = 0;
render_pass_create_info.subpassCount = 1;
render_pass_create_info.pSubpasses = &subpass_description;
render_pass_create_info.dependencyCount = 1;
render_pass_create_info.pDependencies = &image_available_dependency;
rx::vector<VkAttachmentReference> attachment_references{&allocator};
rx::vector<VkAttachmentDescription> attachments{&allocator};
rx::vector<VkImageView> framebuffer_attachments{&allocator};
uint32_t framebuffer_width = framebuffer_size.x;
uint32_t framebuffer_height = framebuffer_size.y;
bool writes_to_backbuffer = false;
// Collect framebuffer size information from color output attachments
data.texture_outputs.each_fwd([&](const renderpack::TextureAttachmentInfo& attachment) {
if(attachment.name == BACKBUFFER_NAME) {
// Handle backbuffer
// Backbuffer framebuffers are handled by themselves in their own special snowflake way so we just need to skip
// everything
writes_to_backbuffer = true;
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = vk_swapchain->get_swapchain_format();
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachments.size()) - 1;
attachment_references.push_back(ref);
framebuffer_width = swapchain_extent.width;
framebuffer_height = swapchain_extent.height;
} else {
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = to_vk_format(attachment.pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = attachment.clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachments.size()) - 1;
attachment_references.push_back(ref);
}
});
VkAttachmentReference depth_reference = {};
// Collect framebuffer size information from the depth attachment
if(data.depth_texture) {
VkAttachmentDescription desc = {};
desc.flags = 0;
desc.format = to_vk_format(data.depth_texture->pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = data.depth_texture->clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depth_reference.attachment = static_cast<uint32_t>(attachments.size()) - 1;
subpass_description.pDepthStencilAttachment = &depth_reference;
}
if(framebuffer_width == 0) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer width for pass {:s} is 0. This is illegal! Make sure that there is at least one attachment for this render pass, and ensure that all attachments used by this pass have a non-zero width",
data.name.data()));
}
if(framebuffer_height == 0) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer height for pass {:s} is 0. This is illegal! Make sure that there is at least one attachment for this render pass, and ensure that all attachments used by this pass have a non-zero height",
data.name.data()));
}
if(framebuffer_attachments.size() > gpu.props.limits.maxColorAttachments) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer for pass {:s} has {:d} color attachments, but your GPU only supports {:d}. Please reduce the number of attachments that this pass uses, possibly by changing some of your input attachments to bound textures",
data.name.data(),
data.texture_outputs.size(),
gpu.props.limits.maxColorAttachments));
}
subpass_description.colorAttachmentCount = static_cast<uint32_t>(attachment_references.size());
subpass_description.pColorAttachments = attachment_references.data();
render_pass_create_info.attachmentCount = static_cast<uint32_t>(attachments.size());
render_pass_create_info.pAttachments = attachments.data();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
NOVA_CHECK_RESULT(vkCreateRenderPass(device, &render_pass_create_info, &vk_alloc, &renderpass->pass));
if(writes_to_backbuffer) {
if(data.texture_outputs.size() > 1) {
logger->error(
"Pass %s writes to the backbuffer, and other textures. Passes that write to the backbuffer are not allowed to write to any other textures",
data.name);
}
}
renderpass->render_area = {{0, 0}, {framebuffer_width, framebuffer_height}};
if(settings.settings.debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_RENDER_PASS;
object_name.objectHandle = reinterpret_cast<uint64_t>(renderpass->pass);
object_name.pObjectName = data.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return ntl::Result(static_cast<RhiRenderpass*>(renderpass));
}
RhiFramebuffer* VulkanRenderDevice::create_framebuffer(const RhiRenderpass* renderpass,
const rx::vector<RhiImage*>& color_attachments,
const rx::optional<RhiImage*> depth_attachment,
const glm::uvec2& framebuffer_size,
rx::memory::allocator& allocator) {
const auto* vk_renderpass = static_cast<const VulkanRenderpass*>(renderpass);
rx::vector<VkImageView> attachment_views(&allocator);
attachment_views.reserve(color_attachments.size() + 1);
color_attachments.each_fwd([&](const RhiImage* attachment) {
const auto* vk_image = static_cast<const VulkanImage*>(attachment);
attachment_views.push_back(vk_image->image_view);
});
// Depth attachment is ALWAYS the last attachment
if(depth_attachment) {
const auto* vk_depth_image = static_cast<const VulkanImage*>(*depth_attachment);
attachment_views.push_back(vk_depth_image->image_view);
}
VkFramebufferCreateInfo framebuffer_create_info = {};
framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_create_info.renderPass = vk_renderpass->pass;
framebuffer_create_info.attachmentCount = static_cast<uint32_t>(attachment_views.size());
framebuffer_create_info.pAttachments = attachment_views.data();
framebuffer_create_info.width = framebuffer_size.x;
framebuffer_create_info.height = framebuffer_size.y;
framebuffer_create_info.layers = 1;
auto* framebuffer = allocator.create<VulkanFramebuffer>();
framebuffer->size = framebuffer_size;
framebuffer->num_attachments = static_cast<uint32_t>(attachment_views.size());
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
NOVA_CHECK_RESULT(vkCreateFramebuffer(device, &framebuffer_create_info, &vk_alloc, &framebuffer->framebuffer));
return framebuffer;
}
rx::ptr<RhiResourceBinder> VulkanRenderDevice::create_resource_binder_for_pipeline(const RhiGraphicsPipelineState& pipeline_state,
rx::memory::allocator& allocator) {
return {};
}
ntl::Result<RhiPipelineInterface*> VulkanRenderDevice::create_pipeline_interface(
const rx::map<rx::string, RhiResourceBindingDescription>& bindings,
const rx::vector<renderpack::TextureAttachmentInfo>& color_attachments,
const rx::optional<renderpack::TextureAttachmentInfo>& depth_texture,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_pipeline_interface");
auto* vk_swapchain = static_cast<VulkanSwapchain*>(swapchain);
auto* pipeline_interface = allocator.create<VulkanPipelineInterface>();
pipeline_interface->bindings = bindings;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
VkSubpassDescription subpass_description;
subpass_description.flags = 0;
subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass_description.inputAttachmentCount = 0;
subpass_description.pInputAttachments = nullptr;
subpass_description.preserveAttachmentCount = 0;
subpass_description.pPreserveAttachments = nullptr;
subpass_description.pResolveAttachments = nullptr;
subpass_description.pDepthStencilAttachment = nullptr;
VkSubpassDependency image_available_dependency;
image_available_dependency.dependencyFlags = 0;
image_available_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
image_available_dependency.dstSubpass = 0;
image_available_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.srcAccessMask = 0;
image_available_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_create_info;
render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_create_info.pNext = nullptr;
render_pass_create_info.flags = 0;
render_pass_create_info.subpassCount = 1;
render_pass_create_info.pSubpasses = &subpass_description;
render_pass_create_info.dependencyCount = 1;
render_pass_create_info.pDependencies = &image_available_dependency;
rx::vector<VkAttachmentReference> attachment_references{&internal_allocator};
rx::vector<VkAttachmentDescription> attachment_descriptions{&internal_allocator};
rx::vector<VkImageView> framebuffer_attachments{&internal_allocator};
// Collect framebuffer size information from color output attachments
color_attachments.each_fwd([&](const renderpack::TextureAttachmentInfo& attachment) {
if(attachment.name == BACKBUFFER_NAME) {
// Handle backbuffer
// Backbuffer framebuffers are handled by themselves in their own special snowflake way so we just need to skip
// everything
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = vk_swapchain->get_swapchain_format();
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
attachment_references.push_back(ref);
return false;
}
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = to_vk_format(attachment.pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = attachment.clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
attachment_references.push_back(ref);
return true;
});
VkAttachmentReference depth_reference = {};
// Collect framebuffer size information from the depth attachment
if(depth_texture) {
VkAttachmentDescription desc = {};
desc.flags = 0;
desc.format = to_vk_format(depth_texture->pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = depth_texture->clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depth_reference.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
subpass_description.pDepthStencilAttachment = &depth_reference;
}
subpass_description.colorAttachmentCount = static_cast<uint32_t>(attachment_references.size());
subpass_description.pColorAttachments = attachment_references.data();
render_pass_create_info.attachmentCount = static_cast<uint32_t>(attachment_descriptions.size());
render_pass_create_info.pAttachments = attachment_descriptions.data();
{
MTR_SCOPE("VulkanRenderDevice", "CreateDummyRenderpass");
NOVA_CHECK_RESULT(vkCreateRenderPass(device, &render_pass_create_info, &vk_alloc, &pipeline_interface->pass));
}
return ntl::Result(static_cast<RhiPipelineInterface*>(pipeline_interface));
}
rx::optional<vk::DescriptorPool> VulkanRenderDevice::create_descriptor_pool(
const rx::map<DescriptorType, uint32_t>& descriptor_capacity, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_descriptor_pool");
rx::vector<vk::DescriptorPoolSize> pool_sizes{&internal_allocator};
uint32_t max_sets = 0;
descriptor_capacity.each_pair([&](const DescriptorType& type, const uint32_t count) {
pool_sizes.emplace_back(vk::DescriptorPoolSize{to_vk_descriptor_type(type), count});
max_sets += count;
});
const auto pool_create_info = vk::DescriptorPoolCreateInfo()
.setFlags(vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind)
.setMaxSets(max_sets)
.setPoolSizeCount(static_cast<uint32_t>(pool_sizes.size()))
.setPPoolSizes(pool_sizes.data());
vk::DescriptorPool pool;
const auto& vk_alloc = wrap_allocator(allocator);
device.createDescriptorPool(&pool_create_info, &vk_alloc, &pool);
return pool;
}
vk::DescriptorSet VulkanRenderDevice::get_next_standard_descriptor_set() {
if(standard_descriptor_sets.is_empty()) {
const auto variable_set_counts = rx::array{MAX_NUM_TEXTURES};
const auto count_allocate_info = vk::DescriptorSetVariableDescriptorCountAllocateInfo()
.setPDescriptorCounts(variable_set_counts.data())
.setDescriptorSetCount(static_cast<uint32_t>(variable_set_counts.size()));
const auto allocate_info = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(standard_descriptor_set_pool->descriptor_pool)
.setDescriptorSetCount(1)
.setPSetLayouts(&standard_set_layout)
.setPNext(&count_allocate_info);
vk::DescriptorSet set;
device.allocateDescriptorSets(&allocate_info, &set);
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET;
object_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkDescriptorSet>(set));
object_name.pObjectName = "Standard descriptor set";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return set;
} else {
const auto set = standard_descriptor_sets.last();
standard_descriptor_sets.pop_back();
return set;
}
}
void VulkanRenderDevice::return_standard_descriptor_sets(const rx::vector<vk::DescriptorSet>& sets) {
standard_descriptor_sets += sets;
}
vk::Fence VulkanRenderDevice::get_next_submission_fence() {
if(submission_fences.is_empty()) {
const auto fence_create_info = vk::FenceCreateInfo();
vk::Fence fence;
device.createFence(&fence_create_info, &vk_internal_allocator, &fence);
return fence;
} else {
const auto fence = submission_fences.last();
submission_fences.pop_back();
return fence;
}
}
ntl::Result<VulkanPipeline> VulkanRenderDevice::create_pipeline(const RhiGraphicsPipelineState& state,
vk::RenderPass renderpass,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_pipeline");
logger->verbose("Creating a VkPipeline for pipeline %s", state.name);
VulkanPipeline vk_pipeline{};
rx::vector<VkPipelineShaderStageCreateInfo> shader_stages{&internal_allocator};
rx::map<VkShaderStageFlags, VkShaderModule> shader_modules{&internal_allocator};
logger->verbose("Compiling vertex module");
const auto vertex_module = create_shader_module(state.vertex_shader.source);
if(vertex_module) {
shader_modules.insert(VK_SHADER_STAGE_VERTEX_BIT, *vertex_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not create vertex module")};
}
if(state.geometry_shader) {
logger->verbose("Compiling geometry module");
const auto geometry_module = create_shader_module(state.geometry_shader->source);
if(geometry_module) {
shader_modules.insert(VK_SHADER_STAGE_GEOMETRY_BIT, *geometry_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not geometry module")};
}
}
if(state.pixel_shader) {
logger->verbose("Compiling fragment module");
const auto fragment_module = create_shader_module(state.pixel_shader->source);
if(fragment_module) {
shader_modules.insert(VK_SHADER_STAGE_FRAGMENT_BIT, *fragment_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not pixel module")};
}
} // namespace nova::renderer::rhi
shader_modules.each_pair([&](const VkShaderStageFlags stage, const VkShaderModule shader_module) {
VkPipelineShaderStageCreateInfo shader_stage_create_info;
shader_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shader_stage_create_info.pNext = nullptr;
shader_stage_create_info.flags = 0;
shader_stage_create_info.stage = static_cast<VkShaderStageFlagBits>(stage);
shader_stage_create_info.module = shader_module;
shader_stage_create_info.pName = "main";
shader_stage_create_info.pSpecializationInfo = nullptr;
shader_stages.push_back(shader_stage_create_info);
});
const auto& [vertex_attribute_descriptions, vertex_binding_descriptions] = get_input_assembler_setup(state.vertex_fields);
VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info;
vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state_create_info.pNext = nullptr;
vertex_input_state_create_info.flags = 0;
vertex_input_state_create_info.vertexBindingDescriptionCount = static_cast<uint32_t>(vertex_binding_descriptions.size());
vertex_input_state_create_info.pVertexBindingDescriptions = vertex_binding_descriptions.data();
vertex_input_state_create_info.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_attribute_descriptions.size());
vertex_input_state_create_info.pVertexAttributeDescriptions = vertex_attribute_descriptions.data();
VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly_create_info.pNext = nullptr;
input_assembly_create_info.flags = 0;
input_assembly_create_info.primitiveRestartEnable = VK_FALSE;
switch(state.topology) {
case PrimitiveTopology::TriangleList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
break;
case PrimitiveTopology::LineList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
break;
case PrimitiveTopology::PointList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
break;
}
VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = state.viewport_size.x;
viewport.height = state.viewport_size.y;
viewport.minDepth = 0.0F;
viewport.maxDepth = 1.0F;
VkRect2D scissor;
scissor.offset = {0, 0};
scissor.extent = {static_cast<uint32_t>(state.viewport_size.x), static_cast<uint32_t>(state.viewport_size.y)};
VkPipelineViewportStateCreateInfo viewport_state_create_info;
viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state_create_info.pNext = nullptr;
viewport_state_create_info.flags = 0;
viewport_state_create_info.viewportCount = 1;
viewport_state_create_info.pViewports = &viewport;
viewport_state_create_info.scissorCount = 1;
viewport_state_create_info.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer_create_info;
rasterizer_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer_create_info.pNext = nullptr;
rasterizer_create_info.flags = 0;
rasterizer_create_info.depthClampEnable = VK_FALSE;
rasterizer_create_info.rasterizerDiscardEnable = VK_FALSE;
rasterizer_create_info.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer_create_info.lineWidth = 1.0F;
rasterizer_create_info.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer_create_info.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer_create_info.depthClampEnable = VK_FALSE;
rasterizer_create_info.depthBiasConstantFactor = state.rasterizer_state.depth_bias;
rasterizer_create_info.depthBiasSlopeFactor = state.rasterizer_state.slope_scaled_depth_bias;
rasterizer_create_info.depthBiasClamp = state.rasterizer_state.maximum_depth_bias;
if(rasterizer_create_info.depthBiasConstantFactor != 0 || rasterizer_create_info.depthBiasSlopeFactor != 0) {
rasterizer_create_info.depthBiasEnable = VK_TRUE;
} else {
rasterizer_create_info.depthBiasEnable = VK_FALSE;
}
VkPipelineMultisampleStateCreateInfo multisample_create_info;
multisample_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisample_create_info.pNext = nullptr;
multisample_create_info.flags = 0;
multisample_create_info.sampleShadingEnable = VK_FALSE;
multisample_create_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisample_create_info.minSampleShading = 1.0F;
multisample_create_info.pSampleMask = nullptr;
multisample_create_info.alphaToCoverageEnable = VK_FALSE;
multisample_create_info.alphaToOneEnable = VK_FALSE;
VkPipelineDepthStencilStateCreateInfo depth_stencil_create_info = {};
depth_stencil_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
if(state.depth_state) {
const auto& depth_state = *state.depth_state;
depth_stencil_create_info.depthTestEnable = VK_TRUE;
depth_stencil_create_info.depthWriteEnable = static_cast<VkBool32>(depth_state.enable_depth_write);
depth_stencil_create_info.depthCompareOp = to_compare_op(depth_state.compare_op);
if(depth_state.bounds_test_state) {
depth_stencil_create_info.depthBoundsTestEnable = VK_TRUE;
if(depth_state.bounds_test_state->mode == DepthBoundsTestMode::Static) {
depth_stencil_create_info.minDepthBounds = depth_state.bounds_test_state->static_state.min_bound;
depth_stencil_create_info.maxDepthBounds = depth_state.bounds_test_state->static_state.max_bound;
}
}
}
if(state.stencil_state) {
const auto stencil_state = *state.stencil_state;
depth_stencil_create_info.stencilTestEnable = VK_TRUE;
depth_stencil_create_info.front.failOp = to_stencil_op(stencil_state.front_face_op.fail_op);
depth_stencil_create_info.front.passOp = to_stencil_op(stencil_state.front_face_op.pass_op);
depth_stencil_create_info.front.depthFailOp = to_stencil_op(stencil_state.front_face_op.depth_fail_op);
depth_stencil_create_info.front.compareOp = to_compare_op(stencil_state.front_face_op.compare_op);
depth_stencil_create_info.front.compareMask = stencil_state.front_face_op.compare_mask;
depth_stencil_create_info.front.writeMask = stencil_state.front_face_op.write_mask;
depth_stencil_create_info.back.failOp = to_stencil_op(stencil_state.back_face_op.fail_op);
depth_stencil_create_info.back.passOp = to_stencil_op(stencil_state.back_face_op.pass_op);
depth_stencil_create_info.back.depthFailOp = to_stencil_op(stencil_state.back_face_op.depth_fail_op);
depth_stencil_create_info.back.compareOp = to_compare_op(stencil_state.back_face_op.compare_op);
depth_stencil_create_info.back.compareMask = stencil_state.back_face_op.compare_mask;
depth_stencil_create_info.back.writeMask = stencil_state.back_face_op.write_mask;
}
VkPipelineColorBlendStateCreateInfo color_blend_create_info{};
color_blend_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend_create_info.pNext = nullptr;
color_blend_create_info.flags = 0;
color_blend_create_info.logicOpEnable = VK_FALSE;
color_blend_create_info.logicOp = VK_LOGIC_OP_COPY;
rx::vector<VkPipelineColorBlendAttachmentState> attachment_states{&allocator};
if(state.blend_state) {
const auto& blend_state = *state.blend_state;
attachment_states.reserve(blend_state.render_target_states.size());
blend_state.render_target_states.each_fwd([&](const RenderTargetBlendState& render_target_blend) {
VkPipelineColorBlendAttachmentState color_blend_attachment;
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = render_target_blend.enable ? VK_TRUE : VK_FALSE;
color_blend_attachment.srcColorBlendFactor = to_blend_factor(render_target_blend.src_color_factor);
color_blend_attachment.dstColorBlendFactor = to_blend_factor(render_target_blend.dst_color_factor);
color_blend_attachment.colorBlendOp = to_blend_op(render_target_blend.color_op);
color_blend_attachment.srcAlphaBlendFactor = to_blend_factor(render_target_blend.src_alpha_factor);
color_blend_attachment.dstAlphaBlendFactor = to_blend_factor(render_target_blend.dst_alpha_factor);
color_blend_attachment.alphaBlendOp = to_blend_op(render_target_blend.alpha_op);
attachment_states.emplace_back(color_blend_attachment);
});
color_blend_create_info.attachmentCount = static_cast<uint32_t>(attachment_states.size());
color_blend_create_info.pAttachments = attachment_states.data();
color_blend_create_info.blendConstants[0] = blend_state.blend_constants.r;
color_blend_create_info.blendConstants[1] = blend_state.blend_constants.g;
color_blend_create_info.blendConstants[2] = blend_state.blend_constants.b;
color_blend_create_info.blendConstants[3] = blend_state.blend_constants.a;
} else {
attachment_states.reserve(state.color_attachments.size());
state.color_attachments.each_fwd([&](const renderpack::TextureAttachmentInfo& /* attachment_info */) {
VkPipelineColorBlendAttachmentState color_blend_attachment{};
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = VK_FALSE;
attachment_states.emplace_back(color_blend_attachment);
});
color_blend_create_info.attachmentCount = static_cast<uint32_t>(attachment_states.size());
color_blend_create_info.pAttachments = attachment_states.data();
}
rx::vector<VkDynamicState> dynamic_states;
if(state.enable_scissor_test) {
dynamic_states.emplace_back(VK_DYNAMIC_STATE_SCISSOR);
}
VkPipelineDynamicStateCreateInfo dynamic_state_create_info = {};
dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state_create_info.dynamicStateCount = static_cast<uint32_t>(dynamic_states.size());
dynamic_state_create_info.pDynamicStates = dynamic_states.data();
VkGraphicsPipelineCreateInfo pipeline_create_info = {};
pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_create_info.pNext = nullptr;
pipeline_create_info.flags = 0;
pipeline_create_info.stageCount = static_cast<uint32_t>(shader_stages.size());
pipeline_create_info.pStages = shader_stages.data();
pipeline_create_info.pVertexInputState = &vertex_input_state_create_info;
pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
pipeline_create_info.pViewportState = &viewport_state_create_info;
pipeline_create_info.pRasterizationState = &rasterizer_create_info;
pipeline_create_info.pMultisampleState = &multisample_create_info;
pipeline_create_info.pDepthStencilState = &depth_stencil_create_info;
pipeline_create_info.pColorBlendState = &color_blend_create_info;
pipeline_create_info.pDynamicState = &dynamic_state_create_info;
pipeline_create_info.layout = standard_pipeline_layout;
pipeline_create_info.renderPass = renderpass;
pipeline_create_info.subpass = 0;
pipeline_create_info.basePipelineIndex = -1;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
const auto result = vkCreateGraphicsPipelines(device, nullptr, 1, &pipeline_create_info, &vk_alloc, &vk_pipeline.pipeline);
if(result != VK_SUCCESS) {
return ntl::Result<VulkanPipeline>{MAKE_ERROR("Could not compile pipeline %s", state.name)};
}
// TODO: Figure out how to have bespoke pipeline layouts for things like post-processing
vk_pipeline.layout = standard_pipeline_layout;
if(settings.settings.debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_PIPELINE;
object_name.objectHandle = reinterpret_cast<uint64_t>(vk_pipeline.pipeline);
object_name.pObjectName = state.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return ntl::Result{vk_pipeline};
}
RhiBuffer* VulkanRenderDevice::create_buffer(const RhiBufferCreateInfo& info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_buffer");
auto* buffer = allocator.create<VulkanBuffer>();
VkBufferCreateInfo vk_create_info = {};
vk_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vk_create_info.size = info.size.b_count();
vk_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo vma_alloc{};
switch(info.buffer_usage) {
case BufferUsage::UniformBuffer: {
if(info.size < gpu.props.limits.maxUniformBufferRange) {
vk_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
} else {
vk_create_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
}
vma_alloc.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
} break;
case BufferUsage::IndexBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_GPU_ONLY;
} break;
case BufferUsage::VertexBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_GPU_ONLY;
} break;
case BufferUsage::StagingBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
vma_alloc.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_CPU_ONLY;
} break;
}
const auto result = vmaCreateBuffer(vma,
&vk_create_info,
&vma_alloc,
&buffer->buffer,
&buffer->allocation,
&buffer->allocation_info);
if(result == VK_SUCCESS) {
buffer->size = info.size;
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_BUFFER;
object_name.objectHandle = reinterpret_cast<uint64_t>(buffer->buffer);
object_name.pObjectName = info.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return buffer;
} else {
logger->error("Could not create buffer %s: %s", info.name, to_string(result));
return nullptr;
}
}
void VulkanRenderDevice::write_data_to_buffer(const void* data, const Bytes num_bytes, const RhiBuffer* buffer) {
MTR_SCOPE("VulkanRenderDevice", "write_data_to_buffer");
const auto* vulkan_buffer = static_cast<const VulkanBuffer*>(buffer);
memcpy(vulkan_buffer->allocation_info.pMappedData, data, num_bytes.b_count());
}
RhiSampler* VulkanRenderDevice::create_sampler(const RhiSamplerCreateInfo& create_info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_sampler");
auto* sampler = allocator.create<VulkanSampler>();
VkSamplerCreateInfo vk_create_info = {};
vk_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
vk_create_info.minFilter = to_vk_filter(create_info.min_filter);
vk_create_info.magFilter = to_vk_filter(create_info.mag_filter);
vk_create_info.addressModeU = to_vk_address_mode(create_info.x_wrap_mode);
vk_create_info.addressModeV = to_vk_address_mode(create_info.y_wrap_mode);
vk_create_info.addressModeW = to_vk_address_mode(create_info.z_wrap_mode);
vk_create_info.mipLodBias = create_info.mip_bias;
vk_create_info.anisotropyEnable = create_info.enable_anisotropy ? VK_TRUE : VK_FALSE;
vk_create_info.maxAnisotropy = create_info.max_anisotropy;
vk_create_info.minLod = create_info.min_lod;
vk_create_info.maxLod = create_info.max_lod;
const VkAllocationCallbacks& alloc_calls = wrap_allocator(allocator);
vkCreateSampler(device, &vk_create_info, &alloc_calls, &sampler->sampler);
return sampler;
}
RhiImage* VulkanRenderDevice::create_image(const renderpack::TextureCreateInfo& info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_image");
auto* image = allocator.create<VulkanImage>();
image->is_dynamic = true;
image->type = ResourceType::Image;
const VkFormat format = to_vk_format(info.format.pixel_format);
// In Nova, images all have a dedicated allocation
// This may or may not change depending on performance data, but given Nova's atlas-centric design I don't think it'll change much
const auto image_pixel_size = info.format.get_size_in_pixels(swapchain_size);
VmaAllocationCreateInfo vma_info = {};
vma_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkImageCreateInfo image_create_info = {};
image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_create_info.imageType = VK_IMAGE_TYPE_2D;
image_create_info.format = format;
image_create_info.extent.width = image_pixel_size.x;
image_create_info.extent.height = image_pixel_size.y;
image_create_info.extent.depth = 1;
image_create_info.mipLevels = 1;
image_create_info.arrayLayers = 1;
image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image->is_depth_tex = true;
}
if(info.usage == renderpack::ImageUsage::SampledImage) {
image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
} else {
// If the image isn't a sampled image, it's a render target
// Render targets get dedicated allocations
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
} else {
image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
vma_info.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
image_create_info.queueFamilyIndexCount = 1;
image_create_info.pQueueFamilyIndices = &graphics_family_index;
image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
const auto result = vmaCreateImage(vma, &image_create_info, &vma_info, &image->image, &image->allocation, nullptr);
if(result == VK_SUCCESS) {
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_IMAGE;
object_name.objectHandle = reinterpret_cast<uint64_t>(image->image);
object_name.pObjectName = info.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
VkImageViewCreateInfo image_view_create_info = {};
image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_create_info.image = image->image;
image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_create_info.format = image_create_info.format;
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
} else {
image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
image_view_create_info.subresourceRange.baseArrayLayer = 0;
image_view_create_info.subresourceRange.layerCount = 1;
image_view_create_info.subresourceRange.baseMipLevel = 0;
image_view_create_info.subresourceRange.levelCount = 1;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateImageView(device, &image_view_create_info, &vk_alloc, &image->image_view);
return image;
} else {
logger->error("Could not create image %s: %s", info.name, to_string(result));
return nullptr;
}
}
RhiSemaphore* VulkanRenderDevice::create_semaphore(rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_semaphore");
auto* semaphore = allocator.create<VulkanSemaphore>();
VkSemaphoreCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateSemaphore(device, &create_info, &vk_alloc, &semaphore->semaphore);
return semaphore;
}
rx::vector<RhiSemaphore*> VulkanRenderDevice::create_semaphores(const uint32_t num_semaphores, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_semaphores");
auto semaphores = rx::vector<RhiSemaphore*>{&allocator};
semaphores.reserve(num_semaphores);
for(uint32_t i = 0; i < num_semaphores; i++) {
semaphores.emplace_back(create_semaphore(allocator));
}
return semaphores;
}
RhiFence* VulkanRenderDevice::create_fence(const bool signaled, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_fence");
auto* fence = allocator.create<VulkanFence>();
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if(signaled) {
fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
}
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateFence(device, &fence_create_info, &vk_alloc, &fence->fence);
return fence;
}
rx::vector<RhiFence*> VulkanRenderDevice::create_fences(const uint32_t num_fences,
const bool signaled,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_fences");
rx::vector<RhiFence*> fences{&allocator};
fences.reserve(num_fences);
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if(signaled) {
fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
}
for(uint32_t i = 0; i < num_fences; i++) {
auto* fence = allocator.create<VulkanFence>();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateFence(device, &fence_create_info, &vk_alloc, &fence->fence);
fences.push_back(fence);
}
return fences;
}
void VulkanRenderDevice::wait_for_fences(const rx::vector<RhiFence*> fences) {
MTR_SCOPE("VulkanRenderDevice", "wait_for_fences");
rx::vector<VkFence> vk_fences{&internal_allocator};
vk_fences.reserve(fences.size());
fences.each_fwd([&](const RhiFence* fence) {
const auto* vk_fence = static_cast<const VulkanFence*>(fence);
vk_fences.push_back(vk_fence->fence);
});
const auto result = vkWaitForFences(device,
static_cast<uint32_t>(vk_fences.size()),
vk_fences.data(),
VK_TRUE,
std::numeric_limits<uint64_t>::max());
if(settings->debug.enabled) {
if(result != VK_SUCCESS) {
logger->error("Could not wait for fences. %s (error code %x)", to_string(result), result);
BREAK_ON_DEVICE_LOST(result);
}
}
}
void VulkanRenderDevice::reset_fences(const rx::vector<RhiFence*>& fences) {
MTR_SCOPE("VulkanRenderDevice", "reset_fences");
rx::vector<VkFence> vk_fences{&internal_allocator};
vk_fences.reserve(fences.size());
fences.each_fwd([&](const RhiFence* fence) {
const auto* vk_fence = static_cast<const VulkanFence*>(fence);
vk_fences.push_back(vk_fence->fence);
});
vkResetFences(device, static_cast<uint32_t>(fences.size()), vk_fences.data());
}
void VulkanRenderDevice::destroy_renderpass(RhiRenderpass* pass, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_renderpasses");
auto* vk_renderpass = static_cast<VulkanRenderpass*>(pass);
vkDestroyRenderPass(device, vk_renderpass->pass, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pass));
}
void VulkanRenderDevice::destroy_framebuffer(RhiFramebuffer* framebuffer, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_framebuffer");
const auto* vk_framebuffer = static_cast<const VulkanFramebuffer*>(framebuffer);
vkDestroyFramebuffer(device, vk_framebuffer->framebuffer, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(framebuffer));
}
void VulkanRenderDevice::destroy_pipeline_interface(RhiPipelineInterface* pipeline_interface, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_pipeline_interface");
auto* vk_interface = static_cast<VulkanPipelineInterface*>(pipeline_interface);
vkDestroyRenderPass(device, vk_interface->pass, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pipeline_interface));
}
void VulkanRenderDevice::destroy_pipeline(VulkanPipeline* pipeline, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_pipeline");
vkDestroyPipeline(device, pipeline->pipeline, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pipeline));
}
void VulkanRenderDevice::destroy_texture(RhiImage* resource, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_texture");
auto* vk_image = static_cast<VulkanImage*>(resource);
vmaDestroyImage(vma, vk_image->image, vk_image->allocation);
allocator.deallocate(reinterpret_cast<rx_byte*>(resource));
}
void VulkanRenderDevice::destroy_semaphores(rx::vector<RhiSemaphore*>& semaphores, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_semaphores");
semaphores.each_fwd([&](RhiSemaphore* semaphore) {
auto* vk_semaphore = static_cast<VulkanSemaphore*>(semaphore);
vkDestroySemaphore(device, vk_semaphore->semaphore, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(semaphore));
});
}
void VulkanRenderDevice::destroy_fences(const rx::vector<RhiFence*>& fences, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_fences");
fences.each_fwd([&](RhiFence* fence) {
auto* vk_fence = static_cast<VulkanFence*>(fence);
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkDestroyFence(device, vk_fence->fence, &vk_alloc);
allocator.deallocate(reinterpret_cast<rx_byte*>(fence));
});
}
RhiRenderCommandList* VulkanRenderDevice::create_command_list(const uint32_t thread_idx,
const QueueType needed_queue_type,
const RhiRenderCommandList::Level level,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_command_list");
const uint32_t queue_family_index = get_queue_family_index(needed_queue_type);
const VkCommandPool pool = *command_pools_by_thread_idx[thread_idx].find(queue_family_index);
VkCommandBufferAllocateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
create_info.commandPool = pool;
create_info.level = to_vk_command_buffer_level(level);
create_info.commandBufferCount = 1;
VkCommandBuffer new_buffer;
vkAllocateCommandBuffers(device, &create_info, &new_buffer);
auto* list = allocator.create<VulkanRenderCommandList>(new_buffer, *this, allocator);
return list;
}
void VulkanRenderDevice::submit_command_list(RhiRenderCommandList* cmds,
const QueueType queue,
RhiFence* fence_to_signal,
const rx::vector<RhiSemaphore*>& wait_semaphores,
const rx::vector<RhiSemaphore*>& signal_semaphores) {
MTR_SCOPE("VulkanRenderDevice", "submit_command_list");
auto* vk_list = static_cast<VulkanRenderCommandList*>(cmds);
vkEndCommandBuffer(vk_list->cmds);
VkQueue queue_to_submit_to;
switch(queue) {
case QueueType::Graphics:
queue_to_submit_to = graphics_queue;
break;
case QueueType::Transfer:
queue_to_submit_to = copy_queue;
break;
case QueueType::AsyncCompute:
queue_to_submit_to = compute_queue;
break;
default:
queue_to_submit_to = graphics_queue;
}
rx::vector<VkSemaphore> vk_wait_semaphores{&internal_allocator};
vk_wait_semaphores.reserve(wait_semaphores.size());
wait_semaphores.each_fwd([&](const RhiSemaphore* semaphore) {
const auto* vk_semaphore = static_cast<const VulkanSemaphore*>(semaphore);
vk_wait_semaphores.push_back(vk_semaphore->semaphore);
});
rx::vector<VkSemaphore> vk_signal_semaphores{&internal_allocator};
vk_signal_semaphores.reserve(signal_semaphores.size());
signal_semaphores.each_fwd([&](const RhiSemaphore* semaphore) {
const auto* vk_semaphore = static_cast<const VulkanSemaphore*>(semaphore);
vk_signal_semaphores.push_back(vk_semaphore->semaphore);
});
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.waitSemaphoreCount = static_cast<uint32_t>(vk_wait_semaphores.size());
submit_info.pWaitSemaphores = vk_wait_semaphores.data();
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &vk_list->cmds;
submit_info.signalSemaphoreCount = static_cast<uint32_t>(vk_signal_semaphores.size());
submit_info.pSignalSemaphores = vk_signal_semaphores.data();
const auto vk_signal_fence = [&]() -> vk::Fence {
if(fence_to_signal) {
return static_cast<const VulkanFence*>(fence_to_signal)->fence;
} else {
return get_next_submission_fence();
}
}();
const auto result = vkQueueSubmit(queue_to_submit_to, 1, &submit_info, vk_signal_fence);
fenced_tasks.emplace_back(vk_signal_fence, [&] {
vk_list->cleanup_resources();
submission_fences.emplace_back(vk_signal_fence);
});
if(settings->debug.enabled) {
if(result != VK_SUCCESS) {
logger->error("Could not submit command list: %s", to_string(result));
BREAK_ON_DEVICE_LOST(result);
}
}
}
void VulkanRenderDevice::end_frame(FrameContext& /* ctx */) {
MTR_SCOPE("VulkanRenderEngine", "end_frame");
// Intentionally copying the vector
auto cur_tasks = fenced_tasks;
// Clear out the list of tasks. We've copied the tasks to the new vector so it's fine, and we'll add back in the tasks that aren't
// ready to run
fenced_tasks.clear();
cur_tasks.each_fwd([&](const FencedTask& task) {
if(device.getFenceStatus(task.fence) == vk::Result::eSuccess) {
task();
} else {
fenced_tasks.push_back(task);
}
});
}
uint32_t VulkanRenderDevice::get_queue_family_index(const QueueType type) const {
switch(type) {
case QueueType::Graphics:
return graphics_family_index;
case QueueType::Transfer:
return transfer_family_index;
case QueueType::AsyncCompute:
return compute_family_index;
default:
RX_ASSERT(false, "Unknown queue type %u", static_cast<uint32_t>(type));
return 9999; // I have to return _something_ or Visual Studio gets mad
}
}
void VulkanRenderDevice::create_surface() {
MTR_SCOPE("VulkanRenderDevice", "create_surface");
#ifdef NOVA_LINUX
VkXlibSurfaceCreateInfoKHR x_surface_create_info;
x_surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
x_surface_create_info.pNext = nullptr;
x_surface_create_info.flags = 0;
x_surface_create_info.dpy = window.get_display();
x_surface_create_info.window = window.get_window_handle();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateXlibSurfaceKHR(instance, &x_surface_create_info, &vk_alloc, &surface));
#elif defined(NOVA_WINDOWS)
VkWin32SurfaceCreateInfoKHR win32_surface_create = {};
win32_surface_create.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
win32_surface_create.hwnd = window.get_window_handle();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateWin32SurfaceKHR(instance, &win32_surface_create, &vk_alloc, &surface));
#else
#error Unsuported window system
#endif
}
void VulkanRenderDevice::create_instance() {
MTR_SCOPE("VulkanRenderDevice", "create_instance");
const auto& version = settings.settings.vulkan.application_version;
VkApplicationInfo application_info;
application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
application_info.pNext = nullptr;
application_info.pApplicationName = settings.settings.vulkan.application_name;
application_info.applicationVersion = VK_MAKE_VERSION(version.major, version.minor, version.patch);
application_info.pEngineName = "Nova Renderer 0.9";
application_info.apiVersion = VK_API_VERSION_1_2;
VkInstanceCreateInfo create_info;
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pNext = nullptr;
create_info.flags = 0;
create_info.pApplicationInfo = &application_info;
if(settings.settings.debug.enabled && settings.settings.debug.enable_validation_layers) {
enabled_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
}
create_info.enabledLayerCount = static_cast<uint32_t>(enabled_layer_names.size());
create_info.ppEnabledLayerNames = enabled_layer_names.data();
rx::vector<const char*> enabled_extension_names{&internal_allocator};
enabled_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
enabled_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
#ifdef NOVA_LINUX
enabled_extension_names.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
#elif defined(NOVA_WINDOWS)
enabled_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#else
#error Unsupported Operating system
#endif
rx::vector<VkValidationFeatureEnableEXT> enabled_validation_features;
if(settings.settings.debug.enabled) {
enabled_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
enabled_extension_names.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT);
if(settings.settings.debug.enable_gpu_based_validation) {
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT);
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT);
}
}
create_info.enabledExtensionCount = static_cast<uint32_t>(enabled_extension_names.size());
create_info.ppEnabledExtensionNames = enabled_extension_names.data();
VkValidationFeaturesEXT validation_features = {};
validation_features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
validation_features.enabledValidationFeatureCount = static_cast<uint32_t>(enabled_validation_features.size());
validation_features.pEnabledValidationFeatures = enabled_validation_features.data();
create_info.pNext = &validation_features;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
{
MTR_SCOPE("VulkanRenderDevice", "vkCreateInstance");
NOVA_CHECK_RESULT(vkCreateInstance(&create_info, &vk_alloc, &instance));
}
}
void VulkanRenderDevice::enable_debug_output() {
MTR_SCOPE("VulkanRenderDevice", "enable_debug_output");
vkCreateDebugUtilsMessengerEXT = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(
vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"));
vkDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
VkDebugUtilsMessengerCreateInfoEXT debug_create_info = {};
debug_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debug_create_info.pNext = nullptr;
debug_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debug_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debug_create_info.pfnUserCallback = reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(&debug_report_callback);
debug_create_info.pUserData = this;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateDebugUtilsMessengerEXT(instance, &debug_create_info, &vk_alloc, &debug_callback));
}
void VulkanRenderDevice::save_device_info() {
MTR_SCOPE("VulkanRenderDevice", "save_device_info");
switch(gpu.props.vendorID) {
case AMD_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Amd;
break;
case INTEL_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Intel;
break;
case NVIDIA_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Nvidia;
break;
default:
info.architecture = DeviceArchitecture::Unknown;
}
vk_info.max_uniform_buffer_size = gpu.props.limits.maxUniformBufferRange;
info.max_texture_size = gpu.props.limits.maxImageDimension2D;
// TODO: Something smarter when Intel releases discreet GPUS
// TODO: Handle integrated AMD GPUs
info.is_uma = info.architecture == DeviceArchitecture::Intel;
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(gpu.phys_device, nullptr, &extension_count, nullptr);
rx::vector<VkExtensionProperties> available_extensions{&internal_allocator, extension_count};
vkEnumerateDeviceExtensionProperties(gpu.phys_device, nullptr, &extension_count, available_extensions.data());
const auto extension_name_matcher = [](const char* ext_name) {
return [=](const VkExtensionProperties& ext_props) -> bool { return strcmp(ext_name, ext_props.extensionName) == 0; };
};
// TODO: Update as more GPUs support hardware raytracing
info.supports_raytracing = available_extensions.find_if(extension_name_matcher(VK_NV_RAY_TRACING_EXTENSION_NAME)) !=
rx::vector<VkExtensionProperties>::k_npos;
// TODO: Update as more GPUs support mesh shaders
info.supports_mesh_shaders = available_extensions.find_if(extension_name_matcher(VK_NV_MESH_SHADER_EXTENSION_NAME));
}
void VulkanRenderDevice::initialize_vma() {
MTR_SCOPE("VulkanRenderDevice", "initialize_vma");
VkAllocationCallbacks callbacks = vk_internal_allocator;
VmaAllocatorCreateInfo create_info{};
create_info.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
create_info.physicalDevice = gpu.phys_device;
create_info.device = device;
create_info.pAllocationCallbacks = &callbacks;
create_info.instance = instance;
const auto result = vmaCreateAllocator(&create_info, &vma);
if(result != VK_SUCCESS) {
logger->error("Could not initialize VMA: %s", to_string(result));
}
}
void VulkanRenderDevice::create_device_and_queues() {
MTR_SCOPE("VulkanRenderDevice", "create_device_and_queues");
rx::vector<char*> device_extensions{&internal_allocator};
device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
uint32_t device_count;
NOVA_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &device_count, nullptr));
auto physical_devices = rx::vector<VkPhysicalDevice>{&internal_allocator, device_count};
NOVA_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &device_count, physical_devices.data()));
uint32_t graphics_family_idx = 0xFFFFFFFF;
uint32_t compute_family_idx = 0xFFFFFFFF;
uint32_t copy_family_idx = 0xFFFFFFFF;
{
MTR_SCOPE("VulkanNovaRenderer", "Select Physical Device");
for(uint32_t device_idx = 0; device_idx < device_count; device_idx++) {
graphics_family_idx = 0xFFFFFFFF;
VkPhysicalDevice current_device = physical_devices[device_idx];
vkGetPhysicalDeviceProperties(current_device, &gpu.props);
const bool is_intel_gpu = gpu.props.vendorID == INTEL_PCI_VENDOR_ID;
const bool more_gpus_available = device_count - 1 > device_idx;
if(is_intel_gpu && more_gpus_available) {
// Intel GPU _probably_ isn't as powerful as a discreet GPU, and if there's more than one GPU then the other one(s) are
// _probably_ discreet GPUs, so let's not use the Intel GPU and instead use the discreet GPU
// TODO: Make a local device for the integrated GPU when we figure out multi-GPU
// TODO: Rework this code when Intel releases discreet GPUs
continue;
}
const auto supports_extensions = does_device_support_extensions(current_device, device_extensions);
if(!supports_extensions) {
continue;
}
uint32_t queue_family_count;
vkGetPhysicalDeviceQueueFamilyProperties(current_device, &queue_family_count, nullptr);
gpu.queue_family_props.resize(queue_family_count);
vkGetPhysicalDeviceQueueFamilyProperties(current_device, &queue_family_count, gpu.queue_family_props.data());
for(uint32_t queue_idx = 0; queue_idx < queue_family_count; queue_idx++) {
const VkQueueFamilyProperties current_properties = gpu.queue_family_props[queue_idx];
if(current_properties.queueCount < 1) {
continue;
}
VkBool32 supports_present = VK_FALSE;
NOVA_CHECK_RESULT(vkGetPhysicalDeviceSurfaceSupportKHR(current_device, queue_idx, surface, &supports_present));
const VkQueueFlags supports_graphics = current_properties.queueFlags & VK_QUEUE_GRAPHICS_BIT;
if((supports_graphics != 0U) && supports_present == VK_TRUE && graphics_family_idx == 0xFFFFFFFF) {
graphics_family_idx = queue_idx;
}
const VkQueueFlags supports_compute = current_properties.queueFlags & VK_QUEUE_COMPUTE_BIT;
if((supports_compute != 0U) && compute_family_idx == 0xFFFFFFFF) {
compute_family_idx = queue_idx;
}
const VkQueueFlags supports_copy = current_properties.queueFlags & VK_QUEUE_TRANSFER_BIT;
if((supports_copy != 0U) && copy_family_idx == 0xFFFFFFFF) {
copy_family_idx = queue_idx;
}
}
if(graphics_family_idx != 0xFFFFFFFF) {
logger->info("Selected GPU %s", gpu.props.deviceName);
gpu.phys_device = current_device;
break;
}
}
}
if(gpu.phys_device == nullptr) {
logger->error("Failed to find good GPU");
// TODO: Message the user that GPU selection failed
return;
}
PROFILE_VOID_EXPR(vkGetPhysicalDeviceFeatures(gpu.phys_device, &gpu.supported_features),
VulkanRenderDevice,
vkGetPhysicalDeviceFeatures);
PROFILE_VOID_EXPR(vkGetPhysicalDeviceMemoryProperties(gpu.phys_device, &gpu.memory_properties),
VulkanRenderDevice,
vkGetPhysicalDeviceMemoryProperties);
const float priority = 1.0;
VkDeviceQueueCreateInfo graphics_queue_create_info{};
graphics_queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
graphics_queue_create_info.pNext = nullptr;
graphics_queue_create_info.flags = 0;
graphics_queue_create_info.queueCount = 1;
graphics_queue_create_info.queueFamilyIndex = graphics_family_idx;
graphics_queue_create_info.pQueuePriorities = &priority;
rx::vector<VkDeviceQueueCreateInfo> queue_create_infos{&internal_allocator};
queue_create_infos.push_back(graphics_queue_create_info);
VkPhysicalDeviceFeatures physical_device_features{};
physical_device_features.geometryShader = VK_TRUE;
physical_device_features.tessellationShader = VK_TRUE;
physical_device_features.samplerAnisotropy = VK_TRUE;
physical_device_features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
if(settings->debug.enable_gpu_based_validation) {
physical_device_features.fragmentStoresAndAtomics = VK_TRUE;
physical_device_features.vertexPipelineStoresAndAtomics = VK_TRUE;
}
VkDeviceCreateInfo device_create_info{};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = nullptr;
device_create_info.flags = 0;
device_create_info.queueCreateInfoCount = static_cast<uint32_t>(queue_create_infos.size());
device_create_info.pQueueCreateInfos = queue_create_infos.data();
device_create_info.pEnabledFeatures = &physical_device_features;
device_create_info.enabledExtensionCount = static_cast<uint32_t>(device_extensions.size());
device_create_info.ppEnabledExtensionNames = device_extensions.data();
device_create_info.enabledLayerCount = static_cast<uint32_t>(enabled_layer_names.size());
if(!enabled_layer_names.is_empty()) {
device_create_info.ppEnabledLayerNames = enabled_layer_names.data();
}
// Set up descriptor indexing
// Currently Nova only cares about indexing for texture descriptors
VkPhysicalDeviceDescriptorIndexingFeatures descriptor_indexing_features = {};
descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES;
descriptor_indexing_features.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
descriptor_indexing_features.runtimeDescriptorArray = true;
descriptor_indexing_features.descriptorBindingVariableDescriptorCount = VK_TRUE;
descriptor_indexing_features.descriptorBindingPartiallyBound = VK_TRUE;
descriptor_indexing_features.descriptorBindingSampledImageUpdateAfterBind = VK_TRUE;
device_create_info.pNext = &descriptor_indexing_features;
const auto dev_12_features = vk::PhysicalDeviceVulkan12Features()
.setDescriptorIndexing(true)
.setShaderSampledImageArrayNonUniformIndexing(true)
.setRuntimeDescriptorArray(true)
.setDescriptorBindingVariableDescriptorCount(true)
.setDescriptorBindingPartiallyBound(true)
.setDescriptorBindingSampledImageUpdateAfterBind(true);
device_create_info.pNext = &dev_12_features;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
VkDevice vk_device;
const auto res = PROFILE_RET_EXPR(vkCreateDevice(gpu.phys_device, &device_create_info, &vk_alloc, &vk_device),
VulkanRenderEngine,
vkCreateDevice);
if(res != VK_SUCCESS) {
// logger();
}
device = vk_device;
graphics_family_index = graphics_family_idx;
vkGetDeviceQueue(device, graphics_family_idx, 0, &graphics_queue);
compute_family_index = compute_family_idx;
vkGetDeviceQueue(device, compute_family_idx, 0, &compute_queue);
transfer_family_index = copy_family_idx;
vkGetDeviceQueue(device, copy_family_idx, 0, ©_queue);
}
bool VulkanRenderDevice::does_device_support_extensions(VkPhysicalDevice device, const rx::vector<char*>& required_device_extensions) {
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, nullptr);
rx::vector<VkExtensionProperties> available(extension_count);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, available.data());
rx::set<rx::string> required{&internal_allocator};
required_device_extensions.each_fwd([&](const char* extension) { required.insert(extension); });
available.each_fwd(
[&](const VkExtensionProperties& extension) { required.erase(static_cast<const char*>(extension.extensionName)); });
if(!required.is_empty()) {
std::stringstream ss;
required.each([&](const rx::string& extension) { ss << extension.data() << ", "; });
logger->warning("Device does not support these required extensions: %s", ss.str().c_str());
}
const auto device_supports_required_extensions = required.is_empty();
return device_supports_required_extensions;
}
void VulkanRenderDevice::create_swapchain() {
MTR_SCOPE("VulkanRenderDevice", "create_swapchain");
// Check what formats our rendering supports, and create a swapchain with one of those formats
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu.phys_device, surface, &gpu.surface_capabilities);
uint32_t num_surface_formats;
vkGetPhysicalDeviceSurfaceFormatsKHR(gpu.phys_device, surface, &num_surface_formats, nullptr);
gpu.surface_formats.resize(num_surface_formats);
vkGetPhysicalDeviceSurfaceFormatsKHR(gpu.phys_device, surface, &num_surface_formats, gpu.surface_formats.data());
uint32_t num_surface_present_modes;
vkGetPhysicalDeviceSurfacePresentModesKHR(gpu.phys_device, surface, &num_surface_present_modes, nullptr);
rx::vector<VkPresentModeKHR> present_modes{&internal_allocator, num_surface_present_modes};
vkGetPhysicalDeviceSurfacePresentModesKHR(gpu.phys_device, surface, &num_surface_present_modes, present_modes.data());
swapchain = internal_allocator.create<VulkanSwapchain>(settings->max_in_flight_frames,
this,
window.get_framebuffer_size(),
present_modes);
swapchain_size = window.get_framebuffer_size();
}
void VulkanRenderDevice::create_per_thread_command_pools() {
MTR_SCOPE("VulkanRenderDevice", "create_per_thread_command_pools");
const uint32_t num_threads = 1; // TODO: Make this real
command_pools_by_thread_idx.reserve(num_threads);
for(uint32_t i = 0; i < num_threads; i++) {
command_pools_by_thread_idx.push_back(make_new_command_pools());
}
}
void VulkanRenderDevice::create_standard_pipeline_layout() {
standard_push_constants = rx::array{
// Camera and Material index
vk::PushConstantRange().setStageFlags(vk::ShaderStageFlagBits::eAll).setOffset(0).setSize(sizeof(uint32_t) * 2)};
const auto flags_per_binding = rx::array{vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlagBits::eUpdateAfterBind |
vk::DescriptorBindingFlagBits::eVariableDescriptorCount |
vk::DescriptorBindingFlagBits::ePartiallyBound};
const auto set_flags = vk::DescriptorSetLayoutBindingFlagsCreateInfo()
.setBindingCount(flags_per_binding.size())
.setPBindingFlags(flags_per_binding.data());
const auto camera_buffer_descriptor_type = (MAX_NUM_CAMERAS * sizeof(CameraUboData)) < gpu.props.limits.maxUniformBufferRange ?
vk::DescriptorType::eUniformBuffer :
vk::DescriptorType::eStorageBuffer;
const auto material_buffer_descriptor_type = MATERIAL_BUFFER_SIZE.b_count() < gpu.props.limits.maxUniformBufferRange ?
vk::DescriptorType::eUniformBuffer :
vk::DescriptorType::eStorageBuffer;
// Binding for the array of material parameter buffers. Nova uses a variable-length, partially-bound
const rx::vector<vk::DescriptorSetLayoutBinding> bindings = rx::array{// Camera data buffer
vk::DescriptorSetLayoutBinding()
.setBinding(0)
.setDescriptorType(camera_buffer_descriptor_type)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Material data buffer
vk::DescriptorSetLayoutBinding()
.setBinding(1)
.setDescriptorType(material_buffer_descriptor_type)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Point sampler
vk::DescriptorSetLayoutBinding()
.setBinding(2)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Bilinear sampler
vk::DescriptorSetLayoutBinding()
.setBinding(3)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Trilinear sampler
vk::DescriptorSetLayoutBinding()
.setBinding(4)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Textures array
vk::DescriptorSetLayoutBinding()
.setBinding(5)
.setDescriptorType(vk::DescriptorType::eSampledImage)
.setDescriptorCount(MAX_NUM_TEXTURES)
.setStageFlags(vk::ShaderStageFlagBits::eAll)};
const auto dsl_layout_create = vk::DescriptorSetLayoutCreateInfo()
.setFlags(vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool)
.setBindingCount(static_cast<uint32_t>(bindings.size()))
.setPBindings(bindings.data())
.setPNext(&set_flags);
device.createDescriptorSetLayout(&dsl_layout_create, &vk_internal_allocator, &standard_set_layout);
const auto pipeline_layout_create = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(1)
.setPSetLayouts(&standard_set_layout)
.setPushConstantRangeCount(static_cast<uint32_t>(standard_push_constants.size()))
.setPPushConstantRanges(standard_push_constants.data());
device.createPipelineLayout(&pipeline_layout_create, &vk_internal_allocator, &standard_pipeline_layout);
auto* pool = create_descriptor_pool(rx::array{rx::pair{DescriptorType::StorageBuffer, 5_u32 * 1024},
rx::pair{DescriptorType::UniformBuffer, 5_u32 * 1024},
rx::pair{DescriptorType::Texture, MAX_NUM_TEXTURES * 1024},
rx::pair{DescriptorType::Sampler, 3_u32 * 1024}},
internal_allocator);
standard_descriptor_set_pool = rx::ptr<VulkanDescriptorPool>{&internal_allocator, static_cast<VulkanDescriptorPool*>(pool)};
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT pipeline_layout_name = {};
pipeline_layout_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
pipeline_layout_name.objectType = VK_OBJECT_TYPE_PIPELINE_LAYOUT;
pipeline_layout_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkPipelineLayout>(standard_pipeline_layout));
pipeline_layout_name.pObjectName = "Standard Pipeline Layout";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &pipeline_layout_name));
VkDebugUtilsObjectNameInfoEXT descriptor_pool_name = {};
descriptor_pool_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
descriptor_pool_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_POOL;
descriptor_pool_name.objectHandle = reinterpret_cast<uint64_t>(
static_cast<VkDescriptorPool>(standard_descriptor_set_pool->descriptor_pool));
descriptor_pool_name.pObjectName = "Standard Descriptor Set Pool";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &descriptor_pool_name));
VkDebugUtilsObjectNameInfoEXT descriptor_set_layout_name = {};
descriptor_set_layout_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
descriptor_set_layout_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT;
descriptor_set_layout_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkDescriptorSetLayout>(standard_set_layout));
descriptor_set_layout_name.pObjectName = "Standard descriptor set layout";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &descriptor_set_layout_name));
}
}
rx::map<uint32_t, VkCommandPool> VulkanRenderDevice::make_new_command_pools() const {
MTR_SCOPE("VulkanRenderDevice", "make_new_command_pools");
rx::vector<uint32_t> queue_indices{&internal_allocator};
queue_indices.push_back(graphics_family_index);
queue_indices.push_back(transfer_family_index);
queue_indices.push_back(compute_family_index);
rx::map<uint32_t, VkCommandPool> pools_by_queue{&internal_allocator};
queue_indices.each_fwd([&](const uint32_t queue_index) {
VkCommandPoolCreateInfo command_pool_create_info;
command_pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
command_pool_create_info.pNext = nullptr;
command_pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
command_pool_create_info.queueFamilyIndex = queue_index;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
VkCommandPool command_pool;
NOVA_CHECK_RESULT(vkCreateCommandPool(device, &command_pool_create_info, &vk_alloc, &command_pool));
pools_by_queue.insert(queue_index, command_pool);
});
return pools_by_queue;
}
uint32_t VulkanRenderDevice::find_memory_type_with_flags(const uint32_t search_flags, const MemorySearchMode search_mode) const {
for(uint32_t i = 0; i < gpu.memory_properties.memoryTypeCount; i++) {
const VkMemoryType& memory_type = gpu.memory_properties.memoryTypes[i];
switch(search_mode) {
case MemorySearchMode::Exact:
if(memory_type.propertyFlags == search_flags) {
return i;
}
break;
case MemorySearchMode::Fuzzy:
if((memory_type.propertyFlags & search_flags) != 0) {
return i;
}
break;
}
}
return VK_MAX_MEMORY_TYPES;
}
rx::vector<VkDescriptorSetLayout> VulkanRenderDevice::create_descriptor_set_layouts(
const rx::map<rx::string, RhiResourceBindingDescription>& all_bindings,
rx::vector<uint32_t>& variable_descriptor_counts,
rx::memory::allocator& allocator) const {
MTR_SCOPE("VulkanRenderDevice", "create_descriptor_set_layouts");
/*
* A few tasks to accomplish:
* - Take the unordered map of descriptor sets (all_bindings) and convert it into
* VkDescriptorSetLayoutCreateInfo structs, ordering everything along the way
* -
*/
uint32_t num_sets = 0;
all_bindings.each_value([&](const RhiResourceBindingDescription& desc) {
if(desc.set >= gpu.props.limits.maxBoundDescriptorSets) {
logger->error("Descriptor set %u is out of range - your GPU only supports %u sets!",
desc.set,
gpu.props.limits.maxBoundDescriptorSets);
} else {
num_sets = rx::algorithm::max(num_sets, desc.set + 1);
}
});
variable_descriptor_counts.resize(num_sets, 0);
// Some precalculations so we know how much room we actually need
rx::vector<uint32_t> num_bindings_per_set{&allocator};
num_bindings_per_set.resize(num_sets);
all_bindings.each_value([&](const RhiResourceBindingDescription& desc) {
num_bindings_per_set[desc.set] = rx::algorithm::max(num_bindings_per_set[desc.set], desc.binding + 1);
});
rx::vector<rx::vector<VkDescriptorSetLayoutBinding>> bindings_by_set{&allocator};
rx::vector<rx::vector<VkDescriptorBindingFlags>> binding_flags_by_set{&allocator};
bindings_by_set.reserve(num_sets);
binding_flags_by_set.reserve(num_sets);
uint32_t set = 0;
num_bindings_per_set.each_fwd([&](const uint32_t num_bindings) {
// Emplace back vectors large enough to hold all the bindings we have
bindings_by_set.emplace_back(num_bindings);
binding_flags_by_set.emplace_back(num_bindings);
logger->verbose("Set %u has %u bindings", set, num_bindings);
set++;
});
all_bindings.each_value([&](const RhiResourceBindingDescription& binding) {
if(binding.set >= bindings_by_set.size()) {
logger->error("You've skipped one or more descriptor sets! Don't do that, Nova can't handle it");
return true;
}
VkDescriptorSetLayoutBinding descriptor_binding = {};
descriptor_binding.binding = binding.binding;
descriptor_binding.descriptorType = static_cast<VkDescriptorType>(to_vk_descriptor_type(binding.type));
descriptor_binding.descriptorCount = binding.count;
descriptor_binding.stageFlags = to_vk_shader_stage_flags(binding.stages);
logger->verbose("Descriptor %u.%u is type %s", binding.set, binding.binding, descriptor_type_to_string(binding.type));
if(binding.is_unbounded) {
binding_flags_by_set[binding.set][binding.binding] = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT |
VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT;
// Record the maximum number of descriptors in the variable size array in this set
variable_descriptor_counts[binding.set] = binding.count;
logger->verbose("Descriptor %u.%u is unbounded", binding.set, binding.binding);
} else {
binding_flags_by_set[binding.set][binding.binding] = 0;
}
bindings_by_set[binding.set][binding.binding] = descriptor_binding;
return true;
});
rx::vector<VkDescriptorSetLayoutCreateInfo> dsl_create_infos{&allocator};
dsl_create_infos.reserve(bindings_by_set.size());
rx::vector<VkDescriptorSetLayoutBindingFlagsCreateInfo> flag_infos{&allocator};
flag_infos.reserve(bindings_by_set.size());
// We may make bindings_by_set much larger than it needs to be is there's multiple descriptor bindings per set. Thus, only iterate
// through the sets we actually care about
bindings_by_set.each_fwd([&](const rx::vector<VkDescriptorSetLayoutBinding>& bindings) {
VkDescriptorSetLayoutCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
create_info.bindingCount = static_cast<uint32_t>(bindings.size());
create_info.pBindings = bindings.data();
const auto& flags = binding_flags_by_set[dsl_create_infos.size()];
VkDescriptorSetLayoutBindingFlagsCreateInfo binding_flags = {};
binding_flags.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO;
binding_flags.bindingCount = static_cast<uint32_t>(flags.size());
binding_flags.pBindingFlags = flags.data();
flag_infos.emplace_back(binding_flags);
create_info.pNext = &flag_infos[flag_infos.size() - 1];
dsl_create_infos.push_back(create_info);
});
rx::vector<VkDescriptorSetLayout> layouts{&allocator};
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
layouts.resize(dsl_create_infos.size());
for(size_t i = 0; i < dsl_create_infos.size(); i++) {
vkCreateDescriptorSetLayout(device, &dsl_create_infos[i], &vk_alloc, &layouts[i]);
}
return layouts;
}
VkImageView VulkanRenderDevice::image_view_for_image(const RhiImage* image) {
// TODO: This method is terrible. We shouldn't tie image views to images, we should let everything that wants
// to use the image create its own image view
const auto* vk_image = static_cast<const VulkanImage*>(image);
return vk_image->image_view;
}
VkCommandBufferLevel VulkanRenderDevice::to_vk_command_buffer_level(const RhiRenderCommandList::Level level) {
switch(level) {
case RhiRenderCommandList::Level::Primary:
return VK_COMMAND_BUFFER_LEVEL_PRIMARY;
case RhiRenderCommandList::Level::Secondary:
return VK_COMMAND_BUFFER_LEVEL_SECONDARY;
}
return VK_COMMAND_BUFFER_LEVEL_PRIMARY;
}
VulkanInputAssemblerLayout VulkanRenderDevice::get_input_assembler_setup(const rx::vector<RhiVertexField>& vertex_fields) {
rx::vector<VkVertexInputAttributeDescription> attributes;
rx::vector<VkVertexInputBindingDescription> bindings;
attributes.reserve(vertex_fields.size());
bindings.reserve(vertex_fields.size());
uint32_t vertex_size = 0;
vertex_fields.each_fwd([&](const RhiVertexField& field) { vertex_size += get_byte_size(field.format); });
uint32_t cur_binding = 0;
uint32_t byte_offset = 0;
vertex_fields.each_fwd([&](const RhiVertexField& field) {
const auto field_size = get_byte_size(field.format);
const auto attr_format = to_vk_vertex_format(field.format);
attributes.emplace_back(VkVertexInputAttributeDescription{cur_binding, 0, attr_format, byte_offset});
bindings.emplace_back(VkVertexInputBindingDescription{cur_binding, vertex_size, VK_VERTEX_INPUT_RATE_VERTEX});
cur_binding++;
byte_offset += field_size;
});
return {attributes, bindings};
}
rx::optional<VkShaderModule> VulkanRenderDevice::create_shader_module(const rx::vector<uint32_t>& spirv) const {
MTR_SCOPE("VulkanRenderDevice", "create_shader_module");
VkShaderModuleCreateInfo shader_module_create_info = {};
shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shader_module_create_info.pCode = spirv.data();
shader_module_create_info.codeSize = spirv.size() * 4;
VkShaderModule module;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
const auto result = vkCreateShaderModule(device, &shader_module_create_info, &vk_alloc, &module);
if(result == VK_SUCCESS) {
return rx::optional<VkShaderModule>(module);
} else {
logger->error("Could not create shader module: %s", to_string(result));
return rx::nullopt;
}
}
VKAPI_ATTR VkBool32 VKAPI_CALL VulkanRenderDevice::debug_report_callback(const VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
const VkDebugUtilsMessageTypeFlagsEXT message_types,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* render_device) {
rx::string type = "General";
if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0U) {
type = "Validation";
} else if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) != 0U) {
type = "Performance";
}
rx::string queue_list;
if(callback_data->queueLabelCount != 0) {
queue_list.append(" Queues: ");
for(uint32_t i = 0; i < callback_data->queueLabelCount; i++) {
queue_list.append(callback_data->pQueueLabels[i].pLabelName);
if(i != callback_data->queueLabelCount - 1) {
queue_list.append(", ");
}
}
}
rx::string command_buffer_list;
if(callback_data->cmdBufLabelCount != 0) {
command_buffer_list.append("Command Buffers: ");
for(uint32_t i = 0; i < callback_data->cmdBufLabelCount; i++) {
command_buffer_list.append(callback_data->pCmdBufLabels[i].pLabelName);
if(i != callback_data->cmdBufLabelCount - 1) {
command_buffer_list.append(", ");
}
}
}
rx::string object_list;
if(callback_data->objectCount != 0) {
object_list.append("Objects: ");
for(uint32_t i = 0; i < callback_data->objectCount; i++) {
object_list.append(to_string(callback_data->pObjects[i].objectType));
if(callback_data->pObjects[i].pObjectName != nullptr) {
object_list.append(rx::string::format(" \"%s\"", callback_data->pObjects[i].pObjectName));
}
object_list.append(rx::string::format(" (%x)", callback_data->pObjects[i].objectHandle));
if(i != callback_data->objectCount - 1) {
object_list.append(", ");
}
}
}
rx::string vk_message;
if(callback_data->pMessage != nullptr) {
vk_message.append(callback_data->pMessage);
}
const rx::string msg = rx::string::format("[%s] %s %s %s %s", type, queue_list, command_buffer_list, object_list, vk_message);
if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0) {
logger->error("%s", msg);
#ifdef NOVA_LINUX
nova_backtrace();
#endif
auto* vk_render_device = reinterpret_cast<VulkanRenderDevice*>(render_device);
if(vk_render_device->settings->debug.break_on_validation_errors) {
rx::abort("Validation error");
}
} else if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) != 0) {
// Warnings may hint at unexpected / non-spec API usage
logger->warning("%s", msg);
} else if(((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) != 0) &&
((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) == 0U)) { // No validation info!
// Informal messages that may become handy during debugging
logger->info("%s", msg);
} else if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) != 0) {
// Diagnostic info from the Vulkan loader and layers
// Usually not helpful in terms of API usage, but may help to debug layer and loader problems
logger->verbose("%s", msg);
} else if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) == 0U) { // No validation info!
// Catch-all to be super sure
logger->info("%s", msg);
}
return VK_FALSE;
}
} // namespace nova::renderer::rhi
[rhi::vk] Create resource binder
// This define MUST be before including vulkan_render_device.hpp
#define VMA_IMPLEMENTATION
#include "vulkan_render_device.hpp"
#include <sstream>
#include <minitrace.h>
#include <rx/core/abort.h>
#include <rx/core/algorithm/max.h>
#include <rx/core/log.h>
#include <rx/core/set.h>
#include <signal.h>
#include <string.h>
#include "nova_renderer/camera.hpp"
#include "nova_renderer/constants.hpp"
#include "nova_renderer/frame_context.hpp"
#include "nova_renderer/renderables.hpp"
#include "nova_renderer/rhi/pipeline_create_info.hpp"
#include "nova_renderer/window.hpp"
#include "vk_structs.hpp"
#include "vulkan_command_list.hpp"
#include "vulkan_resource_binder.hpp"
#include "vulkan_utils.hpp"
// TODO: Move window creation out of the RHI
#ifdef NOVA_LINUX
#define NOVA_VK_XLIB
#include "../../util/linux_utils.hpp"
#elif defined(NOVA_WINDOWS)
#include "nova_renderer/util/windows.hpp"
#endif
using namespace nova::mem;
#if defined(NOVA_WINDOWS)
#define BREAK_ON_DEVICE_LOST(result) \
if((result) == VK_ERROR_DEVICE_LOST) { \
DebugBreak(); \
}
#elif defined(NOVA_LINUX)
#define BREAK_ON_DEVICE_LOST(result) \
if((result) == VK_ERROR_DEVICE_LOST) { \
raise(SIGINT); \
}
#endif
namespace nova::renderer::rhi {
RX_LOG("VulkanRenderDevice", logger);
void FencedTask::operator()() const { work_to_perform(); }
VulkanRenderDevice::VulkanRenderDevice(NovaSettingsAccessManager& settings, NovaWindow& window, rx::memory::allocator& allocator)
: RenderDevice{settings, window, allocator},
vk_internal_allocator{wrap_allocator(internal_allocator)},
command_pools_by_thread_idx{&internal_allocator},
fenced_tasks{&internal_allocator} {
MTR_SCOPE("VulkanRenderDevice", "VulkanRenderDevice");
create_instance();
if(settings.settings.debug.enabled) {
enable_debug_output();
}
create_surface();
create_device_and_queues();
save_device_info();
initialize_vma();
if(settings.settings.debug.enabled) {
// Late init, can only be used when the device has already been created
vkSetDebugUtilsObjectNameEXT = reinterpret_cast<PFN_vkSetDebugUtilsObjectNameEXT>(
vkGetDeviceProcAddr(device, "vkSetDebugUtilsObjectNameEXT"));
}
create_swapchain();
create_per_thread_command_pools();
create_standard_pipeline_layout();
}
void VulkanRenderDevice::set_num_renderpasses(uint32_t /* num_renderpasses */) {
// Pretty sure Vulkan doesn't need to do anything here
}
ntl::Result<RhiRenderpass*> VulkanRenderDevice::create_renderpass(const renderpack::RenderPassCreateInfo& data,
const glm::uvec2& framebuffer_size,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_renderpass");
auto* vk_swapchain = static_cast<VulkanSwapchain*>(swapchain);
VkExtent2D swapchain_extent = {swapchain_size.x, swapchain_size.y};
auto* renderpass = allocator.create<VulkanRenderpass>();
VkSubpassDescription subpass_description = {};
subpass_description.flags = 0;
subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass_description.inputAttachmentCount = 0;
subpass_description.pInputAttachments = nullptr;
subpass_description.preserveAttachmentCount = 0;
subpass_description.pPreserveAttachments = nullptr;
subpass_description.pResolveAttachments = nullptr;
subpass_description.pDepthStencilAttachment = nullptr;
VkSubpassDependency image_available_dependency = {};
image_available_dependency.dependencyFlags = 0;
image_available_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
image_available_dependency.dstSubpass = 0;
image_available_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.srcAccessMask = 0;
image_available_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_create_info = {};
render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_create_info.pNext = nullptr;
render_pass_create_info.flags = 0;
render_pass_create_info.subpassCount = 1;
render_pass_create_info.pSubpasses = &subpass_description;
render_pass_create_info.dependencyCount = 1;
render_pass_create_info.pDependencies = &image_available_dependency;
rx::vector<VkAttachmentReference> attachment_references{&allocator};
rx::vector<VkAttachmentDescription> attachments{&allocator};
rx::vector<VkImageView> framebuffer_attachments{&allocator};
uint32_t framebuffer_width = framebuffer_size.x;
uint32_t framebuffer_height = framebuffer_size.y;
bool writes_to_backbuffer = false;
// Collect framebuffer size information from color output attachments
data.texture_outputs.each_fwd([&](const renderpack::TextureAttachmentInfo& attachment) {
if(attachment.name == BACKBUFFER_NAME) {
// Handle backbuffer
// Backbuffer framebuffers are handled by themselves in their own special snowflake way so we just need to skip
// everything
writes_to_backbuffer = true;
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = vk_swapchain->get_swapchain_format();
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachments.size()) - 1;
attachment_references.push_back(ref);
framebuffer_width = swapchain_extent.width;
framebuffer_height = swapchain_extent.height;
} else {
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = to_vk_format(attachment.pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = attachment.clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachments.size()) - 1;
attachment_references.push_back(ref);
}
});
VkAttachmentReference depth_reference = {};
// Collect framebuffer size information from the depth attachment
if(data.depth_texture) {
VkAttachmentDescription desc = {};
desc.flags = 0;
desc.format = to_vk_format(data.depth_texture->pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = data.depth_texture->clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments.push_back(desc);
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depth_reference.attachment = static_cast<uint32_t>(attachments.size()) - 1;
subpass_description.pDepthStencilAttachment = &depth_reference;
}
if(framebuffer_width == 0) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer width for pass {:s} is 0. This is illegal! Make sure that there is at least one attachment for this render pass, and ensure that all attachments used by this pass have a non-zero width",
data.name.data()));
}
if(framebuffer_height == 0) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer height for pass {:s} is 0. This is illegal! Make sure that there is at least one attachment for this render pass, and ensure that all attachments used by this pass have a non-zero height",
data.name.data()));
}
if(framebuffer_attachments.size() > gpu.props.limits.maxColorAttachments) {
return ntl::Result<RhiRenderpass*>(MAKE_ERROR(
"Framebuffer for pass {:s} has {:d} color attachments, but your GPU only supports {:d}. Please reduce the number of attachments that this pass uses, possibly by changing some of your input attachments to bound textures",
data.name.data(),
data.texture_outputs.size(),
gpu.props.limits.maxColorAttachments));
}
subpass_description.colorAttachmentCount = static_cast<uint32_t>(attachment_references.size());
subpass_description.pColorAttachments = attachment_references.data();
render_pass_create_info.attachmentCount = static_cast<uint32_t>(attachments.size());
render_pass_create_info.pAttachments = attachments.data();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
NOVA_CHECK_RESULT(vkCreateRenderPass(device, &render_pass_create_info, &vk_alloc, &renderpass->pass));
if(writes_to_backbuffer) {
if(data.texture_outputs.size() > 1) {
logger->error(
"Pass %s writes to the backbuffer, and other textures. Passes that write to the backbuffer are not allowed to write to any other textures",
data.name);
}
}
renderpass->render_area = {{0, 0}, {framebuffer_width, framebuffer_height}};
if(settings.settings.debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_RENDER_PASS;
object_name.objectHandle = reinterpret_cast<uint64_t>(renderpass->pass);
object_name.pObjectName = data.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return ntl::Result(static_cast<RhiRenderpass*>(renderpass));
}
RhiFramebuffer* VulkanRenderDevice::create_framebuffer(const RhiRenderpass* renderpass,
const rx::vector<RhiImage*>& color_attachments,
const rx::optional<RhiImage*> depth_attachment,
const glm::uvec2& framebuffer_size,
rx::memory::allocator& allocator) {
const auto* vk_renderpass = static_cast<const VulkanRenderpass*>(renderpass);
rx::vector<VkImageView> attachment_views(&allocator);
attachment_views.reserve(color_attachments.size() + 1);
color_attachments.each_fwd([&](const RhiImage* attachment) {
const auto* vk_image = static_cast<const VulkanImage*>(attachment);
attachment_views.push_back(vk_image->image_view);
});
// Depth attachment is ALWAYS the last attachment
if(depth_attachment) {
const auto* vk_depth_image = static_cast<const VulkanImage*>(*depth_attachment);
attachment_views.push_back(vk_depth_image->image_view);
}
VkFramebufferCreateInfo framebuffer_create_info = {};
framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_create_info.renderPass = vk_renderpass->pass;
framebuffer_create_info.attachmentCount = static_cast<uint32_t>(attachment_views.size());
framebuffer_create_info.pAttachments = attachment_views.data();
framebuffer_create_info.width = framebuffer_size.x;
framebuffer_create_info.height = framebuffer_size.y;
framebuffer_create_info.layers = 1;
auto* framebuffer = allocator.create<VulkanFramebuffer>();
framebuffer->size = framebuffer_size;
framebuffer->num_attachments = static_cast<uint32_t>(attachment_views.size());
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
NOVA_CHECK_RESULT(vkCreateFramebuffer(device, &framebuffer_create_info, &vk_alloc, &framebuffer->framebuffer));
return framebuffer;
}
rx::ptr<RhiResourceBinder> VulkanRenderDevice::create_resource_binder_for_pipeline(const RhiGraphicsPipelineState& pipeline_state,
rx::memory::allocator& allocator) {
return rx::make_ptr<VulkanResourceBinder>(&allocator, pipeline_state, *this, allocator);
}
ntl::Result<RhiPipelineInterface*> VulkanRenderDevice::create_pipeline_interface(
const rx::map<rx::string, RhiResourceBindingDescription>& bindings,
const rx::vector<renderpack::TextureAttachmentInfo>& color_attachments,
const rx::optional<renderpack::TextureAttachmentInfo>& depth_texture,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_pipeline_interface");
auto* vk_swapchain = static_cast<VulkanSwapchain*>(swapchain);
auto* pipeline_interface = allocator.create<VulkanPipelineInterface>();
pipeline_interface->bindings = bindings;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
VkSubpassDescription subpass_description;
subpass_description.flags = 0;
subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass_description.inputAttachmentCount = 0;
subpass_description.pInputAttachments = nullptr;
subpass_description.preserveAttachmentCount = 0;
subpass_description.pPreserveAttachments = nullptr;
subpass_description.pResolveAttachments = nullptr;
subpass_description.pDepthStencilAttachment = nullptr;
VkSubpassDependency image_available_dependency;
image_available_dependency.dependencyFlags = 0;
image_available_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
image_available_dependency.dstSubpass = 0;
image_available_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.srcAccessMask = 0;
image_available_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
image_available_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_create_info;
render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_create_info.pNext = nullptr;
render_pass_create_info.flags = 0;
render_pass_create_info.subpassCount = 1;
render_pass_create_info.pSubpasses = &subpass_description;
render_pass_create_info.dependencyCount = 1;
render_pass_create_info.pDependencies = &image_available_dependency;
rx::vector<VkAttachmentReference> attachment_references{&internal_allocator};
rx::vector<VkAttachmentDescription> attachment_descriptions{&internal_allocator};
rx::vector<VkImageView> framebuffer_attachments{&internal_allocator};
// Collect framebuffer size information from color output attachments
color_attachments.each_fwd([&](const renderpack::TextureAttachmentInfo& attachment) {
if(attachment.name == BACKBUFFER_NAME) {
// Handle backbuffer
// Backbuffer framebuffers are handled by themselves in their own special snowflake way so we just need to skip
// everything
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = vk_swapchain->get_swapchain_format();
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
attachment_references.push_back(ref);
return false;
}
VkAttachmentDescription desc;
desc.flags = 0;
desc.format = to_vk_format(attachment.pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = attachment.clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
VkAttachmentReference ref;
ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
ref.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
attachment_references.push_back(ref);
return true;
});
VkAttachmentReference depth_reference = {};
// Collect framebuffer size information from the depth attachment
if(depth_texture) {
VkAttachmentDescription desc = {};
desc.flags = 0;
desc.format = to_vk_format(depth_texture->pixel_format);
desc.samples = VK_SAMPLE_COUNT_1_BIT;
desc.loadOp = depth_texture->clear ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD;
desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
desc.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
desc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachment_descriptions.push_back(desc);
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depth_reference.attachment = static_cast<uint32_t>(attachment_descriptions.size()) - 1;
subpass_description.pDepthStencilAttachment = &depth_reference;
}
subpass_description.colorAttachmentCount = static_cast<uint32_t>(attachment_references.size());
subpass_description.pColorAttachments = attachment_references.data();
render_pass_create_info.attachmentCount = static_cast<uint32_t>(attachment_descriptions.size());
render_pass_create_info.pAttachments = attachment_descriptions.data();
{
MTR_SCOPE("VulkanRenderDevice", "CreateDummyRenderpass");
NOVA_CHECK_RESULT(vkCreateRenderPass(device, &render_pass_create_info, &vk_alloc, &pipeline_interface->pass));
}
return ntl::Result(static_cast<RhiPipelineInterface*>(pipeline_interface));
}
rx::optional<vk::DescriptorPool> VulkanRenderDevice::create_descriptor_pool(
const rx::map<DescriptorType, uint32_t>& descriptor_capacity, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_descriptor_pool");
rx::vector<vk::DescriptorPoolSize> pool_sizes{&internal_allocator};
uint32_t max_sets = 0;
descriptor_capacity.each_pair([&](const DescriptorType& type, const uint32_t count) {
pool_sizes.emplace_back(vk::DescriptorPoolSize{to_vk_descriptor_type(type), count});
max_sets += count;
});
const auto pool_create_info = vk::DescriptorPoolCreateInfo()
.setFlags(vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind)
.setMaxSets(max_sets)
.setPoolSizeCount(static_cast<uint32_t>(pool_sizes.size()))
.setPPoolSizes(pool_sizes.data());
vk::DescriptorPool pool;
const auto& vk_alloc = wrap_allocator(allocator);
device.createDescriptorPool(&pool_create_info, &vk_alloc, &pool);
return pool;
}
vk::DescriptorSet VulkanRenderDevice::get_next_standard_descriptor_set() {
if(standard_descriptor_sets.is_empty()) {
const auto variable_set_counts = rx::array{MAX_NUM_TEXTURES};
const auto count_allocate_info = vk::DescriptorSetVariableDescriptorCountAllocateInfo()
.setPDescriptorCounts(variable_set_counts.data())
.setDescriptorSetCount(static_cast<uint32_t>(variable_set_counts.size()));
const auto allocate_info = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(standard_descriptor_set_pool->descriptor_pool)
.setDescriptorSetCount(1)
.setPSetLayouts(&standard_set_layout)
.setPNext(&count_allocate_info);
vk::DescriptorSet set;
device.allocateDescriptorSets(&allocate_info, &set);
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET;
object_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkDescriptorSet>(set));
object_name.pObjectName = "Standard descriptor set";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return set;
} else {
const auto set = standard_descriptor_sets.last();
standard_descriptor_sets.pop_back();
return set;
}
}
void VulkanRenderDevice::return_standard_descriptor_sets(const rx::vector<vk::DescriptorSet>& sets) {
standard_descriptor_sets += sets;
}
vk::Fence VulkanRenderDevice::get_next_submission_fence() {
if(submission_fences.is_empty()) {
const auto fence_create_info = vk::FenceCreateInfo();
vk::Fence fence;
device.createFence(&fence_create_info, &vk_internal_allocator, &fence);
return fence;
} else {
const auto fence = submission_fences.last();
submission_fences.pop_back();
return fence;
}
}
ntl::Result<VulkanPipeline> VulkanRenderDevice::create_pipeline(const RhiGraphicsPipelineState& state,
vk::RenderPass renderpass,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_pipeline");
logger->verbose("Creating a VkPipeline for pipeline %s", state.name);
VulkanPipeline vk_pipeline{};
rx::vector<VkPipelineShaderStageCreateInfo> shader_stages{&internal_allocator};
rx::map<VkShaderStageFlags, VkShaderModule> shader_modules{&internal_allocator};
logger->verbose("Compiling vertex module");
const auto vertex_module = create_shader_module(state.vertex_shader.source);
if(vertex_module) {
shader_modules.insert(VK_SHADER_STAGE_VERTEX_BIT, *vertex_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not create vertex module")};
}
if(state.geometry_shader) {
logger->verbose("Compiling geometry module");
const auto geometry_module = create_shader_module(state.geometry_shader->source);
if(geometry_module) {
shader_modules.insert(VK_SHADER_STAGE_GEOMETRY_BIT, *geometry_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not geometry module")};
}
}
if(state.pixel_shader) {
logger->verbose("Compiling fragment module");
const auto fragment_module = create_shader_module(state.pixel_shader->source);
if(fragment_module) {
shader_modules.insert(VK_SHADER_STAGE_FRAGMENT_BIT, *fragment_module);
} else {
return ntl::Result<VulkanPipeline>{ntl::NovaError("Could not pixel module")};
}
} // namespace nova::renderer::rhi
shader_modules.each_pair([&](const VkShaderStageFlags stage, const VkShaderModule shader_module) {
VkPipelineShaderStageCreateInfo shader_stage_create_info;
shader_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shader_stage_create_info.pNext = nullptr;
shader_stage_create_info.flags = 0;
shader_stage_create_info.stage = static_cast<VkShaderStageFlagBits>(stage);
shader_stage_create_info.module = shader_module;
shader_stage_create_info.pName = "main";
shader_stage_create_info.pSpecializationInfo = nullptr;
shader_stages.push_back(shader_stage_create_info);
});
const auto& [vertex_attribute_descriptions, vertex_binding_descriptions] = get_input_assembler_setup(state.vertex_fields);
VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info;
vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state_create_info.pNext = nullptr;
vertex_input_state_create_info.flags = 0;
vertex_input_state_create_info.vertexBindingDescriptionCount = static_cast<uint32_t>(vertex_binding_descriptions.size());
vertex_input_state_create_info.pVertexBindingDescriptions = vertex_binding_descriptions.data();
vertex_input_state_create_info.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_attribute_descriptions.size());
vertex_input_state_create_info.pVertexAttributeDescriptions = vertex_attribute_descriptions.data();
VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly_create_info.pNext = nullptr;
input_assembly_create_info.flags = 0;
input_assembly_create_info.primitiveRestartEnable = VK_FALSE;
switch(state.topology) {
case PrimitiveTopology::TriangleList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
break;
case PrimitiveTopology::LineList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
break;
case PrimitiveTopology::PointList:
input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
break;
}
VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = state.viewport_size.x;
viewport.height = state.viewport_size.y;
viewport.minDepth = 0.0F;
viewport.maxDepth = 1.0F;
VkRect2D scissor;
scissor.offset = {0, 0};
scissor.extent = {static_cast<uint32_t>(state.viewport_size.x), static_cast<uint32_t>(state.viewport_size.y)};
VkPipelineViewportStateCreateInfo viewport_state_create_info;
viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state_create_info.pNext = nullptr;
viewport_state_create_info.flags = 0;
viewport_state_create_info.viewportCount = 1;
viewport_state_create_info.pViewports = &viewport;
viewport_state_create_info.scissorCount = 1;
viewport_state_create_info.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer_create_info;
rasterizer_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer_create_info.pNext = nullptr;
rasterizer_create_info.flags = 0;
rasterizer_create_info.depthClampEnable = VK_FALSE;
rasterizer_create_info.rasterizerDiscardEnable = VK_FALSE;
rasterizer_create_info.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer_create_info.lineWidth = 1.0F;
rasterizer_create_info.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer_create_info.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer_create_info.depthClampEnable = VK_FALSE;
rasterizer_create_info.depthBiasConstantFactor = state.rasterizer_state.depth_bias;
rasterizer_create_info.depthBiasSlopeFactor = state.rasterizer_state.slope_scaled_depth_bias;
rasterizer_create_info.depthBiasClamp = state.rasterizer_state.maximum_depth_bias;
if(rasterizer_create_info.depthBiasConstantFactor != 0 || rasterizer_create_info.depthBiasSlopeFactor != 0) {
rasterizer_create_info.depthBiasEnable = VK_TRUE;
} else {
rasterizer_create_info.depthBiasEnable = VK_FALSE;
}
VkPipelineMultisampleStateCreateInfo multisample_create_info;
multisample_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisample_create_info.pNext = nullptr;
multisample_create_info.flags = 0;
multisample_create_info.sampleShadingEnable = VK_FALSE;
multisample_create_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisample_create_info.minSampleShading = 1.0F;
multisample_create_info.pSampleMask = nullptr;
multisample_create_info.alphaToCoverageEnable = VK_FALSE;
multisample_create_info.alphaToOneEnable = VK_FALSE;
VkPipelineDepthStencilStateCreateInfo depth_stencil_create_info = {};
depth_stencil_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
if(state.depth_state) {
const auto& depth_state = *state.depth_state;
depth_stencil_create_info.depthTestEnable = VK_TRUE;
depth_stencil_create_info.depthWriteEnable = static_cast<VkBool32>(depth_state.enable_depth_write);
depth_stencil_create_info.depthCompareOp = to_compare_op(depth_state.compare_op);
if(depth_state.bounds_test_state) {
depth_stencil_create_info.depthBoundsTestEnable = VK_TRUE;
if(depth_state.bounds_test_state->mode == DepthBoundsTestMode::Static) {
depth_stencil_create_info.minDepthBounds = depth_state.bounds_test_state->static_state.min_bound;
depth_stencil_create_info.maxDepthBounds = depth_state.bounds_test_state->static_state.max_bound;
}
}
}
if(state.stencil_state) {
const auto stencil_state = *state.stencil_state;
depth_stencil_create_info.stencilTestEnable = VK_TRUE;
depth_stencil_create_info.front.failOp = to_stencil_op(stencil_state.front_face_op.fail_op);
depth_stencil_create_info.front.passOp = to_stencil_op(stencil_state.front_face_op.pass_op);
depth_stencil_create_info.front.depthFailOp = to_stencil_op(stencil_state.front_face_op.depth_fail_op);
depth_stencil_create_info.front.compareOp = to_compare_op(stencil_state.front_face_op.compare_op);
depth_stencil_create_info.front.compareMask = stencil_state.front_face_op.compare_mask;
depth_stencil_create_info.front.writeMask = stencil_state.front_face_op.write_mask;
depth_stencil_create_info.back.failOp = to_stencil_op(stencil_state.back_face_op.fail_op);
depth_stencil_create_info.back.passOp = to_stencil_op(stencil_state.back_face_op.pass_op);
depth_stencil_create_info.back.depthFailOp = to_stencil_op(stencil_state.back_face_op.depth_fail_op);
depth_stencil_create_info.back.compareOp = to_compare_op(stencil_state.back_face_op.compare_op);
depth_stencil_create_info.back.compareMask = stencil_state.back_face_op.compare_mask;
depth_stencil_create_info.back.writeMask = stencil_state.back_face_op.write_mask;
}
VkPipelineColorBlendStateCreateInfo color_blend_create_info{};
color_blend_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend_create_info.pNext = nullptr;
color_blend_create_info.flags = 0;
color_blend_create_info.logicOpEnable = VK_FALSE;
color_blend_create_info.logicOp = VK_LOGIC_OP_COPY;
rx::vector<VkPipelineColorBlendAttachmentState> attachment_states{&allocator};
if(state.blend_state) {
const auto& blend_state = *state.blend_state;
attachment_states.reserve(blend_state.render_target_states.size());
blend_state.render_target_states.each_fwd([&](const RenderTargetBlendState& render_target_blend) {
VkPipelineColorBlendAttachmentState color_blend_attachment;
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = render_target_blend.enable ? VK_TRUE : VK_FALSE;
color_blend_attachment.srcColorBlendFactor = to_blend_factor(render_target_blend.src_color_factor);
color_blend_attachment.dstColorBlendFactor = to_blend_factor(render_target_blend.dst_color_factor);
color_blend_attachment.colorBlendOp = to_blend_op(render_target_blend.color_op);
color_blend_attachment.srcAlphaBlendFactor = to_blend_factor(render_target_blend.src_alpha_factor);
color_blend_attachment.dstAlphaBlendFactor = to_blend_factor(render_target_blend.dst_alpha_factor);
color_blend_attachment.alphaBlendOp = to_blend_op(render_target_blend.alpha_op);
attachment_states.emplace_back(color_blend_attachment);
});
color_blend_create_info.attachmentCount = static_cast<uint32_t>(attachment_states.size());
color_blend_create_info.pAttachments = attachment_states.data();
color_blend_create_info.blendConstants[0] = blend_state.blend_constants.r;
color_blend_create_info.blendConstants[1] = blend_state.blend_constants.g;
color_blend_create_info.blendConstants[2] = blend_state.blend_constants.b;
color_blend_create_info.blendConstants[3] = blend_state.blend_constants.a;
} else {
attachment_states.reserve(state.color_attachments.size());
state.color_attachments.each_fwd([&](const renderpack::TextureAttachmentInfo& /* attachment_info */) {
VkPipelineColorBlendAttachmentState color_blend_attachment{};
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = VK_FALSE;
attachment_states.emplace_back(color_blend_attachment);
});
color_blend_create_info.attachmentCount = static_cast<uint32_t>(attachment_states.size());
color_blend_create_info.pAttachments = attachment_states.data();
}
rx::vector<VkDynamicState> dynamic_states;
if(state.enable_scissor_test) {
dynamic_states.emplace_back(VK_DYNAMIC_STATE_SCISSOR);
}
VkPipelineDynamicStateCreateInfo dynamic_state_create_info = {};
dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state_create_info.dynamicStateCount = static_cast<uint32_t>(dynamic_states.size());
dynamic_state_create_info.pDynamicStates = dynamic_states.data();
VkGraphicsPipelineCreateInfo pipeline_create_info = {};
pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_create_info.pNext = nullptr;
pipeline_create_info.flags = 0;
pipeline_create_info.stageCount = static_cast<uint32_t>(shader_stages.size());
pipeline_create_info.pStages = shader_stages.data();
pipeline_create_info.pVertexInputState = &vertex_input_state_create_info;
pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
pipeline_create_info.pViewportState = &viewport_state_create_info;
pipeline_create_info.pRasterizationState = &rasterizer_create_info;
pipeline_create_info.pMultisampleState = &multisample_create_info;
pipeline_create_info.pDepthStencilState = &depth_stencil_create_info;
pipeline_create_info.pColorBlendState = &color_blend_create_info;
pipeline_create_info.pDynamicState = &dynamic_state_create_info;
pipeline_create_info.layout = standard_pipeline_layout;
pipeline_create_info.renderPass = renderpass;
pipeline_create_info.subpass = 0;
pipeline_create_info.basePipelineIndex = -1;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
const auto result = vkCreateGraphicsPipelines(device, nullptr, 1, &pipeline_create_info, &vk_alloc, &vk_pipeline.pipeline);
if(result != VK_SUCCESS) {
return ntl::Result<VulkanPipeline>{MAKE_ERROR("Could not compile pipeline %s", state.name)};
}
// TODO: Figure out how to have bespoke pipeline layouts for things like post-processing
vk_pipeline.layout = standard_pipeline_layout;
if(settings.settings.debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_PIPELINE;
object_name.objectHandle = reinterpret_cast<uint64_t>(vk_pipeline.pipeline);
object_name.pObjectName = state.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return ntl::Result{vk_pipeline};
}
RhiBuffer* VulkanRenderDevice::create_buffer(const RhiBufferCreateInfo& info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_buffer");
auto* buffer = allocator.create<VulkanBuffer>();
VkBufferCreateInfo vk_create_info = {};
vk_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vk_create_info.size = info.size.b_count();
vk_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo vma_alloc{};
switch(info.buffer_usage) {
case BufferUsage::UniformBuffer: {
if(info.size < gpu.props.limits.maxUniformBufferRange) {
vk_create_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
} else {
vk_create_info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
}
vma_alloc.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
} break;
case BufferUsage::IndexBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_GPU_ONLY;
} break;
case BufferUsage::VertexBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_GPU_ONLY;
} break;
case BufferUsage::StagingBuffer: {
vk_create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
vma_alloc.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
vma_alloc.usage = VMA_MEMORY_USAGE_CPU_ONLY;
} break;
}
const auto result = vmaCreateBuffer(vma,
&vk_create_info,
&vma_alloc,
&buffer->buffer,
&buffer->allocation,
&buffer->allocation_info);
if(result == VK_SUCCESS) {
buffer->size = info.size;
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_BUFFER;
object_name.objectHandle = reinterpret_cast<uint64_t>(buffer->buffer);
object_name.pObjectName = info.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
return buffer;
} else {
logger->error("Could not create buffer %s: %s", info.name, to_string(result));
return nullptr;
}
}
void VulkanRenderDevice::write_data_to_buffer(const void* data, const Bytes num_bytes, const RhiBuffer* buffer) {
MTR_SCOPE("VulkanRenderDevice", "write_data_to_buffer");
const auto* vulkan_buffer = static_cast<const VulkanBuffer*>(buffer);
memcpy(vulkan_buffer->allocation_info.pMappedData, data, num_bytes.b_count());
}
RhiSampler* VulkanRenderDevice::create_sampler(const RhiSamplerCreateInfo& create_info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_sampler");
auto* sampler = allocator.create<VulkanSampler>();
VkSamplerCreateInfo vk_create_info = {};
vk_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
vk_create_info.minFilter = to_vk_filter(create_info.min_filter);
vk_create_info.magFilter = to_vk_filter(create_info.mag_filter);
vk_create_info.addressModeU = to_vk_address_mode(create_info.x_wrap_mode);
vk_create_info.addressModeV = to_vk_address_mode(create_info.y_wrap_mode);
vk_create_info.addressModeW = to_vk_address_mode(create_info.z_wrap_mode);
vk_create_info.mipLodBias = create_info.mip_bias;
vk_create_info.anisotropyEnable = create_info.enable_anisotropy ? VK_TRUE : VK_FALSE;
vk_create_info.maxAnisotropy = create_info.max_anisotropy;
vk_create_info.minLod = create_info.min_lod;
vk_create_info.maxLod = create_info.max_lod;
const VkAllocationCallbacks& alloc_calls = wrap_allocator(allocator);
vkCreateSampler(device, &vk_create_info, &alloc_calls, &sampler->sampler);
return sampler;
}
RhiImage* VulkanRenderDevice::create_image(const renderpack::TextureCreateInfo& info, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_image");
auto* image = allocator.create<VulkanImage>();
image->is_dynamic = true;
image->type = ResourceType::Image;
const VkFormat format = to_vk_format(info.format.pixel_format);
// In Nova, images all have a dedicated allocation
// This may or may not change depending on performance data, but given Nova's atlas-centric design I don't think it'll change much
const auto image_pixel_size = info.format.get_size_in_pixels(swapchain_size);
VmaAllocationCreateInfo vma_info = {};
vma_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkImageCreateInfo image_create_info = {};
image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_create_info.imageType = VK_IMAGE_TYPE_2D;
image_create_info.format = format;
image_create_info.extent.width = image_pixel_size.x;
image_create_info.extent.height = image_pixel_size.y;
image_create_info.extent.depth = 1;
image_create_info.mipLevels = 1;
image_create_info.arrayLayers = 1;
image_create_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image->is_depth_tex = true;
}
if(info.usage == renderpack::ImageUsage::SampledImage) {
image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
} else {
// If the image isn't a sampled image, it's a render target
// Render targets get dedicated allocations
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
} else {
image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
vma_info.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
image_create_info.queueFamilyIndexCount = 1;
image_create_info.pQueueFamilyIndices = &graphics_family_index;
image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
const auto result = vmaCreateImage(vma, &image_create_info, &vma_info, &image->image, &image->allocation, nullptr);
if(result == VK_SUCCESS) {
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT object_name = {};
object_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
object_name.objectType = VK_OBJECT_TYPE_IMAGE;
object_name.objectHandle = reinterpret_cast<uint64_t>(image->image);
object_name.pObjectName = info.name.data();
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &object_name));
}
VkImageViewCreateInfo image_view_create_info = {};
image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_create_info.image = image->image;
image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_create_info.format = image_create_info.format;
if(format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT) {
image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
} else {
image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
image_view_create_info.subresourceRange.baseArrayLayer = 0;
image_view_create_info.subresourceRange.layerCount = 1;
image_view_create_info.subresourceRange.baseMipLevel = 0;
image_view_create_info.subresourceRange.levelCount = 1;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateImageView(device, &image_view_create_info, &vk_alloc, &image->image_view);
return image;
} else {
logger->error("Could not create image %s: %s", info.name, to_string(result));
return nullptr;
}
}
RhiSemaphore* VulkanRenderDevice::create_semaphore(rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_semaphore");
auto* semaphore = allocator.create<VulkanSemaphore>();
VkSemaphoreCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateSemaphore(device, &create_info, &vk_alloc, &semaphore->semaphore);
return semaphore;
}
rx::vector<RhiSemaphore*> VulkanRenderDevice::create_semaphores(const uint32_t num_semaphores, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_semaphores");
auto semaphores = rx::vector<RhiSemaphore*>{&allocator};
semaphores.reserve(num_semaphores);
for(uint32_t i = 0; i < num_semaphores; i++) {
semaphores.emplace_back(create_semaphore(allocator));
}
return semaphores;
}
RhiFence* VulkanRenderDevice::create_fence(const bool signaled, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_fence");
auto* fence = allocator.create<VulkanFence>();
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if(signaled) {
fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
}
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateFence(device, &fence_create_info, &vk_alloc, &fence->fence);
return fence;
}
rx::vector<RhiFence*> VulkanRenderDevice::create_fences(const uint32_t num_fences,
const bool signaled,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_fences");
rx::vector<RhiFence*> fences{&allocator};
fences.reserve(num_fences);
VkFenceCreateInfo fence_create_info = {};
fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if(signaled) {
fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
}
for(uint32_t i = 0; i < num_fences; i++) {
auto* fence = allocator.create<VulkanFence>();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkCreateFence(device, &fence_create_info, &vk_alloc, &fence->fence);
fences.push_back(fence);
}
return fences;
}
void VulkanRenderDevice::wait_for_fences(const rx::vector<RhiFence*> fences) {
MTR_SCOPE("VulkanRenderDevice", "wait_for_fences");
rx::vector<VkFence> vk_fences{&internal_allocator};
vk_fences.reserve(fences.size());
fences.each_fwd([&](const RhiFence* fence) {
const auto* vk_fence = static_cast<const VulkanFence*>(fence);
vk_fences.push_back(vk_fence->fence);
});
const auto result = vkWaitForFences(device,
static_cast<uint32_t>(vk_fences.size()),
vk_fences.data(),
VK_TRUE,
std::numeric_limits<uint64_t>::max());
if(settings->debug.enabled) {
if(result != VK_SUCCESS) {
logger->error("Could not wait for fences. %s (error code %x)", to_string(result), result);
BREAK_ON_DEVICE_LOST(result);
}
}
}
void VulkanRenderDevice::reset_fences(const rx::vector<RhiFence*>& fences) {
MTR_SCOPE("VulkanRenderDevice", "reset_fences");
rx::vector<VkFence> vk_fences{&internal_allocator};
vk_fences.reserve(fences.size());
fences.each_fwd([&](const RhiFence* fence) {
const auto* vk_fence = static_cast<const VulkanFence*>(fence);
vk_fences.push_back(vk_fence->fence);
});
vkResetFences(device, static_cast<uint32_t>(fences.size()), vk_fences.data());
}
void VulkanRenderDevice::destroy_renderpass(RhiRenderpass* pass, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_renderpasses");
auto* vk_renderpass = static_cast<VulkanRenderpass*>(pass);
vkDestroyRenderPass(device, vk_renderpass->pass, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pass));
}
void VulkanRenderDevice::destroy_framebuffer(RhiFramebuffer* framebuffer, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_framebuffer");
const auto* vk_framebuffer = static_cast<const VulkanFramebuffer*>(framebuffer);
vkDestroyFramebuffer(device, vk_framebuffer->framebuffer, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(framebuffer));
}
void VulkanRenderDevice::destroy_pipeline_interface(RhiPipelineInterface* pipeline_interface, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_pipeline_interface");
auto* vk_interface = static_cast<VulkanPipelineInterface*>(pipeline_interface);
vkDestroyRenderPass(device, vk_interface->pass, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pipeline_interface));
}
void VulkanRenderDevice::destroy_pipeline(VulkanPipeline* pipeline, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_pipeline");
vkDestroyPipeline(device, pipeline->pipeline, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(pipeline));
}
void VulkanRenderDevice::destroy_texture(RhiImage* resource, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_texture");
auto* vk_image = static_cast<VulkanImage*>(resource);
vmaDestroyImage(vma, vk_image->image, vk_image->allocation);
allocator.deallocate(reinterpret_cast<rx_byte*>(resource));
}
void VulkanRenderDevice::destroy_semaphores(rx::vector<RhiSemaphore*>& semaphores, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_semaphores");
semaphores.each_fwd([&](RhiSemaphore* semaphore) {
auto* vk_semaphore = static_cast<VulkanSemaphore*>(semaphore);
vkDestroySemaphore(device, vk_semaphore->semaphore, nullptr);
allocator.deallocate(reinterpret_cast<rx_byte*>(semaphore));
});
}
void VulkanRenderDevice::destroy_fences(const rx::vector<RhiFence*>& fences, rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "destroy_fences");
fences.each_fwd([&](RhiFence* fence) {
auto* vk_fence = static_cast<VulkanFence*>(fence);
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
vkDestroyFence(device, vk_fence->fence, &vk_alloc);
allocator.deallocate(reinterpret_cast<rx_byte*>(fence));
});
}
RhiRenderCommandList* VulkanRenderDevice::create_command_list(const uint32_t thread_idx,
const QueueType needed_queue_type,
const RhiRenderCommandList::Level level,
rx::memory::allocator& allocator) {
MTR_SCOPE("VulkanRenderDevice", "create_command_list");
const uint32_t queue_family_index = get_queue_family_index(needed_queue_type);
const VkCommandPool pool = *command_pools_by_thread_idx[thread_idx].find(queue_family_index);
VkCommandBufferAllocateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
create_info.commandPool = pool;
create_info.level = to_vk_command_buffer_level(level);
create_info.commandBufferCount = 1;
VkCommandBuffer new_buffer;
vkAllocateCommandBuffers(device, &create_info, &new_buffer);
auto* list = allocator.create<VulkanRenderCommandList>(new_buffer, *this, allocator);
return list;
}
void VulkanRenderDevice::submit_command_list(RhiRenderCommandList* cmds,
const QueueType queue,
RhiFence* fence_to_signal,
const rx::vector<RhiSemaphore*>& wait_semaphores,
const rx::vector<RhiSemaphore*>& signal_semaphores) {
MTR_SCOPE("VulkanRenderDevice", "submit_command_list");
auto* vk_list = static_cast<VulkanRenderCommandList*>(cmds);
vkEndCommandBuffer(vk_list->cmds);
VkQueue queue_to_submit_to;
switch(queue) {
case QueueType::Graphics:
queue_to_submit_to = graphics_queue;
break;
case QueueType::Transfer:
queue_to_submit_to = copy_queue;
break;
case QueueType::AsyncCompute:
queue_to_submit_to = compute_queue;
break;
default:
queue_to_submit_to = graphics_queue;
}
rx::vector<VkSemaphore> vk_wait_semaphores{&internal_allocator};
vk_wait_semaphores.reserve(wait_semaphores.size());
wait_semaphores.each_fwd([&](const RhiSemaphore* semaphore) {
const auto* vk_semaphore = static_cast<const VulkanSemaphore*>(semaphore);
vk_wait_semaphores.push_back(vk_semaphore->semaphore);
});
rx::vector<VkSemaphore> vk_signal_semaphores{&internal_allocator};
vk_signal_semaphores.reserve(signal_semaphores.size());
signal_semaphores.each_fwd([&](const RhiSemaphore* semaphore) {
const auto* vk_semaphore = static_cast<const VulkanSemaphore*>(semaphore);
vk_signal_semaphores.push_back(vk_semaphore->semaphore);
});
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.waitSemaphoreCount = static_cast<uint32_t>(vk_wait_semaphores.size());
submit_info.pWaitSemaphores = vk_wait_semaphores.data();
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &vk_list->cmds;
submit_info.signalSemaphoreCount = static_cast<uint32_t>(vk_signal_semaphores.size());
submit_info.pSignalSemaphores = vk_signal_semaphores.data();
const auto vk_signal_fence = [&]() -> vk::Fence {
if(fence_to_signal) {
return static_cast<const VulkanFence*>(fence_to_signal)->fence;
} else {
return get_next_submission_fence();
}
}();
const auto result = vkQueueSubmit(queue_to_submit_to, 1, &submit_info, vk_signal_fence);
fenced_tasks.emplace_back(vk_signal_fence, [&] {
vk_list->cleanup_resources();
submission_fences.emplace_back(vk_signal_fence);
});
if(settings->debug.enabled) {
if(result != VK_SUCCESS) {
logger->error("Could not submit command list: %s", to_string(result));
BREAK_ON_DEVICE_LOST(result);
}
}
}
void VulkanRenderDevice::end_frame(FrameContext& /* ctx */) {
MTR_SCOPE("VulkanRenderEngine", "end_frame");
// Intentionally copying the vector
auto cur_tasks = fenced_tasks;
// Clear out the list of tasks. We've copied the tasks to the new vector so it's fine, and we'll add back in the tasks that aren't
// ready to run
fenced_tasks.clear();
cur_tasks.each_fwd([&](const FencedTask& task) {
if(device.getFenceStatus(task.fence) == vk::Result::eSuccess) {
task();
} else {
fenced_tasks.push_back(task);
}
});
}
uint32_t VulkanRenderDevice::get_queue_family_index(const QueueType type) const {
switch(type) {
case QueueType::Graphics:
return graphics_family_index;
case QueueType::Transfer:
return transfer_family_index;
case QueueType::AsyncCompute:
return compute_family_index;
default:
RX_ASSERT(false, "Unknown queue type %u", static_cast<uint32_t>(type));
return 9999; // I have to return _something_ or Visual Studio gets mad
}
}
void VulkanRenderDevice::create_surface() {
MTR_SCOPE("VulkanRenderDevice", "create_surface");
#ifdef NOVA_LINUX
VkXlibSurfaceCreateInfoKHR x_surface_create_info;
x_surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
x_surface_create_info.pNext = nullptr;
x_surface_create_info.flags = 0;
x_surface_create_info.dpy = window.get_display();
x_surface_create_info.window = window.get_window_handle();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateXlibSurfaceKHR(instance, &x_surface_create_info, &vk_alloc, &surface));
#elif defined(NOVA_WINDOWS)
VkWin32SurfaceCreateInfoKHR win32_surface_create = {};
win32_surface_create.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
win32_surface_create.hwnd = window.get_window_handle();
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateWin32SurfaceKHR(instance, &win32_surface_create, &vk_alloc, &surface));
#else
#error Unsuported window system
#endif
}
void VulkanRenderDevice::create_instance() {
MTR_SCOPE("VulkanRenderDevice", "create_instance");
const auto& version = settings.settings.vulkan.application_version;
VkApplicationInfo application_info;
application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
application_info.pNext = nullptr;
application_info.pApplicationName = settings.settings.vulkan.application_name;
application_info.applicationVersion = VK_MAKE_VERSION(version.major, version.minor, version.patch);
application_info.pEngineName = "Nova Renderer 0.9";
application_info.apiVersion = VK_API_VERSION_1_2;
VkInstanceCreateInfo create_info;
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pNext = nullptr;
create_info.flags = 0;
create_info.pApplicationInfo = &application_info;
if(settings.settings.debug.enabled && settings.settings.debug.enable_validation_layers) {
enabled_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
}
create_info.enabledLayerCount = static_cast<uint32_t>(enabled_layer_names.size());
create_info.ppEnabledLayerNames = enabled_layer_names.data();
rx::vector<const char*> enabled_extension_names{&internal_allocator};
enabled_extension_names.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
enabled_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
#ifdef NOVA_LINUX
enabled_extension_names.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
#elif defined(NOVA_WINDOWS)
enabled_extension_names.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#else
#error Unsupported Operating system
#endif
rx::vector<VkValidationFeatureEnableEXT> enabled_validation_features;
if(settings.settings.debug.enabled) {
enabled_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
enabled_extension_names.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT);
if(settings.settings.debug.enable_gpu_based_validation) {
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT);
enabled_validation_features.push_back(VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT);
}
}
create_info.enabledExtensionCount = static_cast<uint32_t>(enabled_extension_names.size());
create_info.ppEnabledExtensionNames = enabled_extension_names.data();
VkValidationFeaturesEXT validation_features = {};
validation_features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
validation_features.enabledValidationFeatureCount = static_cast<uint32_t>(enabled_validation_features.size());
validation_features.pEnabledValidationFeatures = enabled_validation_features.data();
create_info.pNext = &validation_features;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
{
MTR_SCOPE("VulkanRenderDevice", "vkCreateInstance");
NOVA_CHECK_RESULT(vkCreateInstance(&create_info, &vk_alloc, &instance));
}
}
void VulkanRenderDevice::enable_debug_output() {
MTR_SCOPE("VulkanRenderDevice", "enable_debug_output");
vkCreateDebugUtilsMessengerEXT = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(
vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"));
vkDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
VkDebugUtilsMessengerCreateInfoEXT debug_create_info = {};
debug_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debug_create_info.pNext = nullptr;
debug_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debug_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debug_create_info.pfnUserCallback = reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(&debug_report_callback);
debug_create_info.pUserData = this;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
NOVA_CHECK_RESULT(vkCreateDebugUtilsMessengerEXT(instance, &debug_create_info, &vk_alloc, &debug_callback));
}
void VulkanRenderDevice::save_device_info() {
MTR_SCOPE("VulkanRenderDevice", "save_device_info");
switch(gpu.props.vendorID) {
case AMD_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Amd;
break;
case INTEL_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Intel;
break;
case NVIDIA_PCI_VENDOR_ID:
info.architecture = DeviceArchitecture::Nvidia;
break;
default:
info.architecture = DeviceArchitecture::Unknown;
}
vk_info.max_uniform_buffer_size = gpu.props.limits.maxUniformBufferRange;
info.max_texture_size = gpu.props.limits.maxImageDimension2D;
// TODO: Something smarter when Intel releases discreet GPUS
// TODO: Handle integrated AMD GPUs
info.is_uma = info.architecture == DeviceArchitecture::Intel;
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(gpu.phys_device, nullptr, &extension_count, nullptr);
rx::vector<VkExtensionProperties> available_extensions{&internal_allocator, extension_count};
vkEnumerateDeviceExtensionProperties(gpu.phys_device, nullptr, &extension_count, available_extensions.data());
const auto extension_name_matcher = [](const char* ext_name) {
return [=](const VkExtensionProperties& ext_props) -> bool { return strcmp(ext_name, ext_props.extensionName) == 0; };
};
// TODO: Update as more GPUs support hardware raytracing
info.supports_raytracing = available_extensions.find_if(extension_name_matcher(VK_NV_RAY_TRACING_EXTENSION_NAME)) !=
rx::vector<VkExtensionProperties>::k_npos;
// TODO: Update as more GPUs support mesh shaders
info.supports_mesh_shaders = available_extensions.find_if(extension_name_matcher(VK_NV_MESH_SHADER_EXTENSION_NAME));
}
void VulkanRenderDevice::initialize_vma() {
MTR_SCOPE("VulkanRenderDevice", "initialize_vma");
VkAllocationCallbacks callbacks = vk_internal_allocator;
VmaAllocatorCreateInfo create_info{};
create_info.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
create_info.physicalDevice = gpu.phys_device;
create_info.device = device;
create_info.pAllocationCallbacks = &callbacks;
create_info.instance = instance;
const auto result = vmaCreateAllocator(&create_info, &vma);
if(result != VK_SUCCESS) {
logger->error("Could not initialize VMA: %s", to_string(result));
}
}
void VulkanRenderDevice::create_device_and_queues() {
MTR_SCOPE("VulkanRenderDevice", "create_device_and_queues");
rx::vector<char*> device_extensions{&internal_allocator};
device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
uint32_t device_count;
NOVA_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &device_count, nullptr));
auto physical_devices = rx::vector<VkPhysicalDevice>{&internal_allocator, device_count};
NOVA_CHECK_RESULT(vkEnumeratePhysicalDevices(instance, &device_count, physical_devices.data()));
uint32_t graphics_family_idx = 0xFFFFFFFF;
uint32_t compute_family_idx = 0xFFFFFFFF;
uint32_t copy_family_idx = 0xFFFFFFFF;
{
MTR_SCOPE("VulkanNovaRenderer", "Select Physical Device");
for(uint32_t device_idx = 0; device_idx < device_count; device_idx++) {
graphics_family_idx = 0xFFFFFFFF;
VkPhysicalDevice current_device = physical_devices[device_idx];
vkGetPhysicalDeviceProperties(current_device, &gpu.props);
const bool is_intel_gpu = gpu.props.vendorID == INTEL_PCI_VENDOR_ID;
const bool more_gpus_available = device_count - 1 > device_idx;
if(is_intel_gpu && more_gpus_available) {
// Intel GPU _probably_ isn't as powerful as a discreet GPU, and if there's more than one GPU then the other one(s) are
// _probably_ discreet GPUs, so let's not use the Intel GPU and instead use the discreet GPU
// TODO: Make a local device for the integrated GPU when we figure out multi-GPU
// TODO: Rework this code when Intel releases discreet GPUs
continue;
}
const auto supports_extensions = does_device_support_extensions(current_device, device_extensions);
if(!supports_extensions) {
continue;
}
uint32_t queue_family_count;
vkGetPhysicalDeviceQueueFamilyProperties(current_device, &queue_family_count, nullptr);
gpu.queue_family_props.resize(queue_family_count);
vkGetPhysicalDeviceQueueFamilyProperties(current_device, &queue_family_count, gpu.queue_family_props.data());
for(uint32_t queue_idx = 0; queue_idx < queue_family_count; queue_idx++) {
const VkQueueFamilyProperties current_properties = gpu.queue_family_props[queue_idx];
if(current_properties.queueCount < 1) {
continue;
}
VkBool32 supports_present = VK_FALSE;
NOVA_CHECK_RESULT(vkGetPhysicalDeviceSurfaceSupportKHR(current_device, queue_idx, surface, &supports_present));
const VkQueueFlags supports_graphics = current_properties.queueFlags & VK_QUEUE_GRAPHICS_BIT;
if((supports_graphics != 0U) && supports_present == VK_TRUE && graphics_family_idx == 0xFFFFFFFF) {
graphics_family_idx = queue_idx;
}
const VkQueueFlags supports_compute = current_properties.queueFlags & VK_QUEUE_COMPUTE_BIT;
if((supports_compute != 0U) && compute_family_idx == 0xFFFFFFFF) {
compute_family_idx = queue_idx;
}
const VkQueueFlags supports_copy = current_properties.queueFlags & VK_QUEUE_TRANSFER_BIT;
if((supports_copy != 0U) && copy_family_idx == 0xFFFFFFFF) {
copy_family_idx = queue_idx;
}
}
if(graphics_family_idx != 0xFFFFFFFF) {
logger->info("Selected GPU %s", gpu.props.deviceName);
gpu.phys_device = current_device;
break;
}
}
}
if(gpu.phys_device == nullptr) {
logger->error("Failed to find good GPU");
// TODO: Message the user that GPU selection failed
return;
}
PROFILE_VOID_EXPR(vkGetPhysicalDeviceFeatures(gpu.phys_device, &gpu.supported_features),
VulkanRenderDevice,
vkGetPhysicalDeviceFeatures);
PROFILE_VOID_EXPR(vkGetPhysicalDeviceMemoryProperties(gpu.phys_device, &gpu.memory_properties),
VulkanRenderDevice,
vkGetPhysicalDeviceMemoryProperties);
const float priority = 1.0;
VkDeviceQueueCreateInfo graphics_queue_create_info{};
graphics_queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
graphics_queue_create_info.pNext = nullptr;
graphics_queue_create_info.flags = 0;
graphics_queue_create_info.queueCount = 1;
graphics_queue_create_info.queueFamilyIndex = graphics_family_idx;
graphics_queue_create_info.pQueuePriorities = &priority;
rx::vector<VkDeviceQueueCreateInfo> queue_create_infos{&internal_allocator};
queue_create_infos.push_back(graphics_queue_create_info);
VkPhysicalDeviceFeatures physical_device_features{};
physical_device_features.geometryShader = VK_TRUE;
physical_device_features.tessellationShader = VK_TRUE;
physical_device_features.samplerAnisotropy = VK_TRUE;
physical_device_features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
if(settings->debug.enable_gpu_based_validation) {
physical_device_features.fragmentStoresAndAtomics = VK_TRUE;
physical_device_features.vertexPipelineStoresAndAtomics = VK_TRUE;
}
VkDeviceCreateInfo device_create_info{};
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_create_info.pNext = nullptr;
device_create_info.flags = 0;
device_create_info.queueCreateInfoCount = static_cast<uint32_t>(queue_create_infos.size());
device_create_info.pQueueCreateInfos = queue_create_infos.data();
device_create_info.pEnabledFeatures = &physical_device_features;
device_create_info.enabledExtensionCount = static_cast<uint32_t>(device_extensions.size());
device_create_info.ppEnabledExtensionNames = device_extensions.data();
device_create_info.enabledLayerCount = static_cast<uint32_t>(enabled_layer_names.size());
if(!enabled_layer_names.is_empty()) {
device_create_info.ppEnabledLayerNames = enabled_layer_names.data();
}
// Set up descriptor indexing
// Currently Nova only cares about indexing for texture descriptors
VkPhysicalDeviceDescriptorIndexingFeatures descriptor_indexing_features = {};
descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES;
descriptor_indexing_features.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
descriptor_indexing_features.runtimeDescriptorArray = true;
descriptor_indexing_features.descriptorBindingVariableDescriptorCount = VK_TRUE;
descriptor_indexing_features.descriptorBindingPartiallyBound = VK_TRUE;
descriptor_indexing_features.descriptorBindingSampledImageUpdateAfterBind = VK_TRUE;
device_create_info.pNext = &descriptor_indexing_features;
const auto dev_12_features = vk::PhysicalDeviceVulkan12Features()
.setDescriptorIndexing(true)
.setShaderSampledImageArrayNonUniformIndexing(true)
.setRuntimeDescriptorArray(true)
.setDescriptorBindingVariableDescriptorCount(true)
.setDescriptorBindingPartiallyBound(true)
.setDescriptorBindingSampledImageUpdateAfterBind(true);
device_create_info.pNext = &dev_12_features;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
VkDevice vk_device;
const auto res = PROFILE_RET_EXPR(vkCreateDevice(gpu.phys_device, &device_create_info, &vk_alloc, &vk_device),
VulkanRenderEngine,
vkCreateDevice);
if(res != VK_SUCCESS) {
// logger();
}
device = vk_device;
graphics_family_index = graphics_family_idx;
vkGetDeviceQueue(device, graphics_family_idx, 0, &graphics_queue);
compute_family_index = compute_family_idx;
vkGetDeviceQueue(device, compute_family_idx, 0, &compute_queue);
transfer_family_index = copy_family_idx;
vkGetDeviceQueue(device, copy_family_idx, 0, ©_queue);
}
bool VulkanRenderDevice::does_device_support_extensions(VkPhysicalDevice device, const rx::vector<char*>& required_device_extensions) {
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, nullptr);
rx::vector<VkExtensionProperties> available(extension_count);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count, available.data());
rx::set<rx::string> required{&internal_allocator};
required_device_extensions.each_fwd([&](const char* extension) { required.insert(extension); });
available.each_fwd(
[&](const VkExtensionProperties& extension) { required.erase(static_cast<const char*>(extension.extensionName)); });
if(!required.is_empty()) {
std::stringstream ss;
required.each([&](const rx::string& extension) { ss << extension.data() << ", "; });
logger->warning("Device does not support these required extensions: %s", ss.str().c_str());
}
const auto device_supports_required_extensions = required.is_empty();
return device_supports_required_extensions;
}
void VulkanRenderDevice::create_swapchain() {
MTR_SCOPE("VulkanRenderDevice", "create_swapchain");
// Check what formats our rendering supports, and create a swapchain with one of those formats
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu.phys_device, surface, &gpu.surface_capabilities);
uint32_t num_surface_formats;
vkGetPhysicalDeviceSurfaceFormatsKHR(gpu.phys_device, surface, &num_surface_formats, nullptr);
gpu.surface_formats.resize(num_surface_formats);
vkGetPhysicalDeviceSurfaceFormatsKHR(gpu.phys_device, surface, &num_surface_formats, gpu.surface_formats.data());
uint32_t num_surface_present_modes;
vkGetPhysicalDeviceSurfacePresentModesKHR(gpu.phys_device, surface, &num_surface_present_modes, nullptr);
rx::vector<VkPresentModeKHR> present_modes{&internal_allocator, num_surface_present_modes};
vkGetPhysicalDeviceSurfacePresentModesKHR(gpu.phys_device, surface, &num_surface_present_modes, present_modes.data());
swapchain = internal_allocator.create<VulkanSwapchain>(settings->max_in_flight_frames,
this,
window.get_framebuffer_size(),
present_modes);
swapchain_size = window.get_framebuffer_size();
}
void VulkanRenderDevice::create_per_thread_command_pools() {
MTR_SCOPE("VulkanRenderDevice", "create_per_thread_command_pools");
const uint32_t num_threads = 1; // TODO: Make this real
command_pools_by_thread_idx.reserve(num_threads);
for(uint32_t i = 0; i < num_threads; i++) {
command_pools_by_thread_idx.push_back(make_new_command_pools());
}
}
void VulkanRenderDevice::create_standard_pipeline_layout() {
standard_push_constants = rx::array{
// Camera and Material index
vk::PushConstantRange().setStageFlags(vk::ShaderStageFlagBits::eAll).setOffset(0).setSize(sizeof(uint32_t) * 2)};
const auto flags_per_binding = rx::array{vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlags{},
vk::DescriptorBindingFlagBits::eUpdateAfterBind |
vk::DescriptorBindingFlagBits::eVariableDescriptorCount |
vk::DescriptorBindingFlagBits::ePartiallyBound};
const auto set_flags = vk::DescriptorSetLayoutBindingFlagsCreateInfo()
.setBindingCount(flags_per_binding.size())
.setPBindingFlags(flags_per_binding.data());
const auto camera_buffer_descriptor_type = (MAX_NUM_CAMERAS * sizeof(CameraUboData)) < gpu.props.limits.maxUniformBufferRange ?
vk::DescriptorType::eUniformBuffer :
vk::DescriptorType::eStorageBuffer;
const auto material_buffer_descriptor_type = MATERIAL_BUFFER_SIZE.b_count() < gpu.props.limits.maxUniformBufferRange ?
vk::DescriptorType::eUniformBuffer :
vk::DescriptorType::eStorageBuffer;
// Binding for the array of material parameter buffers. Nova uses a variable-length, partially-bound
const rx::vector<vk::DescriptorSetLayoutBinding> bindings = rx::array{// Camera data buffer
vk::DescriptorSetLayoutBinding()
.setBinding(0)
.setDescriptorType(camera_buffer_descriptor_type)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Material data buffer
vk::DescriptorSetLayoutBinding()
.setBinding(1)
.setDescriptorType(material_buffer_descriptor_type)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Point sampler
vk::DescriptorSetLayoutBinding()
.setBinding(2)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Bilinear sampler
vk::DescriptorSetLayoutBinding()
.setBinding(3)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Trilinear sampler
vk::DescriptorSetLayoutBinding()
.setBinding(4)
.setDescriptorType(vk::DescriptorType::eSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eAll),
// Textures array
vk::DescriptorSetLayoutBinding()
.setBinding(5)
.setDescriptorType(vk::DescriptorType::eSampledImage)
.setDescriptorCount(MAX_NUM_TEXTURES)
.setStageFlags(vk::ShaderStageFlagBits::eAll)};
const auto dsl_layout_create = vk::DescriptorSetLayoutCreateInfo()
.setFlags(vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool)
.setBindingCount(static_cast<uint32_t>(bindings.size()))
.setPBindings(bindings.data())
.setPNext(&set_flags);
device.createDescriptorSetLayout(&dsl_layout_create, &vk_internal_allocator, &standard_set_layout);
const auto pipeline_layout_create = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(1)
.setPSetLayouts(&standard_set_layout)
.setPushConstantRangeCount(static_cast<uint32_t>(standard_push_constants.size()))
.setPPushConstantRanges(standard_push_constants.data());
device.createPipelineLayout(&pipeline_layout_create, &vk_internal_allocator, &standard_pipeline_layout);
auto* pool = create_descriptor_pool(rx::array{rx::pair{DescriptorType::StorageBuffer, 5_u32 * 1024},
rx::pair{DescriptorType::UniformBuffer, 5_u32 * 1024},
rx::pair{DescriptorType::Texture, MAX_NUM_TEXTURES * 1024},
rx::pair{DescriptorType::Sampler, 3_u32 * 1024}},
internal_allocator);
standard_descriptor_set_pool = rx::ptr<VulkanDescriptorPool>{&internal_allocator, static_cast<VulkanDescriptorPool*>(pool)};
if(settings->debug.enabled) {
VkDebugUtilsObjectNameInfoEXT pipeline_layout_name = {};
pipeline_layout_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
pipeline_layout_name.objectType = VK_OBJECT_TYPE_PIPELINE_LAYOUT;
pipeline_layout_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkPipelineLayout>(standard_pipeline_layout));
pipeline_layout_name.pObjectName = "Standard Pipeline Layout";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &pipeline_layout_name));
VkDebugUtilsObjectNameInfoEXT descriptor_pool_name = {};
descriptor_pool_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
descriptor_pool_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_POOL;
descriptor_pool_name.objectHandle = reinterpret_cast<uint64_t>(
static_cast<VkDescriptorPool>(standard_descriptor_set_pool->descriptor_pool));
descriptor_pool_name.pObjectName = "Standard Descriptor Set Pool";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &descriptor_pool_name));
VkDebugUtilsObjectNameInfoEXT descriptor_set_layout_name = {};
descriptor_set_layout_name.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
descriptor_set_layout_name.objectType = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT;
descriptor_set_layout_name.objectHandle = reinterpret_cast<uint64_t>(static_cast<VkDescriptorSetLayout>(standard_set_layout));
descriptor_set_layout_name.pObjectName = "Standard descriptor set layout";
NOVA_CHECK_RESULT(vkSetDebugUtilsObjectNameEXT(device, &descriptor_set_layout_name));
}
}
rx::map<uint32_t, VkCommandPool> VulkanRenderDevice::make_new_command_pools() const {
MTR_SCOPE("VulkanRenderDevice", "make_new_command_pools");
rx::vector<uint32_t> queue_indices{&internal_allocator};
queue_indices.push_back(graphics_family_index);
queue_indices.push_back(transfer_family_index);
queue_indices.push_back(compute_family_index);
rx::map<uint32_t, VkCommandPool> pools_by_queue{&internal_allocator};
queue_indices.each_fwd([&](const uint32_t queue_index) {
VkCommandPoolCreateInfo command_pool_create_info;
command_pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
command_pool_create_info.pNext = nullptr;
command_pool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
command_pool_create_info.queueFamilyIndex = queue_index;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
VkCommandPool command_pool;
NOVA_CHECK_RESULT(vkCreateCommandPool(device, &command_pool_create_info, &vk_alloc, &command_pool));
pools_by_queue.insert(queue_index, command_pool);
});
return pools_by_queue;
}
uint32_t VulkanRenderDevice::find_memory_type_with_flags(const uint32_t search_flags, const MemorySearchMode search_mode) const {
for(uint32_t i = 0; i < gpu.memory_properties.memoryTypeCount; i++) {
const VkMemoryType& memory_type = gpu.memory_properties.memoryTypes[i];
switch(search_mode) {
case MemorySearchMode::Exact:
if(memory_type.propertyFlags == search_flags) {
return i;
}
break;
case MemorySearchMode::Fuzzy:
if((memory_type.propertyFlags & search_flags) != 0) {
return i;
}
break;
}
}
return VK_MAX_MEMORY_TYPES;
}
rx::vector<VkDescriptorSetLayout> VulkanRenderDevice::create_descriptor_set_layouts(
const rx::map<rx::string, RhiResourceBindingDescription>& all_bindings,
rx::vector<uint32_t>& variable_descriptor_counts,
rx::memory::allocator& allocator) const {
MTR_SCOPE("VulkanRenderDevice", "create_descriptor_set_layouts");
/*
* A few tasks to accomplish:
* - Take the unordered map of descriptor sets (all_bindings) and convert it into
* VkDescriptorSetLayoutCreateInfo structs, ordering everything along the way
* -
*/
uint32_t num_sets = 0;
all_bindings.each_value([&](const RhiResourceBindingDescription& desc) {
if(desc.set >= gpu.props.limits.maxBoundDescriptorSets) {
logger->error("Descriptor set %u is out of range - your GPU only supports %u sets!",
desc.set,
gpu.props.limits.maxBoundDescriptorSets);
} else {
num_sets = rx::algorithm::max(num_sets, desc.set + 1);
}
});
variable_descriptor_counts.resize(num_sets, 0);
// Some precalculations so we know how much room we actually need
rx::vector<uint32_t> num_bindings_per_set{&allocator};
num_bindings_per_set.resize(num_sets);
all_bindings.each_value([&](const RhiResourceBindingDescription& desc) {
num_bindings_per_set[desc.set] = rx::algorithm::max(num_bindings_per_set[desc.set], desc.binding + 1);
});
rx::vector<rx::vector<VkDescriptorSetLayoutBinding>> bindings_by_set{&allocator};
rx::vector<rx::vector<VkDescriptorBindingFlags>> binding_flags_by_set{&allocator};
bindings_by_set.reserve(num_sets);
binding_flags_by_set.reserve(num_sets);
uint32_t set = 0;
num_bindings_per_set.each_fwd([&](const uint32_t num_bindings) {
// Emplace back vectors large enough to hold all the bindings we have
bindings_by_set.emplace_back(num_bindings);
binding_flags_by_set.emplace_back(num_bindings);
logger->verbose("Set %u has %u bindings", set, num_bindings);
set++;
});
all_bindings.each_value([&](const RhiResourceBindingDescription& binding) {
if(binding.set >= bindings_by_set.size()) {
logger->error("You've skipped one or more descriptor sets! Don't do that, Nova can't handle it");
return true;
}
VkDescriptorSetLayoutBinding descriptor_binding = {};
descriptor_binding.binding = binding.binding;
descriptor_binding.descriptorType = static_cast<VkDescriptorType>(to_vk_descriptor_type(binding.type));
descriptor_binding.descriptorCount = binding.count;
descriptor_binding.stageFlags = to_vk_shader_stage_flags(binding.stages);
logger->verbose("Descriptor %u.%u is type %s", binding.set, binding.binding, descriptor_type_to_string(binding.type));
if(binding.is_unbounded) {
binding_flags_by_set[binding.set][binding.binding] = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT |
VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT;
// Record the maximum number of descriptors in the variable size array in this set
variable_descriptor_counts[binding.set] = binding.count;
logger->verbose("Descriptor %u.%u is unbounded", binding.set, binding.binding);
} else {
binding_flags_by_set[binding.set][binding.binding] = 0;
}
bindings_by_set[binding.set][binding.binding] = descriptor_binding;
return true;
});
rx::vector<VkDescriptorSetLayoutCreateInfo> dsl_create_infos{&allocator};
dsl_create_infos.reserve(bindings_by_set.size());
rx::vector<VkDescriptorSetLayoutBindingFlagsCreateInfo> flag_infos{&allocator};
flag_infos.reserve(bindings_by_set.size());
// We may make bindings_by_set much larger than it needs to be is there's multiple descriptor bindings per set. Thus, only iterate
// through the sets we actually care about
bindings_by_set.each_fwd([&](const rx::vector<VkDescriptorSetLayoutBinding>& bindings) {
VkDescriptorSetLayoutCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
create_info.bindingCount = static_cast<uint32_t>(bindings.size());
create_info.pBindings = bindings.data();
const auto& flags = binding_flags_by_set[dsl_create_infos.size()];
VkDescriptorSetLayoutBindingFlagsCreateInfo binding_flags = {};
binding_flags.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO;
binding_flags.bindingCount = static_cast<uint32_t>(flags.size());
binding_flags.pBindingFlags = flags.data();
flag_infos.emplace_back(binding_flags);
create_info.pNext = &flag_infos[flag_infos.size() - 1];
dsl_create_infos.push_back(create_info);
});
rx::vector<VkDescriptorSetLayout> layouts{&allocator};
const VkAllocationCallbacks& vk_alloc = wrap_allocator(allocator);
layouts.resize(dsl_create_infos.size());
for(size_t i = 0; i < dsl_create_infos.size(); i++) {
vkCreateDescriptorSetLayout(device, &dsl_create_infos[i], &vk_alloc, &layouts[i]);
}
return layouts;
}
VkImageView VulkanRenderDevice::image_view_for_image(const RhiImage* image) {
// TODO: This method is terrible. We shouldn't tie image views to images, we should let everything that wants
// to use the image create its own image view
const auto* vk_image = static_cast<const VulkanImage*>(image);
return vk_image->image_view;
}
VkCommandBufferLevel VulkanRenderDevice::to_vk_command_buffer_level(const RhiRenderCommandList::Level level) {
switch(level) {
case RhiRenderCommandList::Level::Primary:
return VK_COMMAND_BUFFER_LEVEL_PRIMARY;
case RhiRenderCommandList::Level::Secondary:
return VK_COMMAND_BUFFER_LEVEL_SECONDARY;
}
return VK_COMMAND_BUFFER_LEVEL_PRIMARY;
}
VulkanInputAssemblerLayout VulkanRenderDevice::get_input_assembler_setup(const rx::vector<RhiVertexField>& vertex_fields) {
rx::vector<VkVertexInputAttributeDescription> attributes;
rx::vector<VkVertexInputBindingDescription> bindings;
attributes.reserve(vertex_fields.size());
bindings.reserve(vertex_fields.size());
uint32_t vertex_size = 0;
vertex_fields.each_fwd([&](const RhiVertexField& field) { vertex_size += get_byte_size(field.format); });
uint32_t cur_binding = 0;
uint32_t byte_offset = 0;
vertex_fields.each_fwd([&](const RhiVertexField& field) {
const auto field_size = get_byte_size(field.format);
const auto attr_format = to_vk_vertex_format(field.format);
attributes.emplace_back(VkVertexInputAttributeDescription{cur_binding, 0, attr_format, byte_offset});
bindings.emplace_back(VkVertexInputBindingDescription{cur_binding, vertex_size, VK_VERTEX_INPUT_RATE_VERTEX});
cur_binding++;
byte_offset += field_size;
});
return {attributes, bindings};
}
rx::optional<VkShaderModule> VulkanRenderDevice::create_shader_module(const rx::vector<uint32_t>& spirv) const {
MTR_SCOPE("VulkanRenderDevice", "create_shader_module");
VkShaderModuleCreateInfo shader_module_create_info = {};
shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shader_module_create_info.pCode = spirv.data();
shader_module_create_info.codeSize = spirv.size() * 4;
VkShaderModule module;
const VkAllocationCallbacks& vk_alloc = wrap_allocator(internal_allocator);
const auto result = vkCreateShaderModule(device, &shader_module_create_info, &vk_alloc, &module);
if(result == VK_SUCCESS) {
return rx::optional<VkShaderModule>(module);
} else {
logger->error("Could not create shader module: %s", to_string(result));
return rx::nullopt;
}
}
VKAPI_ATTR VkBool32 VKAPI_CALL VulkanRenderDevice::debug_report_callback(const VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
const VkDebugUtilsMessageTypeFlagsEXT message_types,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* render_device) {
rx::string type = "General";
if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0U) {
type = "Validation";
} else if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) != 0U) {
type = "Performance";
}
rx::string queue_list;
if(callback_data->queueLabelCount != 0) {
queue_list.append(" Queues: ");
for(uint32_t i = 0; i < callback_data->queueLabelCount; i++) {
queue_list.append(callback_data->pQueueLabels[i].pLabelName);
if(i != callback_data->queueLabelCount - 1) {
queue_list.append(", ");
}
}
}
rx::string command_buffer_list;
if(callback_data->cmdBufLabelCount != 0) {
command_buffer_list.append("Command Buffers: ");
for(uint32_t i = 0; i < callback_data->cmdBufLabelCount; i++) {
command_buffer_list.append(callback_data->pCmdBufLabels[i].pLabelName);
if(i != callback_data->cmdBufLabelCount - 1) {
command_buffer_list.append(", ");
}
}
}
rx::string object_list;
if(callback_data->objectCount != 0) {
object_list.append("Objects: ");
for(uint32_t i = 0; i < callback_data->objectCount; i++) {
object_list.append(to_string(callback_data->pObjects[i].objectType));
if(callback_data->pObjects[i].pObjectName != nullptr) {
object_list.append(rx::string::format(" \"%s\"", callback_data->pObjects[i].pObjectName));
}
object_list.append(rx::string::format(" (%x)", callback_data->pObjects[i].objectHandle));
if(i != callback_data->objectCount - 1) {
object_list.append(", ");
}
}
}
rx::string vk_message;
if(callback_data->pMessage != nullptr) {
vk_message.append(callback_data->pMessage);
}
const rx::string msg = rx::string::format("[%s] %s %s %s %s", type, queue_list, command_buffer_list, object_list, vk_message);
if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0) {
logger->error("%s", msg);
#ifdef NOVA_LINUX
nova_backtrace();
#endif
auto* vk_render_device = reinterpret_cast<VulkanRenderDevice*>(render_device);
if(vk_render_device->settings->debug.break_on_validation_errors) {
rx::abort("Validation error");
}
} else if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) != 0) {
// Warnings may hint at unexpected / non-spec API usage
logger->warning("%s", msg);
} else if(((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) != 0) &&
((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) == 0U)) { // No validation info!
// Informal messages that may become handy during debugging
logger->info("%s", msg);
} else if((message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) != 0) {
// Diagnostic info from the Vulkan loader and layers
// Usually not helpful in terms of API usage, but may help to debug layer and loader problems
logger->verbose("%s", msg);
} else if((message_types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) == 0U) { // No validation info!
// Catch-all to be super sure
logger->info("%s", msg);
}
return VK_FALSE;
}
} // namespace nova::renderer::rhi
|
/**
* @file Heap.hpp
* @author niob
* @date Oct 21, 2016
* @brief Declares and defines the {@link Heap} class.
*/
#ifndef HEAP_HPP_
#define HEAP_HPP_
#pragma once
#include <cstddef>
#include <ostream>
#include <vector>
#include "TaggedPointer.hpp"
#include "TypeDescriptor.hpp"
namespace ssw {
using byte = unsigned char;
class HeapBase
{
using TypePtr = TaggedPointer;
class FreeListNode;
FreeListNode *mFreeList;
const std::size_t mAlign;
std::vector<void*> mRoots;
protected:
/**
* Initialize this heap with the specified storage and alignment.
*
* @param storage Pointer to the storage to use for objects.
* @param size Raw size of the storage.
* @param align The alignment to use for allocated objects, `storage` must have at least that alignment.
*/
HeapBase(byte *storage, std::size_t size, std::size_t align) noexcept;
/**
* Try to allocate a block of memory for the specified type.
*
* @param type Type descriptor for the memory to allocate.
* @return A pointer to the allocated memory block, or `nullptr` if the allocation failed.
*/
void* tryAllocate(const TypeDescriptor &type) noexcept;
/**
* Merge free blocks and build a new free list.
*/
void mergeBlocks() noexcept;
/**
* Deallocate the specified block by putting it back into the free list. No destructors are called.
*
* @param block Pointer to the block to deallocate.
*/
void deallocate(byte *block) noexcept;
/**
* Align the specified offset to the heap alignment.
*
* @param offset The offset to align.
* @return The offset aligned to the next larger multiple of this heap's alignment.
*/
std::size_t align(std::size_t offset) noexcept {
return (offset + mAlign - 1) & ~(mAlign - 1);
}
/**
* Get a reference to the type descriptor pointer from an object address. The type descriptor pointer
* for that address must already have been created before.
*
* @param ptr The object address (pointer to a managed object).
* @return A reference to the pointer to the type descriptor for the object.
*/
static TypePtr& typeDescriptorPtr(byte *ptr) noexcept {
return *reinterpret_cast<TypePtr*>(ptr - sizeof(TypePtr));
}
public:
/**
* Allocate a block of memory for the specified type.
*
* @param type Type descriptor for the memory to allocate.
* @param isRoot (optional) Whether to register the allocated object as a heap root.
* @return A pointer to the allocated memory block, or `nullptr` if the allocation failed.
*/
void* allocate(const TypeDescriptor &type, bool isRoot = false) noexcept;
/**
* Allocate a block of memory for the specified type.
*
* @param isRoot (optional) Whether to register the allocated object as a heap root.
* @return Pointer to the newly allocated and uninitialized object, or `nullptr` if the allocation
* failed.
*
* @tparam The type to allocate memory for, must have a static member variable `type` that holds the
* type descriptor to use.
*/
template <typename T>
T* allocate(bool isRoot = false) noexcept {
assert(T::type.size() >= sizeof(T));
return reinterpret_cast<T*>(allocate(T::type, isRoot));
}
/**
* Register the specified object as a heap root for garbage collection.
*
* @param object Pointer to the object to register.
*/
void registerRoot(void *object) {
mRoots.push_back(object);
}
/**
* Dump the contents of this heap to the specified stream.
*
* The dump contains a list of live objects, a list of free blocks, and overall statistics.
*
* @param os The output stream to write to.
*/
void dump(std::ostream &os) const;
};
template <std::size_t HeapSize, std::size_t Align = alignof(std::max_align_t)>
class Heap : public HeapBase
{
// Make storage slightly bigger to allow for type descriptor pointer
alignas(Align)
byte mStorage[HeapSize + Align];
public:
/** The alignment of this heap. */
static constexpr auto alignment = Align;
/** The size of this heap. */
static constexpr auto size = HeapSize;
Heap() noexcept : HeapBase(mStorage, HeapSize + Align, Align) {
}
};
} // namespace ssw
#endif /* HEAP_HPP_ */
Change visibility of several methods in HeapBase.
The visibility of deallocate() is now public (needed for operator
delete to be able to deallocate objects), all other formerly
protected methods except for the constructor are now private.
/**
* @file Heap.hpp
* @author niob
* @date Oct 21, 2016
* @brief Declares and defines the {@link Heap} class.
*/
#ifndef HEAP_HPP_
#define HEAP_HPP_
#pragma once
#include <cstddef>
#include <ostream>
#include <vector>
#include "TaggedPointer.hpp"
#include "TypeDescriptor.hpp"
namespace ssw {
using byte = unsigned char;
class HeapBase
{
using TypePtr = TaggedPointer;
class FreeListNode;
FreeListNode *mFreeList;
const std::size_t mAlign;
std::vector<void*> mRoots;
protected:
/**
* Initialize this heap with the specified storage and alignment.
*
* @param storage Pointer to the storage to use for objects.
* @param size Raw size of the storage.
* @param align The alignment to use for allocated objects, `storage` must have at least that alignment.
*/
HeapBase(byte *storage, std::size_t size, std::size_t align) noexcept;
public:
/**
* Allocate a block of memory for the specified type.
*
* @param type Type descriptor for the memory to allocate.
* @param isRoot (optional) Whether to register the allocated object as a heap root.
* @return A pointer to the allocated memory block, or `nullptr` if the allocation failed.
*/
void* allocate(const TypeDescriptor &type, bool isRoot = false) noexcept;
/**
* Allocate a block of memory for the specified type.
*
* @param isRoot (optional) Whether to register the allocated object as a heap root.
* @return Pointer to the newly allocated and uninitialized object, or `nullptr` if the allocation
* failed.
*
* @tparam The type to allocate memory for, must have a static member variable `type` that holds the
* type descriptor to use.
*/
template <typename T>
T* allocate(bool isRoot = false) noexcept {
assert(T::type.size() >= sizeof(T));
return reinterpret_cast<T*>(allocate(T::type, isRoot));
}
/**
* Deallocate the specified block by putting it back into the free list. No destructors are called.
*
* This function may be used by `operator delete` of managed objects to free memory immediately instead
* of waiting for the next garbage collection. It is not used during garbage collection.
*
* @param block Pointer to the block to deallocate.
*/
void deallocate(byte *block) noexcept;
/**
* Register the specified object as a heap root for garbage collection.
*
* @param object Pointer to the object to register.
*/
void registerRoot(void *object) {
mRoots.push_back(object);
}
/**
* Dump the contents of this heap to the specified stream.
*
* The dump contains a list of live objects, a list of free blocks, and overall statistics.
*
* @param os The output stream to write to.
*/
void dump(std::ostream &os) const;
private:
/**
* Get a reference to the type descriptor pointer from an object address. The type descriptor pointer
* for that address must already have been created before.
*
* @param ptr The object address (pointer to a managed object).
* @return A reference to the pointer to the type descriptor for the object.
*/
static TypePtr& typeDescriptorPtr(byte *ptr) noexcept {
return *reinterpret_cast<TypePtr*>(ptr - sizeof(TypePtr));
}
/**
* Try to allocate a block of memory for the specified type.
*
* @param type Type descriptor for the memory to allocate.
* @return A pointer to the allocated memory block, or `nullptr` if the allocation failed.
*/
void* tryAllocate(const TypeDescriptor &type) noexcept;
/**
* Merge free blocks and build a new free list.
*/
void mergeBlocks() noexcept;
/**
* Align the specified offset to the heap alignment.
*
* @param offset The offset to align.
* @return The offset aligned to the next larger multiple of this heap's alignment.
*/
std::size_t align(std::size_t offset) noexcept {
return (offset + mAlign - 1) & ~(mAlign - 1);
}
};
template <std::size_t HeapSize, std::size_t Align = alignof(std::max_align_t)>
class Heap : public HeapBase
{
// Make storage slightly bigger to allow for type descriptor pointer
alignas(Align)
byte mStorage[HeapSize + Align];
public:
/** The alignment of this heap. */
static constexpr auto alignment = Align;
/** The size of this heap. */
static constexpr auto size = HeapSize;
Heap() noexcept : HeapBase(mStorage, HeapSize + Align, Align) {
}
};
} // namespace ssw
#endif /* HEAP_HPP_ */
|
/*
* Copyright 2018 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
// Implementation of bed_reader.h
#include "third_party/nucleus/io/bed_reader.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "third_party/nucleus/protos/bed.pb.h"
#include "third_party/nucleus/util/utils.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "third_party/nucleus/platform/types.h"
namespace nucleus {
namespace tf = tensorflow;
// 256 KB read buffer.
constexpr int READER_BUFFER_SIZE = 256 * 1024;
// BED-specific attributes.
constexpr char BED_COMMENT_PREFIX[] = "#";
// -----------------------------------------------------------------------------
//
// Reader for BED format data.
//
// -----------------------------------------------------------------------------
namespace {
bool ValidNumBedFields(const int fields) {
return (fields == 3 || fields == 4 || fields == 5 || fields == 6 ||
fields == 8 || fields == 9 || fields == 12);
}
// Read the next non-comment line.
tf::Status NextNonCommentLine(TextReader& text_reader,
string* line) {
CHECK(line != nullptr);
string tmp;
do {
StatusOr<string> line_or = text_reader.ReadLine();
TF_RETURN_IF_ERROR(line_or.status());
tmp = line_or.ValueOrDie();
} while (absl::StartsWith(tmp, BED_COMMENT_PREFIX));
*line = tmp;
return tf::Status::OK();
}
tf::Status ConvertToPb(const string& line, const int desiredNumFields,
int* numTokensSeen,
nucleus::genomics::v1::BedRecord* record) {
CHECK(record != nullptr) << "BED record cannot be null";
record->Clear();
std::vector<string> tokens = absl::StrSplit(line, '\t');
int numTokens = static_cast<int>(tokens.size());
*numTokensSeen = numTokens;
if (!ValidNumBedFields(numTokens)) {
return tf::errors::Unknown("BED record has invalid number of fields");
}
int numFields =
desiredNumFields == 0 ? numTokens : std::min(numTokens, desiredNumFields);
int64 int64Value;
record->set_reference_name(tokens[0]);
CHECK(absl::SimpleAtoi(tokens[1], &int64Value));
record->set_start(int64Value);
CHECK(absl::SimpleAtoi(tokens[2], &int64Value));
record->set_end(int64Value);
if (numFields > 3) record->set_name(tokens[3]);
if (numFields > 4) {
double value;
CHECK(absl::SimpleAtod(tokens[4].c_str(), &value));
record->set_score(value);
}
if (numFields > 5) {
if (tokens[5] == "+")
record->set_strand(nucleus::genomics::v1::BedRecord::FORWARD_STRAND);
else if (tokens[5] == "-")
record->set_strand(nucleus::genomics::v1::BedRecord::REVERSE_STRAND);
else if (tokens[5] == ".")
record->set_strand(nucleus::genomics::v1::BedRecord::NO_STRAND);
else
return tf::errors::Unknown("Invalid BED record with unknown strand");
}
if (numFields > 7) {
CHECK(absl::SimpleAtoi(tokens[6], &int64Value));
record->set_thick_start(int64Value);
CHECK(absl::SimpleAtoi(tokens[7], &int64Value));
record->set_thick_end(int64Value);
}
if (numFields > 8) record->set_item_rgb(tokens[8]);
if (numFields >= 12) {
int32 int32Value;
CHECK(absl::SimpleAtoi(tokens[9], &int32Value));
record->set_block_count(int32Value);
record->set_block_sizes(tokens[10]);
record->set_block_starts(tokens[11]);
}
return tf::Status::OK();
}
// Peeks into the path to the first BED record and returns the number of fields
// in the record.
// NOTE: This is quite heavyweight. Reading upon initialization and then
// rewinding the stream to 0 would be a nicer solution.
tf::Status GetNumFields(const string& path, int* numFields) {
CHECK(numFields != nullptr);
string line;
StatusOr<std::unique_ptr<TextReader>> status_or = TextReader::FromFile(path);
TF_RETURN_IF_ERROR(status_or.status());
std::unique_ptr<TextReader> text_reader = std::move(status_or.ValueOrDie());
TF_RETURN_IF_ERROR(NextNonCommentLine(*text_reader, &line));
TF_RETURN_IF_ERROR(text_reader->Close());
std::vector<string> tokens = absl::StrSplit(line, '\t');
*numFields = static_cast<int>(tokens.size());
return tf::Status::OK();
}
} // namespace
// Iterable class for traversing all BED records in the file.
class BedFullFileIterable : public BedIterable {
public:
// Advance to the next record.
StatusOr<bool> Next(nucleus::genomics::v1::BedRecord* out) override;
// Constructor is invoked via BedReader::Iterate.
BedFullFileIterable(const BedReader* reader);
~BedFullFileIterable() override;
};
StatusOr<std::unique_ptr<BedReader>> BedReader::FromFile(
const string& bed_path,
const nucleus::genomics::v1::BedReaderOptions& options) {
int numFieldsInBed;
TF_RETURN_IF_ERROR(GetNumFields(bed_path, &numFieldsInBed));
nucleus::genomics::v1::BedHeader header;
header.set_num_fields(numFieldsInBed);
// Ensure options are valid.
if (options.num_fields() != 0 && (options.num_fields() > numFieldsInBed ||
!ValidNumBedFields(options.num_fields()))) {
return tf::errors::InvalidArgument(
"Invalid requested number of fields to parse");
}
StatusOr<std::unique_ptr<TextReader>> status_or =
TextReader::FromFile(bed_path);
TF_RETURN_IF_ERROR(status_or.status());
return std::unique_ptr<BedReader>(
new BedReader(std::move(status_or.ValueOrDie()), options, header));
}
BedReader::BedReader(std::unique_ptr<TextReader> text_reader,
const nucleus::genomics::v1::BedReaderOptions& options,
const nucleus::genomics::v1::BedHeader& header)
: options_(options), header_(header), text_reader_(std::move(text_reader))
{}
BedReader::~BedReader() {
if (text_reader_) {
TF_CHECK_OK(Close());
}
}
tf::Status BedReader::Close() {
if (!text_reader_) {
return tf::errors::FailedPrecondition("BedReader already closed");
}
tf::Status status = text_reader_->Close();
text_reader_ = nullptr;
return status;
}
// Ensures the number of fields is consistent across all records in the BED.
tf::Status BedReader::Validate(const int numTokens) const {
if (header_.num_fields() != numTokens) {
return tf::errors::Unknown(
"Invalid BED with varying number of fields in file");
}
return tf::Status::OK();
}
StatusOr<std::shared_ptr<BedIterable>> BedReader::Iterate() const {
if (!text_reader_)
return tf::errors::FailedPrecondition("Cannot Iterate a closed BedReader.");
return StatusOr<std::shared_ptr<BedIterable>>(
MakeIterable<BedFullFileIterable>(this));
}
// Iterable class definitions.
StatusOr<bool> BedFullFileIterable::Next(
nucleus::genomics::v1::BedRecord* out) {
TF_RETURN_IF_ERROR(CheckIsAlive());
const BedReader* bed_reader = static_cast<const BedReader*>(reader_);
string line;
tf::Status status = NextNonCommentLine(*bed_reader->text_reader_, &line);
if (tf::errors::IsOutOfRange(status)) {
return false;
} else if (!status.ok()) {
return status;
}
int numTokens;
TF_RETURN_IF_ERROR(
ConvertToPb(line, bed_reader->Options().num_fields(), &numTokens, out));
TF_RETURN_IF_ERROR(bed_reader->Validate(numTokens));
return true;
}
BedFullFileIterable::~BedFullFileIterable() {}
BedFullFileIterable::BedFullFileIterable(const BedReader* reader)
: Iterable(reader) {}
} // namespace nucleus
nucleus: Remove unused constant (nit)
PiperOrigin-RevId: 199496113
/*
* Copyright 2018 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
// Implementation of bed_reader.h
#include "third_party/nucleus/io/bed_reader.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "third_party/nucleus/protos/bed.pb.h"
#include "third_party/nucleus/util/utils.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "third_party/nucleus/platform/types.h"
namespace nucleus {
namespace tf = tensorflow;
// BED-specific attributes.
constexpr char BED_COMMENT_PREFIX[] = "#";
// -----------------------------------------------------------------------------
//
// Reader for BED format data.
//
// -----------------------------------------------------------------------------
namespace {
bool ValidNumBedFields(const int fields) {
return (fields == 3 || fields == 4 || fields == 5 || fields == 6 ||
fields == 8 || fields == 9 || fields == 12);
}
// Read the next non-comment line.
tf::Status NextNonCommentLine(TextReader& text_reader,
string* line) {
CHECK(line != nullptr);
string tmp;
do {
StatusOr<string> line_or = text_reader.ReadLine();
TF_RETURN_IF_ERROR(line_or.status());
tmp = line_or.ValueOrDie();
} while (absl::StartsWith(tmp, BED_COMMENT_PREFIX));
*line = tmp;
return tf::Status::OK();
}
tf::Status ConvertToPb(const string& line, const int desiredNumFields,
int* numTokensSeen,
nucleus::genomics::v1::BedRecord* record) {
CHECK(record != nullptr) << "BED record cannot be null";
record->Clear();
std::vector<string> tokens = absl::StrSplit(line, '\t');
int numTokens = static_cast<int>(tokens.size());
*numTokensSeen = numTokens;
if (!ValidNumBedFields(numTokens)) {
return tf::errors::Unknown("BED record has invalid number of fields");
}
int numFields =
desiredNumFields == 0 ? numTokens : std::min(numTokens, desiredNumFields);
int64 int64Value;
record->set_reference_name(tokens[0]);
CHECK(absl::SimpleAtoi(tokens[1], &int64Value));
record->set_start(int64Value);
CHECK(absl::SimpleAtoi(tokens[2], &int64Value));
record->set_end(int64Value);
if (numFields > 3) record->set_name(tokens[3]);
if (numFields > 4) {
double value;
CHECK(absl::SimpleAtod(tokens[4].c_str(), &value));
record->set_score(value);
}
if (numFields > 5) {
if (tokens[5] == "+")
record->set_strand(nucleus::genomics::v1::BedRecord::FORWARD_STRAND);
else if (tokens[5] == "-")
record->set_strand(nucleus::genomics::v1::BedRecord::REVERSE_STRAND);
else if (tokens[5] == ".")
record->set_strand(nucleus::genomics::v1::BedRecord::NO_STRAND);
else
return tf::errors::Unknown("Invalid BED record with unknown strand");
}
if (numFields > 7) {
CHECK(absl::SimpleAtoi(tokens[6], &int64Value));
record->set_thick_start(int64Value);
CHECK(absl::SimpleAtoi(tokens[7], &int64Value));
record->set_thick_end(int64Value);
}
if (numFields > 8) record->set_item_rgb(tokens[8]);
if (numFields >= 12) {
int32 int32Value;
CHECK(absl::SimpleAtoi(tokens[9], &int32Value));
record->set_block_count(int32Value);
record->set_block_sizes(tokens[10]);
record->set_block_starts(tokens[11]);
}
return tf::Status::OK();
}
// Peeks into the path to the first BED record and returns the number of fields
// in the record.
// NOTE: This is quite heavyweight. Reading upon initialization and then
// rewinding the stream to 0 would be a nicer solution.
tf::Status GetNumFields(const string& path, int* numFields) {
CHECK(numFields != nullptr);
string line;
StatusOr<std::unique_ptr<TextReader>> status_or = TextReader::FromFile(path);
TF_RETURN_IF_ERROR(status_or.status());
std::unique_ptr<TextReader> text_reader = std::move(status_or.ValueOrDie());
TF_RETURN_IF_ERROR(NextNonCommentLine(*text_reader, &line));
TF_RETURN_IF_ERROR(text_reader->Close());
std::vector<string> tokens = absl::StrSplit(line, '\t');
*numFields = static_cast<int>(tokens.size());
return tf::Status::OK();
}
} // namespace
// Iterable class for traversing all BED records in the file.
class BedFullFileIterable : public BedIterable {
public:
// Advance to the next record.
StatusOr<bool> Next(nucleus::genomics::v1::BedRecord* out) override;
// Constructor is invoked via BedReader::Iterate.
BedFullFileIterable(const BedReader* reader);
~BedFullFileIterable() override;
};
StatusOr<std::unique_ptr<BedReader>> BedReader::FromFile(
const string& bed_path,
const nucleus::genomics::v1::BedReaderOptions& options) {
int numFieldsInBed;
TF_RETURN_IF_ERROR(GetNumFields(bed_path, &numFieldsInBed));
nucleus::genomics::v1::BedHeader header;
header.set_num_fields(numFieldsInBed);
// Ensure options are valid.
if (options.num_fields() != 0 && (options.num_fields() > numFieldsInBed ||
!ValidNumBedFields(options.num_fields()))) {
return tf::errors::InvalidArgument(
"Invalid requested number of fields to parse");
}
StatusOr<std::unique_ptr<TextReader>> status_or =
TextReader::FromFile(bed_path);
TF_RETURN_IF_ERROR(status_or.status());
return std::unique_ptr<BedReader>(
new BedReader(std::move(status_or.ValueOrDie()), options, header));
}
BedReader::BedReader(std::unique_ptr<TextReader> text_reader,
const nucleus::genomics::v1::BedReaderOptions& options,
const nucleus::genomics::v1::BedHeader& header)
: options_(options), header_(header), text_reader_(std::move(text_reader))
{}
BedReader::~BedReader() {
if (text_reader_) {
TF_CHECK_OK(Close());
}
}
tf::Status BedReader::Close() {
if (!text_reader_) {
return tf::errors::FailedPrecondition("BedReader already closed");
}
tf::Status status = text_reader_->Close();
text_reader_ = nullptr;
return status;
}
// Ensures the number of fields is consistent across all records in the BED.
tf::Status BedReader::Validate(const int numTokens) const {
if (header_.num_fields() != numTokens) {
return tf::errors::Unknown(
"Invalid BED with varying number of fields in file");
}
return tf::Status::OK();
}
StatusOr<std::shared_ptr<BedIterable>> BedReader::Iterate() const {
if (!text_reader_)
return tf::errors::FailedPrecondition("Cannot Iterate a closed BedReader.");
return StatusOr<std::shared_ptr<BedIterable>>(
MakeIterable<BedFullFileIterable>(this));
}
// Iterable class definitions.
StatusOr<bool> BedFullFileIterable::Next(
nucleus::genomics::v1::BedRecord* out) {
TF_RETURN_IF_ERROR(CheckIsAlive());
const BedReader* bed_reader = static_cast<const BedReader*>(reader_);
string line;
tf::Status status = NextNonCommentLine(*bed_reader->text_reader_, &line);
if (tf::errors::IsOutOfRange(status)) {
return false;
} else if (!status.ok()) {
return status;
}
int numTokens;
TF_RETURN_IF_ERROR(
ConvertToPb(line, bed_reader->Options().num_fields(), &numTokens, out));
TF_RETURN_IF_ERROR(bed_reader->Validate(numTokens));
return true;
}
BedFullFileIterable::~BedFullFileIterable() {}
BedFullFileIterable::BedFullFileIterable(const BedReader* reader)
: Iterable(reader) {}
} // namespace nucleus
|
/*****************************************************************************
*
* GARGOYLE_PSCAND: Gargoyle Port Scan Detector
*
* main analysis daemon
*
* Copyright (c) 2016 - 2017, Bayshore Networks, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 <stdexcept>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <errno.h>
#include <ctype.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>
#include <netinet/in.h>
#include "sqlite_wrapper_api.h"
#include "iptables_wrapper_api.h"
#include "singleton.h"
#include "gargoyle_config_vals.h"
std::vector<int> IPTABLES_ENTRIES;
size_t PORT_SCAN_THRESHOLD = 15;
size_t SINGLE_IP_SCAN_THRESHOLD = 6;
size_t OVERALL_PORT_SCAN_THRESHOLD = 8;
// 8 hours
size_t LAST_SEEN_DELTA = 28800;
volatile sig_atomic_t stop;
void handle_signal (int signum) {
stop = 1;
syslog(LOG_INFO | LOG_LOCAL6, "%s: %d, %s", SIGNAL_CAUGHT_SYSLOG, signum, PROG_TERM_SYSLOG);
exit(0);
}
//bool exists_in_iptables_entries(std::string s) {
bool exists_in_iptables_entries(int s) {
std::vector<int>::const_iterator iter;
iter = std::find(IPTABLES_ENTRIES.begin(), IPTABLES_ENTRIES.end(), s);
if (iter != IPTABLES_ENTRIES.end()) {
//std::cout << *iter << " is on position " << (iter - IPTABLES_ENTRIES.begin() + 1);
return true;
} else {
return false;
}
}
//void add_to_iptables_entries(std::string s) {
void add_to_iptables_entries(int s) {
if (exists_in_iptables_entries(s) == false)
IPTABLES_ENTRIES.push_back(s);
}
void do_block_actions(const char *the_ip, int the_ix, int detection_type = 0) {
if (the_ip and the_ix) {
size_t ret;
int tstamp;
tstamp = (int) time(NULL);
ret = iptables_add_drop_rule_to_chain(GARGOYLE_CHAIN_NAME, the_ip);
syslog(LOG_INFO | LOG_LOCAL6, "%s-%s=\"%s\" %s=\"%d\" %s=\"%d\"",
BLOCKED_SYSLOG, VIOLATOR_SYSLOG, the_ip, DETECTION_TYPE_SYSLOG,
detection_type, TIMESTAMP_SYSLOG, tstamp);
// add to DB
add_detected_host(the_ix, tstamp);
// so that we dont have to deal with duplicate data
add_to_iptables_entries(the_ix);
}
}
/*
* one port, too many hits from one host
*/
void query_for_single_port_hits_last_seen() {
int ret;
int row_ix;
int host_ix;
int port_num;
int hit_count;
int iter_cnt;
int iter_cnt2;
int now;
int first_seen;
int last_seen;
const char *tok1 = ">";
char *token1;
char *token1_save;
char *token2;
char *token2_save;
const char *tok2 = ":";
char *token3;
char *token3_save;
char *token4;
char *token4_save;
//char list_of_ports[(size_t)SMALL_DEST_BUF];
size_t list_ports_dst_sz = SMALL_DEST_BUF;
char *list_of_ports = (char*) malloc(list_ports_dst_sz+1);
ret = get_unique_list_of_ports(list_of_ports, list_ports_dst_sz);
size_t list_hosts_dst_sz = SMALL_DEST_BUF;
char *l_hosts = (char*) malloc(list_hosts_dst_sz+1);
token1 = strtok_r(list_of_ports, tok1, &token1_save);
while (token1 != NULL) {
*l_hosts = 0;
get_all_host_one_port_threshold(atoi(token1), PORT_SCAN_THRESHOLD, l_hosts, list_hosts_dst_sz);
if (strlen(l_hosts) > 0) {
/*
std::cout << std::endl << token1 << std::endl;
std::cout << l_hosts << std::endl << std::endl;
*/
//std::cout << "LHOSTS: " << l_hosts << std::endl << std::endl;
token2 = strtok_r(l_hosts, tok1, &token2_save);
while (token2 != NULL) {
/*
std::cout << "TOKEN2: " << token2 << " - " << iter_cnt
<< std::endl;
*/
token3 = strtok_r(token2, tok2, &token3_save);
iter_cnt = 0;
while (token3 != NULL) {
if (iter_cnt == 0) {
row_ix = atoi(token3);
} else if (iter_cnt == 1) {
host_ix = atoi(token3);
} else if (iter_cnt == 2) {
port_num = atoi(token3);
} else if (iter_cnt == 3) {
hit_count = atoi(token3);
}
iter_cnt++;
token3 = strtok_r(NULL, tok2, &token3_save);
}
/*
std::cout << "ROW/HOST/PORT/CNT: " << row_ix << " - " << host_ix
<< " - " << port_num << " - " << hit_count << std::endl;
*/
if (exists_in_iptables_entries(host_ix) == false) {
size_t get_all_dst_sz = LOCAL_BUF_SZ;
char *h_all = (char*) malloc(get_all_dst_sz+1);
get_host_all_by_ix(host_ix, h_all, get_all_dst_sz);
//std::cout << h_all << std::endl;
char *host_ip = (char*) malloc(60);
iter_cnt2 = 0;
token4 = strtok_r(h_all, tok2, &token4_save);
while (token4 != NULL) {
if (iter_cnt2 == 0) {
} else if (iter_cnt2 == 1) {
//host_ip = atoi(token4);
snprintf(host_ip, 60, "%s", token4);
} else if (iter_cnt2 == 2) {
first_seen = atoi(token4);
} else if (iter_cnt2 == 3) {
last_seen = atoi(token4);
}
iter_cnt2++;
token4 = strtok_r(NULL, tok2, &token4_save);
}
//tmp_host_ix,host_ip,first_seen,last_seen = h_all.value.split(':')
/*
std::cout << host_ip << " - " << first_seen << " - "
<< last_seen << std::endl << std::endl;
*/
now = (int) time(NULL);
if ((now - last_seen) <= LAST_SEEN_DELTA) {
/*
* !! ENFORCE
* if we are here then this host violated the
* acceptable number of port hits (for one port per host).
* did we see this host less than LAST_SEEN_DELTA hours ago?
* if so block this bitch
*/
do_block_actions(host_ip, host_ix, 7);
}
free(h_all);
free(host_ip);
}
token2 = strtok_r(NULL, tok1, &token2_save);
}
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
free(list_of_ports);
free(l_hosts);
}
void query_for_multiple_ports_hits_last_seen() {
int ret;
int row_ix;
int host_ix;
int first_seen;
int last_seen;
int iter_cnt;
int now;
int hit_cnt_resp;
int l_count;
const char *tok1 = ">";
char *token1;
char *token1_save;
const char *tok2 = ":";
char *token2;
char *token2_save;
size_t dst_buf_sz = MEDIUM_DEST_BUF;
char *hosts_all_buf = (char*) malloc(dst_buf_sz+1);
char *host_ip = (char*) malloc(60);
ret = get_hosts_all(hosts_all_buf, dst_buf_sz);
/*
std::cout << hosts_all_buf << std::endl;
std::cout << strlen(hosts_all_buf) << std::endl;
*/
if (ret == 0) {
token1 = strtok_r(hosts_all_buf, tok1, &token1_save);
while (token1 != NULL) {
iter_cnt =0;
token2 = strtok_r(token1, tok2, &token2_save);
while (token2 != NULL) {
if (iter_cnt == 0) {
host_ix = atoi(token2);
} else if (iter_cnt == 1) {
snprintf(host_ip, 60, "%s", token2);
} else if (iter_cnt == 2) {
first_seen = atoi(token2);
} else if (iter_cnt == 3) {
last_seen = atoi(token2);
}
iter_cnt++;
token2 = strtok_r(NULL, tok2, &token2_save);
}
/*
std::cout << host_ix << " - " << host_ip << " - " << first_seen << " - "
<< last_seen << std::endl << std::endl;
*/
if (exists_in_iptables_entries(host_ix) == false) {
now = (int) time(NULL);
if ((now - last_seen) <= LAST_SEEN_DELTA) {
hit_cnt_resp = 0;
hit_cnt_resp = get_total_hit_count_one_host_by_ix(host_ix);
if (hit_cnt_resp >= SINGLE_IP_SCAN_THRESHOLD) {
/*
* !! ENFORCE - if more than SINGLE_IP_SCAN_THRESHOLD ports
* were scanned by this src ip then block this bitch
*
* do this by row count from the DB
*/
do_block_actions(host_ip, host_ix, 6);
} else {
/*
* !! ENFORCE - if the collective activity for
* this host surpasses a threshold then block this bitch.
*
* we already have host_ix and host_ip
* get a total count of port hits for this host
*/
l_count = 0;
l_count = get_one_host_hit_count_all_ports(host_ix);
if (l_count > OVERALL_PORT_SCAN_THRESHOLD) {
do_block_actions(host_ip, host_ix, 8);
}
}
}
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
}
free(hosts_all_buf);
free(host_ip);
}
void run_analysis() {
//syslog(LOG_INFO | LOG_LOCAL6, "%s %d", "running analysis process at", (int) time(NULL));
int iter_cnt;
int resp3;
const char *tok1 = ">";
char *token1;
char *token1_save;
const char *tok2 = ":";
char *token2;
char *token2_save;
size_t dst_buf_sz = SMALL_DEST_BUF;
char *l_hosts3 = (char*) malloc(dst_buf_sz+1);
resp3 = get_detected_hosts_all_active_unprocessed(l_hosts3, dst_buf_sz);
if (resp3 == 0) {
/*
std::cout << std::endl << resp3 << std::endl;
std::cout << l_hosts3 << std::endl;
*/
token1 = strtok_r(l_hosts3, tok1, &token1_save);
while (token1 != NULL) {
iter_cnt = 0;
//std::cout << token1 << std::endl;
token2 = strtok_r(token1, tok2, &token2_save);
while (token2 != NULL) {
//std::cout << token2 << " - " << iter_cnt << std::endl;
if (iter_cnt == 1) {
//IPTABLES_ENTRIES.push_back(token2);
add_to_iptables_entries(atoi(token2));
}
token2 = strtok_r(NULL, tok2, &token2_save);
iter_cnt++;
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
/*
std::cout << std::endl << std::endl;
for (std::vector<int>::const_iterator i = IPTABLES_ENTRIES.begin();
i != IPTABLES_ENTRIES.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl << std::endl;
std::cout << exists_in_iptables_entries(31880) << std::endl;
std::cout << exists_in_iptables_entries(31881) << std::endl;
*/
query_for_single_port_hits_last_seen();
query_for_multiple_ports_hits_last_seen();
}
free(l_hosts3);
}
int main() {
signal(SIGINT, handle_signal);
SingletonProcess singleton(6666);
if (!singleton()) {
std::cerr << "process running already. See " << singleton.GetLockFileName() << std::endl;
return 1;
}
while (!stop) {
run_analysis();
// every 30 minutes
sleep(1800);
}
return 0;
}
modified to get domain socket port from config file
/*****************************************************************************
*
* GARGOYLE_PSCAND: Gargoyle Port Scan Detector
*
* main analysis daemon
*
* Copyright (c) 2016 - 2017, Bayshore Networks, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 <stdexcept>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <errno.h>
#include <ctype.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>
#include <netinet/in.h>
#include "sqlite_wrapper_api.h"
#include "iptables_wrapper_api.h"
#include "singleton.h"
#include "gargoyle_config_vals.h"
std::vector<int> IPTABLES_ENTRIES;
size_t PORT_SCAN_THRESHOLD = 15;
size_t SINGLE_IP_SCAN_THRESHOLD = 6;
size_t OVERALL_PORT_SCAN_THRESHOLD = 8;
// 8 hours
size_t LAST_SEEN_DELTA = 28800;
volatile sig_atomic_t stop;
void handle_signal (int signum) {
stop = 1;
syslog(LOG_INFO | LOG_LOCAL6, "%s: %d, %s", SIGNAL_CAUGHT_SYSLOG, signum, PROG_TERM_SYSLOG);
exit(0);
}
//bool exists_in_iptables_entries(std::string s) {
bool exists_in_iptables_entries(int s) {
std::vector<int>::const_iterator iter;
iter = std::find(IPTABLES_ENTRIES.begin(), IPTABLES_ENTRIES.end(), s);
if (iter != IPTABLES_ENTRIES.end()) {
//std::cout << *iter << " is on position " << (iter - IPTABLES_ENTRIES.begin() + 1);
return true;
} else {
return false;
}
}
//void add_to_iptables_entries(std::string s) {
void add_to_iptables_entries(int s) {
if (exists_in_iptables_entries(s) == false)
IPTABLES_ENTRIES.push_back(s);
}
void do_block_actions(const char *the_ip, int the_ix, int detection_type = 0) {
if (the_ip and the_ix) {
size_t ret;
int tstamp;
tstamp = (int) time(NULL);
ret = iptables_add_drop_rule_to_chain(GARGOYLE_CHAIN_NAME, the_ip);
syslog(LOG_INFO | LOG_LOCAL6, "%s-%s=\"%s\" %s=\"%d\" %s=\"%d\"",
BLOCKED_SYSLOG, VIOLATOR_SYSLOG, the_ip, DETECTION_TYPE_SYSLOG,
detection_type, TIMESTAMP_SYSLOG, tstamp);
// add to DB
add_detected_host(the_ix, tstamp);
// so that we dont have to deal with duplicate data
add_to_iptables_entries(the_ix);
}
}
/*
* one port, too many hits from one host
*/
void query_for_single_port_hits_last_seen() {
int ret;
int row_ix;
int host_ix;
int port_num;
int hit_count;
int iter_cnt;
int iter_cnt2;
int now;
int first_seen;
int last_seen;
const char *tok1 = ">";
char *token1;
char *token1_save;
char *token2;
char *token2_save;
const char *tok2 = ":";
char *token3;
char *token3_save;
char *token4;
char *token4_save;
//char list_of_ports[(size_t)SMALL_DEST_BUF];
size_t list_ports_dst_sz = SMALL_DEST_BUF;
char *list_of_ports = (char*) malloc(list_ports_dst_sz+1);
ret = get_unique_list_of_ports(list_of_ports, list_ports_dst_sz);
size_t list_hosts_dst_sz = SMALL_DEST_BUF;
char *l_hosts = (char*) malloc(list_hosts_dst_sz+1);
token1 = strtok_r(list_of_ports, tok1, &token1_save);
while (token1 != NULL) {
*l_hosts = 0;
get_all_host_one_port_threshold(atoi(token1), PORT_SCAN_THRESHOLD, l_hosts, list_hosts_dst_sz);
if (strlen(l_hosts) > 0) {
/*
std::cout << std::endl << token1 << std::endl;
std::cout << l_hosts << std::endl << std::endl;
*/
//std::cout << "LHOSTS: " << l_hosts << std::endl << std::endl;
token2 = strtok_r(l_hosts, tok1, &token2_save);
while (token2 != NULL) {
/*
std::cout << "TOKEN2: " << token2 << " - " << iter_cnt
<< std::endl;
*/
token3 = strtok_r(token2, tok2, &token3_save);
iter_cnt = 0;
while (token3 != NULL) {
if (iter_cnt == 0) {
row_ix = atoi(token3);
} else if (iter_cnt == 1) {
host_ix = atoi(token3);
} else if (iter_cnt == 2) {
port_num = atoi(token3);
} else if (iter_cnt == 3) {
hit_count = atoi(token3);
}
iter_cnt++;
token3 = strtok_r(NULL, tok2, &token3_save);
}
/*
std::cout << "ROW/HOST/PORT/CNT: " << row_ix << " - " << host_ix
<< " - " << port_num << " - " << hit_count << std::endl;
*/
if (exists_in_iptables_entries(host_ix) == false) {
size_t get_all_dst_sz = LOCAL_BUF_SZ;
char *h_all = (char*) malloc(get_all_dst_sz+1);
get_host_all_by_ix(host_ix, h_all, get_all_dst_sz);
//std::cout << h_all << std::endl;
char *host_ip = (char*) malloc(60);
iter_cnt2 = 0;
token4 = strtok_r(h_all, tok2, &token4_save);
while (token4 != NULL) {
if (iter_cnt2 == 0) {
} else if (iter_cnt2 == 1) {
//host_ip = atoi(token4);
snprintf(host_ip, 60, "%s", token4);
} else if (iter_cnt2 == 2) {
first_seen = atoi(token4);
} else if (iter_cnt2 == 3) {
last_seen = atoi(token4);
}
iter_cnt2++;
token4 = strtok_r(NULL, tok2, &token4_save);
}
//tmp_host_ix,host_ip,first_seen,last_seen = h_all.value.split(':')
/*
std::cout << host_ip << " - " << first_seen << " - "
<< last_seen << std::endl << std::endl;
*/
now = (int) time(NULL);
if ((now - last_seen) <= LAST_SEEN_DELTA) {
/*
* !! ENFORCE
* if we are here then this host violated the
* acceptable number of port hits (for one port per host).
* did we see this host less than LAST_SEEN_DELTA hours ago?
* if so block this bitch
*/
do_block_actions(host_ip, host_ix, 7);
}
free(h_all);
free(host_ip);
}
token2 = strtok_r(NULL, tok1, &token2_save);
}
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
free(list_of_ports);
free(l_hosts);
}
void query_for_multiple_ports_hits_last_seen() {
int ret;
int row_ix;
int host_ix;
int first_seen;
int last_seen;
int iter_cnt;
int now;
int hit_cnt_resp;
int l_count;
const char *tok1 = ">";
char *token1;
char *token1_save;
const char *tok2 = ":";
char *token2;
char *token2_save;
size_t dst_buf_sz = MEDIUM_DEST_BUF;
char *hosts_all_buf = (char*) malloc(dst_buf_sz+1);
char *host_ip = (char*) malloc(60);
ret = get_hosts_all(hosts_all_buf, dst_buf_sz);
/*
std::cout << hosts_all_buf << std::endl;
std::cout << strlen(hosts_all_buf) << std::endl;
*/
if (ret == 0) {
token1 = strtok_r(hosts_all_buf, tok1, &token1_save);
while (token1 != NULL) {
iter_cnt =0;
token2 = strtok_r(token1, tok2, &token2_save);
while (token2 != NULL) {
if (iter_cnt == 0) {
host_ix = atoi(token2);
} else if (iter_cnt == 1) {
snprintf(host_ip, 60, "%s", token2);
} else if (iter_cnt == 2) {
first_seen = atoi(token2);
} else if (iter_cnt == 3) {
last_seen = atoi(token2);
}
iter_cnt++;
token2 = strtok_r(NULL, tok2, &token2_save);
}
/*
std::cout << host_ix << " - " << host_ip << " - " << first_seen << " - "
<< last_seen << std::endl << std::endl;
*/
if (exists_in_iptables_entries(host_ix) == false) {
now = (int) time(NULL);
if ((now - last_seen) <= LAST_SEEN_DELTA) {
hit_cnt_resp = 0;
hit_cnt_resp = get_total_hit_count_one_host_by_ix(host_ix);
if (hit_cnt_resp >= SINGLE_IP_SCAN_THRESHOLD) {
/*
* !! ENFORCE - if more than SINGLE_IP_SCAN_THRESHOLD ports
* were scanned by this src ip then block this bitch
*
* do this by row count from the DB
*/
do_block_actions(host_ip, host_ix, 6);
} else {
/*
* !! ENFORCE - if the collective activity for
* this host surpasses a threshold then block this bitch.
*
* we already have host_ix and host_ip
* get a total count of port hits for this host
*/
l_count = 0;
l_count = get_one_host_hit_count_all_ports(host_ix);
if (l_count > OVERALL_PORT_SCAN_THRESHOLD) {
do_block_actions(host_ip, host_ix, 8);
}
}
}
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
}
free(hosts_all_buf);
free(host_ip);
}
void run_analysis() {
//syslog(LOG_INFO | LOG_LOCAL6, "%s %d", "running analysis process at", (int) time(NULL));
int iter_cnt;
int resp3;
const char *tok1 = ">";
char *token1;
char *token1_save;
const char *tok2 = ":";
char *token2;
char *token2_save;
size_t dst_buf_sz = SMALL_DEST_BUF;
char *l_hosts3 = (char*) malloc(dst_buf_sz+1);
resp3 = get_detected_hosts_all_active_unprocessed(l_hosts3, dst_buf_sz);
if (resp3 == 0) {
/*
std::cout << std::endl << resp3 << std::endl;
std::cout << l_hosts3 << std::endl;
*/
token1 = strtok_r(l_hosts3, tok1, &token1_save);
while (token1 != NULL) {
iter_cnt = 0;
//std::cout << token1 << std::endl;
token2 = strtok_r(token1, tok2, &token2_save);
while (token2 != NULL) {
//std::cout << token2 << " - " << iter_cnt << std::endl;
if (iter_cnt == 1) {
//IPTABLES_ENTRIES.push_back(token2);
add_to_iptables_entries(atoi(token2));
}
token2 = strtok_r(NULL, tok2, &token2_save);
iter_cnt++;
}
token1 = strtok_r(NULL, tok1, &token1_save);
}
/*
std::cout << std::endl << std::endl;
for (std::vector<int>::const_iterator i = IPTABLES_ENTRIES.begin();
i != IPTABLES_ENTRIES.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl << std::endl;
std::cout << exists_in_iptables_entries(31880) << std::endl;
std::cout << exists_in_iptables_entries(31881) << std::endl;
*/
query_for_single_port_hits_last_seen();
query_for_multiple_ports_hits_last_seen();
}
free(l_hosts3);
}
int main() {
signal(SIGINT, handle_signal);
int analysis_port;
const char *config_file = ".gargoyle_config";
analysis_port = 0;
ConfigVariables cv;
if (cv.get_vals(config_file) == 0) {
analysis_port = cv.get_gargoyle_pscand_analysis_udp_port();
} else {
return 1;
}
if (analysis_port > 0) {
SingletonProcess singleton(analysis_port);
if (!singleton()) {
syslog(LOG_INFO | LOG_LOCAL6, "%s %s %s", "gargoyle_pscand_analysis", ALREADY_RUNNING, (singleton.GetLockFileName()).c_str());
return 1;
}
while (!stop) {
run_analysis();
// every 30 minutes by default
sleep(1800);
}
} else {
return 1;
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////
// Fast Fourier Transform
//
// fft X_k = \sum_{j=0}^{N - 1} x_k e^{-i * 2pi * j * k / N}
// ifft x_k = (1/N) * \sum_{j=0}^{N - 1} x_k e^{ i * 2pi * j * k / N}
// ex:
// [1, 2, 3, 4]
// [5, 6, 7, 8]
// 66: 5 * 1 + 6 * 4 + 7 * 3 + 8 * 2
// 68: 5 * 2 + 6 * 1 + 7 * 4 + 8 * 3
// 66: 5 * 3 + 6 * 2 + 7 * 1 + 8 * 4
// 60: 5 * 4 + 6 * 3 + 7 * 2 + 8 * 1
// Usage
// Given x[0...N-1], y[0...N-1]
// The convolution z[n] = sum of x[k]y[n-k] (k = 0,...,N-1)
// The index is cyclic: x[-1]=x[N-1], etc.
// To find z[] in O(NlgN)
// 1. Compute X = fft(x), Y = fft(y)
// 2. fft(z) = Z = X * Y (element-wise multiplication)
// 3. z = ifft(Z)
///////////////////////////////////////////////////////////////////////////////
#include <bits/stdc++.h>
using namespace std;
#define SZ(x) ((int)(x).size())
#define PB(x) push_back(x)
#define MEMSET(x,v) memset(x,v,sizeof(x))
#define REP(i,n) for(int (i)=0;(i)<(n);++(i))
typedef complex<double> cpx;
class FFT {
public:
static int rev(int n, int x) {
int r = 0;
for (int i = 0; i < n; i++)
if (x & (1 << i))
r |= (1 << (n - i - 1));
return r;
}
// Size of a must be a power of 2
static vector<cpx> fft(const vector<cpx> &f, bool inv) {
const double TWO_PI = 2 * acos(-1);
int n = SZ(f);
assert(__builtin_popcount(n) == 1);
vector<cpx> v(n);
int r = __builtin_ctz(n);
REP(i, n) v[rev(r, i)] = f[i];
REP(s, r) {
int m = 1 << (s + 1);
double a = (inv ? 1 : -1) * TWO_PI / double(m);
cpx b(cos(a), sin(a));
for (int k = 0; k < n; k += m) {
cpx w(1, 0);
int h = m >> 1;
for (int j = 0; j < h; j++) {
cpx t = w * v[k + j + h];
cpx u = v[k + j];
v[k + j] = u + t;
v[k + j + h] = u - t;
w *= b;
}
}
}
if (inv) for (int i = 0; i < n; i++) v[i] /= n;
return v;
}
static vector<cpx> multiply(vector<cpx> &a, vector<cpx> &b) {
int n = SZ(a);
vector<cpx> A = fft(a, false);
vector<cpx> B = fft(b, false);
REP(i, n) A[i] *= B[i];
return fft(A, true);
}
};
int main() {
vector<cpx> a = {1, 2, 3, 4};
vector<cpx> b = {5, 6, 7, 8};
vector<cpx> c = FFT::multiply(a, b);
for (auto x : c) cout << x << " ";
cout << endl;
return 0;
}
Update FFT.cpp
///////////////////////////////////////////////////////////////////////////////
// Fast Fourier Transform
//
// fft X_k = \sum_{j=0}^{N - 1} x_k e^{-i * 2pi * j * k / N}
// ifft x_k = (1/N) * \sum_{j=0}^{N - 1} x_k e^{ i * 2pi * j * k / N}
// ex:
// [1, 2, 3, 4]
// [5, 6, 7, 8]
// 66: 5 * 1 + 6 * 4 + 7 * 3 + 8 * 2
// 68: 5 * 2 + 6 * 1 + 7 * 4 + 8 * 3
// 66: 5 * 3 + 6 * 2 + 7 * 1 + 8 * 4
// 60: 5 * 4 + 6 * 3 + 7 * 2 + 8 * 1
// Usage
// Given x[0...N-1], y[0...N-1]
// The convolution z[n] = sum of x[k]y[n-k] (k = 0,...,N-1)
// The index is cyclic: x[-1]=x[N-1], etc.
// To find z[] in O(NlgN)
// 1. Compute X = fft(x), Y = fft(y)
// 2. fft(z) = Z = X * Y (element-wise multiplication)
// 3. z = ifft(Z)
///////////////////////////////////////////////////////////////////////////////
#include <bits/stdc++.h>
using namespace std;
#define SZ(x) ((int)(x).size())
#define PB(x) push_back(x)
#define MEMSET(x,v) memset(x,v,sizeof(x))
#define REP(i,n) for(int (i)=0;(i)<(n);++(i))
typedef complex<double> cpx;
class FFT {
public:
static int rev(int n, int x) {
int r = 0;
for (int i = 0; i < n; i++)
if (x & (1 << i))
r |= (1 << (n - i - 1));
return r;
}
// Size of a must be a power of 2
static vector<cpx> fft(const vector<cpx> &f, bool inv) {
const double TWO_PI = 2 * acos(-1);
int n = SZ(f);
assert(__builtin_popcount(n) == 1);
vector<cpx> v(n);
int r = __builtin_ctz(n);
REP(i, n) v[rev(r, i)] = f[i];
REP(s, r) {
int m = 1 << (s + 1);
double a = (inv ? 1 : -1) * TWO_PI / m;
cpx b(cos(a), sin(a));
for (int k = 0; k < n; k += m) {
cpx w(1, 0);
int h = m >> 1;
for (int j = 0; j < h; j++) {
cpx t = w * v[k + j + h];
cpx u = v[k + j];
v[k + j] = u + t;
v[k + j + h] = u - t;
w *= b;
}
}
}
if (inv) for (int i = 0; i < n; i++) v[i] /= n;
return v;
}
static vector<cpx> multiply(vector<cpx> &a, vector<cpx> &b) {
int n = SZ(a);
vector<cpx> A = fft(a, false);
vector<cpx> B = fft(b, false);
REP(i, n) A[i] *= B[i];
return fft(A, true);
}
};
int main() {
vector<cpx> a = {1, 2, 3, 4};
vector<cpx> b = {5, 6, 7, 8};
vector<cpx> c = FFT::multiply(a, b);
for (auto x : c) cout << x << " ";
cout << endl;
return 0;
}
|
/* openrtb_exchange_connector.cc
Eric Robert, 7 May 2013
Implementation of the OpenRTB exchange connector.
*/
#include "openrtb_exchange_connector.h"
#include "rtbkit/common/testing/exchange_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_source.h"
#include "rtbkit/plugins/exchange/http_auction_handler.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "openrtb/openrtb_parsing.h"
#include "soa/types/json_printing.h"
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "jml/utils/file_functions.h"
#include "jml/arch/info.h"
#include "jml/utils/rng.h"
using namespace Datacratic;
namespace Datacratic {
template<typename T, int I, typename S>
Json::Value jsonEncode(const ML::compact_vector<T, I, S> & vec)
{
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T, int I, typename S>
ML::compact_vector<T, I, S>
jsonDecode(const Json::Value & val, ML::compact_vector<T, I, S> *)
{
ExcAssert(val.isArray());
ML::compact_vector<T, I, S> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Datacratic
namespace OpenRTB {
template<typename T>
Json::Value jsonEncode(const OpenRTB::List<T> & vec)
{
using Datacratic::jsonEncode;
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T>
OpenRTB::List<T>
jsonDecode(const Json::Value & val, OpenRTB::List<T> *)
{
using Datacratic::jsonDecode;
ExcAssert(val.isArray());
OpenRTB::List<T> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace OpenRTB
namespace RTBKIT {
BOOST_STATIC_ASSERT(hasFromJson<Datacratic::Id>::value == true);
BOOST_STATIC_ASSERT(hasFromJson<int>::value == false);
/*****************************************************************************/
/* OPENRTB EXCHANGE CONNECTOR */
/*****************************************************************************/
OpenRTBExchangeConnector::
OpenRTBExchangeConnector(ServiceBase & owner, const std::string & name)
: HttpExchangeConnector(name, owner)
{
}
OpenRTBExchangeConnector::
OpenRTBExchangeConnector(const std::string & name,
std::shared_ptr<ServiceProxies> proxies)
: HttpExchangeConnector(name, proxies)
{
}
std::shared_ptr<BidRequest>
OpenRTBExchangeConnector::
parseBidRequest(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
std::shared_ptr<BidRequest> res;
// Check for JSON content-type
if (!header.contentType.empty()) {
static const std::string delimiter = ";";
std::string content = header.contentType.substr(0, header.contentType.find(delimiter));
#if 0
std::string charset = header.contentType.substr(header.contentType.find(delimiter), header.contentType.length());
#endif
if(content != "application/json") {
connection.sendErrorResponse("non-JSON request");
return res;
}
}
else {
connection.sendErrorResponse("non-JSON request");
return res;
}
// Check for the x-openrtb-version header
auto it = header.headers.find("x-openrtb-version");
if (it == header.headers.end()) {
connection.sendErrorResponse("no OpenRTB version header supplied");
return res;
}
// Check that it's version 2.1
std::string openRtbVersion = it->second;
if (openRtbVersion != "2.1") {
connection.sendErrorResponse("expected OpenRTB version 2.1; got " + openRtbVersion);
return res;
}
// Parse the bid request
ML::Parse_Context context("Bid Request", payload.c_str(), payload.size());
res.reset(OpenRtbBidRequestParser::parseBidRequest(context,
exchangeName(),
exchangeName()));
return res;
}
double
OpenRTBExchangeConnector::
getTimeAvailableMs(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
// Scan the payload quickly for the tmax parameter.
static const std::string toFind = "\"tmax\":";
std::string::size_type pos = payload.find(toFind);
if (pos == std::string::npos)
return 30.0;
int tmax = atoi(payload.c_str() + pos + toFind.length());
return tmax;
}
HttpResponse
OpenRTBExchangeConnector::
getResponse(const HttpAuctionHandler & connection,
const HttpHeader & requestHeader,
const Auction & auction) const
{
const Auction::Data * current = auction.getCurrentData();
if (current->hasError())
return getErrorResponse(connection, auction,
current->error + ": " + current->details);
OpenRTB::BidResponse response;
response.id = auction.id;
response.ext = getResponseExt(connection, auction);
// Create a spot for each of the bid responses
for (unsigned spotNum = 0; spotNum < current->responses.size(); ++spotNum) {
if (!current->hasValidResponse(spotNum))
continue;
setSeatBid(auction, spotNum, response);
}
if (response.seatbid.empty())
return HttpResponse(204, "none", "");
static Datacratic::DefaultDescription<OpenRTB::BidResponse> desc;
std::ostringstream stream;
StreamJsonPrintingContext context(stream);
desc.printJsonTyped(&response, context);
return HttpResponse(200, "application/json", stream.str());
}
Json::Value
OpenRTBExchangeConnector::
getResponseExt(const HttpAuctionHandler & connection,
const Auction & auction) const
{
return {};
}
HttpResponse
OpenRTBExchangeConnector::
getDroppedAuctionResponse(const HttpAuctionHandler & connection,
const std::string & reason) const
{
return HttpResponse(204, "application/json", "{}");
}
HttpResponse
OpenRTBExchangeConnector::
getErrorResponse(const HttpAuctionHandler & connection,
const Auction & auction,
const std::string & errorMessage) const
{
Json::Value response;
response["error"] = errorMessage;
return HttpResponse(400, response);
}
std::string
OpenRTBExchangeConnector::
getBidSourceConfiguration() const
{
auto suffix = std::to_string(port());
return ML::format("{\"type\":\"openrtb\",\"url\":\"%s\"}",
ML::fqdn_hostname(suffix) + ":" + suffix);
}
void
OpenRTBExchangeConnector::
setSeatBid(Auction const & auction,
int spotNum,
OpenRTB::BidResponse & response) const
{
const Auction::Data * data = auction.getCurrentData();
// Get the winning bid
auto & resp = data->winningResponse(spotNum);
int seatIndex = 0;
if(response.seatbid.empty()) {
response.seatbid.emplace_back();
}
OpenRTB::SeatBid & seatBid = response.seatbid.at(seatIndex);
// Add a new bid to the array
seatBid.bid.emplace_back();
// Put in the variable parts
auto & b = seatBid.bid.back();
b.cid = Id(resp.agent);
b.id = Id(auction.id, auction.request->imp[0].id);
b.impid = auction.request->imp[spotNum].id;
b.price.val = getAmountIn<CPM>(resp.price.maxPrice);
}
} // namespace RTBKIT
namespace {
using namespace RTBKIT;
struct Init {
Init() {
ExchangeConnector::registerFactory<OpenRTBExchangeConnector>();
}
} init;
}
made changes based on mathieus recommendation to check the delimiter
/* openrtb_exchange_connector.cc
Eric Robert, 7 May 2013
Implementation of the OpenRTB exchange connector.
*/
#include "openrtb_exchange_connector.h"
#include "rtbkit/common/testing/exchange_source.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_source.h"
#include "rtbkit/plugins/exchange/http_auction_handler.h"
#include "rtbkit/core/agent_configuration/agent_config.h"
#include "openrtb/openrtb_parsing.h"
#include "soa/types/json_printing.h"
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "jml/utils/file_functions.h"
#include "jml/arch/info.h"
#include "jml/utils/rng.h"
using namespace Datacratic;
namespace Datacratic {
template<typename T, int I, typename S>
Json::Value jsonEncode(const ML::compact_vector<T, I, S> & vec)
{
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T, int I, typename S>
ML::compact_vector<T, I, S>
jsonDecode(const Json::Value & val, ML::compact_vector<T, I, S> *)
{
ExcAssert(val.isArray());
ML::compact_vector<T, I, S> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace Datacratic
namespace OpenRTB {
template<typename T>
Json::Value jsonEncode(const OpenRTB::List<T> & vec)
{
using Datacratic::jsonEncode;
Json::Value result(Json::arrayValue);
for (unsigned i = 0; i < vec.size(); ++i)
result[i] = jsonEncode(vec[i]);
return result;
}
template<typename T>
OpenRTB::List<T>
jsonDecode(const Json::Value & val, OpenRTB::List<T> *)
{
using Datacratic::jsonDecode;
ExcAssert(val.isArray());
OpenRTB::List<T> res;
res.reserve(val.size());
for (unsigned i = 0; i < val.size(); ++i)
res.push_back(jsonDecode(val[i], (T*)0));
return res;
}
} // namespace OpenRTB
namespace RTBKIT {
BOOST_STATIC_ASSERT(hasFromJson<Datacratic::Id>::value == true);
BOOST_STATIC_ASSERT(hasFromJson<int>::value == false);
/*****************************************************************************/
/* OPENRTB EXCHANGE CONNECTOR */
/*****************************************************************************/
OpenRTBExchangeConnector::
OpenRTBExchangeConnector(ServiceBase & owner, const std::string & name)
: HttpExchangeConnector(name, owner)
{
}
OpenRTBExchangeConnector::
OpenRTBExchangeConnector(const std::string & name,
std::shared_ptr<ServiceProxies> proxies)
: HttpExchangeConnector(name, proxies)
{
}
std::shared_ptr<BidRequest>
OpenRTBExchangeConnector::
parseBidRequest(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
std::shared_ptr<BidRequest> res;
// Check for JSON content-type
if (!header.contentType.empty()) {
static const std::string delimiter = ";";
std::string::size_type posDelim = header.contentType.find(delimiter);
std::string content;
if(posDelim == std::string::npos)
content = header.contentType;
else {
std::string content = header.contentType.substr(0, posDelim);
#if 0
std::string charset = header.contentType.substr(posDelim, header.contentType.length());
#endif
}
if(content != "application/json") {
connection.sendErrorResponse("non-JSON request");
return res;
}
}
else {
connection.sendErrorResponse("non-JSON request");
return res;
}
// Check for the x-openrtb-version header
auto it = header.headers.find("x-openrtb-version");
if (it == header.headers.end()) {
connection.sendErrorResponse("no OpenRTB version header supplied");
return res;
}
// Check that it's version 2.1
std::string openRtbVersion = it->second;
if (openRtbVersion != "2.1") {
connection.sendErrorResponse("expected OpenRTB version 2.1; got " + openRtbVersion);
return res;
}
// Parse the bid request
ML::Parse_Context context("Bid Request", payload.c_str(), payload.size());
res.reset(OpenRtbBidRequestParser::parseBidRequest(context,
exchangeName(),
exchangeName()));
return res;
}
double
OpenRTBExchangeConnector::
getTimeAvailableMs(HttpAuctionHandler & connection,
const HttpHeader & header,
const std::string & payload)
{
// Scan the payload quickly for the tmax parameter.
static const std::string toFind = "\"tmax\":";
std::string::size_type pos = payload.find(toFind);
if (pos == std::string::npos)
return 30.0;
int tmax = atoi(payload.c_str() + pos + toFind.length());
return tmax;
}
HttpResponse
OpenRTBExchangeConnector::
getResponse(const HttpAuctionHandler & connection,
const HttpHeader & requestHeader,
const Auction & auction) const
{
const Auction::Data * current = auction.getCurrentData();
if (current->hasError())
return getErrorResponse(connection, auction,
current->error + ": " + current->details);
OpenRTB::BidResponse response;
response.id = auction.id;
response.ext = getResponseExt(connection, auction);
// Create a spot for each of the bid responses
for (unsigned spotNum = 0; spotNum < current->responses.size(); ++spotNum) {
if (!current->hasValidResponse(spotNum))
continue;
setSeatBid(auction, spotNum, response);
}
if (response.seatbid.empty())
return HttpResponse(204, "none", "");
static Datacratic::DefaultDescription<OpenRTB::BidResponse> desc;
std::ostringstream stream;
StreamJsonPrintingContext context(stream);
desc.printJsonTyped(&response, context);
return HttpResponse(200, "application/json", stream.str());
}
Json::Value
OpenRTBExchangeConnector::
getResponseExt(const HttpAuctionHandler & connection,
const Auction & auction) const
{
return {};
}
HttpResponse
OpenRTBExchangeConnector::
getDroppedAuctionResponse(const HttpAuctionHandler & connection,
const std::string & reason) const
{
return HttpResponse(204, "application/json", "{}");
}
HttpResponse
OpenRTBExchangeConnector::
getErrorResponse(const HttpAuctionHandler & connection,
const Auction & auction,
const std::string & errorMessage) const
{
Json::Value response;
response["error"] = errorMessage;
return HttpResponse(400, response);
}
std::string
OpenRTBExchangeConnector::
getBidSourceConfiguration() const
{
auto suffix = std::to_string(port());
return ML::format("{\"type\":\"openrtb\",\"url\":\"%s\"}",
ML::fqdn_hostname(suffix) + ":" + suffix);
}
void
OpenRTBExchangeConnector::
setSeatBid(Auction const & auction,
int spotNum,
OpenRTB::BidResponse & response) const
{
const Auction::Data * data = auction.getCurrentData();
// Get the winning bid
auto & resp = data->winningResponse(spotNum);
int seatIndex = 0;
if(response.seatbid.empty()) {
response.seatbid.emplace_back();
}
OpenRTB::SeatBid & seatBid = response.seatbid.at(seatIndex);
// Add a new bid to the array
seatBid.bid.emplace_back();
// Put in the variable parts
auto & b = seatBid.bid.back();
b.cid = Id(resp.agent);
b.id = Id(auction.id, auction.request->imp[0].id);
b.impid = auction.request->imp[spotNum].id;
b.price.val = getAmountIn<CPM>(resp.price.maxPrice);
}
} // namespace RTBKIT
namespace {
using namespace RTBKIT;
struct Init {
Init() {
ExchangeConnector::registerFactory<OpenRTBExchangeConnector>();
}
} init;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.