hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
9c561e082f3817638d932a746474b6b048b18591
58,556
c
C
src/SDK/boards/lpcxpresso55s28/usb_examples/usb_device_audio_speaker/bm/usb_device_descriptor.c
glassboard-dev/gl-umeasurement-firmware
ca0fb88f3ced84de9c88b256be0a6d5989c31cfe
[ "MIT" ]
1
2021-12-30T01:56:04.000Z
2021-12-30T01:56:04.000Z
src/SDK/boards/lpcxpresso55s28/usb_examples/usb_device_audio_speaker/bm/usb_device_descriptor.c
glassboard-dev/gl-umeasurement-firmware
ca0fb88f3ced84de9c88b256be0a6d5989c31cfe
[ "MIT" ]
null
null
null
src/SDK/boards/lpcxpresso55s28/usb_examples/usb_device_audio_speaker/bm/usb_device_descriptor.c
glassboard-dev/gl-umeasurement-firmware
ca0fb88f3ced84de9c88b256be0a6d5989c31cfe
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc. * Copyright 2016 - 2017, 2019 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "usb_device_config.h" #include "usb.h" #include "usb_device.h" #include "usb_device_class.h" #include "usb_device_audio.h" #include "usb_device_descriptor.h" #include "audio_speaker.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Prototypes ******************************************************************************/ /******************************************************************************* * Variables ******************************************************************************/ /* Audio generator stream endpoint information */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) usb_device_endpoint_struct_t g_UsbDeviceAudioSpeakerEndpoints[USB_AUDIO_STREAM_ENDPOINT_COUNT] = { /* Audio generator ISO OUT pipe */ { USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), USB_ENDPOINT_ISOCHRONOUS, FS_ISO_OUT_ENDP_PACKET_SIZE, /* The max packet size should be increased otherwise if host send data larger than max packet size will cause DMA error. */ FS_ISO_OUT_ENDP_INTERVAL, }, }; #else usb_device_endpoint_struct_t g_UsbDeviceAudioSpeakerEndpoints[USB_AUDIO_STREAM_ENDPOINT_COUNT] = { /* Audio generator ISO OUT pipe */ { USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), USB_ENDPOINT_ISOCHRONOUS, FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS *AUDIO_FORMAT_SIZE, /* The max packet size should be increased otherwise if host send data larger than max packet size will cause DMA error. */ FS_ISO_OUT_ENDP_INTERVAL, }, { USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), USB_ENDPOINT_ISOCHRONOUS, FS_ISO_FEEDBACK_ENDP_PACKET_SIZE, FS_ISO_FEEDBACK_ENDP_INTERVAL, }}; #endif /* Audio speaker control endpoint information */ usb_device_endpoint_struct_t g_UsbDeviceAudioControlEndpoints[USB_AUDIO_CONTROL_ENDPOINT_COUNT] = {{ USB_AUDIO_CONTROL_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), USB_ENDPOINT_INTERRUPT, FS_AUDIO_INTERRUPT_IN_PACKET_SIZE, FS_AUDIO_INTERRUPT_IN_INTERVAL, }}; /* Audio generator entity struct */ usb_device_audio_entity_struct_t g_UsbDeviceAudioEntity[] = { #if (USB_DEVICE_CONFIG_AUDIO_CLASS_2_0) {USB_AUDIO_SPEAKER_CONTROL_CLOCK_SOURCE_ENTITY_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_CLOCK_SOURCE_UNIT, 0U}, { USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_INPUT_TERMINAL, 0U, }, { USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_FEATURE_UNIT, 0U, }, {USB_AUDIO_SPEAKER_CONTROL_OUTPUT_TERMINAL_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_OUTPUT_TERMINAL, 0U}, #else { USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_INPUT_TERMINAL, 0U, }, { USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_FEATURE_UNIT, 0U, }, { USB_AUDIO_SPEAKER_CONTROL_OUTPUT_TERMINAL_ID, USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_OUTPUT_TERMINAL, 0U, }, #endif }; /* Audio speaker entity information */ usb_device_audio_entities_struct_t g_UsbDeviceAudioEntities = { g_UsbDeviceAudioEntity, sizeof(g_UsbDeviceAudioEntity) / sizeof(usb_device_audio_entity_struct_t), }; /* Audio speaker control interface information */ usb_device_interface_struct_t g_UsbDeviceAudioControInterface[] = {{ 0U, { USB_AUDIO_CONTROL_ENDPOINT_COUNT, g_UsbDeviceAudioControlEndpoints, }, &g_UsbDeviceAudioEntities, }}; /* Audio speaker stream interface information */ usb_device_interface_struct_t g_UsbDeviceAudioStreamInterface[] = { { 0U, { 0U, NULL, }, NULL, }, { 1U, { USB_AUDIO_STREAM_ENDPOINT_COUNT, g_UsbDeviceAudioSpeakerEndpoints, }, NULL, }, }; /* Define interfaces for audio speaker */ usb_device_interfaces_struct_t g_UsbDeviceAudioInterfaces[USB_AUDIO_SPEAKER_INTERFACE_COUNT] = { { USB_AUDIO_CLASS, /* Audio class code */ USB_SUBCLASS_AUDIOCONTROL, /* Audio control subclass code */ USB_AUDIO_PROTOCOL, /* Audio protocol code */ USB_AUDIO_CONTROL_INTERFACE_INDEX, /* The interface number of the Audio control */ g_UsbDeviceAudioControInterface, /* The handle of Audio control */ sizeof(g_UsbDeviceAudioControInterface) / sizeof(usb_device_interface_struct_t), }, { USB_AUDIO_CLASS, /* Audio class code */ USB_SUBCLASS_AUDIOSTREAM, /* Audio stream subclass code */ USB_AUDIO_PROTOCOL, /* Audio protocol code */ USB_AUDIO_STREAM_INTERFACE_INDEX, /* The interface number of the Audio control */ g_UsbDeviceAudioStreamInterface, /* The handle of Audio stream */ sizeof(g_UsbDeviceAudioStreamInterface) / sizeof(usb_device_interface_struct_t), } }; /* Define configurations for audio speaker */ usb_device_interface_list_t g_UsbDeviceAudioInterfaceList[USB_DEVICE_CONFIGURATION_COUNT] = { { USB_AUDIO_SPEAKER_INTERFACE_COUNT, g_UsbDeviceAudioInterfaces, }, }; /* Define class information for audio speaker */ usb_device_class_struct_t g_UsbDeviceAudioClass = { g_UsbDeviceAudioInterfaceList, kUSB_DeviceClassTypeAudio, USB_DEVICE_CONFIGURATION_COUNT, }; /* Define device descriptor */ USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE) uint8_t g_UsbDeviceDescriptor[] = { USB_DESCRIPTOR_LENGTH_DEVICE, /* Size of this descriptor in bytes */ USB_DESCRIPTOR_TYPE_DEVICE, /* DEVICE Descriptor Type */ USB_SHORT_GET_LOW(USB_DEVICE_SPECIFIC_BCD_VERSION), USB_SHORT_GET_HIGH(USB_DEVICE_SPECIFIC_BCD_VERSION), /* USB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). */ USB_DEVICE_CLASS, /* Class code (assigned by the USB-IF). */ USB_DEVICE_SUBCLASS, /* Subclass code (assigned by the USB-IF). */ USB_DEVICE_PROTOCOL, /* Protocol code (assigned by the USB-IF). */ USB_CONTROL_MAX_PACKET_SIZE, /* Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid) */ USB_SHORT_GET_LOW(USB_DEVICE_VID), USB_SHORT_GET_HIGH(USB_DEVICE_VID), /* Vendor ID (assigned by the USB-IF) */ USB_SHORT_GET_LOW(USB_DEVICE_PID), USB_SHORT_GET_HIGH(USB_DEVICE_PID), /* Product ID (assigned by the manufacturer) */ USB_SHORT_GET_LOW(USB_DEVICE_DEMO_BCD_VERSION), USB_SHORT_GET_HIGH(USB_DEVICE_DEMO_BCD_VERSION), /* Device release number in binary-coded decimal */ 0x01U, /* Index of string descriptor describing manufacturer */ 0x02U, /* Index of string descriptor describing product */ 0x00U, /* Index of string descriptor describing the device's serial number */ USB_DEVICE_CONFIGURATION_COUNT, /* Number of possible configurations */ }; USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE) uint8_t g_UsbDeviceConfigurationDescriptor[] = { #if (USB_DEVICE_CONFIG_AUDIO_CLASS_2_0) /* Configuration Descriptor Size - always 9 bytes*/ USB_DESCRIPTOR_LENGTH_CONFIGURE, /* Size of this descriptor in bytes */ USB_DESCRIPTOR_TYPE_CONFIGURE, /* CONFIGURATION Descriptor Type */ USB_SHORT_GET_LOW(USB_DESCRIPTOR_LENGTH_CONFIGURE + 0x08U + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH + 0x08U + 0x11U + #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x22U + #else 0x12U + #endif 0x0CU + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_DESCRIPTOR_LENGTH_INTERFACE + 0x10U + 0x06U + USB_AUDIO_STANDARD_AS_ISO_DATA_ENDPOINT_LENGTH + USB_AUDIO_CLASS_SPECIFIC_ENDPOINT_LENGTH #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) ), #else + USB_AUDIO_STANDARD_AS_ISO_FEEDBACK_ENDPOINT_LENGTH), /* Total length of data returned for this configuration. */ #endif USB_SHORT_GET_HIGH(USB_DESCRIPTOR_LENGTH_CONFIGURE + 0x08U + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH + 0x08U + 0x11U + #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x22U + #else 0x12U + #endif 0x0CU + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_DESCRIPTOR_LENGTH_INTERFACE + 0x10U + 0x06U + USB_AUDIO_STANDARD_AS_ISO_DATA_ENDPOINT_LENGTH + USB_AUDIO_CLASS_SPECIFIC_ENDPOINT_LENGTH #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) ), #else + USB_AUDIO_STANDARD_AS_ISO_FEEDBACK_ENDPOINT_LENGTH), /* Total length of data returned for this configuration. */ #endif USB_AUDIO_SPEAKER_INTERFACE_COUNT, /* Number of interfaces supported by this configuration */ USB_AUDIO_SPEAKER_CONFIGURE_INDEX, /* Value to use as an argument to the SetConfiguration() request to select this configuration */ 0x00U, /* Index of string descriptor describing this configuration */ (USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_D7_MASK) | (USB_DEVICE_CONFIG_SELF_POWER << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_SELF_POWERED_SHIFT) | (USB_DEVICE_CONFIG_REMOTE_WAKEUP << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_REMOTE_WAKEUP_SHIFT), /* Configuration characteristics D7: Reserved (set to one) D6: Self-powered D5: Remote Wakeup D4...0: Reserved (reset to zero) */ 0xFAU, /* Maximum power consumption of the USB * device from the bus in this specific * configuration when the device is fully * operational. Expressed in 2 mA units * (i.e., 50 = 100 mA). */ 0x08U, /* Descriptor size is 8 bytes */ USB_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION, /* INTERFACE_ASSOCIATION Descriptor Type */ 0x00U, /* The first interface number associated with this function is 0 */ 0x02U, /* The number of contiguous interfaces associated with this function is 2 */ USB_AUDIO_CLASS, /* The function belongs to the Audio Interface Class */ 0x00U, /* The function belongs to the SUBCLASS_UNDEFINED Subclass */ USB_AUDIO_PROTOCOL, /* Protocol code = 32 */ 0x00U, /* The Function string descriptor index is 0 */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ 0x00U, /* The number of this interface is 0 */ 0x00U, /* The value used to select the alternate setting for this interface is 0 */ 0x00U, /* The number of endpoints used by this interface is 0 (excluding endpoint zero) */ USB_AUDIO_CLASS, /* The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOCONTROL, /* The interface implements the AUDIOCONTROL Subclass */ USB_AUDIO_PROTOCOL, /* The Protocol code is 32 */ 0x02U, /* The interface string descriptor index is 2 */ USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_HEADER, /* HEADER descriptor subtype */ 0x00U, 0x02U, /* Audio Device compliant to the USB Audio specification version 2.00 */ 0x01U, /* DESKTOP_SPEAKER(0x01) : Indicating the primary use of this audio function */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x50U, 0x00U, /* Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Unit and Terminal descriptors. */ #else 0x40U, 0x00U, /* Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Unit and Terminal descriptors. */ #endif 0x00U, /* D1..0: Latency Control */ 0x08U, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_CLOCK_SOURCE_UNIT, /* CLOCK_SOURCE descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_CLOCK_SOURCE_ENTITY_ID, /* Constant uniquely identifying the Clock Source Entity within the audio funcion */ 0x01U, /* D1..0: 01: Internal Fixed Clock D2: 0 Clock is not synchronized to SOF D7..3: Reserved, should set to 0 */ 0x07U, /* D1..0: Clock Frequency Control is present and Host programmable D3..2: Clock Validity Control is present but read-only D7..4: Reserved, should set to 0 */ 0x00U, /* This Clock Source has no association */ 0x02U, /* Index of a string descriptor, describing the Clock Source Entity */ 0x11U, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_INPUT_TERMINAL, /* INPUT_TERMINAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* Constant uniquely identifying the Terminal within the audio function. This value is used in all requests to address this Terminal. */ 0x01U, 0x01U, /* A Terminal dealing with a signal carried over an endpoint in an AudioStreaming interface. The AudioStreaming interface descriptor points to the associated Terminal through the bTerminalLink field. */ 0x00U, /* This Input Terminal has no association */ USB_AUDIO_SPEAKER_CONTROL_CLOCK_SOURCE_ENTITY_ID, /* ID of the Clock Entity to which this Input Terminal is connected. */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x06U, /* This Terminal's output audio channel cluster has 6 logical output channels */ 0x3FU, 0x00U, 0x00U, 0x00U, /* Describes the spatial location of the logical channels:: Mono, no spatial location */ #else 0x02U, /* This Terminal's output audio channel cluster has 2 logical output channels */ 0x03U, 0x00U, 0x00U, 0x00U, /* Describes the spatial location of the logical channels:: Mono, no spatial location */ #endif 0x00U, /* Index of a string descriptor, describing the name of the first logical channel. */ 0x00U, 0x00U, /* bmControls D1..0: Copy Protect Control is not present D3..2: Connector Control is not present D5..4: Overload Control is not present D7..6: Cluster Control is not present D9..8: Underflow Control is not present D11..10: Overflow Control is not present D15..12: Reserved, should set to 0*/ 0x02U, /* Index of a string descriptor, describing the Input Terminal. */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x22U, /* Size of the descriptor, in bytes : 6 + (6 + 1) * 4 */ #else 0x12U, /* Size of the descriptor, in bytes : 6 + (2 + 1) * 4 */ #endif USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_FEATURE_UNIT, /* FEATURE_UNIT descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, /* Constant uniquely identifying the Unit within the audio function. This value is used in all requests to address this Unit. */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* ID of the Unit or Terminal to which this Feature Unit is connected. */ 0x0FU, 0x00U, 0x00U, 0x00U, /* logic channel 0 bmaControls(0)(0x0000000F): D1..0: Mute Control is present and host programmable D3..2: Volume Control is present and host programmable D5..4: Bass Control is not present D7..6: Mid Control is not present D9..8: Treble Control is not present D11..10: Graphic Equalizer Control is not present D13..12: Automatic Gain Control is not present D15..14: Delay Control is not present D17..16: Bass Control is not present D19..18: Loudness Control is not present D21..20: Input Gain Control is not present D23..22: Input Gain Pad Control is not present D25..24: Phase Inverter Control is not present D27..26: Underflow Control is not present D29..28: Overflow Control is not present D31..30: Reserved, should set to 0 */ 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 1. */ 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 2. */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 3. */ 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 4. */ 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 5. */ 0x00U, 0x00U, 0x00U, 0x00U, /* The Controls bitmap for logical channel 6. */ #endif 0x00U, /* Index of a string descriptor, describing this Feature Unit. */ 0x0CU, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_OUTPUT_TERMINAL, /* OUTPUT_TERMINAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_OUTPUT_TERMINAL_ID, /* Constant uniquely identifying the Terminal within the audio function. This value is used in all requests to address this Terminal. */ 0x01U, 0x03U, /* A Terminal dealing with a signal carried over an endpoint in an AudioStreaming interface. The AudioStreaming interface descriptor points to the associated Terminal through the bTerminalLink field. */ 0x00U, /* This Output Terminal has no association */ USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, /* ID of the Unit or Terminal to which this Terminal is connected. */ USB_AUDIO_SPEAKER_CONTROL_CLOCK_SOURCE_ENTITY_ID, /* ID of the Clock Entity to which this Output Terminal is connected */ 0x00U, 0x00U, /* bmControls: D1..0: Copy Protect Control is not present D3..2: Connector Control is not present D5..4: Overload Control is not present D7..6: Underflow Control is not present D9..8: Overflow Control is not present D15..10: Reserved, should set to 0 */ 0x00U, /* Index of a string descriptor, describing the Output Terminal. */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ 0x01U, /* The number of this interface is 1. */ 0x00U, /* The value used to select the alternate setting for this interface is 0 */ 0x00U, /* The number of endpoints used by this interface is 0 (excluding endpoint zero) */ USB_AUDIO_CLASS, /* The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOSTREAM, /* The interface implements the AUDIOSTREAMING Subclass */ USB_AUDIO_PROTOCOL, /* The Protocol code is 32 */ 0x02U, /* The interface string descriptor index is 2 */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ 0x01U, /* The number of this interface is 1. */ 0x01U, /* The value used to select the alternate setting for this interface is 1 */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) 0x01U, /* The number of endpoints used by this interface is 1 (excluding endpoint zero) */ #else 0x02U, /* The number of endpoints used by this interface is 2 (excluding endpoint zero) */ #endif USB_AUDIO_CLASS, /* The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOSTREAM, /* The interface implements the AUDIOSTREAMING Subclass */ USB_AUDIO_PROTOCOL, /* The Protocol code is 32 */ 0x02U, /* The interface string descriptor index is 2 */ 0x10U, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_STREAMING_AS_GENERAL, /* AS_GENERAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* The Terminal ID of the terminal to which this interface is connected */ 0x00U, /* bmControls : D1..0: Active Alternate Setting Control is not present D3..2: Valid Alternate Settings Control is not present D7..4: Reserved, should set to 0 */ USB_AUDIO_FORMAT_TYPE_I, /* The format type AudioStreaming interfae using is FORMAT_TYPE_I (0x01) */ 0x01U, 0x00U, 0x00U, 0x00U, /* The Audio Data Format that can be Used to communicate with this interface, D0:PCM */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x06U, /* Number of physical channels in the AS Interface audio channel cluster */ 0x3FU, 0x00U, 0x00U, 0x00U, /* Describes the spatial location of the logical channels: */ #else 0x02U, /* Number of physical channels in the AS Interface audio channel cluster */ 0x03U, 0x00U, 0x00U, 0x00U, /* Describes the spatial location of the logical channels: */ #endif 0x00U, /* Index of a string descriptor, describing the name of the first physical channel */ 0x06U, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_STREAMING_FORMAT_TYPE, /* FORMAT_TYPE descriptor subtype */ USB_AUDIO_FORMAT_TYPE_I, /* The format type AudioStreaming interfae using is FORMAT_TYPE_I (0x01) */ 0x02U, /* The number of bytes occupied by one audio subslot. Can be 1, 2, 3 or 4. */ 0x10U, /* The number of effectively used bits from the available bits in an audio subslot */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) USB_AUDIO_STANDARD_AS_ISO_DATA_ENDPOINT_LENGTH, /* Descriptor size is 7 bytes */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* ENDPOINT Descriptor Type*/ USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* This is an OUT endpoint with endpoint number 2 */ 0x0D, /* Types - Transfer: ISOCHRONOUS Sync: Async Usage: Data EP */ USB_SHORT_GET_LOW(FS_ISO_OUT_ENDP_PACKET_SIZE), USB_SHORT_GET_HIGH(FS_ISO_OUT_ENDP_PACKET_SIZE), /* Maximum packet size for this endpoint */ ISO_OUT_ENDP_INTERVAL, /* The polling interval value is every 1 Frames. If Hi-Speed, 1 uFrames/NAK */ #else USB_AUDIO_STANDARD_AS_ISO_DATA_ENDPOINT_LENGTH, /* Descriptor size is 7 bytes */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* ENDPOINT Descriptor Type*/ USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* This is an OUT endpoint with endpoint number 2 */ 0x05, /* Types - Transfer: ISOCHRONOUS Sync: Async Usage: Data EP */ USB_SHORT_GET_LOW(FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), USB_SHORT_GET_HIGH(FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), /* Maximum packet size for this endpoint */ ISO_OUT_ENDP_INTERVAL, /* The polling interval value is every 1 Frames. If Hi-Speed, 1 uFrames/NAK */ #endif /* Audio Class Specific ENDPOINT Descriptor */ USB_AUDIO_CLASS_SPECIFIC_ENDPOINT_LENGTH, /* Size of the descriptor, 8 bytes */ USB_AUDIO_STREAM_ENDPOINT_DESCRIPTOR, /* CS_ENDPOINT Descriptor Type */ USB_AUDIO_EP_GENERAL_DESCRIPTOR_SUBTYPE, /* AUDIO_EP_GENERAL descriptor subtype */ 0x00U, 0x00U, 0x00U, 0x00U, 0x00U, #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) #else /* Endpoint 3 Feedback ENDPOINT */ USB_AUDIO_STANDARD_AS_ISO_FEEDBACK_ENDPOINT_LENGTH, /* Descriptor size is 7 bytes */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* This is an IN endpoint with endpoint number 3 */ USB_ENDPOINT_ISOCHRONOUS | 0x10, /* Types - Transfer: ISOCHRONOUS Sync: Async Usage: Feedback EP */ #if defined(USB_DEVICE_WORKAROUND_AUDIO_20_WINDOWS) && (USB_DEVICE_WORKAROUND_AUDIO_20_WINDOWS > 0) 0x04, 0x00, /* wMaxPacketSize */ #else 0x03, 0x00, /* wMaxPacketSize */ #endif FS_ISO_FEEDBACK_ENDP_INTERVAL, /* interval polling(2^x ms) */ #endif #else /* Configuration Descriptor Size - always 9 bytes*/ USB_DESCRIPTOR_LENGTH_CONFIGURE, /* Size of this descriptor in bytes */ USB_DESCRIPTOR_TYPE_CONFIGURE, /* CONFIGURATION Descriptor Type */ USB_SHORT_GET_LOW(USB_DESCRIPTOR_LENGTH_CONFIGURE + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH + USB_AUDIO_INPUT_TERMINAL_ONLY_DESC_SIZE + #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(6, 1) #else USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(2, 1) #endif + USB_AUDIO_OUTPUT_TERMINAL_ONLY_DESC_SIZE + USB_DESCRIPTOR_LENGTH_AC_INTERRUPT_ENDPOINT + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_STREAMING_IFACE_DESC_SIZE + USB_AUDIO_STREAMING_TYPE_I_DESC_SIZE + USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH + USB_AUDIO_STREAMING_ENDP_DESC_SIZE #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) ), #else + USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH), /* Total length of data returned for this configuration. */ #endif USB_SHORT_GET_HIGH(USB_DESCRIPTOR_LENGTH_CONFIGURE + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH + USB_AUDIO_INPUT_TERMINAL_ONLY_DESC_SIZE + #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(6, 1) #else USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(2, 1) #endif + USB_AUDIO_OUTPUT_TERMINAL_ONLY_DESC_SIZE + USB_DESCRIPTOR_LENGTH_AC_INTERRUPT_ENDPOINT + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_DESCRIPTOR_LENGTH_INTERFACE + USB_AUDIO_STREAMING_IFACE_DESC_SIZE + USB_AUDIO_STREAMING_TYPE_I_DESC_SIZE + USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH + USB_AUDIO_STREAMING_ENDP_DESC_SIZE #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) ), #else + USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH), /* Total length of data returned for this configuration. */ #endif USB_AUDIO_SPEAKER_INTERFACE_COUNT, /* Number of interfaces supported by this configuration */ USB_AUDIO_SPEAKER_CONFIGURE_INDEX, /* Value to use as an argument to the SetConfiguration() request to select this configuration */ 0x00U, /* Index of string descriptor describing this configuration */ (USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_D7_MASK) | (USB_DEVICE_CONFIG_SELF_POWER << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_SELF_POWERED_SHIFT) | (USB_DEVICE_CONFIG_REMOTE_WAKEUP << USB_DESCRIPTOR_CONFIGURE_ATTRIBUTE_REMOTE_WAKEUP_SHIFT), /* Configuration characteristics D7: Reserved (set to one) D6: Self-powered D5: Remote Wakeup D4...0: Reserved (reset to zero) */ USB_DEVICE_MAX_POWER, /* Maximum power consumption of the USB * device from the bus in this specific * configuration when the device is fully * operational. Expressed in 2 mA units * (i.e., 50 = 100 mA). */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Size of this descriptor in bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ USB_AUDIO_CONTROL_INTERFACE_INDEX, /* Number of this interface. */ 0x00U, /* Value used to select this alternate setting for the interface identified in the prior field */ 0x01U, /* Number of endpoints used by this interface (excluding endpoint zero). */ USB_AUDIO_CLASS, /*The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOCONTROL, /*The interface implements the AUDIOCONTROL Subclass */ USB_AUDIO_PROTOCOL, /*The interface doesn't use any class-specific protocols */ 0x00U, /* The device doesn't have a string descriptor describing this iInterface */ /* Audio Class Specific type of INTERFACE Descriptor */ USB_AUDIO_CONTROL_INTERFACE_HEADER_LENGTH, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_HEADER, /* HEADER descriptor subtype */ 0x00U, 0x01U, /* Audio Device compliant to the USB Audio specification version 1.00 */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x2C, 0x00U, /* Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Unit and Terminal descriptors. */ #else 0x28, 0x00U, /* Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Unit and Terminal descriptors. */ #endif 0x01U, /* The number of AudioStreaming and MIDIStreaming interfaces in the Audio Interface Collection to which this AudioControl interface belongs */ 0x01U, /* The number of AudioStreaming and MIDIStreaming interfaces in the Audio Interface baNumber */ /* Audio Class Specific type of Input Terminal*/ USB_AUDIO_INPUT_TERMINAL_ONLY_DESC_SIZE, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_INPUT_TERMINAL, /* INPUT_TERMINAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* Constant uniquely identifying the Terminal within the audio function. This value is used in all requests to address this Terminal. */ 0x01U, 0x01, /* A generic microphone that does not fit under any of the other classifications. */ 0x00U, /* This Input Terminal has no association */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x06U, /* This Terminal's output audio channel cluster has 6 logical output channels */ 0x3FU, 0x00U, /* front left, front right, rear left, rear right, front center, subwoofer */ #else 0x02U, /* This Terminal's output audio channel cluster has 1 logical output channels */ 0x03U, 0x00U, /* Spatial locations present in the cluster */ #endif 0x00U, /* Index of a string descriptor, describing the name of the first logical channel. */ 0x00U, /* Index of a string descriptor, describing the Input Terminal. */ /* Audio Class Specific type of Feature Unit */ /* The USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE should be changed to 0x0a and Master channel controls should be changed to 0x03, 0x00U, 0x00U, if sampling rate is 48k */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(6, 1), /* Size of the descriptor, in bytes */ #else USB_AUDIO_FEATURE_UNIT_ONLY_DESC_SIZE(2, 1), /* Size of the descriptor, in bytes */ #endif USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_FEATURE_UNIT, /* FEATURE_UNIT descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, /* Constant uniquely identifying the Unit within the audio function. This value is used in all requests to address this Unit. */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* ID of the Unit or Terminal to which this Feature Unit is connected. */ 0x01U, /* Size in bytes of an element of the bmaControls() array: */ 0x03U, /* Master channel 0 controls */ 0x00U, /* channel 1 controls */ 0x00U, /* channel 2 controls */ #if defined(USB_AUDIO_CHANNEL5_1) && (USB_AUDIO_CHANNEL5_1 > 0U) 0x00U, /* channel 3 controls */ 0x00U, /* channel 4 controls */ 0x00U, /* channel 5 controls */ 0x00U, /* channel 6 controls */ #endif 0x00U, /* Index of a string descriptor, describing this Feature Unit. */ /* Audio Class Specific type of Output Terminal */ USB_AUDIO_OUTPUT_TERMINAL_ONLY_DESC_SIZE, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_CONTROL_OUTPUT_TERMINAL, /* OUTPUT_TERMINAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_OUTPUT_TERMINAL_ID, /* Constant uniquely identifying the Terminal within the audio function*/ 0x01U, 0x03U, /* A Terminal dealing with a signal carried over an endpoint in an AudioStreaming interface */ 0x00U, /* This Output Terminal has no association */ USB_AUDIO_SPEAKER_CONTROL_FEATURE_UNIT_ID, /* ID of the Unit or Terminal to which this Terminal is connected. */ 0x00U, /* Index of a string descriptor, describing the Output Terminal. */ USB_DESCRIPTOR_LENGTH_AC_INTERRUPT_ENDPOINT, /* Size of this descriptor, in bytes: 9U */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* ENDPOINT descriptor type */ USB_AUDIO_CONTROL_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* Endpoint address */ USB_ENDPOINT_INTERRUPT, /* Transfer type */ USB_SHORT_GET_LOW(FS_AUDIO_INTERRUPT_IN_PACKET_SIZE), USB_SHORT_GET_HIGH(FS_AUDIO_INTERRUPT_IN_PACKET_SIZE), /* Max Packet Size */ FS_AUDIO_INTERRUPT_IN_INTERVAL, /* Interval */ 0, 0, /* Audio Class Specific INTERFACE Descriptor, alternative interface 0 */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ USB_AUDIO_STREAM_INTERFACE_INDEX, /* The number of this interface is 1. */ 0x00U, /* The value used to select the alternate setting for this interface is 0 */ 0x00U, /* The number of endpoints used by this interface is 0 (excluding endpoint zero) */ USB_AUDIO_CLASS, /* The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOSTREAM, /* The interface implements the AUDIOSTREAMING Subclass */ USB_AUDIO_PROTOCOL, /* The interface doesn't use any class-specific protocols */ 0x00U, /* The device doesn't have a string descriptor describing this iInterface */ /* Audio Class Specific INTERFACE Descriptor, alternative interface 1 */ USB_DESCRIPTOR_LENGTH_INTERFACE, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_INTERFACE, /* INTERFACE Descriptor Type */ USB_AUDIO_STREAM_INTERFACE_INDEX, /*The number of this interface is 1. */ 0x01U, /* The value used to select the alternate setting for this interface is 1 */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) 0x01U, /* The number of endpoints used by this interface is 1 (excluding endpoint zero) */ #else 0x02U, /* The number of endpoints used by this interface is 2 (excluding endpoint zero) */ #endif USB_AUDIO_CLASS, /* The interface implements the Audio Interface class */ USB_SUBCLASS_AUDIOSTREAM, /* The interface implements the AUDIOSTREAMING Subclass */ USB_AUDIO_PROTOCOL, /* The interface doesn't use any class-specific protocols */ 0x00U, /* The device doesn't have a string descriptor describing this iInterface */ /* Audio Class Specific CS INTERFACE Descriptor*/ USB_AUDIO_STREAMING_IFACE_DESC_SIZE, /* Size of the descriptor, in bytes */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* CS_INTERFACE Descriptor Type */ USB_DESCRIPTOR_SUBTYPE_AUDIO_STREAMING_AS_GENERAL, /* AS_GENERAL descriptor subtype */ USB_AUDIO_SPEAKER_CONTROL_INPUT_TERMINAL_ID, /* The Terminal ID of the Terminal to which the endpoint of this interface is connected. */ 0x01U, /* Delay introduced by the data path. Expressed in number of frames. */ 0x01U, 0x00U, /* PCM */ /* Audio Class Specific type I format INTERFACE Descriptor */ USB_AUDIO_STREAMING_TYPE_I_DESC_SIZE, /* bLength (11) */ USB_DESCRIPTOR_TYPE_AUDIO_CS_INTERFACE, /* bDescriptorType (CS_INTERFACE) */ USB_DESCRIPTOR_SUBTYPE_AUDIO_STREAMING_FORMAT_TYPE, /* DescriptorSubtype: AUDIO STREAMING FORMAT TYPE */ USB_AUDIO_FORMAT_TYPE_I, /* Format Type: Type I */ AUDIO_FORMAT_CHANNELS, /* Number of Channels: one channel */ AUDIO_FORMAT_SIZE, /* SubFrame Size: one byte per audio subframe */ AUDIO_FORMAT_BITS, /* Bit Resolution: 8 bits per sample */ 0x01U, /* One frequency supported */ /* 0x40, 0x1F,0x00U, 8 kHz */ TSAMFREQ2BYTES(AUDIO_SAMPLING_RATE_KHZ * 1000), /* 16 kHz */ /* 0x80,0xBB,0x00U, 48 kHz */ /* 0x00U, 0xFA,0x00U, 72 kHz */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) /* ENDPOINT Descriptor */ USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* Descriptor type (endpoint descriptor) */ USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* OUT endpoint address 1 */ USB_ENDPOINT_ISOCHRONOUS | 0x0CU, /* Isochronous endpoint and Synchronous*/ USB_SHORT_GET_LOW(FS_ISO_OUT_ENDP_PACKET_SIZE), USB_SHORT_GET_HIGH(FS_ISO_OUT_ENDP_PACKET_SIZE), /* 16 bytes */ FS_ISO_OUT_ENDP_INTERVAL, /* bInterval(0x01U): x ms */ 0x00U, /* Unused */ 0x00U, /* Synchronization Endpoint (if used) is endpoint 0x83 */ #else /* ENDPOINT Descriptor */ USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH, /* Descriptor size is 9 bytes */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* Descriptor type (endpoint descriptor) */ USB_AUDIO_SPEAKER_STREAM_ENDPOINT | (USB_OUT << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* OUT endpoint address 1 */ USB_ENDPOINT_ISOCHRONOUS | 0x04, /* Isochronous endpoint */ USB_SHORT_GET_LOW(FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), USB_SHORT_GET_HIGH(FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), /* 16 bytes */ FS_ISO_OUT_ENDP_INTERVAL, /* bInterval(0x01U): x ms */ 0x00U, /* Unused */ USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* Synchronization Endpoint (if used) is endpoint 0x83 */ #endif /* Audio Class Specific ENDPOINT Descriptor */ USB_AUDIO_STREAMING_ENDP_DESC_SIZE, /* Size of the descriptor, in bytes */ USB_AUDIO_STREAM_ENDPOINT_DESCRIPTOR, /* CS_ENDPOINT Descriptor Type */ USB_AUDIO_EP_GENERAL_DESCRIPTOR_SUBTYPE, /* AUDIO_EP_GENERAL descriptor subtype */ 0x00U, /* Bit 0: Sampling Frequency 0 Bit 1: Pitch 0 Bit 7: MaxPacketsOnly 0 */ 0x00U, /* Indicates the units used for the wLockDelay field: 0: Undefined */ 0x00U, 0x00U, /* Indicates the time it takes this endpoint to reliably lock its internal clock recovery circuitry */ #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) #else /* Endpoint 3 Feedback ENDPOINT */ USB_ENDPOINT_AUDIO_DESCRIPTOR_LENGTH, /* bLength */ USB_DESCRIPTOR_TYPE_ENDPOINT, /* bDescriptorType */ USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT | (USB_IN << USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT), /* This is an IN endpoint with endpoint number 3 */ USB_ENDPOINT_ISOCHRONOUS | 0x10, /* Types - Transfer: ISOCHRONOUS Sync: Async Usage: Feedback EP */ FS_ISO_FEEDBACK_ENDP_PACKET_SIZE, 0x00, /* wMaxPacketSize */ FS_ISO_FEEDBACK_ENDP_INTERVAL, /* interval polling(2^x ms) */ 0x05, /* bRefresh(32ms) */ 0x00, /* unused */ #endif #endif /* AUDIO_CLASS_2_0 */ }; /* Define string descriptor */ USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE) uint8_t g_UsbDeviceString0[] = { 2U + 2U, USB_DESCRIPTOR_TYPE_STRING, 0x09U, 0x04U, }; USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE) uint8_t g_UsbDeviceString1[] = { 2U + 2U * 18U, USB_DESCRIPTOR_TYPE_STRING, 'N', 0x00U, 'X', 0x00U, 'P', 0x00U, ' ', 0x00U, 'S', 0x00U, 'E', 0x00U, 'M', 0x00U, 'I', 0x00U, 'C', 0x00U, 'O', 0x00U, 'N', 0x00U, 'D', 0x00U, 'U', 0x00U, 'C', 0x00U, 'T', 0x00U, 'O', 0x00U, 'R', 0x00U, 'S', 0x00U, }; USB_DMA_INIT_DATA_ALIGN(USB_DATA_ALIGN_SIZE) uint8_t g_UsbDeviceString2[] = { 2U + 2U * 14U, USB_DESCRIPTOR_TYPE_STRING, 'U', 0x00U, 'S', 0x00U, 'B', 0x00U, ' ', 0x00U, 'A', 0x00U, 'U', 0x00U, 'D', 0x00U, 'I', 0x00U, 'O', 0x00U, ' ', 0x00U, 'D', 0x00U, 'E', 0x00U, 'M', 0x00U, 'O', 0x00U, }; uint32_t g_UsbDeviceStringDescriptorLength[USB_DEVICE_STRING_COUNT] = { sizeof(g_UsbDeviceString0), sizeof(g_UsbDeviceString1), sizeof(g_UsbDeviceString2), }; uint8_t *g_UsbDeviceStringDescriptorArray[USB_DEVICE_STRING_COUNT] = { g_UsbDeviceString0, g_UsbDeviceString1, g_UsbDeviceString2, }; usb_language_t g_UsbDeviceLanguage[USB_DEVICE_LANGUAGE_COUNT] = {{ g_UsbDeviceStringDescriptorArray, g_UsbDeviceStringDescriptorLength, (uint16_t)0x0409U, }}; usb_language_list_t g_UsbDeviceLanguageList = { g_UsbDeviceString0, sizeof(g_UsbDeviceString0), g_UsbDeviceLanguage, USB_DEVICE_LANGUAGE_COUNT, }; /******************************************************************************* * Code ******************************************************************************/ /*! * @brief USB device get device descriptor function. * * This function gets the device descriptor of the USB device. * * @param handle The USB device handle. * @param deviceDescriptor The pointer to the device descriptor structure. * * @return A USB error code or kStatus_USB_Success. */ usb_status_t USB_DeviceGetDeviceDescriptor(usb_device_handle handle, usb_device_get_device_descriptor_struct_t *deviceDescriptor) { deviceDescriptor->buffer = g_UsbDeviceDescriptor; deviceDescriptor->length = USB_DESCRIPTOR_LENGTH_DEVICE; return kStatus_USB_Success; } /*! * @brief USB device get configuration descriptor function. * * This function gets the configuration descriptor of the USB device. * * @param handle The USB device handle. * @param configurationDescriptor The pointer to the configuration descriptor structure. * * @return A USB error code or kStatus_USB_Success. */ usb_status_t USB_DeviceGetConfigurationDescriptor( usb_device_handle handle, usb_device_get_configuration_descriptor_struct_t *configurationDescriptor) { if (USB_AUDIO_SPEAKER_CONFIGURE_INDEX > configurationDescriptor->configuration) { configurationDescriptor->buffer = g_UsbDeviceConfigurationDescriptor; configurationDescriptor->length = USB_DESCRIPTOR_LENGTH_CONFIGURATION_ALL; return kStatus_USB_Success; } return kStatus_USB_InvalidRequest; } /*! * @brief USB device get string descriptor function. * * This function gets the string descriptor of the USB device. * * @param handle The USB device handle. * @param stringDescriptor The pointer to the string descriptor structure. * * @return A USB error code or kStatus_USB_Success. */ usb_status_t USB_DeviceGetStringDescriptor(usb_device_handle handle, usb_device_get_string_descriptor_struct_t *stringDescriptor) { if (stringDescriptor->stringIndex == 0U) { stringDescriptor->buffer = (uint8_t *)g_UsbDeviceLanguageList.languageString; stringDescriptor->length = g_UsbDeviceLanguageList.stringLength; } else { uint8_t languageId = 0U; uint8_t languageIndex = USB_DEVICE_STRING_COUNT; for (; languageId < USB_DEVICE_LANGUAGE_COUNT; languageId++) { if (stringDescriptor->languageId == g_UsbDeviceLanguageList.languageList[languageId].languageId) { if (stringDescriptor->stringIndex < USB_DEVICE_STRING_COUNT) { languageIndex = stringDescriptor->stringIndex; } break; } } if (USB_DEVICE_STRING_COUNT == languageIndex) { return kStatus_USB_InvalidRequest; } stringDescriptor->buffer = (uint8_t *)g_UsbDeviceLanguageList.languageList[languageId].string[languageIndex]; stringDescriptor->length = g_UsbDeviceLanguageList.languageList[languageId].length[languageIndex]; } return kStatus_USB_Success; } /* Due to the difference of HS and FS descriptors, the device descriptors and configurations need to be updated to match * current speed. * As the default, the device descriptors and configurations are configured by using FS parameters for both EHCI and * KHCI. * When the EHCI is enabled, the application needs to call this function to update device by using current speed. * The updated information includes endpoint max packet size, endpoint interval, etc. */ usb_status_t USB_DeviceSetSpeed(usb_device_handle handle, uint8_t speed) { usb_descriptor_union_t *descriptorHead; usb_descriptor_union_t *descriptorTail; descriptorHead = (usb_descriptor_union_t *)&g_UsbDeviceConfigurationDescriptor[0]; descriptorTail = (usb_descriptor_union_t *)(&g_UsbDeviceConfigurationDescriptor[USB_DESCRIPTOR_LENGTH_CONFIGURATION_ALL - 1U]); while (descriptorHead < descriptorTail) { if (descriptorHead->common.bDescriptorType == USB_DESCRIPTOR_TYPE_ENDPOINT) { if (USB_SPEED_HIGH == speed) { #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) if ((USB_AUDIO_SPEAKER_STREAM_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_OUT)) { descriptorHead->endpoint.bInterval = HS_ISO_OUT_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS((HS_ISO_OUT_ENDP_PACKET_SIZE), descriptorHead->endpoint.wMaxPacketSize); } #else if ((USB_AUDIO_SPEAKER_STREAM_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_OUT)) { descriptorHead->endpoint.bInterval = HS_ISO_OUT_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS( (HS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), descriptorHead->endpoint.wMaxPacketSize); } else if ((USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_IN)) { descriptorHead->endpoint.bInterval = HS_ISO_FEEDBACK_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(HS_ISO_FEEDBACK_ENDP_PACKET_SIZE, descriptorHead->endpoint.wMaxPacketSize); } #endif else { } } else { #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) if ((USB_AUDIO_SPEAKER_STREAM_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_OUT)) { descriptorHead->endpoint.bInterval = FS_ISO_OUT_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS((FS_ISO_OUT_ENDP_PACKET_SIZE), descriptorHead->endpoint.wMaxPacketSize); } #else if ((USB_AUDIO_SPEAKER_STREAM_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_OUT)) { descriptorHead->endpoint.bInterval = FS_ISO_OUT_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS( (FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE), descriptorHead->endpoint.wMaxPacketSize); } else if ((USB_AUDIO_SPEAKER_FEEDBACK_ENDPOINT == (descriptorHead->endpoint.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)) && ((descriptorHead->endpoint.bEndpointAddress >> USB_DESCRIPTOR_ENDPOINT_ADDRESS_DIRECTION_SHIFT) == USB_IN)) { descriptorHead->endpoint.bInterval = FS_ISO_FEEDBACK_ENDP_INTERVAL; USB_SHORT_TO_LITTLE_ENDIAN_ADDRESS(FS_ISO_FEEDBACK_ENDP_PACKET_SIZE, descriptorHead->endpoint.wMaxPacketSize); } #endif else { } } } descriptorHead = (usb_descriptor_union_t *)((uint8_t *)descriptorHead + descriptorHead->common.bLength); } if (USB_SPEED_HIGH == speed) { #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) g_UsbDeviceAudioSpeakerEndpoints[0].maxPacketSize = (HS_ISO_OUT_ENDP_PACKET_SIZE); g_UsbDeviceAudioSpeakerEndpoints[0].interval = (HS_ISO_OUT_ENDP_INTERVAL); #else g_UsbDeviceAudioSpeakerEndpoints[0].maxPacketSize = (HS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE); g_UsbDeviceAudioSpeakerEndpoints[0].interval = (HS_ISO_OUT_ENDP_INTERVAL); g_UsbDeviceAudioSpeakerEndpoints[1].maxPacketSize = HS_ISO_FEEDBACK_ENDP_PACKET_SIZE; g_UsbDeviceAudioSpeakerEndpoints[1].interval = HS_ISO_FEEDBACK_ENDP_INTERVAL; #endif } else { #if defined(USB_DEVICE_AUDIO_USE_SYNC_MODE) && (USB_DEVICE_AUDIO_USE_SYNC_MODE > 0U) g_UsbDeviceAudioSpeakerEndpoints[0].maxPacketSize = (FS_ISO_OUT_ENDP_PACKET_SIZE); g_UsbDeviceAudioSpeakerEndpoints[0].interval = (FS_ISO_OUT_ENDP_INTERVAL); #else g_UsbDeviceAudioSpeakerEndpoints[0].maxPacketSize = (FS_ISO_OUT_ENDP_PACKET_SIZE + AUDIO_FORMAT_CHANNELS * AUDIO_FORMAT_SIZE); g_UsbDeviceAudioSpeakerEndpoints[0].interval = (FS_ISO_OUT_ENDP_INTERVAL); g_UsbDeviceAudioSpeakerEndpoints[1].maxPacketSize = FS_ISO_FEEDBACK_ENDP_PACKET_SIZE; g_UsbDeviceAudioSpeakerEndpoints[1].interval = FS_ISO_FEEDBACK_ENDP_INTERVAL; #endif } return kStatus_USB_Success; }
54.521415
130
0.627468
807e8373800d2653b9fd65205a0941f4d60a60b9
2,277
h
C
shared_include/optimization/fitmodel/EnergyData.h
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
null
null
null
shared_include/optimization/fitmodel/EnergyData.h
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
2
2017-05-29T09:43:01.000Z
2017-05-29T09:50:05.000Z
shared_include/optimization/fitmodel/EnergyData.h
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
4
2017-05-17T11:56:02.000Z
2022-03-05T09:12:24.000Z
#ifndef __FIT_MODEL_ENERGY_DATA_H__ #define __FIT_MODEL_ENERGY_DATA_H__ #include <vector> #include <armadillo> #include "landmark/Landmark.h" #include "model/Model.h" #include "mesh/Mesh.h" namespace fitModel{ /* class that contains data that is set directly and * does not need to be derived */ class EnergyData{ public: /*--------------------------------------------------------------------------*/ EnergyData(const Model& model, const Mesh& target): model(model), target(target) { // initialize the weights to the mean weights this->speakerWeights = arma::vec( model.data().get_speaker_mode_dimension(), arma::fill::zeros); this->phonemeWeights = arma::vec( model.data().get_phoneme_mode_dimension(), arma::fill::zeros); this->model.convert().to_weights( this->speakerWeights, this->phonemeWeights); this->oldSpeakerWeights = this->speakerWeights; this->oldPhonemeWeights = this->phonemeWeights; } /*--------------------------------------------------------------------------*/ EnergyData(const Model& model): model(model) { update(); } /*--------------------------------------------------------------------------*/ void update() { // initialize the weights to the mean weights this->speakerWeights = arma::vec( model.data().get_speaker_mode_dimension(), arma::fill::zeros); this->phonemeWeights = arma::vec( model.data().get_phoneme_mode_dimension(), arma::fill::zeros); this->model.convert().to_weights( this->speakerWeights, this->phonemeWeights); this->oldSpeakerWeights = this->speakerWeights; this->oldPhonemeWeights = this->phonemeWeights; } /*--------------------------------------------------------------------------*/ const Model& model; // current weights arma::vec speakerWeights; arma::vec phonemeWeights; // old weights for evaluating the smoothness in a tracking scenario arma::vec oldSpeakerWeights; arma::vec oldPhonemeWeights; Mesh target; std::vector<Landmark> landmarks; /*--------------------------------------------------------------------------*/ }; } #endif
23.474227
82
0.538428
4136e10fb6dc9edd8ab1bbf67b222863c66c57b8
2,933
h
C
applications/plugins/DEPRECATED/QtOgreViewer/OgreSofaViewer.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/DEPRECATED/QtOgreViewer/OgreSofaViewer.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/DEPRECATED/QtOgreViewer/OgreSofaViewer.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef OGRESOFAVIEWER_H #define OGRESOFAVIEWER_H #include <sofa/gui/qt/viewer/VisualModelPolicy.h> #include <sofa/gui/qt/viewer/SofaViewer.h> #include "DrawToolOGRE.h" namespace sofa { namespace gui { namespace qt { namespace viewer { class OgreVisualModelPolicy : public VisualModelPolicy { protected: sofa::core::ObjectFactory::ClassEntry::SPtr classVisualModel; sofa::core::ObjectFactory::ClassEntry::SPtr classOglModel; sofa::core::visual::DrawToolOGRE drawToolOGRE; public: void load() { // Replace OpenGL visual models with OgreVisualModel sofa::core::ObjectFactory::AddAlias("OglModel", "OgreVisualModel", true, &classOglModel); sofa::core::ObjectFactory::AddAlias("VisualModel", "OgreVisualModel", true, &classVisualModel); vparams->drawTool() = &drawToolOGRE; // vparams->setSupported(sofa::core::visual::API_OGRE); // ? } void unload() { sofa::core::ObjectFactory::ResetAlias("OglModel", classOglModel); sofa::core::ObjectFactory::ResetAlias("VisualModel", classVisualModel); vparams->drawTool() = NULL; } }; typedef sofa::gui::qt::viewer::CustomPolicySofaViewer< OgreVisualModelPolicy > OgreSofaViewer; } } } } #endif // OGRESOFAVIEWER_H
41.309859
103
0.537675
41e0da0cec3e63ff2af8ad8733d92b951cd92aee
872
h
C
implementations/sjolund2016/src/c/sse_funcs.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
20
2016-11-21T05:36:09.000Z
2022-01-01T22:21:24.000Z
implementations/sjolund2016/src/c/sse_funcs.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
5
2016-09-25T13:27:40.000Z
2016-11-21T23:12:50.000Z
implementations/sjolund2016/src/c/sse_funcs.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
2
2019-03-25T09:39:19.000Z
2022-03-20T13:48:12.000Z
#ifndef SSE_FUNCS_H #define SSE_FUNCS_H #ifdef __cplusplus extern "C" { #endif #include <tmmintrin.h> #include <emmintrin.h> #include <xmmintrin.h> #include <smmintrin.h> #include <pmmintrin.h> void printvec(__m128i v, char * a); void set_matrix_values_from_diagonal_byte_vector(__m128i v, unsigned short * matrix, int queryindex,int query_length,int dbindex,int db_length); void set_matrix_values_from_diagonal_word_vector(__m128i v, unsigned short * matrix,int queryindex,int query_length,int dbindex,int db_length); #ifdef CHECK_MATRICES_BYTE void printvec_byte_index(__m128i v, char * matrix,int queryindex,int query_length,int dbindex,int db_length); #endif #ifdef CHECK_MATRICES_WORD void printvec_word_index(__m128i v, char * matrix,int queryindex,int query_length,int dbindex,int db_length); #endif #ifdef __cplusplus } #endif #endif // SSE_FUNCS_H
24.914286
144
0.799312
70fefe08f32a24c02fc27ce79a09f78d56198cce
6,062
c
C
tools/ringleb.c
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
29
2018-09-13T13:58:18.000Z
2022-03-08T21:44:13.000Z
tools/ringleb.c
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
3
2020-11-10T11:28:30.000Z
2021-11-23T09:21:28.000Z
tools/ringleb.c
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
20
2018-07-26T08:17:37.000Z
2022-03-04T08:41:55.000Z
// SPDX-License-Identifier: BSD-2-Clause /* Copyright 2015 Bernard Parent 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. 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. */ /* reference: G Chiocchia, Exact solutions to transonic and supersonic flows. Technical report AR-211, AGARD, 1985. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <exm.h> #define nj 25 //25, 49, 97 #define ni nj #define MIRROR FALSE /* mirror the solution with respect to the x axis? */ #define kmax 1.5 #define kmin 0.7 #define dq 1e-10 #define q0 0.5 #define gamma 1.4 #define Rgas 286.0 #define postfilename "ringleb.dat" #define gridfilename "ringleb.grid" #define initfilename "ringleb.init" void Findxyfromkq ( double k, double q, double *x, double *y ) { double a, rho, J; a = sqrt ( 1.0 - ( gamma - 1 ) / 2.0 * sqr ( q ) ); rho = pow ( a, 2.0 / ( gamma - 1.0 ) ); J = 1.0 / a + 1.0 / 3.0 / powint ( a, 3 ) + 1.0 / 5.0 / powint ( a, 5 ) - 0.5 * log ( ( 1.0 + a ) / ( 1.0 - a ) ); *x = 1.0 / 2.0 / rho * ( 2.0 / k / k - 1.0 / q / q ) - J / 2.0; *y = 1.0 / k / rho / q * sqrt ( 1.0 - sqr ( q / k ) ); if ( 1.0 - sqr ( q / k ) < 0.0 ) printf ( "q=%E k=%E\n", q, k ); } /* needed to create a more or less uniform mesh spacing along i */ double spacingfunction_i2 ( double x ) { double y, A, B, C, D; A = 6.61229818085967073309E-04; B = 1.28288906000451397027E-01; C = 2.77647338125862397362E+00; D = -1.90476228725907792416E+00; y = A + B * x + C * x * x + D * x * x * x; return ( y ); } /* needed to create a more or less uniform mesh spacing along i */ double spacingfunction_i ( double x ) { double y; y = spacingfunction_i2 ( x * 0.994 ) / spacingfunction_i2 ( 0.994 ); return ( y ); } int main ( ) { double T, L, q, k, a, rho, P, x, y, x1, y1, x2, y2, vx, vy; long i, j, i2, i2max; FILE *postfile; FILE *gridfile, *initfile; gridfile = fopen ( gridfilename, "w" ); initfile = fopen ( initfilename, "w" ); if ( MIRROR ) i2max = ni * 2 - 1; else i2max = ni; fprintf ( gridfile, "Grid2D(\n is=1; ie=%ld; js=1; je=%ld;\n Size(is,js,ie,je);\n", ( long ) i2max, ( long ) nj ); postfile = fopen ( postfilename, "w" ); fprintf ( postfile, "VARIABLES= \"X\", \"Y\",\n" ); fprintf ( postfile, "\"V[0]\",\n" ); fprintf ( postfile, "\"V[1]\",\n" ); fprintf ( postfile, "\"M[0]\",\n" ); fprintf ( postfile, "\"M[1]\",\n" ); fprintf ( postfile, "\"rho\",\n" ); fprintf ( postfile, "\"P\",\n" ); fprintf ( postfile, "\"T\",\n" ); fprintf ( postfile, "\"a\",\n" ); fprintf ( postfile, "ZONE I=%ld, J=%ld F=POINT\n", ( long ) i2max, ( long ) nj ); printf ( "Writing ringleb data to..\nGridfile: %s\nInit file: %s\nTecplot data file: %s\n", gridfilename, initfilename, postfilename ); for ( j = 0; j < nj; j++ ) { for ( i2 = 0; i2 < i2max; i2++ ) { if ( i2 > ni - 2 ) i = ni - ( i2 - ni ) - 2; else i = i2; if ( i >= 0 ) { k = kmin + ( kmax - kmin ) * ( double ) j / ( double ) ( nj - 1 ); q = q0 + ( k - q0 ) * spacingfunction_i ( ( double ) i / ( double ) ( ni - 1 ) ); Findxyfromkq ( k, q, &x, &y ); if ( q + dq <= k ) { Findxyfromkq ( k, q, &x1, &y1 ); Findxyfromkq ( k, q + dq, &x2, &y2 ); } else { if ( q - dq > k ) printf ( "problem here q=%E dq=%E k=%E q-dq=%E spacingfunction_i=%E\n", q, dq, k, q - dq, spacingfunction_i ( ( double ) i / ( double ) ( ni - 1 ) ) ); Findxyfromkq ( k, q - dq, &x1, &y1 ); Findxyfromkq ( k, q, &x2, &y2 ); } a = sqrt ( 1.0 - ( gamma - 1 ) / 2.0 * sqr ( q ) ); rho = pow ( a, 2.0 / ( gamma - 1.0 ) ); P = 1.0 / gamma * pow ( a, 2.0 * gamma / ( gamma - 1.0 ) ); // J=1.0/a+1.0/3.0/powint(a,3)+1.0/5.0/powint(a,5) -0.5*log((1.0+a)/(1.0-a)); L = sqrt ( sqr ( x2 - x1 ) + sqr ( y2 - y1 ) ); vx = ( x2 - x1 ) / L * q; vy = ( y2 - y1 ) / L * q; if ( i != i2 ) { y = -y; vx = -vx; } //if (j==0) printf("i=%ld i2=%ld y=%E vx=%E\n",i,i2,y,vx); T = P / rho / Rgas; fprintf ( postfile, "%E %E %E %E %E %E %E %E %E %E\n", x, y, vx, vy, vx / a, vy / a, rho, P, T, a ); fprintf ( gridfile, " Point(%ld,%ld,%E,%E);\n", 1 + i2, 1 + j, x, y ); fprintf ( initfile, " Region(%ld,%ld,%ld,%ld,INIT_TYPE1,%E,%E,%E,%E);\n", 1 + i2, 1 + j, 1 + i2, 1 + j, vx, vy, P, T ); } } } fprintf ( gridfile, ");\n" ); fclose ( postfile ); fclose ( gridfile ); fclose ( initfile ); printf ( "[done]\n" ); return ( EXIT_SUCCESS ); }
37.190184
118
0.54355
02d4c7d990c901fca60532ec489e7f62b2cab0dd
726
h
C
drawingWorkshop/pitchDrawing/src/aubio/aubioAnalyzer.h
ofZach/VAW_workshop
0a0adab37bfd9f5cfbdb3f5eaf4cb255e8997f4d
[ "MIT" ]
19
2015-02-06T16:23:23.000Z
2021-06-23T07:56:36.000Z
drawingWorkshop/pitchDrawing/src/aubio/aubioAnalyzer.h
ofZach/VAW_workshop
0a0adab37bfd9f5cfbdb3f5eaf4cb255e8997f4d
[ "MIT" ]
1
2017-02-11T17:28:03.000Z
2017-02-11T17:28:03.000Z
pitchDrawing/src/aubio/aubioAnalyzer.h
ofZach/drawingCodeACT
c53844f64246679bc22def36bbe136fbe8a980ee
[ "MIT" ]
5
2015-11-25T06:33:09.000Z
2019-03-16T11:19:06.000Z
#pragma once #include "aubio.h" #include "ofMain.h" class aubioAnalyzer{ public: void setup(); void processAudio(float * buffer, int bufferSize); ~aubioAnalyzer(); float pitch; float amplitude; // ------------------------------------------------------------------ // internal aubio variables unsigned int win_s; /* window size */ unsigned int hop_s; /* hop size */ unsigned int samplerate; /* samplerate */ unsigned int channels; /* number of channel */ aubio_pitchdetection_mode mode; aubio_pitchdetection_type type; fvec_t * in; aubio_pitchdetection_t * pitch_output ; // ------------------------------------------------------------------ };
20.166667
71
0.527548
7e36ba56d98954e6dce2474d1af47dd5d3c51a67
13,639
h
C
ext/ds_squares.h
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
1
2017-09-28T19:41:04.000Z
2017-09-28T19:41:04.000Z
ext/ds_squares.h
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
null
null
null
ext/ds_squares.h
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
null
null
null
#pragma once #include <diesel.h> //#define QUAD_BATCH_IMPLEMENTATION struct QuadBatchConstantBuffer { ds::vec4 screenDimension; ds::vec4 screenCenter; ds::matrix wvp; }; struct quad_texture { RID textureID; ds::vec2 textureSize; }; struct vs_input { ds::vec3 pos; float tex[2]; ds::Color color; }; struct QuadBatchBufferInfo { unsigned int maxSprites; ds::TextureFilters textureFilter; RID blendState; RID vertexShader; RID pixelShader; RID constantBuffer; }; class QuadBatchDesc { public: QuadBatchDesc() { _info.maxSprites = 1024; _info.textureFilter = ds::TextureFilters::LINEAR; _info.blendState = NO_RID; _info.pixelShader = NO_RID; _info.vertexShader = NO_RID; _info.constantBuffer = NO_RID; } QuadBatchDesc& MaxSprites(int max) { _info.maxSprites = max; return *this; } QuadBatchDesc& TextureFilter(ds::TextureFilters filter) { _info.textureFilter = filter; return *this; } QuadBatchDesc& BlendState(RID blendState) { _info.blendState = blendState; return *this; } QuadBatchDesc& PixelShader(RID pixelShader) { _info.pixelShader = pixelShader; return *this; } QuadBatchDesc& VertexShader(RID vertexShader) { _info.vertexShader = vertexShader; return *this; } QuadBatchDesc& ConstantBuffer(RID constantBuffer) { _info.constantBuffer = constantBuffer; return *this; } const QuadBatchBufferInfo& getInfo() const { return _info; } private: QuadBatchBufferInfo _info; }; namespace quads { void initialize(const QuadBatchDesc& info); void begin(); void flush(); void draw(RID textureID, const ds::vec2* positions, const ds::vec4& textureRect, const ds::vec2& scale = ds::vec2(1.0f,1.0f), float rotation = 0.0f, const ds::Color& clr = ds::Color(255,255,255,255)); void shutdown(); } #ifdef QUAD_BATCH_IMPLEMENTATION #include <vector> #include <assert.h> const BYTE Quad_VS_Main[] = { 68, 88, 66, 67, 190, 223, 60, 190, 237, 80, 102, 169, 230, 201, 8, 45, 12, 251, 233, 191, 1, 0, 0, 0, 92, 2, 0, 0, 3, 0, 0, 0, 44, 0, 0, 0, 156, 0, 0, 0, 16, 1, 0, 0, 73, 83, 71, 78, 104, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 7, 3, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 3, 3, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 15, 15, 0, 0, 80, 79, 83, 73, 84, 73, 79, 78, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 67, 79, 76, 79, 82, 0, 79, 83, 71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 3, 12, 0, 0, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 15, 0, 0, 0, 83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 67, 79, 76, 79, 82, 0, 171, 83, 72, 68, 82, 68, 1, 0, 0, 64, 0, 1, 0, 81, 0, 0, 0, 89, 0, 0, 4, 70, 142, 32, 0, 0, 0, 0, 0, 6, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 0, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 1, 0, 0, 0, 95, 0, 0, 3, 242, 16, 16, 0, 2, 0, 0, 0, 103, 0, 0, 4, 242, 32, 16, 0, 0, 0, 0, 0, 1, 0, 0, 0, 101, 0, 0, 3, 50, 32, 16, 0, 1, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 2, 0, 0, 0, 104, 0, 0, 2, 1, 0, 0, 0, 54, 0, 0, 5, 66, 32, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 50, 0, 16, 0, 0, 0, 0, 0, 70, 16, 16, 0, 0, 0, 0, 0, 70, 128, 32, 128, 65, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 54, 0, 0, 5, 66, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 63, 16, 0, 0, 8, 18, 32, 16, 0, 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, 70, 131, 32, 0, 0, 0, 0, 0, 2, 0, 0, 0, 16, 0, 0, 8, 34, 32, 16, 0, 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, 70, 131, 32, 0, 0, 0, 0, 0, 3, 0, 0, 0, 16, 0, 0, 8, 130, 32, 16, 0, 0, 0, 0, 0, 70, 2, 16, 0, 0, 0, 0, 0, 70, 131, 32, 0, 0, 0, 0, 0, 5, 0, 0, 0, 54, 0, 0, 5, 50, 32, 16, 0, 1, 0, 0, 0, 70, 16, 16, 0, 1, 0, 0, 0, 54, 0, 0, 5, 242, 32, 16, 0, 2, 0, 0, 0, 70, 30, 16, 0, 2, 0, 0, 0, 62, 0, 0, 1 }; const BYTE Quad_PS_Main[] = { 68, 88, 66, 67, 133, 123, 244, 109, 36, 101, 150, 228, 91, 135, 209, 221, 54, 143, 33, 28, 1, 0, 0, 0, 112, 1, 0, 0, 3, 0, 0, 0, 44, 0, 0, 0, 160, 0, 0, 0, 212, 0, 0, 0, 73, 83, 71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 3, 3, 0, 0, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 15, 15, 0, 0, 83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 67, 79, 76, 79, 82, 0, 171, 79, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 83, 86, 95, 84, 65, 82, 71, 69, 84, 0, 171, 171, 83, 72, 68, 82, 148, 0, 0, 0, 64, 0, 0, 0, 37, 0, 0, 0, 90, 0, 0, 3, 0, 96, 16, 0, 0, 0, 0, 0, 88, 24, 0, 4, 0, 112, 16, 0, 0, 0, 0, 0, 85, 85, 0, 0, 98, 16, 0, 3, 50, 16, 16, 0, 1, 0, 0, 0, 98, 16, 0, 3, 242, 16, 16, 0, 2, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 0, 0, 0, 0, 104, 0, 0, 2, 1, 0, 0, 0, 69, 0, 0, 9, 242, 0, 16, 0, 0, 0, 0, 0, 70, 16, 16, 0, 1, 0, 0, 0, 70, 126, 16, 0, 0, 0, 0, 0, 0, 96, 16, 0, 0, 0, 0, 0, 56, 0, 0, 7, 242, 32, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 0, 0, 0, 0, 70, 30, 16, 0, 2, 0, 0, 0, 62, 0, 0, 1 }; struct QuadDrawItem { RID textureId; RID drawItem; }; struct QuadBatchContext { RID currentTexture; bool rendering; unsigned int max; unsigned int current; RID renderPass; RID vertexBufferId; RID basicGroup; QuadBatchConstantBuffer constantBuffer; std::vector<QuadDrawItem> drawItems; RID pixelShader; ds::vec2 screenCenter; ds::Camera camera; vs_input* vertices; }; static QuadBatchContext* _qbCtx = 0; namespace quads { void initialize(const QuadBatchDesc& desc) { _qbCtx = new QuadBatchContext; _qbCtx->current = 0; _qbCtx->rendering = false; const QuadBatchBufferInfo& info = desc.getInfo(); _qbCtx->max = info.maxSprites; _qbCtx->vertices = new vs_input[info.maxSprites * 4]; RID vertexShader = info.vertexShader; if (vertexShader == NO_RID) { vertexShader = ds::createShader(ds::ShaderDesc() .Data(Quad_VS_Main) .DataSize(sizeof(Quad_VS_Main)) .ShaderType(ds::ShaderType::ST_VERTEX_SHADER) , "QuadVS" ); } _qbCtx->pixelShader = info.pixelShader; if (_qbCtx->pixelShader == NO_RID) { _qbCtx->pixelShader = ds::createShader(ds::ShaderDesc() .Data(Quad_PS_Main) .DataSize(sizeof(Quad_PS_Main)) .ShaderType(ds::ShaderType::ST_PIXEL_SHADER) , "QuadPS" ); } RID bs_id = info.blendState; if (bs_id == NO_RID) { bs_id = ds::createBlendState(ds::BlendStateDesc() .SrcBlend(ds::BlendStates::SRC_ALPHA) .SrcAlphaBlend(ds::BlendStates::SRC_ALPHA) .DestBlend(ds::BlendStates::INV_SRC_ALPHA) .DestAlphaBlend(ds::BlendStates::INV_SRC_ALPHA) .AlphaEnabled(true) ); } RID constantBuffer = info.constantBuffer; if (constantBuffer == NO_RID) { constantBuffer = ds::createConstantBuffer(sizeof(QuadBatchConstantBuffer), &_qbCtx->constantBuffer); } RID sSPID = createSamplerState(ds::SamplerStateDesc() .AddressMode(ds::TextureAddressModes::CLAMP) .Filter(info.textureFilter) ); int indices[] = { 0,1,2,2,3,0 }; RID idxBuffer = ds::createQuadIndexBuffer(_qbCtx->max, indices); _qbCtx->vertexBufferId = ds::createVertexBuffer(ds::VertexBufferDesc() .VertexSize(sizeof(vs_input)) .NumVertices(_qbCtx->max * 4) .BufferType(ds::BufferType::DYNAMIC) ); // create buffer input layout ds::InputLayoutDefinition decl[] = { { "POSITION", 0, ds::BufferAttributeType::FLOAT3 }, { "TEXCOORD", 0, ds::BufferAttributeType::FLOAT2 }, { "COLOR", 0, ds::BufferAttributeType::FLOAT4 } }; RID rid = ds::createInputLayout(ds::InputLayoutDesc() .Declarations(decl) .NumDeclarations(3) .VertexShader(vertexShader) ); assert(rid != NO_RID); _qbCtx->basicGroup = ds::StateGroupBuilder() .constantBuffer(constantBuffer, vertexShader) .blendState(bs_id) .inputLayout(rid) .vertexBuffer(_qbCtx->vertexBufferId) .vertexShader(vertexShader) .indexBuffer(idxBuffer) .pixelShader(_qbCtx->pixelShader) .samplerState(sSPID, _qbCtx->pixelShader) .build(); ds::DrawCommand drawCmd = { info.maxSprites, ds::DrawType::DT_INDEXED, ds::PrimitiveTypes::TRIANGLE_LIST }; // create orthographic view ds::matrix orthoView = ds::matIdentity(); ds::matrix orthoProjection = ds::matOrthoLH(ds::getScreenWidth(), ds::getScreenHeight(), 0.0f, 1.0f); _qbCtx->camera = { orthoView, orthoProjection, orthoView * orthoProjection, ds::vec3(0,0,0), ds::vec3(0,0,1), ds::vec3(0,1,0), ds::vec3(1,0,0), 0.0f, 0.0f, 0.0f }; RID vp = ds::createViewport(ds::ViewportDesc() .Top(0) .Left(0) .Width(ds::getScreenWidth()) .Height(ds::getScreenHeight()) .MinDepth(0.0f) .MaxDepth(1.0f), "QuadOrthoViewport" ); _qbCtx->renderPass = ds::createRenderPass(ds::RenderPassDesc() .Camera(&_qbCtx->camera) .Viewport(vp) .DepthBufferState(ds::DepthBufferState::DISABLED) .RenderTargets(0) .NumRenderTargets(0), "QuadOrthoPass" ); _qbCtx->constantBuffer.wvp = ds::matTranspose(_qbCtx->camera.viewProjectionMatrix); _qbCtx->screenCenter = ds::vec2(ds::getScreenWidth() * 0.5f, ds::getScreenHeight() * 0.5f); } void set_screen_center(const ds::vec2& center) { _qbCtx->screenCenter = center; } void shutdown() { delete[] _qbCtx->vertices; delete _qbCtx; } void begin() { _qbCtx->current = 0; _qbCtx->rendering = true; _qbCtx->currentTexture = NO_RID; } static bool spr__requiresFlush(RID textureID) { if (_qbCtx->currentTexture == NO_RID) { return false; } return ((_qbCtx->current + 1) >= _qbCtx->max || textureID != _qbCtx->currentTexture); } static int spr__createDrawItem(RID textureId) { QuadDrawItem item; ds::DrawCommand drawCmd = { 100, ds::DrawType::DT_INDEXED, ds::PrimitiveTypes::TRIANGLE_LIST }; RID myGroup = ds::StateGroupBuilder().texture(textureId, _qbCtx->pixelShader, 0).build(); RID groups[] = { _qbCtx->basicGroup, myGroup }; item.drawItem = ds::compile(drawCmd, groups, 2); item.textureId = textureId; _qbCtx->drawItems.push_back(item); return _qbCtx->drawItems.size() - 1; } void draw(RID textureID, const ds::vec2* positions, const ds::vec4& rect, const ds::vec2& scale, float rotation, const ds::Color& clr) { if (spr__requiresFlush(textureID)) { flush(); } _qbCtx->currentTexture = textureID; int cur = _qbCtx->current; for (int i = 0; i < 4; ++i) { ds::vec2 p = positions[i]; vs_input& ip = _qbCtx->vertices[_qbCtx->current++]; ip.pos = ds::vec3(p.x(), p.y(), 0.0f); ip.color = clr; } ds::vec2 ts = ds::getTextureSize(textureID); // u0 / v1 _qbCtx->vertices[cur].tex[0] = rect.x / ts.x(); _qbCtx->vertices[cur].tex[1] = (rect.y + rect.w) / ts.y(); // u0 / v0 _qbCtx->vertices[cur + 1].tex[0] = rect.x / ts.x(); _qbCtx->vertices[cur + 1].tex[1] = rect.y / ts.y(); // u1 / v0 _qbCtx->vertices[cur + 2].tex[0] = (rect.x + rect.z) / ts.x(); _qbCtx->vertices[cur + 2].tex[1] = rect.y / ts.y(); // u1 / v1 _qbCtx->vertices[cur + 3].tex[0] = (rect.x + rect.z) / ts.x(); _qbCtx->vertices[cur + 3].tex[1] = (rect.y + rect.w) / ts.y(); } static int spr__findDrawItemIndex(RID textureId) { for (size_t i = 0; i < _qbCtx->drawItems.size(); ++i) { if (_qbCtx->drawItems[i].textureId == textureId) { return i; } } return -1; } void flush() { if (_qbCtx->current > 0) { ds::vec2 textureSize = ds::getTextureSize(_qbCtx->currentTexture); _qbCtx->constantBuffer.screenDimension = { _qbCtx->screenCenter.x(), _qbCtx->screenCenter.y(), textureSize.x(), textureSize.y() }; _qbCtx->constantBuffer.screenCenter = { _qbCtx->screenCenter.x(), _qbCtx->screenCenter.y(), textureSize.x(), textureSize.y() }; ds::mapBufferData(_qbCtx->vertexBufferId, _qbCtx->vertices, _qbCtx->current * sizeof(vs_input)); int idx = spr__findDrawItemIndex(_qbCtx->currentTexture); if (idx == -1) { idx = spr__createDrawItem(_qbCtx->currentTexture); } const QuadDrawItem drawItem = _qbCtx->drawItems[idx]; ds::submit(_qbCtx->renderPass, drawItem.drawItem, _qbCtx->current / 4 * 6); _qbCtx->current = 0; _qbCtx->currentTexture = NO_RID; } _qbCtx->rendering = false; } } #endif
35.986807
201
0.552093
0bc554a667ce5316ca36fe219beb4c5d8dff952a
2,392
h
C
src/net/ip/IGMP.h
tristanseifert/lichtenstein-firmware
7680d0b2489332a5798030be5ab49f58518332f3
[ "BSD-3-Clause" ]
null
null
null
src/net/ip/IGMP.h
tristanseifert/lichtenstein-firmware
7680d0b2489332a5798030be5ab49f58518332f3
[ "BSD-3-Clause" ]
null
null
null
src/net/ip/IGMP.h
tristanseifert/lichtenstein-firmware
7680d0b2489332a5798030be5ab49f58518332f3
[ "BSD-3-Clause" ]
null
null
null
/* * IGMP.h * * Implements the means to transmit IGMP packet for joining/leaving multicast * groups. This presently only implements a limited subset of IGMPv2, in that * group queries are not implemented. * * Created on: Mar 9, 2018 * Author: tristan */ #ifndef NET_IP_IGMP_H_ #define NET_IP_IGMP_H_ #include "StackTypes.h" #include <LichtensteinApp.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpadded" namespace ip { class Stack; class IPv4; class IGMP { public: IGMP(Stack *stack, IPv4 *ipv4); virtual ~IGMP(); // API for the IPv4 handler to call into public: void processMulticastFrame(void *); private: void processIGMPv3Packet(void *); // byte order conversion helpers private: void convertPacketByteOrder(void *, bool); void packetNetworkToHost(void *_packet) { this->convertPacketByteOrder(_packet, false); } void packetHostToNetwork(void *_packet) { this->convertPacketByteOrder(_packet, true); } void insertIGMPChecksum(void *, ssize_t length = -1); bool verifyIGMPChecksum(void *, ssize_t length = -1); private: uint64_t receivedPackets = 0; // reply processing task private: friend void _IGMPTaskTrampoline(void *); void taskEntry(void); void taskSendMembershipReport2(void *); void taskSendMembershipReport3(void *); void taskSendLeaveGroup2(void *); void taskSendLeaveGroup3(void *); int postMessageToTask(void *, int timeout = portMAX_DELAY); private: // size of the ICMP task's stack, in words static const size_t TaskStackSize = 150; // priority of the ICMP task static const int TaskPriority = 2; // how many messages may be pending on the message queue at a time static const size_t messageQueueSize = 4; // how many times an unsolicited packet should be sent static const size_t PacketResends = 2; TaskHandle_t task = nullptr; QueueHandle_t messageQueue = nullptr; // helper functions called by the IPv4 stack to send IGMP messages public: void joinedGroup(stack_ipv4_addr_t address); void leftGroup(stack_ipv4_addr_t address); private: // IGMPv3 address static const stack_ipv4_addr_t IGMPv3Address = __builtin_bswap32(0xe0000016); private: Stack *stack = nullptr; IPv4 *ipv4 = nullptr; }; } /* namespace ip */ #pragma GCC diagnostic pop #endif /* NET_IP_IGMP_H_ */
23.45098
80
0.716137
a37bb9525975155bc040b64212bb6fa0f33bd37b
1,078
h
C
src/sig/rainbow/pqclean_rainbowIa-cyclic_clean/api.h
nicholasfulton/liboqs
f61cd669253097052e1b4b5350a0b4616ed74df9
[ "MIT" ]
4
2020-12-28T15:16:49.000Z
2022-01-05T16:40:09.000Z
src/sig/rainbow/pqclean_rainbowIa-cyclic_clean/api.h
nicholasfulton/liboqs
f61cd669253097052e1b4b5350a0b4616ed74df9
[ "MIT" ]
null
null
null
src/sig/rainbow/pqclean_rainbowIa-cyclic_clean/api.h
nicholasfulton/liboqs
f61cd669253097052e1b4b5350a0b4616ed74df9
[ "MIT" ]
4
2020-12-22T00:45:01.000Z
2022-01-05T16:40:14.000Z
#ifndef PQCLEAN_RAINBOWIACYCLIC_CLEAN_API_H #define PQCLEAN_RAINBOWIACYCLIC_CLEAN_API_H #include <stddef.h> #include <stdint.h> #define PQCLEAN_RAINBOWIACYCLIC_CLEAN_CRYPTO_SECRETKEYBYTES 92960 #define PQCLEAN_RAINBOWIACYCLIC_CLEAN_CRYPTO_PUBLICKEYBYTES 58144 #define PQCLEAN_RAINBOWIACYCLIC_CLEAN_CRYPTO_BYTES 64 #define PQCLEAN_RAINBOWIACYCLIC_CLEAN_CRYPTO_ALGNAME "RAINBOW(16,32,32,32) - cyclic" int PQCLEAN_RAINBOWIACYCLIC_CLEAN_crypto_sign_keypair(uint8_t *pk, uint8_t *sk); int PQCLEAN_RAINBOWIACYCLIC_CLEAN_crypto_sign_signature( uint8_t *sig, size_t *siglen, const uint8_t *m, size_t mlen, const uint8_t *sk); int PQCLEAN_RAINBOWIACYCLIC_CLEAN_crypto_sign_verify( const uint8_t *sig, size_t siglen, const uint8_t *m, size_t mlen, const uint8_t *pk); int PQCLEAN_RAINBOWIACYCLIC_CLEAN_crypto_sign(uint8_t *sm, size_t *smlen, const uint8_t *m, size_t mlen, const uint8_t *sk); int PQCLEAN_RAINBOWIACYCLIC_CLEAN_crypto_sign_open(uint8_t *m, size_t *mlen, const uint8_t *sm, size_t smlen, const uint8_t *pk); #endif
32.666667
84
0.802412
28052177297c34030a8473d19d80c08318407e46
358,322
h
C
Source/HoudiniEngine/Private/GeometryToolsEngine.h
leaping-rhino/HoudiniEngineForUnreal
7da6fea61907101071fb837e40c1902320604f7f
[ "BSD-3-Clause" ]
null
null
null
Source/HoudiniEngine/Private/GeometryToolsEngine.h
leaping-rhino/HoudiniEngineForUnreal
7da6fea61907101071fb837e40c1902320604f7f
[ "BSD-3-Clause" ]
null
null
null
Source/HoudiniEngine/Private/GeometryToolsEngine.h
leaping-rhino/HoudiniEngineForUnreal
7da6fea61907101071fb837e40c1902320604f7f
[ "BSD-3-Clause" ]
null
null
null
 #pragma once #include "CoreMinimal.h" #include <algorithm> #include <array> #include <cmath> #include <cstddef> #include <cstring> #include <initializer_list> #include <limits> #include <map> #include <memory> #include <mutex> #include <random> #include <set> #include <string> #include <thread> #include <type_traits> #include <vector> // ---------------------------------------------- // ProgressCancel.h // ---------------------------------------------- // Copyright Epic Games, Inc. All Rights Reserved. // Port of geometry3cpp ProgressCancel /** * FHEProgressCancel is an obejct that is intended to be passed to long-running * computes to do two things: * 1) provide progress info back to caller (not implemented yet) * 2) allow caller to cancel the computation */ class FHEProgressCancel { private: bool WasCancelled = false; // will be set to true if CancelF() ever returns true public: TFunction<bool()> CancelF = []() { return false; }; /** * @return true if client would like to cancel operation */ bool Cancelled() { if (WasCancelled) { return true; } WasCancelled = CancelF(); return WasCancelled; } public: enum class EMessageLevel { // Note: Corresponds to EToolMessageLevel in InteractiveToolsFramework/ToolContextInterfaces.h /** Development message goes into development log */ Internal = 0, /** User message should appear in user-facing log */ UserMessage = 1, /** Notification message should be shown in a non-modal notification window */ UserNotification = 2, /** Warning message should be shown in a non-modal notification window with panache */ UserWarning = 3, /** Error message should be shown in a modal notification window */ UserError = 4 }; struct FMessageInfo { FText MessageText; EMessageLevel MessageLevel; FDateTime Timestamp; }; void AddWarning(const FText& MessageText, EMessageLevel MessageLevel) { Warnings.Add(FMessageInfo{ MessageText , MessageLevel, FDateTime::Now() }); } TArray<FMessageInfo> Warnings; }; // ---------------------------------------------- // GTEngineDEF.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) //---------------------------------------------------------------------------- // The platform specification. // // __MSWINDOWS__ : Microsoft Windows (WIN32 or WIN64) // __APPLE__ : Macintosh OS X // __LINUX__ : Linux or Cygwin //---------------------------------------------------------------------------- #if !defined(__LINUX__) && (defined(WIN32) || defined(_WIN64)) #define __MSWINDOWS__ #if !defined(_MSC_VER) #error Microsoft Visual Studio 2013 or later is required. #endif // MSVC 6 is version 12.0 // MSVC 7.0 is version 13.0 (MSVS 2002) // MSVC 7.1 is version 13.1 (MSVS 2003) // MSVC 8.0 is version 14.0 (MSVS 2005) // MSVC 9.0 is version 15.0 (MSVS 2008) // MSVC 10.0 is version 16.0 (MSVS 2010) // MSVC 11.0 is version 17.0 (MSVS 2012) // MSVC 12.0 is version 18.0 (MSVS 2013) // MSVC 14.0 is version 19.0 (MSVS 2015) // Currently, projects are provided only for MSVC 12.0 and 14.0. #if _MSC_VER < 1800 #error Microsoft Visual Studio 2013 or later is required. #endif // Debug build values (choose_your_value is 0, 1, or 2) // 0: Disables checked iterators and disables iterator debugging. // 1: Enables checked iterators and disables iterator debugging. // 2: (default) Enables iterator debugging; checked iterators are not relevant. // // Release build values (choose_your_value is 0 or 1) // 0: (default) Disables checked iterators. // 1: Enables checked iterators; iterator debugging is not relevant. // // #define _ITERATOR_DEBUG_LEVEL choose_your_value #endif // WIN32 or _WIN64 // TODO: Windows DLL configurations have not yet been added to the project, // but these defines are required to support them (when we do add them). // // Add GTE_EXPORT to project preprocessor options for dynamic library // configurations to export their symbols. #if defined(GTE_EXPORT) // For the dynamic library configurations. #define GTE_IMPEXP __declspec(dllexport) #else // For a client of the dynamic library or for the static library // configurations. #define GTE_IMPEXP #endif // Expose exactly one of these. #define GTE_USE_ROW_MAJOR //#define GTE_USE_COL_MAJOR // Expose exactly one of these. #define GTE_USE_MAT_VEC //#define GTE_USE_VEC_MAT #if (defined(GTE_USE_ROW_MAJOR) && defined(GTE_USE_COL_MAJOR)) || (!defined(GTE_USE_ROW_MAJOR) && !defined(GTE_USE_COL_MAJOR)) #error Exactly one storage order must be specified. #endif #if (defined(GTE_USE_MAT_VEC) && defined(GTE_USE_VEC_MAT)) || (!defined(GTE_USE_MAT_VEC) && !defined(GTE_USE_VEC_MAT)) #error Exactly one multiplication convention must be specified. #endif // ---------------------------------------------- // GteLogger.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Uncomment this to turn off the logging system. The macros LogAssert, // LogError, LogWarning, and LogInformation expand to nothing. (Do this for // optimal performance.) //#define GTE_NO_LOGGER namespace gte { class GTE_IMPEXP Logger { public: // Construction. The Logger object is designed to exist only for a // single-line call. A string is generated from the input parameters and // is used for reporting. Logger(char const* file, char const* function, int line, std::string const& message); // Notify current listeners about the logged information. void Assertion(); void Error(); void Warning(); void Information(); // Listeners subscribe to Logger to receive message strings. class Listener { public: enum { LISTEN_FOR_NOTHING = 0x00000000, LISTEN_FOR_ASSERTION = 0x00000001, LISTEN_FOR_ERROR = 0x00000002, LISTEN_FOR_WARNING = 0x00000004, LISTEN_FOR_INFORMATION = 0x00000008, LISTEN_FOR_ALL = 0xFFFFFFFF }; // Construction and destruction. virtual ~Listener(); Listener(int flags = LISTEN_FOR_NOTHING); // What the listener wants to hear. int GetFlags() const; // Handlers for the messages received from the logger. void Assertion(std::string const& message); void Error(std::string const& message); void Warning(std::string const& message); void Information(std::string const& message); private: virtual void Report(std::string const& message); int mFlags; }; static void Subscribe(Listener* listener); static void Unsubscribe(Listener* listener); private: std::string mMessage; static std::mutex msMutex; static std::set<Listener*> msListeners; }; } #if !defined(GTE_NO_LOGGER) #define LogAssert(condition, message) \ if (!(condition)) \ { \ gte::Logger(__FILE__, __FUNCTION__, __LINE__, message).Assertion(); \ } #define LogError(message) \ gte::Logger(__FILE__, __FUNCTION__, __LINE__, message).Error() #define LogWarning(message) \ gte::Logger(__FILE__, __FUNCTION__, __LINE__, message).Warning() #define LogInformation(message) \ gte::Logger(__FILE__, __FUNCTION__, __LINE__, message).Information() #else // No logging of assertions, warnings, errors, or information. #define LogAssert(condition, message) #define LogError(message) #define LogWarning(message) #define LogInformation(message) #endif // ---------------------------------------------- // GteVector.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.3 (2018/10/05) namespace gte { template <int N, typename Real> class Vector { public: // The tuple is uninitialized. Vector(); // The tuple is fully initialized by the inputs. Vector(std::array<Real, N> const& values); // At most N elements are copied from the initializer list, setting any // remaining elements to zero. Create the zero vector using the syntax // Vector<N,Real> zero{(Real)0}; // WARNING: The C++ 11 specification states that // Vector<N,Real> zero{}; // will lead to a call of the default constructor, not the initializer // constructor! Vector(std::initializer_list<Real> values); // For 0 <= d < N, element d is 1 and all others are 0. If d is invalid, // the zero vector is created. This is a convenience for creating the // standard Euclidean basis vectors; see also MakeUnit(int) and Unit(int). Vector(int d); // The copy constructor, destructor, and assignment operator are generated // by the compiler. // Member access. The first operator[] returns a const reference rather // than a Real value. This supports writing via standard file operations // that require a const pointer to data. inline int GetSize() const; // returns N inline Real const& operator[](int i) const; inline Real& operator[](int i); // Comparisons for sorted containers and geometric ordering. inline bool operator==(Vector const& vec) const; inline bool operator!=(Vector const& vec) const; inline bool operator< (Vector const& vec) const; inline bool operator<=(Vector const& vec) const; inline bool operator> (Vector const& vec) const; inline bool operator>=(Vector const& vec) const; // Special vectors. void MakeZero(); // All components are 0. void MakeUnit(int d); // Component d is 1, all others are zero. static Vector Zero(); static Vector Unit(int d); protected: // This data structure takes advantage of the built-in operator[], // range checking, and visualizers in MSVS. std::array<Real, N> mTuple; }; // Unary operations. template <int N, typename Real> Vector<N, Real> operator+(Vector<N, Real> const& v); template <int N, typename Real> Vector<N, Real> operator-(Vector<N, Real> const& v); // Linear-algebraic operations. template <int N, typename Real> Vector<N, Real> operator+(Vector<N, Real> const& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real> operator-(Vector<N, Real> const& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real> operator*(Vector<N, Real> const& v, Real scalar); template <int N, typename Real> Vector<N, Real> operator*(Real scalar, Vector<N, Real> const& v); template <int N, typename Real> Vector<N, Real> operator/(Vector<N, Real> const& v, Real scalar); template <int N, typename Real> Vector<N, Real>& operator+=(Vector<N, Real>& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real>& operator-=(Vector<N, Real>& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real>& operator*=(Vector<N, Real>& v, Real scalar); template <int N, typename Real> Vector<N, Real>& operator/=(Vector<N, Real>& v, Real scalar); // Componentwise algebraic operations. template <int N, typename Real> Vector<N, Real> operator*(Vector<N, Real> const& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real> operator/(Vector<N, Real> const& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real>& operator*=(Vector<N, Real>& v0, Vector<N, Real> const& v1); template <int N, typename Real> Vector<N, Real>& operator/=(Vector<N, Real>& v0, Vector<N, Real> const& v1); // Geometric operations. The functions with 'robust' set to 'false' use the // standard algorithm for normalizing a vector by computing the length as a // square root of the squared length and dividing by it. The results can be // infinite (or NaN) if the length is zero. When 'robust' is set to 'true', // the algorithm is designed to avoid floating-point overflow and sets the // normalized vector to zero when the length is zero. template <int N, typename Real> Real Dot(Vector<N, Real> const& v0, Vector<N, Real> const& v1); template <int N, typename Real> Real Length(Vector<N, Real> const& v, bool robust = false); template <int N, typename Real> Real Normalize(Vector<N, Real>& v, bool robust = false); // Gram-Schmidt orthonormalization to generate orthonormal vectors from the // linearly independent inputs. The function returns the smallest length of // the unnormalized vectors computed during the process. If this value is // nearly zero, it is possible that the inputs are linearly dependent (within // numerical round-off errors). On input, 1 <= numElements <= N and v[0] // through v[numElements-1] must be initialized. On output, the vectors // v[0] through v[numElements-1] form an orthonormal set. template <int N, typename Real> Real Orthonormalize(int numElements, Vector<N, Real>* v, bool robust = false); // Construct a single vector orthogonal to the nonzero input vector. If the // maximum absolute component occurs at index i, then the orthogonal vector // U has u[i] = v[i+1], u[i+1] = -v[i], and all other components zero. The // index addition i+1 is computed modulo N. template <int N, typename Real> Vector<N, Real> GetOrthogonal(Vector<N, Real> const& v, bool unitLength); // Compute the axis-aligned bounding box of the vectors. The return value is // 'true' iff the inputs are valid, in which case vmin and vmax have valid // values. template <int N, typename Real> bool ComputeExtremes(int numVectors, Vector<N, Real> const* v, Vector<N, Real>& vmin, Vector<N, Real>& vmax); // Lift n-tuple v to homogeneous (n+1)-tuple (v,last). template <int N, typename Real> Vector<N + 1, Real> HLift(Vector<N, Real> const& v, Real last); // Project homogeneous n-tuple v = (u,v[n-1]) to (n-1)-tuple u. template <int N, typename Real> Vector<N - 1, Real> HProject(Vector<N, Real> const& v); // Lift n-tuple v = (w0,w1) to (n+1)-tuple u = (w0,u[inject],w1). By // inference, w0 is a (inject)-tuple [nonexistent when inject=0] and w1 is a // (n-inject)-tuple [nonexistent when inject=n]. template <int N, typename Real> Vector<N + 1, Real> Lift(Vector<N, Real> const& v, int inject, Real value); // Project n-tuple v = (w0,v[reject],w1) to (n-1)-tuple u = (w0,w1). By // inference, w0 is a (reject)-tuple [nonexistent when reject=0] and w1 is a // (n-1-reject)-tuple [nonexistent when reject=n-1]. template <int N, typename Real> Vector<N - 1, Real> Project(Vector<N, Real> const& v, int reject); template <int N, typename Real> Vector<N, Real>::Vector() { // Uninitialized. } template <int N, typename Real> Vector<N, Real>::Vector(std::array<Real, N> const& values) : mTuple(values) { } template <int N, typename Real> Vector<N, Real>::Vector(std::initializer_list<Real> values) { int const numValues = static_cast<int>(values.size()); if (N == numValues) { std::copy(values.begin(), values.end(), mTuple.begin()); } else if (N > numValues) { std::copy(values.begin(), values.end(), mTuple.begin()); std::fill(mTuple.begin() + numValues, mTuple.end(), (Real)0); } else // N < numValues { std::copy(values.begin(), values.begin() + N, mTuple.begin()); } } template <int N, typename Real> Vector<N, Real>::Vector(int d) { MakeUnit(d); } template <int N, typename Real> inline int Vector<N, Real>::GetSize() const { return N; } template <int N, typename Real> inline Real const& Vector<N, Real>::operator[](int i) const { return mTuple[i]; } template <int N, typename Real> inline Real& Vector<N, Real>::operator[](int i) { return mTuple[i]; } template <int N, typename Real> inline bool Vector<N, Real>::operator==(Vector const& vec) const { return mTuple == vec.mTuple; } template <int N, typename Real> inline bool Vector<N, Real>::operator!=(Vector const& vec) const { return mTuple != vec.mTuple; } template <int N, typename Real> inline bool Vector<N, Real>::operator<(Vector const& vec) const { return mTuple < vec.mTuple; } template <int N, typename Real> inline bool Vector<N, Real>::operator<=(Vector const& vec) const { return mTuple <= vec.mTuple; } template <int N, typename Real> inline bool Vector<N, Real>::operator>(Vector const& vec) const { return mTuple > vec.mTuple; } template <int N, typename Real> inline bool Vector<N, Real>::operator>=(Vector const& vec) const { return mTuple >= vec.mTuple; } template <int N, typename Real> void Vector<N, Real>::MakeZero() { std::fill(mTuple.begin(), mTuple.end(), (Real)0); } template <int N, typename Real> void Vector<N, Real>::MakeUnit(int d) { std::fill(mTuple.begin(), mTuple.end(), (Real)0); if (0 <= d && d < N) { mTuple[d] = (Real)1; } } template <int N, typename Real> Vector<N, Real> Vector<N, Real>::Zero() { Vector<N, Real> v; v.MakeZero(); return v; } template <int N, typename Real> Vector<N, Real> Vector<N, Real>::Unit(int d) { Vector<N, Real> v; v.MakeUnit(d); return v; } template <int N, typename Real> Vector<N, Real> operator+(Vector<N, Real> const& v) { return v; } template <int N, typename Real> Vector<N, Real> operator-(Vector<N, Real> const& v) { Vector<N, Real> result; for (int i = 0; i < N; ++i) { result[i] = -v[i]; } return result; } template <int N, typename Real> Vector<N, Real> operator+(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { Vector<N, Real> result = v0; return result += v1; } template <int N, typename Real> Vector<N, Real> operator-(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { Vector<N, Real> result = v0; return result -= v1; } template <int N, typename Real> Vector<N, Real> operator*(Vector<N, Real> const& v, Real scalar) { Vector<N, Real> result = v; return result *= scalar; } template <int N, typename Real> Vector<N, Real> operator*(Real scalar, Vector<N, Real> const& v) { Vector<N, Real> result = v; return result *= scalar; } template <int N, typename Real> Vector<N, Real> operator/(Vector<N, Real> const& v, Real scalar) { Vector<N, Real> result = v; return result /= scalar; } template <int N, typename Real> Vector<N, Real>& operator+=(Vector<N, Real>& v0, Vector<N, Real> const& v1) { for (int i = 0; i < N; ++i) { v0[i] += v1[i]; } return v0; } template <int N, typename Real> Vector<N, Real>& operator-=(Vector<N, Real>& v0, Vector<N, Real> const& v1) { for (int i = 0; i < N; ++i) { v0[i] -= v1[i]; } return v0; } template <int N, typename Real> Vector<N, Real>& operator*=(Vector<N, Real>& v, Real scalar) { for (int i = 0; i < N; ++i) { v[i] *= scalar; } return v; } template <int N, typename Real> Vector<N, Real>& operator/=(Vector<N, Real>& v, Real scalar) { if (scalar != (Real)0) { Real invScalar = ((Real)1) / scalar; for (int i = 0; i < N; ++i) { v[i] *= invScalar; } } else { for (int i = 0; i < N; ++i) { v[i] = (Real)0; } } return v; } template <int N, typename Real> Vector<N, Real> operator*(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { Vector<N, Real> result = v0; return result *= v1; } template <int N, typename Real> Vector<N, Real> operator/(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { Vector<N, Real> result = v0; return result /= v1; } template <int N, typename Real> Vector<N, Real>& operator*=(Vector<N, Real>& v0, Vector<N, Real> const& v1) { for (int i = 0; i < N; ++i) { v0[i] *= v1[i]; } return v0; } template <int N, typename Real> Vector<N, Real>& operator/=(Vector<N, Real>& v0, Vector<N, Real> const& v1) { for (int i = 0; i < N; ++i) { v0[i] /= v1[i]; } return v0; } template <int N, typename Real> Real Dot(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { Real dot = v0[0] * v1[0]; for (int i = 1; i < N; ++i) { dot += v0[i] * v1[i]; } return dot; } template <int N, typename Real> Real Length(Vector<N, Real> const& v, bool robust) { if (robust) { Real maxAbsComp = std::abs(v[0]); for (int i = 1; i < N; ++i) { Real absComp = std::abs(v[i]); if (absComp > maxAbsComp) { maxAbsComp = absComp; } } Real length; if (maxAbsComp > (Real)0) { Vector<N, Real> scaled = v / maxAbsComp; length = maxAbsComp * std::sqrt(Dot(scaled, scaled)); } else { length = (Real)0; } return length; } else { return std::sqrt(Dot(v, v)); } } template <int N, typename Real> Real Normalize(Vector<N, Real>& v, bool robust) { if (robust) { Real maxAbsComp = std::abs(v[0]); for (int i = 1; i < N; ++i) { Real absComp = std::abs(v[i]); if (absComp > maxAbsComp) { maxAbsComp = absComp; } } Real length; if (maxAbsComp > (Real)0) { v /= maxAbsComp; length = std::sqrt(Dot(v, v)); v /= length; length *= maxAbsComp; } else { length = (Real)0; for (int i = 0; i < N; ++i) { v[i] = (Real)0; } } return length; } else { Real length = std::sqrt(Dot(v, v)); if (length > (Real)0) { v /= length; } else { for (int i = 0; i < N; ++i) { v[i] = (Real)0; } } return length; } } template <int N, typename Real> Real Orthonormalize(int numInputs, Vector<N, Real>* v, bool robust) { if (v && 1 <= numInputs && numInputs <= N) { Real minLength = Normalize(v[0], robust); for (int i = 1; i < numInputs; ++i) { for (int j = 0; j < i; ++j) { Real dot = Dot(v[i], v[j]); v[i] -= v[j] * dot; } Real length = Normalize(v[i], robust); if (length < minLength) { minLength = length; } } return minLength; } return (Real)0; } template <int N, typename Real> Vector<N, Real> GetOrthogonal(Vector<N, Real> const& v, bool unitLength) { Real cmax = std::abs(v[0]); int imax = 0; for (int i = 1; i < N; ++i) { Real c = std::abs(v[i]); if (c > cmax) { cmax = c; imax = i; } } Vector<N, Real> result; result.MakeZero(); int inext = imax + 1; if (inext == N) { inext = 0; } result[imax] = v[inext]; result[inext] = -v[imax]; if (unitLength) { Real sqrDistance = result[imax] * result[imax] + result[inext] * result[inext]; Real invLength = ((Real)1) / std::sqrt(sqrDistance); result[imax] *= invLength; result[inext] *= invLength; } return result; } template <int N, typename Real> bool ComputeExtremes(int numVectors, Vector<N, Real> const* v, Vector<N, Real>& vmin, Vector<N, Real>& vmax) { if (v && numVectors > 0) { vmin = v[0]; vmax = vmin; for (int j = 1; j < numVectors; ++j) { Vector<N, Real> const& vec = v[j]; for (int i = 0; i < N; ++i) { if (vec[i] < vmin[i]) { vmin[i] = vec[i]; } else if (vec[i] > vmax[i]) { vmax[i] = vec[i]; } } } return true; } return false; } template <int N, typename Real> Vector<N + 1, Real> HLift(Vector<N, Real> const& v, Real last) { Vector<N + 1, Real> result; for (int i = 0; i < N; ++i) { result[i] = v[i]; } result[N] = last; return result; } template <int N, typename Real> Vector<N - 1, Real> HProject(Vector<N, Real> const& v) { static_assert(N >= 2, "Invalid dimension."); Vector<N - 1, Real> result; for (int i = 0; i < N - 1; ++i) { result[i] = v[i]; } return result; } template <int N, typename Real> Vector<N + 1, Real> Lift(Vector<N, Real> const& v, int inject, Real value) { Vector<N + 1, Real> result; int i; for (i = 0; i < inject; ++i) { result[i] = v[i]; } result[i] = value; int j = i; for (++j; i < N; ++i, ++j) { result[j] = v[i]; } return result; } template <int N, typename Real> Vector<N - 1, Real> Project(Vector<N, Real> const& v, int reject) { static_assert(N >= 2, "Invalid dimension."); Vector<N - 1, Real> result; for (int i = 0, j = 0; i < N - 1; ++i, ++j) { if (j == reject) { ++j; } result[i] = v[j]; } return result; } } // ---------------------------------------------- // GteVector3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.2 (2018/10/04) namespace gte { // Template alias for convenience. template <typename Real> using Vector3 = Vector<3, Real>; // Cross, UnitCross, and DotCross have a template parameter N that should // be 3 or 4. The latter case supports affine vectors in 4D (last component // w = 0) when you want to use 4-tuples and 4x4 matrices for affine algebra. // Compute the cross product using the formal determinant: // cross = det{{e0,e1,e2},{x0,x1,x2},{y0,y1,y2}} // = (x1*y2-x2*y1, x2*y0-x0*y2, x0*y1-x1*y0) // where e0 = (1,0,0), e1 = (0,1,0), e2 = (0,0,1), v0 = (x0,x1,x2), and // v1 = (y0,y1,y2). template <int N, typename Real> Vector<N,Real> Cross(Vector<N,Real> const& v0, Vector<N,Real> const& v1); // Compute the normalized cross product. template <int N, typename Real> Vector<N, Real> UnitCross(Vector<N,Real> const& v0, Vector<N,Real> const& v1, bool robust = false); // Compute Dot((x0,x1,x2),Cross((y0,y1,y2),(z0,z1,z2)), the triple scalar // product of three vectors, where v0 = (x0,x1,x2), v1 = (y0,y1,y2), and // v2 is (z0,z1,z2). template <int N, typename Real> Real DotCross(Vector<N,Real> const& v0, Vector<N,Real> const& v1, Vector<N,Real> const& v2); // Compute a right-handed orthonormal basis for the orthogonal complement // of the input vectors. The function returns the smallest length of the // unnormalized vectors computed during the process. If this value is nearly // zero, it is possible that the inputs are linearly dependent (within // numerical round-off errors). On input, numInputs must be 1 or 2 and // v[0] through v[numInputs-1] must be initialized. On output, the // vectors v[0] through v[2] form an orthonormal set. template <typename Real> Real ComputeOrthogonalComplement(int numInputs, Vector3<Real>* v, bool robust = false); // Compute the barycentric coordinates of the point P with respect to the // tetrahedron <V0,V1,V2,V3>, P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where // b0 + b1 + b2 + b3 = 1. The return value is 'true' iff {V0,V1,V2,V3} is // a linearly independent set. Numerically, this is measured by // |det[V0 V1 V2 V3]| <= epsilon. The values bary[] are valid only when the // return value is 'true' but set to zero when the return value is 'false'. template <typename Real> bool ComputeBarycentrics(Vector3<Real> const& p, Vector3<Real> const& v0, Vector3<Real> const& v1, Vector3<Real> const& v2, Vector3<Real> const& v3, Real bary[4], Real epsilon = (Real)0); // Get intrinsic information about the input array of vectors. The return // value is 'true' iff the inputs are valid (numVectors > 0, v is not null, // and epsilon >= 0), in which case the class members are valid. template <typename Real> class IntrinsicsVector3 { public: // The constructor sets the class members based on the input set. IntrinsicsVector3(int numVectors, Vector3<Real> const* v, Real inEpsilon); // A nonnegative tolerance that is used to determine the intrinsic // dimension of the set. Real epsilon; // The intrinsic dimension of the input set, computed based on the // nonnegative tolerance mEpsilon. int dimension; // Axis-aligned bounding box of the input set. The maximum range is // the larger of max[0]-min[0], max[1]-min[1], and max[2]-min[2]. Real min[3], max[3]; Real maxRange; // Coordinate system. The origin is valid for any dimension d. The // unit-length direction vector is valid only for 0 <= i < d. The // extreme index is relative to the array of input points, and is also // valid only for 0 <= i < d. If d = 0, all points are effectively // the same, but the use of an epsilon may lead to an extreme index // that is not zero. If d = 1, all points effectively lie on a line // segment. If d = 2, all points effectively line on a plane. If // d = 3, the points are not coplanar. Vector3<Real> origin; Vector3<Real> direction[3]; // The indices that define the maximum dimensional extents. The // values extreme[0] and extreme[1] are the indices for the points // that define the largest extent in one of the coordinate axis // directions. If the dimension is 2, then extreme[2] is the index // for the point that generates the largest extent in the direction // perpendicular to the line through the points corresponding to // extreme[0] and extreme[1]. Furthermore, if the dimension is 3, // then extreme[3] is the index for the point that generates the // largest extent in the direction perpendicular to the triangle // defined by the other extreme points. The tetrahedron formed by the // points V[extreme[0]], V[extreme[1]], V[extreme[2]], and // V[extreme[3]] is clockwise or counterclockwise, the condition // stored in extremeCCW. int extreme[4]; bool extremeCCW; }; template <int N, typename Real> Vector<N, Real> Cross(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Vector<N, Real> result; result.MakeZero(); result[0] = v0[1] * v1[2] - v0[2] * v1[1]; result[1] = v0[2] * v1[0] - v0[0] * v1[2]; result[2] = v0[0] * v1[1] - v0[1] * v1[0]; return result; } template <int N, typename Real> Vector<N, Real> UnitCross(Vector<N, Real> const& v0, Vector<N, Real> const& v1, bool robust) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Vector<N, Real> unitCross = Cross(v0, v1); Normalize(unitCross, robust); return unitCross; } template <int N, typename Real> Real DotCross(Vector<N, Real> const& v0, Vector<N, Real> const& v1, Vector<N, Real> const& v2) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); return Dot(v0, Cross(v1, v2)); } template <typename Real> Real ComputeOrthogonalComplement(int numInputs, Vector3<Real>* v, bool robust) { if (numInputs == 1) { if (std::abs(v[0][0]) > std::abs(v[0][1])) { v[1] = { -v[0][2], (Real)0, +v[0][0] }; } else { v[1] = { (Real)0, +v[0][2], -v[0][1] }; } numInputs = 2; } if (numInputs == 2) { v[2] = Cross(v[0], v[1]); return Orthonormalize<3, Real>(3, v, robust); } return (Real)0; } template <typename Real> bool ComputeBarycentrics(Vector3<Real> const& p, Vector3<Real> const& v0, Vector3<Real> const& v1, Vector3<Real> const& v2, Vector3<Real> const& v3, Real bary[4], Real epsilon) { // Compute the vectors relative to V3 of the tetrahedron. Vector3<Real> diff[4] = { v0 - v3, v1 - v3, v2 - v3, p - v3 }; Real det = DotCross(diff[0], diff[1], diff[2]); if (det < -epsilon || det > epsilon) { Real invDet = ((Real)1) / det; bary[0] = DotCross(diff[3], diff[1], diff[2]) * invDet; bary[1] = DotCross(diff[3], diff[2], diff[0]) * invDet; bary[2] = DotCross(diff[3], diff[0], diff[1]) * invDet; bary[3] = (Real)1 - bary[0] - bary[1] - bary[2]; return true; } for (int i = 0; i < 4; ++i) { bary[i] = (Real)0; } return false; } template <typename Real> IntrinsicsVector3<Real>::IntrinsicsVector3(int numVectors, Vector3<Real> const* v, Real inEpsilon) : epsilon(inEpsilon), dimension(0), maxRange((Real)0), origin({ (Real)0, (Real)0, (Real)0 }), extremeCCW(false) { min[0] = (Real)0; min[1] = (Real)0; min[2] = (Real)0; direction[0] = { (Real)0, (Real)0, (Real)0 }; direction[1] = { (Real)0, (Real)0, (Real)0 }; direction[2] = { (Real)0, (Real)0, (Real)0 }; extreme[0] = 0; extreme[1] = 0; extreme[2] = 0; extreme[3] = 0; if (numVectors > 0 && v && epsilon >= (Real)0) { // Compute the axis-aligned bounding box for the input vectors. Keep // track of the indices into 'vectors' for the current min and max. int j, indexMin[3], indexMax[3]; for (j = 0; j < 3; ++j) { min[j] = v[0][j]; max[j] = min[j]; indexMin[j] = 0; indexMax[j] = 0; } int i; for (i = 1; i < numVectors; ++i) { for (j = 0; j < 3; ++j) { if (v[i][j] < min[j]) { min[j] = v[i][j]; indexMin[j] = i; } else if (v[i][j] > max[j]) { max[j] = v[i][j]; indexMax[j] = i; } } } // Determine the maximum range for the bounding box. maxRange = max[0] - min[0]; extreme[0] = indexMin[0]; extreme[1] = indexMax[0]; Real range = max[1] - min[1]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[1]; extreme[1] = indexMax[1]; } range = max[2] - min[2]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[2]; extreme[1] = indexMax[2]; } // The origin is either the vector of minimum x0-value, vector of // minimum x1-value, or vector of minimum x2-value. origin = v[extreme[0]]; // Test whether the vector set is (nearly) a vector. if (maxRange <= epsilon) { dimension = 0; for (j = 0; j < 3; ++j) { extreme[j + 1] = extreme[0]; } return; } // Test whether the vector set is (nearly) a line segment. We need // {direction[2],direction[3]} to span the orthogonal complement of // direction[0]. direction[0] = v[extreme[1]] - origin; Normalize(direction[0], false); if (std::abs(direction[0][0]) > std::abs(direction[0][1])) { direction[1][0] = -direction[0][2]; direction[1][1] = (Real)0; direction[1][2] = +direction[0][0]; } else { direction[1][0] = (Real)0; direction[1][1] = +direction[0][2]; direction[1][2] = -direction[0][1]; } Normalize(direction[1], false); direction[2] = Cross(direction[0], direction[1]); // Compute the maximum distance of the points from the line // origin+t*direction[0]. Real maxDistance = (Real)0; Real distance, dot; extreme[2] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector3<Real> diff = v[i] - origin; dot = Dot(direction[0], diff); Vector3<Real> proj = diff - dot * direction[0]; distance = Length(proj, false); if (distance > maxDistance) { maxDistance = distance; extreme[2] = i; } } if (maxDistance <= epsilon*maxRange) { // The points are (nearly) on the line origin+t*direction[0]. dimension = 1; extreme[2] = extreme[1]; extreme[3] = extreme[1]; return; } // Test whether the vector set is (nearly) a planar polygon. The // point v[extreme[2]] is farthest from the line: origin + // t*direction[0]. The vector v[extreme[2]]-origin is not // necessarily perpendicular to direction[0], so project out the // direction[0] component so that the result is perpendicular to // direction[0]. direction[1] = v[extreme[2]] - origin; dot = Dot(direction[0], direction[1]); direction[1] -= dot * direction[0]; Normalize(direction[1], false); // We need direction[2] to span the orthogonal complement of // {direction[0],direction[1]}. direction[2] = Cross(direction[0], direction[1]); // Compute the maximum distance of the points from the plane // origin+t0*direction[0]+t1*direction[1]. maxDistance = (Real)0; Real maxSign = (Real)0; extreme[3] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector3<Real> diff = v[i] - origin; distance = Dot(direction[2], diff); Real sign = (distance >(Real)0 ? (Real)1 : (distance < (Real)0 ? (Real)-1 : (Real)0)); distance = std::abs(distance); if (distance > maxDistance) { maxDistance = distance; maxSign = sign; extreme[3] = i; } } if (maxDistance <= epsilon * maxRange) { // The points are (nearly) on the plane origin+t0*direction[0] // +t1*direction[1]. dimension = 2; extreme[3] = extreme[2]; return; } dimension = 3; extremeCCW = (maxSign > (Real)0); return; } } } // ---------------------------------------------- // GteHypersphere.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // The hypersphere is represented as |X-C| = R where C is the center and R is // the radius. The hypersphere is a circle for dimension 2 or a sphere for // dimension 3. namespace gte { template <int N, typename Real> class Hypersphere { public: // Construction and destruction. The default constructor sets the center // to (0,...,0) and the radius to 1. Hypersphere(); Hypersphere(Vector<N, Real> const& inCenter, Real inRadius); // Public member access. Vector<N, Real> center; Real radius; public: // Comparisons to support sorted containers. bool operator==(Hypersphere const& hypersphere) const; bool operator!=(Hypersphere const& hypersphere) const; bool operator< (Hypersphere const& hypersphere) const; bool operator<=(Hypersphere const& hypersphere) const; bool operator> (Hypersphere const& hypersphere) const; bool operator>=(Hypersphere const& hypersphere) const; }; // Template aliases for convenience. template <typename Real> using Circle2 = Hypersphere<2, Real>; template <typename Real> using Sphere3 = Hypersphere<3, Real>; template <int N, typename Real> Hypersphere<N, Real>::Hypersphere() : radius((Real)1) { center.MakeZero(); } template <int N, typename Real> Hypersphere<N, Real>::Hypersphere(Vector<N, Real> const& inCenter, Real inRadius) : center(inCenter), radius(inRadius) { } template <int N, typename Real> bool Hypersphere<N, Real>::operator==(Hypersphere const& hypersphere) const { return center == hypersphere.center && radius == hypersphere.radius; } template <int N, typename Real> bool Hypersphere<N, Real>::operator!=(Hypersphere const& hypersphere) const { return !operator==(hypersphere); } template <int N, typename Real> bool Hypersphere<N, Real>::operator<(Hypersphere const& hypersphere) const { if (center < hypersphere.center) { return true; } if (center > hypersphere.center) { return false; } return radius < hypersphere.radius; } template <int N, typename Real> bool Hypersphere<N, Real>::operator<=(Hypersphere const& hypersphere) const { return operator<(hypersphere) || operator==(hypersphere); } template <int N, typename Real> bool Hypersphere<N, Real>::operator>(Hypersphere const& hypersphere) const { return !operator<=(hypersphere); } template <int N, typename Real> bool Hypersphere<N, Real>::operator>=(Hypersphere const& hypersphere) const { return !operator<(hypersphere); } } // ---------------------------------------------- // GteOrientedBox.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // A box has center C, axis directions U[i], and extents e[i]. The set // {U[0],...,U[N-1]} is orthonormal, which means the vectors are // unit-length and mutually perpendicular. The extents are nonnegative; // zero is allowed, meaning the box is degenerate in the corresponding // direction. A point X is represented in box coordinates by // X = C + y[0]*U[0] + y[1]*U[1]. This point is inside or on the // box whenever |y[i]| <= e[i] for all i. namespace gte { template <int N, typename Real> class OrientedBox { public: // Construction and destruction. The default constructor sets the center // to (0,...,0), axis d to Vector<N,Real>::Unit(d), and extent d to +1. OrientedBox(); OrientedBox(Vector<N, Real> const& inCenter, std::array<Vector<N, Real>, N> const& inAxis, Vector<N, Real> const& inExtent); // Compute the vertices of the box. If index i has the bit pattern // i = b[N-1]...b[0], then // vertex[i] = center + sum_{d=0}^{N-1} sign[d] * extent[d] * axis[d] // where sign[d] = 2*b[d] - 1. void GetVertices(std::array<Vector<N, Real>, (1 << N)>& vertex) const; // Public member access. It is required that extent[i] >= 0. Vector<N, Real> center; std::array<Vector<N, Real>, N> axis; Vector<N, Real> extent; public: // Comparisons to support sorted containers. bool operator==(OrientedBox const& box) const; bool operator!=(OrientedBox const& box) const; bool operator< (OrientedBox const& box) const; bool operator<=(OrientedBox const& box) const; bool operator> (OrientedBox const& box) const; bool operator>=(OrientedBox const& box) const; }; // Template aliases for convenience. template <typename Real> using OrientedBox2 = OrientedBox<2, Real>; template <typename Real> using OrientedBox3 = OrientedBox<3, Real>; template <int N, typename Real> OrientedBox<N, Real>::OrientedBox() { center.MakeZero(); for (int i = 0; i < N; ++i) { axis[i].MakeUnit(i); extent[i] = (Real)1; } } template <int N, typename Real> OrientedBox<N, Real>::OrientedBox(Vector<N, Real> const& inCenter, std::array<Vector<N, Real>, N> const& inAxis, Vector<N, Real> const& inExtent) : center(inCenter), axis(inAxis), extent(inExtent) { } template <int N, typename Real> void OrientedBox<N, Real>::GetVertices( std::array<Vector<N, Real>, (1 << N)>& vertex) const { unsigned int const dsup = static_cast<unsigned int>(N); std::array<Vector<N, Real>, N> product; for (unsigned int d = 0; d < dsup; ++d) { product[d] = extent[d] * axis[d]; } int const imax = (1 << N); for (int i = 0; i < imax; ++i) { vertex[i] = center; for (unsigned int d = 0, mask = 1; d < dsup; ++d, mask <<= 1) { Real sign = (i & mask ? (Real)1 : (Real)-1); vertex[i] += sign * product[d]; } } } template <int N, typename Real> bool OrientedBox<N, Real>::operator==(OrientedBox const& box) const { return center == box.center && axis == box.axis && extent == box.extent; } template <int N, typename Real> bool OrientedBox<N, Real>::operator!=(OrientedBox const& box) const { return !operator==(box); } template <int N, typename Real> bool OrientedBox<N, Real>::operator<(OrientedBox const& box) const { if (center < box.center) { return true; } if (center > box.center) { return false; } if (axis < box.axis) { return true; } if (axis > box.axis) { return false; } return extent < box.extent; } template <int N, typename Real> bool OrientedBox<N, Real>::operator<=(OrientedBox const& box) const { return operator<(box) || operator==(box); } template <int N, typename Real> bool OrientedBox<N, Real>::operator>(OrientedBox const& box) const { return !operator<=(box); } template <int N, typename Real> bool OrientedBox<N, Real>::operator>=(OrientedBox const& box) const { return !operator<(box); } } // ---------------------------------------------- // GteFeatureKey.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) namespace gte { template <int N, bool Ordered> class FeatureKey { protected: // Abstract base class with V[] uninitialized. The derived classes must // set the V[] values accordingly. // // An ordered feature key has V[0] = min(V[]) with (V[0],V[1],...,V[N-1]) a // permutation of N inputs with an even number of transpositions. // // An unordered feature key has V[0] < V[1] < ... < V[N-1]. // // Note that the word 'order' is about the geometry of the feature, not // the comparison order for any sorting. FeatureKey(); public: bool operator<(FeatureKey const& key) const; bool operator==(FeatureKey const& key) const; int V[N]; }; template <int N, bool Ordered> FeatureKey<N, Ordered>::FeatureKey() { } template <int N, bool Ordered> bool FeatureKey<N, Ordered>::operator<(FeatureKey const& key) const { for (int i = N - 1; i >= 0; --i) { if (V[i] < key.V[i]) { return true; } if (V[i] > key.V[i]) { return false; } } return false; } template <int N, bool Ordered> bool FeatureKey<N, Ordered>::operator==(FeatureKey const& key) const { for (int i = 0; i < N; ++i) { if (V[i] != key.V[i]) { return false; } } return true; } } // ---------------------------------------------- // GteEdgeKey.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/05/22) namespace gte { template <bool Ordered> class EdgeKey : public FeatureKey<2, Ordered> { public: // An ordered edge has (V[0],V[1]) = (v0,v1). An unordered edge has // (V[0],V[1]) = (min(V[0],V[1]),max(V[0],V[1])). EdgeKey(); // creates key (-1,-1) explicit EdgeKey(int v0, int v1); }; template<> inline EdgeKey<true>::EdgeKey() { V[0] = -1; V[1] = -1; } template<> inline EdgeKey<true>::EdgeKey(int v0, int v1) { V[0] = v0; V[1] = v1; } template<> inline EdgeKey<false>::EdgeKey() { V[0] = -1; V[1] = -1; } template<> inline EdgeKey<false>::EdgeKey(int v0, int v1) { if (v0 < v1) { // v0 is minimum V[0] = v0; V[1] = v1; } else { // v1 is minimum V[0] = v1; V[1] = v0; } } } // ---------------------------------------------- // GteTriangleKey.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/05/22) namespace gte { template <bool Ordered> class TriangleKey : public FeatureKey<3, Ordered> { public: // An ordered triangle has V[0] = min(v0,v1,v2). Choose // (V[0],V[1],V[2]) to be a permutation of (v0,v1,v2) so that the // final storage is one of // (v0,v1,v2), (v1,v2,v0), (v2,v0,v1) // The idea is that if v0 corresponds to (1,0,0), v1 corresponds to // (0,1,0), and v2 corresponds to (0,0,1), the ordering (v0,v1,v2) // corresponds to the 3x3 identity matrix I; the rows are the // specified 3-tuples. The permutation (V[0],V[1],V[2]) induces a // permutation of the rows of the identity matrix to form a // permutation matrix P with det(P) = 1 = det(I). // // An unordered triangle stores a permutation of (v0,v1,v2) so that // V[0] < V[1] < V[2]. TriangleKey(); // creates key (-1,-1,-1) explicit TriangleKey(int v0, int v1, int v2); }; template<> inline TriangleKey<true>::TriangleKey() { V[0] = -1; V[1] = -1; V[2] = -1; } template<> inline TriangleKey<true>::TriangleKey(int v0, int v1, int v2) { if (v0 < v1) { if (v0 < v2) { // v0 is minimum V[0] = v0; V[1] = v1; V[2] = v2; } else { // v2 is minimum V[0] = v2; V[1] = v0; V[2] = v1; } } else { if (v1 < v2) { // v1 is minimum V[0] = v1; V[1] = v2; V[2] = v0; } else { // v2 is minimum V[0] = v2; V[1] = v0; V[2] = v1; } } } template<> inline TriangleKey<false>::TriangleKey() { V[0] = -1; V[1] = -1; V[2] = -1; } template<> inline TriangleKey<false>::TriangleKey(int v0, int v1, int v2) { if (v0 < v1) { if (v0 < v2) { // v0 is minimum V[0] = v0; V[1] = std::min(v1, v2); V[2] = std::max(v1, v2); } else { // v2 is minimum V[0] = v2; V[1] = std::min(v0, v1); V[2] = std::max(v0, v1); } } else { if (v1 < v2) { // v1 is minimum V[0] = v1; V[1] = std::min(v2, v0); V[2] = std::max(v2, v0); } else { // v2 is minimum V[0] = v2; V[1] = std::min(v0, v1); V[2] = std::max(v0, v1); } } } } // ---------------------------------------------- // GteETManifoldMesh.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2017/01/02) namespace gte { class GTE_IMPEXP ETManifoldMesh { public: // Edge data types. class Edge; typedef std::shared_ptr<Edge> (*ECreator)(int, int); typedef std::map<EdgeKey<false>, std::shared_ptr<Edge>> EMap; // Triangle data types. class Triangle; typedef std::shared_ptr<Triangle> (*TCreator)(int, int, int); typedef std::map<TriangleKey<true>, std::shared_ptr<Triangle>> TMap; // Edge object. class GTE_IMPEXP Edge { public: virtual ~Edge(); Edge(int v0, int v1); // Vertices of the edge. int V[2]; // Triangles sharing the edge. std::weak_ptr<Triangle> T[2]; }; // Triangle object. class GTE_IMPEXP Triangle { public: virtual ~Triangle(); Triangle(int v0, int v1, int v2); // Vertices, listed in counterclockwise order (V[0],V[1],V[2]). int V[3]; // Adjacent edges. E[i] points to edge (V[i],V[(i+1)%3]). std::weak_ptr<Edge> E[3]; // Adjacent triangles. T[i] points to the adjacent triangle // sharing edge E[i]. std::weak_ptr<Triangle> T[3]; }; // Construction and destruction. virtual ~ETManifoldMesh(); ETManifoldMesh(ECreator eCreator = nullptr, TCreator tCreator = nullptr); // Support for a deep copy of the mesh. The mEMap and mTMap objects have // dynamically allocated memory for edges and triangles. A shallow copy // of the pointers to this memory is problematic. Allowing sharing, say, // via std::shared_ptr, is an option but not really the intent of copying // the mesh graph. ETManifoldMesh(ETManifoldMesh const& mesh); ETManifoldMesh& operator=(ETManifoldMesh const& mesh); // Member access. EMap const& GetEdges() const; TMap const& GetTriangles() const; // If the insertion of a triangle fails because the mesh would become // nonmanifold, the default behavior is to trigger a LogError message. // You can disable this behavior in situations where you want the Logger // system on but you want to continue gracefully without an assertion. // The return value is the previous value of the internal state // mAssertOnNonmanifoldInsertion. bool AssertOnNonmanifoldInsertion(bool doAssert); // If <v0,v1,v2> is not in the mesh, a Triangle object is created and // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is returned. // If the insertion leads to a nonmanifold mesh, the call fails with a // nullptr returned. virtual std::shared_ptr<Triangle> Insert(int v0, int v1, int v2); // If <v0,v1,v2> is in the mesh, it is removed and 'true' is returned; // otherwise, <v0,v1,v2> is not in the mesh and 'false' is returned. virtual bool Remove(int v0, int v1, int v2); // Destroy the edges and triangles to obtain an empty mesh. virtual void Clear(); // A manifold mesh is closed if each edge is shared twice. A closed // mesh is not necessarily oriented. For example, you could have a // mesh with spherical topology. The upper hemisphere has outer-facing // normals and the lower hemisphere has inner-facing normals. The // discontinuity in orientation occurs on the circle shared by the // hemispheres. bool IsClosed() const; // Test whether all triangles in the mesh are oriented consistently and // that no two triangles are coincident. The latter means that you // cannot have both triangles <v0,v1,v2> and <v0,v2,v1> in the mesh to // be considered oriented. bool IsOriented() const; // Compute the connected components of the edge-triangle graph that the // mesh represents. The first function returns pointers into 'this' // object's containers, so you must consume the components before // clearing or destroying 'this'. The second function returns triangle // keys, which requires three times as much storage as the pointers but // allows you to clear or destroy 'this' before consuming the components. void GetComponents(std::vector<std::vector<std::shared_ptr<Triangle>>>& components) const; void GetComponents(std::vector<std::vector<TriangleKey<true>>>& components) const; protected: // The edge data and default edge creation. static std::shared_ptr<Edge> CreateEdge(int v0, int v1); ECreator mECreator; EMap mEMap; // The triangle data and default triangle creation. static std::shared_ptr<Triangle> CreateTriangle(int v0, int v1, int v2); TCreator mTCreator; TMap mTMap; bool mAssertOnNonmanifoldInsertion; // default: true // Support for computing connected components. This is a straightforward // depth-first search of the graph but uses a preallocated stack rather // than a recursive function that could possibly overflow the call stack. void DepthFirstSearch(std::shared_ptr<Triangle> const& tInitial, std::map<std::shared_ptr<Triangle>, int>& visited, std::vector<std::shared_ptr<Triangle>>& component) const; }; } // ---------------------------------------------- // GteLine.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // The line is represented by P+t*D, where P is an origin point, D is a // unit-length direction vector, and t is any real number. The user must // ensure that D is unit length. namespace gte { template <int N, typename Real> class Line { public: // Construction and destruction. The default constructor sets the origin // to (0,...,0) and the line direction to (1,0,...,0). Line(); Line(Vector<N, Real> const& inOrigin, Vector<N, Real> const& inDirection); // Public member access. The direction must be unit length. Vector<N, Real> origin, direction; public: // Comparisons to support sorted containers. bool operator==(Line const& line) const; bool operator!=(Line const& line) const; bool operator< (Line const& line) const; bool operator<=(Line const& line) const; bool operator> (Line const& line) const; bool operator>=(Line const& line) const; }; // Template aliases for convenience. template <typename Real> using Line2 = Line<2, Real>; template <typename Real> using Line3 = Line<3, Real>; template <int N, typename Real> Line<N, Real>::Line() { origin.MakeZero(); direction.MakeUnit(0); } template <int N, typename Real> Line<N, Real>::Line(Vector<N, Real> const& inOrigin, Vector<N, Real> const& inDirection) : origin(inOrigin), direction(inDirection) { } template <int N, typename Real> bool Line<N, Real>::operator==(Line const& line) const { return origin == line.origin && direction == line.direction; } template <int N, typename Real> bool Line<N, Real>::operator!=(Line const& line) const { return !operator==(line); } template <int N, typename Real> bool Line<N, Real>::operator<(Line const& line) const { if (origin < line.origin) { return true; } if (origin > line.origin) { return false; } return direction < line.direction; } template <int N, typename Real> bool Line<N, Real>::operator<=(Line const& line) const { return operator<(line) || operator==(line); } template <int N, typename Real> bool Line<N, Real>::operator>(Line const& line) const { return !operator<=(line); } template <int N, typename Real> bool Line<N, Real>::operator>=(Line const& line) const { return !operator<(line); } } // ---------------------------------------------- // GtePrimalQuery3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Queries about the relation of a point to various geometric objects. The // choices for N when using UIntegerFP32<N> for either BSNumber of BSRational // are determined in GeometricTools/GTEngine/Tools/PrecisionCalculator. These // N-values are worst case scenarios. Your specific input data might require // much smaller N, in which case you can modify PrecisionCalculator to use the // BSPrecision(int32_t,int32_t,int32_t,bool) constructors. namespace gte { template <typename Real> class PrimalQuery3 { public: // The caller is responsible for ensuring that the array is not empty // before calling queries and that the indices passed to the queries are // valid. The class does no range checking. PrimalQuery3(); PrimalQuery3(int numVertices, Vector3<Real> const* vertices); // Member access. inline void Set(int numVertices, Vector3<Real> const* vertices); inline int GetNumVertices() const; inline Vector3<Real> const* GetVertices() const; // In the following, point P refers to vertices[i] or 'test' and Vi refers // to vertices[vi]. // For a plane with origin V0 and normal N = Cross(V1-V0,V2-V0), ToPlane // returns // +1, P on positive side of plane (side to which N points) // -1, P on negative side of plane (side to which -N points) // 0, P on the plane // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 27 // double | BSNumber | 197 // float | BSRational | 2882 // double | BSRational | 21688 int ToPlane(int i, int v0, int v1, int v2) const; int ToPlane(Vector3<Real> const& test, int v0, int v1, int v2) const; // For a tetrahedron with vertices ordered as described in the file // GteTetrahedronKey.h, the function returns // +1, P outside tetrahedron // -1, P inside tetrahedron // 0, P on tetrahedron // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+---- // float | BSNumber | 27 // double | BSNumber | 197 // float | BSRational | 2882 // double | BSRational | 21688 // The query involves four calls of ToPlane, so the numbers match those // of ToPlane. int ToTetrahedron(int i, int v0, int v1, int v2, int v3) const; int ToTetrahedron(Vector3<Real> const& test, int v0, int v1, int v2, int v3) const; // For a tetrahedron with vertices ordered as described in the file // GteTetrahedronKey.h, the function returns // +1, P outside circumsphere of tetrahedron // -1, P inside circumsphere of tetrahedron // 0, P on circumsphere of tetrahedron // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+-------- // float | BSNumber | 44 // float | BSRational | 329 // double | BSNumber | 298037 // double | BSRational | 2254442 int ToCircumsphere(int i, int v0, int v1, int v2, int v3) const; int ToCircumsphere(Vector3<Real> const& test, int v0, int v1, int v2, int v3) const; private: int mNumVertices; Vector3<Real> const* mVertices; }; template <typename Real> PrimalQuery3<Real>::PrimalQuery3() : mNumVertices(0), mVertices(nullptr) { } template <typename Real> PrimalQuery3<Real>::PrimalQuery3(int numVertices, Vector3<Real> const* vertices) : mNumVertices(numVertices), mVertices(vertices) { } template <typename Real> inline void PrimalQuery3<Real>::Set(int numVertices, Vector3<Real> const* vertices) { mNumVertices = numVertices; mVertices = vertices; } template <typename Real> inline int PrimalQuery3<Real>::GetNumVertices() const { return mNumVertices; } template <typename Real> inline Vector3<Real> const* PrimalQuery3<Real>::GetVertices() const { return mVertices; } template <typename Real> int PrimalQuery3<Real>::ToPlane(int i, int v0, int v1, int v2) const { return ToPlane(mVertices[i], v0, v1, v2); } template <typename Real> int PrimalQuery3<Real>::ToPlane(Vector3<Real> const& test, int v0, int v1, int v2) const { Vector3<Real> const& vec0 = mVertices[v0]; Vector3<Real> const& vec1 = mVertices[v1]; Vector3<Real> const& vec2 = mVertices[v2]; Real x0 = test[0] - vec0[0]; Real y0 = test[1] - vec0[1]; Real z0 = test[2] - vec0[2]; Real x1 = vec1[0] - vec0[0]; Real y1 = vec1[1] - vec0[1]; Real z1 = vec1[2] - vec0[2]; Real x2 = vec2[0] - vec0[0]; Real y2 = vec2[1] - vec0[1]; Real z2 = vec2[2] - vec0[2]; Real y1z2 = y1*z2; Real y2z1 = y2*z1; Real y2z0 = y2*z0; Real y0z2 = y0*z2; Real y0z1 = y0*z1; Real y1z0 = y1*z0; Real c0 = y1z2 - y2z1; Real c1 = y2z0 - y0z2; Real c2 = y0z1 - y1z0; Real x0c0 = x0*c0; Real x1c1 = x1*c1; Real x2c2 = x2*c2; Real term = x0c0 + x1c1; Real det = term + x2c2; Real const zero(0); return (det > zero ? +1 : (det < zero ? -1 : 0)); } template <typename Real> int PrimalQuery3<Real>::ToTetrahedron(int i, int v0, int v1, int v2, int v3) const { return ToTetrahedron(mVertices[i], v0, v1, v2, v3); } template <typename Real> int PrimalQuery3<Real>::ToTetrahedron(Vector3<Real> const& test, int v0, int v1, int v2, int v3) const { int sign0 = ToPlane(test, v1, v2, v3); if (sign0 > 0) { return +1; } int sign1 = ToPlane(test, v0, v2, v3); if (sign1 < 0) { return +1; } int sign2 = ToPlane(test, v0, v1, v3); if (sign2 > 0) { return +1; } int sign3 = ToPlane(test, v0, v1, v2); if (sign3 < 0) { return +1; } return ((sign0 && sign1 && sign2 && sign3) ? -1 : 0); } template <typename Real> int PrimalQuery3<Real>::ToCircumsphere(int i, int v0, int v1, int v2, int v3) const { return ToCircumsphere(mVertices[i], v0, v1, v2, v3); } template <typename Real> int PrimalQuery3<Real>::ToCircumsphere(Vector3<Real> const& test, int v0, int v1, int v2, int v3) const { Vector3<Real> const& vec0 = mVertices[v0]; Vector3<Real> const& vec1 = mVertices[v1]; Vector3<Real> const& vec2 = mVertices[v2]; Vector3<Real> const& vec3 = mVertices[v3]; Real x0 = vec0[0] - test[0]; Real y0 = vec0[1] - test[1]; Real z0 = vec0[2] - test[2]; Real s00 = vec0[0] + test[0]; Real s01 = vec0[1] + test[1]; Real s02 = vec0[2] + test[2]; Real t00 = s00*x0; Real t01 = s01*y0; Real t02 = s02*z0; Real t00pt01 = t00 + t01; Real w0 = t00pt01 + t02; Real x1 = vec1[0] - test[0]; Real y1 = vec1[1] - test[1]; Real z1 = vec1[2] - test[2]; Real s10 = vec1[0] + test[0]; Real s11 = vec1[1] + test[1]; Real s12 = vec1[2] + test[2]; Real t10 = s10*x1; Real t11 = s11*y1; Real t12 = s12*z1; Real t10pt11 = t10 + t11; Real w1 = t10pt11 + t12; Real x2 = vec2[0] - test[0]; Real y2 = vec2[1] - test[1]; Real z2 = vec2[2] - test[2]; Real s20 = vec2[0] + test[0]; Real s21 = vec2[1] + test[1]; Real s22 = vec2[2] + test[2]; Real t20 = s20*x2; Real t21 = s21*y2; Real t22 = s22*z2; Real t20pt21 = t20 + t21; Real w2 = t20pt21 + t22; Real x3 = vec3[0] - test[0]; Real y3 = vec3[1] - test[1]; Real z3 = vec3[2] - test[2]; Real s30 = vec3[0] + test[0]; Real s31 = vec3[1] + test[1]; Real s32 = vec3[2] + test[2]; Real t30 = s30*x3; Real t31 = s31*y3; Real t32 = s32*z3; Real t30pt31 = t30 + t31; Real w3 = t30pt31 + t32; Real x0y1 = x0*y1; Real x0y2 = x0*y2; Real x0y3 = x0*y3; Real x1y0 = x1*y0; Real x1y2 = x1*y2; Real x1y3 = x1*y3; Real x2y0 = x2*y0; Real x2y1 = x2*y1; Real x2y3 = x2*y3; Real x3y0 = x3*y0; Real x3y1 = x3*y1; Real x3y2 = x3*y2; Real a0 = x0y1 - x1y0; Real a1 = x0y2 - x2y0; Real a2 = x0y3 - x3y0; Real a3 = x1y2 - x2y1; Real a4 = x1y3 - x3y1; Real a5 = x2y3 - x3y2; Real z0w1 = z0*w1; Real z0w2 = z0*w2; Real z0w3 = z0*w3; Real z1w0 = z1*w0; Real z1w2 = z1*w2; Real z1w3 = z1*w3; Real z2w0 = z2*w0; Real z2w1 = z2*w1; Real z2w3 = z2*w3; Real z3w0 = z3*w0; Real z3w1 = z3*w1; Real z3w2 = z3*w2; Real b0 = z0w1 - z1w0; Real b1 = z0w2 - z2w0; Real b2 = z0w3 - z3w0; Real b3 = z1w2 - z2w1; Real b4 = z1w3 - z3w1; Real b5 = z2w3 - z3w2; Real a0b5 = a0*b5; Real a1b4 = a1*b4; Real a2b3 = a2*b3; Real a3b2 = a3*b2; Real a4b1 = a4*b1; Real a5b0 = a5*b0; Real term0 = a0b5 - a1b4; Real term1 = term0 + a2b3; Real term2 = term1 + a3b2; Real term3 = term2 - a4b1; Real det = term3 + a5b0; Real const zero(0); return (det > zero ? 1 : (det < zero ? -1 : 0)); } } // ---------------------------------------------- // GteLexicoArray2.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) namespace gte { // A template class to provide 2D array access that conforms to row-major // order (RowMajor = true) or column-major order (RowMajor = false). The template <bool RowMajor, typename Real, int... Dimensions> class LexicoArray2 {}; // The array dimensions are known only at run time. template <typename Real> class LexicoArray2<true, Real> { public: inline LexicoArray2(int numRows, int numCols, Real* matrix); inline int GetNumRows() const; inline int GetNumCols() const; inline Real& operator()(int r, int c); inline Real const& operator()(int r, int c) const; private: int mNumRows, mNumCols; Real* mMatrix; }; template <typename Real> class LexicoArray2<false, Real> { public: inline LexicoArray2(int numRows, int numCols, Real* matrix); inline int GetNumRows() const; inline int GetNumCols() const; inline Real& operator()(int r, int c); inline Real const& operator()(int r, int c) const; private: int mNumRows, mNumCols; Real* mMatrix; }; // The array dimensions are known at compile time. template <typename Real, int NumRows, int NumCols> class LexicoArray2<true, Real, NumRows, NumCols> { public: inline LexicoArray2(Real* matrix); inline int GetNumRows() const; inline int GetNumCols() const; inline Real& operator()(int r, int c); inline Real const& operator()(int r, int c) const; private: Real* mMatrix; }; template <typename Real, int NumRows, int NumCols> class LexicoArray2<false, Real, NumRows, NumCols> { public: inline LexicoArray2(Real* matrix); inline int GetNumRows() const; inline int GetNumCols() const; inline Real& operator()(int r, int c); inline Real const& operator()(int r, int c) const; private: Real* mMatrix; }; template <typename Real> inline LexicoArray2<true, Real>::LexicoArray2(int numRows, int numCols, Real* matrix) : mNumRows(numRows), mNumCols(numCols), mMatrix(matrix) { } template <typename Real> inline int LexicoArray2<true, Real>::GetNumRows() const { return mNumRows; } template <typename Real> inline int LexicoArray2<true, Real>::GetNumCols() const { return mNumCols; } template <typename Real> inline Real& LexicoArray2<true, Real>::operator()(int r, int c) { return mMatrix[c + mNumCols*r]; } template <typename Real> inline Real const& LexicoArray2<true, Real>::operator()(int r, int c) const { return mMatrix[c + mNumCols*r]; } template <typename Real> inline LexicoArray2<false, Real>::LexicoArray2(int numRows, int numCols, Real* matrix) : mNumRows(numRows), mNumCols(numCols), mMatrix(matrix) { } template <typename Real> inline int LexicoArray2<false, Real>::GetNumRows() const { return mNumRows; } template <typename Real> inline int LexicoArray2<false, Real>::GetNumCols() const { return mNumCols; } template <typename Real> inline Real& LexicoArray2<false, Real>::operator()(int r, int c) { return mMatrix[r + mNumRows*c]; } template <typename Real> inline Real const& LexicoArray2<false, Real>::operator()(int r, int c) const { return mMatrix[r + mNumRows*c]; } template <typename Real, int NumRows, int NumCols> inline LexicoArray2<true, Real, NumRows, NumCols>::LexicoArray2(Real* matrix) : mMatrix(matrix) { } template <typename Real, int NumRows, int NumCols> inline int LexicoArray2<true, Real, NumRows, NumCols>::GetNumRows() const { return NumRows; } template <typename Real, int NumRows, int NumCols> inline int LexicoArray2<true, Real, NumRows, NumCols>::GetNumCols() const { return NumCols; } template <typename Real, int NumRows, int NumCols> inline Real& LexicoArray2<true, Real, NumRows, NumCols>::operator()(int r, int c) { return mMatrix[c + NumCols*r]; } template <typename Real, int NumRows, int NumCols> inline Real const& LexicoArray2<true, Real, NumRows, NumCols>::operator()(int r, int c) const { return mMatrix[c + NumCols*r]; } template <typename Real, int NumRows, int NumCols> inline LexicoArray2<false, Real, NumRows, NumCols>::LexicoArray2(Real* matrix) : mMatrix(matrix) { } template <typename Real, int NumRows, int NumCols> inline int LexicoArray2<false, Real, NumRows, NumCols>::GetNumRows() const { return NumRows; } template <typename Real, int NumRows, int NumCols> inline int LexicoArray2<false, Real, NumRows, NumCols>::GetNumCols() const { return NumCols; } template <typename Real, int NumRows, int NumCols> inline Real& LexicoArray2<false, Real, NumRows, NumCols>::operator()(int r, int c) { return mMatrix[r + NumRows*c]; } template <typename Real, int NumRows, int NumCols> inline Real const& LexicoArray2<false, Real, NumRows, NumCols>::operator()(int r, int c) const { return mMatrix[r + NumRows*c]; } } // ---------------------------------------------- // GteGaussianElimination.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // The input matrix M must be NxN. The storage convention for element lookup // is determined by GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR, whichever is // active. If you want the inverse of M, pass a nonnull pointer inverseM; // this matrix must also be NxN and use the same storage convention as M. If // you do not want the inverse of M, pass a nullptr for inverseM. If you want // to solve M*X = B for X, where X and B are Nx1, pass nonnull pointers for B // and X. If you want to solve M*Y = C for Y, where X and C are NxK, pass // nonnull pointers for C and Y and pass K to numCols. In all cases, pass // N to numRows. namespace gte { template <typename Real> class GaussianElimination { public: bool operator()(int numRows, Real const* M, Real* inverseM, Real& determinant, Real const* B, Real* X, Real const* C, int numCols, Real* Y) const; private: // Support for copying source to target or to set target to zero. If // source is nullptr, then target is set to zero; otherwise source is // copied to target. This function hides the type traits used to // determine whether Real is native floating-point or otherwise (such // as BSNumber or BSRational). void Set(int numElements, Real const* source, Real* target) const; }; template <typename Real> bool GaussianElimination<Real>::operator()(int numRows, Real const* M, Real* inverseM, Real& determinant, Real const* B, Real* X, Real const* C, int numCols, Real* Y) const { if (numRows <= 0 || !M || ((B != nullptr) != (X != nullptr)) || ((C != nullptr) != (Y != nullptr)) || (C != nullptr && numCols < 1)) { LogError("Invalid input."); return false; } int numElements = numRows * numRows; bool wantInverse = (inverseM != nullptr); std::vector<Real> localInverseM; if (!wantInverse) { localInverseM.resize(numElements); inverseM = localInverseM.data(); } Set(numElements, M, inverseM); if (B) { Set(numRows, B, X); } if (C) { Set(numRows * numCols, C, Y); } #if defined(GTE_USE_ROW_MAJOR) LexicoArray2<true, Real> matInvM(numRows, numRows, inverseM); LexicoArray2<true, Real> matY(numRows, numCols, Y); #else LexicoArray2<false, Real> matInvM(numRows, numRows, inverseM); LexicoArray2<false, Real> matY(numRows, numCols, Y); #endif std::vector<int> colIndex(numRows), rowIndex(numRows), pivoted(numRows); std::fill(pivoted.begin(), pivoted.end(), 0); Real const zero = (Real)0; Real const one = (Real)1; bool odd = false; determinant = one; // Elimination by full pivoting. int i1, i2, row = 0, col = 0; for (int i0 = 0; i0 < numRows; ++i0) { // Search matrix (excluding pivoted rows) for maximum absolute entry. Real maxValue = zero; for (i1 = 0; i1 < numRows; ++i1) { if (!pivoted[i1]) { for (i2 = 0; i2 < numRows; ++i2) { if (!pivoted[i2]) { Real absValue = std::abs(matInvM(i1, i2)); if (absValue > maxValue) { maxValue = absValue; row = i1; col = i2; } } } } } if (maxValue == zero) { // The matrix is not invertible. if (wantInverse) { Set(numElements, nullptr, inverseM); } determinant = zero; if (B) { Set(numRows, nullptr, X); } if (C) { Set(numRows * numCols, nullptr, Y); } return false; } pivoted[col] = true; // Swap rows so that the pivot entry is in row 'col'. if (row != col) { odd = !odd; for (int i = 0; i < numRows; ++i) { std::swap(matInvM(row, i), matInvM(col, i)); } if (B) { std::swap(X[row], X[col]); } if (C) { for (int i = 0; i < numCols; ++i) { std::swap(matY(row, i), matY(col, i)); } } } // Keep track of the permutations of the rows. rowIndex[i0] = row; colIndex[i0] = col; // Scale the row so that the pivot entry is 1. Real diagonal = matInvM(col, col); determinant *= diagonal; Real inv = one / diagonal; matInvM(col, col) = one; for (i2 = 0; i2 < numRows; ++i2) { matInvM(col, i2) *= inv; } if (B) { X[col] *= inv; } if (C) { for (i2 = 0; i2 < numCols; ++i2) { matY(col, i2) *= inv; } } // Zero out the pivot column locations in the other rows. for (i1 = 0; i1 < numRows; ++i1) { if (i1 != col) { Real save = matInvM(i1, col); matInvM(i1, col) = zero; for (i2 = 0; i2 < numRows; ++i2) { matInvM(i1, i2) -= matInvM(col, i2) * save; } if (B) { X[i1] -= X[col] * save; } if (C) { for (i2 = 0; i2 < numCols; ++i2) { matY(i1, i2) -= matY(col, i2) * save; } } } } } if (wantInverse) { // Reorder rows to undo any permutations in Gaussian elimination. for (i1 = numRows - 1; i1 >= 0; --i1) { if (rowIndex[i1] != colIndex[i1]) { for (i2 = 0; i2 < numRows; ++i2) { std::swap(matInvM(i2, rowIndex[i1]), matInvM(i2, colIndex[i1])); } } } } if (odd) { determinant = -determinant; } return true; } template <typename Real> void GaussianElimination<Real>::Set(int numElements, Real const* source, Real* target) const { if (std::is_floating_point<Real>() == std::true_type()) { // Fast set/copy for native floating-point. size_t numBytes = numElements * sizeof(Real); if (source) { Memcpy(target, source, numBytes); } else { memset(target, 0, numBytes); } } else { // The inputs are not std containers, so ensure assignment works // correctly. if (source) { for (int i = 0; i < numElements; ++i) { target[i] = source[i]; } } else { Real const zero = (Real)0; for (int i = 0; i < numElements; ++i) { target[i] = zero; } } } } } // ---------------------------------------------- // GteMatrix.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.2 (2018/10/05) namespace gte { template <int NumRows, int NumCols, typename Real> class Matrix { public: // The table is initialized to zero. Matrix(); // The table is fully initialized by the inputs. The 'values' must be // specified in row-major order, regardless of the active storage scheme // (GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR). Matrix(std::array<Real, NumRows*NumCols> const& values); // At most NumRows*NumCols are copied from the initializer list, setting // any remaining elements to zero. The 'values' must be specified in // row-major order, regardless of the active storage scheme // (GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR). Create the zero matrix using // the syntax // Matrix<NumRows,NumCols,Real> zero{(Real)0}; // WARNING: The C++ 11 specification states that // Matrix<NumRows,NumCols,Real> zero{}; // will lead to a call of the default constructor, not the initializer // constructor! Matrix(std::initializer_list<Real> values); // For 0 <= r < NumRows and 0 <= c < NumCols, element (r,c) is 1 and all // others are 0. If either of r or c is invalid, the zero matrix is // created. This is a convenience for creating the standard Euclidean // basis matrices; see also MakeUnit(int,int) and Unit(int,int). Matrix(int r, int c); // The copy constructor, destructor, and assignment operator are generated // by the compiler. // Member access for which the storage representation is transparent. The // matrix entry in row r and column c is A(r,c). The first operator() // returns a const reference rather than a Real value. This supports // writing via standard file operations that require a const pointer to // data. inline Real const& operator()(int r, int c) const; inline Real& operator()(int r, int c); // Member access by rows or by columns. void SetRow(int r, Vector<NumCols,Real> const& vec); void SetCol(int c, Vector<NumRows,Real> const& vec); Vector<NumCols,Real> GetRow(int r) const; Vector<NumRows,Real> GetCol(int c) const; // Member access by 1-dimensional index. NOTE: These accessors are // useful for the manipulation of matrix entries when it does not // matter whether storage is row-major or column-major. Do not use // constructs such as M[c+NumCols*r] or M[r+NumRows*c] that expose the // storage convention. inline Real const& operator[](int i) const; inline Real& operator[](int i); // Comparisons for sorted containers and geometric ordering. inline bool operator==(Matrix const& mat) const; inline bool operator!=(Matrix const& mat) const; inline bool operator< (Matrix const& mat) const; inline bool operator<=(Matrix const& mat) const; inline bool operator> (Matrix const& mat) const; inline bool operator>=(Matrix const& mat) const; // Special matrices. void MakeZero(); // All components are 0. void MakeUnit(int r, int c); // Component (r,c) is 1, all others zero. void MakeIdentity(); // Diagonal entries 1, others 0, even when nonsquare static Matrix Zero(); static Matrix Unit(int r, int c); static Matrix Identity(); protected: class Table { public: // Storage-order-independent element access as 2D array. inline Real const& operator()(int r, int c) const; inline Real& operator()(int r, int c); // Element access as 1D array. Use this internally only when // the 2D storage order is not relevant. inline Real const& operator[](int i) const; inline Real& operator[](int i); #if defined(GTE_USE_ROW_MAJOR) std::array<std::array<Real,NumCols>,NumRows> mStorage; #else std::array<std::array<Real,NumRows>,NumCols> mStorage; #endif }; Table mTable; }; // Unary operations. template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator+(Matrix<NumRows,NumCols,Real> const& M); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator-(Matrix<NumRows,NumCols,Real> const& M); // Linear-algebraic operations. template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator+( Matrix<NumRows,NumCols,Real> const& M0, Matrix<NumRows,NumCols,Real> const& M1); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator-( Matrix<NumRows,NumCols,Real> const& M0, Matrix<NumRows,NumCols,Real> const& M1); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator*(Matrix<NumRows,NumCols,Real> const& M, Real scalar); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator*(Real scalar, Matrix<NumRows,NumCols,Real> const& M); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> operator/(Matrix<NumRows,NumCols,Real> const& M, Real scalar); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real>& operator+=( Matrix<NumRows,NumCols,Real>& M0, Matrix<NumRows,NumCols,Real> const& M1); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real>& operator-=( Matrix<NumRows,NumCols,Real>& M0, Matrix<NumRows,NumCols,Real> const& M1); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real>& operator*=(Matrix<NumRows,NumCols,Real>& M, Real scalar); template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real>& operator/=(Matrix<NumRows,NumCols,Real>& M, Real scalar); // Geometric operations. template <int NumRows, int NumCols, typename Real> Real L1Norm(Matrix<NumRows,NumCols,Real> const& M); template <int NumRows, int NumCols, typename Real> Real L2Norm(Matrix<NumRows,NumCols,Real> const& M); template <int NumRows, int NumCols, typename Real> Real LInfinityNorm(Matrix<NumRows,NumCols,Real> const& M); template <int N, typename Real> Matrix<N,N,Real> Inverse(Matrix<N,N,Real> const& M, bool* reportInvertibility = nullptr); template <int N, typename Real> Real Determinant(Matrix<N, N, Real> const& M); // M^T template <int NumRows, int NumCols, typename Real> Matrix<NumCols,NumRows,Real> Transpose(Matrix<NumRows,NumCols,Real> const& M); // M*V template <int NumRows, int NumCols, typename Real> Vector<NumRows,Real> operator*( Matrix<NumRows,NumCols,Real> const& M, Vector<NumCols,Real> const& V); // V^T*M template <int NumRows, int NumCols, typename Real> Vector<NumCols,Real> operator*( Vector<NumRows,Real> const& V, Matrix<NumRows,NumCols,Real> const& M); // A*B template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows,NumCols,Real> operator*( Matrix<NumRows,NumCommon,Real> const& A, Matrix<NumCommon,NumCols,Real> const& B); template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows,NumCols,Real> MultiplyAB( Matrix<NumRows,NumCommon,Real> const& A, Matrix<NumCommon,NumCols,Real> const& B); // A*B^T template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows,NumCols,Real> MultiplyABT( Matrix<NumRows,NumCommon,Real> const& A, Matrix<NumCols,NumCommon,Real> const& B); // A^T*B template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows,NumCols,Real> MultiplyATB( Matrix<NumCommon,NumRows,Real> const& A, Matrix<NumCommon,NumCols,Real> const& B); // A^T*B^T template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows,NumCols,Real> MultiplyATBT( Matrix<NumCommon,NumRows,Real> const& A, Matrix<NumCols,NumCommon,Real> const& B); // M*D, D is diagonal NumCols-by-NumCols template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> MultiplyMD( Matrix<NumRows,NumCols,Real> const& M, Vector<NumCols,Real> const& D); // D*M, D is diagonal NumRows-by-NumRows template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> MultiplyDM( Vector<NumRows,Real> const& D, Matrix<NumRows,NumCols,Real> const& M); // U*V^T, U is NumRows-by-1, V is Num-Cols-by-1, result is NumRows-by-NumCols. template <int NumRows, int NumCols, typename Real> Matrix<NumRows,NumCols,Real> OuterProduct(Vector<NumRows, Real> const& U, Vector<NumCols, Real> const& V); // Initialization to a diagonal matrix whose diagonal entries are the // components of D. template <int N, typename Real> void MakeDiagonal(Vector<N, Real> const& D, Matrix<N, N, Real>& M); // Create an (N+1)-by-(N+1) matrix H by setting the upper N-by-N block to the // input N-by-N matrix and all other entries to 0 except for the last row // and last column entry which is set to 1. template <int N, typename Real> Matrix<N + 1, N+1, Real> HLift(Matrix<N, N, Real> const& M); // Extract the upper (N-1)-by-(N-1) block of the input N-by-N matrix. template <int N, typename Real> Matrix<N - 1, N - 1, Real> HProject(Matrix<N, N, Real> const& M); template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>::Matrix() { MakeZero(); } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>::Matrix( std::array<Real, NumRows*NumCols> const& values) { for (int r = 0, i = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c, ++i) { mTable(r, c) = values[i]; } } } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>::Matrix(std::initializer_list<Real> values) { int const numValues = static_cast<int>(values.size()); auto iter = values.begin(); int r, c, i; for (r = 0, i = 0; r < NumRows; ++r) { for (c = 0; c < NumCols; ++c, ++i) { if (i < numValues) { mTable(r, c) = *iter++; } else { break; } } if (c < NumCols) { // Fill in the remaining columns of the current row with zeros. for (/**/; c < NumCols; ++c) { mTable(r, c) = (Real)0; } ++r; break; } } if (r < NumRows) { // Fill in the remain rows with zeros. for (/**/; r < NumRows; ++r) { for (c = 0; c < NumCols; ++c) { mTable(r, c) = (Real)0; } } } } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>::Matrix(int r, int c) { MakeUnit(r, c); } template <int NumRows, int NumCols, typename Real> inline Real const& Matrix<NumRows, NumCols, Real>::operator()(int r, int c) const { return mTable(r, c); } template <int NumRows, int NumCols, typename Real> inline Real& Matrix<NumRows, NumCols, Real>::operator()(int r, int c) { return mTable(r, c); } template <int NumRows, int NumCols, typename Real> void Matrix<NumRows, NumCols, Real>::SetRow(int r, Vector<NumCols, Real> const& vec) { for (int c = 0; c < NumCols; ++c) { mTable(r, c) = vec[c]; } } template <int NumRows, int NumCols, typename Real> void Matrix<NumRows, NumCols, Real>::SetCol(int c, Vector<NumRows, Real> const& vec) { for (int r = 0; r < NumRows; ++r) { mTable(r, c) = vec[r]; } } template <int NumRows, int NumCols, typename Real> Vector<NumCols, Real> Matrix<NumRows, NumCols, Real>::GetRow(int r) const { Vector<NumCols, Real> vec; for (int c = 0; c < NumCols; ++c) { vec[c] = mTable(r, c); } return vec; } template <int NumRows, int NumCols, typename Real> Vector<NumRows, Real> Matrix<NumRows, NumCols, Real>::GetCol(int c) const { Vector<NumRows, Real> vec; for (int r = 0; r < NumRows; ++r) { vec[r] = mTable(r, c); } return vec; } template <int NumRows, int NumCols, typename Real> inline Real const& Matrix<NumRows, NumCols, Real>::operator[](int i) const { return mTable[i]; } template <int NumRows, int NumCols, typename Real> inline Real& Matrix<NumRows, NumCols, Real>::operator[](int i) { return mTable[i]; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator==(Matrix const& mat) const { return mTable.mStorage == mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator!=(Matrix const& mat) const { return mTable.mStorage != mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator<(Matrix const& mat) const { return mTable.mStorage < mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator<=(Matrix const& mat) const { return mTable.mStorage <= mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator>(Matrix const& mat) const { return mTable.mStorage > mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> inline bool Matrix<NumRows, NumCols, Real>::operator>=(Matrix const& mat) const { return mTable.mStorage >= mat.mTable.mStorage; } template <int NumRows, int NumCols, typename Real> void Matrix<NumRows, NumCols, Real>::MakeZero() { Real const zero = (Real)0; for (int i = 0; i < NumRows * NumCols; ++i) { mTable[i] = zero; } } template <int NumRows, int NumCols, typename Real> void Matrix<NumRows, NumCols, Real>::MakeUnit(int r, int c) { MakeZero(); if (0 <= r && r < NumRows && 0 <= c && c < NumCols) { mTable(r, c) = (Real)1; } } template <int NumRows, int NumCols, typename Real> void Matrix<NumRows, NumCols, Real>::MakeIdentity() { MakeZero(); int const numDiagonal = (NumRows <= NumCols ? NumRows : NumCols); for (int i = 0; i < numDiagonal; ++i) { mTable(i, i) = (Real)1; } } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> Matrix<NumRows, NumCols, Real>::Zero() { Matrix M; M.MakeZero(); return M; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> Matrix<NumRows, NumCols, Real>::Unit(int r, int c) { Matrix M; M.MakeUnit(r, c); return M; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> Matrix<NumRows, NumCols, Real>::Identity() { Matrix M; M.MakeIdentity(); return M; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator+(Matrix<NumRows, NumCols, Real> const& M) { return M; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator-(Matrix<NumRows, NumCols, Real> const& M) { Matrix<NumRows, NumCols, Real> result; for (int i = 0; i < NumRows*NumCols; ++i) { result[i] = -M[i]; } return result; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator+( Matrix<NumRows, NumCols, Real> const& M0, Matrix<NumRows, NumCols, Real> const& M1) { Matrix<NumRows, NumCols, Real> result = M0; return result += M1; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator-( Matrix<NumRows, NumCols, Real> const& M0, Matrix<NumRows, NumCols, Real> const& M1) { Matrix<NumRows, NumCols, Real> result = M0; return result -= M1; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator*(Matrix<NumRows, NumCols, Real> const& M, Real scalar) { Matrix<NumRows, NumCols, Real> result = M; return result *= scalar; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator*(Real scalar, Matrix<NumRows, NumCols, Real> const& M) { Matrix<NumRows, NumCols, Real> result = M; return result *= scalar; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> operator/(Matrix<NumRows, NumCols, Real> const& M, Real scalar) { Matrix<NumRows, NumCols, Real> result = M; return result /= scalar; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>& operator+=( Matrix<NumRows, NumCols, Real>& M0, Matrix<NumRows, NumCols, Real> const& M1) { for (int i = 0; i < NumRows*NumCols; ++i) { M0[i] += M1[i]; } return M0; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>& operator-=( Matrix<NumRows, NumCols, Real>& M0, Matrix<NumRows, NumCols, Real> const& M1) { for (int i = 0; i < NumRows*NumCols; ++i) { M0[i] -= M1[i]; } return M0; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>& operator*=(Matrix<NumRows, NumCols, Real>& M, Real scalar) { for (int i = 0; i < NumRows*NumCols; ++i) { M[i] *= scalar; } return M; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real>& operator/=(Matrix<NumRows, NumCols, Real>& M, Real scalar) { if (scalar != (Real)0) { Real invScalar = ((Real)1) / scalar; for (int i = 0; i < NumRows*NumCols; ++i) { M[i] *= invScalar; } } else { for (int i = 0; i < NumRows*NumCols; ++i) { M[i] = (Real)0; } } return M; } template <int NumRows, int NumCols, typename Real> Real L1Norm(Matrix<NumRows, NumCols, Real> const& M) { Real sum = std::abs(M[0]); for (int i = 1; i < NumRows*NumCols; ++i) { sum += std::abs(M[i]); } return sum; } template <int NumRows, int NumCols, typename Real> Real L2Norm(Matrix<NumRows, NumCols, Real> const& M) { Real sum = M[0] * M[0]; for (int i = 1; i < NumRows*NumCols; ++i) { sum += M[i] * M[i]; } return std::sqrt(sum); } template <int NumRows, int NumCols, typename Real> Real LInfinityNorm(Matrix<NumRows, NumCols, Real> const& M) { Real maxAbsElement = M[0]; for (int i = 1; i < NumRows*NumCols; ++i) { Real absElement = std::abs(M[i]); if (absElement > maxAbsElement) { maxAbsElement = absElement; } } return maxAbsElement; } template <int N, typename Real> Matrix<N, N, Real> Inverse(Matrix<N, N, Real> const& M, bool* reportInvertibility) { Matrix<N, N, Real> invM; Real determinant; bool invertible = GaussianElimination<Real>()(N, &M[0], &invM[0], determinant, nullptr, nullptr, nullptr, 0, nullptr); if (reportInvertibility) { *reportInvertibility = invertible; } return invM; } template <int N, typename Real> Real Determinant(Matrix<N, N, Real> const& M) { Real determinant; GaussianElimination<Real>()(N, &M[0], nullptr, determinant, nullptr, nullptr, nullptr, 0, nullptr); return determinant; } template <int NumRows, int NumCols, typename Real> Matrix<NumCols, NumRows, Real> Transpose(Matrix<NumRows, NumCols, Real> const& M) { Matrix<NumCols, NumRows, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(c, r) = M(r, c); } } return result; } template <int NumRows, int NumCols, typename Real> Vector<NumRows, Real> operator*( Matrix<NumRows, NumCols, Real> const& M, Vector<NumCols, Real> const& V) { Vector<NumRows, Real> result; for (int r = 0; r < NumRows; ++r) { result[r] = (Real)0; for (int c = 0; c < NumCols; ++c) { result[r] += M(r, c) * V[c]; } } return result; } template <int NumRows, int NumCols, typename Real> Vector<NumCols, Real> operator*(Vector<NumRows, Real> const& V, Matrix<NumRows, NumCols, Real> const& M) { Vector<NumCols, Real> result; for (int c = 0; c < NumCols; ++c) { result[c] = (Real)0; for (int r = 0; r < NumRows; ++r) { result[c] += V[r] * M(r, c); } } return result; } template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows, NumCols, Real> operator*( Matrix<NumRows, NumCommon, Real> const& A, Matrix<NumCommon, NumCols, Real> const& B) { return MultiplyAB(A, B); } template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows, NumCols, Real> MultiplyAB( Matrix<NumRows, NumCommon, Real> const& A, Matrix<NumCommon, NumCols, Real> const& B) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = (Real)0; for (int i = 0; i < NumCommon; ++i) { result(r, c) += A(r, i) * B(i, c); } } } return result; } template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows, NumCols, Real> MultiplyABT( Matrix<NumRows, NumCommon, Real> const& A, Matrix<NumCols, NumCommon, Real> const& B) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = (Real)0; for (int i = 0; i < NumCommon; ++i) { result(r, c) += A(r, i) * B(c, i); } } } return result; } template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows, NumCols, Real> MultiplyATB( Matrix<NumCommon, NumRows, Real> const& A, Matrix<NumCommon, NumCols, Real> const& B) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = (Real)0; for (int i = 0; i < NumCommon; ++i) { result(r, c) += A(i, r) * B(i, c); } } } return result; } template <int NumRows, int NumCols, int NumCommon, typename Real> Matrix<NumRows, NumCols, Real> MultiplyATBT( Matrix<NumCommon, NumRows, Real> const& A, Matrix<NumCols, NumCommon, Real> const& B) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = (Real)0; for (int i = 0; i < NumCommon; ++i) { result(r, c) += A(i, r) * B(c, i); } } } return result; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> MultiplyMD( Matrix<NumRows, NumCols, Real> const& M, Vector<NumCols, Real> const& D) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = M(r, c) * D[c]; } } return result; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> MultiplyDM( Vector<NumRows, Real> const& D, Matrix<NumRows, NumCols, Real> const& M) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = D[r] * M(r, c); } } return result; } template <int NumRows, int NumCols, typename Real> Matrix<NumRows, NumCols, Real> OuterProduct(Vector<NumRows, Real> const& U, Vector<NumCols, Real> const& V) { Matrix<NumRows, NumCols, Real> result; for (int r = 0; r < NumRows; ++r) { for (int c = 0; c < NumCols; ++c) { result(r, c) = U[r] * V[c]; } } return result; } template <int N, typename Real> void MakeDiagonal(Vector<N, Real> const& D, Matrix<N, N, Real>& M) { for (int i = 0; i < N*N; ++i) { M[i] = (Real)0; } for (int i = 0; i < N; ++i) { M(i, i) = D[i]; } } template <int N, typename Real> Matrix<N + 1, N + 1, Real> HLift(Matrix<N, N, Real> const& M) { Matrix<N + 1, N + 1, Real> result; result.MakeIdentity(); for (int r = 0; r < N; ++r) { for (int c = 0; c < N; ++c) { result(r, c) = M(r, c); } } return result; } // Extract the upper (N-1)-by-(N-1) block of the input N-by-N matrix. template <int N, typename Real> Matrix<N - 1, N - 1, Real> HProject(Matrix<N, N, Real> const& M) { static_assert(N >= 2, "Invalid matrix dimension."); Matrix<N - 1, N - 1, Real> result; for (int r = 0; r < N - 1; ++r) { for (int c = 0; c < N - 1; ++c) { result(r, c) = M(r, c); } } return result; } // Matrix<N,C,Real>::Table template <int NumRows, int NumCols, typename Real> inline Real const& Matrix<NumRows, NumCols, Real>::Table::operator()(int r, int c) const { #if defined(GTE_USE_ROW_MAJOR) return mStorage[r][c]; #else return mStorage[c][r]; #endif } template <int NumRows, int NumCols, typename Real> inline Real& Matrix<NumRows, NumCols, Real>::Table::operator()(int r, int c) { #if defined(GTE_USE_ROW_MAJOR) return mStorage[r][c]; #else return mStorage[c][r]; #endif } template <int NumRows, int NumCols, typename Real> inline Real const& Matrix<NumRows, NumCols, Real>::Table::operator[](int i) const { Real const* elements = &mStorage[0][0]; return elements[i]; } template <int NumRows, int NumCols, typename Real> inline Real& Matrix<NumRows, NumCols, Real>::Table::operator[](int i) { Real* elements = &mStorage[0][0]; return elements[i]; } } // ---------------------------------------------- // GteRangeIteration.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // For information on range-based for-loops, see // http://en.cppreference.com/w/cpp/language/range-for namespace gte { // The function gte::reverse supports reverse iteration in range-based // for-loops using the auto keyword. For example, // // std::vector<int> numbers(4); // int i = 0; // for (auto& number : numbers) // { // number = i++; // std::cout << number << ' '; // } // // Output: 0 1 2 3 // // for (auto& number : gte::reverse(numbers)) // { // std::cout << number << ' '; // } // // Output: 3 2 1 0 template <typename Iterator> class ReversalObject { public: ReversalObject(Iterator begin, Iterator end) : mBegin(begin), mEnd(end) { } Iterator begin() const { return mBegin; } Iterator end() const { return mEnd; } private: Iterator mBegin, mEnd; }; template < typename Iterable, typename Iterator = decltype(std::begin(std::declval<Iterable>())), typename ReverseIterator = std::reverse_iterator<Iterator> > ReversalObject<ReverseIterator> reverse(Iterable&& range) { return ReversalObject<ReverseIterator>( ReverseIterator(std::end(range)), ReverseIterator(std::begin(range))); } } // ---------------------------------------------- // GteWrapper.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Wrappers around platform-specific low-level library calls. namespace gte { void Memcpy(void* target, void const* source, size_t count); void Memcpy(wchar_t* target, wchar_t const* source, size_t count); } // ---------------------------------------------- // GteSingularValueDecomposition.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) // The SingularValueDecomposition class is an implementation of Algorithm // 8.3.2 (The SVD Algorithm) described in "Matrix Computations, 2nd // edition" by G. H. Golub and Charles F. Van Loan, The Johns Hopkins // Press, Baltimore MD, Fourth Printing 1993. Algorithm 5.4.2 (Householder // Bidiagonalization) is used to reduce A to bidiagonal B. Algorithm 8.3.1 // (Golub-Kahan SVD Step) is used for the iterative reduction from bidiagonal // to diagonal. If A is the original matrix, S is the matrix whose diagonal // entries are the singular values, and U and V are corresponding matrices, // then theoretically U^T*A*V = S. Numerically, we have errors // E = U^T*A*V - S. Algorithm 8.3.2 mentions that one expects |E| is // approximately u*|A|, where |M| denotes the Frobenius norm of M and where // u is the unit roundoff for the floating-point arithmetic: 2^{-23} for // 'float', which is FLT_EPSILON = 1.192092896e-7f, and 2^{-52} for'double', // which is DBL_EPSILON = 2.2204460492503131e-16. // // The condition |a(i,i+1)| <= epsilon*(|a(i,i) + a(i+1,i+1)|) used to // determine when the reduction decouples to smaller problems is implemented // as: sum = |a(i,i)| + |a(i+1,i+1)|; sum + |a(i,i+1)| == sum. The idea is // that the superdiagonal term is small relative to its diagonal neighbors, // and so it is effectively zero. The unit tests have shown that this // interpretation of decoupling is effective. // // The condition |a(i,i)| <= epsilon*|B| used to determine when the // reduction decouples (with a zero singular value) is implemented using // the Frobenius norm of B and epsilon = multiplier*u, where for now the // multiplier is hard-coded in Solve(...) as 8. // // The authors suggest that once you have the bidiagonal matrix, a practical // implementation will store the diagonal and superdiagonal entries in linear // arrays, ignoring the theoretically zero values not in the 2-band. This is // good for cache coherence, and we have used the suggestion. The essential // parts of the Householder u-vectors are stored in the lower-triangular // portion of the matrix and the essential parts of the Householder v-vectors // are stored in the upper-triangular portion of the matrix. To avoid having // to recompute 2/Dot(u,u) and 2/Dot(v,v) when constructing orthogonal U and // V, we store these quantities in additional memory during bidiagonalization. // // For matrices with randomly generated values in [0,1], the unit tests // produce the following information for N-by-N matrices. // // N |A| |E| |E|/|A| iterations // ------------------------------------------- // 2 1.4831 4.1540e-16 2.8007e-16 1 // 3 2.1065 3.5024e-16 1.6626e-16 4 // 4 2.4979 7.4605e-16 2.9867e-16 6 // 5 3.6591 1.8305e-15 5.0025e-16 9 // 6 4.0572 2.0571e-15 5.0702e-16 10 // 7 4.7745 2.9057e-15 6.0859e-16 12 // 8 5.1964 2.7958e-15 5.3803e-16 13 // 9 5.7599 3.3128e-15 5.7514e-16 16 // 10 6.2700 3.7209e-15 5.9344e-16 16 // 11 6.8220 5.0580e-15 7.4142e-16 18 // 12 7.4540 5.2493e-15 7.0422e-16 21 // 13 8.1225 5.6043e-15 6.8997e-16 24 // 14 8.5883 5.8553e-15 6.8177e-16 26 // 15 9.1337 6.9663e-15 7.6270e-16 27 // 16 9.7884 9.1358e-15 9.3333e-16 29 // 17 10.2407 8.2715e-15 8.0771e-16 34 // 18 10.7147 8.9748e-15 8.3761e-16 33 // 19 11.1887 1.0094e-14 9.0220e-16 32 // 20 11.7739 9.7000e-15 8.2386e-16 35 // 21 12.2822 1.1217e-14 9.1329e-16 36 // 22 12.7649 1.1071e-14 8.6732e-16 37 // 23 13.3366 1.1271e-14 8.4513e-16 41 // 24 13.8505 1.2806e-14 9.2460e-16 43 // 25 14.4332 1.3081e-14 9.0637e-16 43 // 26 14.9301 1.4882e-14 9.9680e-16 46 // 27 15.5214 1.5571e-14 1.0032e-15 48 // 28 16.1029 1.7553e-14 1.0900e-15 49 // 29 16.6407 1.6219e-14 9.7467e-16 53 // 30 17.1891 1.8560e-14 1.0797e-15 55 // 31 17.7773 1.8522e-14 1.0419e-15 56 // // The singularvalues and |E|/|A| values were compared to those generated by // Mathematica Version 9.0; Wolfram Research, Inc., Champaign IL, 2012. // The results were all comparable with singular values agreeing to a large // number of decimal places. // // Timing on an Intel (R) Core (TM) i7-3930K CPU @ 3.20 GHZ (in seconds) // for NxN matrices: // // N |E|/|A| iters bidiag QR U-and-V comperr // ------------------------------------------------------- // 512 3.8632e-15 848 0.341 0.016 1.844 2.203 // 1024 5.6456e-15 1654 4.279 0.032 18.765 20.844 // 2048 7.5499e-15 3250 40.421 0.141 186.607 213.216 // // where iters is the number of QR steps taken, bidiag is the computation // of the Householder reflection vectors, U-and-V is the composition of // Householder reflections and Givens rotations to obtain the orthogonal // matrices of the decomposigion, and comperr is the computation E = // U^T*A*V - S. namespace gte { template <typename Real> class SingularValueDecomposition { public: // The solver processes MxN symmetric matrices, where M >= N > 1 // ('numRows' is M and 'numCols' is N) and the matrix is stored in // row-major order. The maximum number of iterations ('maxIterations') // must be specified for the reduction of a bidiagonal matrix to a // diagonal matrix. The goal is to compute MxM orthogonal U, NxN // orthogonal V, and MxN matrix S for which U^T*A*V = S. The only // nonzero entries of S are on the diagonal; the diagonal entries are // the singular values of the original matrix. SingularValueDecomposition(int numRows, int numCols, unsigned int maxIterations); // A copy of the MxN input is made internally. The order of the singular // values is specified by sortType: -1 (decreasing), 0 (no sorting), or +1 // (increasing). When sorted, the columns of the orthogonal matrices // are ordered accordingly. The return value is the number of iterations // consumed when convergence occurred, 0xFFFFFFFF when convergence did not // occur or 0 when N <= 1 or M < N was passed to the constructor. unsigned int Solve(Real const* input, int sortType); // Get the singular values of the matrix passed to Solve(...). The input // 'singularValues' must have N elements. void GetSingularValues(Real* singularValues) const; // Accumulate the Householder reflections, the Givens rotations, and the // diagonal fix-up matrix to compute the orthogonal matrices U and V for // which U^T*A*V = S. The input uMatrix must be MxM and the input vMatrix // must be NxN, both stored in row-major order. void GetU(Real* uMatrix) const; void GetV(Real* vMatrix) const; // Compute a single column of U or V. The reflections and rotations are // applied incrementally. This is useful when you want only a small // number of the singular values or vectors. void GetUColumn(int index, Real* uColumn) const; void GetVColumn(int index, Real* vColumn) const; Real GetSingularValue(int index) const; private: // Bidiagonalize using Householder reflections. On input, mMatrix is a // copy of the input matrix and has one extra row. On output, the // diagonal and superdiagonal contain the bidiagonalized results. The // lower-triangular portion stores the essential parts of the Householder // u vectors (the elements of u after the leading 1-valued component) and // the upper-triangular portion stores the essential parts of the // Householder v vectors. To avoid recomputing 2/Dot(u,u) and 2/Dot(v,v), // these quantities are stored in mTwoInvUTU and mTwoInvVTV. void Bidiagonalize(); // A helper for generating Givens rotation sine and cosine robustly. void GetSinCos(Real u, Real v, Real& cs, Real& sn); // Test for (effectively) zero-valued diagonal entries (through all but // the last). For each such entry, the B matrix decouples. Perform // that decoupling. If there are no zero-valued entries, then the // Golub-Kahan step must be performed. bool DiagonalEntriesNonzero(int imin, int imax, Real threshold); // This is Algorithm 8.3.1 in "Matrix Computations, 2nd edition" by // G. H. Golub and C. F. Van Loan. void DoGolubKahanStep(int imin, int imax); // The diagonal entries are not guaranteed to be nonnegative during the // construction. After convergence to a diagonal matrix S, test for // negative entries and build a diagonal matrix that reverses the sign // on the S-entry. void EnsureNonnegativeDiagonal(); // Sort the singular values and compute the corresponding permutation of // the indices of the array storing the singular values. The permutation // is used for reordering the singular values and the corresponding // columns of the orthogonal matrix in the calls to GetSingularValues(...) // and GetOrthogonalMatrices(...). void ComputePermutation(int sortType); // The number rows and columns of the matrices to be processed. int mNumRows, mNumCols; // The maximum number of iterations for reducing the bidiagonal matrix // to a diagonal matrix. unsigned int mMaxIterations; // The internal copy of a matrix passed to the solver. See the comments // about function Bidiagonalize() about what is stored in the matrix. std::vector<Real> mMatrix; // MxN elements // After the initial bidiagonalization by Householder reflections, we no // longer need the full mMatrix. Copy the diagonal and superdiagonal // entries to linear arrays in order to be cache friendly. std::vector<Real> mDiagonal; // N elements std::vector<Real> mSuperdiagonal; // N-1 elements // The Givens rotations used to reduce the initial bidiagonal matrix to // a diagonal matrix. A rotation is the identity with the following // replacement entries: R(index0,index0) = cs, R(index0,index1) = sn, // R(index1,index0) = -sn, and R(index1,index1) = cs. If N is the // number of matrix columns and K is the maximum number of iterations, the // maximum number of right or left Givens rotations is K*(N-1). The // maximum amount of memory is allocated to store these. However, we also // potentially need left rotations to decouple the matrix when a diagonal // terms are zero. Worst case is a number of matrices quadratic in N, so // for now we just use std::vector<Rotation> whose initial capacity is // K*(N-1). struct GivensRotation { GivensRotation(); GivensRotation(int inIndex0, int inIndex1, Real inCs, Real inSn); int index0, index1; Real cs, sn; }; std::vector<GivensRotation> mRGivens; std::vector<GivensRotation> mLGivens; // The diagonal matrix that is used to convert S-entries to nonnegative. std::vector<Real> mFixupDiagonal; // N elements // When sorting is requested, the permutation associated with the sort is // stored in mPermutation. When sorting is not requested, mPermutation[0] // is set to -1. mVisited is used for finding cycles in the permutation. std::vector<int> mPermutation; // N elements mutable std::vector<int> mVisited; // N elements // Temporary storage to compute Householder reflections and to support // sorting of columns of the orthogonal matrices. std::vector<Real> mTwoInvUTU; // N elements std::vector<Real> mTwoInvVTV; // N-2 elements mutable std::vector<Real> mUVector; // M elements mutable std::vector<Real> mVVector; // N elements mutable std::vector<Real> mWVector; // max(M,N) elements }; template <typename Real> SingularValueDecomposition<Real>::SingularValueDecomposition(int numRows, int numCols, unsigned int maxIterations) : mNumRows(0), mNumCols(0), mMaxIterations(0) { if (numCols > 1 && numRows >= numCols && maxIterations > 0) { mNumRows = numRows; mNumCols = numCols; mMaxIterations = maxIterations; mMatrix.resize(numRows * numCols); mDiagonal.resize(numCols); mSuperdiagonal.resize(numCols - 1); mRGivens.reserve(maxIterations*(numCols - 1)); mLGivens.reserve(maxIterations*(numCols - 1)); mFixupDiagonal.resize(numCols); mPermutation.resize(numCols); mVisited.resize(numCols); mTwoInvUTU.resize(numCols); mTwoInvVTV.resize(numCols - 2); mUVector.resize(numRows); mVVector.resize(numCols); mWVector.resize(numRows); } } template <typename Real> unsigned int SingularValueDecomposition<Real>::Solve(Real const* input, int sortType) { if (mNumRows > 0) { int numElements = mNumRows * mNumCols; std::copy(input, input + numElements, mMatrix.begin()); Bidiagonalize(); // Compute 'threshold = multiplier*epsilon*|B|' as the threshold for // diagonal entries effectively zero; that is, |d| <= |threshold| // implies that d is (effectively) zero. TODO: Allow the caller to // pass 'multiplier' to the constructor. // // We will use the L2-norm |B|, which is the length of the elements // of B treated as an NM-tuple. The following code avoids overflow // when accumulating the squares of the elements when those elements // are large. Real maxAbsComp = std::abs(input[0]); for (int i = 1; i < numElements; ++i) { Real absComp = std::abs(input[i]); if (absComp > maxAbsComp) { maxAbsComp = absComp; } } Real norm = (Real)0; if (maxAbsComp > (Real)0) { Real invMaxAbsComp = ((Real)1) / maxAbsComp; for (int i = 0; i < numElements; ++i) { Real ratio = input[i] * invMaxAbsComp; norm += ratio * ratio; } norm = maxAbsComp * std::sqrt(norm); } Real const multiplier = (Real)8; // TODO: Expose to caller. Real const epsilon = std::numeric_limits<Real>::epsilon(); Real const threshold = multiplier * epsilon * norm; mRGivens.clear(); mLGivens.clear(); for (unsigned int j = 0; j < mMaxIterations; ++j) { int imin = -1, imax = -1; for (int i = mNumCols - 2; i >= 0; --i) { // When a01 is much smaller than its diagonal neighbors, it is // effectively zero. Real a00 = mDiagonal[i]; Real a01 = mSuperdiagonal[i]; Real a11 = mDiagonal[i + 1]; Real sum = std::abs(a00) + std::abs(a11); if (sum + std::abs(a01) != sum) { if (imax == -1) { imax = i; } imin = i; } else { // The superdiagonal term is effectively zero compared to // the neighboring diagonal terms. if (imin >= 0) { break; } } } if (imax == -1) { // The algorithm has converged. EnsureNonnegativeDiagonal(); ComputePermutation(sortType); return j; } // We need to test diagonal entries of B for zero. For each zero // diagonal entry, zero the superdiagonal. if (DiagonalEntriesNonzero(imin, imax, threshold)) { // Process the lower-right-most unreduced bidiagonal block. DoGolubKahanStep(imin, imax); } } return 0xFFFFFFFF; } else { return 0; } } template <typename Real> void SingularValueDecomposition<Real>::GetSingularValues( Real* singularValues) const { if (singularValues && mNumCols > 0) { if (mPermutation[0] >= 0) { // Sorting was requested. for (int i = 0; i < mNumCols; ++i) { int p = mPermutation[i]; singularValues[i] = mDiagonal[p]; } } else { // Sorting was not requested. size_t numBytes = mNumCols*sizeof(Real); Memcpy(singularValues, &mDiagonal[0], numBytes); } } } template <typename Real> void SingularValueDecomposition<Real>::GetU(Real* uMatrix) const { if (!uMatrix || mNumCols == 0) { // Invalid input or the constructor failed. return; } // Start with the identity matrix. std::fill(uMatrix, uMatrix + mNumRows*mNumRows, (Real)0); for (int d = 0; d < mNumRows; ++d) { uMatrix[d + mNumRows*d] = (Real)1; } // Multiply the Householder reflections using backward accumulation. int r, c; for (int i0 = mNumCols - 1, i1 = i0 + 1; i0 >= 0; --i0, --i1) { // Copy the u vector and 2/Dot(u,u) from the matrix. Real twoinvudu = mTwoInvUTU[i0]; Real const* column = &mMatrix[i0]; mUVector[i0] = (Real)1; for (r = i1; r < mNumRows; ++r) { mUVector[r] = column[mNumCols*r]; } // Compute the w vector. mWVector[i0] = twoinvudu; for (r = i1; r < mNumRows; ++r) { mWVector[r] = (Real)0; for (c = i1; c < mNumRows; ++c) { mWVector[r] += mUVector[c] * uMatrix[r + mNumRows*c]; } mWVector[r] *= twoinvudu; } // Update the matrix, U <- U - u*w^T. for (r = i0; r < mNumRows; ++r) { for (c = i0; c < mNumRows; ++c) { uMatrix[c + mNumRows*r] -= mUVector[r] * mWVector[c]; } } } // Multiply the Givens rotations. for (auto const& givens : mLGivens) { int j0 = givens.index0; int j1 = givens.index1; for (r = 0; r < mNumRows; ++r, j0 += mNumRows, j1 += mNumRows) { Real& q0 = uMatrix[j0]; Real& q1 = uMatrix[j1]; Real prd0 = givens.cs * q0 - givens.sn * q1; Real prd1 = givens.sn * q0 + givens.cs * q1; q0 = prd0; q1 = prd1; } } if (mPermutation[0] >= 0) { // Sorting was requested. std::fill(mVisited.begin(), mVisited.end(), 0); for (c = 0; c < mNumCols; ++c) { if (mVisited[c] == 0 && mPermutation[c] != c) { // The item starts a cycle with 2 or more elements. int start = c, current = c, next; for (r = 0; r < mNumRows; ++r) { mWVector[r] = uMatrix[c + mNumRows*r]; } while ((next = mPermutation[current]) != start) { mVisited[current] = 1; for (r = 0; r < mNumRows; ++r) { uMatrix[current + mNumRows*r] = uMatrix[next + mNumRows*r]; } current = next; } mVisited[current] = 1; for (r = 0; r < mNumRows; ++r) { uMatrix[current + mNumRows*r] = mWVector[r]; } } } } } template <typename Real> void SingularValueDecomposition<Real>::GetV(Real* vMatrix) const { if (!vMatrix || mNumCols == 0) { // Invalid input or the constructor failed. return; } // Start with the identity matrix. std::fill(vMatrix, vMatrix + mNumCols*mNumCols, (Real)0); for (int d = 0; d < mNumCols; ++d) { vMatrix[d + mNumCols*d] = (Real)1; } // Multiply the Householder reflections using backward accumulation. int i0 = mNumCols - 3; int i1 = i0 + 1; int i2 = i0 + 2; int r, c; for (/**/; i0 >= 0; --i0, --i1, --i2) { // Copy the v vector and 2/Dot(v,v) from the matrix. Real twoinvvdv = mTwoInvVTV[i0]; Real const* row = &mMatrix[mNumCols*i0]; mVVector[i1] = (Real)1; for (r = i2; r < mNumCols; ++r) { mVVector[r] = row[r]; } // Compute the w vector. mWVector[i1] = twoinvvdv; for (r = i2; r < mNumCols; ++r) { mWVector[r] = (Real)0; for (c = i2; c < mNumCols; ++c) { mWVector[r] += mVVector[c] * vMatrix[r + mNumCols*c]; } mWVector[r] *= twoinvvdv; } // Update the matrix, V <- V - v*w^T. for (r = i1; r < mNumCols; ++r) { for (c = i1; c < mNumCols; ++c) { vMatrix[c + mNumCols*r] -= mVVector[r] * mWVector[c]; } } } // Multiply the Givens rotations. for (auto const& givens : mRGivens) { int j0 = givens.index0; int j1 = givens.index1; for (c = 0; c < mNumCols; ++c, j0 += mNumCols, j1 += mNumCols) { Real& q0 = vMatrix[j0]; Real& q1 = vMatrix[j1]; Real prd0 = givens.cs * q0 - givens.sn * q1; Real prd1 = givens.sn * q0 + givens.cs * q1; q0 = prd0; q1 = prd1; } } // Fix-up the diagonal. for (r = 0; r < mNumCols; ++r) { for (c = 0; c < mNumCols; ++c) { vMatrix[c + mNumCols*r] *= mFixupDiagonal[c]; } } if (mPermutation[0] >= 0) { // Sorting was requested. std::fill(mVisited.begin(), mVisited.end(), 0); for (c = 0; c < mNumCols; ++c) { if (mVisited[c] == 0 && mPermutation[c] != c) { // The item starts a cycle with 2 or more elements. int start = c, current = c, next; for (r = 0; r < mNumCols; ++r) { mWVector[r] = vMatrix[c + mNumCols*r]; } while ((next = mPermutation[current]) != start) { mVisited[current] = 1; for (r = 0; r < mNumCols; ++r) { vMatrix[current + mNumCols*r] = vMatrix[next + mNumCols*r]; } current = next; } mVisited[current] = 1; for (r = 0; r < mNumCols; ++r) { vMatrix[current + mNumCols*r] = mWVector[r]; } } } } } template <typename Real> void SingularValueDecomposition<Real>::GetUColumn(int index, Real* uColumn) const { if (0 <= index && index < mNumRows) { // y = H*x, then x and y are swapped for the next H Real* x = uColumn; Real* y = &mWVector[0]; // Start with the Euclidean basis vector. memset(x, 0, mNumRows * sizeof(Real)); if (index < mNumCols && mPermutation[0] >= 0) { // Sorting was requested. x[mPermutation[index]] = (Real)1; } else { x[index] = (Real)1; } // Apply the Givens rotations. for (auto const& givens : gte::reverse(mLGivens)) { Real& xr0 = x[givens.index0]; Real& xr1 = x[givens.index1]; Real tmp0 = givens.cs * xr0 + givens.sn * xr1; Real tmp1 = -givens.sn * xr0 + givens.cs * xr1; xr0 = tmp0; xr1 = tmp1; } // Apply the Householder reflections. for (int c = mNumCols - 1; c >= 0; --c) { // Get the Householder vector u. int r; for (r = 0; r < c; ++r) { y[r] = x[r]; } // Compute s = Dot(x,u) * 2/u^T*u. Real s = x[r]; // r = c, u[r] = 1 for (int j = r + 1; j < mNumRows; ++j) { s += x[j] * mMatrix[c + mNumCols * j]; } s *= mTwoInvUTU[c]; // r = c, y[r] = x[r]*u[r] - s = x[r] - s because u[r] = 1 y[r] = x[r] - s; // Compute the remaining components of y. for (++r; r < mNumRows; ++r) { y[r] = x[r] - s * mMatrix[c + mNumCols * r]; } std::swap(x, y); } // The final product is stored in x. if (x != uColumn) { size_t numBytes = mNumRows*sizeof(Real); Memcpy(uColumn, x, numBytes); } } } template <typename Real> void SingularValueDecomposition<Real>::GetVColumn(int index, Real* vColumn) const { if (0 <= index && index < mNumCols) { // y = H*x, then x and y are swapped for the next H Real* x = vColumn; Real* y = &mWVector[0]; // Start with the Euclidean basis vector. memset(x, 0, mNumCols * sizeof(Real)); if (mPermutation[0] >= 0) { // Sorting was requested. int p = mPermutation[index]; x[p] = mFixupDiagonal[p]; } else { x[index] = mFixupDiagonal[index]; } // Apply the Givens rotations. for (auto const& givens : gte::reverse(mRGivens)) { Real& xr0 = x[givens.index0]; Real& xr1 = x[givens.index1]; Real tmp0 = givens.cs * xr0 + givens.sn * xr1; Real tmp1 = -givens.sn * xr0 + givens.cs * xr1; xr0 = tmp0; xr1 = tmp1; } // Apply the Householder reflections. for (int r = mNumCols - 3; r >= 0; --r) { // Get the Householder vector v. int c; for (c = 0; c < r + 1; ++c) { y[c] = x[c]; } // Compute s = Dot(x,v) * 2/v^T*v. Real s = x[c]; // c = r+1, v[c] = 1 for (int j = c + 1; j < mNumCols; ++j) { s += x[j] * mMatrix[j + mNumCols * r]; } s *= mTwoInvVTV[r]; // c = r+1, y[c] = x[c]*v[c] - s = x[c] - s because v[c] = 1 y[c] = x[c] - s; // Compute the remaining components of y. for (++c; c < mNumCols; ++c) { y[c] = x[c] - s * mMatrix[c + mNumCols * r]; } std::swap(x, y); } // The final product is stored in x. if (x != vColumn) { size_t numBytes = mNumCols*sizeof(Real); Memcpy(vColumn, x, numBytes); } } } template <typename Real> Real SingularValueDecomposition<Real>::GetSingularValue(int index) const { if (0 <= index && index < mNumCols) { if (mPermutation[0] >= 0) { // Sorting was requested. return mDiagonal[mPermutation[index]]; } else { // Sorting was not requested. return mDiagonal[index]; } } else { return (Real)0; } } template <typename Real> void SingularValueDecomposition<Real>::Bidiagonalize() { int r, c; for (int i = 0, ip1 = 1; i < mNumCols; ++i, ++ip1) { // Compute the U-Householder vector. Real length = (Real)0; for (r = i; r < mNumRows; ++r) { Real ur = mMatrix[i + mNumCols*r]; mUVector[r] = ur; length += ur * ur; } Real udu = (Real)1; length = std::sqrt(length); if (length >(Real)0) { Real& u1 = mUVector[i]; Real sgn = (u1 >= (Real)0 ? (Real)1 : (Real)-1); Real invDenom = ((Real)1) / (u1 + sgn * length); u1 = (Real)1; for (r = ip1; r < mNumRows; ++r) { Real& ur = mUVector[r]; ur *= invDenom; udu += ur * ur; } } // Compute the rank-1 offset u*w^T. Real invudu = (Real)1 / udu; Real twoinvudu = invudu * (Real)2; for (c = i; c < mNumCols; ++c) { mWVector[c] = (Real)0; for (r = i; r < mNumRows; ++r) { mWVector[c] += mMatrix[c + mNumCols*r] * mUVector[r]; } mWVector[c] *= twoinvudu; } // Update the input matrix. for (r = i; r < mNumRows; ++r) { for (c = i; c < mNumCols; ++c) { mMatrix[c + mNumCols*r] -= mUVector[r] * mWVector[c]; } } if (i < mNumCols - 2) { // Compute the V-Householder vectors. length = (Real)0; for (c = ip1; c < mNumCols; ++c) { Real vc = mMatrix[c + mNumCols*i]; mVVector[c] = vc; length += vc * vc; } Real vdv = (Real)1; length = std::sqrt(length); if (length >(Real)0) { Real& v1 = mVVector[ip1]; Real sgn = (v1 >= (Real)0 ? (Real)1 : (Real)-1); Real invDenom = ((Real)1) / (v1 + sgn * length); v1 = (Real)1; for (c = ip1 + 1; c < mNumCols; ++c) { Real& vc = mVVector[c]; vc *= invDenom; vdv += vc * vc; } } // Compute the rank-1 offset w*v^T. Real invvdv = (Real)1 / vdv; Real twoinvvdv = invvdv * (Real)2; for (r = i; r < mNumRows; ++r) { mWVector[r] = (Real)0; for (c = ip1; c < mNumCols; ++c) { mWVector[r] += mMatrix[c + mNumCols*r] * mVVector[c]; } mWVector[r] *= twoinvvdv; } // Update the input matrix. for (r = i; r < mNumRows; ++r) { for (c = ip1; c < mNumCols; ++c) { mMatrix[c + mNumCols*r] -= mWVector[r] * mVVector[c]; } } mTwoInvVTV[i] = twoinvvdv; for (c = i + 2; c < mNumCols; ++c) { mMatrix[c + mNumCols*i] = mVVector[c]; } } mTwoInvUTU[i] = twoinvudu; for (r = ip1; r < mNumRows; ++r) { mMatrix[i + mNumCols*r] = mUVector[r]; } } // Copy the diagonal and subdiagonal for cache coherence in the // Golub-Kahan iterations. int k, ksup = mNumCols - 1, index = 0, delta = mNumCols + 1; for (k = 0; k < ksup; ++k, index += delta) { mDiagonal[k] = mMatrix[index]; mSuperdiagonal[k] = mMatrix[index + 1]; } mDiagonal[k] = mMatrix[index]; } template <typename Real> void SingularValueDecomposition<Real>::GetSinCos(Real x, Real y, Real& cs, Real& sn) { // Solves sn*x + cs*y = 0 robustly. Real tau; if (y != (Real)0) { if (std::abs(y) > std::abs(x)) { tau = -x / y; sn = ((Real)1) / std::sqrt(((Real)1) + tau*tau); cs = sn * tau; } else { tau = -y / x; cs = ((Real)1) / std::sqrt(((Real)1) + tau*tau); sn = cs * tau; } } else { cs = (Real)1; sn = (Real)0; } } template <typename Real> bool SingularValueDecomposition<Real>::DiagonalEntriesNonzero(int imin, int imax, Real threshold) { for (int i = imin; i <= imax; ++i) { if (std::abs(mDiagonal[i]) <= threshold) { // Use planar rotations to case the superdiagonal entry out of // the matrix, thus producing a row of zeros. Real x, z, cs, sn; Real y = mSuperdiagonal[i]; mSuperdiagonal[i] = (Real)0; for (int j = i + 1; j <= imax + 1; ++j) { x = mDiagonal[j]; GetSinCos(x, y, cs, sn); mLGivens.push_back(GivensRotation(i, j, cs, sn)); mDiagonal[j] = cs*x - sn*y; if (j <= imax) { z = mSuperdiagonal[j]; mSuperdiagonal[j] = cs*z; y = sn*z; } } return false; } } return true; } template <typename Real> void SingularValueDecomposition<Real>::DoGolubKahanStep(int imin, int imax) { // The implicit shift. Compute the eigenvalue u of the lower-right 2x2 // block of A = B^T*B that is closer to b11. Real f0 = (imax >= (Real)1 ? mSuperdiagonal[imax - 1] : (Real)0); Real d1 = mDiagonal[imax]; Real f1 = mSuperdiagonal[imax]; Real d2 = mDiagonal[imax + 1]; Real a00 = d1*d1 + f0*f0; Real a01 = d1*f1; Real a11 = d2*d2 + f1*f1; Real dif = (a00 - a11) * (Real)0.5; Real sgn = (dif >= (Real)0 ? (Real)1 : (Real)-1); Real a01sqr = a01 * a01; Real u = a11 - a01sqr / (dif + sgn * std::sqrt(dif*dif + a01sqr)); Real x = mDiagonal[imin] * mDiagonal[imin] - u; Real y = mDiagonal[imin] * mSuperdiagonal[imin]; Real a12, a21, a22, a23, cs, sn; Real a02 = (Real)0; int i0 = imin - 1, i1 = imin, i2 = imin + 1; for (/**/; i1 <= imax; ++i0, ++i1, ++i2) { // Compute the Givens rotation G and save it for use in computing // V in U^T*A*V = S. GetSinCos(x, y, cs, sn); mRGivens.push_back(GivensRotation(i1, i2, cs, sn)); // Update B0 = B*G. if (i1 > imin) { mSuperdiagonal[i0] = cs*mSuperdiagonal[i0] - sn*a02; } a11 = mDiagonal[i1]; a12 = mSuperdiagonal[i1]; a22 = mDiagonal[i2]; mDiagonal[i1] = cs*a11 - sn*a12; mSuperdiagonal[i1] = sn*a11 + cs*a12; mDiagonal[i2] = cs*a22; a21 = -sn*a22; // Update the parameters for the next Givens rotations. x = mDiagonal[i1]; y = a21; // Compute the Givens rotation G and save it for use in computing // U in U^T*A*V = S. GetSinCos(x, y, cs, sn); mLGivens.push_back(GivensRotation(i1, i2, cs, sn)); // Update B1 = G^T*B0. a11 = mDiagonal[i1]; a12 = mSuperdiagonal[i1]; a22 = mDiagonal[i2]; mDiagonal[i1] = cs*a11 - sn*a21; mSuperdiagonal[i1] = cs*a12 - sn*a22; mDiagonal[i2] = sn*a12 + cs*a22; if (i1 < imax) { a23 = mSuperdiagonal[i2]; a02 = -sn*a23; mSuperdiagonal[i2] = cs*a23; // Update the parameters for the next Givens rotations. x = mSuperdiagonal[i1]; y = a02; } } } template <typename Real> void SingularValueDecomposition<Real>::EnsureNonnegativeDiagonal() { for (int i = 0; i < mNumCols; ++i) { if (mDiagonal[i] >= (Real)0) { mFixupDiagonal[i] = (Real)1; } else { mDiagonal[i] = -mDiagonal[i]; mFixupDiagonal[i] = (Real)-1; } } } template <typename Real> void SingularValueDecomposition<Real>::ComputePermutation(int sortType) { if (sortType == 0) { // Set a flag for GetSingularValues() and GetOrthogonalMatrices() to // know that sorted output was not requested. mPermutation[0] = -1; return; } // Compute the permutation induced by sorting. Initially, we start with // the identity permutation I = (0,1,...,N-1). struct SortItem { Real singularValue; int index; }; std::vector<SortItem> items(mNumCols); int i; for (i = 0; i < mNumCols; ++i) { items[i].singularValue = mDiagonal[i]; items[i].index = i; } if (sortType > 0) { std::sort(items.begin(), items.end(), [](SortItem const& item0, SortItem const& item1) { return item0.singularValue < item1.singularValue; } ); } else { std::sort(items.begin(), items.end(), [](SortItem const& item0, SortItem const& item1) { return item0.singularValue > item1.singularValue; } ); } i = 0; for (auto const& item : items) { mPermutation[i++] = item.index; } // GetOrthogonalMatrices() has nontrivial code for computing the // orthogonal U and V from the reflections and rotations. To avoid // complicating the code further when sorting is requested, U and V are // computed as in the unsorted case. We then need to swap columns of // U and V to be consistent with the sorting of the singular values. To // minimize copying due to column swaps, we use permutation P. The // minimum number of transpositions to obtain P from I is N minus the // number of cycles of P. Each cycle is reordered with a minimum number // of transpositions; that is, the singular items are cyclically swapped, // leading to a minimum amount of copying. For example, if there is a // cycle i0 -> i1 -> i2 -> i3, then the copying is // save = singularitem[i0]; // singularitem[i1] = singularitem[i2]; // singularitem[i2] = singularitem[i3]; // singularitem[i3] = save; } template <typename Real> SingularValueDecomposition<Real>::GivensRotation::GivensRotation() { // No default initialization for fast creation of std::vector of objects // of this type. } template <typename Real> SingularValueDecomposition<Real>::GivensRotation::GivensRotation(int inIndex0, int inIndex1, Real inCs, Real inSn) : index0(inIndex0), index1(inIndex1), cs(inCs), sn(inSn) { } } // ---------------------------------------------- // GteHyperplane.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2016/07/28) // The plane is represented as Dot(U,X) = c where U is a unit-length normal // vector, c is the plane constant, and X is any point on the plane. The user // must ensure that the normal vector is unit length. namespace gte { template <int N, typename Real> class Hyperplane { public: // Construction and destruction. The default constructor sets the normal // to (0,...,0,1) and the constant to zero (plane z = 0). Hyperplane(); // Specify U and c directly. Hyperplane(Vector<N, Real> const& inNormal, Real inConstant); // U is specified, c = Dot(U,p) where p is a point on the hyperplane. Hyperplane(Vector<N, Real> const& inNormal, Vector<N, Real> const& p); // U is a unit-length vector in the orthogonal complement of the set // {p[1]-p[0],...,p[n-1]-p[0]} and c = Dot(U,p[0]), where the p[i] are // pointson the hyperplane. Hyperplane(std::array<Vector<N, Real>, N> const& p); // Public member access. Vector<N, Real> normal; Real constant; public: // Comparisons to support sorted containers. bool operator==(Hyperplane const& hyperplane) const; bool operator!=(Hyperplane const& hyperplane) const; bool operator< (Hyperplane const& hyperplane) const; bool operator<=(Hyperplane const& hyperplane) const; bool operator> (Hyperplane const& hyperplane) const; bool operator>=(Hyperplane const& hyperplane) const; }; // Template alias for convenience. template <typename Real> using Plane3 = Hyperplane<3, Real>; template <int N, typename Real> Hyperplane<N, Real>::Hyperplane() : constant((Real)0) { normal.MakeUnit(N - 1); } template <int N, typename Real> Hyperplane<N, Real>::Hyperplane(Vector<N, Real> const& inNormal, Real inConstant) : normal(inNormal), constant(inConstant) { } template <int N, typename Real> Hyperplane<N, Real>::Hyperplane(Vector<N, Real> const& inNormal, Vector<N, Real> const& p) : normal(inNormal), constant(Dot(inNormal, p)) { } template <int N, typename Real> Hyperplane<N, Real>::Hyperplane(std::array<Vector<N, Real>, N> const& p) { Matrix<N, N - 1, Real> edge; for (int i = 0; i < N - 1; ++i) { edge.SetCol(i, p[i + 1] - p[0]); } // Compute the 1-dimensional orthogonal complement of the edges of the // simplex formed by the points p[]. SingularValueDecomposition<Real> svd(N, N - 1, 32); svd.Solve(&edge[0], -1); svd.GetUColumn(N - 1, &normal[0]); constant = Dot(normal, p[0]); } template <int N, typename Real> bool Hyperplane<N, Real>::operator==(Hyperplane const& hyperplane) const { return normal == hyperplane.normal && constant == hyperplane.constant; } template <int N, typename Real> bool Hyperplane<N, Real>::operator!=(Hyperplane const& hyperplane) const { return !operator==(hyperplane); } template <int N, typename Real> bool Hyperplane<N, Real>::operator<(Hyperplane const& hyperplane) const { if (normal < hyperplane.normal) { return true; } if (normal > hyperplane.normal) { return false; } return constant < hyperplane.constant; } template <int N, typename Real> bool Hyperplane<N, Real>::operator<=(Hyperplane const& hyperplane) const { return operator<(hyperplane) || operator==(hyperplane); } template <int N, typename Real> bool Hyperplane<N, Real>::operator>(Hyperplane const& hyperplane) const { return !operator<=(hyperplane); } template <int N, typename Real> bool Hyperplane<N, Real>::operator>=(Hyperplane const& hyperplane) const { return !operator<(hyperplane); } } // ---------------------------------------------- // GteConvexHull3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Compute the convex hull of 3D points using incremental insertion. The only // way to ensure a correct result for the input vertices (assumed to be exact) // is to choose ComputeType for exact rational arithmetic. You may use // BSNumber. No divisions are performed in this computation, so you do not // have to use BSRational. // // The worst-case choices of N for Real of type BSNumber or BSRational with // integer storage UIntegerFP32<N> are listed in the next table. The numerical // computations are encapsulated in PrimalQuery3<Real>::ToPlane. We recommend // using only BSNumber, because no divisions are performed in the convex-hull // computations. // // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 27 // double | BSNumber | 197 // float | BSRational | 2882 // double | BSRational | 21688 namespace gte { template <typename InputType, typename ComputeType> class ConvexHull3 { public: // The class is a functor to support computing the convex hull of multiple // data sets using the same class object. For multithreading in Update, // choose 'numThreads' subject to the constraints // 1 <= numThreads <= std::thread::hardware_concurrency(). ConvexHull3(unsigned int numThreads = 1); // The input is the array of points whose convex hull is required. The // epsilon value is used to determine the intrinsic dimensionality of the // vertices (d = 0, 1, 2, or 3). When epsilon is positive, the // determination is fuzzy--points approximately the same point, // approximately on a line, approximately planar, or volumetric. bool operator()(int numPoints, Vector3<InputType> const* points, InputType epsilon); // Dimensional information. If GetDimension() returns 1, the points lie // on a line P+t*D (fuzzy comparison when epsilon > 0). You can sort // these if you need a polyline output by projecting onto the line each // vertex X = P+t*D, where t = Dot(D,X-P). If GetDimension() returns 2, // the points line on a plane P+s*U+t*V (fuzzy comparison when // epsilon > 0). You can project each point X = P+s*U+t*V, where // s = Dot(U,X-P) and t = Dot(V,X-P), then apply ConvexHull2 to the (s,t) // tuples. inline InputType GetEpsilon() const; inline int GetDimension() const; inline Line3<InputType> const& GetLine() const; inline Plane3<InputType> const& GetPlane() const; // Member access. inline int GetNumPoints() const; inline int GetNumUniquePoints() const; inline Vector3<InputType> const* GetPoints() const; inline PrimalQuery3<ComputeType> const& GetQuery() const; // The convex hull is a convex polyhedron with triangular faces. inline std::vector<TriangleKey<true>> const& GetHullUnordered() const; ETManifoldMesh const& GetHullMesh() const; private: // Support for incremental insertion. void Update(int i); // The epsilon value is used for fuzzy determination of intrinsic // dimensionality. If the dimension is 0, 1, or 2, the constructor // returns early. The caller is responsible for retrieving the dimension // and taking an alternate path should the dimension be smaller than 3. // If the dimension is 0, the caller may as well treat all points[] as a // single point, say, points[0]. If the dimension is 1, the caller can // query for the approximating line and project points[] onto it for // further processing. If the dimension is 2, the caller can query for // the approximating plane and project points[] onto it for further // processing. InputType mEpsilon; int mDimension; Line3<InputType> mLine; Plane3<InputType> mPlane; // The array of points used for geometric queries. If you want to be // certain of a correct result, choose ComputeType to be BSNumber. std::vector<Vector3<ComputeType>> mComputePoints; PrimalQuery3<ComputeType> mQuery; int mNumPoints; int mNumUniquePoints; Vector3<InputType> const* mPoints; std::vector<TriangleKey<true>> mHullUnordered; mutable ETManifoldMesh mHullMesh; unsigned int mNumThreads; }; template <typename InputType, typename ComputeType> ConvexHull3<InputType, ComputeType>::ConvexHull3(unsigned int numThreads) : mEpsilon((InputType)0), mDimension(0), mLine(Vector3<InputType>::Zero(), Vector3<InputType>::Zero()), mPlane(Vector3<InputType>::Zero(), (InputType)0), mNumPoints(0), mNumUniquePoints(0), mPoints(nullptr), mNumThreads(numThreads) { } template <typename InputType, typename ComputeType> bool ConvexHull3<InputType, ComputeType>::operator()(int numPoints, Vector3<InputType> const* points, InputType epsilon) { mEpsilon = std::max(epsilon, (InputType)0); mDimension = 0; mLine.origin = Vector3<InputType>::Zero(); mLine.direction = Vector3<InputType>::Zero(); mPlane.normal = Vector3<InputType>::Zero(); mPlane.constant = (InputType)0; mNumPoints = numPoints; mNumUniquePoints = 0; mPoints = points; mHullUnordered.clear(); mHullMesh.Clear(); int i, j; if (mNumPoints < 4) { // ConvexHull3 should be called with at least four points. return false; } IntrinsicsVector3<InputType> info(mNumPoints, mPoints, mEpsilon); if (info.dimension == 0) { // The set is (nearly) a point. return false; } if (info.dimension == 1) { // The set is (nearly) collinear. mDimension = 1; mLine = Line3<InputType>(info.origin, info.direction[0]); return false; } if (info.dimension == 2) { // The set is (nearly) coplanar. mDimension = 2; mPlane = Plane3<InputType>(UnitCross(info.direction[0], info.direction[1]), info.origin); return false; } mDimension = 3; // Compute the vertices for the queries. mComputePoints.resize(mNumPoints); mQuery.Set(mNumPoints, &mComputePoints[0]); for (i = 0; i < mNumPoints; ++i) { for (j = 0; j < 3; ++j) { mComputePoints[i][j] = points[i][j]; } } // Insert the faces of the (nondegenerate) tetrahedron constructed by the // call to GetInformation. if (!info.extremeCCW) { std::swap(info.extreme[2], info.extreme[3]); } mHullUnordered.push_back(TriangleKey<true>(info.extreme[1], info.extreme[2], info.extreme[3])); mHullUnordered.push_back(TriangleKey<true>(info.extreme[0], info.extreme[3], info.extreme[2])); mHullUnordered.push_back(TriangleKey<true>(info.extreme[0], info.extreme[1], info.extreme[3])); mHullUnordered.push_back(TriangleKey<true>(info.extreme[0], info.extreme[2], info.extreme[1])); // Incrementally update the hull. The set of processed points is // maintained to eliminate duplicates, either in the original input // points or in the points obtained by snap rounding. std::set<Vector3<InputType>> processed; for (i = 0; i < 4; ++i) { processed.insert(points[info.extreme[i]]); } for (i = 0; i < mNumPoints; ++i) { if (processed.find(points[i]) == processed.end()) { Update(i); processed.insert(points[i]); } } mNumUniquePoints = static_cast<int>(processed.size()); return true; } template <typename InputType, typename ComputeType> inline InputType ConvexHull3<InputType, ComputeType>::GetEpsilon() const { return mEpsilon; } template <typename InputType, typename ComputeType> inline int ConvexHull3<InputType, ComputeType>::GetDimension() const { return mDimension; } template <typename InputType, typename ComputeType> inline Line3<InputType> const& ConvexHull3<InputType, ComputeType>::GetLine() const { return mLine; } template <typename InputType, typename ComputeType> inline Plane3<InputType> const& ConvexHull3<InputType, ComputeType>::GetPlane() const { return mPlane; } template <typename InputType, typename ComputeType> inline int ConvexHull3<InputType, ComputeType>::GetNumPoints() const { return mNumPoints; } template <typename InputType, typename ComputeType> inline int ConvexHull3<InputType, ComputeType>::GetNumUniquePoints() const { return mNumUniquePoints; } template <typename InputType, typename ComputeType> inline Vector3<InputType> const* ConvexHull3<InputType, ComputeType>::GetPoints() const { return mPoints; } template <typename InputType, typename ComputeType> inline PrimalQuery3<ComputeType> const& ConvexHull3<InputType, ComputeType>::GetQuery() const { return mQuery; } template <typename InputType, typename ComputeType> inline std::vector<TriangleKey<true>> const& ConvexHull3<InputType, ComputeType>::GetHullUnordered() const { return mHullUnordered; } template <typename InputType, typename ComputeType> ETManifoldMesh const& ConvexHull3<InputType, ComputeType>::GetHullMesh() const { // Create the mesh only on demand. if (mHullMesh.GetTriangles().size() == 0) { for (auto const& tri : mHullUnordered) { mHullMesh.Insert(tri.V[0], tri.V[1], tri.V[2]); } } return mHullMesh; } template <typename InputType, typename ComputeType> void ConvexHull3<InputType, ComputeType>::Update(int i) { // The terminator that separates visible faces from nonvisible faces is // constructed by this code. Visible faces for the incoming hull are // removed, and the boundary of that set of triangles is the terminator. // New visible faces are added using the incoming point and the edges of // the terminator. // // A simple algorithm for computing terminator edges is the following. // Back-facing triangles are located and the three edges are processed. // The first time an edge is visited, insert it into the terminator. If // it is visited a second time, the edge is removed because it is shared // by another back-facing triangle and, therefore, cannot be a terminator // edge. After visiting all back-facing triangles, the only remaining // edges in the map are the terminator edges. // // The order of vertices of an edge is important for adding new faces with // the correct vertex winding. However, the edge "toggle" (insert edge, // remove edge) should use edges with unordered vertices, because the // edge shared by one triangle has opposite ordering relative to that of // the other triangle. The map uses unordered edges as the keys but // stores the ordered edge as the value. This avoids having to look up // an edge twice in a map with ordered edge keys. unsigned int numFaces = static_cast<unsigned int>(mHullUnordered.size()); std::vector<int> queryResult(numFaces); if (mNumThreads > 1 && numFaces >= mNumThreads) { // Partition the data for multiple threads. unsigned int numFacesPerThread = numFaces / mNumThreads; std::vector<unsigned int> jmin(mNumThreads), jmax(mNumThreads); for (unsigned int t = 0; t < mNumThreads; ++t) { jmin[t] = t * numFacesPerThread; jmax[t] = jmin[t] + numFacesPerThread - 1; } jmax[mNumThreads - 1] = numFaces - 1; // Execute the point-plane queries in multiple threads. std::vector<std::thread> process(mNumThreads); for (unsigned int t = 0; t < mNumThreads; ++t) { process[t] = std::thread([this, i, t, &jmin, &jmax, &queryResult]() { for (unsigned int j = jmin[t]; j <= jmax[t]; ++j) { TriangleKey<true> const& tri = mHullUnordered[j]; queryResult[j] = mQuery.ToPlane(i, tri.V[0], tri.V[1], tri.V[2]); } }); } // Wait for all threads to finish. for (unsigned int t = 0; t < mNumThreads; ++t) { process[t].join(); } } else { unsigned int j = 0; for (auto const& tri : mHullUnordered) { queryResult[j++] = mQuery.ToPlane(i, tri.V[0], tri.V[1], tri.V[2]); } } std::map<EdgeKey<false>, std::pair<int, int>> terminator; std::vector<TriangleKey<true>> backFaces; bool existsFrontFacingTriangle = false; unsigned int j = 0; for (auto const& tri : mHullUnordered) { if (queryResult[j++] <= 0) { // The triangle is back facing. These include triangles that // are coplanar with the incoming point. backFaces.push_back(tri); // The current hull is a 2-manifold watertight mesh. The // terminator edges are those shared with a front-facing triangle. // The first time an edge of a back-facing triangle is visited, // insert it into the terminator. If it is visited a second time, // the edge is removed because it is shared by another back-facing // triangle. After all back-facing triangles are visited, the // only remaining edges are shared by a single back-facing // triangle, which makes them terminator edges. for (int j0 = 2, j1 = 0; j1 < 3; j0 = j1++) { int v0 = tri.V[j0], v1 = tri.V[j1]; EdgeKey<false> edge(v0, v1); auto iter = terminator.find(edge); if (iter == terminator.end()) { // The edge is visited for the first time. terminator.insert(std::make_pair(edge, std::make_pair(v0, v1))); } else { // The edge is visited for the second time. terminator.erase(edge); } } } else { // If there are no strictly front-facing triangles, then the // incoming point is inside or on the convex hull. If we get // to this code, then the point is truly outside and we can // update the hull. existsFrontFacingTriangle = true; } } if (!existsFrontFacingTriangle) { // The incoming point is inside or on the current hull, so no // update of the hull is necessary. return; } // The updated hull contains the triangles not visible to the incoming // point. mHullUnordered = backFaces; // Insert the triangles formed by the incoming point and the terminator // edges. for (auto const& edge : terminator) { mHullUnordered.push_back(TriangleKey<true>(i, edge.second.second, edge.second.first)); } } } // ---------------------------------------------- // GteVector2.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.2 (2018/10/04) namespace gte { // Template alias for convenience. template <typename Real> using Vector2 = Vector<2, Real>; // Compute the perpendicular using the formal determinant, // perp = det{{e0,e1},{x0,x1}} = (x1,-x0) // where e0 = (1,0), e1 = (0,1), and v = (x0,x1). template <typename Real> Vector2<Real> Perp(Vector2<Real> const& v); // Compute the normalized perpendicular. template <typename Real> Vector2<Real> UnitPerp(Vector2<Real> const& v, bool robust = false); // Compute Dot((x0,x1),Perp(y0,y1)) = x0*y1 - x1*y0, where v0 = (x0,x1) // and v1 = (y0,y1). template <typename Real> Real DotPerp(Vector2<Real> const& v0, Vector2<Real> const& v1); // Compute a right-handed orthonormal basis for the orthogonal complement // of the input vectors. The function returns the smallest length of the // unnormalized vectors computed during the process. If this value is nearly // zero, it is possible that the inputs are linearly dependent (within // numerical round-off errors). On input, numInputs must be 1 and v[0] // must be initialized. On output, the vectors v[0] and v[1] form an // orthonormal set. template <typename Real> Real ComputeOrthogonalComplement(int numInputs, Vector2<Real>* v, bool robust = false); // Compute the barycentric coordinates of the point P with respect to the // triangle <V0,V1,V2>, P = b0*V0 + b1*V1 + b2*V2, where b0 + b1 + b2 = 1. // The return value is 'true' iff {V0,V1,V2} is a linearly independent set. // Numerically, this is measured by |det[V0 V1 V2]| <= epsilon. The values // bary[] are valid only when the return value is 'true' but set to zero when // the return value is 'false'. template <typename Real> bool ComputeBarycentrics(Vector2<Real> const& p, Vector2<Real> const& v0, Vector2<Real> const& v1, Vector2<Real> const& v2, Real bary[3], Real epsilon = (Real)0); // Get intrinsic information about the input array of vectors. The return // value is 'true' iff the inputs are valid (numVectors > 0, v is not null, // and epsilon >= 0), in which case the class members are valid. template <typename Real> class IntrinsicsVector2 { public: // The constructor sets the class members based on the input set. IntrinsicsVector2(int numVectors, Vector2<Real> const* v, Real inEpsilon); // A nonnegative tolerance that is used to determine the intrinsic // dimension of the set. Real epsilon; // The intrinsic dimension of the input set, computed based on the // nonnegative tolerance mEpsilon. int dimension; // Axis-aligned bounding box of the input set. The maximum range is // the larger of max[0]-min[0] and max[1]-min[1]. Real min[2], max[2]; Real maxRange; // Coordinate system. The origin is valid for any dimension d. The // unit-length direction vector is valid only for 0 <= i < d. The // extreme index is relative to the array of input points, and is also // valid only for 0 <= i < d. If d = 0, all points are effectively // the same, but the use of an epsilon may lead to an extreme index // that is not zero. If d = 1, all points effectively lie on a line // segment. If d = 2, the points are not collinear. Vector2<Real> origin; Vector2<Real> direction[2]; // The indices that define the maximum dimensional extents. The // values extreme[0] and extreme[1] are the indices for the points // that define the largest extent in one of the coordinate axis // directions. If the dimension is 2, then extreme[2] is the index // for the point that generates the largest extent in the direction // perpendicular to the line through the points corresponding to // extreme[0] and extreme[1]. The triangle formed by the points // V[extreme[0]], V[extreme[1]], and V[extreme[2]] is clockwise or // counterclockwise, the condition stored in extremeCCW. int extreme[3]; bool extremeCCW; }; template <typename Real> Vector2<Real> Perp(Vector2<Real> const& v) { return Vector2<Real>{ v[1], -v[0] }; } template <typename Real> Vector2<Real> UnitPerp(Vector2<Real> const& v, bool robust) { Vector2<Real> unitPerp{ v[1], -v[0] }; Normalize(unitPerp, robust); return unitPerp; } template <typename Real> Real DotPerp(Vector2<Real> const& v0, Vector2<Real> const& v1) { return Dot(v0, Perp(v1)); } template <typename Real> Real ComputeOrthogonalComplement(int numInputs, Vector2<Real>* v, bool robust) { if (numInputs == 1) { v[1] = -Perp(v[0]); return Orthonormalize<2, Real>(2, v, robust); } return (Real)0; } template <typename Real> bool ComputeBarycentrics(Vector2<Real> const& p, Vector2<Real> const& v0, Vector2<Real> const& v1, Vector2<Real> const& v2, Real bary[3], Real epsilon) { // Compute the vectors relative to V2 of the triangle. Vector2<Real> diff[3] = { v0 - v2, v1 - v2, p - v2 }; Real det = DotPerp(diff[0], diff[1]); if (det < -epsilon || det > epsilon) { Real invDet = ((Real)1) / det; bary[0] = DotPerp(diff[2], diff[1])*invDet; bary[1] = DotPerp(diff[0], diff[2])*invDet; bary[2] = (Real)1 - bary[0] - bary[1]; return true; } for (int i = 0; i < 3; ++i) { bary[i] = (Real)0; } return false; } template <typename Real> IntrinsicsVector2<Real>::IntrinsicsVector2(int numVectors, Vector2<Real> const* v, Real inEpsilon) : epsilon(inEpsilon), dimension(0), maxRange((Real)0), origin({ (Real)0, (Real)0 }), extremeCCW(false) { min[0] = (Real)0; min[1] = (Real)0; direction[0] = { (Real)0, (Real)0 }; direction[1] = { (Real)0, (Real)0 }; extreme[0] = 0; extreme[1] = 0; extreme[2] = 0; if (numVectors > 0 && v && epsilon >= (Real)0) { // Compute the axis-aligned bounding box for the input vectors. Keep // track of the indices into 'vectors' for the current min and max. int j, indexMin[2], indexMax[2]; for (j = 0; j < 2; ++j) { min[j] = v[0][j]; max[j] = min[j]; indexMin[j] = 0; indexMax[j] = 0; } int i; for (i = 1; i < numVectors; ++i) { for (j = 0; j < 2; ++j) { if (v[i][j] < min[j]) { min[j] = v[i][j]; indexMin[j] = i; } else if (v[i][j] > max[j]) { max[j] = v[i][j]; indexMax[j] = i; } } } // Determine the maximum range for the bounding box. maxRange = max[0] - min[0]; extreme[0] = indexMin[0]; extreme[1] = indexMax[0]; Real range = max[1] - min[1]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[1]; extreme[1] = indexMax[1]; } // The origin is either the vector of minimum x0-value or vector of // minimum x1-value. origin = v[extreme[0]]; // Test whether the vector set is (nearly) a vector. if (maxRange <= epsilon) { dimension = 0; for (j = 0; j < 2; ++j) { extreme[j + 1] = extreme[0]; } return; } // Test whether the vector set is (nearly) a line segment. We need // direction[1] to span the orthogonal complement of direction[0]. direction[0] = v[extreme[1]] - origin; Normalize(direction[0], false); direction[1] = -Perp(direction[0]); // Compute the maximum distance of the points from the line // origin+t*direction[0]. Real maxDistance = (Real)0; Real maxSign = (Real)0; extreme[2] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector2<Real> diff = v[i] - origin; Real distance = Dot(direction[1], diff); Real sign = (distance >(Real)0 ? (Real)1 : (distance < (Real)0 ? (Real)-1 : (Real)0)); distance = std::abs(distance); if (distance > maxDistance) { maxDistance = distance; maxSign = sign; extreme[2] = i; } } if (maxDistance <= epsilon * maxRange) { // The points are (nearly) on the line origin+t*direction[0]. dimension = 1; extreme[2] = extreme[1]; return; } dimension = 2; extremeCCW = (maxSign > (Real)0); return; } } } // ---------------------------------------------- // GtePrimalQuery2.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Queries about the relation of a point to various geometric objects. The // choices for N when using UIntegerFP32<N> for either BSNumber of BSRational // are determined in GeometricTools/GTEngine/Tools/PrecisionCalculator. These // N-values are worst case scenarios. Your specific input data might require // much smaller N, in which case you can modify PrecisionCalculator to use the // BSPrecision(int32_t,int32_t,int32_t,bool) constructors. namespace gte { template <typename Real> class PrimalQuery2 { public: // The caller is responsible for ensuring that the array is not empty // before calling queries and that the indices passed to the queries are // valid. The class does no range checking. PrimalQuery2(); PrimalQuery2(int numVertices, Vector2<Real> const* vertices); // Member access. inline void Set(int numVertices, Vector2<Real> const* vertices); inline int GetNumVertices() const; inline Vector2<Real> const* GetVertices() const; // In the following, point P refers to vertices[i] or 'test' and Vi refers // to vertices[vi]. // For a line with origin V0 and direction <V0,V1>, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+----- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 214 // double | BSRational | 1587 int ToLine(int i, int v0, int v1) const; int ToLine(Vector2<Real> const& test, int v0, int v1) const; // For a line with origin V0 and direction <V0,V1>, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line // The 'order' parameter is // -3, points not collinear, P on left of line // -2, P strictly left of V0 on the line // -1, P = V0 // 0, P interior to line segment [V0,V1] // +1, P = V1 // +2, P strictly right of V0 on the line // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+----- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 214 // double | BSRational | 1587 // This is the same as the first-listed ToLine calls because the worst-case // path has the same computational complexity. int ToLine(int i, int v0, int v1, int& order) const; int ToLine(Vector2<Real> const& test, int v0, int v1, int& order) const; // For a triangle with counterclockwise vertices V0, V1, and V2, // ToTriangle returns // +1, P outside triangle // -1, P inside triangle // 0, P on triangle // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+----- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 214 // double | BSRational | 1587 // The query involves three calls to ToLine, so the numbers match those // of ToLine. int ToTriangle(int i, int v0, int v1, int v2) const; int ToTriangle(Vector2<Real> const& test, int v0, int v1, int v2) const; // For a triangle with counterclockwise vertices V0, V1, and V2, // ToCircumcircle returns // +1, P outside circumcircle of triangle // -1, P inside circumcircle of triangle // 0, P on circumcircle of triangle // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 35 // double | BSNumber | 263 // float | BSRational | 12302 // double | BSRational | 92827 // The query involves three calls of ToLine, so the numbers match those // of ToLine. int ToCircumcircle(int i, int v0, int v1, int v2) const; int ToCircumcircle(Vector2<Real> const& test, int v0, int v1, int v2) const; // An extended classification of the relationship of a point to a line // segment. For noncollinear points, the return value is // ORDER_POSITIVE when <P,Q0,Q1> is a counterclockwise triangle // ORDER_NEGATIVE when <P,Q0,Q1> is a clockwise triangle // For collinear points, the line direction is Q1-Q0. The return value is // ORDER_COLLINEAR_LEFT when the line ordering is <P,Q0,Q1> // ORDER_COLLINEAR_RIGHT when the line ordering is <Q0,Q1,P> // ORDER_COLLINEAR_CONTAIN when the line ordering is <Q0,P,Q1> enum OrderType { ORDER_Q0_EQUALS_Q1, ORDER_P_EQUALS_Q0, ORDER_P_EQUALS_Q1, ORDER_POSITIVE, ORDER_NEGATIVE, ORDER_COLLINEAR_LEFT, ORDER_COLLINEAR_RIGHT, ORDER_COLLINEAR_CONTAIN }; // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+----- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 214 // double | BSRational | 1587 // This is the same as the first-listed ToLine calls because the worst-case // path has the same computational complexity. OrderType ToLineExtended(Vector2<Real> const& P, Vector2<Real> const& Q0, Vector2<Real> const& Q1) const; private: int mNumVertices; Vector2<Real> const* mVertices; }; template <typename Real> PrimalQuery2<Real>::PrimalQuery2() : mNumVertices(0), mVertices(nullptr) { } template <typename Real> PrimalQuery2<Real>::PrimalQuery2(int numVertices, Vector2<Real> const* vertices) : mNumVertices(numVertices), mVertices(vertices) { } template <typename Real> inline void PrimalQuery2<Real>::Set(int numVertices, Vector2<Real> const* vertices) { mNumVertices = numVertices; mVertices = vertices; } template <typename Real> inline int PrimalQuery2<Real>::GetNumVertices() const { return mNumVertices; } template <typename Real> inline Vector2<Real> const* PrimalQuery2<Real>::GetVertices() const { return mVertices; } template <typename Real> int PrimalQuery2<Real>::ToLine(int i, int v0, int v1) const { return ToLine(mVertices[i], v0, v1); } template <typename Real> int PrimalQuery2<Real>::ToLine(Vector2<Real> const& test, int v0, int v1) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Real x0 = test[0] - vec0[0]; Real y0 = test[1] - vec0[1]; Real x1 = vec1[0] - vec0[0]; Real y1 = vec1[1] - vec0[1]; Real x0y1 = x0*y1; Real x1y0 = x1*y0; Real det = x0y1 - x1y0; Real const zero(0); return (det > zero ? +1 : (det < zero ? -1 : 0)); } template <typename Real> int PrimalQuery2<Real>::ToLine(int i, int v0, int v1, int& order) const { return ToLine(mVertices[i], v0, v1, order); } template <typename Real> int PrimalQuery2<Real>::ToLine(Vector2<Real> const& test, int v0, int v1, int& order) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Real x0 = test[0] - vec0[0]; Real y0 = test[1] - vec0[1]; Real x1 = vec1[0] - vec0[0]; Real y1 = vec1[1] - vec0[1]; Real x0y1 = x0*y1; Real x1y0 = x1*y0; Real det = x0y1 - x1y0; Real const zero(0); if (det > zero) { order = +3; return +1; } if (det < zero) { order = -3; return -1; } Real x0x1 = x0*x1; Real y0y1 = y0*y1; Real dot = x0x1 + y0y1; if (dot == zero) { order = -1; } else if (dot < zero) { order = -2; } else { Real x0x0 = x0*x0; Real y0y0 = y0*y0; Real sqrLength = x0x0 + y0y0; if (dot == sqrLength) { order = +1; } else if (dot > sqrLength) { order = +2; } else { order = 0; } } return 0; } template <typename Real> int PrimalQuery2<Real>::ToTriangle(int i, int v0, int v1, int v2) const { return ToTriangle(mVertices[i], v0, v1, v2); } template <typename Real> int PrimalQuery2<Real>::ToTriangle(Vector2<Real> const& test, int v0, int v1, int v2) const { int sign0 = ToLine(test, v1, v2); if (sign0 > 0) { return +1; } int sign1 = ToLine(test, v0, v2); if (sign1 < 0) { return +1; } int sign2 = ToLine(test, v0, v1); if (sign2 > 0) { return +1; } return ((sign0 && sign1 && sign2) ? -1 : 0); } template <typename Real> int PrimalQuery2<Real>::ToCircumcircle(int i, int v0, int v1, int v2) const { return ToCircumcircle(mVertices[i], v0, v1, v2); } template <typename Real> int PrimalQuery2<Real>::ToCircumcircle(Vector2<Real> const& test, int v0, int v1, int v2) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Vector2<Real> const& vec2 = mVertices[v2]; Real x0 = vec0[0] - test[0]; Real y0 = vec0[1] - test[1]; Real s00 = vec0[0] + test[0]; Real s01 = vec0[1] + test[1]; Real t00 = s00*x0; Real t01 = s01*y0; Real z0 = t00 + t01; Real x1 = vec1[0] - test[0]; Real y1 = vec1[1] - test[1]; Real s10 = vec1[0] + test[0]; Real s11 = vec1[1] + test[1]; Real t10 = s10*x1; Real t11 = s11*y1; Real z1 = t10 + t11; Real x2 = vec2[0] - test[0]; Real y2 = vec2[1] - test[1]; Real s20 = vec2[0] + test[0]; Real s21 = vec2[1] + test[1]; Real t20 = s20*x2; Real t21 = s21*y2; Real z2 = t20 + t21; Real y0z1 = y0*z1; Real y0z2 = y0*z2; Real y1z0 = y1*z0; Real y1z2 = y1*z2; Real y2z0 = y2*z0; Real y2z1 = y2*z1; Real c0 = y1z2 - y2z1; Real c1 = y2z0 - y0z2; Real c2 = y0z1 - y1z0; Real x0c0 = x0*c0; Real x1c1 = x1*c1; Real x2c2 = x2*c2; Real term = x0c0 + x1c1; Real det = term + x2c2; Real const zero(0); return (det < zero ? 1 : (det > zero ? -1 : 0)); } template <typename Real> typename PrimalQuery2<Real>::OrderType PrimalQuery2<Real>::ToLineExtended( Vector2<Real> const& P, Vector2<Real> const& Q0, Vector2<Real> const& Q1) const { Real const zero(0); Real x0 = Q1[0] - Q0[0]; Real y0 = Q1[1] - Q0[1]; if (x0 == zero && y0 == zero) { return ORDER_Q0_EQUALS_Q1; } Real x1 = P[0] - Q0[0]; Real y1 = P[1] - Q0[1]; if (x1 == zero && y1 == zero) { return ORDER_P_EQUALS_Q0; } Real x2 = P[0] - Q1[0]; Real y2 = P[1] - Q1[1]; if (x2 == zero && y2 == zero) { return ORDER_P_EQUALS_Q1; } // The theoretical classification relies on computing exactly the sign of // the determinant. Numerical roundoff errors can cause misclassification. Real x0y1 = x0 * y1; Real x1y0 = x1 * y0; Real det = x0y1 - x1y0; if (det != zero) { if (det > zero) { // The points form a counterclockwise triangle <P,Q0,Q1>. return ORDER_POSITIVE; } else { // The points form a clockwise triangle <P,Q1,Q0>. return ORDER_NEGATIVE; } } else { // The points are collinear; P is on the line through Q0 and Q1. Real x0x1 = x0 * x1; Real y0y1 = y0 * y1; Real dot = x0x1 + y0y1; if (dot < zero) { // The line ordering is <P,Q0,Q1>. return ORDER_COLLINEAR_LEFT; } Real x0x0 = x0 * x0; Real y0y0 = y0 * y0; Real sqrLength = x0x0 + y0y0; if (dot > sqrLength) { // The line ordering is <Q0,Q1,P>. return ORDER_COLLINEAR_RIGHT; } // The line ordering is <Q0,P,Q1> with P strictly between Q0 and Q1. return ORDER_COLLINEAR_CONTAIN; } } } // ---------------------------------------------- // GteConvexHull2.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Compute the convex hull of 2D points using a divide-and-conquer algorithm. // This is an O(N log N) algorithm for N input points. The only way to ensure // a correct result for the input vertices (assumed to be exact) is to choose // ComputeType for exact rational arithmetic. You may use BSNumber. No // divisions are performed in this computation, so you do not have to use // BSRational. // // The worst-case choices of N for Real of type BSNumber or BSRational with // integer storage UIntegerFP32<N> are listed in the next table. The numerical // computations are encapsulated in PrimalQuery2<Real>::ToLineExtended. We // recommend using only BSNumber, because no divisions are performed in the // convex-hull computations. // // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 214 // double | BSRational | 1587 namespace gte { template <typename InputType, typename ComputeType> class ConvexHull2 { public: // The class is a functor to support computing the convex hull of multiple // data sets using the same class object. ConvexHull2(); // The input is the array of points whose convex hull is required. The // epsilon value is used to determine the intrinsic dimensionality of the // vertices (d = 0, 1, or 2). When epsilon is positive, the determination // is fuzzy--points approximately the same point, approximately on a // line, or planar. The return value is 'true' if and only if the hull // construction is successful. bool operator()(int numPoints, Vector2<InputType> const* points, InputType epsilon); // Dimensional information. If GetDimension() returns 1, the points lie // on a line P+t*D (fuzzy comparison when epsilon > 0). You can sort // these if you need a polyline output by projecting onto the line each // vertex X = P+t*D, where t = Dot(D,X-P). inline InputType GetEpsilon() const; inline int GetDimension() const; inline Line2<InputType> const& GetLine() const; // Member access. inline int GetNumPoints() const; inline int GetNumUniquePoints() const; inline Vector2<InputType> const* GetPoints() const; inline PrimalQuery2<ComputeType> const& GetQuery() const; // The convex hull is a convex polygon whose vertices are listed in // counterclockwise order. inline std::vector<int> const& GetHull() const; private: // Support for divide-and-conquer. void GetHull(int& i0, int& i1); void Merge(int j0, int j1, int j2, int j3, int& i0, int& i1); void GetTangent(int j0, int j1, int j2, int j3, int& i0, int& i1); // The epsilon value is used for fuzzy determination of intrinsic // dimensionality. If the dimension is 0 or 1, the constructor returns // early. The caller is responsible for retrieving the dimension and // taking an alternate path should the dimension be smaller than 2. If // the dimension is 0, the caller may as well treat all points[] as a // single point, say, points[0]. If the dimension is 1, the caller can // query for the approximating line and project points[] onto it for // further processing. InputType mEpsilon; int mDimension; Line2<InputType> mLine; // The array of points used for geometric queries. If you want to be // certain of a correct result, choose ComputeType to be BSNumber. std::vector<Vector2<ComputeType>> mComputePoints; PrimalQuery2<ComputeType> mQuery; int mNumPoints; int mNumUniquePoints; Vector2<InputType> const* mPoints; std::vector<int> mMerged, mHull; }; template <typename InputType, typename ComputeType> ConvexHull2<InputType, ComputeType>::ConvexHull2() : mEpsilon((InputType)0), mDimension(0), mLine(Vector2<InputType>::Zero(), Vector2<InputType>::Zero()), mNumPoints(0), mNumUniquePoints(0), mPoints(nullptr) { } template <typename InputType, typename ComputeType> bool ConvexHull2<InputType, ComputeType>::operator()(int numPoints, Vector2<InputType> const* points, InputType epsilon) { mEpsilon = std::max(epsilon, (InputType)0); mDimension = 0; mLine.origin = Vector2<InputType>::Zero(); mLine.direction = Vector2<InputType>::Zero(); mNumPoints = numPoints; mNumUniquePoints = 0; mPoints = points; mMerged.clear(); mHull.clear(); int i, j; if (mNumPoints < 3) { // ConvexHull2 should be called with at least three points. return false; } IntrinsicsVector2<InputType> info(mNumPoints, mPoints, mEpsilon); if (info.dimension == 0) { // mDimension is 0 return false; } if (info.dimension == 1) { // The set is (nearly) collinear. mDimension = 1; mLine = Line2<InputType>(info.origin, info.direction[0]); return false; } mDimension = 2; // Compute the points for the queries. mComputePoints.resize(mNumPoints); mQuery.Set(mNumPoints, &mComputePoints[0]); for (i = 0; i < mNumPoints; ++i) { for (j = 0; j < 2; ++j) { mComputePoints[i][j] = points[i][j]; } } // Sort the points. mHull.resize(mNumPoints); for (i = 0; i < mNumPoints; ++i) { mHull[i] = i; } std::sort(mHull.begin(), mHull.end(), [points](int i0, int i1) { if (points[i0][0] < points[i1][0]) { return true; } if (points[i0][0] > points[i1][0]) { return false; } return points[i0][1] < points[i1][1]; } ); // Remove duplicates. auto newEnd = std::unique(mHull.begin(), mHull.end(), [points](int i0, int i1) { return points[i0] == points[i1]; } ); mHull.erase(newEnd, mHull.end()); mNumUniquePoints = static_cast<int>(mHull.size()); // Use a divide-and-conquer algorithm. The merge step computes the // convex hull of two convex polygons. mMerged.resize(mNumUniquePoints); int i0 = 0, i1 = mNumUniquePoints - 1; GetHull(i0, i1); mHull.resize(i1 - i0 + 1); return true; } template <typename InputType, typename ComputeType> inline InputType ConvexHull2<InputType, ComputeType>::GetEpsilon() const { return mEpsilon; } template <typename InputType, typename ComputeType> inline int ConvexHull2<InputType, ComputeType>::GetDimension() const { return mDimension; } template <typename InputType, typename ComputeType> inline Line2<InputType> const& ConvexHull2<InputType, ComputeType>::GetLine() const { return mLine; } template <typename InputType, typename ComputeType> inline int ConvexHull2<InputType, ComputeType>::GetNumPoints() const { return mNumPoints; } template <typename InputType, typename ComputeType> inline int ConvexHull2<InputType, ComputeType>::GetNumUniquePoints() const { return mNumUniquePoints; } template <typename InputType, typename ComputeType> inline Vector2<InputType> const* ConvexHull2<InputType, ComputeType>::GetPoints() const { return mPoints; } template <typename InputType, typename ComputeType> inline PrimalQuery2<ComputeType> const& ConvexHull2<InputType, ComputeType>::GetQuery() const { return mQuery; } template <typename InputType, typename ComputeType> inline std::vector<int> const& ConvexHull2<InputType, ComputeType>::GetHull() const { return mHull; } template <typename InputType, typename ComputeType> inline void ConvexHull2<InputType, ComputeType>::GetHull(int& i0, int& i1) { int numVertices = i1 - i0 + 1; if (numVertices > 1) { // Compute the middle index of input range. int mid = (i0 + i1) / 2; // Compute the hull of subsets (mid-i0+1 >= i1-mid). int j0 = i0, j1 = mid, j2 = mid + 1, j3 = i1; GetHull(j0, j1); GetHull(j2, j3); // Merge the convex hulls into a single convex hull. Merge(j0, j1, j2, j3, i0, i1); } // else: The convex hull is a single point. } template <typename InputType, typename ComputeType> inline void ConvexHull2<InputType, ComputeType>::Merge(int j0, int j1, int j2, int j3, int& i0, int& i1) { // Subhull0 is to the left of subhull1 because of the initial sorting of // the points by x-components. We need to find two mutually visible // points, one on the left subhull and one on the right subhull. int size0 = j1 - j0 + 1; int size1 = j3 - j2 + 1; int i; Vector2<ComputeType> p; // Find the right-most point of the left subhull. Vector2<ComputeType> pmax0 = mComputePoints[mHull[j0]]; int imax0 = j0; for (i = j0 + 1; i <= j1; ++i) { p = mComputePoints[mHull[i]]; if (pmax0 < p) { pmax0 = p; imax0 = i; } } // Find the left-most point of the right subhull. Vector2<ComputeType> pmin1 = mComputePoints[mHull[j2]]; int imin1 = j2; for (i = j2 + 1; i <= j3; ++i) { p = mComputePoints[mHull[i]]; if (p < pmin1) { pmin1 = p; imin1 = i; } } // Get the lower tangent to hulls (LL = lower-left, LR = lower-right). int iLL = imax0, iLR = imin1; GetTangent(j0, j1, j2, j3, iLL, iLR); // Get the upper tangent to hulls (UL = upper-left, UR = upper-right). int iUL = imax0, iUR = imin1; GetTangent(j2, j3, j0, j1, iUR, iUL); // Construct the counterclockwise-ordered merged-hull vertices. int k; int numMerged = 0; i = iUL; for (k = 0; k < size0; ++k) { mMerged[numMerged++] = mHull[i]; if (i == iLL) { break; } i = (i < j1 ? i + 1 : j0); } LogAssert(k < size0, "Unexpected condition."); i = iLR; for (k = 0; k < size1; ++k) { mMerged[numMerged++] = mHull[i]; if (i == iUR) { break; } i = (i < j3 ? i + 1 : j2); } LogAssert(k < size1, "Unexpected condition."); int next = j0; for (k = 0; k < numMerged; ++k) { mHull[next] = mMerged[k]; ++next; } i0 = j0; i1 = next - 1; } template <typename InputType, typename ComputeType> inline void ConvexHull2<InputType, ComputeType>::GetTangent(int j0, int j1, int j2, int j3, int& i0, int& i1) { // In theory the loop terminates in a finite number of steps, but the // upper bound for the loop variable is used to trap problems caused by // floating point roundoff errors that might lead to an infinite loop. int size0 = j1 - j0 + 1; int size1 = j3 - j2 + 1; int const imax = size0 + size1; int i, iLm1, iRp1; Vector2<ComputeType> L0, L1, R0, R1; for (i = 0; i < imax; i++) { // Get the endpoints of the potential tangent. L1 = mComputePoints[mHull[i0]]; R0 = mComputePoints[mHull[i1]]; // Walk along the left hull to find the point of tangency. if (size0 > 1) { iLm1 = (i0 > j0 ? i0 - 1 : j1); L0 = mComputePoints[mHull[iLm1]]; auto order = mQuery.ToLineExtended(R0, L0, L1); if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE || order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_RIGHT) { i0 = iLm1; continue; } } // Walk along right hull to find the point of tangency. if (size1 > 1) { iRp1 = (i1 < j3 ? i1 + 1 : j2); R1 = mComputePoints[mHull[iRp1]]; auto order = mQuery.ToLineExtended(L1, R0, R1); if (order == PrimalQuery2<ComputeType>::ORDER_NEGATIVE || order == PrimalQuery2<ComputeType>::ORDER_COLLINEAR_LEFT) { i1 = iRp1; continue; } } // The tangent segment has been found. break; } // Detect an "infinite loop" caused by floating point round-off errors. LogAssert(i < imax, "Unexpected condition."); } } // ---------------------------------------------- // GteMinimumAreaBox2.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.2 (2018/10/05) // Compute a minimum-area oriented box containing the specified points. The // algorithm uses the rotating calipers method. // http://www-cgrl.cs.mcgill.ca/~godfried/research/calipers.html // http://cgm.cs.mcgill.ca/~orm/rotcal.html // The box is supported by the convex hull of the points, so the algorithm // is really about computing the minimum-area box containing a convex polygon. // The rotating calipers approach is O(n) in time for n polygon edges. // // A detailed description of the algorithm and implementation is found in // http://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf // // NOTE: This algorithm guarantees a correct output only when ComputeType is // an exact arithmetic type that supports division. In GTEngine, one such // type is BSRational<UIntegerAP32> (arbitrary precision). Another such type // is BSRational<UIntegerFP32<N>> (fixed precision), where N is chosen large // enough for your input data sets. If you choose ComputeType to be 'float' // or 'double', the output is not guaranteed to be correct. // // See GeometricTools/GTEngine/Samples/Geometrics/MinimumAreaBox2 for an // example of how to use the code. namespace gte { template <typename InputType, typename ComputeType> class MinimumAreaBox2 { public: // The class is a functor to support computing the minimum-area box of // multiple data sets using the same class object. MinimumAreaBox2(); // The points are arbitrary, so we must compute the convex hull from // them in order to compute the minimum-area box. The input parameters // are necessary for using ConvexHull2. NOTE: ConvexHull2 guarantees // that the hull does not have three consecutive collinear points. OrientedBox2<InputType> operator()(int numPoints, Vector2<InputType> const* points, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value); // The points already form a counterclockwise, nondegenerate convex // polygon. If the points directly are the convex polygon, set // numIndices to 0 and indices to nullptr. If the polygon vertices // are a subset of the incoming points, that subset is identified by // numIndices >= 3 and indices having numIndices elements. OrientedBox2<InputType> operator()(int numPoints, Vector2<InputType> const* points, int numIndices, int const* indices, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value); // Member access. inline int GetNumPoints() const; inline Vector2<InputType> const* GetPoints() const; inline std::vector<int> const& GetHull() const; inline std::array<int, 4> const& GetSupportIndices() const; inline InputType GetArea() const; private: // The box axes are U[i] and are usually not unit-length in order to allow // exact arithmetic. The box is supported by mPoints[index[i]], where i // is one of the enumerations above. The box axes are not necessarily unit // length, but they have the same length. They need to be normalized for // conversion back to InputType. struct Box { Vector2<ComputeType> U[2]; std::array<int, 4> index; // order: bottom, right, top, left ComputeType sqrLenU0, area; }; // The rotating calipers algorithm has a loop invariant that requires // the convex polygon not to have collinear points. Any such points // must be removed first. The code is also executed for the O(n^2) // algorithm to reduce the number of process edges. void RemoveCollinearPoints(std::vector<Vector2<ComputeType>>& vertices); // This is the slow O(n^2) search. Box ComputeBoxForEdgeOrderNSqr( std::vector<Vector2<ComputeType>> const& vertices); // The fast O(n) search. Box ComputeBoxForEdgeOrderN( std::vector<Vector2<ComputeType>> const& vertices); // Compute the smallest box for the polygon edge <V[i0],V[i1]>. Box SmallestBox(int i0, int i1, std::vector<Vector2<ComputeType>> const& vertices); // Compute (sin(angle))^2 for the polygon edges emanating from the support // vertices of the box. The return value is 'true' if at least one angle // is in [0,pi/2); otherwise, the return value is 'false' and the original // polygon must be a rectangle. bool ComputeAngles(std::vector<Vector2<ComputeType>> const& vertices, Box const& box, std::array<std::pair<ComputeType, int>, 4>& A, int& numA) const; // Sort the angles indirectly. The sorted indices are returned. This // avoids swapping elements of A[], which can be expensive when // ComputeType is an exact rational type. std::array<int, 4> SortAngles( std::array<std::pair<ComputeType, int>, 4> const& A, int numA) const; bool UpdateSupport(std::array<std::pair<ComputeType, int>, 4> const& A, int numA, std::array<int, 4> const& sort, std::vector<Vector2<ComputeType>> const& vertices, std::vector<bool>& visited, Box& box); // Convert the ComputeType box to the InputType box. When the ComputeType // is an exact rational type, the conversions are performed to avoid // precision loss until necessary at the last step. void ConvertTo(Box const& minBox, std::vector<Vector2<ComputeType>> const& computePoints, OrientedBox2<InputType>& itMinBox); // The input points to be bound. int mNumPoints; Vector2<InputType> const* mPoints; // The indices into mPoints/mComputePoints for the convex hull vertices. std::vector<int> mHull; // The support indices for the minimum-area box. std::array<int, 4> mSupportIndices; // The area of the minimum-area box. The ComputeType value is exact, // so the only rounding errors occur in the conversion from ComputeType // to InputType (default rounding mode is round-to-nearest-ties-to-even). InputType mArea; // Convenient values that occur regularly in the code. When using // rational ComputeType, we construct these numbers only once. ComputeType mZero, mOne, mNegOne, mHalf; }; template <typename InputType, typename ComputeType> MinimumAreaBox2<InputType, ComputeType>::MinimumAreaBox2() : mNumPoints(0), mPoints(nullptr), mArea((InputType)0), mZero(0), mOne(1), mNegOne(-1), mHalf((InputType)0.5) { mSupportIndices = { { 0, 0, 0, 0 } }; } template <typename InputType, typename ComputeType> OrientedBox2<InputType> MinimumAreaBox2<InputType, ComputeType>::operator()( int numPoints, Vector2<InputType> const* points, bool useRotatingCalipers) { mNumPoints = numPoints; mPoints = points; mHull.clear(); // Get the convex hull of the points. ConvexHull2<InputType, ComputeType> ch2; ch2(mNumPoints, mPoints, (InputType)0); int dimension = ch2.GetDimension(); OrientedBox2<InputType> minBox; if (dimension == 0) { // The points are all effectively the same (using fuzzy epsilon). minBox.center = mPoints[0]; minBox.axis[0] = Vector2<InputType>::Unit(0); minBox.axis[1] = Vector2<InputType>::Unit(1); minBox.extent[0] = (InputType)0; minBox.extent[1] = (InputType)0; mHull.resize(1); mHull[0] = 0; return minBox; } if (dimension == 1) { // The points effectively lie on a line (using fuzzy epsilon). // Determine the extreme t-values for the points represented as // P = origin + t*direction. We know that 'origin' is an input // vertex, so we can start both t-extremes at zero. Line2<InputType> const& line = ch2.GetLine(); InputType tmin = (InputType)0, tmax = (InputType)0; int imin = 0, imax = 0; for (int i = 0; i < mNumPoints; ++i) { Vector2<InputType> diff = mPoints[i] - line.origin; InputType t = Dot(diff, line.direction); if (t > tmax) { tmax = t; imax = i; } else if (t < tmin) { tmin = t; imin = i; } } minBox.center = line.origin + ((InputType)0.5)*(tmin + tmax) * line.direction; minBox.extent[0] = ((InputType)0.5)*(tmax - tmin); minBox.extent[1] = (InputType)0; minBox.axis[0] = line.direction; minBox.axis[1] = -Perp(line.direction); mHull.resize(2); mHull[0] = imin; mHull[1] = imax; return minBox; } mHull = ch2.GetHull(); Vector2<ComputeType> const* queryPoints = ch2.GetQuery().GetVertices(); std::vector<Vector2<ComputeType>> computePoints(mHull.size()); for (size_t i = 0; i < mHull.size(); ++i) { computePoints[i] = queryPoints[mHull[i]]; } RemoveCollinearPoints(computePoints); Box box; if (useRotatingCalipers) { box = ComputeBoxForEdgeOrderN(computePoints); } else { box = ComputeBoxForEdgeOrderNSqr(computePoints); } ConvertTo(box, computePoints, minBox); return minBox; } template <typename InputType, typename ComputeType> OrientedBox2<InputType> MinimumAreaBox2<InputType, ComputeType>::operator()( int numPoints, Vector2<InputType> const* points, int numIndices, int const* indices, bool useRotatingCalipers) { mHull.clear(); OrientedBox2<InputType> minBox; if (numPoints < 3 || !points || (indices && numIndices < 3)) { minBox.center = Vector2<InputType>::Zero(); minBox.axis[0] = Vector2<InputType>::Unit(0); minBox.axis[1] = Vector2<InputType>::Unit(1); minBox.extent = Vector2<InputType>::Zero(); return minBox; } if (indices) { mHull.resize(numIndices); std::copy(indices, indices + numIndices, mHull.begin()); } else { numIndices = numPoints; mHull.resize(numIndices); for (int i = 0; i < numIndices; ++i) { mHull[i] = i; } } std::vector<Vector2<ComputeType>> computePoints(numIndices); for (int i = 0; i < numIndices; ++i) { int h = mHull[i]; computePoints[i][0] = (ComputeType)points[h][0]; computePoints[i][1] = (ComputeType)points[h][1]; } RemoveCollinearPoints(computePoints); Box box; if (useRotatingCalipers) { box = ComputeBoxForEdgeOrderN(computePoints); } else { box = ComputeBoxForEdgeOrderNSqr(computePoints); } ConvertTo(box, computePoints, minBox); return minBox; } template <typename InputType, typename ComputeType> inline int MinimumAreaBox2<InputType, ComputeType>::GetNumPoints() const { return mNumPoints; } template <typename InputType, typename ComputeType> inline Vector2<InputType> const* MinimumAreaBox2<InputType, ComputeType>::GetPoints() const { return mPoints; } template <typename InputType, typename ComputeType> inline std::vector<int> const& MinimumAreaBox2<InputType, ComputeType>::GetHull() const { return mHull; } template <typename InputType, typename ComputeType> inline std::array<int, 4> const& MinimumAreaBox2<InputType, ComputeType>::GetSupportIndices() const { return mSupportIndices; } template <typename InputType, typename ComputeType> inline InputType MinimumAreaBox2<InputType, ComputeType>::GetArea() const { return mArea; } template <typename InputType, typename ComputeType> void MinimumAreaBox2<InputType, ComputeType>::RemoveCollinearPoints( std::vector<Vector2<ComputeType>>& vertices) { std::vector<Vector2<ComputeType>> tmpVertices = vertices; int const numVertices = static_cast<int>(vertices.size()); int numNoncollinear = 0; Vector2<ComputeType> ePrev = tmpVertices[0] - tmpVertices.back(); for (int i0 = 0, i1 = 1; i0 < numVertices; ++i0) { Vector2<ComputeType> eNext = tmpVertices[i1] - tmpVertices[i0]; ComputeType dp = DotPerp(ePrev, eNext); if (dp != mZero) { vertices[numNoncollinear++] = tmpVertices[i0]; } ePrev = eNext; if (++i1 == numVertices) { i1 = 0; } } vertices.resize(numNoncollinear); } template <typename InputType, typename ComputeType> typename MinimumAreaBox2<InputType, ComputeType>::Box MinimumAreaBox2<InputType, ComputeType>::ComputeBoxForEdgeOrderNSqr( std::vector<Vector2<ComputeType>> const& vertices) { Box minBox; minBox.area = mNegOne; int const numIndices = static_cast<int>(vertices.size()); for (int i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { Box box = SmallestBox(i0, i1, vertices); if (minBox.area == mNegOne || box.area < minBox.area) { minBox = box; } } return minBox; } template <typename InputType, typename ComputeType> typename MinimumAreaBox2<InputType, ComputeType>::Box MinimumAreaBox2<InputType, ComputeType>::ComputeBoxForEdgeOrderN( std::vector<Vector2<ComputeType>> const& vertices) { // The inputs are assumed to be the vertices of a convex polygon that // is counterclockwise ordered. The input points must not contain three // consecutive collinear points. // When the bounding box corresponding to a polygon edge is computed, // we mark the edge as visited. If the edge is encountered later, the // algorithm terminates. std::vector<bool> visited(vertices.size()); std::fill(visited.begin(), visited.end(), false); // Start the minimum-area rectangle search with the edge from the last // polygon vertex to the first. When updating the extremes, we want the // bottom-most point on the left edge, the top-most point on the right // edge, the left-most point on the top edge, and the right-most point // on the bottom edge. The polygon edges starting at these points are // then guaranteed not to coincide with a box edge except when an extreme // point is shared by two box edges (at a corner). Box minBox = SmallestBox((int)vertices.size() - 1, 0, vertices); visited[minBox.index[0]] = true; // Execute the rotating calipers algorithm. Box box = minBox; for (size_t i = 0; i < vertices.size(); ++i) { std::array<std::pair<ComputeType, int>, 4> A; int numA; if (!ComputeAngles(vertices, box, A, numA)) { // The polygon is a rectangle, so the search is over. break; } // Indirectly sort the A-array. std::array<int, 4> sort = SortAngles(A, numA); // Update the supporting indices (box.index[]) and the box axis // directions (box.U[]). if (!UpdateSupport(A, numA, sort, vertices, visited, box)) { // We have already processed the box polygon edge, so the search // is over. break; } if (box.area < minBox.area) { minBox = box; } } return minBox; } template <typename InputType, typename ComputeType> typename MinimumAreaBox2<InputType, ComputeType>::Box MinimumAreaBox2<InputType, ComputeType>::SmallestBox(int i0, int i1, std::vector<Vector2<ComputeType>> const& vertices) { Box box; box.U[0] = vertices[i1] - vertices[i0]; box.U[1] = -Perp(box.U[0]); box.index = { { i1, i1, i1, i1 } }; box.sqrLenU0 = Dot(box.U[0], box.U[0]); Vector2<ComputeType> const& origin = vertices[i1]; Vector2<ComputeType> support[4]; for (int j = 0; j < 4; ++j) { support[j] = { mZero, mZero }; } int i = 0; for (auto const& vertex : vertices) { Vector2<ComputeType> diff = vertex - origin; Vector2<ComputeType> v = { Dot(box.U[0], diff), Dot(box.U[1], diff) }; // The right-most vertex of the bottom edge is vertices[i1]. The // assumption of no triple of collinear vertices guarantees that // box.index[0] is i1, which is the initial value assigned at the // beginning of this function. Therefore, there is no need to test // for other vertices farther to the right than vertices[i1]. if (v[0] > support[1][0] || (v[0] == support[1][0] && v[1] > support[1][1])) { // New right maximum OR same right maximum but closer to top. box.index[1] = i; support[1] = v; } if (v[1] > support[2][1] || (v[1] == support[2][1] && v[0] < support[2][0])) { // New top maximum OR same top maximum but closer to left. box.index[2] = i; support[2] = v; } if (v[0] < support[3][0] || (v[0] == support[3][0] && v[1] < support[3][1])) { // New left minimum OR same left minimum but closer to bottom. box.index[3] = i; support[3] = v; } ++i; } // The comment in the loop has the implication that support[0] = { 0, 0 }, // so the scaled height (support[2][1] - support[0][1]) is simply // support[2][1]. ComputeType scaledWidth = support[1][0] - support[3][0]; ComputeType scaledHeight = support[2][1]; box.area = scaledWidth * scaledHeight / box.sqrLenU0; return box; } template <typename InputType, typename ComputeType> bool MinimumAreaBox2<InputType, ComputeType>::ComputeAngles( std::vector<Vector2<ComputeType>> const& vertices, Box const& box, std::array<std::pair<ComputeType, int>, 4>& A, int& numA) const { int const numVertices = static_cast<int>(vertices.size()); numA = 0; for (int k0 = 3, k1 = 0; k1 < 4; k0 = k1++) { if (box.index[k0] != box.index[k1]) { // The box edges are ordered in k1 as U[0], U[1], -U[0], -U[1]. Vector2<ComputeType> D = ((k0 & 2) ? -box.U[k0 & 1] : box.U[k0 & 1]); int j0 = box.index[k0], j1 = j0 + 1; if (j1 == numVertices) { j1 = 0; } Vector2<ComputeType> E = vertices[j1] - vertices[j0]; ComputeType dp = DotPerp(D, E); ComputeType esqrlen = Dot(E, E); ComputeType sinThetaSqr = (dp * dp) / esqrlen; A[numA++] = std::make_pair(sinThetaSqr, k0); } } return numA > 0; } template <typename InputType, typename ComputeType> std::array<int, 4> MinimumAreaBox2<InputType, ComputeType>::SortAngles( std::array<std::pair<ComputeType, int>, 4> const& A, int numA) const { std::array<int, 4> sort = {{ 0, 1, 2, 3 }}; if (numA > 1) { if (numA == 2) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } } else if (numA == 3) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } else // numA == 4 { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[2]].first > A[sort[3]].first) { std::swap(sort[2], sort[3]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[3]].first) { std::swap(sort[1], sort[3]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } } return sort; } template <typename InputType, typename ComputeType> bool MinimumAreaBox2<InputType, ComputeType>::UpdateSupport( std::array<std::pair<ComputeType, int>, 4> const& A, int numA, std::array<int, 4> const& sort, std::vector<Vector2<ComputeType>> const& vertices, std::vector<bool>& visited, Box& box) { // Replace the support vertices of those edges attaining minimum angle // with the other endpoints of the edges. int const numVertices = static_cast<int>(vertices.size()); auto const& amin = A[sort[0]]; for (int k = 0; k < numA; ++k) { auto const& a = A[sort[k]]; if (a.first == amin.first) { if (++box.index[a.second] == numVertices) { box.index[a.second] = 0; } } else { break; } } int bottom = box.index[amin.second]; if (visited[bottom]) { // We have already processed this polygon edge. return false; } visited[bottom] = true; // Cycle the vertices so that the bottom support occurs first. std::array<int, 4> nextIndex; for (int k = 0; k < 4; ++k) { nextIndex[k] = box.index[(amin.second + k) % 4]; } box.index = nextIndex; // Compute the box axis directions. int j1 = box.index[0], j0 = j1 - 1; if (j0 < 0) { j0 = numVertices - 1; } box.U[0] = vertices[j1] - vertices[j0]; box.U[1] = -Perp(box.U[0]); box.sqrLenU0 = Dot(box.U[0], box.U[0]); // Compute the box area. Vector2<ComputeType> diff[2] = { vertices[box.index[1]] - vertices[box.index[3]], vertices[box.index[2]] - vertices[box.index[0]] }; box.area = Dot(box.U[0], diff[0]) * Dot(box.U[1], diff[1]) / box.sqrLenU0; return true; } template <typename InputType, typename ComputeType> void MinimumAreaBox2<InputType, ComputeType>::ConvertTo(Box const& minBox, std::vector<Vector2<ComputeType>> const& computePoints, OrientedBox2<InputType>& itMinBox) { // The sum, difference, and center are all computed exactly. Vector2<ComputeType> sum[2] = { computePoints[minBox.index[1]] + computePoints[minBox.index[3]], computePoints[minBox.index[2]] + computePoints[minBox.index[0]] }; Vector2<ComputeType> difference[2] = { computePoints[minBox.index[1]] - computePoints[minBox.index[3]], computePoints[minBox.index[2]] - computePoints[minBox.index[0]] }; Vector2<ComputeType> center = mHalf * ( Dot(minBox.U[0], sum[0]) * minBox.U[0] + Dot(minBox.U[1], sum[1]) * minBox.U[1]) / minBox.sqrLenU0; // Calculate the squared extent using ComputeType to avoid loss of // precision before computing a squared root. Vector2<ComputeType> sqrExtent; for (int i = 0; i < 2; ++i) { sqrExtent[i] = mHalf * Dot(minBox.U[i], difference[i]); sqrExtent[i] *= sqrExtent[i]; sqrExtent[i] /= minBox.sqrLenU0; } for (int i = 0; i < 2; ++i) { itMinBox.center[i] = (InputType)center[i]; itMinBox.extent[i] = std::sqrt((InputType)sqrExtent[i]); // Before converting to floating-point, factor out the maximum // component using ComputeType to generate rational numbers in a // range that avoids loss of precision during the conversion and // normalization. Vector2<ComputeType> const& axis = minBox.U[i]; ComputeType cmax = std::max(std::abs(axis[0]), std::abs(axis[1])); ComputeType invCMax = mOne / cmax; for (int j = 0; j < 2; ++j) { itMinBox.axis[i][j] = (InputType)(axis[j] * invCMax); } Normalize(itMinBox.axis[i]); } mSupportIndices = minBox.index; mArea = (InputType)minBox.area; } } // ---------------------------------------------- // GteMinimumVolumeBox3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) // Compute a minimum-volume oriented box containing the specified points. The // algorithm is really about computing the minimum-volume box containing the // convex hull of the points, so we must compute the convex hull or you must // pass an already built hull to the code. // // The minimum-volume oriented box has a face coincident with a hull face // or has three mutually orthogonal edges coincident with three hull edges // that (of course) are mutually orthogonal. // J.O'Rourke, "Finding minimal enclosing boxes", // Internat. J. Comput. Inform. Sci., 14:183-199, 1985. // // A detailed description of the algorithm and implementation is found in // the documents // http://www.geometrictools.com/Documentation/MinimumVolumeBox.pdf // http://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf // // NOTE: This algorithm guarantees a correct output only when ComputeType is // an exact arithmetic type that supports division. In GTEngine, one such // type is BSRational<UIntegerAP32> (arbitrary precision). Another such type // is BSRational<UIntegerFP32<N>> (fixed precision), where N is chosen large // enough for your input data sets. If you choose ComputeType to be 'float' // or 'double', the output is not guaranteed to be correct. // // See GeometricTools/GTEngine/Samples/Geometrics/MinimumVolumeBox3 for an // example of how to use the code. namespace gte { template <typename InputType, typename ComputeType> class MinimumVolumeBox3 { public: // The class is a functor to support computing the minimum-volume box of // multiple data sets using the same class object. For multithreading // in ProcessFaces, choose 'numThreads' subject to the constraints // 1 <= numThreads <= std::thread::hardware_concurrency() // To execute ProcessEdges in a thread separate from the main thrad, // choose 'threadProcessEdges' to 'true'. MinimumVolumeBox3(unsigned int numThreads = 1, bool threadProcessEdges = false); // The points are arbitrary, so we must compute the convex hull from // them in order to compute the minimum-area box. The input parameters // are necessary for using ConvexHull3. OrientedBox3<InputType> operator()(int numPoints, Vector3<InputType> const* points, FHEProgressCancel* Progress, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value); // The points form a nondegenerate convex polyhedron. The indices input // must be nonnull and specify the triangle faces. OrientedBox3<InputType> operator()(int numPoints, Vector3<InputType> const* points, int numIndices, int const* indices, FHEProgressCancel* Progress, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value); // Member access. inline int GetNumPoints() const; inline Vector3<InputType> const* GetPoints() const; inline std::vector<int> const& GetHull() const; inline InputType GetVolume() const; private: struct Box { Vector3<ComputeType> P, U[3]; ComputeType sqrLenU[3], range[3][2], volume; }; struct ExtrudeRectangle { Vector3<ComputeType> U[2]; std::array<int, 4> index; ComputeType sqrLenU[2], area; }; // Compute the minimum-volume box relative to each hull face. void ProcessFaces(ETManifoldMesh const& mesh, Box& minBox, FHEProgressCancel* Progress = nullptr); // Compute the minimum-volume box for each triple of orthgonal hull edges. void ProcessEdges(ETManifoldMesh const& mesh, Box& minBox); // Compute the minimum-volume box relative to a single hull face. typedef ETManifoldMesh::Triangle Triangle; void ProcessFace(std::shared_ptr<Triangle> const& supportTri, std::vector<Vector3<ComputeType>> const& normal, std::map<std::shared_ptr<Triangle>, int> const& triNormalMap, ETManifoldMesh::EMap const& emap, Box& localMinBox); // The rotating calipers algorithm has a loop invariant that requires // the convex polygon not to have collinear points. Any such points // must be removed first. The code is also executed for the O(n^2) // algorithm to reduce the number of process edges. void RemoveCollinearPoints(Vector3<ComputeType> const& N, std::vector<int>& polyline); // This is the slow order O(n^2) search. void ComputeBoxForFaceOrderNSqr(Vector3<ComputeType> const& N, std::vector<int> const& polyline, Box& box); // This is the rotating calipers version, which is O(n). void ComputeBoxForFaceOrderN(Vector3<ComputeType> const& N, std::vector<int> const& polyline, Box& box); // Compute the smallest rectangle for the polyline edge <V[i0],V[i1]>. ExtrudeRectangle SmallestRectangle(int i0, int i1, Vector3<ComputeType> const& N, std::vector<int> const& polyline); // Compute (sin(angle))^2 for the polyline edges emanating from the // support vertices of the rectangle. The return value is 'true' if at // least one angle is in [0,pi/2); otherwise, the return value is 'false' // and the original polyline must project to a rectangle. bool ComputeAngles(Vector3<ComputeType> const& N, std::vector<int> const& polyline, ExtrudeRectangle const& rct, std::array<std::pair<ComputeType, int>, 4>& A, int& numA) const; // Sort the angles indirectly. The sorted indices are returned. This // avoids swapping elements of A[], which can be expensive when // ComputeType is an exact rational type. std::array<int, 4> SortAngles(std::array<std::pair<ComputeType, int>, 4> const& A, int numA) const; bool UpdateSupport(std::array<std::pair<ComputeType, int>, 4> const& A, int numA, std::array<int, 4> const& sort, Vector3<ComputeType> const& N, std::vector<int> const& polyline, std::vector<bool>& visited, ExtrudeRectangle& rct); // Convert the extruded box to the minimum-volume box of InputType. When // the ComputeType is an exact rational type, the conversions are // performed to avoid precision loss until necessary at the last step. void ConvertTo(Box const& minBox, OrientedBox3<InputType>& itMinBox); // The code is multithreaded, both for convex hull computation and // computing minimum-volume extruded boxes for the hull faces. The // default value is 1, which implies a single-threaded computation (on // the main thread). unsigned int mNumThreads; bool mThreadProcessEdges; // The input points to be bound. int mNumPoints; Vector3<InputType> const* mPoints; // The ComputeType conversions of the input points. Only points of the // convex hull (vertices of a convex polyhedron) are converted for // performance when ComputeType is rational. Vector3<ComputeType> const* mComputePoints; // The indices into mPoints/mComputePoints for the convex hull vertices. std::vector<int> mHull; // The unique indices in mHull. This set allows us to compute only for // the hull vertices and avoids redundant computations if the indices // were to have repeated indices into mPoints/mComputePoints. This is // a performance improvement for rational ComputeType. std::set<int> mUniqueIndices; // The caller can specify whether to use rotating calipers or the slower // all-edge processing for computing an extruded bounding box. bool mUseRotatingCalipers; // The volume of the minimum-volume box. The ComputeType value is exact, // so the only rounding errors occur in the conversion from ComputeType // to InputType (default rounding mode is round-to-nearest-ties-to-even). InputType mVolume; // Convenient values that occur regularly in the code. When using // rational ComputeType, we construct these numbers only once. ComputeType mZero, mOne, mNegOne, mHalf; }; template <typename InputType, typename ComputeType> MinimumVolumeBox3<InputType, ComputeType>::MinimumVolumeBox3(unsigned int numThreads, bool threadProcessEdges) : mNumThreads(numThreads), mThreadProcessEdges(threadProcessEdges), mNumPoints(0), mPoints(nullptr), mComputePoints(nullptr), mUseRotatingCalipers(true), mVolume((InputType)0), mZero(0), mOne(1), mNegOne(-1), mHalf((InputType)0.5) { } template <typename InputType, typename ComputeType> OrientedBox3<InputType> MinimumVolumeBox3<InputType, ComputeType>::operator()( int numPoints, Vector3<InputType> const* points, FHEProgressCancel* Progress, bool useRotatingCalipers) { mNumPoints = numPoints; mPoints = points; mUseRotatingCalipers = useRotatingCalipers; mHull.clear(); mUniqueIndices.clear(); // Get the convex hull of the points. ConvexHull3<InputType, ComputeType> ch3; ch3(mNumPoints, mPoints, (InputType)0); int dimension = ch3.GetDimension(); OrientedBox3<InputType> itMinBox; if (dimension == 0) { // The points are all effectively the same (using fuzzy epsilon). itMinBox.center = mPoints[0]; itMinBox.axis[0] = Vector3<InputType>::Unit(0); itMinBox.axis[1] = Vector3<InputType>::Unit(1); itMinBox.axis[2] = Vector3<InputType>::Unit(2); itMinBox.extent[0] = (InputType)0; itMinBox.extent[1] = (InputType)0; itMinBox.extent[2] = (InputType)0; mHull.resize(1); mHull[0] = 0; return itMinBox; } if (dimension == 1) { // The points effectively lie on a line (using fuzzy epsilon). // Determine the extreme t-values for the points represented as // P = origin + t*direction. We know that 'origin' is an input // vertex, so we can start both t-extremes at zero. Line3<InputType> const& line = ch3.GetLine(); InputType tmin = (InputType)0, tmax = (InputType)0; int imin = 0, imax = 0; for (int i = 0; i < mNumPoints; ++i) { Vector3<InputType> diff = mPoints[i] - line.origin; InputType t = Dot(diff, line.direction); if (t > tmax) { tmax = t; imax = i; } else if (t < tmin) { tmin = t; imin = i; } } itMinBox.center = line.origin + ((InputType)0.5)*(tmin + tmax) * line.direction; itMinBox.extent[0] = ((InputType)0.5)*(tmax - tmin); itMinBox.extent[1] = (InputType)0; itMinBox.extent[2] = (InputType)0; itMinBox.axis[0] = line.direction; ComputeOrthogonalComplement(1, &itMinBox.axis[0]); mHull.resize(2); mHull[0] = imin; mHull[1] = imax; return itMinBox; } if (dimension == 2) { // The points effectively line on a plane (using fuzzy epsilon). // Project the points onto the plane and compute the minimum-area // bounding box of them. Plane3<InputType> const& plane = ch3.GetPlane(); // Get a coordinate system relative to the plane of the points. // Choose the origin to be any of the input points. Vector3<InputType> origin = mPoints[0]; Vector3<InputType> basis[3]; basis[0] = plane.normal; ComputeOrthogonalComplement(1, basis); // Project the input points onto the plane. std::vector<Vector2<InputType>> projection(mNumPoints); for (int i = 0; i < mNumPoints; ++i) { Vector3<InputType> diff = mPoints[i] - origin; projection[i][0] = Dot(basis[1], diff); projection[i][1] = Dot(basis[2], diff); } // Compute the minimum area box in 2D. MinimumAreaBox2<InputType, ComputeType> mab2; OrientedBox2<InputType> rectangle = mab2(mNumPoints, &projection[0]); // Lift the values into 3D. itMinBox.center = origin + rectangle.center[0] * basis[1] + rectangle.center[1] * basis[2]; itMinBox.axis[0] = rectangle.axis[0][0] * basis[1] + rectangle.axis[0][1] * basis[2]; itMinBox.axis[1] = rectangle.axis[1][0] * basis[1] + rectangle.axis[1][1] * basis[2]; itMinBox.axis[2] = basis[0]; itMinBox.extent[0] = rectangle.extent[0]; itMinBox.extent[1] = rectangle.extent[1]; itMinBox.extent[2] = (InputType)0; mHull = mab2.GetHull(); return itMinBox; } // Get the set of unique indices of the hull. This is used to project // hull vertices onto lines. ETManifoldMesh const& mesh = ch3.GetHullMesh(); mHull.resize(3 * mesh.GetTriangles().size()); int h = 0; for (auto const& element : mesh.GetTriangles()) { for (int i = 0; i < 3; ++i, ++h) { int index = element.first.V[i]; mHull[h] = index; mUniqueIndices.insert(index); } } mComputePoints = ch3.GetQuery().GetVertices(); Box minBox, minBoxEdges; minBox.volume = mNegOne; minBoxEdges.volume = mNegOne; if (mThreadProcessEdges) { std::thread doEdges([this, &mesh, &minBoxEdges]() { ProcessEdges(mesh, minBoxEdges); }); ProcessFaces(mesh, minBox); doEdges.join(); } else { ProcessEdges(mesh, minBoxEdges); ProcessFaces(mesh, minBox); } if (minBoxEdges.volume != mNegOne && minBoxEdges.volume < minBox.volume) { minBox = minBoxEdges; } ConvertTo(minBox, itMinBox); mComputePoints = nullptr; return itMinBox; } template <typename InputType, typename ComputeType> OrientedBox3<InputType> MinimumVolumeBox3<InputType, ComputeType>::operator()( int numPoints, Vector3<InputType> const* points, int numIndices, int const* indices, FHEProgressCancel* Progress, bool useRotatingCalipers) { mNumPoints = numPoints; mPoints = points; mUseRotatingCalipers = useRotatingCalipers; mUniqueIndices.clear(); // Build the mesh from the indices. The box construction uses the edge // map of the mesh. ETManifoldMesh mesh; int numTriangles = numIndices / 3; for (int t = 0; t < numTriangles; ++t) { int v0 = *indices++; int v1 = *indices++; int v2 = *indices++; mesh.Insert(v0, v1, v2); } // Get the set of unique indices of the hull. This is used to project // hull vertices onto lines. mHull.resize(3 * mesh.GetTriangles().size()); int h = 0; for (auto const& element : mesh.GetTriangles()) { for (int i = 0; i < 3; ++i, ++h) { int index = element.first.V[i]; mHull[h] = index; mUniqueIndices.insert(index); } } // Create the ComputeType points to be used downstream. std::vector<Vector3<ComputeType>> computePoints(mNumPoints); for (auto i : mUniqueIndices) { for (int j = 0; j < 3; ++j) { computePoints[i][j] = (ComputeType)mPoints[i][j]; } } OrientedBox3<InputType> itMinBox; mComputePoints = &computePoints[0]; Box minBox, minBoxEdges; minBox.volume = mNegOne; minBoxEdges.volume = mNegOne; if (mThreadProcessEdges) { std::thread doEdges([this, &mesh, &minBoxEdges]() { ProcessEdges(mesh, minBoxEdges); }); ProcessFaces(mesh, minBox); doEdges.join(); } else { ProcessEdges(mesh, minBoxEdges); ProcessFaces(mesh, minBox, Progress); if (Progress && Progress->Cancelled()) { return itMinBox; } } if (minBoxEdges.volume != mNegOne && minBoxEdges.volume < minBox.volume) { minBox = minBoxEdges; } ConvertTo(minBox, itMinBox); mComputePoints = nullptr; return itMinBox; } template <typename InputType, typename ComputeType> inline int MinimumVolumeBox3<InputType, ComputeType>::GetNumPoints() const { return mNumPoints; } template <typename InputType, typename ComputeType> inline Vector3<InputType> const* MinimumVolumeBox3<InputType, ComputeType>::GetPoints() const { return mPoints; } template <typename InputType, typename ComputeType> inline std::vector<int> const& MinimumVolumeBox3<InputType, ComputeType>::GetHull() const { return mHull; } template <typename InputType, typename ComputeType> inline InputType MinimumVolumeBox3<InputType, ComputeType>::GetVolume() const { return mVolume; } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ProcessFaces(ETManifoldMesh const& mesh, Box& minBox, FHEProgressCancel* Progress) { // Get the mesh data structures. auto const& tmap = mesh.GetTriangles(); auto const& emap = mesh.GetEdges(); // Compute inner-pointing face normals for searching boxes supported by // a face and an extreme vertex. The indirection in triNormalMap, using // an integer index instead of the normal/sqrlength pair itself, avoids // expensive copies when using exact arithmetic. std::vector<Vector3<ComputeType>> normal(tmap.size()); std::map<std::shared_ptr<Triangle>, int> triNormalMap; int index = 0; for (auto const& element : tmap) { auto tri = element.second; Vector3<ComputeType> const& v0 = mComputePoints[tri->V[0]]; Vector3<ComputeType> const& v1 = mComputePoints[tri->V[1]]; Vector3<ComputeType> const& v2 = mComputePoints[tri->V[2]]; Vector3<ComputeType> edge1 = v1 - v0; Vector3<ComputeType> edge2 = v2 - v0; normal[index] = Cross(edge2, edge1); // inner-pointing normal triNormalMap[tri] = index++; } // Process the triangle faces. For each face, compute the polyline of // edges that supports the bounding box with a face coincident to the // triangle face. The projection of the polyline onto the plane of the // triangle face is a convex polygon, so we can use the method of rotating // calipers to compute its minimum-area box efficiently. unsigned int numFaces = static_cast<unsigned int>(tmap.size()); if (mNumThreads > 1 && numFaces >= mNumThreads) { // Repackage the triangle pointers to support the partitioning of // faces for multithreaded face processing. std::vector<std::shared_ptr<Triangle>> triangles; triangles.reserve(numFaces); for (auto const& element : tmap) { triangles.push_back(element.second); } // Partition the data for multiple threads. unsigned int numFacesPerThread = numFaces / mNumThreads; std::vector<unsigned int> imin(mNumThreads), imax(mNumThreads); std::vector<Box> localMinBox(mNumThreads); for (unsigned int t = 0; t < mNumThreads; ++t) { imin[t] = t * numFacesPerThread; imax[t] = imin[t] + numFacesPerThread - 1; localMinBox[t].volume = mNegOne; } imax[mNumThreads - 1] = numFaces - 1; // Execute the face processing in multiple threads. std::vector<std::thread> process(mNumThreads); for (unsigned int t = 0; t < mNumThreads; ++t) { process[t] = std::thread([this, t, &imin, &imax, &triangles, &normal, &triNormalMap, &emap, &localMinBox]() { for (unsigned int i = imin[t]; i <= imax[t]; ++i) { auto const& supportTri = triangles[i]; ProcessFace(supportTri, normal, triNormalMap, emap, localMinBox[t]); } }); } // Wait for all threads to finish. for (unsigned int t = 0; t < mNumThreads; ++t) { process[t].join(); // Update the minimum-volume box candidate. if (minBox.volume == mNegOne || localMinBox[t].volume < minBox.volume) { minBox = localMinBox[t]; } } } else { for (auto const& element : tmap) { auto const& supportTri = element.second; ProcessFace(supportTri, normal, triNormalMap, emap, minBox); if (Progress && Progress->Cancelled()) { return; } } } } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ProcessEdges(ETManifoldMesh const& mesh, Box& minBox) { // The minimum-volume box can also be supported by three mutually // orthogonal edges of the convex hull. For each triple of orthogonal // edges, compute the minimum-volume box for that coordinate frame by // projecting the points onto the axes of the frame. Use a hull vertex // as the origin. int index = mesh.GetTriangles().begin()->first.V[0]; Vector3<ComputeType> const& origin = mComputePoints[index]; Vector3<ComputeType> U[3]; std::array<ComputeType, 3> sqrLenU; auto const& emap = mesh.GetEdges(); auto e2 = emap.begin(), end = emap.end(); for (/**/; e2 != end; ++e2) { U[2] = mComputePoints[e2->first.V[1]] - mComputePoints[e2->first.V[0]]; auto e1 = e2; for (++e1; e1 != end; ++e1) { U[1] = mComputePoints[e1->first.V[1]] - mComputePoints[e1->first.V[0]]; if (Dot(U[1], U[2]) != mZero) { continue; } sqrLenU[1] = Dot(U[1], U[1]); auto e0 = e1; for (++e0; e0 != end; ++e0) { U[0] = mComputePoints[e0->first.V[1]] - mComputePoints[e0->first.V[0]]; sqrLenU[0] = Dot(U[0], U[0]); if (Dot(U[0], U[1]) != mZero || Dot(U[0], U[2]) != mZero) { continue; } // The three edges are mutually orthogonal. To support exact // rational arithmetic for volume computation, we replace U[2] // by a parallel vector. U[2] = Cross(U[0], U[1]); sqrLenU[2] = sqrLenU[0] * sqrLenU[1]; // Project the vertices onto the lines containing the edges. // Use vertex 0 as the origin. std::array<ComputeType, 3> umin, umax; for (int j = 0; j < 3; ++j) { umin[j] = mZero; umax[j] = mZero; } for (auto i : mUniqueIndices) { Vector3<ComputeType> diff = mComputePoints[i] - origin; for (int j = 0; j < 3; ++j) { ComputeType dot = Dot(diff, U[j]); if (dot < umin[j]) { umin[j] = dot; } else if (dot > umax[j]) { umax[j] = dot; } } } ComputeType volume = (umax[0] - umin[0]) / sqrLenU[0]; volume *= (umax[1] - umin[1]) / sqrLenU[1]; volume *= (umax[2] - umin[2]); // Update current minimum-volume box (if necessary). if (minBox.volume == mOne || volume < minBox.volume) { // The edge keys have unordered vertices, so it is // possible that {U[0],U[1],U[2]} is a left-handed set. // We need a right-handed set. if (DotCross(U[0], U[1], U[2]) < mZero) { U[2] = -U[2]; } minBox.P = origin; for (int j = 0; j < 3; ++j) { minBox.U[j] = U[j]; minBox.sqrLenU[j] = sqrLenU[j]; for (int k = 0; k < 3; ++k) { minBox.range[k][0] = umin[k]; minBox.range[k][1] = umax[k]; } } minBox.volume = volume; } } } } } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ProcessFace(std::shared_ptr<Triangle> const& supportTri, std::vector<Vector3<ComputeType>> const& normal, std::map<std::shared_ptr<Triangle>, int> const& triNormalMap, ETManifoldMesh::EMap const& emap, Box& localMinBox) { // Get the supporting triangle information. auto foundSupport = triNormalMap.find(supportTri); if (foundSupport == triNormalMap.end()) return; Vector3<ComputeType> const& supportNormal = normal[foundSupport->second]; // Build the polyline of supporting edges. The pair (v,polyline[v]) // represents an edge directed appropriately (see next set of // comments). std::vector<int> polyline(mNumPoints); int polylineStart = -1; for (auto const& edgeElement : emap) { auto const& edge = *edgeElement.second; auto const& tri0 = edge.T[0].lock(); auto const& tri1 = edge.T[1].lock(); auto found0 = triNormalMap.find(tri0); if (found0 == triNormalMap.end()) return; auto found1 = triNormalMap.find(tri1); if (found1 == triNormalMap.end()) return; auto const& normal0 = normal[found0->second]; auto const& normal1 = normal[found1->second]; ComputeType dot0 = Dot(supportNormal, normal0); ComputeType dot1 = Dot(supportNormal, normal1); std::shared_ptr<Triangle> tri; if (dot0 < mZero && dot1 >= mZero) { tri = tri0; } else if (dot1 < mZero && dot0 >= mZero) { tri = tri1; } if (tri) { // The edge supports the bounding box. Insert the edge in the // list using clockwise order relative to tri. This will lead // to a polyline whose projection onto the plane of the hull // face is a convex polygon that is counterclockwise oriented. for (int j0 = 2, j1 = 0; j1 < 3; j0 = j1++) { if (tri->V[j1] == edge.V[0]) { if (tri->V[j0] == edge.V[1]) { polyline[edge.V[1]] = edge.V[0]; } else { polyline[edge.V[0]] = edge.V[1]; } polylineStart = edge.V[0]; break; } } } } if (polylineStart < 0) // abort if start search failed { return; } // Rearrange the edges to form a closed polyline. For M vertices, each // ComputeBoxFor*() function starts with the edge from closedPolyline[M-1] // to closedPolyline[0]. std::vector<int> closedPolyline(mNumPoints); int numClosedPolyline = 0; int v = polylineStart; for (auto& cp : closedPolyline) { cp = v; ++numClosedPolyline; v = polyline[v]; if (v == polylineStart) { break; } } closedPolyline.resize(numClosedPolyline); // This avoids redundant face testing in the O(n^2) or O(n) algorithms // and it simplifies the O(n) implementation. RemoveCollinearPoints(supportNormal, closedPolyline); if (closedPolyline.size() < 2) // abort if we no longer have a polygon { return; } // Compute the box coincident to the hull triangle that has minimum // area on the face coincident with the triangle. Box faceBox; if (mUseRotatingCalipers) { ComputeBoxForFaceOrderN(supportNormal, closedPolyline, faceBox); } else { ComputeBoxForFaceOrderNSqr(supportNormal, closedPolyline, faceBox); } // Update the minimum-volume box candidate. if (localMinBox.volume == mNegOne || faceBox.volume < localMinBox.volume) { localMinBox = faceBox; } } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::RemoveCollinearPoints( Vector3<ComputeType> const& N, std::vector<int>& polyline) { std::vector<int> tmpPolyline = polyline; int const numPolyline = static_cast<int>(polyline.size()); int numNoncollinear = 0; Vector3<ComputeType> ePrev = mComputePoints[tmpPolyline[0]] - mComputePoints[tmpPolyline.back()]; for (int i0 = 0, i1 = 1; i0 < numPolyline; ++i0) { Vector3<ComputeType> eNext = mComputePoints[tmpPolyline[i1]] - mComputePoints[tmpPolyline[i0]]; ComputeType tsp = DotCross(ePrev, eNext, N); if (tsp != mZero) { polyline[numNoncollinear++] = tmpPolyline[i0]; } ePrev = eNext; if (++i1 == numPolyline) { i1 = 0; } } polyline.resize(numNoncollinear); } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ComputeBoxForFaceOrderNSqr( Vector3<ComputeType> const& N, std::vector<int> const& polyline, Box& box) { // This code processes the polyline terminator associated with a convex // hull face of inner-pointing normal N. The polyline is usually not // contained by a plane, and projecting the polyline to a convex polygon // in a plane perpendicular to N introduces floating-point rounding // errors. The minimum-area box for the projected polyline is computed // indirectly to support exact rational arithmetic. box.P = mComputePoints[polyline[0]]; box.U[2] = N; box.sqrLenU[2] = Dot(N, N); box.range[1][0] = mZero; box.volume = mNegOne; int const numPolyline = static_cast<int>(polyline.size()); for (int i0 = numPolyline - 1, i1 = 0; i1 < numPolyline; i0 = i1++) { // Create a coordinate system for the plane perpendicular to the face // normal and containing a polyline vertex. Vector3<ComputeType> const& P = mComputePoints[polyline[i0]]; Vector3<ComputeType> E = mComputePoints[polyline[i1]] - mComputePoints[polyline[i0]]; Vector3<ComputeType> U1 = Cross(N, E); Vector3<ComputeType> U0 = Cross(U1, N); // Compute the smallest rectangle containing the projected polyline. ComputeType min0 = mZero, max0 = mZero, max1 = mZero; for (int j = 0; j < numPolyline; ++j) { Vector3<ComputeType> diff = mComputePoints[polyline[j]] - P; ComputeType dot = Dot(U0, diff); if (dot < min0) { min0 = dot; } else if (dot > max0) { max0 = dot; } dot = Dot(U1, diff); if (dot > max1) { max1 = dot; } } // The true area is Area(rectangle)*Length(N). After the smallest // scaled-area rectangle is computed and returned, the box.volume is // updated to be the actual squared volume of the box. ComputeType sqrLenU1 = Dot(U1, U1); ComputeType volume = (max0 - min0) * max1 / sqrLenU1; if (box.volume == mNegOne || volume < box.volume) { box.P = P; box.U[0] = U0; box.U[1] = U1; box.sqrLenU[0] = sqrLenU1 * box.sqrLenU[2]; box.sqrLenU[1] = sqrLenU1; box.range[0][0] = min0; box.range[0][1] = max0; box.range[1][1] = max1; box.volume = volume; } } // Compute the range of points in the support-normal direction. box.range[2][0] = mZero; box.range[2][1] = mZero; for (auto i : mUniqueIndices) { Vector3<ComputeType> diff = mComputePoints[i] - box.P; ComputeType height = Dot(box.U[2], diff); if (height < box.range[2][0]) { box.range[2][0] = height; } else if (height > box.range[2][1]) { box.range[2][1] = height; } } // Compute the actual volume. box.volume *= (box.range[2][1] - box.range[2][0]) / box.sqrLenU[2]; } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ComputeBoxForFaceOrderN( Vector3<ComputeType> const& N, std::vector<int> const& polyline, Box& box) { // This code processes the polyline terminator associated with a convex // hull face of inner-pointing normal N. The polyline is usually not // contained by a plane, and projecting the polyline to a convex polygon // in a plane perpendicular to N introduces floating-point rounding // errors. The minimum-area box for the projected polyline is computed // indirectly to support exact rational arithmetic. // When the bounding box corresponding to a polyline edge is computed, // we mark the edge as visited. If the edge is encountered later, the // algorithm terminates. std::vector<bool> visited(polyline.size()); std::fill(visited.begin(), visited.end(), false); // Start the minimum-area rectangle search with the edge from the last // polyline vertex to the first. When updating the extremes, we want the // bottom-most point on the left edge, the top-most point on the right // edge, the left-most point on the top edge, and the right-most point // on the bottom edge. The polygon edges starting at these points are // then guaranteed not to coincide with a box edge except when an extreme // point is shared by two box edges (at a corner). ExtrudeRectangle minRct = SmallestRectangle((int)polyline.size() - 1, 0, N, polyline); visited[minRct.index[0]] = true; // Execute the rotating calipers algorithm. ExtrudeRectangle rct = minRct; for (size_t i = 0; i < polyline.size(); ++i) { std::array<std::pair<ComputeType, int>, 4> A; int numA; if (!ComputeAngles(N, polyline, rct, A, numA)) { // The polyline projects to a rectangle, so the search is over. break; } // Indirectly sort the A-array. std::array<int, 4> sort = SortAngles(A, numA); // Update the supporting indices (rct.index[]) and the rectangle axis // directions (rct.U[]). if (!UpdateSupport(A, numA, sort, N, polyline, visited, rct)) { // We have already processed the rectangle polygon edge, so the // search is over. break; } if (rct.area < minRct.area) { minRct = rct; } } // Store relevant box information for computing volume and converting to // an InputType bounding box. box.P = mComputePoints[polyline[minRct.index[0]]]; box.U[0] = minRct.U[0]; box.U[1] = minRct.U[1]; box.U[2] = N; box.sqrLenU[0] = minRct.sqrLenU[0]; box.sqrLenU[1] = minRct.sqrLenU[1]; box.sqrLenU[2] = Dot(box.U[2], box.U[2]); // Compute the range of points in the plane perpendicular to the support // normal. box.range[0][0] = Dot(box.U[0], mComputePoints[polyline[minRct.index[3]]] - box.P); box.range[0][1] = Dot(box.U[0], mComputePoints[polyline[minRct.index[1]]] - box.P); box.range[1][0] = mZero; box.range[1][1] = Dot(box.U[1], mComputePoints[polyline[minRct.index[2]]] - box.P); // Compute the range of points in the support-normal direction. box.range[2][0] = mZero; box.range[2][1] = mZero; for (auto i : mUniqueIndices) { Vector3<ComputeType> diff = mComputePoints[i] - box.P; ComputeType height = Dot(box.U[2], diff); if (height < box.range[2][0]) { box.range[2][0] = height; } else if (height > box.range[2][1]) { box.range[2][1] = height; } } // Compute the actual volume. box.volume = (box.range[0][1] - box.range[0][0]) * ((box.range[1][1] - box.range[1][0]) / box.sqrLenU[1]) * ((box.range[2][1] - box.range[2][0]) / box.sqrLenU[2]); } template <typename InputType, typename ComputeType> typename MinimumVolumeBox3<InputType, ComputeType>::ExtrudeRectangle MinimumVolumeBox3<InputType, ComputeType>::SmallestRectangle(int i0, int i1, Vector3<ComputeType> const& N, std::vector<int> const& polyline) { ExtrudeRectangle rct; Vector3<ComputeType> E = mComputePoints[polyline[i1]] - mComputePoints[polyline[i0]]; rct.U[1] = Cross(N, E); rct.U[0] = Cross(rct.U[1], N); rct.index = { { i1, i1, i1, i1 } }; rct.sqrLenU[0] = Dot(rct.U[0], rct.U[0]); rct.sqrLenU[1] = Dot(rct.U[1], rct.U[1]); Vector3<ComputeType> const& origin = mComputePoints[polyline[i1]]; Vector2<ComputeType> support[4]; for (int j = 0; j < 4; ++j) { support[j] = { mZero, mZero }; } int i = 0; for (auto p : polyline) { Vector3<ComputeType> diff = mComputePoints[p] - origin; Vector2<ComputeType> v = { Dot(rct.U[0], diff), Dot(rct.U[1], diff) }; // The right-most vertex of the bottom edge is vertices[i1]. The // assumption of no triple of collinear vertices guarantees that // box.index[0] is i1, which is the initial value assigned at the // beginning of this function. Therefore, there is no need to test // for other vertices farther to the right than vertices[i1]. if (v[0] > support[1][0] || (v[0] == support[1][0] && v[1] > support[1][1])) { // New right maximum OR same right maximum but closer to top. rct.index[1] = i; support[1] = v; } if (v[1] > support[2][1] || (v[1] == support[2][1] && v[0] < support[2][0])) { // New top maximum OR same top maximum but closer to left. rct.index[2] = i; support[2] = v; } if (v[0] < support[3][0] || (v[0] == support[3][0] && v[1] < support[3][1])) { // New left minimum OR same left minimum but closer to bottom. rct.index[3] = i; support[3] = v; } ++i; } // The comment in the loop has the implication that support[0] = { 0, 0 }, // so the scaled height (support[2][1] - support[0][1]) is simply // support[2][1]. ComputeType scaledWidth = support[1][0] - support[3][0]; ComputeType scaledHeight = support[2][1]; rct.area = scaledWidth * scaledHeight / rct.sqrLenU[1]; return rct; } template <typename InputType, typename ComputeType> bool MinimumVolumeBox3<InputType, ComputeType>::ComputeAngles( Vector3<ComputeType> const& N, std::vector<int> const& polyline, ExtrudeRectangle const& rct, std::array<std::pair<ComputeType, int>, 4>& A, int& numA) const { int const numPolyline = static_cast<int>(polyline.size()); numA = 0; for (int k0 = 3, k1 = 0; k1 < 4; k0 = k1++) { if (rct.index[k0] != rct.index[k1]) { // The rct edges are ordered in k1 as U[0], U[1], -U[0], -U[1]. int lookup = (k0 & 1); Vector3<ComputeType> D = ((k0 & 2) ? -rct.U[lookup] : rct.U[lookup]); int j0 = rct.index[k0], j1 = j0 + 1; if (j1 == numPolyline) { j1 = 0; } Vector3<ComputeType> E = mComputePoints[polyline[j1]] - mComputePoints[polyline[j0]]; Vector3<ComputeType> Eperp = Cross(N, E); E = Cross(Eperp, N); Vector3<ComputeType> DxE = Cross(D, E); ComputeType csqrlen = Dot(DxE, DxE); ComputeType dsqrlen = rct.sqrLenU[lookup]; ComputeType esqrlen = Dot(E, E); ComputeType sinThetaSqr = csqrlen / (dsqrlen * esqrlen); A[numA++] = std::make_pair(sinThetaSqr, k0); } } return numA > 0; } template <typename InputType, typename ComputeType> std::array<int, 4> MinimumVolumeBox3<InputType, ComputeType>::SortAngles( std::array<std::pair<ComputeType, int>, 4> const& A, int numA) const { std::array<int, 4> sort = {{ 0, 1, 2, 3 }}; if (numA > 1) { if (numA == 2) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } } else if (numA == 3) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } else // numA == 4 { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[2]].first > A[sort[3]].first) { std::swap(sort[2], sort[3]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[3]].first) { std::swap(sort[1], sort[3]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } } return sort; } template <typename InputType, typename ComputeType> bool MinimumVolumeBox3<InputType, ComputeType>::UpdateSupport( std::array<std::pair<ComputeType, int>, 4> const& A, int numA, std::array<int, 4> const& sort, Vector3<ComputeType> const& N, std::vector<int> const& polyline, std::vector<bool>& visited, ExtrudeRectangle& rct) { // Replace the support vertices of those edges attaining minimum angle // with the other endpoints of the edges. int const numPolyline = static_cast<int>(polyline.size()); auto const& amin = A[sort[0]]; for (int k = 0; k < numA; ++k) { auto const& a = A[sort[k]]; if (a.first == amin.first) { if (++rct.index[a.second] == numPolyline) { rct.index[a.second] = 0; } } else { break; } } int bottom = rct.index[amin.second]; if (visited[bottom]) { // We have already processed this polyline edge. return false; } visited[bottom] = true; // Cycle the vertices so that the bottom support occurs first. std::array<int, 4> nextIndex; for (int k = 0; k < 4; ++k) { nextIndex[k] = rct.index[(amin.second + k) % 4]; } rct.index = nextIndex; // Compute the rectangle axis directions. int j1 = rct.index[0], j0 = j1 - 1; if (j1 < 0) { j1 = numPolyline - 1; } Vector3<ComputeType> E = mComputePoints[polyline[j1]] - mComputePoints[polyline[j0]]; rct.U[1] = Cross(N, E); rct.U[0] = Cross(rct.U[1], N); rct.sqrLenU[0] = Dot(rct.U[0], rct.U[0]); rct.sqrLenU[1] = Dot(rct.U[1], rct.U[1]); // Compute the rectangle area. Vector3<ComputeType> diff[2] = { mComputePoints[polyline[rct.index[1]]] - mComputePoints[polyline[rct.index[3]]], mComputePoints[polyline[rct.index[2]]] - mComputePoints[polyline[rct.index[0]]] }; ComputeType scaledWidth = Dot(rct.U[0], diff[0]); ComputeType scaledHeight = Dot(rct.U[1], diff[1]); rct.area = scaledWidth * scaledHeight / rct.sqrLenU[1]; return true; } template <typename InputType, typename ComputeType> void MinimumVolumeBox3<InputType, ComputeType>::ConvertTo(Box const& minBox, OrientedBox3<InputType>& itMinBox) { Vector3<ComputeType> center = minBox.P; for (int i = 0; i < 3; ++i) { ComputeType average = mHalf * (minBox.range[i][0] + minBox.range[i][1]); center += (average / minBox.sqrLenU[i]) * minBox.U[i]; } // Calculate the squared extent using ComputeType to avoid loss of // precision before computing a squared root. Vector3<ComputeType> sqrExtent; for (int i = 0; i < 3; ++i) { sqrExtent[i] = mHalf * (minBox.range[i][1] - minBox.range[i][0]); sqrExtent[i] *= sqrExtent[i]; sqrExtent[i] /= minBox.sqrLenU[i]; } for (int i = 0; i < 3; ++i) { itMinBox.center[i] = (InputType)center[i]; itMinBox.extent[i] = std::sqrt((InputType)sqrExtent[i]); // Before converting to floating-point, factor out the maximum // component using ComputeType to generate rational numbers in a // range that avoids loss of precision during the conversion and // normalization. Vector3<ComputeType> const& axis = minBox.U[i]; ComputeType cmax = std::max(std::abs(axis[0]), std::abs(axis[1])); cmax = std::max(cmax, std::abs(axis[2])); ComputeType invCMax = mOne / cmax; for (int j = 0; j < 3; ++j) { itMinBox.axis[i][j] = (InputType)(axis[j] * invCMax); } Normalize(itMinBox.axis[i]); } mVolume = (InputType)minBox.volume; } } // ---------------------------------------------- // GteMath.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.17.1 (2019/01/17) // This file extends the <cmath> support to include convenient constants and // functions. The shared constants for CPU, Intel SSE and GPU lead to // correctly rounded approximations of the constants when using 'float' or // 'double'. The file also includes a type trait, is_arbitrary_precision, // to support selecting between floating-point arithmetic (float, double, //long double) or arbitrary-precision arithmetic (BSNumber<T>, BSRational<T>) // in an implementation using std::enable_if. There is also a type trait, // has_division_operator, to support selecting between numeric types that // have a division operator (BSRational<T>) and those that do not have a // division operator (BSNumber<T>). // Maximum number of iterations for bisection before a subinterval // degenerates to a single point. TODO: Verify these. I used the formula: // 3 + std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent. // IEEEBinary16: digits = 11, min_exponent = -13 // float: digits = 27, min_exponent = -125 // double: digits = 53, min_exponent = -1021 // BSNumber and BSRational use std::numeric_limits<unsigned int>::max(), // but maybe these should be set to a large number or be user configurable. // The MAX_BISECTIONS_GENERIC is an arbitrary choice for now and is used // in template code where Real is the template parameter. #define GTE_C_MAX_BISECTIONS_FLOAT16 27u #define GTE_C_MAX_BISECTIONS_FLOAT32 155u #define GTE_C_MAX_BISECTIONS_FLOAT64 1077u #define GTE_C_MAX_BISECTIONS_BSNUMBER 0xFFFFFFFFu #define GTE_C_MAX_BISECTIONS_BSRATIONAL 0xFFFFFFFFu #define GTE_C_MAX_BISECTIONS_GENERIC 2048u // Constants involving pi. #define GTE_C_PI 3.1415926535897931 #define GTE_C_HALF_PI 1.5707963267948966 #define GTE_C_QUARTER_PI 0.7853981633974483 #define GTE_C_TWO_PI 6.2831853071795862 #define GTE_C_INV_PI 0.3183098861837907 #define GTE_C_INV_TWO_PI 0.1591549430918953 #define GTE_C_INV_HALF_PI 0.6366197723675813 // Conversions between degrees and radians. #define GTE_C_DEG_TO_RAD 0.0174532925199433 #define GTE_C_RAD_TO_DEG 57.295779513082321 // Common constants. #define GTE_C_SQRT_2 1.4142135623730951 #define GTE_C_INV_SQRT_2 0.7071067811865475 #define GTE_C_LN_2 0.6931471805599453 #define GTE_C_INV_LN_2 1.4426950408889634 #define GTE_C_LN_10 2.3025850929940459 #define GTE_C_INV_LN_10 0.43429448190325176 // Constants for minimax polynomial approximations to sqrt(x). // The algorithm minimizes the maximum absolute error on [1,2]. #define GTE_C_SQRT_DEG1_C0 +1.0 #define GTE_C_SQRT_DEG1_C1 +4.1421356237309505e-01 #define GTE_C_SQRT_DEG1_MAX_ERROR 1.7766952966368793e-2 #define GTE_C_SQRT_DEG2_C0 +1.0 #define GTE_C_SQRT_DEG2_C1 +4.8563183076125260e-01 #define GTE_C_SQRT_DEG2_C2 -7.1418268388157458e-02 #define GTE_C_SQRT_DEG2_MAX_ERROR 1.1795695163108744e-3 #define GTE_C_SQRT_DEG3_C0 +1.0 #define GTE_C_SQRT_DEG3_C1 +4.9750045320242231e-01 #define GTE_C_SQRT_DEG3_C2 -1.0787308044477850e-01 #define GTE_C_SQRT_DEG3_C3 +2.4586189615451115e-02 #define GTE_C_SQRT_DEG3_MAX_ERROR 1.1309620116468910e-4 #define GTE_C_SQRT_DEG4_C0 +1.0 #define GTE_C_SQRT_DEG4_C1 +4.9955939832918816e-01 #define GTE_C_SQRT_DEG4_C2 -1.2024066151943025e-01 #define GTE_C_SQRT_DEG4_C3 +4.5461507257698486e-02 #define GTE_C_SQRT_DEG4_C4 -1.0566681694362146e-02 #define GTE_C_SQRT_DEG4_MAX_ERROR 1.2741170151556180e-5 #define GTE_C_SQRT_DEG5_C0 +1.0 #define GTE_C_SQRT_DEG5_C1 +4.9992197660031912e-01 #define GTE_C_SQRT_DEG5_C2 -1.2378506719245053e-01 #define GTE_C_SQRT_DEG5_C3 +5.6122776972699739e-02 #define GTE_C_SQRT_DEG5_C4 -2.3128836281145482e-02 #define GTE_C_SQRT_DEG5_C5 +5.0827122737047148e-03 #define GTE_C_SQRT_DEG5_MAX_ERROR 1.5725568940708201e-6 #define GTE_C_SQRT_DEG6_C0 +1.0 #define GTE_C_SQRT_DEG6_C1 +4.9998616695784914e-01 #define GTE_C_SQRT_DEG6_C2 -1.2470733323278438e-01 #define GTE_C_SQRT_DEG6_C3 +6.0388587356982271e-02 #define GTE_C_SQRT_DEG6_C4 -3.1692053551807930e-02 #define GTE_C_SQRT_DEG6_C5 +1.2856590305148075e-02 #define GTE_C_SQRT_DEG6_C6 -2.6183954624343642e-03 #define GTE_C_SQRT_DEG6_MAX_ERROR 2.0584155535630089e-7 #define GTE_C_SQRT_DEG7_C0 +1.0 #define GTE_C_SQRT_DEG7_C1 +4.9999754817809228e-01 #define GTE_C_SQRT_DEG7_C2 -1.2493243476353655e-01 #define GTE_C_SQRT_DEG7_C3 +6.1859954146370910e-02 #define GTE_C_SQRT_DEG7_C4 -3.6091595023208356e-02 #define GTE_C_SQRT_DEG7_C5 +1.9483946523450868e-02 #define GTE_C_SQRT_DEG7_C6 -7.5166134568007692e-03 #define GTE_C_SQRT_DEG7_C7 +1.4127567687864939e-03 #define GTE_C_SQRT_DEG7_MAX_ERROR 2.8072302919734948e-8 #define GTE_C_SQRT_DEG8_C0 +1.0 #define GTE_C_SQRT_DEG8_C1 +4.9999956583056759e-01 #define GTE_C_SQRT_DEG8_C2 -1.2498490369914350e-01 #define GTE_C_SQRT_DEG8_C3 +6.2318494667579216e-02 #define GTE_C_SQRT_DEG8_C4 -3.7982961896432244e-02 #define GTE_C_SQRT_DEG8_C5 +2.3642612312869460e-02 #define GTE_C_SQRT_DEG8_C6 -1.2529377587270574e-02 #define GTE_C_SQRT_DEG8_C7 +4.5382426960713929e-03 #define GTE_C_SQRT_DEG8_C8 -7.8810995273670414e-04 #define GTE_C_SQRT_DEG8_MAX_ERROR 3.9460605685825989e-9 // Constants for minimax polynomial approximations to 1/sqrt(x). // The algorithm minimizes the maximum absolute error on [1,2]. #define GTE_C_INVSQRT_DEG1_C0 +1.0 #define GTE_C_INVSQRT_DEG1_C1 -2.9289321881345254e-01 #define GTE_C_INVSQRT_DEG1_MAX_ERROR 3.7814314552701983e-2 #define GTE_C_INVSQRT_DEG2_C0 +1.0 #define GTE_C_INVSQRT_DEG2_C1 -4.4539812104566801e-01 #define GTE_C_INVSQRT_DEG2_C2 +1.5250490223221547e-01 #define GTE_C_INVSQRT_DEG2_MAX_ERROR 4.1953446330581234e-3 #define GTE_C_INVSQRT_DEG3_C0 +1.0 #define GTE_C_INVSQRT_DEG3_C1 -4.8703230993068791e-01 #define GTE_C_INVSQRT_DEG3_C2 +2.8163710486669835e-01 #define GTE_C_INVSQRT_DEG3_C3 -8.7498013749463421e-02 #define GTE_C_INVSQRT_DEG3_MAX_ERROR 5.6307702007266786e-4 #define GTE_C_INVSQRT_DEG4_C0 +1.0 #define GTE_C_INVSQRT_DEG4_C1 -4.9710061558048779e-01 #define GTE_C_INVSQRT_DEG4_C2 +3.4266247597676802e-01 #define GTE_C_INVSQRT_DEG4_C3 -1.9106356536293490e-01 #define GTE_C_INVSQRT_DEG4_C4 +5.2608486153198797e-02 #define GTE_C_INVSQRT_DEG4_MAX_ERROR 8.1513919987605266e-5 #define GTE_C_INVSQRT_DEG5_C0 +1.0 #define GTE_C_INVSQRT_DEG5_C1 -4.9937760586004143e-01 #define GTE_C_INVSQRT_DEG5_C2 +3.6508741295133973e-01 #define GTE_C_INVSQRT_DEG5_C3 -2.5884890281853501e-01 #define GTE_C_INVSQRT_DEG5_C4 +1.3275782221320753e-01 #define GTE_C_INVSQRT_DEG5_C5 -3.2511945299404488e-02 #define GTE_C_INVSQRT_DEG5_MAX_ERROR 1.2289367475583346e-5 #define GTE_C_INVSQRT_DEG6_C0 +1.0 #define GTE_C_INVSQRT_DEG6_C1 -4.9987029229547453e-01 #define GTE_C_INVSQRT_DEG6_C2 +3.7220923604495226e-01 #define GTE_C_INVSQRT_DEG6_C3 -2.9193067713256937e-01 #define GTE_C_INVSQRT_DEG6_C4 +1.9937605991094642e-01 #define GTE_C_INVSQRT_DEG6_C5 -9.3135712130901993e-02 #define GTE_C_INVSQRT_DEG6_C6 +2.0458166789566690e-02 #define GTE_C_INVSQRT_DEG6_MAX_ERROR 1.9001451223750465e-6 #define GTE_C_INVSQRT_DEG7_C0 +1.0 #define GTE_C_INVSQRT_DEG7_C1 -4.9997357250704977e-01 #define GTE_C_INVSQRT_DEG7_C2 +3.7426216884998809e-01 #define GTE_C_INVSQRT_DEG7_C3 -3.0539882498248971e-01 #define GTE_C_INVSQRT_DEG7_C4 +2.3976005607005391e-01 #define GTE_C_INVSQRT_DEG7_C5 -1.5410326351684489e-01 #define GTE_C_INVSQRT_DEG7_C6 +6.5598809723041995e-02 #define GTE_C_INVSQRT_DEG7_C7 -1.3038592450470787e-02 #define GTE_C_INVSQRT_DEG7_MAX_ERROR 2.9887724993168940e-7 #define GTE_C_INVSQRT_DEG8_C0 +1.0 #define GTE_C_INVSQRT_DEG8_C1 -4.9999471066120371e-01 #define GTE_C_INVSQRT_DEG8_C2 +3.7481415745794067e-01 #define GTE_C_INVSQRT_DEG8_C3 -3.1023804387422160e-01 #define GTE_C_INVSQRT_DEG8_C4 +2.5977002682930106e-01 #define GTE_C_INVSQRT_DEG8_C5 -1.9818790717727097e-01 #define GTE_C_INVSQRT_DEG8_C6 +1.1882414252613671e-01 #define GTE_C_INVSQRT_DEG8_C7 -4.6270038088550791e-02 #define GTE_C_INVSQRT_DEG8_C8 +8.3891541755747312e-03 #define GTE_C_INVSQRT_DEG8_MAX_ERROR 4.7596926146947771e-8 // Constants for minimax polynomial approximations to sin(x). // The algorithm minimizes the maximum absolute error on [-pi/2,pi/2]. #define GTE_C_SIN_DEG3_C0 +1.0 #define GTE_C_SIN_DEG3_C1 -1.4727245910375519e-01 #define GTE_C_SIN_DEG3_MAX_ERROR 1.3481903639145865e-2 #define GTE_C_SIN_DEG5_C0 +1.0 #define GTE_C_SIN_DEG5_C1 -1.6600599923812209e-01 #define GTE_C_SIN_DEG5_C2 +7.5924178409012000e-03 #define GTE_C_SIN_DEG5_MAX_ERROR 1.4001209384639779e-4 #define GTE_C_SIN_DEG7_C0 +1.0 #define GTE_C_SIN_DEG7_C1 -1.6665578084732124e-01 #define GTE_C_SIN_DEG7_C2 +8.3109378830028557e-03 #define GTE_C_SIN_DEG7_C3 -1.8447486103462252e-04 #define GTE_C_SIN_DEG7_MAX_ERROR 1.0205878936686563e-6 #define GTE_C_SIN_DEG9_C0 +1.0 #define GTE_C_SIN_DEG9_C1 -1.6666656235308897e-01 #define GTE_C_SIN_DEG9_C2 +8.3329962509886002e-03 #define GTE_C_SIN_DEG9_C3 -1.9805100675274190e-04 #define GTE_C_SIN_DEG9_C4 +2.5967200279475300e-06 #define GTE_C_SIN_DEG9_MAX_ERROR 5.2010746265374053e-9 #define GTE_C_SIN_DEG11_C0 +1.0 #define GTE_C_SIN_DEG11_C1 -1.6666666601721269e-01 #define GTE_C_SIN_DEG11_C2 +8.3333303183525942e-03 #define GTE_C_SIN_DEG11_C3 -1.9840782426250314e-04 #define GTE_C_SIN_DEG11_C4 +2.7521557770526783e-06 #define GTE_C_SIN_DEG11_C5 -2.3828544692960918e-08 #define GTE_C_SIN_DEG11_MAX_ERROR 1.9295870457014530e-11 // Constants for minimax polynomial approximations to cos(x). // The algorithm minimizes the maximum absolute error on [-pi/2,pi/2]. #define GTE_C_COS_DEG2_C0 +1.0 #define GTE_C_COS_DEG2_C1 -4.0528473456935105e-01 #define GTE_C_COS_DEG2_MAX_ERROR 5.4870946878404048e-2 #define GTE_C_COS_DEG4_C0 +1.0 #define GTE_C_COS_DEG4_C1 -4.9607181958647262e-01 #define GTE_C_COS_DEG4_C2 +3.6794619653489236e-02 #define GTE_C_COS_DEG4_MAX_ERROR 9.1879932449712154e-4 #define GTE_C_COS_DEG6_C0 +1.0 #define GTE_C_COS_DEG6_C1 -4.9992746217057404e-01 #define GTE_C_COS_DEG6_C2 +4.1493920348353308e-02 #define GTE_C_COS_DEG6_C3 -1.2712435011987822e-03 #define GTE_C_COS_DEG6_MAX_ERROR 9.2028470133065365e-6 #define GTE_C_COS_DEG8_C0 +1.0 #define GTE_C_COS_DEG8_C1 -4.9999925121358291e-01 #define GTE_C_COS_DEG8_C2 +4.1663780117805693e-02 #define GTE_C_COS_DEG8_C3 -1.3854239405310942e-03 #define GTE_C_COS_DEG8_C4 +2.3154171575501259e-05 #define GTE_C_COS_DEG8_MAX_ERROR 5.9804533020235695e-8 #define GTE_C_COS_DEG10_C0 +1.0 #define GTE_C_COS_DEG10_C1 -4.9999999508695869e-01 #define GTE_C_COS_DEG10_C2 +4.1666638865338612e-02 #define GTE_C_COS_DEG10_C3 -1.3888377661039897e-03 #define GTE_C_COS_DEG10_C4 +2.4760495088926859e-05 #define GTE_C_COS_DEG10_C5 -2.6051615464872668e-07 #define GTE_C_COS_DEG10_MAX_ERROR 2.7006769043325107e-10 // Constants for minimax polynomial approximations to tan(x). // The algorithm minimizes the maximum absolute error on [-pi/4,pi/4]. #define GTE_C_TAN_DEG3_C0 1.0 #define GTE_C_TAN_DEG3_C1 4.4295926544736286e-01 #define GTE_C_TAN_DEG3_MAX_ERROR 1.1661892256204731e-2 #define GTE_C_TAN_DEG5_C0 1.0 #define GTE_C_TAN_DEG5_C1 3.1401320403542421e-01 #define GTE_C_TAN_DEG5_C2 2.0903948109240345e-01 #define GTE_C_TAN_DEG5_MAX_ERROR 5.8431854390143118e-4 #define GTE_C_TAN_DEG7_C0 1.0 #define GTE_C_TAN_DEG7_C1 3.3607213284422555e-01 #define GTE_C_TAN_DEG7_C2 1.1261037305184907e-01 #define GTE_C_TAN_DEG7_C3 9.8352099470524479e-02 #define GTE_C_TAN_DEG7_MAX_ERROR 3.5418688397723108e-5 #define GTE_C_TAN_DEG9_C0 1.0 #define GTE_C_TAN_DEG9_C1 3.3299232843941784e-01 #define GTE_C_TAN_DEG9_C2 1.3747843432474838e-01 #define GTE_C_TAN_DEG9_C3 3.7696344813028304e-02 #define GTE_C_TAN_DEG9_C4 4.6097377279281204e-02 #define GTE_C_TAN_DEG9_MAX_ERROR 2.2988173242199927e-6 #define GTE_C_TAN_DEG11_C0 1.0 #define GTE_C_TAN_DEG11_C1 3.3337224456224224e-01 #define GTE_C_TAN_DEG11_C2 1.3264516053824593e-01 #define GTE_C_TAN_DEG11_C3 5.8145237645931047e-02 #define GTE_C_TAN_DEG11_C4 1.0732193237572574e-02 #define GTE_C_TAN_DEG11_C5 2.1558456793513869e-02 #define GTE_C_TAN_DEG11_MAX_ERROR 1.5426257940140409e-7 #define GTE_C_TAN_DEG13_C0 1.0 #define GTE_C_TAN_DEG13_C1 3.3332916426394554e-01 #define GTE_C_TAN_DEG13_C2 1.3343404625112498e-01 #define GTE_C_TAN_DEG13_C3 5.3104565343119248e-02 #define GTE_C_TAN_DEG13_C4 2.5355038312682154e-02 #define GTE_C_TAN_DEG13_C5 1.8253255966556026e-03 #define GTE_C_TAN_DEG13_C6 1.0069407176615641e-02 #define GTE_C_TAN_DEG13_MAX_ERROR 1.0550264249037378e-8 // Constants for minimax polynomial approximations to acos(x), where the // approximation is of the form acos(x) = sqrt(1 - x)*p(x) with p(x) a // polynomial. The algorithm minimizes the maximum error // |acos(x)/sqrt(1-x) - p(x)| on [0,1]. At the same time we get an // approximation for asin(x) = pi/2 - acos(x). #define GTE_C_ACOS_DEG1_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG1_C1 -1.5658276442180141e-01 #define GTE_C_ACOS_DEG1_MAX_ERROR 1.1659002803738105e-2 #define GTE_C_ACOS_DEG2_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG2_C1 -2.0347053865798365e-01 #define GTE_C_ACOS_DEG2_C2 +4.6887774236182234e-02 #define GTE_C_ACOS_DEG2_MAX_ERROR 9.0311602490029258e-4 #define GTE_C_ACOS_DEG3_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG3_C1 -2.1253291899190285e-01 #define GTE_C_ACOS_DEG3_C2 +7.4773789639484223e-02 #define GTE_C_ACOS_DEG3_C3 -1.8823635069382449e-02 #define GTE_C_ACOS_DEG3_MAX_ERROR 9.3066396954288172e-5 #define GTE_C_ACOS_DEG4_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG4_C1 -2.1422258835275865e-01 #define GTE_C_ACOS_DEG4_C2 +8.4936675142844198e-02 #define GTE_C_ACOS_DEG4_C3 -3.5991475120957794e-02 #define GTE_C_ACOS_DEG4_C4 +8.6946239090712751e-03 #define GTE_C_ACOS_DEG4_MAX_ERROR 1.0930595804481413e-5 #define GTE_C_ACOS_DEG5_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG5_C1 -2.1453292139805524e-01 #define GTE_C_ACOS_DEG5_C2 +8.7973089282889383e-02 #define GTE_C_ACOS_DEG5_C3 -4.5130266382166440e-02 #define GTE_C_ACOS_DEG5_C4 +1.9467466687281387e-02 #define GTE_C_ACOS_DEG5_C5 -4.3601326117634898e-03 #define GTE_C_ACOS_DEG5_MAX_ERROR 1.3861070257241426-6 #define GTE_C_ACOS_DEG6_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG6_C1 -2.1458939285677325e-01 #define GTE_C_ACOS_DEG6_C2 +8.8784960563641491e-02 #define GTE_C_ACOS_DEG6_C3 -4.8887131453156485e-02 #define GTE_C_ACOS_DEG6_C4 +2.7011519960012720e-02 #define GTE_C_ACOS_DEG6_C5 -1.1210537323478320e-02 #define GTE_C_ACOS_DEG6_C6 +2.3078166879102469e-03 #define GTE_C_ACOS_DEG6_MAX_ERROR 1.8491291330427484e-7 #define GTE_C_ACOS_DEG7_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG7_C1 -2.1459960076929829e-01 #define GTE_C_ACOS_DEG7_C2 +8.8986946573346160e-02 #define GTE_C_ACOS_DEG7_C3 -5.0207843052845647e-02 #define GTE_C_ACOS_DEG7_C4 +3.0961594977611639e-02 #define GTE_C_ACOS_DEG7_C5 -1.7162031184398074e-02 #define GTE_C_ACOS_DEG7_C6 +6.7072304676685235e-03 #define GTE_C_ACOS_DEG7_C7 -1.2690614339589956e-03 #define GTE_C_ACOS_DEG7_MAX_ERROR 2.5574620927948377e-8 #define GTE_C_ACOS_DEG8_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG8_C1 -2.1460143648688035e-01 #define GTE_C_ACOS_DEG8_C2 +8.9034700107934128e-02 #define GTE_C_ACOS_DEG8_C3 -5.0625279962389413e-02 #define GTE_C_ACOS_DEG8_C4 +3.2683762943179318e-02 #define GTE_C_ACOS_DEG8_C5 -2.0949278766238422e-02 #define GTE_C_ACOS_DEG8_C6 +1.1272900916992512e-02 #define GTE_C_ACOS_DEG8_C7 -4.1160981058965262e-03 #define GTE_C_ACOS_DEG8_C8 +7.1796493341480527e-04 #define GTE_C_ACOS_DEG8_MAX_ERROR 3.6340015129032732e-9 // Constants for minimax polynomial approximations to atan(x). // The algorithm minimizes the maximum absolute error on [-1,1]. #define GTE_C_ATAN_DEG3_C0 +1.0 #define GTE_C_ATAN_DEG3_C1 -2.1460183660255172e-01 #define GTE_C_ATAN_DEG3_MAX_ERROR 1.5970326392614240e-2 #define GTE_C_ATAN_DEG5_C0 +1.0 #define GTE_C_ATAN_DEG5_C1 -3.0189478312144946e-01 #define GTE_C_ATAN_DEG5_C2 +8.7292946518897740e-02 #define GTE_C_ATAN_DEG5_MAX_ERROR 1.3509832247372636e-3 #define GTE_C_ATAN_DEG7_C0 +1.0 #define GTE_C_ATAN_DEG7_C1 -3.2570157599356531e-01 #define GTE_C_ATAN_DEG7_C2 +1.5342994884206673e-01 #define GTE_C_ATAN_DEG7_C3 -4.2330209451053591e-02 #define GTE_C_ATAN_DEG7_MAX_ERROR 1.5051227215514412e-4 #define GTE_C_ATAN_DEG9_C0 +1.0 #define GTE_C_ATAN_DEG9_C1 -3.3157878236439586e-01 #define GTE_C_ATAN_DEG9_C2 +1.8383034738018011e-01 #define GTE_C_ATAN_DEG9_C3 -8.9253037587244677e-02 #define GTE_C_ATAN_DEG9_C4 +2.2399635968909593e-02 #define GTE_C_ATAN_DEG9_MAX_ERROR 1.8921598624582064e-5 #define GTE_C_ATAN_DEG11_C0 +1.0 #define GTE_C_ATAN_DEG11_C1 -3.3294527685374087e-01 #define GTE_C_ATAN_DEG11_C2 +1.9498657165383548e-01 #define GTE_C_ATAN_DEG11_C3 -1.1921576270475498e-01 #define GTE_C_ATAN_DEG11_C4 +5.5063351366968050e-02 #define GTE_C_ATAN_DEG11_C5 -1.2490720064867844e-02 #define GTE_C_ATAN_DEG11_MAX_ERROR 2.5477724974187765e-6 #define GTE_C_ATAN_DEG13_C0 +1.0 #define GTE_C_ATAN_DEG13_C1 -3.3324998579202170e-01 #define GTE_C_ATAN_DEG13_C2 +1.9856563505717162e-01 #define GTE_C_ATAN_DEG13_C3 -1.3374657325451267e-01 #define GTE_C_ATAN_DEG13_C4 +8.1675882859940430e-02 #define GTE_C_ATAN_DEG13_C5 -3.5059680836411644e-02 #define GTE_C_ATAN_DEG13_C6 +7.2128853633444123e-03 #define GTE_C_ATAN_DEG13_MAX_ERROR 3.5859104691865484e-7 // Constants for minimax polynomial approximations to exp2(x) = 2^x. // The algorithm minimizes the maximum absolute error on [0,1]. #define GTE_C_EXP2_DEG1_C0 1.0 #define GTE_C_EXP2_DEG1_C1 1.0 #define GTE_C_EXP2_DEG1_MAX_ERROR 8.6071332055934313e-2 #define GTE_C_EXP2_DEG2_C0 1.0 #define GTE_C_EXP2_DEG2_C1 6.5571332605741528e-01 #define GTE_C_EXP2_DEG2_C2 3.4428667394258472e-01 #define GTE_C_EXP2_DEG2_MAX_ERROR 3.8132476831060358e-3 #define GTE_C_EXP2_DEG3_C0 1.0 #define GTE_C_EXP2_DEG3_C1 6.9589012084456225e-01 #define GTE_C_EXP2_DEG3_C2 2.2486494900110188e-01 #define GTE_C_EXP2_DEG3_C3 7.9244930154334980e-02 #define GTE_C_EXP2_DEG3_MAX_ERROR 1.4694877755186408e-4 #define GTE_C_EXP2_DEG4_C0 1.0 #define GTE_C_EXP2_DEG4_C1 6.9300392358459195e-01 #define GTE_C_EXP2_DEG4_C2 2.4154981722455560e-01 #define GTE_C_EXP2_DEG4_C3 5.1744260331489045e-02 #define GTE_C_EXP2_DEG4_C4 1.3701998859367848e-02 #define GTE_C_EXP2_DEG4_MAX_ERROR 4.7617792624521371e-6 #define GTE_C_EXP2_DEG5_C0 1.0 #define GTE_C_EXP2_DEG5_C1 6.9315298010274962e-01 #define GTE_C_EXP2_DEG5_C2 2.4014712313022102e-01 #define GTE_C_EXP2_DEG5_C3 5.5855296413199085e-02 #define GTE_C_EXP2_DEG5_C4 8.9477503096873079e-03 #define GTE_C_EXP2_DEG5_C5 1.8968500441332026e-03 #define GTE_C_EXP2_DEG5_MAX_ERROR 1.3162098333463490e-7 #define GTE_C_EXP2_DEG6_C0 1.0 #define GTE_C_EXP2_DEG6_C1 6.9314698914837525e-01 #define GTE_C_EXP2_DEG6_C2 2.4023013440952923e-01 #define GTE_C_EXP2_DEG6_C3 5.5481276898206033e-02 #define GTE_C_EXP2_DEG6_C4 9.6838443037086108e-03 #define GTE_C_EXP2_DEG6_C5 1.2388324048515642e-03 #define GTE_C_EXP2_DEG6_C6 2.1892283501756538e-04 #define GTE_C_EXP2_DEG6_MAX_ERROR 3.1589168225654163e-9 #define GTE_C_EXP2_DEG7_C0 1.0 #define GTE_C_EXP2_DEG7_C1 6.9314718588750690e-01 #define GTE_C_EXP2_DEG7_C2 2.4022637363165700e-01 #define GTE_C_EXP2_DEG7_C3 5.5505235570535660e-02 #define GTE_C_EXP2_DEG7_C4 9.6136265387940512e-03 #define GTE_C_EXP2_DEG7_C5 1.3429234504656051e-03 #define GTE_C_EXP2_DEG7_C6 1.4299202757683815e-04 #define GTE_C_EXP2_DEG7_C7 2.1662892777385423e-05 #define GTE_C_EXP2_DEG7_MAX_ERROR 6.6864513925679603e-11 // Constants for minimax polynomial approximations to log2(x). // The algorithm minimizes the maximum absolute error on [1,2]. // The polynomials all have constant term zero. #define GTE_C_LOG2_DEG1_C1 +1.0 #define GTE_C_LOG2_DEG1_MAX_ERROR 8.6071332055934202e-2 #define GTE_C_LOG2_DEG2_C1 +1.3465553856377803 #define GTE_C_LOG2_DEG2_C2 -3.4655538563778032e-01 #define GTE_C_LOG2_DEG2_MAX_ERROR 7.6362868906658110e-3 #define GTE_C_LOG2_DEG3_C1 +1.4228653756681227 #define GTE_C_LOG2_DEG3_C2 -5.8208556916449616e-01 #define GTE_C_LOG2_DEG3_C3 +1.5922019349637218e-01 #define GTE_C_LOG2_DEG3_MAX_ERROR 8.7902902652883808e-4 #define GTE_C_LOG2_DEG4_C1 +1.4387257478171547 #define GTE_C_LOG2_DEG4_C2 -6.7778401359918661e-01 #define GTE_C_LOG2_DEG4_C3 +3.2118898377713379e-01 #define GTE_C_LOG2_DEG4_C4 -8.2130717995088531e-02 #define GTE_C_LOG2_DEG4_MAX_ERROR 1.1318551355360418e-4 #define GTE_C_LOG2_DEG5_C1 +1.4419170408633741 #define GTE_C_LOG2_DEG5_C2 -7.0909645927612530e-01 #define GTE_C_LOG2_DEG5_C3 +4.1560609399164150e-01 #define GTE_C_LOG2_DEG5_C4 -1.9357573729558908e-01 #define GTE_C_LOG2_DEG5_C5 +4.5149061716699634e-02 #define GTE_C_LOG2_DEG5_MAX_ERROR 1.5521274478735858e-5 #define GTE_C_LOG2_DEG6_C1 +1.4425449435950917 #define GTE_C_LOG2_DEG6_C2 -7.1814525675038965e-01 #define GTE_C_LOG2_DEG6_C3 +4.5754919692564044e-01 #define GTE_C_LOG2_DEG6_C4 -2.7790534462849337e-01 #define GTE_C_LOG2_DEG6_C5 +1.2179791068763279e-01 #define GTE_C_LOG2_DEG6_C6 -2.5841449829670182e-02 #define GTE_C_LOG2_DEG6_MAX_ERROR 2.2162051216689793e-6 #define GTE_C_LOG2_DEG7_C1 +1.4426664401536078 #define GTE_C_LOG2_DEG7_C2 -7.2055423726162360e-01 #define GTE_C_LOG2_DEG7_C3 +4.7332419162501083e-01 #define GTE_C_LOG2_DEG7_C4 -3.2514018752954144e-01 #define GTE_C_LOG2_DEG7_C5 +1.9302965529095673e-01 #define GTE_C_LOG2_DEG7_C6 -7.8534970641157997e-02 #define GTE_C_LOG2_DEG7_C7 +1.5209108363023915e-02 #define GTE_C_LOG2_DEG7_MAX_ERROR 3.2546531700261561e-7 #define GTE_C_LOG2_DEG8_C1 +1.4426896453621882 #define GTE_C_LOG2_DEG8_C2 -7.2115893912535967e-01 #define GTE_C_LOG2_DEG8_C3 +4.7861716616785088e-01 #define GTE_C_LOG2_DEG8_C4 -3.4699935395019565e-01 #define GTE_C_LOG2_DEG8_C5 +2.4114048765477492e-01 #define GTE_C_LOG2_DEG8_C6 -1.3657398692885181e-01 #define GTE_C_LOG2_DEG8_C7 +5.1421382871922106e-02 #define GTE_C_LOG2_DEG8_C8 -9.1364020499895560e-03 #define GTE_C_LOG2_DEG8_MAX_ERROR 4.8796219218050219e-8 // These functions are convenient for some applications. The classes // BSNumber, BSRational and IEEEBinary16 have implementations that // (for now) use typecasting to call the 'float' or 'double' versions. namespace gte { inline float atandivpi(float x) { return std::atan(x) * (float)GTE_C_INV_PI; } inline float atan2divpi(float y, float x) { return std::atan2(y, x) * (float)GTE_C_INV_PI; } inline float clamp(float x, float xmin, float xmax) { return (x <= xmin ? xmin : (x >= xmax ? xmax : x)); } inline float cospi(float x) { return std::cos(x * (float)GTE_C_PI); } inline float exp10(float x) { return std::exp(x * (float)GTE_C_LN_10); } inline float invsqrt(float x) { return 1.0f / std::sqrt(x); } inline int isign(float x) { return (x > 0.0f ? 1 : (x < 0.0f ? -1 : 0)); } inline float saturate(float x) { return (x <= 0.0f ? 0.0f : (x >= 1.0f ? 1.0f : x)); } inline float sign(float x) { return (x > 0.0f ? 1.0f : (x < 0.0f ? -1.0f : 0.0f)); } inline float sinpi(float x) { return std::sin(x * (float)GTE_C_PI); } inline float sqr(float x) { return x * x; } inline double atandivpi(double x) { return std::atan(x) * GTE_C_INV_PI; } inline double atan2divpi(double y, double x) { return std::atan2(y, x) * GTE_C_INV_PI; } inline double clamp(double x, double xmin, double xmax) { return (x <= xmin ? xmin : (x >= xmax ? xmax : x)); } inline double cospi(double x) { return std::cos(x * GTE_C_PI); } inline double exp10(double x) { return std::exp(x * GTE_C_LN_10); } inline double invsqrt(double x) { return 1.0 / std::sqrt(x); } inline double sign(double x) { return (x > 0.0 ? 1.0 : (x < 0.0 ? -1.0 : 0.0f)); } inline int isign(double x) { return (x > 0.0 ? 1 : (x < 0.0 ? -1 : 0)); } inline double saturate(double x) { return (x <= 0.0 ? 0.0 : (x >= 1.0 ? 1.0 : x)); } inline double sinpi(double x) { return std::sin(x * GTE_C_PI); } inline double sqr(double x) { return x * x; } } // Type traits to support std::enable_if conditional compilation for // numerical computations. namespace gte { // The trait is_arbitrary_precision<T> for type T of float, double or // long double generates is_arbitrary_precision<T>::value of false. The // implementations for arbitrary-precision arithmetic are found in // GteArbitraryPrecision.h. template <typename T> struct is_arbitrary_precision_internal : std::false_type {}; template <typename T> struct is_arbitrary_precision : is_arbitrary_precision_internal<std::remove_cv_t<T>>::type {}; // The trait has_division_operator<T> for type T of float, double or // long double generates has_division_operator<T>::value of true. The // implementations for arbitrary-precision arithmetic are found in // GteArbitraryPrecision.h. template <typename T> struct has_division_operator_internal : std::false_type {}; template <typename T> struct has_division_operator : has_division_operator_internal<std::remove_cv_t<T>>::type {}; template <> struct has_division_operator_internal<float> : std::true_type {}; template <> struct has_division_operator_internal<double> : std::true_type {}; template <> struct has_division_operator_internal<long double> : std::true_type {}; } // ---------------------------------------------- // GteDCPQuery.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) namespace gte { // Distance and closest-point queries. template <typename Real, typename Type0, typename Type1> class DCPQuery { public: struct Result { // A DCPQuery-base class B must define a B::Result struct with member // 'Real distance'. A DCPQuery-derived class D must also derive a // D::Result from B:Result but may have no members. The idea is to // allow Result to store closest-point information in addition to the // distance. The operator() is non-const to allow DCPQuery to store // and modify private state that supports the query. }; Result operator()(Type0 const& primitive0, Type1 const& primitive1); }; } // ---------------------------------------------- // GteApprQuery.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Class ApprQuery supports the RANSAC algorithm for fitting and uses the // Curiously Recurring Template Pattern. The ModelType must be a class or // struct with the following interfaces: // // // The minimum number of observations required to fit the model. // int ModelType::GetMinimumRequired() const; // // // Compute the model error for the specified observation for the current // // model parameters. // Real Error(ObservationType const& observation) const; // // // Estimate the model parameters for all observations specified by the // // indices. The three Fit() functions of ApprQuery manipulate their // // inputs in order to pass them to ModelType::Fit(). // ModelType::Fit(std::vector<ObservationType> const& observations, // std::vector<size_t> const& indices); namespace gte { template <typename Real, typename ModelType, typename ObservationType> class ApprQuery { public: // Estimate the model parameters for all observations. bool Fit(std::vector<ObservationType> const& observations); // Estimate the model parameters for a contiguous subset of observations. bool Fit(std::vector<ObservationType> const& observations, int const imin, int const imax); // Estimate the model parameters for the subset of observations specified // by the indices and the number of indices that is possibly smaller than // indices.size(). bool Fit(std::vector<ObservationType> const& observations, std::vector<int> const& indices, int const numIndices); // Apply the RANdom SAmple Consensus algorithm for fitting a model to // observations. static bool RANSAC( ModelType& candidateModel, std::vector<ObservationType> const& observations, int const numRequiredForGoodFit, Real const maxErrorForGoodFit, int const numIterations, std::vector<int>& bestConsensus, ModelType& bestModel); }; template <typename Real, typename ModelType, typename ObservationType> bool ApprQuery<Real, ModelType, ObservationType>::Fit( std::vector<ObservationType> const& observations) { std::vector<int> indices(observations.size()); int i = 0; for (auto& index : indices) { index = i++; } return ((ModelType*)this)->Fit(observations, indices); } template <typename Real, typename ModelType, typename ObservationType> bool ApprQuery<Real, ModelType, ObservationType>::Fit( std::vector<ObservationType> const& observations, int const imin, int const imax) { if (imin <= imax) { int numIndices = imax - imin + 1; std::vector<int> indices(numIndices); int i = imin; for (auto& index : indices) { index = i++; } return ((ModelType*)this)->Fit(observations, indices); } else { return false; } } template <typename Real, typename ModelType, typename ObservationType> bool ApprQuery<Real, ModelType, ObservationType>::Fit( std::vector<ObservationType> const& observations, std::vector<int> const& indices, int const numIndices) { int imax = std::min(numIndices, static_cast<int>(observations.size())); std::vector<int> localindices(imax); int i = 0; for (auto& index : localindices) { index = indices[i++]; } return ((ModelType*)this)->Fit(observations, indices); } template <typename Real, typename ModelType, typename ObservationType> bool ApprQuery<Real, ModelType, ObservationType>::RANSAC( ModelType& candidateModel, std::vector<ObservationType> const& observations, int const numRequiredForGoodFit, Real const maxErrorForGoodFit, int const numIterations, std::vector<int>& bestConsensus, ModelType& bestModel) { int const numObservations = static_cast<int>(observations.size()); int const minRequired = candidateModel.GetMinimumRequired(); if (numObservations < minRequired) { // Too few observations for model fitting. return false; } // The first part of the array will store the consensus set, initially // filled with the minimumu number of indices that correspond to the // candidate inliers. The last part will store the remaining indices. // These points are tested against the model and are added to the // consensus set when they fit. All the index manipulation is done // in place. Initially, the candidates are the identity permutation. std::vector<int> candidates(numObservations); int j = 0; for (auto& c : candidates) { c = j++; } if (numObservations == minRequired) { // We have the minimum number of observations to generate the model, // so RANSAC cannot be used. Compute the model with the entire set // of observations. bestConsensus = candidates; return bestModel.Fit(observations); } int bestNumFittedObservations = minRequired; for (int i = 0; i < numIterations; ++i) { // Randomly permute the previous candidates, partitioning the array // into GetMinimumRequired() indices (the candidate inliers) followed // by the remaining indices (candidates for testing against the // model). std::shuffle(candidates.begin(), candidates.end(), std::default_random_engine()); // Fit the model to the inliers. if (candidateModel.Fit(observations, candidates, minRequired)) { // Test each remaining observation whether it fits the model. If // it does, include it in the consensus set. int numFittedObservations = minRequired; for (j = minRequired; j < numObservations; ++j) { if (candidateModel.Error(observations[candidates[j]]) <= maxErrorForGoodFit) { std::swap(candidates[j], candidates[numFittedObservations]); ++numFittedObservations; } } if (numFittedObservations >= numRequiredForGoodFit) { // We have observations that fit the model. Update the best // model using the consensus set. candidateModel.Fit(observations, candidates, numFittedObservations); if (numFittedObservations > bestNumFittedObservations) { // The consensus set is larger than the previous consensus // set, so its model becomes the best one. bestModel = candidateModel; bestConsensus.resize(numFittedObservations); std::copy(candidates.begin(), candidates.begin() + numFittedObservations, bestConsensus.begin()); bestNumFittedObservations = numFittedObservations; } } } } return bestNumFittedObservations >= numRequiredForGoodFit; } } // ---------------------------------------------- // GteSymmetricEigensolver3x3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.5 (2018/10/09) // The document // http://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf // describes algorithms for solving the eigensystem associated with a 3x3 // symmetric real-valued matrix. The iterative algorithm is implemented // by class SymmmetricEigensolver3x3. The noniterative algorithm is // implemented by class NISymmetricEigensolver3x3. The code does not use // GTEngine objects. namespace gte { template <typename Real> class SymmetricEigensolver3x3 { public: // The input matrix must be symmetric, so only the unique elements must // be specified: a00, a01, a02, a11, a12, and a22. // // If 'aggressive' is 'true', the iterations occur until a superdiagonal // entry is exactly zero. If 'aggressive' is 'false', the iterations // occur until a superdiagonal entry is effectively zero compared to the // sum of magnitudes of its diagonal neighbors. Generally, the // nonaggressive convergence is acceptable. // // The order of the eigenvalues is specified by sortType: -1 (decreasing), // 0 (no sorting), or +1 (increasing). When sorted, the eigenvectors are // ordered accordingly, and {evec[0], evec[1], evec[2]} is guaranteed to // be a right-handed orthonormal set. The return value is the number of // iterations used by the algorithm. int operator()(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, bool aggressive, int sortType, std::array<Real, 3>& eval, std::array<std::array<Real, 3>, 3>& evec) const; private: // Update Q = Q*G in-place using G = {{c,0,-s},{s,0,c},{0,0,1}}. void Update0(Real Q[3][3], Real c, Real s) const; // Update Q = Q*G in-place using G = {{0,1,0},{c,0,s},{-s,0,c}}. void Update1(Real Q[3][3], Real c, Real s) const; // Update Q = Q*H in-place using H = {{c,s,0},{s,-c,0},{0,0,1}}. void Update2(Real Q[3][3], Real c, Real s) const; // Update Q = Q*H in-place using H = {{1,0,0},{0,c,s},{0,s,-c}}. void Update3(Real Q[3][3], Real c, Real s) const; // Normalize (u,v) robustly, avoiding floating-point overflow in the sqrt // call. The normalized pair is (cs,sn) with cs <= 0. If (u,v) = (0,0), // the function returns (cs,sn) = (-1,0). When used to generate a // Householder reflection, it does not matter whether (cs,sn) or (-cs,-sn) // is used. When generating a Givens reflection, cs = cos(2*theta) and // sn = sin(2*theta). Having a negative cosine for the double-angle // term ensures that the single-angle terms c = cos(theta) and // s = sin(theta) satisfy |c| <= |s|. void GetCosSin(Real u, Real v, Real& cs, Real& sn) const; // The convergence test. When 'aggressive' is 'true', the superdiagonal // test is "bSuper == 0". When 'aggressive' is 'false', the superdiagonal // test is "|bDiag0| + |bDiag1| + |bSuper| == |bDiag0| + |bDiag1|, which // means bSuper is effectively zero compared to the sizes of the diagonal // entries. bool Converged(bool aggressive, Real bDiag0, Real bDiag1, Real bSuper) const; // Support for sorting the eigenvalues and eigenvectors. The output // (i0,i1,i2) is a permutation of (0,1,2) so that d[i0] <= d[i1] <= d[i2]. // The 'bool' return indicates whether the permutation is odd. If it is // not, the handedness of the Q matrix must be adjusted. bool Sort(std::array<Real, 3> const& d, int& i0, int& i1, int& i2) const; }; template <typename Real> class NISymmetricEigensolver3x3 { public: // The input matrix must be symmetric, so only the unique elements must // be specified: a00, a01, a02, a11, a12, and a22. The eigenvalues are // sorted in ascending order: eval0 <= eval1 <= eval2. void operator()(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, std::array<Real, 3>& eval, std::array<std::array<Real, 3>, 3>& evec) const; private: static std::array<Real, 3> Multiply(Real s, std::array<Real, 3> const& U); static std::array<Real, 3> Subtract(std::array<Real, 3> const& U, std::array<Real, 3> const& V); static std::array<Real, 3> Divide(std::array<Real, 3> const& U, Real s); static Real Dot(std::array<Real, 3> const& U, std::array<Real, 3> const& V); static std::array<Real, 3> Cross(std::array<Real, 3> const& U, std::array<Real, 3> const& V); void ComputeOrthogonalComplement(std::array<Real, 3> const& W, std::array<Real, 3>& U, std::array<Real, 3>& V) const; void ComputeEigenvector0(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, Real eval0, std::array<Real, 3>& evec0) const; void ComputeEigenvector1(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, std::array<Real, 3> const& evec0, Real eval1, std::array<Real, 3>& evec1) const; }; template <typename Real> int SymmetricEigensolver3x3<Real>::operator()(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, bool aggressive, int sortType, std::array<Real, 3>& eval, std::array<std::array<Real, 3>, 3>& evec) const { // Compute the Householder reflection H and B = H*A*H, where b02 = 0. Real const zero = (Real)0, one = (Real)1, half = (Real)0.5; bool isRotation = false; Real c, s; GetCosSin(a12, -a02, c, s); Real Q[3][3] = { { c, s, zero }, { s, -c, zero }, { zero, zero, one } }; Real term0 = c * a00 + s * a01; Real term1 = c * a01 + s * a11; Real b00 = c * term0 + s * term1; Real b01 = s * term0 - c * term1; term0 = s * a00 - c * a01; term1 = s * a01 - c * a11; Real b11 = s * term0 - c * term1; Real b12 = s * a02 - c * a12; Real b22 = a22; // Givens reflections, B' = G^T*B*G, preserve tridiagonal matrices. int const maxIteration = 2 * (1 + std::numeric_limits<Real>::digits - std::numeric_limits<Real>::min_exponent); int iteration; Real c2, s2; if (std::abs(b12) <= std::abs(b01)) { Real saveB00, saveB01, saveB11; for (iteration = 0; iteration < maxIteration; ++iteration) { // Compute the Givens reflection. GetCosSin(half * (b00 - b11), b01, c2, s2); s = std::sqrt(half * (one - c2)); // >= 1/sqrt(2) c = half * s2 / s; // Update Q by the Givens reflection. Update0(Q, c, s); isRotation = !isRotation; // Update B <- Q^T*B*Q, ensuring that b02 is zero and |b12| has // strictly decreased. saveB00 = b00; saveB01 = b01; saveB11 = b11; term0 = c * saveB00 + s * saveB01; term1 = c * saveB01 + s * saveB11; b00 = c * term0 + s * term1; b11 = b22; term0 = c * saveB01 - s * saveB00; term1 = c * saveB11 - s * saveB01; b22 = c * term1 - s * term0; b01 = s * b12; b12 = c * b12; if (Converged(aggressive, b00, b11, b01)) { // Compute the Householder reflection. GetCosSin(half * (b00 - b11), b01, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // >= 1/sqrt(2) // Update Q by the Householder reflection. Update2(Q, c, s); isRotation = !isRotation; // Update D = Q^T*B*Q. saveB00 = b00; saveB01 = b01; saveB11 = b11; term0 = c * saveB00 + s * saveB01; term1 = c * saveB01 + s * saveB11; b00 = c * term0 + s * term1; term0 = s * saveB00 - c * saveB01; term1 = s * saveB01 - c * saveB11; b11 = s * term0 - c * term1; break; } } } else { Real saveB11, saveB12, saveB22; for (iteration = 0; iteration < maxIteration; ++iteration) { // Compute the Givens reflection. GetCosSin(half * (b22 - b11), b12, c2, s2); s = std::sqrt(half * (one - c2)); // >= 1/sqrt(2) c = half * s2 / s; // Update Q by the Givens reflection. Update1(Q, c, s); isRotation = !isRotation; // Update B <- Q^T*B*Q, ensuring that b02 is zero and |b12| has // strictly decreased. MODIFY... saveB11 = b11; saveB12 = b12; saveB22 = b22; term0 = c * saveB22 + s * saveB12; term1 = c * saveB12 + s * saveB11; b22 = c * term0 + s * term1; b11 = b00; term0 = c * saveB12 - s * saveB22; term1 = c * saveB11 - s * saveB12; b00 = c * term1 - s * term0; b12 = s * b01; b01 = c * b01; if (Converged(aggressive, b11, b22, b12)) { // Compute the Householder reflection. GetCosSin(half * (b11 - b22), b12, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // >= 1/sqrt(2) // Update Q by the Householder reflection. Update3(Q, c, s); isRotation = !isRotation; // Update D = Q^T*B*Q. saveB11 = b11; saveB12 = b12; saveB22 = b22; term0 = c * saveB11 + s * saveB12; term1 = c * saveB12 + s * saveB22; b11 = c * term0 + s * term1; term0 = s * saveB11 - c * saveB12; term1 = s * saveB12 - c * saveB22; b22 = s * term0 - c * term1; break; } } } std::array<Real, 3> diagonal = { { b00, b11, b22 } }; int i0, i1, i2; if (sortType >= 1) { // diagonal[i0] <= diagonal[i1] <= diagonal[i2] bool isOdd = Sort(diagonal, i0, i1, i2); if (!isOdd) { isRotation = !isRotation; } } else if (sortType <= -1) { // diagonal[i0] >= diagonal[i1] >= diagonal[i2] bool isOdd = Sort(diagonal, i0, i1, i2); std::swap(i0, i2); // (i0,i1,i2)->(i2,i1,i0) is odd if (isOdd) { isRotation = !isRotation; } } else { i0 = 0; i1 = 1; i2 = 2; } eval[0] = diagonal[i0]; eval[1] = diagonal[i1]; eval[2] = diagonal[i2]; evec[0][0] = Q[0][i0]; evec[0][1] = Q[1][i0]; evec[0][2] = Q[2][i0]; evec[1][0] = Q[0][i1]; evec[1][1] = Q[1][i1]; evec[1][2] = Q[2][i1]; evec[2][0] = Q[0][i2]; evec[2][1] = Q[1][i2]; evec[2][2] = Q[2][i2]; // Ensure the columns of Q form a right-handed set. if (!isRotation) { for (int j = 0; j < 3; ++j) { evec[2][j] = -evec[2][j]; } } return iteration; } template <typename Real> void SymmetricEigensolver3x3<Real>::Update0(Real Q[3][3], Real c, Real s) const { for (int r = 0; r < 3; ++r) { Real tmp0 = c * Q[r][0] + s * Q[r][1]; Real tmp1 = Q[r][2]; Real tmp2 = c * Q[r][1] - s * Q[r][0]; Q[r][0] = tmp0; Q[r][1] = tmp1; Q[r][2] = tmp2; } } template <typename Real> void SymmetricEigensolver3x3<Real>::Update1(Real Q[3][3], Real c, Real s) const { for (int r = 0; r < 3; ++r) { Real tmp0 = c * Q[r][1] - s * Q[r][2]; Real tmp1 = Q[r][0]; Real tmp2 = c * Q[r][2] + s * Q[r][1]; Q[r][0] = tmp0; Q[r][1] = tmp1; Q[r][2] = tmp2; } } template <typename Real> void SymmetricEigensolver3x3<Real>::Update2(Real Q[3][3], Real c, Real s) const { for (int r = 0; r < 3; ++r) { Real tmp0 = c * Q[r][0] + s * Q[r][1]; Real tmp1 = s * Q[r][0] - c * Q[r][1]; Q[r][0] = tmp0; Q[r][1] = tmp1; } } template <typename Real> void SymmetricEigensolver3x3<Real>::Update3(Real Q[3][3], Real c, Real s) const { for (int r = 0; r < 3; ++r) { Real tmp0 = c * Q[r][1] + s * Q[r][2]; Real tmp1 = s * Q[r][1] - c * Q[r][2]; Q[r][1] = tmp0; Q[r][2] = tmp1; } } template <typename Real> void SymmetricEigensolver3x3<Real>::GetCosSin(Real u, Real v, Real& cs, Real& sn) const { Real maxAbsComp = std::max(std::abs(u), std::abs(v)); if (maxAbsComp > (Real)0) { u /= maxAbsComp; // in [-1,1] v /= maxAbsComp; // in [-1,1] Real length = std::sqrt(u * u + v * v); cs = u / length; sn = v / length; if (cs > (Real)0) { cs = -cs; sn = -sn; } } else { cs = (Real)-1; sn = (Real)0; } } template <typename Real> bool SymmetricEigensolver3x3<Real>::Converged(bool aggressive, Real bDiag0, Real bDiag1, Real bSuper) const { if (aggressive) { return bSuper == (Real)0; } else { Real sum = std::abs(bDiag0) + std::abs(bDiag1); return sum + std::abs(bSuper) == sum; } } template <typename Real> bool SymmetricEigensolver3x3<Real>::Sort(std::array<Real, 3> const& d, int& i0, int& i1, int& i2) const { bool odd; if (d[0] < d[1]) { if (d[2] < d[0]) { i0 = 2; i1 = 0; i2 = 1; odd = true; } else if (d[2] < d[1]) { i0 = 0; i1 = 2; i2 = 1; odd = false; } else { i0 = 0; i1 = 1; i2 = 2; odd = true; } } else { if (d[2] < d[1]) { i0 = 2; i1 = 1; i2 = 0; odd = false; } else if (d[2] < d[0]) { i0 = 1; i1 = 2; i2 = 0; odd = true; } else { i0 = 1; i1 = 0; i2 = 2; odd = false; } } return odd; } template <typename Real> void NISymmetricEigensolver3x3<Real>::operator() (Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, std::array<Real, 3>& eval, std::array<std::array<Real, 3>, 3>& evec) const { // Precondition the matrix by factoring out the maximum absolute value // of the components. This guards against floating-point overflow when // computing the eigenvalues. Real max0 = std::max(std::abs(a00), std::abs(a01)); Real max1 = std::max(std::abs(a02), std::abs(a11)); Real max2 = std::max(std::abs(a12), std::abs(a22)); Real maxAbsElement = std::max(std::max(max0, max1), max2); if (maxAbsElement == (Real)0) { // A is the zero matrix. eval[0] = (Real)0; eval[1] = (Real)0; eval[2] = (Real)0; evec[0] = { (Real)1, (Real)0, (Real)0 }; evec[1] = { (Real)0, (Real)1, (Real)0 }; evec[2] = { (Real)0, (Real)0, (Real)1 }; return; } Real invMaxAbsElement = (Real)1 / maxAbsElement; a00 *= invMaxAbsElement; a01 *= invMaxAbsElement; a02 *= invMaxAbsElement; a11 *= invMaxAbsElement; a12 *= invMaxAbsElement; a22 *= invMaxAbsElement; Real norm = a01 * a01 + a02 * a02 + a12 * a12; if (norm > (Real)0) { // Compute the eigenvalues of A. // In the PDF mentioned previously, B = (A - q*I)/p, where q = tr(A)/3 // with tr(A) the trace of A (sum of the diagonal entries of A) and where // p = sqrt(tr((A - q*I)^2)/6). Real q = (a00 + a11 + a22) / (Real)3; // The matrix A - q*I is represented by the following, where b00, b11 and // b22 are computed after these comments, // +- -+ // | b00 a01 a02 | // | a01 b11 a12 | // | a02 a12 b22 | // +- -+ Real b00 = a00 - q; Real b11 = a11 - q; Real b22 = a22 - q; // The is the variable p mentioned in the PDF. Real p = std::sqrt((b00 * b00 + b11 * b11 + b22 * b22 + norm * (Real)2) / (Real)6); // We need det(B) = det((A - q*I)/p) = det(A - q*I)/p^3. The value // det(A - q*I) is computed using a cofactor expansion by the first // row of A - q*I. The cofactors are c00, c01 and c02 and the // determinant is b00*c00 - a01*c01 + a02*c02. The det(B) is then // computed finally by the division with p^3. Real c00 = b11 * b22 - a12 * a12; Real c01 = a01 * b22 - a12 * a02; Real c02 = a01 * a12 - b11 * a02; Real det = (b00 * c00 - a01 * c01 + a02 * c02) / (p * p * p); // The halfDet value is cos(3*theta) mentioned in the PDF. The acos(z) // function requires |z| <= 1, but will fail silently and return NaN // if the input is larger than 1 in magnitude. To avoid this problem // due to rounding errors, the halfDet/ value is clamped to [-1,1]. Real halfDet = det * (Real)0.5; halfDet = std::min(std::max(halfDet, (Real)-1), (Real)1); // The eigenvalues of B are ordered as beta0 <= beta1 <= beta2. The // number of digits in twoThirdsPi is chosen so that, whether float or // double, the floating-point number is the closest to theoretical 2*pi/3. Real angle = std::acos(halfDet) / (Real)3; Real const twoThirdsPi = (Real)2.09439510239319549; Real beta2 = std::cos(angle) * (Real)2; Real beta0 = std::cos(angle + twoThirdsPi) * (Real)2; Real beta1 = -(beta0 + beta2); // The eigenvalues of A are ordered as alpha0 <= alpha1 <= alpha2. eval[0] = q + p * beta0; eval[1] = q + p * beta1; eval[2] = q + p * beta2; // Compute the eigenvectors so that the set {evec[0], evec[1], evec[2]} // is right handed and orthonormal. if (halfDet >= (Real)0) { ComputeEigenvector0(a00, a01, a02, a11, a12, a22, eval[2], evec[2]); ComputeEigenvector1(a00, a01, a02, a11, a12, a22, evec[2], eval[1], evec[1]); evec[0] = Cross(evec[1], evec[2]); } else { ComputeEigenvector0(a00, a01, a02, a11, a12, a22, eval[0], evec[0]); ComputeEigenvector1(a00, a01, a02, a11, a12, a22, evec[0], eval[1], evec[1]); evec[2] = Cross(evec[0], evec[1]); } } else { // The matrix is diagonal. eval[0] = a00; eval[1] = a11; eval[2] = a22; evec[0] = { (Real)1, (Real)0, (Real)0 }; evec[1] = { (Real)0, (Real)1, (Real)0 }; evec[2] = { (Real)0, (Real)0, (Real)1 }; } // The preconditioning scaled the matrix A, which scales the eigenvalues. // Revert the scaling. eval[0] *= maxAbsElement; eval[1] *= maxAbsElement; eval[2] *= maxAbsElement; } template <typename Real> std::array<Real, 3> NISymmetricEigensolver3x3<Real>::Multiply( Real s, std::array<Real, 3> const& U) { std::array<Real, 3> product = { s * U[0], s * U[1], s * U[2] }; return product; } template <typename Real> std::array<Real, 3> NISymmetricEigensolver3x3<Real>::Subtract( std::array<Real, 3> const& U, std::array<Real, 3> const& V) { std::array<Real, 3> difference = { U[0] - V[0], U[1] - V[1], U[2] - V[2] }; return difference; } template <typename Real> std::array<Real, 3> NISymmetricEigensolver3x3<Real>::Divide( std::array<Real, 3> const& U, Real s) { Real invS = (Real)1 / s; std::array<Real, 3> division = { U[0] * invS, U[1] * invS, U[2] * invS }; return division; } template <typename Real> Real NISymmetricEigensolver3x3<Real>::Dot(std::array<Real, 3> const& U, std::array<Real, 3> const& V) { Real dot = U[0] * V[0] + U[1] * V[1] + U[2] * V[2]; return dot; } template <typename Real> std::array<Real, 3> NISymmetricEigensolver3x3<Real>::Cross(std::array<Real, 3> const& U, std::array<Real, 3> const& V) { std::array<Real, 3> cross = { U[1] * V[2] - U[2] * V[1], U[2] * V[0] - U[0] * V[2], U[0] * V[1] - U[1] * V[0] }; return cross; } template <typename Real> void NISymmetricEigensolver3x3<Real>::ComputeOrthogonalComplement( std::array<Real, 3> const& W, std::array<Real, 3>& U, std::array<Real, 3>& V) const { // Robustly compute a right-handed orthonormal set { U, V, W }. The // vector W is guaranteed to be unit-length, in which case there is no // need to worry about a division by zero when computing invLength. Real invLength; if (std::abs(W[0]) > std::abs(W[1])) { // The component of maximum absolute value is either W[0] or W[2]. invLength = (Real)1 / std::sqrt(W[0] * W[0] + W[2] * W[2]); U = { -W[2] * invLength, (Real)0, +W[0] * invLength }; } else { // The component of maximum absolute value is either W[1] or W[2]. invLength = (Real)1 / std::sqrt(W[1] * W[1] + W[2] * W[2]); U = { (Real)0, +W[2] * invLength, -W[1] * invLength }; } V = Cross(W, U); } template <typename Real> void NISymmetricEigensolver3x3<Real>::ComputeEigenvector0(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, Real eval0, std::array<Real, 3>& evec0) const { // Compute a unit-length eigenvector for eigenvalue[i0]. The matrix is // rank 2, so two of the rows are linearly independent. For a robust // computation of the eigenvector, select the two rows whose cross product // has largest length of all pairs of rows. std::array<Real, 3> row0 = { a00 - eval0, a01, a02 }; std::array<Real, 3> row1 = { a01, a11 - eval0, a12 }; std::array<Real, 3> row2 = { a02, a12, a22 - eval0 }; std::array<Real, 3> r0xr1 = Cross(row0, row1); std::array<Real, 3> r0xr2 = Cross(row0, row2); std::array<Real, 3> r1xr2 = Cross(row1, row2); Real d0 = Dot(r0xr1, r0xr1); Real d1 = Dot(r0xr2, r0xr2); Real d2 = Dot(r1xr2, r1xr2); Real dmax = d0; int imax = 0; if (d1 > dmax) { dmax = d1; imax = 1; } if (d2 > dmax) { imax = 2; } if (imax == 0) { evec0 = Divide(r0xr1, std::sqrt(d0)); } else if (imax == 1) { evec0 = Divide(r0xr2, std::sqrt(d1)); } else { evec0 = Divide(r1xr2, std::sqrt(d2)); } } template <typename Real> void NISymmetricEigensolver3x3<Real>::ComputeEigenvector1(Real a00, Real a01, Real a02, Real a11, Real a12, Real a22, std::array<Real, 3> const& evec0, Real eval1, std::array<Real, 3>& evec1) const { // Robustly compute a right-handed orthonormal set { U, V, evec0 }. std::array<Real, 3> U, V; ComputeOrthogonalComplement(evec0, U, V); // Let e be eval1 and let E be a corresponding eigenvector which is a // solution to the linear system (A - e*I)*E = 0. The matrix (A - e*I) // is 3x3, not invertible (so infinitely many solutions), and has rank 2 // when eval1 and eval are different. It has rank 1 when eval1 and eval2 // are equal. Numerically, it is difficult to compute robustly the rank // of a matrix. Instead, the 3x3 linear system is reduced to a 2x2 system // as follows. Define the 3x2 matrix J = [U V] whose columns are the U // and V computed previously. Define the 2x1 vector X = J*E. The 2x2 // system is 0 = M * X = (J^T * (A - e*I) * J) * X where J^T is the // transpose of J and M = J^T * (A - e*I) * J is a 2x2 matrix. The system // may be written as // +- -++- -+ +- -+ // | U^T*A*U - e U^T*A*V || x0 | = e * | x0 | // | V^T*A*U V^T*A*V - e || x1 | | x1 | // +- -++ -+ +- -+ // where X has row entries x0 and x1. std::array<Real, 3> AU = { a00 * U[0] + a01 * U[1] + a02 * U[2], a01 * U[0] + a11 * U[1] + a12 * U[2], a02 * U[0] + a12 * U[1] + a22 * U[2] }; std::array<Real, 3> AV = { a00 * V[0] + a01 * V[1] + a02 * V[2], a01 * V[0] + a11 * V[1] + a12 * V[2], a02 * V[0] + a12 * V[1] + a22 * V[2] }; Real m00 = U[0] * AU[0] + U[1] * AU[1] + U[2] * AU[2] - eval1; Real m01 = U[0] * AV[0] + U[1] * AV[1] + U[2] * AV[2]; Real m11 = V[0] * AV[0] + V[1] * AV[1] + V[2] * AV[2] - eval1; // For robustness, choose the largest-length row of M to compute the // eigenvector. The 2-tuple of coefficients of U and V in the // assignments to eigenvector[1] lies on a circle, and U and V are // unit length and perpendicular, so eigenvector[1] is unit length // (within numerical tolerance). Real absM00 = std::abs(m00); Real absM01 = std::abs(m01); Real absM11 = std::abs(m11); Real maxAbsComp; if (absM00 >= absM11) { maxAbsComp = std::max(absM00, absM01); if (maxAbsComp > (Real)0) { if (absM00 >= absM01) { m01 /= m00; m00 = (Real)1 / std::sqrt((Real)1 + m01 * m01); m01 *= m00; } else { m00 /= m01; m01 = (Real)1 / std::sqrt((Real)1 + m00 * m00); m00 *= m01; } evec1 = Subtract(Multiply(m01, U), Multiply(m00, V)); } else { evec1 = U; } } else { maxAbsComp = std::max(absM11, absM01); if (maxAbsComp > (Real)0) { if (absM11 >= absM01) { m01 /= m11; m11 = (Real)1 / std::sqrt((Real)1 + m01 * m01); m01 *= m11; } else { m11 /= m01; m01 = (Real)1 / std::sqrt((Real)1 + m11 * m11); m11 *= m01; } evec1 = Subtract(Multiply(m11, U), Multiply(m01, V)); } else { evec1 = U; } } } } // ---------------------------------------------- // TODO: GteApprOrthogonalLine3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // Least-squares fit of a line to (x,y,z) data by using distance measurements // orthogonal to the proposed line. The return value is 'true' iff the fit // is unique (always successful, 'true' when a minimum eigenvalue is unique). // The mParameters value is a line with (P,D) = (origin,direction). The // error for S = (x0,y0,z0) is (S-P)^T*(I - D*D^T)*(S-P). namespace gte { template <typename Real> class ApprOrthogonalLine3 : public ApprQuery<Real, ApprOrthogonalLine3<Real>, Vector3<Real>> { public: // Initialize the model parameters to zero. ApprOrthogonalLine3(); // Basic fitting algorithm. bool Fit(int numPoints, Vector3<Real> const* points); Line3<Real> const& GetParameters() const; // Functions called by ApprQuery::RANSAC. See GteApprQuery.h for a // detailed description. int GetMinimumRequired() const; Real Error(Vector3<Real> const& observation) const; bool Fit(std::vector<Vector3<Real>> const& observations, std::vector<int> const& indices); private: Line3<Real> mParameters; }; template <typename Real> ApprOrthogonalLine3<Real>::ApprOrthogonalLine3() : mParameters(Vector3<Real>::Zero(), Vector3<Real>::Zero()) { } template <typename Real> bool ApprOrthogonalLine3<Real>::Fit(int numPoints, Vector3<Real> const* points) { if (numPoints >= GetMinimumRequired() && points) { // Compute the mean of the points. Vector3<Real> mean = Vector3<Real>::Zero(); for (int i = 0; i < numPoints; ++i) { mean += points[i]; } Real invSize = ((Real)1) / (Real)numPoints; mean *= invSize; // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; for (int i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - mean; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar02 += diff[0] * diff[2]; covar11 += diff[1] * diff[1]; covar12 += diff[1] * diff[2]; covar22 += diff[2] * diff[2]; } covar00 *= invSize; covar01 *= invSize; covar02 *= invSize; covar11 *= invSize; covar12 *= invSize; covar22 *= invSize; // Solve the eigensystem. SymmetricEigensolver3x3<Real> es; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; es(covar00, covar01, covar02, covar11, covar12, covar22, false, +1, eval, evec); // The line direction is the eigenvector in the direction of largest // variance of the points. mParameters.origin = mean; mParameters.direction = evec[2]; // The fitted line is unique when the maximum eigenvalue has // multiplicity 1. return eval[1]< eval[2]; } mParameters = Line3<Real>(Vector3<Real>::Zero(), Vector3<Real>::Zero()); return false; } template <typename Real> Line3<Real> const& ApprOrthogonalLine3<Real>::GetParameters() const { return mParameters; } template <typename Real> int ApprOrthogonalLine3<Real>::GetMinimumRequired() const { return 2; } template <typename Real> Real ApprOrthogonalLine3<Real>::Error(Vector3<Real> const& observation) const { Vector3<Real> diff = observation - mParameters.origin; Real sqrlen = Dot(diff, diff); Real dot = Dot(diff, mParameters.direction); Real error = std::abs(sqrlen - dot*dot); return error; } template <typename Real> bool ApprOrthogonalLine3<Real>::Fit( std::vector<Vector3<Real>> const& observations, std::vector<int> const& indices) { if (static_cast<int>(indices.size()) >= GetMinimumRequired()) { // Compute the mean of the points. Vector3<Real> mean = Vector3<Real>::Zero(); for (auto index : indices) { mean += observations[index]; } Real invSize = ((Real)1) / (Real)indices.size(); mean *= invSize; // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; for (auto index : indices) { Vector3<Real> diff = observations[index] - mean; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar02 += diff[0] * diff[2]; covar11 += diff[1] * diff[1]; covar12 += diff[1] * diff[2]; covar22 += diff[2] * diff[2]; } covar00 *= invSize; covar01 *= invSize; covar02 *= invSize; covar11 *= invSize; covar12 *= invSize; covar22 *= invSize; // Solve the eigensystem. SymmetricEigensolver3x3<Real> es; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; es(covar00, covar01, covar02, covar11, covar12, covar22, false, +1, eval, evec); // The line direction is the eigenvector in the direction of largest // variance of the points. mParameters.origin = mean; mParameters.direction = evec[2]; // The fitted line is unique when the maximum eigenvalue has // multiplicity 1. return eval[1]< eval[2]; } mParameters = Line3<Real>(Vector3<Real>::Zero(), Vector3<Real>::Zero()); return false; } } // ---------------------------------------------- // GteDistPointLine.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) namespace gte { template <int N, typename Real> class DCPQuery<Real, Vector<N, Real>, Line<N, Real>> { public: struct Result { Real distance, sqrDistance; Real lineParameter; // t in (-infinity,+infinity) Vector<N, Real> lineClosest; // origin + t * direction }; Result operator()(Vector<N, Real> const& point, Line<N, Real> const& line); }; // Template aliases for convenience. template <int N, typename Real> using DCPPointLine = DCPQuery<Real, Vector<N, Real>, Line<N, Real>>; template <typename Real> using DCPPoint2Line2 = DCPPointLine<2, Real>; template <typename Real> using DCPPoint3Line3 = DCPPointLine<3, Real>; template <int N, typename Real> typename DCPQuery<Real, Vector<N, Real>, Line<N, Real>>::Result DCPQuery<Real, Vector<N, Real>, Line<N, Real>>::operator()( Vector<N, Real> const& point, Line<N, Real> const& line) { Result result; Vector<N, Real> diff = point - line.origin; result.lineParameter = Dot(line.direction, diff); result.lineClosest = line.origin + result.lineParameter*line.direction; diff = point - result.lineClosest; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } } // ---------------------------------------------- // GteSegment.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) // The segment is represented by (1-t)*P0 + t*P1, where P0 and P1 are the // endpoints of the segment and 0 <= t <= 1. Some algorithms prefer a // centered representation that is similar to how oriented bounding boxes are // defined. This representation is C + s*D, where C = (P0 + P1)/2 is the // center of the segment, D = (P1 - P0)/|P1 - P0| is a unit-length direction // vector for the segment, and |t| <= e. The value e = |P1 - P0|/2 is the // extent (or radius or half-length) of the segment. namespace gte { template <int N, typename Real> class Segment { public: // Construction and destruction. The default constructor sets p0 to // (-1,0,...,0) and p1 to (1,0,...,0). NOTE: If you set p0 and p1; // compute C, D, and e; and then recompute q0 = C-e*D and q1 = C+e*D, // numerical round-off errors can lead to q0 not exactly equal to p0 // and q1 not exactly equal to p1. Segment(); Segment(Vector<N, Real> const& p0, Vector<N, Real> const& p1); Segment(std::array<Vector<N, Real>, 2> const& inP); Segment(Vector<N, Real> const& center, Vector<N, Real> const& direction, Real extent); // Manipulation via the centered form. void SetCenteredForm(Vector<N, Real> const& center, Vector<N, Real> const& direction, Real extent); void GetCenteredForm(Vector<N, Real>& center, Vector<N, Real>& direction, Real& extent) const; // Public member access. std::array<Vector<N, Real>, 2> p; public: // Comparisons to support sorted containers. bool operator==(Segment const& segment) const; bool operator!=(Segment const& segment) const; bool operator< (Segment const& segment) const; bool operator<=(Segment const& segment) const; bool operator> (Segment const& segment) const; bool operator>=(Segment const& segment) const; }; // Template aliases for convenience. template <typename Real> using Segment2 = Segment<2, Real>; template <typename Real> using Segment3 = Segment<3, Real>; template <int N, typename Real> Segment<N, Real>::Segment() { p[1].MakeUnit(0); p[0] = -p[1]; } template <int N, typename Real> Segment<N, Real>::Segment(Vector<N, Real> const& p0, Vector<N, Real> const& p1) { p[0] = p0; p[1] = p1; } template <int N, typename Real> Segment<N, Real>::Segment(std::array<Vector<N, Real>, 2> const& inP) { p = inP; } template <int N, typename Real> Segment<N, Real>::Segment(Vector<N, Real> const& center, Vector<N, Real> const& direction, Real extent) { SetCenteredForm(center, direction, extent); } template <int N, typename Real> void Segment<N, Real>::SetCenteredForm(Vector<N, Real> const& center, Vector<N, Real> const& direction, Real extent) { p[0] = center - extent * direction; p[1] = center + extent * direction; } template <int N, typename Real> void Segment<N, Real>::GetCenteredForm(Vector<N, Real>& center, Vector<N, Real>& direction, Real& extent) const { center = ((Real)0.5)*(p[0] + p[1]); direction = p[1] - p[0]; extent = ((Real)0.5)*Normalize(direction); } template <int N, typename Real> bool Segment<N, Real>::operator==(Segment const& segment) const { return p == segment.p; } template <int N, typename Real> bool Segment<N, Real>::operator!=(Segment const& segment) const { return !operator==(segment); } template <int N, typename Real> bool Segment<N, Real>::operator<(Segment const& segment) const { return p < segment.p; } template <int N, typename Real> bool Segment<N, Real>::operator<=(Segment const& segment) const { return operator<(segment) || operator==(segment); } template <int N, typename Real> bool Segment<N, Real>::operator>(Segment const& segment) const { return !operator<=(segment); } template <int N, typename Real> bool Segment<N, Real>::operator>=(Segment const& segment) const { return !operator<(segment); } } // ---------------------------------------------- // GteDistPointSegment.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) namespace gte { template <int N, typename Real> class DCPQuery<Real, Vector<N, Real>, Segment<N, Real>> { public: struct Result { Real distance, sqrDistance; Real segmentParameter; // t in [0,1] Vector<N, Real> segmentClosest; // (1-t)*p[0] + t*p[1] }; Result operator()(Vector<N, Real> const& point, Segment<N, Real> const& segment); }; // Template aliases for convenience. template <int N, typename Real> using DCPPointSegment = DCPQuery<Real, Vector<N, Real>, Segment<N, Real>>; template <typename Real> using DCPPoint2Segment2 = DCPPointSegment<2, Real>; template <typename Real> using DCPPoint3Segment3 = DCPPointSegment<3, Real>; template <int N, typename Real> typename DCPQuery<Real, Vector<N, Real>, Segment<N, Real>>::Result DCPQuery<Real, Vector<N, Real>, Segment<N, Real>>::operator()( Vector<N, Real> const& point, Segment<N, Real> const& segment) { Result result; // The direction vector is not unit length. The normalization is deferred // until it is needed. Vector<N, Real> direction = segment.p[1] - segment.p[0]; Vector<N, Real> diff = point - segment.p[1]; Real t = Dot(direction, diff); if (t >= (Real)0) { result.segmentParameter = (Real)1; result.segmentClosest = segment.p[1]; } else { diff = point - segment.p[0]; t = Dot(direction, diff); if (t <= (Real)0) { result.segmentParameter = (Real)0; result.segmentClosest = segment.p[0]; } else { Real sqrLength = Dot(direction, direction); if (sqrLength > (Real)0) { t /= sqrLength; result.segmentParameter = t; result.segmentClosest = segment.p[0] + t * direction; } else { result.segmentParameter = (Real)0; result.segmentClosest = segment.p[0]; } } } diff = point - result.segmentClosest; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } } // ---------------------------------------------- // GteCapsule.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) namespace gte { // A capsule is the set of points that are equidistant from a segment, the // common distance called the radius. template <int N, typename Real> class Capsule { public: // Construction and destruction. The default constructor sets the segment // to have endpoints p0 = (-1,0,...,0) and p1 = (1,0,...,0), and the // radius is 1. Capsule(); Capsule(Segment<N, Real> const& inSegment, Real inRadius); // Public member access. Segment<N, Real> segment; Real radius; public: // Comparisons to support sorted containers. bool operator==(Capsule const& capsule) const; bool operator!=(Capsule const& capsule) const; bool operator< (Capsule const& capsule) const; bool operator<=(Capsule const& capsule) const; bool operator> (Capsule const& capsule) const; bool operator>=(Capsule const& capsule) const; }; // Template alias for convenience. template <typename Real> using Capsule3 = Capsule<3, Real>; template <int N, typename Real> Capsule<N, Real>::Capsule() : radius((Real)1) { } template <int N, typename Real> Capsule<N, Real>::Capsule(Segment<N, Real> const& inSegment, Real inRadius) : segment(inSegment), radius(inRadius) { } template <int N, typename Real> bool Capsule<N, Real>::operator==(Capsule const& capsule) const { return segment == capsule.segment && radius == capsule.radius; } template <int N, typename Real> bool Capsule<N, Real>::operator!=(Capsule const& capsule) const { return !operator==(capsule); } template <int N, typename Real> bool Capsule<N, Real>::operator<(Capsule const& capsule) const { if (segment < capsule.segment) { return true; } if (segment > capsule.segment) { return false; } return radius < capsule.radius; } template <int N, typename Real> bool Capsule<N, Real>::operator<=(Capsule const& capsule) const { return operator<(capsule) || operator==(capsule); } template <int N, typename Real> bool Capsule<N, Real>::operator>(Capsule const& capsule) const { return !operator<=(capsule); } template <int N, typename Real> bool Capsule<N, Real>::operator>=(Capsule const& capsule) const { return !operator<(capsule); } } // ---------------------------------------------- // GteContCapsule3.h // ---------------------------------------------- // David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2018/10/05) namespace gte { // Compute the axis of the capsule segment using least-squares fitting. The // radius is the maximum distance from the points to the axis. Hemispherical // caps are chosen as close together as possible. template <typename Real> bool GetContainer(int numPoints, Vector3<Real> const* points, Capsule3<Real>& capsule); // Test for containment of a point by a capsule. template <typename Real> bool InContainer(Vector3<Real> const& point, Capsule3<Real> const& capsule); // Test for containment of a sphere by a capsule. template <typename Real> bool InContainer(Sphere3<Real> const& sphere, Capsule3<Real> const& capsule); // Test for containment of a capsule by a capsule. template <typename Real> bool InContainer(Capsule3<Real> const& testCapsule, Capsule3<Real> const& capsule); // Compute a capsule that contains the input capsules. The returned capsule // is not necessarily the one of smallest volume that contains the inputs. template <typename Real> bool MergeContainers(Capsule3<Real> const& capsule0, Capsule3<Real> const& capsule1, Capsule3<Real>& merge); template <typename Real> bool GetContainer(int numPoints, Vector3<Real> const* points, Capsule3<Real>& capsule) { ApprOrthogonalLine3<Real> fitter; fitter.Fit(numPoints, points); Line3<Real> line = fitter.GetParameters(); DCPQuery<Real, Vector3<Real>, Line3<Real>> plQuery; Real maxRadiusSqr = (Real)0; for (int i = 0; i < numPoints; ++i) { auto result = plQuery(points[i], line); if (result.sqrDistance > maxRadiusSqr) { maxRadiusSqr = result.sqrDistance; } } Vector3<Real> basis[3]; basis[0] = line.direction; ComputeOrthogonalComplement(1, basis); Real minValue = std::numeric_limits<Real>::max(); Real maxValue = -std::numeric_limits<Real>::max(); for (int i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - line.origin; Real uDotDiff = Dot(diff, basis[1]); Real vDotDiff = Dot(diff, basis[2]); Real wDotDiff = Dot(diff, basis[0]); Real discr = maxRadiusSqr - (uDotDiff*uDotDiff + vDotDiff*vDotDiff); Real radical = std::sqrt(std::max(discr, (Real)0)); Real test = wDotDiff + radical; if (test < minValue) { minValue = test; } test = wDotDiff - radical; if (test > maxValue) { maxValue = test; } } Vector3<Real> center = line.origin + (((Real)0.5)*(minValue + maxValue))*line.direction; Real extent; if (maxValue > minValue) { // Container is a capsule. extent = ((Real)0.5)*(maxValue - minValue); } else { // Container is a sphere. extent = (Real)0; } capsule.segment = Segment3<Real>(center, line.direction, extent); capsule.radius = std::sqrt(maxRadiusSqr); return true; } template <typename Real> bool InContainer(Vector3<Real> const& point, Capsule3<Real> const& capsule) { DCPQuery<Real, Vector3<Real>, Segment3<Real>> psQuery; auto result = psQuery(point, capsule.segment); return result.distance <= capsule.radius; } template <typename Real> bool InContainer(Sphere3<Real> const& sphere, Capsule3<Real> const& capsule) { Real rDiff = capsule.radius - sphere.radius; if (rDiff >= (Real)0) { DCPQuery<Real, Vector3<Real>, Segment3<Real>> psQuery; auto result = psQuery(sphere.center, capsule.segment); return result.distance <= rDiff; } return false; } template <typename Real> bool InContainer(Capsule3<Real> const& testCapsule, Capsule3<Real> const& capsule) { Sphere3<Real> spherePosEnd(testCapsule.segment.p[1], testCapsule.radius); Sphere3<Real> sphereNegEnd(testCapsule.segment.p[0], testCapsule.radius); return InContainer<Real>(spherePosEnd, capsule) && InContainer<Real>(sphereNegEnd, capsule); } template <typename Real> bool MergeContainers(Capsule3<Real> const& capsule0, Capsule3<Real> const& capsule1, Capsule3<Real>& merge) { if (InContainer<Real>(capsule0, capsule1)) { merge = capsule1; return true; } if (InContainer<Real>(capsule1, capsule0)) { merge = capsule0; return true; } Vector3<Real> P0, P1, D0, D1; Real extent0, extent1; capsule0.segment.GetCenteredForm(P0, D0, extent0); capsule1.segment.GetCenteredForm(P1, D1, extent1); // Axis of final capsule. Line3<Real> line; // Axis center is average of input axis centers. line.origin = ((Real)0.5)*(P0 + P1); // Axis unit direction is average of input axis unit directions. if (Dot(D0, D1) >= (Real)0) { line.direction = D0 + D1; } else { line.direction = D0 - D1; } Normalize(line.direction); // Cylinder with axis 'line' must contain the spheres centered at the // endpoints of the input capsules. DCPQuery<Real, Vector3<Real>, Line3<Real>> plQuery; Vector3<Real> posEnd0 = capsule0.segment.p[1]; Real radius = plQuery(posEnd0, line).distance + capsule0.radius; Vector3<Real> negEnd0 = capsule0.segment.p[0]; Real tmp = plQuery(negEnd0, line).distance + capsule0.radius; Vector3<Real> posEnd1 = capsule1.segment.p[1]; tmp = plQuery(posEnd1, line).distance + capsule1.radius; if (tmp > radius) { radius = tmp; } Vector3<Real> negEnd1 = capsule1.segment.p[0]; tmp = plQuery(negEnd1, line).distance + capsule1.radius; if (tmp > radius) { radius = tmp; } // Process sphere <posEnd0,r0>. Real rDiff = radius - capsule0.radius; Real rDiffSqr = rDiff*rDiff; Vector3<Real> diff = line.origin - posEnd0; Real k0 = Dot(diff, diff) - rDiffSqr; Real k1 = Dot(diff, line.direction); Real discr = k1*k1 - k0; // assert: k1*k1-k0 >= 0, guard against anyway Real root = std::sqrt(std::max(discr, (Real)0)); Real tPos = -k1 - root; Real tNeg = -k1 + root; // Process sphere <negEnd0,r0>. diff = line.origin - negEnd0; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1*k1 - k0; // assert: k1*k1-k0 >= 0, guard against anyway root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } // Process sphere <posEnd1,r1>. rDiff = radius - capsule1.radius; rDiffSqr = rDiff*rDiff; diff = line.origin - posEnd1; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1*k1 - k0; // assert: k1*k1-k0 >= 0, guard against anyway root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } // Process sphere <negEnd1,r1>. diff = line.origin - negEnd1; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1*k1 - k0; // assert: k1*k1-k0 >= 0, guard against anyway root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } Vector3<Real> center = line.origin + ((Real)0.5)*(tPos + tNeg)*line.direction; Real extent; if (tPos > tNeg) { // Container is a capsule. extent = ((Real)0.5)*(tPos - tNeg); } else { // Container is a sphere. extent = (Real)0; } merge.segment = Segment3<Real>(center, line.direction, extent); merge.radius = radius; return true; } } // ---------------------------------------------- // GteUtil.h // ---------------------------------------------- template<typename Real> gte::Vector3<Real> Convert(const FVector& Vec) { return gte::Vector3<Real>({ Vec.X, Vec.Y, Vec.Z }); } template<typename Real> FVector Convert(const gte::Vector3<Real>& Vec) { return FVector(Vec[0], Vec[1], Vec[2]); }
31.185553
130
0.605444
287f5ec16525f445a908976fb6c7132170ea726c
8,846
h
C
cpp/limax/include/json.h
zhangtongrui/limax_5.16
cb243c50bbce5720da733ba913a271a5452fec04
[ "MIT" ]
null
null
null
cpp/limax/include/json.h
zhangtongrui/limax_5.16
cb243c50bbce5720da733ba913a271a5452fec04
[ "MIT" ]
null
null
null
cpp/limax/include/json.h
zhangtongrui/limax_5.16
cb243c50bbce5720da733ba913a271a5452fec04
[ "MIT" ]
null
null
null
#pragma once namespace limax { namespace json_impl { struct LIMAX_DLL_EXPORT_API JSONException { std::string message; JSONException(int32_t _line); }; class JSONBuilder; class LIMAX_DLL_EXPORT_API JSONMarshal { public: virtual ~JSONMarshal() {} virtual JSONBuilder& marshal(JSONBuilder &jb) const = 0; }; class LIMAX_DLL_EXPORT_API JSONBuilder { friend class JSON; std::string sb; void _append(char c); void _append(int8_t v); void _append(uint8_t v); void _append(int16_t v); void _append(uint16_t v); void _append(int32_t v); void _append(uint32_t v); void _append(int64_t v); void _append(uint64_t v); void _append(float v); void _append(double v); void _append(bool v); void _append(const std::string& v); template<typename II> void _append(II it, II ie, char c0, char c1) { const char* comma = ""; sb.push_back(c0); for (; it != ie; ++it) { sb.append(comma); append(*it); comma = ","; } sb.push_back(c1); } void _append(const char *p); public: JSONBuilder& append(const JSONMarshal& v); JSONBuilder& append(int8_t v); JSONBuilder& append(uint8_t v); JSONBuilder& append(int16_t v); JSONBuilder& append(uint16_t v); JSONBuilder& append(int32_t v); JSONBuilder& append(uint32_t v); JSONBuilder& append(int64_t v); JSONBuilder& append(uint64_t v); JSONBuilder& append(float v); JSONBuilder& append(double v); JSONBuilder& append(bool v); JSONBuilder& append(char v); JSONBuilder& append(const std::string& v); JSONBuilder& append(const char *v); template<typename T, typename A> JSONBuilder& append(const std::vector<T, A>& v) { _append(v.begin(), v.end(), '[', ']'); return *this; } template<typename T, typename A> JSONBuilder& append(const std::list<T, A>& v) { _append(v.begin(), v.end(), '[', ']'); return *this; } template<typename T, typename A> JSONBuilder& append(const std::deque<T, A>& v) { _append(v.begin(), v.end(), '[', ']'); return *this; } template<typename K, typename P, typename A> JSONBuilder& append(const std::set<K, P, A> & v) { _append(v.begin(), v.end(), '[', ']'); return *this; } template<typename K, typename H, typename E, typename A> JSONBuilder& append(const std::unordered_set<K, H, E, A>& v) { _append(v.begin(), v.end(), '[', ']'); return *this; } template<typename K, typename T, typename P, typename A> JSONBuilder& append(const std::map<K, T, P, A>& v) { _append(v.begin(), v.end(), '{', '}'); return *this; } template<typename K, typename V, typename H, typename E, typename A> JSONBuilder& append(const std::unordered_map<K, V, H, E, A>& v) { _append(v.begin(), v.end(), '{', '}'); return *this; } template<typename T1, typename T2> JSONBuilder& append(const std::pair<T1, T2>& v) { sb.push_back('"'); _append(v.first); sb.append("\":"); append(v.second); return *this; } JSONBuilder& begin(); JSONBuilder& end(); JSONBuilder& comma(); JSONBuilder& colon(); JSONBuilder& null(); std::string toString() const; }; class LIMAX_DLL_EXPORT_API JSON : public JSONMarshal { friend class JSONDecoder; struct LIMAX_DLL_EXPORT_API _Object{ virtual ~_Object(){} }; public: typedef std::shared_ptr<_Object> Object; private: struct _String : public _Object, public std::string { _String() {} _String(const char *p) : std::string(p) {} _String(const std::string& p) : std::string(p) {} }; struct _Number : public _String {}; typedef std::shared_ptr<_String> String; typedef std::shared_ptr<_Number> Number; struct StringHash { size_t operator()(const String& a) const { return std::hash<std::string>()(*a); } }; struct StringEqual { bool operator()(const String& a, const String& b) const { return *a == *b; } }; struct _Map : public _Object, public std::unordered_map<String, Object, StringHash, StringEqual> { }; typedef std::shared_ptr<_Map> Map; class _List : public _Object, public std::vector <Object> {}; typedef std::shared_ptr<_List> List; Object data; public: static const Object Undefined; static const Object Null; static const Object True; static const Object False; JSON(Object _data) : data(_data){} private: template<class R> static R cast(Object data) { return std::dynamic_pointer_cast<typename R::element_type>(data); } template<class R> R cast() const { if (R r = cast<R>(data)) return r; throw JSONException(__LINE__); } std::string make_string(const char *p) const; bool tryLong(std::string s, int64_t& r) const; bool tryDouble(std::string s, double& r) const; static JSONBuilder& marshal(JSONBuilder &jb, Object data); public: std::shared_ptr<JSON> get(const std::string& key) const; std::vector<std::string> keySet() const; std::shared_ptr<JSON> get(size_t index) const; std::vector<std::shared_ptr<JSON>> toArray() const; std::string toString() const; bool booleanValue() const; int32_t intValue() const; int64_t longValue() const; double doubleValue() const; bool isUndefined() const; bool isNull() const; bool isBoolean() const; bool isString() const; bool isNumber() const; bool isObject() const; bool isArray() const; JSONBuilder& marshal(JSONBuilder &jb) const; static std::shared_ptr<JSON> parse(const std::string& text); template<typename T> static std::string stringify(const T& obj) { return JSONBuilder().append(obj).toString(); } static std::string stringify(const char* obj); static std::string stringify(std::shared_ptr<JSON> obj); }; typedef std::function<void(std::shared_ptr<JSON>)> JSONConsumer; class LIMAX_DLL_EXPORT_API JSONDecoder { friend class JSON; private: typedef JSON::Object Object; typedef JSON::Map Map; typedef JSON::List List; typedef JSON::String String; typedef JSON::Number Number; struct _JSONValue { virtual ~_JSONValue() {} virtual bool accept(char c) = 0; virtual void reduce(Object v) {} }; struct _JSONRoot : public _JSONValue { JSONDecoder &decoder; _JSONRoot(JSONDecoder& _decoder); bool accept(char c) override; void reduce(Object v) override; }; typedef std::shared_ptr<_JSONRoot> JSONRoot; typedef std::shared_ptr<_JSONValue> JSONValue; struct _JSONObject : public _JSONValue { JSONDecoder &decoder; JSONValue parent; Map map; String key; int stage = 0; _JSONObject(JSONDecoder& _decoder); bool accept(char c) override; void reduce(Object v) override; }; struct _JSONArray : public _JSONValue { JSONDecoder &decoder; JSONValue parent; List list; int stage = 0; _JSONArray(JSONDecoder& _decoder); bool accept(char c) override; void reduce(Object v) override; }; struct _JSONString : public _JSONValue { JSONDecoder &decoder; JSONValue parent; String sb; int stage = 0; int cp = 0; _JSONString(JSONDecoder& _decoder); bool accept(char c) override; }; struct _JSONNumber : public _JSONValue { JSONDecoder &decoder; JSONValue parent; Number sb; _JSONNumber(JSONDecoder& _decoder); bool accept(char c) override; }; struct _JSONConst : public _JSONValue { JSONDecoder& decoder; JSONValue parent; std::string match; Object value; int stage = 0; _JSONConst(JSONDecoder& _decoder, std::string _match, Object _value); bool accept(char c) override; }; typedef std::shared_ptr<_JSONObject> JSONObject; typedef std::shared_ptr<_JSONArray> JSONArray; typedef std::shared_ptr<_JSONString> JSONString; typedef std::shared_ptr<_JSONNumber> JSONNumber; typedef std::shared_ptr<_JSONConst> JSONConst; JSONConsumer consumer; JSONRoot root; JSONValue current; JSONValue change; std::shared_ptr<JSON> json; void flush(); public: JSONDecoder(JSONConsumer _consumer); JSONDecoder(); void accept(char c); std::shared_ptr<JSON> get(); }; } typedef json_impl::JSONException JSONException; typedef json_impl::JSONBuilder JSONBuilder; typedef json_impl::JSONMarshal JSONMarshal; typedef json_impl::JSONDecoder JSONDecoder; typedef json_impl::JSONConsumer JSONConsumer; typedef json_impl::JSON JSON; } // namespace limax {
28.627832
100
0.635655
4de8989a8741fa21842d78fb2e2bbabc9f9f29d3
16,535
h
C
tools/irstlm/src/ngramtable.h
hihihippp/Kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
19
2015-03-19T10:53:38.000Z
2020-12-17T06:12:32.000Z
tools/irstlm/src/ngramtable.h
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
1
2018-12-18T17:43:44.000Z
2018-12-18T17:43:44.000Z
tools/irstlm/src/ngramtable.h
UdyanSachdev/kaldi
861f838a2aea264a9e4ffa4df253df00a8b1247f
[ "Apache-2.0" ]
47
2015-01-27T06:22:57.000Z
2021-11-11T20:59:04.000Z
// $Id: ngramtable.h 34 2010-06-03 09:19:34Z nicolabertoldi $ /****************************************************************************** IrstLM: IRST Language Model Toolkit, compile LM Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy 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 ******************************************************************************/ #ifndef MF_NGRAMTABLE_H #define MF_NGRAMTABLE_H //Backoff symbol #ifndef BACKOFF_ #define BACKOFF_ "_backoff_" #endif //Dummy symbol #ifndef DUMMY_ #define DUMMY_ "_dummy_" #endif // internal data structure #ifdef MYCODESIZE #define DEFCODESIZE MYCODESIZE #else #define DEFCODESIZE (int)2 #endif #define SHORTSIZE (int)2 #define PTRSIZE (int)sizeof(char *) #define INTSIZE (int)4 #define CHARSIZE (int)1 //Node flags #define FREQ1 (unsigned char) 1 #define FREQ2 (unsigned char) 2 #define FREQ4 (unsigned char) 4 #define INODE (unsigned char) 8 #define LNODE (unsigned char) 16 #define SNODE (unsigned char) 32 #define FREQ6 (unsigned char) 64 #define FREQ3 (unsigned char) 128 typedef char* node; //inodes, lnodes, snodes typedef char* table; //inode table, lnode table, singleton table typedef unsigned char NODETYPE; typedef enum {FIND, //!< search: find an entry ENTER, //!< search: enter an entry DELETE, //!< search: find and remove entry INIT, //!< scan: start scan CONT //!< scan: continue scan } ACTION; typedef enum {COUNT, //!< table: only counters LEAFPROB, //!< table: only probs on leafs FLEAFPROB, //!< table: only probs on leafs and FROZEN LEAFPROB2, //!< table: only probs on leafs LEAFPROB3, //!< table: only probs on leafs LEAFPROB4, //!< table: only probs on leafs LEAFCODE, //!< table: only codes on leafs SIMPLE_I, //!< table: simple interpolated LM SIMPLE_B, //!< table: simple backoff LM SHIFTBETA_I, //!< table: interpolated shiftbeta SHIFTBETA_B, //!< table: backoff shiftbeta MSHIFTBETA_I,//!< table: interp modified shiftbeta MSHIFTBETA_B,//!< table: backoff modified shiftbeta FULL, //!< table: full fledged table } TABLETYPE; class tabletype{ TABLETYPE ttype; public: int CODESIZE; //sizeof word codes long long code_range[7]; //max code for each size //Offsets of internal node fields int WORD_OFFS; //word code position int MSUCC_OFFS; //number of successors int MTAB_OFFS; //pointer to successors int FLAGS_OFFS; //flag table int SUCC1_OFFS; //number of successors with freq=1 int SUCC2_OFFS; //number of successors with freq=2 int BOFF_OFFS; //back-off probability int I_FREQ_OFFS; //frequency offset int I_FREQ_NUM; //number of internal frequencies int L_FREQ_NUM; //number of leaf frequencies int L_FREQ_SIZE; //minimum size for leaf frequencies //Offsets of leaf node fields int L_FREQ_OFFS; //frequency offset TABLETYPE tbtype(){return ttype;} tabletype(TABLETYPE tt,int codesize=DEFCODESIZE){ if (codesize<=4 && codesize>0) CODESIZE=codesize; else{ cerr << "ngramtable wrong codesize\n"; exit(1); } code_range[1]=255; code_range[2]=65535; code_range[3]=16777214; code_range[4]=2147483640; code_range[6]=140737488360000LL; //stay below true limit // code_range[6]=281474977000000LL; //stay below true limit //information which is useful to initialize //LEAFPROB tables L_FREQ_SIZE=FREQ1; WORD_OFFS =0; MSUCC_OFFS =CODESIZE; MTAB_OFFS =MSUCC_OFFS+CODESIZE; FLAGS_OFFS =MTAB_OFFS+PTRSIZE; switch (tt){ case COUNT: SUCC1_OFFS =0; SUCC2_OFFS =0; BOFF_OFFS =0; I_FREQ_OFFS=FLAGS_OFFS+CHARSIZE; I_FREQ_NUM=1; L_FREQ_NUM=1; ttype=tt; break; case FULL:case MSHIFTBETA_B: SUCC1_OFFS =FLAGS_OFFS+CHARSIZE; SUCC2_OFFS =SUCC1_OFFS+CODESIZE; BOFF_OFFS =SUCC2_OFFS+CODESIZE; I_FREQ_OFFS=BOFF_OFFS+INTSIZE; L_FREQ_OFFS=CODESIZE; I_FREQ_NUM=2; L_FREQ_NUM=1; ttype=tt; break; case MSHIFTBETA_I: SUCC1_OFFS =FLAGS_OFFS+CHARSIZE; SUCC2_OFFS =SUCC1_OFFS+CODESIZE; BOFF_OFFS =0; I_FREQ_OFFS=SUCC2_OFFS+CODESIZE; L_FREQ_OFFS=CODESIZE; I_FREQ_NUM=2; L_FREQ_NUM=1; ttype=tt; break; case SIMPLE_I: SUCC1_OFFS = 0; SUCC2_OFFS = 0; BOFF_OFFS = 0; I_FREQ_OFFS= FLAGS_OFFS+CHARSIZE; L_FREQ_OFFS=CODESIZE; I_FREQ_NUM=1; L_FREQ_NUM=1; ttype=tt; break; case SIMPLE_B: SUCC1_OFFS = 0; SUCC2_OFFS = 0; BOFF_OFFS = FLAGS_OFFS+CHARSIZE; I_FREQ_OFFS = BOFF_OFFS+INTSIZE; L_FREQ_OFFS = CODESIZE; I_FREQ_NUM = 1; L_FREQ_NUM = 1; ttype=tt; break; case SHIFTBETA_I: SUCC1_OFFS = FLAGS_OFFS+CHARSIZE; SUCC2_OFFS = 0; BOFF_OFFS = 0; I_FREQ_OFFS= SUCC1_OFFS+CODESIZE; L_FREQ_OFFS=CODESIZE; I_FREQ_NUM=1; L_FREQ_NUM=1; ttype=tt; break; case SHIFTBETA_B: SUCC1_OFFS = FLAGS_OFFS+CHARSIZE; SUCC2_OFFS = 0; BOFF_OFFS = SUCC1_OFFS+CODESIZE; I_FREQ_OFFS = BOFF_OFFS+INTSIZE; L_FREQ_OFFS = CODESIZE; I_FREQ_NUM = 1; L_FREQ_NUM = 1; ttype=tt; break; case LEAFPROB: case FLEAFPROB: SUCC1_OFFS = 0; SUCC2_OFFS = 0; BOFF_OFFS = 0; I_FREQ_OFFS = FLAGS_OFFS+CHARSIZE; I_FREQ_NUM = 0; L_FREQ_NUM = 1; ttype=tt; break; case LEAFPROB2: SUCC1_OFFS =0; SUCC2_OFFS =0; BOFF_OFFS =0; I_FREQ_OFFS=FLAGS_OFFS+CHARSIZE; I_FREQ_NUM=0; L_FREQ_NUM=2; ttype=LEAFPROB; break; case LEAFPROB3: SUCC1_OFFS =0; SUCC2_OFFS =0; BOFF_OFFS =0; I_FREQ_OFFS=FLAGS_OFFS+CHARSIZE; I_FREQ_NUM=0; L_FREQ_NUM=3; ttype=LEAFPROB; break; case LEAFPROB4: SUCC1_OFFS =0; SUCC2_OFFS =0; BOFF_OFFS =0; I_FREQ_OFFS=FLAGS_OFFS+CHARSIZE; I_FREQ_NUM=0; L_FREQ_NUM=4; ttype=LEAFPROB; break; default: assert(tt==COUNT); } L_FREQ_OFFS=CODESIZE; } int inodesize(int s){ return I_FREQ_OFFS + I_FREQ_NUM * s; } int lnodesize(int s){ return L_FREQ_OFFS + L_FREQ_NUM * s; } }; class ngramtable:tabletype{ node tree; // ngram table root int maxlev; // max storable n-gram NODETYPE treeflags; char info[100]; //information put in the header int resolution; //max resolution for probabilities double decay; //decay constant storage* mem; //memory storage class int* memory; // memory load per level int* occupancy; // memory occupied per level long long* mentr; // multiple entries per level long long card; //entries at maxlev int idx[MAX_NGRAM+1]; int oov_code,oov_size,du_code, bo_code; //used by prob; int backoff_state; //used by prob; public: int corrcounts; //corrected counters flag dictionary *dict; // dictionary // filtering dictionary: // if the first word of the ngram does not belong to filterdict // do not insert the ngram dictionary *filterdict; ngramtable(char* filename,int maxl,char* is,char *oovlex, char* filterdictfile, int googletable=0, int dstco=0,char* hmask=NULL,int inplen=0, TABLETYPE tt=FULL,int codesize=DEFCODESIZE); inline char* ngtype(char *str=NULL){if (str!=NULL) strcpy(info,str);return info;} ~ngramtable(); void freetree(node nd); void stat(int level=4); inline long long totfreq(long long v=-1){ return (v==-1?freq(tree,INODE):freq(tree,INODE,v)); } inline long long btotfreq(long long v=-1){ return (v==-1?getfreq(tree,treeflags,1):setfreq(tree,treeflags,v,1)); } inline long long entries(int lev){ return mentr[lev]; } int maxlevel(){return maxlev;} // void savetxt(char *filename,int sz=0); void savetxt(char *filename,int sz=0,int googleformat=0); void loadtxt(char *filename,int googletable=0); void savebin(char *filename,int sz=0); void savebin(mfstream& out); void savebin(mfstream& out,node nd,NODETYPE ndt,int lev,int mlev); void loadbin(const char *filename); void loadbin(mfstream& inp); void loadbin(mfstream& inp,node nd,NODETYPE ndt,int lev); void loadbinold(char *filename); void loadbinold(mfstream& inp,node nd,NODETYPE ndt,int lev); void generate(char *filename); void generate_dstco(char *filename,int dstco); void generate_hmask(char *filename,char* hmask,int inplen=0); void augment(ngramtable* ngt); int scan(ngram& ng,ACTION action=CONT,int maxlev=-1){ return scan(tree,INODE,0,ng,action,maxlev);} int succscan(ngram& h,ngram& ng,ACTION action,int lev){ //return scan(h.link,h.info,h.lev,ng,action,lev); return scan(h.link,h.info,lev-1,ng,action,lev); } double prob(ngram ng); int scan(node nd,NODETYPE ndt,int lev,ngram& ng,ACTION action=CONT,int maxl=-1); void show(); void *search(table *tb,NODETYPE ndt,int lev,int n,int sz,int *w, ACTION action,char **found=(char **)NULL); int mybsearch(char *ar, int n, int size, unsigned char *key, int *idx); int put(ngram& ng); int put(ngram& ng,node nd,NODETYPE ndt,int lev); inline int get(ngram& ng){ return get(ng,maxlev,maxlev); } int get(ngram& ng,int n,int lev); int comptbsize(int n); table *grow(table *tb,NODETYPE ndt,int lev,int n,int sz,NODETYPE oldndt=0); bool check_dictsize_bound(); inline int putmem(char* ptr,int value,int offs,int size){ assert(ptr!=NULL); for (int i=0;i<size;i++) ptr[offs+i]=(value >> (8 * i)) & 0xff; return value; } inline int getmem(char* ptr,int* value,int offs,int size){ assert(ptr!=NULL); *value=ptr[offs] & 0xff; for (int i=1;i<size;i++) *value= *value | ( ( ptr[offs+i] & 0xff ) << (8 *i)); return *value; } inline long putmem(char* ptr,long long value,int offs,int size){ assert(ptr!=NULL); for (int i=0;i<size;i++) ptr[offs+i]=(value >> (8 * i)) & 0xffLL; return value; } inline long getmem(char* ptr,long long* value,int offs,int size){ assert(ptr!=NULL); *value=ptr[offs] & 0xff; for (int i=1;i<size;i++) *value= *value | ( ( ptr[offs+i] & 0xffLL ) << (8 *i)); return *value; } inline void tb2ngcpy(int* wordp,char* tablep,int n=1){ for (int i=0;i<n;i++) getmem(tablep,&wordp[i],i*CODESIZE,CODESIZE); } inline void ng2tbcpy(char* tablep,int* wordp,int n=1){ for (int i=0;i<n;i++) putmem(tablep,wordp[i],i*CODESIZE,CODESIZE); } inline int ngtbcmp(int* wordp,char* tablep,int n=1){ int word; for (int i=0;i<n;i++){ getmem(tablep,&word,i*CODESIZE,CODESIZE); if (wordp[i]!=word) return 1; } return 0; } inline int word(node nd,int value) { putmem(nd,value,WORD_OFFS,CODESIZE); return value; } inline int word(node nd) { int v; getmem(nd,&v,WORD_OFFS,CODESIZE); return v; } unsigned char mtflags(node nd,unsigned char value){ return *(unsigned char *)(nd+FLAGS_OFFS)=value; } unsigned char mtflags(node nd){ return *(unsigned char *)(nd+FLAGS_OFFS); } int update(ngram ng){ if (!get(ng,ng.size,ng.size)) { cerr << "cannot find " << ng << "\n"; exit (1); } freq(ng.link,ng.pinfo,ng.freq); return 1; } long long freq(node nd,NODETYPE ndt,long long value) { int offs=(ndt & LNODE)?L_FREQ_OFFS:I_FREQ_OFFS; if (ndt & FREQ1) putmem(nd,value,offs,1); else if (ndt & FREQ2) putmem(nd,value,offs,2); else if (ndt & FREQ3) putmem(nd,value,offs,3); else if (ndt & FREQ4) putmem(nd,value,offs,4); else putmem(nd,value,offs,6); return value; } long long freq(node nd,NODETYPE ndt) { int offs=(ndt & LNODE)?L_FREQ_OFFS:I_FREQ_OFFS; long long value; if (ndt & FREQ1) getmem(nd,&value,offs,1); else if (ndt & FREQ2) getmem(nd,&value,offs,2); else if (ndt & FREQ3) getmem(nd,&value,offs,3); else if (ndt & FREQ4) getmem(nd,&value,offs,4); else getmem(nd,&value,offs,6); return value; } long long setfreq(node nd,NODETYPE ndt,long long value,int index=0) { int offs=(ndt & LNODE)?L_FREQ_OFFS:I_FREQ_OFFS; if (ndt & FREQ1) putmem(nd,value,offs+index * 1,1); else if (ndt & FREQ2) putmem(nd,value,offs+index * 2,2); else if (ndt & FREQ3) putmem(nd,value,offs+index * 3,3); else if (ndt & FREQ4) putmem(nd,value,offs+index * 4,4); else putmem(nd,value,offs+index * 6,6); return value; } long long getfreq(node nd,NODETYPE ndt,int index=0) { int offs=(ndt & LNODE)?L_FREQ_OFFS:I_FREQ_OFFS; long long value; if (ndt & FREQ1) getmem(nd,&value,offs+ index * 1,1); else if (ndt & FREQ2) getmem(nd,&value,offs+ index * 2,2); else if (ndt & FREQ3) getmem(nd,&value,offs+ index * 3,3); else if (ndt & FREQ4) getmem(nd,&value,offs+ index * 4,4); else getmem(nd,&value,offs+ index * 6,6); return value; } double boff(node nd) { int value=0; getmem(nd,&value,BOFF_OFFS,INTSIZE); return double (value/(double)1000000000.0); } double myround(double x){ long int i=(long int)(x); return (x-i)>0.500?i+1.0:(double)i; } int boff(node nd,double value) { int v=(int)myround(value * 1000000000.0); putmem(nd,v,BOFF_OFFS,INTSIZE); return 1; } int succ2(node nd,int value) { putmem(nd,value,SUCC2_OFFS,CODESIZE); return value; } int succ2(node nd) { int value=0; getmem(nd,&value,SUCC2_OFFS,CODESIZE); return value; } int succ1(node nd,int value) { putmem(nd,value,SUCC1_OFFS,CODESIZE); return value; } int succ1(node nd) { int value=0; getmem(nd,&value,SUCC1_OFFS,CODESIZE); return value; } int msucc(node nd,int value) { putmem(nd,value,MSUCC_OFFS,CODESIZE); return value; } int msucc(node nd) { int value; getmem(nd,&value,MSUCC_OFFS,CODESIZE); return value; } table mtable(node nd) { char v[PTRSIZE];; for (int i=0;i<PTRSIZE;i++) v[i]=nd[MTAB_OFFS+i]; return *(table *)v; } table mtable(node nd,table value) { char *v=(char *)&value; for (int i=0;i<PTRSIZE;i++) nd[MTAB_OFFS+i]=v[i]; return value; } int mtablesz(node nd) { if (mtflags(nd) & LNODE){ if (mtflags(nd) & FREQ1) return lnodesize(1); else if (mtflags(nd) & FREQ2) return lnodesize(2); else if (mtflags(nd) & FREQ3) return lnodesize(3); else if (mtflags(nd) & FREQ4) return lnodesize(4); else return lnodesize(6); } else if (mtflags(nd) & INODE){ if (mtflags(nd) & FREQ1) return inodesize(1); else if (mtflags(nd) & FREQ2) return inodesize(2); else if (mtflags(nd) & FREQ3) return inodesize(3); else if (mtflags(nd) & FREQ4) return inodesize(4); else return inodesize(6); } else{ cerr << "node has wrong flags\n"; exit(1); } } int bo_state(int value=-1){ return (value==-1?backoff_state:backoff_state=value); } }; #endif
23.894509
83
0.610826
d1a98cd8475d482cdb2f0c0e4d63b16d793ed385
2,539
c
C
c/normal/append.c
zhgxun/cNotes
5458182ed6757e0b6db2797eceff8424b302ef0a
[ "Apache-2.0" ]
1
2019-03-01T16:04:12.000Z
2019-03-01T16:04:12.000Z
c/normal/append.c
zhgxun/cNotes
5458182ed6757e0b6db2797eceff8424b302ef0a
[ "Apache-2.0" ]
8
2020-03-04T22:44:00.000Z
2022-03-31T21:11:05.000Z
c/normal/append.c
zhgxun/cNotes
5458182ed6757e0b6db2797eceff8424b302ef0a
[ "Apache-2.0" ]
2
2018-03-12T06:19:06.000Z
2019-07-08T09:01:30.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFSIZE 4096 #define SLEN 81 void append(FILE *source, FILE *dest); char * s_gets(char *st, int n); /** * 把一个文件的内容附加到另一个文件的末尾 */ int main(void) { // fd指向目标文件 fs指向源文件 FILE *fd, *fs; // 附加文件的个数 int files = 0; // 目标文件和源文件必须是当前目录下存在的文件 char file_dest[SLEN]; char file_src[SLEN]; int ch; puts("Enter name of destination(target) file:"); // 读取待添加存储内容文件名,比如test,将源文件名存入file_dest中 s_gets(file_dest, SLEN); // 以追加方式打开文件 if ((fd = fopen(file_dest, "a+")) == NULL) { fprintf(stderr, "Can't open %s\n", file_dest); exit(EXIT_FAILURE); } // _IOFBF full buffering 为文件打开设置一个缓冲区 if (setvbuf(fd, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't create output buffer\n", stderr); exit(EXIT_FAILURE); } puts("Enter name of first source file (empty line to quit): "); // 待追加进来的源文件名 while (s_gets(file_src, SLEN) && file_src[0] != '\0') { // 如果输入的是同一个文件,不需要文件自身进行追加操作 if (strcmp(file_src, file_dest) == 0) { fputs("Can't append file to itself\n", stderr); // 读取源文件 } else if ((fs = fopen(file_src, "r")) == NULL) { fprintf(stderr, "Can't open %s\n", file_src); } else { if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't create input buffer\n", stderr); continue; } } // 将读取出来的源文件内容追加到目标文件中 append(fs, fd); // 检查文件流是否存在错误 if (ferror(fs) != 0) { fprintf(stderr, "Error in reading file %s\n", file_src); } if (ferror(fd) != 0) { fprintf(stderr, "Error in writing file %s\n", file_dest); } // 关闭源文件句柄 fclose(fs); // 保存读取的源文件数量 files++; printf("File %s appended.\n", file_src); puts("Next file (empty line to quit): "); } printf("Done appending. %d files appended.\n", files); // 移动文件指针至文件开始处,读取目标文件追加后的内容 rewind(fd); printf("%s content: \n", file_dest); while ((ch = getc(fd)) != EOF) { putchar(ch); } puts("Done displaying."); // 关闭目标文件 fclose(fd); return 0; } /** * 将源文件内容追加到目标文件中 */ void append(FILE *source, FILE *dest) { size_t bytes; // 静态存储区,一次性读取BUFSIZE个字符 static char temp[BUFSIZE]; // 返回成功读取字符的数量 while ((bytes = fread(temp, sizeof(char), BUFSIZE, source)) > 0) { fwrite(temp, sizeof(char), bytes, dest); } }
24.892157
70
0.551398
9e69cc85d08bbb4b4e550f30e584ad961fa1a0cf
17,710
h
C
src/ic/ic.h
ADVAN-ELAA-8QM-PRC1/platform-external-v8
d424a9e93b8e25ab0e3ac5aead27a5fac0795a1b
[ "BSD-3-Clause" ]
22
2016-07-28T03:25:31.000Z
2022-02-19T02:51:14.000Z
src/ic/ic.h
ADVAN-ELAA-8QM-PRC1/platform-external-v8
d424a9e93b8e25ab0e3ac5aead27a5fac0795a1b
[ "BSD-3-Clause" ]
10
2016-09-30T14:57:49.000Z
2017-06-30T12:56:01.000Z
src/ic/ic.h
ADVAN-ELAA-8QM-PRC1/platform-external-v8
d424a9e93b8e25ab0e3ac5aead27a5fac0795a1b
[ "BSD-3-Clause" ]
23
2016-08-03T17:43:32.000Z
2021-03-04T17:09:00.000Z
// Copyright 2012 the V8 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. #ifndef V8_IC_H_ #define V8_IC_H_ #include "src/ic/ic-state.h" #include "src/macro-assembler.h" #include "src/messages.h" namespace v8 { namespace internal { // // IC is the base class for LoadIC, StoreIC, KeyedLoadIC, and KeyedStoreIC. // class IC { public: // Alias the inline cache state type to make the IC code more readable. typedef InlineCacheState State; // The IC code is either invoked with no extra frames on the stack // or with a single extra frame for supporting calls. enum FrameDepth { NO_EXTRA_FRAME = 0, EXTRA_CALL_FRAME = 1 }; // Construct the IC structure with the given number of extra // JavaScript frames on the stack. IC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL); virtual ~IC() {} State state() const { return state_; } inline Address address() const; // Compute the current IC state based on the target stub, receiver and name. void UpdateState(Handle<Object> receiver, Handle<Object> name); bool RecomputeHandlerForName(Handle<Object> name); void MarkRecomputeHandler(Handle<Object> name) { DCHECK(RecomputeHandlerForName(name)); old_state_ = state_; state_ = RECOMPUTE_HANDLER; } // Clear the inline cache to initial state. static void Clear(Isolate* isolate, Address address, Address constant_pool); #ifdef DEBUG bool IsLoadStub() const { return kind_ == Code::LOAD_IC || kind_ == Code::LOAD_GLOBAL_IC || kind_ == Code::KEYED_LOAD_IC; } bool IsStoreStub() const { return kind_ == Code::STORE_IC || kind_ == Code::KEYED_STORE_IC; } bool IsCallStub() const { return kind_ == Code::CALL_IC; } #endif static inline Handle<Map> GetHandlerCacheHolder(Handle<Map> receiver_map, bool receiver_is_holder, Isolate* isolate, CacheHolderFlag* flag); static inline Handle<Map> GetICCacheHolder(Handle<Map> receiver_map, Isolate* isolate, CacheHolderFlag* flag); static bool IsCleared(FeedbackNexus* nexus) { InlineCacheState state = nexus->StateFromFeedback(); return !FLAG_use_ic || state == UNINITIALIZED || state == PREMONOMORPHIC; } static bool ICUseVector(Code::Kind kind) { return kind == Code::LOAD_IC || kind == Code::LOAD_GLOBAL_IC || kind == Code::KEYED_LOAD_IC || kind == Code::CALL_IC || kind == Code::STORE_IC || kind == Code::KEYED_STORE_IC; } // The ICs that don't pass slot and vector through the stack have to // save/restore them in the dispatcher. static bool ShouldPushPopSlotAndVector(Code::Kind kind); static InlineCacheState StateFromCode(Code* code); static inline bool IsHandler(Object* object); protected: Address fp() const { return fp_; } Address pc() const { return *pc_address_; } Isolate* isolate() const { return isolate_; } // Get the shared function info of the caller. SharedFunctionInfo* GetSharedFunctionInfo() const; // Get the code object of the caller. Code* GetCode() const; inline bool AddressIsDeoptimizedCode() const; inline static bool AddressIsDeoptimizedCode(Isolate* isolate, Address address); // Set the call-site target. inline void set_target(Code* code); bool is_vector_set() { return vector_set_; } bool UseVector() const { bool use = ICUseVector(kind()); // If we are supposed to use the nexus, verify the nexus is non-null. DCHECK(!use || nexus_ != nullptr); return use; } // Configure for most states. void ConfigureVectorState(IC::State new_state, Handle<Object> key); // Configure the vector for MONOMORPHIC. void ConfigureVectorState(Handle<Name> name, Handle<Map> map, Handle<Object> handler); // Configure the vector for POLYMORPHIC. void ConfigureVectorState(Handle<Name> name, MapHandleList* maps, List<Handle<Object>>* handlers); // Configure the vector for POLYMORPHIC with transitions (only for element // keyed stores). void ConfigureVectorState(MapHandleList* maps, MapHandleList* transitioned_maps, CodeHandleList* handlers); char TransitionMarkFromState(IC::State state); void TraceIC(const char* type, Handle<Object> name); void TraceIC(const char* type, Handle<Object> name, State old_state, State new_state); MaybeHandle<Object> TypeError(MessageTemplate::Template, Handle<Object> object, Handle<Object> key); MaybeHandle<Object> ReferenceError(Handle<Name> name); // Access the target code for the given IC address. static inline Code* GetTargetAtAddress(Address address, Address constant_pool); static inline void SetTargetAtAddress(Address address, Code* target, Address constant_pool); // As a vector-based IC, type feedback must be updated differently. static void OnTypeFeedbackChanged(Isolate* isolate, Code* host); static void PostPatching(Address address, Code* target, Code* old_target); void TraceHandlerCacheHitStats(LookupIterator* lookup); // Compute the handler either by compiling or by retrieving a cached version. Handle<Object> ComputeHandler(LookupIterator* lookup, Handle<Object> value = Handle<Code>::null()); virtual Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) { UNREACHABLE(); return Handle<Code>::null(); } virtual Handle<Object> CompileHandler(LookupIterator* lookup, Handle<Object> value, CacheHolderFlag cache_holder) { UNREACHABLE(); return Handle<Object>::null(); } void UpdateMonomorphicIC(Handle<Object> handler, Handle<Name> name); bool UpdatePolymorphicIC(Handle<Name> name, Handle<Object> code); void UpdateMegamorphicCache(Map* map, Name* name, Object* code); StubCache* stub_cache(); void CopyICToMegamorphicCache(Handle<Name> name); bool IsTransitionOfMonomorphicTarget(Map* source_map, Map* target_map); void PatchCache(Handle<Name> name, Handle<Object> code); Code::Kind kind() const { return kind_; } bool is_keyed() const { return kind_ == Code::KEYED_LOAD_IC || kind_ == Code::KEYED_STORE_IC; } Code::Kind handler_kind() const { if (kind_ == Code::KEYED_LOAD_IC) return Code::LOAD_IC; DCHECK(kind_ == Code::LOAD_IC || kind_ == Code::STORE_IC || kind_ == Code::KEYED_STORE_IC); return kind_; } bool ShouldRecomputeHandler(Handle<String> name); ExtraICState extra_ic_state() const { return extra_ic_state_; } Handle<Map> receiver_map() { return receiver_map_; } void update_receiver_map(Handle<Object> receiver) { if (receiver->IsSmi()) { receiver_map_ = isolate_->factory()->heap_number_map(); } else { receiver_map_ = handle(HeapObject::cast(*receiver)->map()); } } void TargetMaps(MapHandleList* list) { FindTargetMaps(); for (int i = 0; i < target_maps_.length(); i++) { list->Add(target_maps_.at(i)); } } Map* FirstTargetMap() { FindTargetMaps(); return target_maps_.length() > 0 ? *target_maps_.at(0) : NULL; } Handle<TypeFeedbackVector> vector() const { return nexus()->vector_handle(); } FeedbackVectorSlot slot() const { return nexus()->slot(); } State saved_state() const { return state() == RECOMPUTE_HANDLER ? old_state_ : state(); } template <class NexusClass> NexusClass* casted_nexus() { return static_cast<NexusClass*>(nexus_); } FeedbackNexus* nexus() const { return nexus_; } inline Code* get_host(); inline Code* target() const; private: inline Address constant_pool() const; inline Address raw_constant_pool() const; void FindTargetMaps() { if (target_maps_set_) return; target_maps_set_ = true; DCHECK(UseVector()); nexus()->ExtractMaps(&target_maps_); } // Frame pointer for the frame that uses (calls) the IC. Address fp_; // All access to the program counter and constant pool of an IC structure is // indirect to make the code GC safe. This feature is crucial since // GetProperty and SetProperty are called and they in turn might // invoke the garbage collector. Address* pc_address_; // The constant pool of the code which originally called the IC (which might // be for the breakpointed copy of the original code). Address* constant_pool_address_; Isolate* isolate_; bool vector_set_; State old_state_; // For saving if we marked as prototype failure. State state_; Code::Kind kind_; Handle<Map> receiver_map_; MaybeHandle<Object> maybe_handler_; ExtraICState extra_ic_state_; MapHandleList target_maps_; bool target_maps_set_; FeedbackNexus* nexus_; DISALLOW_IMPLICIT_CONSTRUCTORS(IC); }; class CallIC : public IC { public: CallIC(Isolate* isolate, CallICNexus* nexus) : IC(EXTRA_CALL_FRAME, isolate, nexus) { DCHECK(nexus != NULL); } void HandleMiss(Handle<Object> function); static void Clear(Isolate* isolate, Code* host, CallICNexus* nexus); }; class LoadIC : public IC { public: LoadIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL) : IC(depth, isolate, nexus) { DCHECK(nexus != NULL); DCHECK(IsLoadStub()); } bool ShouldThrowReferenceError() const { return kind() == Code::LOAD_GLOBAL_IC && LoadGlobalICState::GetTypeofMode(extra_ic_state()) == NOT_INSIDE_TYPEOF; } // Code generator routines. static void GenerateMiss(MacroAssembler* masm); static void GenerateRuntimeGetProperty(MacroAssembler* masm); static void GenerateNormal(MacroAssembler* masm); MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Object> object, Handle<Name> name); static void Clear(Isolate* isolate, Code* host, LoadICNexus* nexus); protected: virtual Handle<Code> slow_stub() const { return isolate()->builtins()->LoadIC_Slow(); } // Update the inline cache and the global stub cache based on the // lookup result. void UpdateCaches(LookupIterator* lookup); Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) override; Handle<Object> CompileHandler(LookupIterator* lookup, Handle<Object> unused, CacheHolderFlag cache_holder) override; private: // Creates a data handler that represents a load of a field by given index. Handle<Object> SimpleFieldLoad(FieldIndex index); // Creates a data handler that represents a prototype chain check followed // by given Smi-handler that encoded a load from the holder. // Can be used only if GetPrototypeCheckCount() returns non negative value. Handle<Object> LoadFromPrototype(Handle<Map> receiver_map, Handle<JSObject> holder, Handle<Name> name, Handle<Object> smi_handler); // Creates a data handler that represents a load of a non-existent property. Handle<Object> LoadNonExistent(Handle<Map> receiver_map, Handle<Name> name); friend class IC; }; class LoadGlobalIC : public LoadIC { public: LoadGlobalIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL) : LoadIC(depth, isolate, nexus) {} MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Name> name); static void Clear(Isolate* isolate, Code* host, LoadGlobalICNexus* nexus); protected: Handle<Code> slow_stub() const override { return isolate()->builtins()->LoadGlobalIC_Slow(); } }; class KeyedLoadIC : public LoadIC { public: KeyedLoadIC(FrameDepth depth, Isolate* isolate, KeyedLoadICNexus* nexus = NULL) : LoadIC(depth, isolate, nexus) { DCHECK(nexus != NULL); } MUST_USE_RESULT MaybeHandle<Object> Load(Handle<Object> object, Handle<Object> key); // Code generator routines. static void GenerateMiss(MacroAssembler* masm); static void GenerateRuntimeGetProperty(MacroAssembler* masm); static void Clear(Isolate* isolate, Code* host, KeyedLoadICNexus* nexus); protected: // receiver is HeapObject because it could be a String or a JSObject void UpdateLoadElement(Handle<HeapObject> receiver); private: friend class IC; }; class StoreIC : public IC { public: StoreIC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus = NULL) : IC(depth, isolate, nexus) { DCHECK(IsStoreStub()); } LanguageMode language_mode() const { return StoreICState::GetLanguageMode(extra_ic_state()); } // Code generators for stub routines. Only called once at startup. static void GenerateSlow(MacroAssembler* masm); static void GenerateMiss(MacroAssembler* masm); static void GenerateNormal(MacroAssembler* masm); MUST_USE_RESULT MaybeHandle<Object> Store( Handle<Object> object, Handle<Name> name, Handle<Object> value, JSReceiver::StoreFromKeyed store_mode = JSReceiver::CERTAINLY_NOT_STORE_FROM_KEYED); bool LookupForWrite(LookupIterator* it, Handle<Object> value, JSReceiver::StoreFromKeyed store_mode); static void Clear(Isolate* isolate, Code* host, StoreICNexus* nexus); protected: // Stub accessors. Handle<Code> slow_stub() const { switch (language_mode()) { case SLOPPY: return isolate()->builtins()->StoreIC_SlowSloppy(); case STRICT: return isolate()->builtins()->StoreIC_SlowStrict(); default: UNREACHABLE(); return Handle<Code>(); } } // Update the inline cache and the global stub cache based on the // lookup result. void UpdateCaches(LookupIterator* lookup, Handle<Object> value, JSReceiver::StoreFromKeyed store_mode); Handle<Object> GetMapIndependentHandler(LookupIterator* lookup) override; Handle<Object> CompileHandler(LookupIterator* lookup, Handle<Object> value, CacheHolderFlag cache_holder) override; private: Handle<Object> StoreTransition(Handle<Map> receiver_map, Handle<JSObject> holder, Handle<Map> transition, Handle<Name> name); friend class IC; }; enum KeyedStoreCheckMap { kDontCheckMap, kCheckMap }; enum KeyedStoreIncrementLength { kDontIncrementLength, kIncrementLength }; class KeyedStoreIC : public StoreIC { public: KeyedAccessStoreMode GetKeyedAccessStoreMode() { return casted_nexus<KeyedStoreICNexus>()->GetKeyedAccessStoreMode(); } KeyedStoreIC(FrameDepth depth, Isolate* isolate, KeyedStoreICNexus* nexus = NULL) : StoreIC(depth, isolate, nexus) {} MUST_USE_RESULT MaybeHandle<Object> Store(Handle<Object> object, Handle<Object> name, Handle<Object> value); // Code generators for stub routines. Only called once at startup. static void GenerateMiss(MacroAssembler* masm); static void GenerateSlow(MacroAssembler* masm); static void GenerateMegamorphic(MacroAssembler* masm, LanguageMode language_mode); static Handle<Code> ChooseMegamorphicStub(Isolate* isolate, ExtraICState extra_state); static void Clear(Isolate* isolate, Code* host, KeyedStoreICNexus* nexus); protected: void UpdateStoreElement(Handle<Map> receiver_map, KeyedAccessStoreMode store_mode); private: Handle<Map> ComputeTransitionedMap(Handle<Map> map, KeyedAccessStoreMode store_mode); friend class IC; }; // Type Recording BinaryOpIC, that records the types of the inputs and outputs. class BinaryOpIC : public IC { public: explicit BinaryOpIC(Isolate* isolate) : IC(EXTRA_CALL_FRAME, isolate) {} MaybeHandle<Object> Transition(Handle<AllocationSite> allocation_site, Handle<Object> left, Handle<Object> right) WARN_UNUSED_RESULT; }; class CompareIC : public IC { public: CompareIC(Isolate* isolate, Token::Value op) : IC(EXTRA_CALL_FRAME, isolate), op_(op) {} // Update the inline cache for the given operands. Code* UpdateCaches(Handle<Object> x, Handle<Object> y); // Helper function for computing the condition for a compare operation. static Condition ComputeCondition(Token::Value op); private: static bool HasInlinedSmiCode(Address address); bool strict() const { return op_ == Token::EQ_STRICT; } Condition GetCondition() const { return ComputeCondition(op_); } static Code* GetRawUninitialized(Isolate* isolate, Token::Value op); static void Clear(Isolate* isolate, Address address, Code* target, Address constant_pool); Token::Value op_; friend class IC; }; class ToBooleanIC : public IC { public: explicit ToBooleanIC(Isolate* isolate) : IC(EXTRA_CALL_FRAME, isolate) {} Handle<Object> ToBoolean(Handle<Object> object); }; // Helper for BinaryOpIC and CompareIC. enum InlinedSmiCheck { ENABLE_INLINED_SMI_CHECK, DISABLE_INLINED_SMI_CHECK }; void PatchInlinedSmiCode(Isolate* isolate, Address address, InlinedSmiCheck check); } // namespace internal } // namespace v8 #endif // V8_IC_H_
33.605313
80
0.677019
9ec711d38677e53bacc2d3978f1b487761893c5e
618
h
C
src/ADBViewer/src/App/gui/guiPage.h
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
9
2019-05-20T12:06:36.000Z
2022-03-24T19:11:06.000Z
src/ADBViewer/src/App/gui/guiPage.h
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
null
null
null
src/ADBViewer/src/App/gui/guiPage.h
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
3
2020-07-06T04:51:33.000Z
2021-07-26T20:08:02.000Z
#pragma once class guiPage { public: // SDL_Point getoffset(SDL_Rect & r) { return { .x = r.x, .y = r.y }; } SDL_Point getsize(SDL_Rect & r) { return { .x = r.w, .y = r.h }; } SDL_Point getdisplay() { SDL_DisplayMode dm{}; if (SDL_GetCurrentDisplayMode(0, &dm) < 0) return { .x = -1, .y = -1 }; return { .x = dm.w, .y = dm.h }; } SDL_Rect getwindow(SDL_Window *sdlw) { SDL_Rect r{}; SDL_GetWindowPosition(sdlw, &r.x, &r.y); SDL_GetWindowSize(sdlw, &r.w, &r.h); return r; } };
17.657143
50
0.478964
3d19611329286c441e449c55c14bdd8790f253eb
2,197
h
C
lib/sk/other/yaml-cpp/src/setting.h
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
4
2019-02-19T16:48:41.000Z
2022-01-31T07:57:54.000Z
lib/sk/other/yaml-cpp/src/setting.h
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
1
2019-01-30T04:48:35.000Z
2019-01-30T04:48:35.000Z
lib/sk/other/yaml-cpp/src/setting.h
stemkit-collection/stemkit-cpp
dfa77d831f49916ba6d134f407a4dcd0983328f6
[ "MIT" ]
null
null
null
#pragma once #ifndef SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #include <memory> #include <vector> #include "noncopyable.h" namespace SK_YAML { class SettingChangeBase; template <typename T> class Setting { public: Setting(): m_value() {} const T get() const { return m_value; } std::auto_ptr <SettingChangeBase> set(const T& value); void restore(const Setting<T>& oldSetting) { m_value = oldSetting.get(); } private: T m_value; }; class SettingChangeBase { public: virtual ~SettingChangeBase() {} virtual void pop() = 0; }; template <typename T> class SettingChange: public SettingChangeBase { public: SettingChange(Setting<T> *pSetting): m_pCurSetting(pSetting) { // copy old setting to save its state m_oldSetting = *pSetting; } virtual void pop() { m_pCurSetting->restore(m_oldSetting); } private: Setting<T> *m_pCurSetting; Setting<T> m_oldSetting; }; template <typename T> inline std::auto_ptr <SettingChangeBase> Setting<T>::set(const T& value) { std::auto_ptr <SettingChangeBase> pChange(new SettingChange<T> (this)); m_value = value; return pChange; } class SettingChanges: private noncopyable { public: SettingChanges() {} ~SettingChanges() { clear(); } void clear() { restore(); for(setting_changes::const_iterator it=m_settingChanges.begin();it!=m_settingChanges.end();++it) delete *it; m_settingChanges.clear(); } void restore() { for(setting_changes::const_iterator it=m_settingChanges.begin();it!=m_settingChanges.end();++it) (*it)->pop(); } void push(std::auto_ptr <SettingChangeBase> pSettingChange) { m_settingChanges.push_back(pSettingChange.release()); } // like std::auto_ptr - assignment is transfer of ownership SettingChanges& operator = (SettingChanges& rhs) { if(this == &rhs) return *this; clear(); m_settingChanges = rhs.m_settingChanges; rhs.m_settingChanges.clear(); return *this; } private: typedef std::vector <SettingChangeBase *> setting_changes; setting_changes m_settingChanges; }; } #endif // SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66
21.125
99
0.712335
9a632e28fba58f7bd04fe9004797036c56e101ae
187
h
C
DataVault/AMPPreviewController/Example/AMPPreviewControllerExample/TestPreview.h
TheArchitect123/Xcode-Portfolio-Projects
4040dad2b7c982016fe2485a5998f8cd548a3210
[ "MIT" ]
21
2015-02-08T16:25:38.000Z
2021-05-11T06:36:58.000Z
DataVault/AMPPreviewController/Example/AMPPreviewControllerExample/TestPreview.h
TheArchitect123/Xcode-Portfolio-Projects
4040dad2b7c982016fe2485a5998f8cd548a3210
[ "MIT" ]
5
2015-05-14T20:56:18.000Z
2019-11-06T14:23:24.000Z
DataVault/AMPPreviewController/Example/AMPPreviewControllerExample/TestPreview.h
TheArchitect123/Xcode-Portfolio-Projects
4040dad2b7c982016fe2485a5998f8cd548a3210
[ "MIT" ]
22
2015-06-04T05:35:50.000Z
2021-09-01T08:00:32.000Z
#import <Foundation/Foundation.h> #import <QuickLook/QLPreviewItem.h> @interface TestPreview : NSObject <QLPreviewItem> - (NSString *)previewItemTitle; - (NSURL *)previewItemURL; @end
18.7
49
0.764706
3c1779c5514da44d78f1b0f8746a36de093a32bb
3,929
c
C
lib/gotconfig.c
gnohz-gnay/got
a7973c852b152d7e284db431caf42fc2f7f6b835
[ "ISC" ]
1
2020-11-17T16:11:33.000Z
2020-11-17T16:11:33.000Z
lib/gotconfig.c
gnohz-gnay/got
a7973c852b152d7e284db431caf42fc2f7f6b835
[ "ISC" ]
null
null
null
lib/gotconfig.c
gnohz-gnay/got
a7973c852b152d7e284db431caf42fc2f7f6b835
[ "ISC" ]
2
2020-10-23T17:21:36.000Z
2020-10-27T16:35:18.000Z
/* * Copyright (c) 2020 Stefan Sperling <stsp@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <sys/queue.h> #include <sys/uio.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <imsg.h> #include <sha1.h> #include <limits.h> #include "openbsd-compat.h" #include "got_error.h" #include "got_object.h" #include "got_repository.h" #include "got_lib_delta.h" #include "got_lib_object.h" #include "got_lib_privsep.h" #include "got_lib_gotconfig.h" const struct got_error * got_gotconfig_read(struct got_gotconfig **conf, const char *gotconfig_path) { const struct got_error *err = NULL, *child_err = NULL; int fd = -1; int imsg_fds[2] = { -1, -1 }; pid_t pid; struct imsgbuf *ibuf; *conf = calloc(1, sizeof(**conf)); if (*conf == NULL) return got_error_from_errno("calloc"); fd = open(gotconfig_path, O_RDONLY); if (fd == -1) { if (errno == ENOENT) return NULL; return got_error_from_errno2("open", gotconfig_path); } ibuf = calloc(1, sizeof(*ibuf)); if (ibuf == NULL) { err = got_error_from_errno("calloc"); goto done; } if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, imsg_fds) == -1) { err = got_error_from_errno("socketpair"); goto done; } pid = fork(); if (pid == -1) { err = got_error_from_errno("fork"); goto done; } else if (pid == 0) { got_privsep_exec_child(imsg_fds, GOT_PATH_PROG_READ_GOTCONFIG, gotconfig_path); /* not reached */ } if (close(imsg_fds[1]) == -1) { err = got_error_from_errno("close"); goto done; } imsg_fds[1] = -1; imsg_init(ibuf, imsg_fds[0]); err = got_privsep_send_gotconfig_parse_req(ibuf, fd); if (err) goto done; fd = -1; err = got_privsep_send_gotconfig_author_req(ibuf); if (err) goto done; err = got_privsep_recv_gotconfig_str(&(*conf)->author, ibuf); if (err) goto done; err = got_privsep_send_gotconfig_remotes_req(ibuf); if (err) goto done; err = got_privsep_recv_gotconfig_remotes(&(*conf)->remotes, &(*conf)->nremotes, ibuf); if (err) goto done; imsg_clear(ibuf); err = got_privsep_send_stop(imsg_fds[0]); child_err = got_privsep_wait_for_child(pid); if (child_err && err == NULL) err = child_err; done: if (imsg_fds[0] != -1 && close(imsg_fds[0]) == -1 && err == NULL) err = got_error_from_errno("close"); if (imsg_fds[1] != -1 && close(imsg_fds[1]) == -1 && err == NULL) err = got_error_from_errno("close"); if (fd != -1 && close(fd) == -1 && err == NULL) err = got_error_from_errno2("close", gotconfig_path); if (err) { got_gotconfig_free(*conf); *conf = NULL; } free(ibuf); return err; } void got_gotconfig_free(struct got_gotconfig *conf) { int i; if (conf == NULL) return; free(conf->author); for (i = 0; i < conf->nremotes; i++) { free(conf->remotes[i].name); free(conf->remotes[i].url); } free(conf->remotes); free(conf); } const char * got_gotconfig_get_author(const struct got_gotconfig *conf) { return conf->author; } void got_gotconfig_get_remotes(int *nremotes, const struct got_remote_repo **remotes, const struct got_gotconfig *conf) { *nremotes = conf->nremotes; *remotes = conf->remotes; }
23.957317
80
0.692543
d2e6618c485e7946a47d6f23f567d7fb0079e061
2,501
h
C
orbsvcs/FtRtEvent/EventChannel/FtEventServiceInterceptor.h
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/FtRtEvent/EventChannel/FtEventServiceInterceptor.h
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/FtRtEvent/EventChannel/FtEventServiceInterceptor.h
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
// -*- C++ -*- //============================================================================= /** * @file FtEventServiceInterceptor.h * * $Id: FtEventServiceInterceptor.h 935 2008-12-10 21:47:27Z mitza $ * * @author Huang-Ming Huang <hh1@cse.wustl.edu> */ //============================================================================= #ifndef FTEVENTSERVICEINTERCEPTOR_H #define FTEVENTSERVICEINTERCEPTOR_H #include "ace/Hash_Map_Manager_T.h" #include "ace/SString.h" #include "tao/PortableInterceptorC.h" #include "tao/LocalObject.h" #include "tao/ORB.h" #include "orbsvcs/FtRtecEventChannelAdminC.h" #include "tao/PI_Server/PI_Server.h" #include "tao/PI/PI.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL class TAO_FTEC_Event_Channel_Impl; typedef FtRtecEventChannelAdmin::CachedResult CachedRequestInfo; class CachedRequestTable { public: bool is_new_request(const ACE_CString& client_id, CORBA::Long retention_id); int update(const ACE_CString& client_id, CORBA::Long retention_id, const CORBA::Any&); CORBA::Any get_result(const ACE_CString& client_id); void get_state(FtRtecEventChannelAdmin::CachedOptionResults& state); void set_state(const FtRtecEventChannelAdmin::CachedOptionResults& state); private: typedef ACE_Hash_Map_Manager<ACE_CString, CachedRequestInfo, TAO_SYNCH_MUTEX> TableImpl; TableImpl table_; }; class FtEventServiceInterceptor : public PortableInterceptor::ServerRequestInterceptor { public: FtEventServiceInterceptor(); ~FtEventServiceInterceptor(); static FtEventServiceInterceptor* instance(); virtual char * name (void); virtual void destroy (void); virtual void receive_request (PortableInterceptor::ServerRequestInfo_ptr ri); virtual void receive_request_service_contexts ( PortableInterceptor::ServerRequestInfo_ptr); virtual void send_reply (PortableInterceptor::ServerRequestInfo_ptr ri); virtual void send_exception (PortableInterceptor::ServerRequestInfo_ptr ri); virtual void send_other (PortableInterceptor::ServerRequestInfo_ptr); void get_state(FtRtecEventChannelAdmin::CachedOptionResults& state); void set_state(const FtRtecEventChannelAdmin::CachedOptionResults& state); private: PortableInterceptor::Current_var pic(PortableInterceptor::ServerRequestInfo_ptr ri); CORBA::ORB_var orb_; CachedRequestTable request_table_; }; TAO_END_VERSIONED_NAMESPACE_DECL #endif
29.77381
91
0.739304
fdbcc7bdd218d41816ae849f734652c527a2595c
1,473
h
C
shill/cellular/mm1_modem_modem3gpp_proxy_interface.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
shill/cellular/mm1_modem_modem3gpp_proxy_interface.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
shill/cellular/mm1_modem_modem3gpp_proxy_interface.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SHILL_CELLULAR_MM1_MODEM_MODEM3GPP_PROXY_INTERFACE_H_ #define SHILL_CELLULAR_MM1_MODEM_MODEM3GPP_PROXY_INTERFACE_H_ #include <string> #include "shill/callbacks.h" namespace shill { class Error; namespace mm1 { // These are the methods that a // org.freedesktop.ModemManager1.Modem.Modem3gpp proxy must support. // The interface is provided so that it can be mocked in tests. // All calls are made asynchronously. Call completion is signalled via // the callbacks passed to the methods. class ModemModem3gppProxyInterface { public: virtual ~ModemModem3gppProxyInterface() = default; virtual void Register(const std::string& operator_id, Error* error, const ResultCallback& callback, int timeout) = 0; virtual void Scan(Error* error, const KeyValueStoresCallback& callback, int timeout) = 0; virtual void SetInitialEpsBearerSettings(const KeyValueStore& properties, Error* error, const ResultCallback& callback, int timeout) = 0; }; } // namespace mm1 } // namespace shill #endif // SHILL_CELLULAR_MM1_MODEM_MODEM3GPP_PROXY_INTERFACE_H_
34.255814
75
0.660557
fdbd135d49f60233cc88c6a53aaeb67b3a52a613
15,867
c
C
libjr/io/mailhost.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
libjr/io/mailhost.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
libjr/io/mailhost.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
#define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include <sys/types.h> #include <string.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> #include "jr/io.h" #include "jr/alist.h" #include "jr/string.h" #include "jr/malloc.h" #include "jr/inetlib.h" #include "jr/mail.h" #include "jr/misc.h" #include "jr/nettype.h" #include "mailproj.h" #define MAX_RESPONSE_SIZE 8192 #ifndef HFIXEDSZ # define HFIXEDSZ 12 /* sizeof (HEADER) */ #endif #ifndef INT16SZ # define INT16SZ 2 /* from sendmail code */ #endif #ifndef INT32SZ # define INT32SZ 4 /* from sendmail code */ #endif jr_int jr_MailGetMailExchanger (host_name, smtp_server_name, smtp_server_name_length, error_buf) const char * host_name; char * smtp_server_name; jr_int smtp_server_name_length; char * error_buf; { jr_MX_EntryListType mx_entry_list[1]; jr_MX_EntryType * mx_entry_ptr; jr_int status; jr_MX_EntryListInit (mx_entry_list); status = jr_MX_EntryListLoadHostNameInfo (mx_entry_list, host_name, error_buf); if (status != 0) { goto return_status; } jr_MX_EntryListSortByPreference (mx_entry_list); mx_entry_ptr = jr_MX_EntryListFirstEntryPtr (mx_entry_list); strncpy (smtp_server_name, jr_MX_EntryName (mx_entry_ptr), smtp_server_name_length); smtp_server_name [smtp_server_name_length - 1] = 0; status = 0; return_status : { jr_MX_EntryListUndo (mx_entry_list); } return status; } void jr_MX_EntryListInit (mx_entry_list) jr_MX_EntryListType * mx_entry_list; { jr_AListInit (mx_entry_list->list_field, sizeof (jr_MX_EntryType)); } void jr_MX_EntryListUndo (mx_entry_list) jr_MX_EntryListType * mx_entry_list; { jr_MX_EntryType * mx_entry_ptr; jr_AListForEachElementPtr (mx_entry_list->list_field, mx_entry_ptr) { jr_MX_EntryUndo (mx_entry_ptr); } jr_AListUndo (mx_entry_list->list_field); } void jr_MX_EntryListAddEntry (mx_entry_list, mx_name, mx_preference) jr_MX_EntryListType * mx_entry_list; const char * mx_name; jr_int mx_preference; { jr_MX_EntryType * mx_entry_ptr; mx_entry_ptr = jr_AListNewTailPtr (mx_entry_list->list_field); jr_MX_EntryInit (mx_entry_ptr, mx_name, mx_preference); } void jr_MX_EntryListSetInetAddress (mx_entry_list, mx_name, inet_addr_number) jr_MX_EntryListType * mx_entry_list; const char * mx_name; jr_int inet_addr_number; { jr_MX_EntryType * mx_entry_ptr; jr_MX_EntryListForEachEntryPtr (mx_entry_list, mx_entry_ptr) { if (strcasecmp (mx_name, jr_MX_EntryName (mx_entry_ptr)) == 0) { jr_MX_EntrySetInetAddrNumber (mx_entry_ptr, inet_addr_number); } } } jr_int jr_MX_EntryListLoadHostNameInfo (mx_entry_list, host_name, error_buf) jr_MX_EntryListType * mx_entry_list; const char * host_name; char * error_buf; { unsigned char * response_buffer = 0; unsigned jr_int max_response_length = MAX_RESPONSE_SIZE; unsigned jr_int response_length; char * tmp_name_ptr = 0; HEADER * header_ptr; unsigned char * curr_ptr; unsigned char * end_ptr; jr_int answer_type; jr_int answer_length; jr_int num_question_entries; jr_int num_answer_entries; jr_int mx_preference; jr_int j; jr_int status; if (max_response_length < sizeof (HEADER)) { max_response_length = sizeof (HEADER); } response_buffer = jr_malloc (max_response_length); tmp_name_ptr = jr_malloc (max_response_length); status = res_query (host_name, C_IN, T_MX, response_buffer, max_response_length); if (status < 0) { jr_esprintf (error_buf, "couldn't get MX info for '%.32s", host_name); goto return_status; } response_length = status; if (response_length > max_response_length) { jr_esprintf (error_buf, "res_query() response length %d > max. of %d passed in!", response_length, max_response_length ); status = jr_INET_SYSTEM_ERROR; goto return_status; } header_ptr = (void *) response_buffer; num_question_entries = jr_ntohs (header_ptr->qdcount); num_answer_entries = jr_ntohs (header_ptr->ancount); curr_ptr = response_buffer + HFIXEDSZ; end_ptr = response_buffer + response_length; for (j=0; j < num_question_entries; j++) { status = dn_skipname(curr_ptr, end_ptr); if (status < 0) { status = jr_INET_HOST_NOT_FOUND; jr_esprintf (error_buf, "no MX entries found"); goto return_status; } curr_ptr += status + QFIXEDSZ; } for (j=0; j < num_answer_entries; j++) { if (curr_ptr >= end_ptr) { break; } status = dn_expand (response_buffer, end_ptr, curr_ptr, tmp_name_ptr, max_response_length); if (status < 0) { break; } curr_ptr += status; GETSHORT (answer_type, curr_ptr); curr_ptr += INT16SZ + INT32SZ; /* * Skip over the 'class' value and the 'ttl' value * Class is: C_IN, C_CHAOS, C_HS, C_HESIOD, C_ANY, C_NONE. * (from 'bind' source, lib/resolv/res_debug.c, * def. for 'struct res_sym __p_class_syms[]' array. */ GETSHORT (answer_length, curr_ptr); switch (answer_type) { /* * Look in source for 'bind', function Print_rr() in bin/nslookup/debug.c * for code to interpret each type of nameserver record. */ case T_A : { jr_int inet_addr_number; GETLONG (inet_addr_number, curr_ptr); jr_MX_EntryListSetInetAddress (mx_entry_list, tmp_name_ptr, inet_addr_number); /* * tmp_name_ptr contains the name of the mx entry with this address */ curr_ptr += answer_length; break; } case T_MX : { GETSHORT (mx_preference, curr_ptr); status = dn_expand ( response_buffer, end_ptr, curr_ptr, tmp_name_ptr, max_response_length ); if (status < 0) { goto return_list; } curr_ptr += status; jr_MX_EntryListAddEntry (mx_entry_list, tmp_name_ptr, mx_preference); break; } default : { curr_ptr += answer_length; break; } } } return_list : if (jr_MX_EntryListIsEmpty (mx_entry_list)) { status = jr_INET_HOST_NOT_FOUND; jr_esprintf (error_buf, "no MX entries found"); goto return_status; } status = 0; return_status : { if (response_buffer) { jr_free (response_buffer); } if (tmp_name_ptr) { jr_free (tmp_name_ptr); } } return status; } jr_int jr_MX_EntryListSetInetAddrNumbers (mx_entry_list, error_buf) jr_MX_EntryListType * mx_entry_list; char * error_buf; { jr_MX_EntryType * mx_entry_ptr; struct sockaddr_in sockaddr_info[1] ; jr_int status ; jr_MX_EntryListForEachEntryPtr (mx_entry_list, mx_entry_ptr) { if (jr_MX_EntryInetAddrNumber (mx_entry_ptr) == 0) { status = jr_InetAddressInit ( sockaddr_info, jr_MX_EntryName (mx_entry_ptr), SMTP_PORT, error_buf ); if (status != 0) { jr_esprintf (error_buf, "couldn't get inet address for '%.32s': %s", jr_MX_EntryName (mx_entry_ptr), error_buf ); return status; } jr_MX_EntrySetInetAddrNumber ( mx_entry_ptr, sockaddr_info->sin_addr.s_addr ); } } return 0; } void jr_MX_EntryInit (mx_entry_ptr, mx_name, mx_preference) jr_MX_EntryType * mx_entry_ptr; const char * mx_name; jr_int mx_preference; { memset (mx_entry_ptr, 0, sizeof (*mx_entry_ptr)); mx_entry_ptr->mx_name = jr_strdup (mx_name); mx_entry_ptr->mx_preference = mx_preference; } void jr_MX_EntryUndo (mx_entry_ptr) jr_MX_EntryType * mx_entry_ptr; { jr_free (mx_entry_ptr->mx_name); } jr_int jr_MX_EntryPreferenceCmp (void_ptr_1, void_ptr_2) const void * void_ptr_1; const void * void_ptr_2; { const jr_MX_EntryType * mx_entry_ptr_1 = void_ptr_1; const jr_MX_EntryType * mx_entry_ptr_2 = void_ptr_2; if (mx_entry_ptr_1->mx_preference < mx_entry_ptr_2->mx_preference) { return -1; } if (mx_entry_ptr_1->mx_preference > mx_entry_ptr_2->mx_preference) { return 1; } return 0; } #ifdef __sendmail_original_code /* * This is what the above mail exchanger code was based on. * Stolen from sendmail's getmxrr() */ #include <sysexits.h> #include <netinet/in.h> /* * for EX_OK, etc. constants */ #include <netdb.h> #define RES_UNC_T char * #define SIZE_T size_t #define FALSE 0 #define TRUE (! FALSE) #define MAXPACKET 8192 /* max packet size used internally by BIND */ #define MAXMXHOSTS 100 #define MXHOSTBUFSIZE (128 * MAXMXHOSTS) #define MAXSHORTSTR 203 #define tTd(flag, level) 0 /* JR - for diagnostic levels */ #define sm_gethostbyname(n) gethostbyname (n) #define UseNameServer 1 #define HasWildcardMX 0 /* don't use MX records when canonifying */ #define ConfigLevel 8 /* JR - the config file level, refers to sendmail version? */ static char * FallBackMX; static char * MyHostName; static jr_int TryNullMXList = 0; static char MXHostBuf[MXHOSTBUFSIZE]; #define syserr printf typedef union { HEADER qb1; /* JR - declared in arpa/nameser.h */ u_char qb2[MAXPACKET]; } querybuf; typedef jr_int bool; extern int h_errno; extern int res_query(), res_search(); extern int mxrand __P((char *)); jr_int getmxrr(host, mxhosts, droplocalhost, rcode) char * host; char ** mxhosts; jr_int droplocalhost; jr_int * rcode; { unsigned char * eom; unsigned char * cp; jr_int i; jr_int j; jr_int n; jr_int nmx = 0; char * bp; HEADER * hp; querybuf answer; jr_int ancount; jr_int qdcount; jr_int buflen; jr_int seenlocal = FALSE; unsigned jr_short pref; unsigned jr_short type; unsigned jr_short localpref = 256; char * fallbackMX = FallBackMX; jr_int trycanon = FALSE; jr_int (*resfunc)(); unsigned jr_short prefer[MAXMXHOSTS]; jr_int weight[MAXMXHOSTS]; if (tTd(8, 2)) { printf("getmxrr(%s, droplocalhost=%d)\n", host, droplocalhost); } if ( fallbackMX != NULL && droplocalhost && wordinclass(fallbackMX, 'w')) { /* don't use fallback for this pass */ fallbackMX = NULL; } *rcode = EX_OK; /* efficiency hack -- numeric or non-MX lookups */ if (host[0] == '[') { goto punt; } /* ** If we don't have MX records in our host switch, don't ** try for MX records. Note that this really isn't "right", ** since we might be set up to try NIS first and then DNS; ** if the host is found in NIS we really shouldn't be doing ** MX lookups. However, that should be a degenerate case. */ if (!UseNameServer) { goto punt; } if (HasWildcardMX && ConfigLevel >= 6) { resfunc = res_query; } else { resfunc = res_search; } errno = 0; n = (*resfunc)(host, C_IN, T_MX, (u_char *) &answer, sizeof(answer)); if (n < 0) { if (tTd(8, 1)) { printf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n", (host == NULL) ? "<NULL>" : host, errno, h_errno ); } switch (h_errno) { case NO_DATA: trycanon = TRUE; /* fall through */ case NO_RECOVERY: /* no MX data on this host */ goto punt; case HOST_NOT_FOUND: # if BROKEN_RES_SEARCH case 0: /* Ultrix resolver retns failure w/ h_errno=0 */ # endif /* host doesn't exist in DNS; might be in /etc/hosts */ trycanon = TRUE; *rcode = EX_NOHOST; goto punt; case TRY_AGAIN: case -1: /* couldn't connect to the name server */ if (fallbackMX != NULL) { /* name server is hosed -- push to fallback */ mxhosts[nmx++] = fallbackMX; return nmx; } /* it might come up later; better queue it up */ *rcode = EX_TEMPFAIL; break; default: syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)\n", host, h_errno ); *rcode = EX_OSERR; break; } /* irreconcilable differences */ return (-1); } /* avoid problems after truncation in tcp packets */ if (n > sizeof(answer)) { n = sizeof(answer); } # ifdef _garbage__ unsigned qdcount :16; /* number of question entries */ unsigned ancount :16; /* number of answer entries */ unsigned nscount :16; /* number of authority entries */ unsigned arcount :16; /* number of resource entries */ # endif /* find first satisfactory answer */ hp = (HEADER *)&answer; cp = (u_char *)&answer + HFIXEDSZ; eom = (u_char *)&answer + n; qdcount = jr_ntohs(hp->qdcount); ancount = jr_ntohs(hp->ancount); for (j=0; j < qdcount; j++; cp += n + QFIXEDSZ) { if ((n = dn_skipname(cp, eom)) < 0) { goto punt; } } buflen = sizeof(MXHostBuf) - 1; bp = MXHostBuf; for (j=0; j < ancount; j++) { if (cp >= eom || nmx >= MAXMXHOSTS - 1) { break; } if ((n = dn_expand((u_char *)&answer, eom, cp, (RES_UNC_T) bp, buflen)) < 0) { break; } cp += n; GETSHORT(type, cp); cp += INT16SZ + INT32SZ; GETSHORT(n, cp); if (type != T_MX) { if (tTd(8, 8) || _res.options & RES_DEBUG) { printf("unexpected answer type %d, size %d\n", type, n); } cp += n; continue; } GETSHORT(pref, cp); if ((n = dn_expand((u_char *)&answer, eom, cp, (RES_UNC_T) bp, buflen)) < 0) { break; } cp += n; if (wordinclass(bp, 'w')) { if (tTd(8, 3)) { printf("found localhost (%s) in MX list, pref=%d\n", bp, pref); } if (droplocalhost) { if (!seenlocal || pref < localpref) { localpref = pref; } seenlocal = TRUE; continue; } weight[nmx] = 0; } else { weight[nmx] = mxrand(bp); } prefer[nmx] = pref; mxhosts[nmx++] = bp; n = strlen(bp); bp += n; if (bp[-1] != '.') { *bp++ = '.'; n++; } *bp++ = '\0'; buflen -= n + 1; } /* sort the records */ for (i = 0; i < nmx; i++) { for (j = i + 1; j < nmx; j++) { if ( prefer[i] > prefer[j] || (prefer[i] == prefer[j] && weight[i] > weight[j])) { jr_int temp; char * temp1; temp = prefer[i]; prefer[i] = prefer[j]; prefer[j] = temp; temp1 = mxhosts[i]; mxhosts[i] = mxhosts[j]; mxhosts[j] = temp1; temp = weight[i]; weight[i] = weight[j]; weight[j] = temp; } } if (seenlocal && prefer[i] >= localpref) { /* truncate higher preference part of list */ nmx = i; } } /* delete duplicates from list (yes, some bozos have duplicates) */ for (i = 0; i < nmx - 1; ) { if (strcasecmp(mxhosts[i], mxhosts[i + 1]) != 0) { i++; } else { /* compress out duplicate */ for (j = i + 1; j < nmx; j++) { mxhosts[j] = mxhosts[j + 1]; } nmx--; } } if (nmx == 0) punt: { if ( seenlocal && (!TryNullMXList || sm_gethostbyname(host) == NULL)) { /* ** If we have deleted all MX entries, this is ** an error -- we should NEVER send to a host that ** has an MX, and this should have been caught ** earlier in the config file. ** ** Some sites prefer to go ahead and try the ** A record anyway; that case is handled by ** setting TryNullMXList. I believe this is a ** bad idea, but it's up to you.... */ *rcode = EX_CONFIG; syserr("MX list for %s points back to %s", host, MyHostName); return -1; } if (strlen(host) >= (SIZE_T) sizeof MXHostBuf) { *rcode = EX_CONFIG; syserr("Host name %s too long", shortenstring(host, MAXSHORTSTR)); return -1; } snprintf(MXHostBuf, sizeof MXHostBuf, "%s", host); mxhosts[0] = MXHostBuf; if (host[0] == '[') { register char *p; /* this may be an MX suppression-style address */ p = strchr(MXHostBuf, ']'); if (p != NULL) { *p = '\0'; if (inet_addr(&MXHostBuf[1]) != INADDR_NONE) { nmx++; *p = ']'; } else { trycanon = TRUE; mxhosts[0]++; } } } if (trycanon && getcanonname(mxhosts[0], sizeof MXHostBuf - 2, FALSE)) { bp = &MXHostBuf[strlen(MXHostBuf)]; if (bp[-1] != '.') { *bp++ = '.'; *bp = '\0'; } nmx = 1; } } /* if we have a default lowest preference, include that */ if (fallbackMX != NULL && !seenlocal) { mxhosts[nmx++] = fallbackMX; } return (nmx); } #endif
21.12783
96
0.64839
45e579b518d151d221769949df6510787c100eac
39
h
C
riscv/insns/sltiu.h
qmn/riscv-isa-sim
917b74c2fe8bcef5c12acda72f5f84cc4e13173e
[ "BSD-3-Clause" ]
1
2015-07-19T07:34:32.000Z
2015-07-19T07:34:32.000Z
riscv/insns/sltiu.h
qmn/riscv-isa-sim
917b74c2fe8bcef5c12acda72f5f84cc4e13173e
[ "BSD-3-Clause" ]
null
null
null
riscv/insns/sltiu.h
qmn/riscv-isa-sim
917b74c2fe8bcef5c12acda72f5f84cc4e13173e
[ "BSD-3-Clause" ]
1
2022-01-17T19:58:49.000Z
2022-01-17T19:58:49.000Z
RD = cmp_trunc(RS1) < cmp_trunc(SIMM);
19.5
38
0.692308
a9c2c3dae40375f564423122daaebb9f02e33af8
2,043
h
C
windows/test/rs485drvtestdlg.h
grodansparadis/vscpl1drv-rs484
6ee7bbf91bc5f8c0ad022ea23bd1987a8d311cfd
[ "MIT" ]
1
2022-01-24T20:20:23.000Z
2022-01-24T20:20:23.000Z
windows/test/rs485drvtestdlg.h
grodansparadis/vscpl1drv-rs484
6ee7bbf91bc5f8c0ad022ea23bd1987a8d311cfd
[ "MIT" ]
null
null
null
windows/test/rs485drvtestdlg.h
grodansparadis/vscpl1drv-rs484
6ee7bbf91bc5f8c0ad022ea23bd1987a8d311cfd
[ "MIT" ]
null
null
null
// can232drvTestDlg.h : header file // // Copyright (C) 2000-2020 // Ake Hedman, Grodans Paradis AB, <akhe@grodansparadis.com> #if !defined(AFX_CAN232DRVTESTDLG_H__89C80B00_D749_40AE_9AB7_6DA29FD82BA7__INCLUDED_) #define AFX_CAN232DRVTESTDLG_H__89C80B00_D749_40AE_9AB7_6DA29FD82BA7__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "../../common/can232obj.h" ///////////////////////////////////////////////////////////////////////////// // CCan232drvTestDlg dialog class CCan232drvTestDlg : public CDialog { // Construction public: CCan232drvTestDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CCan232drvTestDlg) enum { IDD = IDD_CAN232DRVTEST_DIALOG }; CString m_strStatus; CString m_strMask; CString m_strCode; CString m_strData0; CString m_strData1; CString m_strData2; CString m_strData3; CString m_strData4; CString m_strData5; CString m_strData6; CString m_strData7; CString m_strDLC; CString m_strCANID; BOOL m_bExteded; CString m_strOpenArg; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCan232drvTestDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; CCAN232Obj m_drvobj; // Generated message map functions //{{AFX_MSG(CCan232drvTestDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnButtonOpen(); afx_msg void OnButtonClose(); afx_msg void OnButtonSend(); afx_msg void OnButtonPoll(); afx_msg void OnButtonFilter(); virtual void OnOK(); virtual void OnCancel(); afx_msg void OnButtonStatus(); afx_msg void OnButtonCheckData(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CAN232DRVTESTDLG_H__89C80B00_D749_40AE_9AB7_6DA29FD82BA7__INCLUDED_)
25.860759
97
0.753793
aaa3f3d130f0067613485232e630a5d373574bd8
322
h
C
headers/3rdparty/NSAttributeDescription-MagicalRecord_DataImport.h
Tatsh-archive/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
1
2015-03-03T13:37:47.000Z
2015-03-03T13:37:47.000Z
headers/3rdparty/NSAttributeDescription-MagicalRecord_DataImport.h
Tatsh/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
null
null
null
headers/3rdparty/NSAttributeDescription-MagicalRecord_DataImport.h
Tatsh/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSAttributeDescription.h" @interface NSAttributeDescription (MagicalRecord_DataImport) - (id)MR_primaryKey; - (id)MR_valueForKeyPath:(id)arg1 fromObjectData:(id)arg2; @end
23
83
0.723602
8024623545e16a868ddd96ee22176e0ccd20fcad
9,463
c
C
src/sys/geom/raid/tr_raid0.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/geom/raid/tr_raid0.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/geom/raid/tr_raid0.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org> * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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 <sys/cdefs.h> __FBSDID("$FreeBSD: head/sys/geom/raid/tr_raid0.c 256610 2013-10-16 09:33:23Z mav $"); #include <sys/param.h> #include <sys/bio.h> #include <sys/endian.h> #include <sys/kernel.h> #include <sys/kobj.h> #include <sys/lock.h> #include <sys/malloc.h> #include <sys/mutex.h> #include <sys/systm.h> #include <geom/geom.h> #include "geom/raid/g_raid.h" #include "g_raid_tr_if.h" static MALLOC_DEFINE(M_TR_RAID0, "tr_raid0_data", "GEOM_RAID RAID0 data"); struct g_raid_tr_raid0_object { struct g_raid_tr_object trso_base; int trso_starting; int trso_stopped; }; static g_raid_tr_taste_t g_raid_tr_taste_raid0; static g_raid_tr_event_t g_raid_tr_event_raid0; static g_raid_tr_start_t g_raid_tr_start_raid0; static g_raid_tr_stop_t g_raid_tr_stop_raid0; static g_raid_tr_iostart_t g_raid_tr_iostart_raid0; static g_raid_tr_iodone_t g_raid_tr_iodone_raid0; static g_raid_tr_kerneldump_t g_raid_tr_kerneldump_raid0; static g_raid_tr_free_t g_raid_tr_free_raid0; static kobj_method_t g_raid_tr_raid0_methods[] = { KOBJMETHOD(g_raid_tr_taste, g_raid_tr_taste_raid0), KOBJMETHOD(g_raid_tr_event, g_raid_tr_event_raid0), KOBJMETHOD(g_raid_tr_start, g_raid_tr_start_raid0), KOBJMETHOD(g_raid_tr_stop, g_raid_tr_stop_raid0), KOBJMETHOD(g_raid_tr_iostart, g_raid_tr_iostart_raid0), KOBJMETHOD(g_raid_tr_iodone, g_raid_tr_iodone_raid0), KOBJMETHOD(g_raid_tr_kerneldump, g_raid_tr_kerneldump_raid0), KOBJMETHOD(g_raid_tr_free, g_raid_tr_free_raid0), { 0, 0 } }; static struct g_raid_tr_class g_raid_tr_raid0_class = { "RAID0", g_raid_tr_raid0_methods, sizeof(struct g_raid_tr_raid0_object), .trc_enable = 1, .trc_priority = 100, .trc_accept_unmapped = 1 }; static int g_raid_tr_taste_raid0(struct g_raid_tr_object *tr, struct g_raid_volume *volume) { struct g_raid_tr_raid0_object *trs; trs = (struct g_raid_tr_raid0_object *)tr; if (tr->tro_volume->v_raid_level != G_RAID_VOLUME_RL_RAID0 || tr->tro_volume->v_raid_level_qualifier != G_RAID_VOLUME_RLQ_NONE) return (G_RAID_TR_TASTE_FAIL); trs->trso_starting = 1; return (G_RAID_TR_TASTE_SUCCEED); } static int g_raid_tr_update_state_raid0(struct g_raid_volume *vol) { struct g_raid_tr_raid0_object *trs; struct g_raid_softc *sc; u_int s; int n, f; sc = vol->v_softc; trs = (struct g_raid_tr_raid0_object *)vol->v_tr; if (trs->trso_stopped) s = G_RAID_VOLUME_S_STOPPED; else if (trs->trso_starting) s = G_RAID_VOLUME_S_STARTING; else { n = g_raid_nsubdisks(vol, G_RAID_SUBDISK_S_ACTIVE); f = g_raid_nsubdisks(vol, G_RAID_SUBDISK_S_FAILED); if (n + f == vol->v_disks_count) { if (f == 0) s = G_RAID_VOLUME_S_OPTIMAL; else s = G_RAID_VOLUME_S_SUBOPTIMAL; } else s = G_RAID_VOLUME_S_BROKEN; } if (s != vol->v_state) { g_raid_event_send(vol, G_RAID_VOLUME_S_ALIVE(s) ? G_RAID_VOLUME_E_UP : G_RAID_VOLUME_E_DOWN, G_RAID_EVENT_VOLUME); g_raid_change_volume_state(vol, s); if (!trs->trso_starting && !trs->trso_stopped) g_raid_write_metadata(sc, vol, NULL, NULL); } return (0); } static int g_raid_tr_event_raid0(struct g_raid_tr_object *tr, struct g_raid_subdisk *sd, u_int event) { struct g_raid_tr_raid0_object *trs; struct g_raid_softc *sc; struct g_raid_volume *vol; int state; trs = (struct g_raid_tr_raid0_object *)tr; vol = tr->tro_volume; sc = vol->v_softc; state = sd->sd_state; if (state != G_RAID_SUBDISK_S_NONE && state != G_RAID_SUBDISK_S_FAILED && state != G_RAID_SUBDISK_S_ACTIVE) { G_RAID_DEBUG1(1, sc, "Promote subdisk %s:%d from %s to ACTIVE.", vol->v_name, sd->sd_pos, g_raid_subdisk_state2str(sd->sd_state)); g_raid_change_subdisk_state(sd, G_RAID_SUBDISK_S_ACTIVE); } if (state != sd->sd_state && !trs->trso_starting && !trs->trso_stopped) g_raid_write_metadata(sc, vol, sd, NULL); g_raid_tr_update_state_raid0(vol); return (0); } static int g_raid_tr_start_raid0(struct g_raid_tr_object *tr) { struct g_raid_tr_raid0_object *trs; struct g_raid_volume *vol; trs = (struct g_raid_tr_raid0_object *)tr; vol = tr->tro_volume; trs->trso_starting = 0; g_raid_tr_update_state_raid0(vol); return (0); } static int g_raid_tr_stop_raid0(struct g_raid_tr_object *tr) { struct g_raid_tr_raid0_object *trs; struct g_raid_volume *vol; trs = (struct g_raid_tr_raid0_object *)tr; vol = tr->tro_volume; trs->trso_starting = 0; trs->trso_stopped = 1; g_raid_tr_update_state_raid0(vol); return (0); } static void g_raid_tr_iostart_raid0(struct g_raid_tr_object *tr, struct bio *bp) { struct g_raid_volume *vol; struct g_raid_subdisk *sd; struct bio_queue_head queue; struct bio *cbp; char *addr; off_t offset, start, length, nstripe, remain; u_int no, strip_size; vol = tr->tro_volume; if (vol->v_state != G_RAID_VOLUME_S_OPTIMAL && vol->v_state != G_RAID_VOLUME_S_SUBOPTIMAL) { g_raid_iodone(bp, EIO); return; } if (bp->bio_cmd == BIO_FLUSH) { g_raid_tr_flush_common(tr, bp); return; } if ((bp->bio_flags & BIO_UNMAPPED) != 0) addr = NULL; else addr = bp->bio_data; strip_size = vol->v_strip_size; /* Stripe number. */ nstripe = bp->bio_offset / strip_size; /* Start position in stripe. */ start = bp->bio_offset % strip_size; /* Disk number. */ no = nstripe % vol->v_disks_count; /* Stripe start position in disk. */ offset = (nstripe / vol->v_disks_count) * strip_size; /* Length of data to operate. */ remain = bp->bio_length; bioq_init(&queue); do { length = MIN(strip_size - start, remain); cbp = g_clone_bio(bp); if (cbp == NULL) goto failure; cbp->bio_offset = offset + start; cbp->bio_length = length; if ((bp->bio_flags & BIO_UNMAPPED) != 0 && bp->bio_cmd != BIO_DELETE) { cbp->bio_ma_offset += (uintptr_t)addr; cbp->bio_ma += cbp->bio_ma_offset / PAGE_SIZE; cbp->bio_ma_offset %= PAGE_SIZE; cbp->bio_ma_n = round_page(cbp->bio_ma_offset + cbp->bio_length) / PAGE_SIZE; } else cbp->bio_data = addr; cbp->bio_caller1 = &vol->v_subdisks[no]; bioq_insert_tail(&queue, cbp); if (++no >= vol->v_disks_count) { no = 0; offset += strip_size; } remain -= length; if (bp->bio_cmd != BIO_DELETE) addr += length; start = 0; } while (remain > 0); while ((cbp = bioq_takefirst(&queue)) != NULL) { sd = cbp->bio_caller1; cbp->bio_caller1 = NULL; g_raid_subdisk_iostart(sd, cbp); } return; failure: while ((cbp = bioq_takefirst(&queue)) != NULL) g_destroy_bio(cbp); if (bp->bio_error == 0) bp->bio_error = ENOMEM; g_raid_iodone(bp, bp->bio_error); } static int g_raid_tr_kerneldump_raid0(struct g_raid_tr_object *tr, void *virtual, vm_offset_t physical, off_t boffset, size_t blength) { struct g_raid_volume *vol; char *addr; off_t offset, start, length, nstripe, remain; u_int no, strip_size; int error; vol = tr->tro_volume; if (vol->v_state != G_RAID_VOLUME_S_OPTIMAL) return (ENXIO); addr = virtual; strip_size = vol->v_strip_size; /* Stripe number. */ nstripe = boffset / strip_size; /* Start position in stripe. */ start = boffset % strip_size; /* Disk number. */ no = nstripe % vol->v_disks_count; /* Stripe tart position in disk. */ offset = (nstripe / vol->v_disks_count) * strip_size; /* Length of data to operate. */ remain = blength; do { length = MIN(strip_size - start, remain); error = g_raid_subdisk_kerneldump(&vol->v_subdisks[no], addr, 0, offset + start, length); if (error != 0) return (error); if (++no >= vol->v_disks_count) { no = 0; offset += strip_size; } remain -= length; addr += length; start = 0; } while (remain > 0); return (0); } static void g_raid_tr_iodone_raid0(struct g_raid_tr_object *tr, struct g_raid_subdisk *sd,struct bio *bp) { struct bio *pbp; pbp = bp->bio_parent; if (pbp->bio_error == 0) pbp->bio_error = bp->bio_error; g_destroy_bio(bp); pbp->bio_inbed++; if (pbp->bio_children == pbp->bio_inbed) { pbp->bio_completed = pbp->bio_length; g_raid_iodone(pbp, bp->bio_error); } } static int g_raid_tr_free_raid0(struct g_raid_tr_object *tr) { return (0); } G_RAID_TR_DECLARE(raid0, "RAID0");
28.16369
86
0.727676
3404b0ee2e7b91b5aa1a3030d6440f65d325ab82
4,707
c
C
day25/api.c
ghosind/HariboteOS
f2e1d3a46e061d68e2bb23f3d5eb25e8147b2d85
[ "MIT" ]
11
2021-06-09T01:11:51.000Z
2022-03-17T12:32:28.000Z
day25/api.c
ghosind/HariboteOS
f2e1d3a46e061d68e2bb23f3d5eb25e8147b2d85
[ "MIT" ]
null
null
null
day25/api.c
ghosind/HariboteOS
f2e1d3a46e061d68e2bb23f3d5eb25e8147b2d85
[ "MIT" ]
null
null
null
#include <stdio.h> #include "api.h" #include "console.h" #include "graphic.h" #include "io.h" #include "sheet.h" #include "task.h" #include "window.h" int *hrb_api(int edi, int esi, int ebp, int esp, int ebx, int edx, int ecx, int eax) { struct Task *task = task_now(); int ds_base = task->ds_base; struct Console *cons = task->cons; struct Shtctl *shtctl = (struct Shtctl *)*((int *)0x0fe4); struct Sheet *sht; char s[12]; int *reg = &eax + 1; int data; switch (edx) { case 1: cons_putchar(cons, eax & 0xff, 1); break; case 2: cons_putstr(cons, (char *)ebx + ds_base); break; case 3: cons_putnstr(cons, (char *)ebx + ds_base, ecx); break; case 4: return &(task->tss.esp0); break; case 5: sht = sheet_alloc(shtctl); sht->task = task; sht->flags |= 0x10; sheet_setbuf(sht, (unsigned char *)(ebx + ds_base), esi, edi, eax); make_window8((unsigned char *)(ebx + ds_base), esi, edi, (char *)(ecx + ds_base), 0); sheet_slide(sht, (shtctl->xsize - esi) / 2, (shtctl->ysize - edi) / 2); sheet_updown(sht, shtctl->top); reg[7] = (int)sht; break; case 6: sht = (struct Sheet *)(ebx & 0xfffffffe); put_fonts8_asc(sht->buf, sht->bxsize, esi, edi, eax, (char *)(ebp + ds_base)); if (!(ebx & 1)) { sheet_refresh(sht, esi, edi, esi + ecx * 8, edi + 16); } break; case 7: sht = (struct Sheet *)(ebx & 0xfffffffe); box_fill8(sht->buf, sht->bxsize, ebp, eax, ecx, esi, edi); if (!(ebx & 1)) { sheet_refresh(sht, eax, ecx, esi + 1, edi + 1); } break; case 8: memman_init((struct MemMan *)(ebx + ds_base)); ecx &= 0xfffffff0; memman_free((struct MemMan *)(ebx + ds_base), eax, ecx); break; case 9: ecx = (ecx + 0x0f) & 0xfffffff0; reg[7] = memman_alloc((struct MemMan *)(ebx + ds_base), ecx); break; case 10: ecx = (ecx + 0x0f) & 0xfffffff0; memman_free((struct MemMan *)(ebx + ds_base), eax, ecx); break; case 11: sht = (struct Sheet *)(ebx & 0xfffffffe); sht->buf[sht->bxsize * edi + esi] = eax; if (!(ebx & 1)) { sheet_refresh(sht, esi, edi, esi + 1, edi + 1); } break; case 12: sht = (struct Sheet *)ebx; sheet_refresh(sht, eax, ecx, esi, edi); break; case 13: sht = (struct Sheet *)(ebx & 0xfffffffe); api_line_win(sht, eax, ecx, esi, edi, ebp); if (!(ebx & 1)) { sheet_refresh(sht, esi, edi, esi + 1, edi + 1); } break; case 14: sheet_free((struct Sheet *)ebx); break; case 15: for (;;) { io_cli(); if (!fifo32_status(&task->fifo)) { if (eax) { task_sleep(task); } else { io_sti(); reg[7] = -1; return 0; } } data = fifo32_get(&task->fifo); io_sti(); if (data <= 1) { timer_init(cons->timer, &task->fifo, 1); timer_set_timer(cons->timer, 50); } if (data == 2) { cons->cur_c = COL8_FFFFFF; } if (data == 3) { cons->cur_c = -1; } if (256 <= data) { reg[7] = data - 256; return 0; } } break; case 16: reg[7] = (int)timer_alloc(); ((struct Timer *)reg[7])->flags2 = 1; break; case 17: timer_init((struct Timer *)ebx, &task->fifo, eax + 256); break; case 18: timer_set_timer((struct Timer *)ebx, eax); break; case 19: timer_free((struct Timer *)ebx); break; case 20: if (!eax) { data = io_in8(0x61); io_out8(0x61, data & 0x0d); } else { data = 1193180000 / eax; io_out8(0x43, 0xb6); io_out8(0x42, data & 0xff); io_out8(0x42, data >> 8); data = io_in8(0x61); io_out8(0x61, (data | 0x03) & 0x0f); } break; default: break; } return 0; } void api_line_win(struct Sheet *sht, int x0, int y0, int x1, int y1, int col) { int dx = x1 - x0; int dy = y1 - y0; int x = x0 << 10; int y = y0 << 10; int len = 0; if (dx < 0) { dx = -dx; } if (dy < 0) { dy = -dy; } if (dx >= dy) { len = dx + 1; if (x0 > x1) { dx = -1024; } else { dx = 1024; } if (y0 <= y1) { dy = ((y1 - y0 + 1) << 10) / len; } else { dy = ((y1 - y0 - 1) << 10) / len; } } else { len = dy + 1; if (y0 > y1) { dy = -1024; } else { dy = 1024; } if (x0 <= x1) { dx = ((x1 - x0 + 1) << 10) / len; } else { dx = ((x1 - x0 - 1) << 10) / len; } } for (int i = 0; i < len; i++) { sht->buf[(y >> 10) * sht->bxsize + (x >> 10)] = col; x += dx; y += dy; } }
22.308057
79
0.499256
437c129e5fc0092b732677af0ec3359c751991c4
569
h
C
lab-7b/part-3/ArrayStats.h
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
lab-7b/part-3/ArrayStats.h
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
lab-7b/part-3/ArrayStats.h
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
#ifndef ARRAYSTATS_H #define ARRAYSTATS_H #include <iostream> #include <string> #include <iomanip> #include <fstream> #include <vector> class ArrayStats { public: ArrayStats(int size); ~ArrayStats() { delete [] numbers; } void setNumber(float value, int index) { numbers[index] = value; }; float getNumber(int index) const { return numbers[index]; }; float getMax() const; float getMin() const; float getAverage() const; private: int size; float * numbers; }; #endif // ARRAYSTATS_H
19.62069
75
0.622144
b7647cca04bd267461f1ab7ffe58708d298822d1
1,449
h
C
src/prod/src/client/ClientServerTransport/MoveNextUpgradeDomainMessageBody.h
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/client/ClientServerTransport/MoveNextUpgradeDomainMessageBody.h
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/client/ClientServerTransport/MoveNextUpgradeDomainMessageBody.h
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Management { namespace ClusterManager { class MoveNextUpgradeDomainMessageBody : public ServiceModel::ClientServerMessageBody { public: MoveNextUpgradeDomainMessageBody() { } explicit MoveNextUpgradeDomainMessageBody( Common::NamingUri const & applicationName, std::wstring const & nextUpgradeDomain) : applicationName_(applicationName) , nextUpgradeDomain_(nextUpgradeDomain) { } __declspec(property(get=get_ApplicationName)) Common::NamingUri const & ApplicationName; Common::NamingUri const & get_ApplicationName() const { return applicationName_; } __declspec(property(get=get_NextUpgradeDomain)) std::wstring const & NextUpgradeDomain; std::wstring const & get_NextUpgradeDomain() { return nextUpgradeDomain_; } FABRIC_FIELDS_02(applicationName_, nextUpgradeDomain_) private: Common::NamingUri applicationName_; std::wstring nextUpgradeDomain_; }; } }
35.341463
100
0.590062
3181a274ec677202b0e5250cd00ee562b4b70064
6,717
h
C
ns3-sat-sim/simulator/contrib/basic-sim/test/core/tcp-optimizer-test.h
kalelpida/hypatia
c10b63592b3229a35dbdc1d5b70b5e80ebc256bd
[ "MIT" ]
1
2022-03-18T15:42:45.000Z
2022-03-18T15:42:45.000Z
ns3-sat-sim/simulator/contrib/basic-sim/test/core/tcp-optimizer-test.h
kalelpida/hypatia
c10b63592b3229a35dbdc1d5b70b5e80ebc256bd
[ "MIT" ]
null
null
null
ns3-sat-sim/simulator/contrib/basic-sim/test/core/tcp-optimizer-test.h
kalelpida/hypatia
c10b63592b3229a35dbdc1d5b70b5e80ebc256bd
[ "MIT" ]
null
null
null
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "ns3/basic-simulation.h" #include "ns3/test.h" #include "ns3/topology-ptop.h" #include "../test-helpers.h" #include "ns3/ipv4-arbiter-routing-helper.h" #include "ns3/traffic-control-layer.h" #include "ns3/tcp-flow-scheduler.h" #include "ns3/tcp-optimizer.h" using namespace ns3; const std::string tcp_optimizer_test_dir = ".tmp-tcp-optimizer-test"; void cleanup_tcp_optimizer_test() { remove_file_if_exists(tcp_optimizer_test_dir + "/config_ns3.properties"); remove_file_if_exists(tcp_optimizer_test_dir + "/topology.properties.temp"); remove_file_if_exists(tcp_optimizer_test_dir + "/tcp_flow_schedule.csv"); remove_file_if_exists(tcp_optimizer_test_dir + "/logs_ns3/finished.txt"); remove_file_if_exists(tcp_optimizer_test_dir + "/logs_ns3/timing_results.txt"); remove_file_if_exists(tcp_optimizer_test_dir + "/logs_ns3/timing_results.csv"); remove_dir_if_exists(tcp_optimizer_test_dir + "/logs_ns3"); remove_dir_if_exists(tcp_optimizer_test_dir); } //////////////////////////////////////////////////////////////////////////////////////// class TcpOptimizerBasicTestCase : public TestCase { public: TcpOptimizerBasicTestCase () : TestCase ("tcp-optimizer basic") {}; void DoRun () { mkdir_if_not_exists(tcp_optimizer_test_dir); std::ofstream config_file(tcp_optimizer_test_dir + "/config_ns3.properties"); config_file << "simulation_end_time_ns=1950000000" << std::endl; config_file << "simulation_seed=123456789" << std::endl; config_file << "topology_ptop_filename=\"topology.properties.temp\"" << std::endl; config_file << "enable_tcp_flow_scheduler=true" << std::endl; config_file << "tcp_flow_schedule_filename=\"tcp_flow_schedule.csv\"" << std::endl; config_file.close(); std::ofstream tcp_flow_schedule_file; tcp_flow_schedule_file.open (tcp_optimizer_test_dir + "/tcp_flow_schedule.csv"); tcp_flow_schedule_file << "0,0,3,1000000,10000,," << std::endl; // Flow 0: 0 -> 3, 1MB, starting at t=10000ns tcp_flow_schedule_file.close(); std::ofstream topology_file; topology_file.open (tcp_optimizer_test_dir + "/topology.properties.temp"); topology_file << "num_nodes=4" << std::endl; topology_file << "num_undirected_edges=4" << std::endl; topology_file << "switches=set(0,1,2,3)" << std::endl; topology_file << "switches_which_are_tors=set(0,3)" << std::endl; topology_file << "servers=set()" << std::endl; topology_file << "undirected_edges=set(0-1,1-3,0-2,2-3)" << std::endl; topology_file << "link_channel_delay_ns=10000" << std::endl; topology_file << "link_device_data_rate_megabit_per_s=100" << std::endl; topology_file << "link_device_queue=drop_tail(100p)" << std::endl; topology_file << "link_interface_traffic_control_qdisc=disabled" << std::endl; topology_file << "all_nodes_are_endpoints=true" << std::endl; topology_file.close(); // Create simulation environment Ptr<BasicSimulation> basicSimulation = CreateObject<BasicSimulation>(tcp_optimizer_test_dir); // Create topology Ptr<TopologyPtop> topology = CreateObject<TopologyPtop>(basicSimulation, Ipv4ArbiterRoutingHelper()); ArbiterEcmpHelper::InstallArbiters(basicSimulation, topology); // Optimize TCP in only the basic sense TcpOptimizer::OptimizeBasic(basicSimulation); // Schedule UDP bursts TcpFlowScheduler tcpFlowScheduler(basicSimulation, topology); // Run simulation basicSimulation->Run(); // Finalize the simulation basicSimulation->Finalize(); cleanup_tcp_optimizer_test(); } }; //////////////////////////////////////////////////////////////////////////////////////// class TcpOptimizerWorstCaseRttTestCase : public TestCase { public: TcpOptimizerWorstCaseRttTestCase () : TestCase ("tcp-optimizer worst-case-rtt") {}; void DoRun () { mkdir_if_not_exists(tcp_optimizer_test_dir); std::ofstream config_file(tcp_optimizer_test_dir + "/config_ns3.properties"); config_file << "simulation_end_time_ns=1950000000" << std::endl; config_file << "simulation_seed=123456789" << std::endl; config_file << "topology_ptop_filename=\"topology.properties.temp\"" << std::endl; config_file << "enable_tcp_flow_scheduler=true" << std::endl; config_file << "tcp_flow_schedule_filename=\"tcp_flow_schedule.csv\"" << std::endl; config_file.close(); std::ofstream tcp_flow_schedule_file; tcp_flow_schedule_file.open (tcp_optimizer_test_dir + "/tcp_flow_schedule.csv"); tcp_flow_schedule_file << "0,0,3,1000000,10000,," << std::endl; // Flow 0: 0 -> 3, 1MB, starting at t=10000ns tcp_flow_schedule_file.close(); std::ofstream topology_file; topology_file.open (tcp_optimizer_test_dir + "/topology.properties.temp"); topology_file << "num_nodes=4" << std::endl; topology_file << "num_undirected_edges=4" << std::endl; topology_file << "switches=set(0,1,2,3)" << std::endl; topology_file << "switches_which_are_tors=set(0,3)" << std::endl; topology_file << "servers=set()" << std::endl; topology_file << "undirected_edges=set(0-1,1-3,0-2,2-3)" << std::endl; topology_file << "link_channel_delay_ns=10000" << std::endl; topology_file << "link_device_data_rate_megabit_per_s=100" << std::endl; topology_file << "link_device_queue=drop_tail(100p)" << std::endl; topology_file << "link_interface_traffic_control_qdisc=disabled" << std::endl; topology_file << "all_nodes_are_endpoints=true" << std::endl; topology_file.close(); // Create simulation environment Ptr<BasicSimulation> basicSimulation = CreateObject<BasicSimulation>(tcp_optimizer_test_dir); // Create topology Ptr<TopologyPtop> topology = CreateObject<TopologyPtop>(basicSimulation, Ipv4ArbiterRoutingHelper()); ArbiterEcmpHelper::InstallArbiters(basicSimulation, topology); // Optimize TCP TcpOptimizer::OptimizeUsingWorstCaseRtt(basicSimulation, topology->GetWorstCaseRttEstimateNs()); // Schedule UDP bursts TcpFlowScheduler tcpFlowScheduler(basicSimulation, topology); // Run simulation basicSimulation->Run(); // Finalize the simulation basicSimulation->Finalize(); cleanup_tcp_optimizer_test(); } }; ////////////////////////////////////////////////////////////////////////////////////////
45.385135
117
0.664731
c8926a8945ac6c84e81ff651a18ed0b2eb8566ef
1,843
c
C
SOFTWARE/A64-TERES/u-boot_new/drivers/serial/lpc32xx_hsuart.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
35
2019-04-26T04:00:10.000Z
2022-03-30T11:37:06.000Z
SOFTWARE/A64-TERES/u-boot_new/drivers/serial/lpc32xx_hsuart.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
4
2016-08-30T11:30:25.000Z
2020-12-27T09:58:07.000Z
SOFTWARE/A64-TERES/u-boot_new/drivers/serial/lpc32xx_hsuart.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
11
2020-01-07T05:39:10.000Z
2021-12-26T07:27:21.000Z
/* * Copyright (C) 2011 Vladimir Zapolskiy <vz@mleia.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/arch/cpu.h> #include <asm/arch/clk.h> #include <asm/arch/uart.h> #include <asm/io.h> #include <serial.h> #include <linux/compiler.h> DECLARE_GLOBAL_DATA_PTR; static struct hsuart_regs *hsuart = (struct hsuart_regs *)HS_UART_BASE; static void lpc32xx_serial_setbrg(void) { u32 div; /* UART rate = PERIPH_CLK / ((HSU_RATE + 1) x 14) */ div = (get_serial_clock() / 14 + gd->baudrate / 2) / gd->baudrate - 1; if (div > 255) div = 255; writel(div, &hsuart->rate); } static int lpc32xx_serial_getc(void) { while (!(readl(&hsuart->level) & HSUART_LEVEL_RX)) /* NOP */; return readl(&hsuart->rx) & HSUART_RX_DATA; } static void lpc32xx_serial_putc(const char c) { if (c == '\n') serial_putc('\r'); writel(c, &hsuart->tx); /* Wait for character to be sent */ while (readl(&hsuart->level) & HSUART_LEVEL_TX) /* NOP */; } static int lpc32xx_serial_tstc(void) { if (readl(&hsuart->level) & HSUART_LEVEL_RX) return 1; return 0; } static int lpc32xx_serial_init(void) { lpc32xx_serial_setbrg(); /* Disable hardware RTS and CTS flow control, set up RX and TX FIFO */ writel(HSUART_CTRL_TMO_16 | HSUART_CTRL_HSU_OFFSET(20) | HSUART_CTRL_HSU_RX_TRIG_32 | HSUART_CTRL_HSU_TX_TRIG_0, &hsuart->ctrl); return 0; } static struct serial_device lpc32xx_serial_drv = { .name = "lpc32xx_serial", .start = lpc32xx_serial_init, .stop = NULL, .setbrg = lpc32xx_serial_setbrg, .putc = lpc32xx_serial_putc, .puts = default_serial_puts, .getc = lpc32xx_serial_getc, .tstc = lpc32xx_serial_tstc, }; void lpc32xx_serial_initialize(void) { serial_register(&lpc32xx_serial_drv); } __weak struct serial_device *default_serial_console(void) { return &lpc32xx_serial_drv; }
20.477778
71
0.705914
c8948b7d5674047a2b6368e86529dc0011364c4c
990
h
C
PrivateFrameworks/OfficeImport/OAITOrientedBounds.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/OfficeImport/OAITOrientedBounds.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/OfficeImport/OAITOrientedBounds.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" __attribute__((visibility("hidden"))) @interface OAITOrientedBounds : NSObject { } + (struct CGRect)axisParallelBoundsOfOrientedBounds:(id)arg1; + (id)relativeOrientedBoundsOfDrawable:(id)arg1; + (id)relativeOrientedBoundsWithAbsoluteOrientedBounds:(id)arg1 parentOrientedBounds:(id)arg2 parentLogicalBounds:(struct CGRect)arg3; + (id)absoluteOrientedBoundsWithRelativeOrientedBounds:(id)arg1 parentOrientedBounds:(id)arg2 parentLogicalBounds:(struct CGRect)arg3; + (struct CGAffineTransform)transformFromBounds:(struct CGRect)arg1 toOrientedBounds:(id)arg2; + (id)adjustedOrientedBoundsWithOrientedBounds:(id)arg1; + (id)absoluteOrientedBoundsOfDrawable:(id)arg1; + (id)adjustedOrientedBoundsWithOrientedBounds:(id)arg1 logicalBounds:(struct CGRect)arg2; + (float)scaleFactorFromLength:(float)arg1 toLength:(float)arg2; @end
38.076923
134
0.79798
4e443dd72c88aa7089b13e6c159158f1203f2d8b
1,858
h
C
code/Modules/Gfx/d3d11/d3d11MeshFactory.h
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
code/Modules/Gfx/d3d11/d3d11MeshFactory.h
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
code/Modules/Gfx/d3d11/d3d11MeshFactory.h
waywardmonkeys/oryol
6b496fa9f5fd7acbae3363e0617cb13d333aa6bf
[ "MIT" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ /** @class Oryol::_priv::d3d11MeshFactory @ingroup _priv @brief D3D11 implementation of MeshFactory */ #include "Resource/ResourceState.h" #include "Gfx/Core/gfxPointers.h" #include "Gfx/Core/Enums.h" #include "Gfx/d3d11/d3d11_decl.h" namespace Oryol { namespace _priv { class mesh; class d3d11MeshFactory { public: /// constructor d3d11MeshFactory(); /// destructor ~d3d11MeshFactory(); /// setup with a pointer to the state wrapper object void Setup(const gfxPointers& ptrs); /// discard the factory void Discard(); /// return true if the object has been setup bool IsValid() const; /// setup resource ResourceState::Code SetupResource(mesh& mesh); /// setup with 'raw' data ResourceState::Code SetupResource(mesh& mesh, const void* data, int32 size); /// discard the resource void DestroyResource(mesh& mesh); /// helper method to setup a mesh object as fullscreen quad ResourceState::Code createFullscreenQuad(mesh& mesh); /// helper method to create empty mesh ResourceState::Code createEmptyMesh(mesh& mesh); /// create from data ResourceState::Code createFromData(mesh& mesh, const void* data, int32 size); private: /// helper method to create vertex or index buffer ID3D11Buffer* createBuffer(const void* vertexData, uint32 vertexDataSize, uint32 d3d11BindFlags, Usage::Code usage); /// helper method to populate vertex and index buffer attributes in mesh object void setupAttrs(mesh& mesh); /// helper method to populate primitive groups array in mesh object void setupPrimGroups(mesh& mesh); gfxPointers pointers; ID3D11Device* d3d11Device; bool isValid; }; } // namespace _priv } // namespace Oryol
29.967742
120
0.673843
0828f678a63a33b046d5670828fe4b6e11e69ef2
233
h
C
BLEDemo/BLEDemo/ViewController.h
CoderHJZhao/HJBluetoothDemo
2fa075b3fd9f53f286ba34ba0438885297074cad
[ "MIT" ]
null
null
null
BLEDemo/BLEDemo/ViewController.h
CoderHJZhao/HJBluetoothDemo
2fa075b3fd9f53f286ba34ba0438885297074cad
[ "MIT" ]
null
null
null
BLEDemo/BLEDemo/ViewController.h
CoderHJZhao/HJBluetoothDemo
2fa075b3fd9f53f286ba34ba0438885297074cad
[ "MIT" ]
null
null
null
// // ViewController.h // BLEDemo // // Created by ZhaoHanjun on 16/4/3. // Copyright © 2016年 https://github.com/CoderHJZhao. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
14.5625
74
0.695279
0c0b282671169b229fe86639cf3f273ad9662c44
1,402
h
C
src/sys/processors/processor_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
15
2015-07-07T15:48:30.000Z
2019-10-27T18:49:49.000Z
src/sys/processors/processor_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
null
null
null
src/sys/processors/processor_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
4
2016-11-23T05:50:01.000Z
2019-09-18T12:44:36.000Z
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_SYS_PROCESSOR_FACTORY_H #define __SHAWN_SYS_PROCESSOR_FACTORY_H #include <string> #include "sys/util/keeper_managed.h" #include "sys/util/refcnt_pointer.h" namespace shawn { class Processor; class ProcessorKeeper; DECLARE_HANDLES(ProcessorFactory); class ProcessorFactory : public KeeperManaged { public: virtual ~ProcessorFactory(); virtual Processor* create( void ) throw() = 0; }; } #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/sys/processors/processor_factory.h,v $ * Version $Revision: 38 $ * Date $Date: 2007-06-08 14:30:12 +0200 (Fri, 08 Jun 2007) $ *----------------------------------------------------------------------- * $Log: processor_factory.h,v $ *-----------------------------------------------------------------------*/
31.863636
75
0.506419
aede68952b3e539104ccb9d46d7d281eef54078e
1,696
h
C
src/qt/qtwebkit/Source/WebKit/qt/WidgetSupport/DefaultFullScreenVideoHandler.h
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebKit/qt/WidgetSupport/DefaultFullScreenVideoHandler.h
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebKit/qt/WidgetSupport/DefaultFullScreenVideoHandler.h
zwollerob/PhantomJS_AMR6VL
71c126e98a8c32950158d04d0bd75823cd008b99
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2015 The Qt Company Ltd. * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * 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; 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef DefaultFullScreenVideoHandler_h #define DefaultFullScreenVideoHandler_h #include "qwebkitplatformplugin.h" namespace WebKit { class FullScreenVideoWidget; // We do not use ENABLE or USE because moc does not expand these macros. #if defined(WTF_USE_QT_MULTIMEDIA) && WTF_USE_QT_MULTIMEDIA class DefaultFullScreenVideoHandler : public QWebFullScreenVideoHandler { Q_OBJECT public: DefaultFullScreenVideoHandler(); virtual ~DefaultFullScreenVideoHandler(); bool requiresFullScreenForVideoPlayback() const; public Q_SLOTS: void enterFullScreen(QMediaPlayer*); void exitFullScreen(); private: static bool s_shouldForceFullScreenVideoPlayback; FullScreenVideoWidget *m_fullScreenWidget; }; #endif } // namespace WebKit #endif // DefaultFullScreenVideoHandler_h
33.254902
76
0.773585
aef1f12e79bc7cfa9585568e25203dc7418763f5
1,007
c
C
cpuinfo.c
traktofon/cpuinfo
176d7df561038218951c017a800d777c5a820e37
[ "MIT" ]
null
null
null
cpuinfo.c
traktofon/cpuinfo
176d7df561038218951c017a800d777c5a820e37
[ "MIT" ]
null
null
null
cpuinfo.c
traktofon/cpuinfo
176d7df561038218951c017a800d777c5a820e37
[ "MIT" ]
null
null
null
#include <hwloc.h> #include <stdio.h> void exit_usage(int exitcode) { fprintf(stderr, "Usage: cpuinfo [ socket | core | thread ]\n" "Print the number of CPU objects in the system. Default is core.\n"); exit(exitcode); } int main(int argc, char* argv[]) { hwloc_topology_t topology; hwloc_obj_type_t objtype; int nb; if (argc == 1) { objtype = HWLOC_OBJ_CORE; } else if (argc == 2) { if (strcmp(argv[1], "socket") == 0) { objtype = HWLOC_OBJ_SOCKET; } else if (strcmp(argv[1], "core") == 0) { objtype = HWLOC_OBJ_CORE; } else if (strcmp(argv[1], "thread") == 0) { objtype = HWLOC_OBJ_PU; } else { exit_usage(9); } } else { exit_usage(9); } hwloc_topology_init(&topology); hwloc_topology_load(topology); nb = hwloc_get_nbobjs_by_type(topology, objtype); printf("%d\n", nb); hwloc_topology_destroy(topology); return 0; }
25.175
89
0.566038
0396de9a5dd681705ad4a41503354735c669281e
15,752
c
C
src/mosfet.c
SequentMicrosystems/8mosfet-rpi
445e7d2245f8936f9fd7c7eca7237832b101eb9b
[ "MIT" ]
2
2020-07-09T15:25:32.000Z
2021-07-07T03:21:53.000Z
src/mosfet.c
SequentMicrosystems/8mosfet-rpi
445e7d2245f8936f9fd7c7eca7237832b101eb9b
[ "MIT" ]
null
null
null
src/mosfet.c
SequentMicrosystems/8mosfet-rpi
445e7d2245f8936f9fd7c7eca7237832b101eb9b
[ "MIT" ]
1
2021-07-07T03:21:57.000Z
2021-07-07T03:21:57.000Z
/* * mosfet8.c: * Command-line interface to the Raspberry * Pi's 8-Mosfet board. * Copyright (c) 2016-2020 Sequent Microsystem * <http://www.sequentmicrosystem.com> *********************************************************************** * Author: Alexandru Burcea *********************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "mosfet.h" #include "comm.h" #include "thread.h" #define VERSION_BASE (int)1 #define VERSION_MAJOR (int)0 #define VERSION_MINOR (int)0 #define UNUSED(X) (void)X /* To avoid gcc/g++ warnings */ #define CMD_ARRAY_SIZE 7 const u8 mosfetMaskRemap[8] = { 0x20, 0x40, 0x08, 0x04, 0x02, 0x01, 0x80, 0x10}; const int mosfetChRemap[8] = { 5, 6, 3, 2, 1, 0, 7, 4}; int mosfetChSet(int dev, u8 channel, OutStateEnumType state); int mosfetChGet(int dev, u8 channel, OutStateEnumType* state); u8 mosfetToIO(u8 mosfet); u8 IOToMosfet(u8 io); static void doHelp(int argc, char *argv[]); const CliCmdType CMD_HELP = { "-h", 1, &doHelp, "\t-h Display the list of command options or one command option details\n", "\tUsage: 8mosfet -h Display command options list\n", "\tUsage: 8mosfet -h <param> Display help for <param> command option\n", "\tExample: 8mosfet -h write Display help for \"write\" command option\n"}; static void doVersion(int argc, char *argv[]); const CliCmdType CMD_VERSION = { "-v", 1, &doVersion, "\t-v Display the version number\n", "\tUsage: 8mosfet -v\n", "", "\tExample: 8mosfet -v Display the version number\n"}; static void doWarranty(int argc, char* argv[]); const CliCmdType CMD_WAR = { "-warranty", 1, &doWarranty, "\t-warranty Display the warranty\n", "\tUsage: 8mosfet -warranty\n", "", "\tExample: 8mosfet -warranty Display the warranty text\n"}; static void doList(int argc, char *argv[]); const CliCmdType CMD_LIST = { "-list", 1, &doList, "\t-list: List all 8mosfet boards connected,\n\treturn nr of boards and stack level for every board\n", "\tUsage: 8mosfet -list\n", "", "\tExample: 8mosfet -list display: 1,0 \n"}; static void doMosfetWrite(int argc, char *argv[]); const CliCmdType CMD_WRITE = { "write", 2, &doMosfetWrite, "\twrite: Set mosfets On/Off\n", "\tUsage: 8mosfet <id> write <channel> <on/off>\n", "\tUsage: 8mosfet <id> write <value>\n", "\tExample: 8mosfet 0 write 2 On; Set Mosfet #2 on Board #0 On\n"}; static void doMosfetRead(int argc, char *argv[]); const CliCmdType CMD_READ = { "read", 2, &doMosfetRead, "\tread: Read mosfets status\n", "\tUsage: 8mosfet <id> read <channel>\n", "\tUsage: 8mosfet <id> read\n", "\tExample: 8mosfet 0 read 2; Read Status of Mosfet #2 on Board #0\n"}; static void doTest(int argc, char* argv[]); const CliCmdType CMD_TEST = { "test", 2, &doTest, "\ttest: Turn ON and OFF the mosfets until press a key\n", "", "\tUsage: 8mosfet <id> test\n", "\tExample: 8mosfet 0 test\n"}; CliCmdType gCmdArray[CMD_ARRAY_SIZE]; char *usage = "Usage: 8mosfet -h <command>\n" " 8mosfet -v\n" " 8mosfet -warranty\n" " 8mosfet -list\n" " 8mosfet <id> write <channel> <on/off>\n" " 8mosfet <id> write <value>\n" " 8mosfet <id> read <channel>\n" " 8mosfet <id> read\n" " 8mosfet <id> test\n" "Where: <id> = Board level id = 0..7\n" "Type 8mosfet -h <command> for more help"; // No trailing newline needed here. char *warranty = " Copyright (c) 2016-2020 Sequent Microsystems\n" " \n" " This program is free software; you can redistribute it and/or modify\n" " it under the terms of the GNU Leser General Public License as published\n" " by the Free Software Foundation, either version 3 of the License, or\n" " (at your option) any later version.\n" " \n" " This program is distributed in the hope that it will be useful,\n" " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" " GNU Lesser General Public License for more details.\n" " \n" " You should have received a copy of the GNU Lesser General Public License\n" " along with this program. If not, see <http://www.gnu.org/licenses/>."; u8 mosfetToIO(u8 mosfet) { u8 i; u8 val = 0; for (i = 0; i < 8; i++) { if ( (mosfet & (1 << i)) != 0) val += mosfetMaskRemap[i]; } return 0xff ^ val; } u8 IOToMosfet(u8 io) { u8 i; u8 val = 0; io ^= 0xff; for (i = 0; i < 8; i++) { if ( (io & mosfetMaskRemap[i]) != 0) { val += 1 << i; } } return val; } int mosfetChSet(int dev, u8 channel, OutStateEnumType state) { int resp; u8 buff[2]; if ( (channel < CHANNEL_NR_MIN) || (channel > MOSFET_CH_NR_MAX)) { printf("Invalid mosfet nr!\n"); return ERROR; } if (FAIL == i2cMem8Read(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1)) { return FAIL; } switch (state) { case ON: buff[0] &= ~ (1 << mosfetChRemap[channel - 1]); resp = i2cMem8Write(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1); break; case OFF: buff[0] |= 1 << mosfetChRemap[channel - 1]; resp = i2cMem8Write(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1); break; default: printf("Invalid mosfet state!\n"); return ERROR; break; } return resp; } int mosfetChGet(int dev, u8 channel, OutStateEnumType* state) { u8 buff[2]; if (NULL == state) { return ERROR; } if ( (channel < CHANNEL_NR_MIN) || (channel > MOSFET_CH_NR_MAX)) { printf("Invalid mosfet nr!\n"); return ERROR; } if (FAIL == i2cMem8Read(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1)) { return ERROR; } if (buff[0] & (1 << mosfetChRemap[channel - 1])) { *state = OFF; } else { *state = ON; } return OK; } int mosfetSet(int dev, int val) { u8 buff[2]; buff[0] = mosfetToIO(0xff & val); return i2cMem8Write(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1); } int mosfetGet(int dev, int* val) { u8 buff[2]; if (NULL == val) { return ERROR; } if (FAIL == i2cMem8Read(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1)) { return ERROR; } *val = IOToMosfet(buff[0]); return OK; } int doBoardInit(int stack) { int dev = 0; int add = 0; uint8_t buff[8]; if((stack < 0) || (stack > 7)) { printf("Invalid stack level [0..7]!"); return ERROR; } add = (stack + MOSFET8_HW_I2C_BASE_ADD) ^ 0x07; dev = i2cSetup(add); if (dev == -1) { return ERROR; } if (ERROR == i2cMem8Read(dev, MOSFET8_CFG_REG_ADD, buff, 1)) { printf("8-MOSFETS card id %d not detected\n", stack); return ERROR; } if (buff[0] != 0) //non initialized I/O Expander { // make all I/O pins output buff[0] = 0; if (0 > i2cMem8Write(dev, MOSFET8_CFG_REG_ADD, buff, 1)) { return ERROR; } // put all pins in 0-logic state buff[0] = 0xff; if (0 > i2cMem8Write(dev, MOSFET8_OUTPORT_REG_ADD, buff, 1)) { return ERROR; } } return dev; } int boardCheck(int hwAdd) { int dev = 0; uint8_t buff[8]; hwAdd ^= 0x07; dev = i2cSetup(hwAdd); if (dev == -1) { return FAIL; } if (ERROR == i2cMem8Read(dev, MOSFET8_CFG_REG_ADD, buff, 1)) { return ERROR; } return OK; } /* * doMosfetWrite: * Write coresponding mosfet channel ************************************************************************************** */ static void doMosfetWrite(int argc, char *argv[]) { int pin = 0; OutStateEnumType state = STATE_COUNT; int val = 0; int dev = 0; OutStateEnumType stateR = STATE_COUNT; int valR = 0; int retry = 0; if ( (argc != 5) && (argc != 4)) { printf("Usage: 8mosfet <id> write <mosfet number> <on/off> \n"); printf("Usage: 8mosfet <id> write <mosfet reg value> \n"); exit(1); } dev = doBoardInit(atoi(argv[1])); if (dev <= 0) { exit(1); } if (argc == 5) { pin = atoi(argv[3]); if ( (pin < CHANNEL_NR_MIN) || (pin > MOSFET_CH_NR_MAX)) { printf("Mosfet number value out of range\n"); exit(1); } /**/if ( (strcasecmp(argv[4], "up") == 0) || (strcasecmp(argv[4], "on") == 0)) state = ON; else if ( (strcasecmp(argv[4], "down") == 0) || (strcasecmp(argv[4], "off") == 0)) state = OFF; else { if ( (atoi(argv[4]) >= STATE_COUNT) || (atoi(argv[4]) < 0)) { printf("Invalid mosfet state!\n"); exit(1); } state = (OutStateEnumType)atoi(argv[4]); } retry = RETRY_TIMES; while ( (retry > 0) && (stateR != state)) { if (OK != mosfetChSet(dev, pin, state)) { printf("Fail to write mosfet\n"); exit(1); } if (OK != mosfetChGet(dev, pin, &stateR)) { printf("Fail to read mosfet\n"); exit(1); } retry--; } #ifdef DEBUG_I if(retry < RETRY_TIMES) { printf("retry %d times\n", 3-retry); } #endif if (retry == 0) { printf("Fail to write mosfet\n"); exit(1); } } else { val = atoi(argv[3]); if (val < 0 || val > 255) { printf("Invalid mosfet value\n"); exit(1); } retry = RETRY_TIMES; valR = -1; while ( (retry > 0) && (valR != val)) { if (OK != mosfetSet(dev, val)) { printf("Fail to write mosfet!\n"); exit(1); } if (OK != mosfetGet(dev, &valR)) { printf("Fail to read mosfet!\n"); exit(1); } } if (retry == 0) { printf("Fail to write mosfet!\n"); exit(1); } } } /* * doMosfetRead: * Read mosfet state ****************************************************************************************** */ static void doMosfetRead(int argc, char *argv[]) { int pin = 0; int val = 0; int dev = 0; OutStateEnumType state = STATE_COUNT; dev = doBoardInit(atoi(argv[1])); if (dev <= 0) { exit(1); } if (argc == 4) { pin = atoi(argv[3]); if ( (pin < CHANNEL_NR_MIN) || (pin > MOSFET_CH_NR_MAX)) { printf("Mosfet number value out of range!\n"); exit(1); } if (OK != mosfetChGet(dev, pin, &state)) { printf("Fail to read!\n"); exit(1); } if (state != 0) { printf("1\n"); } else { printf("0\n"); } } else if (argc == 3) { if (OK != mosfetGet(dev, &val)) { printf("Fail to read!\n"); exit(1); } printf("%d\n", val); } else { printf("Usage: %s read mosfet value\n", argv[0]); exit(1); } } static void doHelp(int argc, char *argv[]) { int i = 0; if (argc == 3) { for (i = 0; i < CMD_ARRAY_SIZE; i++) { if ( (gCmdArray[i].name != NULL )) { if (strcasecmp(argv[2], gCmdArray[i].name) == 0) { printf("%s%s%s%s", gCmdArray[i].help, gCmdArray[i].usage1, gCmdArray[i].usage2, gCmdArray[i].example); break; } } } if (CMD_ARRAY_SIZE == i) { printf("Option \"%s\" not found\n", argv[2]); printf("%s: %s\n", argv[0], usage); } } else { printf("%s: %s\n", argv[0], usage); } } static void doVersion(int argc, char *argv[]) { UNUSED(argc); UNUSED(argv); printf("8mosfet v%d.%d.%d Copyright (c) 2016 - 2020 Sequent Microsystems\n", VERSION_BASE, VERSION_MAJOR, VERSION_MINOR); printf("\nThis is free software with ABSOLUTELY NO WARRANTY.\n"); printf("For details type: 8mosfet -warranty\n"); } static void doList(int argc, char *argv[]) { int ids[8]; int i; int cnt = 0; UNUSED(argc); UNUSED(argv); for (i = 0; i < 8; i++) { if (boardCheck(MOSFET8_HW_I2C_BASE_ADD + i) == OK) { ids[cnt] = i; cnt++; } } printf("%d board(s) detected\n", cnt); if (cnt > 0) { printf("Id:"); } while (cnt > 0) { cnt--; printf(" %d", ids[cnt]); } printf("\n"); } /* * Self test for production */ static void doTest(int argc, char* argv[]) { int dev = 0; int i = 0; int retry = 0; int relVal; int valR; int mosfetResult = 0; FILE* file = NULL; const u8 mosfetOrder[8] = { 1, 2, 3, 4, 5, 6, 7, 8}; dev = doBoardInit(atoi(argv[1])); if (dev <= 0) { exit(1); } if (argc == 4) { file = fopen(argv[3], "w"); if (!file) { printf("Fail to open result file\n"); //return -1; } } //mosfet test**************************** if (strcasecmp(argv[2], "test") == 0) { relVal = 0; printf( "Are all mosfets and LEDs turning on and off in sequence?\nPress y for Yes or any key for No...."); startThread(); while (mosfetResult == 0) { for (i = 0; i < 8; i++) { mosfetResult = checkThreadResult(); if (mosfetResult != 0) { break; } valR = 0; relVal = (u8)1 << (mosfetOrder[i] - 1); retry = RETRY_TIMES; while ( (retry > 0) && ( (valR & relVal) == 0)) { if (OK != mosfetChSet(dev, mosfetOrder[i], ON)) { retry = 0; break; } if (OK != mosfetGet(dev, &valR)) { retry = 0; } } if (retry == 0) { printf("Fail to write mosfet\n"); if (file) fclose(file); exit(1); } busyWait(150); } for (i = 0; i < 8; i++) { mosfetResult = checkThreadResult(); if (mosfetResult != 0) { break; } valR = 0xff; relVal = (u8)1 << (mosfetOrder[i] - 1); retry = RETRY_TIMES; while ( (retry > 0) && ( (valR & relVal) != 0)) { if (OK != mosfetChSet(dev, mosfetOrder[i], OFF)) { retry = 0; } if (OK != mosfetGet(dev, &valR)) { retry = 0; } } if (retry == 0) { printf("Fail to write mosfet!\n"); if (file) fclose(file); exit(1); } busyWait(150); } } } if (mosfetResult == YES) { if (file) { fprintf(file, "Mosfet Test ............................ PASS\n"); } else { printf("Mosfet Test ............................ PASS\n"); } } else { if (file) { fprintf(file, "Mosfet Test ............................ FAIL!\n"); } else { printf("Mosfet Test ............................ FAIL!\n"); } } if (file) { fclose(file); } mosfetSet(dev, 0); } static void doWarranty(int argc UNU, char* argv[] UNU) { printf("%s\n", warranty); } static void cliInit(void) { int i = 0; memset(gCmdArray, 0, sizeof(CliCmdType) * CMD_ARRAY_SIZE); memcpy(&gCmdArray[i], &CMD_HELP, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_WAR, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_LIST, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_WRITE, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_READ, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_TEST, sizeof(CliCmdType)); i++; memcpy(&gCmdArray[i], &CMD_VERSION, sizeof(CliCmdType)); } int main(int argc, char *argv[]) { int i = 0; cliInit(); if (argc == 1) { printf("%s\n", usage); return 1; } for (i = 0; i < CMD_ARRAY_SIZE; i++) { if ( (gCmdArray[i].name != NULL ) && (gCmdArray[i].namePos < argc)) { if (strcasecmp(argv[gCmdArray[i].namePos], gCmdArray[i].name) == 0) { gCmdArray[i].pFunc(argc, argv); return 0; } } } printf("Invalid command option\n"); printf("%s\n", usage); return 0; }
20.404145
117
0.534599
26c1df1dea931beecf124acc587eb0a12859d548
205
h
C
firmware/user/QMA6981.h
thaeli/Swadge-Devkit-Fw
f7104c759fcbb7a1c7d192af09ecdf9d54f69fbc
[ "MIT" ]
4
2020-01-06T19:18:49.000Z
2020-07-20T14:42:58.000Z
firmware/user/QMA6981.h
thaeli/Swadge-Devkit-Fw
f7104c759fcbb7a1c7d192af09ecdf9d54f69fbc
[ "MIT" ]
60
2019-03-26T04:41:00.000Z
2019-12-21T17:36:50.000Z
firmware/user/QMA6981.h
thaeli/Swadge-Devkit-Fw
f7104c759fcbb7a1c7d192af09ecdf9d54f69fbc
[ "MIT" ]
5
2019-07-07T01:28:22.000Z
2019-12-14T04:16:12.000Z
/* * QMA6981.h * * Created on: Jul 9, 2019 * Author: adam */ #ifndef QMA6981_H_ #define QMA6981_H_ bool QMA6981_setup(void); void QMA6981_poll(accel_t* currentAccel); #endif /* QMA6981_H_ */
13.666667
41
0.673171
145d7a42b63fc5c9057f71826aaef913d2f28b51
925
c
C
kernel/drivers/kevent_dev.c
ilmarfreitaso/wscodelabs
6d168602c32e301187948479b997e6ceb3c1afe7
[ "Apache-2.0" ]
null
null
null
kernel/drivers/kevent_dev.c
ilmarfreitaso/wscodelabs
6d168602c32e301187948479b997e6ceb3c1afe7
[ "Apache-2.0" ]
null
null
null
kernel/drivers/kevent_dev.c
ilmarfreitaso/wscodelabs
6d168602c32e301187948479b997e6ceb3c1afe7
[ "Apache-2.0" ]
null
null
null
#include <dev/basic_dev.h> #include <system.h> bool kevent_init() { return true; } #define KEVENT_BUF_SIZE 32 static char _buffer_data[KEVENT_BUF_SIZE]; static dev_buffer_t _kevent_buffer = { _buffer_data, KEVENT_BUF_SIZE, 0, 0 }; static int32_t _kevent_lock = 0; void dev_kevent_push(uint32_t ev) { const char* p = (char*)&ev; CRIT_IN(_kevent_lock) dev_buffer_push(&_kevent_buffer, p[0], true); dev_buffer_push(&_kevent_buffer, p[1], true); dev_buffer_push(&_kevent_buffer, p[2], true); dev_buffer_push(&_kevent_buffer, p[3], true); CRIT_OUT(_kevent_lock) } int32_t dev_kevent_read(int16_t id, void* buf, uint32_t size) { (void)id; CRIT_IN(_kevent_lock) int32_t sz = size < _kevent_buffer.size ? size:_kevent_buffer.size; char* p = (char*)buf; int32_t i = 0; while(i < sz) { char c; if(dev_buffer_pop(&_kevent_buffer, &c) != 0) break; p[i] = c; i++; } CRIT_OUT(_kevent_lock) return i; }
22.560976
77
0.713514
6cecf8581f50d8ff4dbd5b5ebbf0c35c1fdc312d
809
c
C
divide-and-conquer-examples/c/ex_6.c
prabhatk579/algorithms
fdbc962244a98846750564f4c3f3972c808a7247
[ "MIT" ]
null
null
null
divide-and-conquer-examples/c/ex_6.c
prabhatk579/algorithms
fdbc962244a98846750564f4c3f3972c808a7247
[ "MIT" ]
null
null
null
divide-and-conquer-examples/c/ex_6.c
prabhatk579/algorithms
fdbc962244a98846750564f4c3f3972c808a7247
[ "MIT" ]
2
2021-05-21T17:01:07.000Z
2021-05-23T05:45:44.000Z
/* Given a sorted array of non-repeated integers A[1...n], n > 1 then check whether there is an index i for which A[i] = i. Give an algorithm that runs in O(logn) time */ #include <stdio.h> int BS(int a[], int l, int h){ if(h >= l){ int mid = (l + h)/2; if(a[mid] == mid){ return mid; } if(a[mid] < mid){ return BS(a, mid + 1, h); } if(a[mid] > mid){ return BS(a, l, mid - 1); } } return -1; } int main(){ int a[10] = {-2, -1, 0, 1, 2, 4, 5, 7, 11, 13}; int n = sizeof(a)/sizeof(a[0]); int result = BS(a, 0, n-1); if(result != -1){ printf("A[i] = i at Point: %d", result); } else{ printf("There is not element satisfying A[i] = i"); } return 0; }
23.794118
93
0.458591
159d45d8ced0cd0565830f0cde0467008d40f218
2,076
h
C
OpenSeesLibs/petsc/Unix/3.10.3_2/include/petscmachineinfo.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
OpenSeesLibs/petsc/Unix/3.10.3_2/include/petscmachineinfo.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
OpenSeesLibs/petsc/Unix/3.10.3_2/include/petscmachineinfo.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
static const char *petscmachineinfo = "\n" "-----------------------------------------\n" "Libraries compiled on 2019-05-31 04:06:45 on Office \n" "Machine characteristics: Linux-5.0.0-15-generic-x86_64-with-Ubuntu-19.04-disco\n" "Using PETSc directory: /home/linuxbrew/.linuxbrew/Cellar/petsc/3.10.3_2\n" "Using PETSc arch: \n" "-----------------------------------------\n"; static const char *petsccompilerinfo = "\n" "Using C compiler: mpicc -fPIC -Wall -Wwrite-strings -Wno-strict-aliasing -Wno-unknown-pragmas -fstack-protector -fvisibility=hidden -g -O \n" "Using Fortran compiler: mpif90 -fPIC -Wall -ffree-line-length-0 -Wno-unused-dummy-argument -g -O \n" "-----------------------------------------\n"; static const char *petsccompilerflagsinfo = "\n" "Using include paths: -I/home/linuxbrew/.linuxbrew/Cellar/petsc/3.10.3_2/include\n" "-----------------------------------------\n"; static const char *petsclinkerinfo = "\n" "Using C linker: mpicc\n" "Using Fortran linker: mpif90\n" "Using libraries: -Wl,-rpath,/home/linuxbrew/.linuxbrew/Cellar/petsc/3.10.3_2/lib -L/home/linuxbrew/.linuxbrew/Cellar/petsc/3.10.3_2/lib -lpetsc -Wl,-rpath,/home/linuxbrew/.linuxbrew/opt/libevent/lib -L/home/linuxbrew/.linuxbrew/opt/libevent/lib -Wl,-rpath,/home/linuxbrew/.linuxbrew/Cellar/open-mpi/4.0.1_1/lib -L/home/linuxbrew/.linuxbrew/Cellar/open-mpi/4.0.1_1/lib -Wl,-rpath,/home/linuxbrew/.linuxbrew/lib -Wl,-rpath,/home/linuxbrew/.linuxbrew/Cellar/gcc/5.5.0_4/lib/gcc/x86_64-unknown-linux-gnu/5.5.0 -L/home/linuxbrew/.linuxbrew/Cellar/gcc/5.5.0_4/lib/gcc/x86_64-unknown-linux-gnu/5.5.0 -Wl,-rpath,/home/linuxbrew/.linuxbrew/Cellar/gcc/5.5.0_4/lib -L/home/linuxbrew/.linuxbrew/Cellar/gcc/5.5.0_4/lib -Wl,-rpath,/lib/x86_64-linux-gnu -L/lib/x86_64-linux-gnu -Wl,-rpath,/usr/lib/x86_64-linux-gnu -L/usr/lib/x86_64-linux-gnu -L/home/linuxbrew/.linuxbrew/lib -llapack -lblas -lm -lstdc++ -ldl -lmpi_usempif08 -lmpi_usempi_ignore_tkr -lmpi_mpifh -lmpi -lgfortran -lm -lgfortran -lm -lgcc_s -lquadmath -lpthread -lstdc++ -ldl\n" "-----------------------------------------\n";
103.8
1,029
0.67341
29dff087eed3fa5b30f42d579c11492b05378fbe
6,457
h
C
src/min_l-bfgs.h
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
3
2018-06-06T05:43:36.000Z
2020-07-18T14:31:37.000Z
src/min_l-bfgs.h
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
null
null
null
src/min_l-bfgs.h
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
7
2018-01-16T03:21:20.000Z
2020-07-20T19:36:13.000Z
#ifndef __MAPP__min_l_bfgs__ #define __MAPP__min_l_bfgs__ #include "min_cg.h" namespace MAPP_NS { class MinLBFGS:public MinCG { private: protected: int m; type0* rho; type0* alpha; void* s_ptr; void* y_ptr; public: MinLBFGS(int,type0,bool(&)[__dim__][__dim__],bool,type0,class LineSearch*); ~MinLBFGS(); void run(int); void init(); void fin(); template<bool BC,bool X> void __init(); template<bool BC,bool X,bool OUT,bool XOUT,class LS> void __run(LS*,int); template<bool BC,bool X> void __fin(); typedef struct { PyObject_HEAD MinLBFGS* min; LineSearch::Object* ls; ExportMD::Object* xprt; }Object; static PyTypeObject TypeObject; static PyObject* __new__(PyTypeObject*,PyObject*, PyObject*); static int __init__(PyObject*, PyObject*,PyObject*); static PyObject* __alloc__(PyTypeObject*,Py_ssize_t); static void __dealloc__(PyObject*); static PyMethodDef methods[]; static void setup_tp_methods(); static PyGetSetDef getset[]; static void setup_tp_getset(); static void getset_m(PyGetSetDef&); static int setup_tp(); }; } using namespace MAPP_NS; /*-------------------------------------------- --------------------------------------------*/ template<bool BC,bool X> void MinLBFGS::__init() { MinMDHandler<BC,X>* __handler_ptr=new (&handler_buff) MinMDHandler<BC,X>(atoms,ff,max_dx,H_dof); __handler_ptr->init(); typedef typename MinMDHandler<BC,X>::VECTENS1 VECTENS1; VECTENS1* __y_ptr=m==0 ? NULL:new VECTENS1[m]; VECTENS1* __s_ptr=m==0 ? NULL:new VECTENS1[m]; for(int i=0;i<m;i++) { __y_ptr[i].~VECTENS1(); new (__y_ptr+i) VECTENS1(atoms,__dim__,X); __s_ptr[i].~VECTENS1(); new (__s_ptr+i) VECTENS1(atoms,__dim__,X); } s_ptr=__s_ptr; y_ptr=__y_ptr; static constexpr int N1=MinMDHandler<BC,X>::N1; for(int i=0;i<m;i++) { Algebra::Do<N1>::func([&__s_ptr,&__y_ptr,&i,&__handler_ptr](int j) { __handler_ptr->dynamic.add_xchng(__y_ptr[i].vecs[j]); __handler_ptr->dynamic.add_xchng(__s_ptr[i].vecs[j]); }); } __handler_ptr->dynamic.init(); rho=m==0 ?NULL:new type0[m]; alpha=m==0 ?NULL:new type0[m]; if(xprt) { try { xprt->atoms=atoms; xprt->init(); } catch(std::string& err_msg) { __fin<BC,X>(); throw err_msg; } } } /*-------------------------------------------- --------------------------------------------*/ template<bool BC,bool X,bool OUT,bool XOUT,class LS> void MinLBFGS::__run(LS* ls,int nsteps) { MinMDHandler<BC,X> &handler=*reinterpret_cast<MinMDHandler<BC,X>*>(&handler_buff); typedef typename MinMDHandler<BC,X>::VECTENS0 VECTENS0; typedef typename MinMDHandler<BC,X>::VECTENS1 VECTENS1; VECTENS1& f=handler.f; VECTENS1& f0=handler.f0; VECTENS1& h=handler.h; VECTENS0& x0=handler.x0; VECTENS0& x=handler.x; VECTENS1* y=reinterpret_cast<VECTENS1*>(y_ptr); VECTENS1* s=reinterpret_cast<VECTENS1*>(s_ptr); type0& f_h=handler.f_h; ls->reset(); int step=atoms->step; handler.force_calc(); MinHelper::ThermoHandler<OUT>::init(*this,step); MinHelper::ExportHandler<XOUT>::init(*this,step); type0 e_prev,e_curr=atoms->pe; type0 alpha_m,gamma; type0 inner0,inner1,scl0; int k=0; gamma=1.0; int err=nsteps==0? MIN_F_MAX_ITER:LS_S; int istep=0; for(;err==LS_S;istep++) { x0=x; h=f0=f; for(int i=0;i<k;i++) { alpha[i]=-rho[i]*(s[i]*h); h+=alpha[i]*y[i]; } h*=gamma; for(int i=k-1;i>-1;i--) { scl0=-alpha[i]-rho[i]*(y[i]*h); h+=scl0*s[i]; } e_prev=e_curr; f_h=f*h; if(f_h<0.0) { h=f; k=0; f_h=f*f; } handler.prep(); err=ls->min(&handler,e_curr,alpha_m,0); if(err!=LS_S) { // this was a bullshit step so we have to decrease the setup once to compensate // the last step was the previous one istep--; continue; } handler.force_calc(); MinHelper::ThermoHandler<OUT>::print(*this,step,istep); MinHelper::ExportHandler<XOUT>::print(*this,step,istep); //this was a successfull step but the last one if(e_prev-e_curr<e_tol) err=MIN_S_TOLERANCE; if(istep+1==nsteps) err=MIN_F_MAX_ITER; if(err) continue; if(m) { if(k!=m) k++; cyclic_shift(s,k); cyclic_shift(y,k); for(int i=m-1;i>0;i--) rho[i]=rho[i-1]; s[0]=alpha_m*h; y[0]=f0-f; inner0=s[0]*y[0]; inner1=y[0]*y[0]; gamma=inner0/inner1; rho[0]=1.0/inner0; } else gamma=alpha_m*(h*f0-h*f)/(f*f+f0*f0-2.0*(f*f0)); } MinHelper::ThermoHandler<OUT>::fin(*this,step,istep,err_msgs[err]); MinHelper::ExportHandler<XOUT>::fin(*this,step,istep); atoms->step+=istep; } /*-------------------------------------------- --------------------------------------------*/ template<bool BC,bool X> void MinLBFGS::__fin() { delete [] alpha; alpha=NULL; delete [] rho; rho=NULL; if(xprt) { xprt->fin(); xprt->atoms=NULL; } MinMDHandler<BC,X>* __handler_ptr=reinterpret_cast<MinMDHandler<BC,X>*>(&handler_buff); __handler_ptr->dynamic.fin(); typedef typename MinMDHandler<BC,X>::VECTENS1 VECTENS1; VECTENS1* __y_ptr=reinterpret_cast<VECTENS1*>(y_ptr); VECTENS1* __s_ptr=reinterpret_cast<VECTENS1*>(s_ptr); delete [] __s_ptr; delete [] __y_ptr; s_ptr=NULL; y_ptr=NULL; __handler_ptr->fin(); __handler_ptr->~MinMDHandler(); } #endif
25.623016
100
0.513087
76730150e20c6fd718b6656d3289cb973e00bdfd
962
h
C
deps/webrtc/include/third_party/WebKit/Source/core/leak_detector/BlinkLeakDetector.h
QueenConch/quick_start_webrtc_native
0321fb204a076b437e0d708c2ec55cae6464c4f3
[ "MIT" ]
2
2018-07-04T00:29:09.000Z
2020-07-05T09:24:59.000Z
deps/webrtc/include/third_party/WebKit/Source/core/leak_detector/BlinkLeakDetector.h
QueenConch/quick_start_webrtc_native
0321fb204a076b437e0d708c2ec55cae6464c4f3
[ "MIT" ]
null
null
null
deps/webrtc/include/third_party/WebKit/Source/core/leak_detector/BlinkLeakDetector.h
QueenConch/quick_start_webrtc_native
0321fb204a076b437e0d708c2ec55cae6464c4f3
[ "MIT" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BlinkLeakDetector_h #define BlinkLeakDetector_h #include "core/CoreExport.h" #include "platform/Timer.h" namespace blink { class BlinkLeakDetectorClient; class WebFrame; // This class is responsible for stabilizing the detection results which are // InstanceCounter values by 1) preparing for leak detection and 2) operating // garbage collections before leak detection. class CORE_EXPORT BlinkLeakDetector { public: explicit BlinkLeakDetector(BlinkLeakDetectorClient*); ~BlinkLeakDetector(); void PrepareForLeakDetection(WebFrame*); void CollectGarbage(); private: void TimerFiredGC(TimerBase*); TaskRunnerTimer<BlinkLeakDetector> delayed_gc_timer_; int number_of_gc_needed_; BlinkLeakDetectorClient* client_; }; } // namespace blink #endif // LeakDetector_h
26
77
0.788981
e464df0473ba1311030dbcff8ebc8a290db34708
482
h
C
Source/FSD/Public/SchematicGADataEntry.h
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Public/SchematicGADataEntry.h
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Public/SchematicGADataEntry.h
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#pragma once #include "CoreMinimal.h" #include "Engine/DataTable.h" #include "SchematicGADataEntry.generated.h" USTRUCT(BlueprintType) struct FSchematicGADataEntry : public FTableRowBase { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 SchematicGAID; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FString SchematicName; FSD_API FSchematicGADataEntry(); };
25.368421
79
0.76971
538afbac5454f2442a7503758a479933aac0f54c
1,134
h
C
VideoTime/VideoTime/Network/Base/BaseNetworkHandler.h
wuyuanping/VideoTime
8b8217492245ff4d1bf5ebcf9ef1ba3339bac66a
[ "Apache-2.0" ]
null
null
null
VideoTime/VideoTime/Network/Base/BaseNetworkHandler.h
wuyuanping/VideoTime
8b8217492245ff4d1bf5ebcf9ef1ba3339bac66a
[ "Apache-2.0" ]
null
null
null
VideoTime/VideoTime/Network/Base/BaseNetworkHandler.h
wuyuanping/VideoTime
8b8217492245ff4d1bf5ebcf9ef1ba3339bac66a
[ "Apache-2.0" ]
null
null
null
// // BaseNetworkHandler.h // VideoTime // // Created by 吴园平 on 23/09/2017. // Copyright © 2017 WuYuanPing. All rights reserved. // // 该类主要用来实现数据加密,解密操作 #import <Foundation/Foundation.h> #import "BaseResponseResult.h" /** * 网络请求缓存 * cacheData : 缓存对象 */ typedef void (^RequestCacheBlock)(id cacheData); /** * Handler处理成功时调用的Block */ typedef void (^RequestSuccessBlock)(BaseResponseResult *result); /** * Handler处理失败时调用的Block */ typedef void (^RequestFailedBlock)(NSError *error); @interface BaseNetworkHandler : NSObject /** * 获取请求URL * * @param path * @return 拼装好的URL */ //+ (NSString *)requestUrlWithPath:(NSString *)path; /** * 生成sign * @param params 请求参数 * @return 按协定方式加密生成的验证字符串 */ + (NSString *)generateSignString:(NSDictionary *)params; /** * 请求数据的加密 * * @param 参数字典 * @return 加密之后的请求参数 */ //+ (NSDictionary *)requestDataEncryptWithParameter:(NSDictionary *)parameDic needToken:(BOOL)needToken; /** * 返回数据的解密 * * @param responseDic 返回数据 * @return 解密之后的返回数据 */ //+ (NSDictionary *)responseDataDecrypt:(NSDictionary *)responseDic isUsePublicKey:(BOOL)usePublicKey; @end
16.434783
104
0.69224
410dc1aea56d170caab50f4b10e68d9984ee28c1
452
c
C
examples/test_monocypher_eddsa.c
trailofbits/sandshrew
caf14dbb4c45392ba7347c2adc11282cbd1f4e71
[ "MIT" ]
19
2019-04-01T08:23:39.000Z
2022-02-25T01:51:31.000Z
examples/test_monocypher_eddsa.c
trailofbits/sandshrew
caf14dbb4c45392ba7347c2adc11282cbd1f4e71
[ "MIT" ]
2
2019-04-22T15:48:19.000Z
2021-03-26T00:01:58.000Z
examples/test_monocypher_eddsa.c
trailofbits/sandshrew
caf14dbb4c45392ba7347c2adc11282cbd1f4e71
[ "MIT" ]
2
2019-04-22T15:43:53.000Z
2022-02-25T01:51:34.000Z
/* test_monocypher_eddsa.c * * Tests: * EdDSA signing fault with all-zero input * * Descriptions: * Tests sandshrews ability to determine ... * * Results: * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "monocypher.c" int main(int argc, char *argv[]) { uint8_t public_key[32]; uint8_t zero_key[32] = {0}; crypto_sign_public_key(public_key, (const uint8_t *) argv[1]); return 0; }
16.740741
63
0.632743
5b2a424e235f4b428b9b149e784b5381893a9a8b
3,742
h
C
src/lib/crypto/OSSLComp.h
ansasaki/SoftHSMv2
80b96a9f79b9898a2c799aa6ce899ae6f88211cd
[ "BSD-2-Clause" ]
486
2015-01-04T05:57:25.000Z
2022-03-30T02:40:52.000Z
src/lib/crypto/OSSLComp.h
martinpaljak/SoftHSMv2
a431e61b890b91fb208711816014c25fb83367a9
[ "BSD-2-Clause" ]
486
2015-01-12T08:51:33.000Z
2022-03-22T09:06:15.000Z
src/lib/crypto/OSSLComp.h
martinpaljak/SoftHSMv2
a431e61b890b91fb208711816014c25fb83367a9
[ "BSD-2-Clause" ]
274
2015-01-21T21:41:45.000Z
2022-03-30T15:05:54.000Z
/* * Copyright (c) 2016 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** OSSLComp.h Adding OpenSSL forward-compatible code as suggested by OpenSSL *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLCOMP_H #define _SOFTHSM_V2_OSSLCOMP_H #include "config.h" #include <openssl/opensslv.h> #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/dh.h> #include <openssl/dsa.h> #ifdef WITH_ECC #include <openssl/ecdsa.h> #endif #include <openssl/rsa.h> // EVP digest routines EVP_MD_CTX *EVP_MD_CTX_new(void); void EVP_MD_CTX_free(EVP_MD_CTX *ctx); // HMAC routines HMAC_CTX *HMAC_CTX_new(void); void HMAC_CTX_free(HMAC_CTX *ctx); // DH routines void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g); int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g); void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key); int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key); long DH_get_length(const DH *dh); int DH_set_length(DH *dh, long length); // DSA routines void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g); int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g); void DSA_get0_key(const DSA *d, const BIGNUM **pub_key, const BIGNUM **priv_key); int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key); // DSA_SIG routines void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps); int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s); // ECDSA_SIG routines #ifdef WITH_ECC void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps); int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s); #endif // EDDSA #ifdef WITH_EDDSA #error This OpenSSL version is incompatible with EDDSA #endif // RSA routines int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d); int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q); int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp); void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d); void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q); void RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1, const BIGNUM **iqmp); #endif #endif // !_SOFTHSM_V2_OSSLCOMP_H
35.980769
80
0.714324
c475ee33bcfca6f6fda542e3c87ccc02a16258ab
3,732
c
C
pyscf/lib/gto/fill_r_4c.c
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
1
2017-03-03T02:12:08.000Z
2017-03-03T02:12:08.000Z
pyscf/lib/gto/fill_r_4c.c
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
null
null
null
pyscf/lib/gto/fill_r_4c.c
robert-anderson/pyscf
cdc56e168cb15f47e8cdc791a92d689fa9b655af
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014-2018 The PySCF Developers. 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. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include <complex.h> #include "config.h" #include "cint.h" int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); /* * out[naoi,naoj,naok,comp] in F-order */ void GTOr4c_fill_s1(int (*intor)(), double complex *out, double *buf, int comp, int ish, int jsh, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const int lsh0 = shls_slice[6]; const int lsh1 = shls_slice[7]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t naol = ao_loc[lsh1] - ao_loc[lsh0]; const size_t nij = naoi * naoj; const int dims[] = {naoi, naoj, naok, naol}; ish += ish0; jsh += jsh0; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += jp * naoi + ip; int ksh, lsh, k0, l0; int shls[4]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh < lsh1; lsh++) { shls[2] = ksh; shls[3] = lsh; k0 = ao_loc[ksh] - ao_loc[ksh0]; l0 = ao_loc[lsh] - ao_loc[lsh0]; (*intor)(out+(l0*naok+k0)*nij, dims, shls, atm, natm, bas, nbas, env, cintopt, buf); } } } void GTOr4c_drv(int (*intor)(), void (*fill)(), int (*prescreen)(), double complex *eri, int comp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const int cache_size = GTOmax_cache_size(intor, shls_slice, 4, atm, natm, bas, nbas, env); #pragma omp parallel default(none) \ shared(intor, fill, eri, comp, shls_slice, ao_loc, cintopt, \ atm, natm, bas, nbas, env) { int ish, jsh, ij; double *buf = malloc(sizeof(double) * cache_size); #pragma omp for schedule(dynamic) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; (*fill)(intor, eri, buf, comp, ish, jsh, shls_slice, ao_loc, cintopt, atm, natm, bas, nbas, env); } free(buf); } }
35.884615
76
0.556538
0efbab7183042a5c73aa3881ac0b0169d9a83f4b
2,380
h
C
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Joints/PRISMATIC_TWIST_JOINT.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Joints/PRISMATIC_TWIST_JOINT.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Joints/PRISMATIC_TWIST_JOINT.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2007, Craig Schroeder, Tamar Shinar, Jonathan Su // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class PRISMATIC_TWIST_JOINT //##################################################################### #ifndef __PRISMATIC_TWIST_JOINT__ #define __PRISMATIC_TWIST_JOINT__ #include <PhysBAM_Tools/Matrices/MATRIX_POLICY.h> #include <PhysBAM_Solids/PhysBAM_Rigids/Joints/ANGLE_JOINT.h> namespace PhysBAM{ template<class TV> class PRISMATIC_TWIST_JOINT:public ANGLE_JOINT<TV> { typedef typename TV::SCALAR T;typedef ANGLE_JOINT<TV> BASE;typedef typename TV::SPIN T_SPIN; using BASE::J;using BASE::F_pj;typedef typename TV::template REBIND<bool>::TYPE TV_BOOL; public: TV_BOOL constrain; TV prismatic_min,prismatic_max; PRISMATIC_TWIST_JOINT() {constrain.x=true;} virtual ~PRISMATIC_TWIST_JOINT(); void Set_Prismatic_Constraints(const TV_BOOL& constrain_input,const TV& min=TV(),const TV& max=TV()) {constrain=constrain_input;prismatic_min=min;prismatic_max=max;} private: TV_BOOL Equality_Constraint() const {return TV::Componentwise_And(constrain,TV::Componentwise_Greater_Equal(prismatic_min,prismatic_max));} public: //##################################################################### bool Has_Prismatic_Constraint() const PHYSBAM_OVERRIDE; void Constrain_Prismatically(TV& translation) const PHYSBAM_OVERRIDE; // This is in joint space void Constrain_Relative_Linear_Velocity(const FRAME<TV>& parent_frame,TV& relative_linear_velocity) const PHYSBAM_OVERRIDE; // This is in world space. TV Prismatic_Component_Translation() const PHYSBAM_OVERRIDE; void Prismatic_Constraint_Matrix(const FRAME<TV>& parent_frame,MATRIX_MXN<T>& constrained_matrix,MATRIX_MXN<T>* unconstrained_matrix=0) const PHYSBAM_OVERRIDE; //##################################################################### }; template<class T_input> class PRISMATIC_TWIST_JOINT<VECTOR<T_input,1> >:public JOINT<VECTOR<T_input,1> > { typedef T_input T;typedef JOINT<VECTOR<T,1> > BASE; public: PRISMATIC_TWIST_JOINT() {PHYSBAM_FATAL_ERROR();} virtual ~PRISMATIC_TWIST_JOINT(); }; } #endif
41.754386
163
0.669748
3f51a8d3ceaa37731f0bdce2ca21a622508194c0
2,875
h
C
third_party/wpilibsuite/allwpilib/hal/src/main/native/sim/MockData/DIODataInternal.h
GregPikitis/robot-code-public
9671deebff32336fea9865daf0f54d7925c36dd8
[ "MIT" ]
2
2018-07-28T17:30:42.000Z
2018-09-12T18:14:20.000Z
third_party/wpilibsuite/allwpilib/hal/src/main/native/sim/MockData/DIODataInternal.h
GregPikitis/robot-code-public
9671deebff32336fea9865daf0f54d7925c36dd8
[ "MIT" ]
2
2018-09-23T01:03:48.000Z
2019-08-30T19:11:10.000Z
third_party/wpilibsuite/allwpilib/hal/src/main/native/sim/MockData/DIODataInternal.h
GregPikitis/robot-code-public
9671deebff32336fea9865daf0f54d7925c36dd8
[ "MIT" ]
2
2018-07-28T14:53:16.000Z
2018-09-20T19:52:51.000Z
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include <atomic> #include <memory> #include <support/mutex.h> #include "MockData/DIOData.h" #include "MockData/NotifyListenerVector.h" namespace hal { class DIOData { public: int32_t RegisterInitializedCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelInitializedCallback(int32_t uid); void InvokeInitializedCallback(HAL_Value value); HAL_Bool GetInitialized(); void SetInitialized(HAL_Bool initialized); int32_t RegisterValueCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelValueCallback(int32_t uid); void InvokeValueCallback(HAL_Value value); HAL_Bool GetValue(); void SetValue(HAL_Bool value); int32_t RegisterPulseLengthCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelPulseLengthCallback(int32_t uid); void InvokePulseLengthCallback(HAL_Value value); double GetPulseLength(); void SetPulseLength(double pulseLength); int32_t RegisterIsInputCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelIsInputCallback(int32_t uid); void InvokeIsInputCallback(HAL_Value value); HAL_Bool GetIsInput(); void SetIsInput(HAL_Bool isInput); int32_t RegisterFilterIndexCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelFilterIndexCallback(int32_t uid); void InvokeFilterIndexCallback(HAL_Value value); int32_t GetFilterIndex(); void SetFilterIndex(int32_t filterIndex); virtual void ResetData(); private: wpi::mutex m_registerMutex; std::atomic<HAL_Bool> m_initialized{false}; std::shared_ptr<NotifyListenerVector> m_initializedCallbacks = nullptr; std::atomic<HAL_Bool> m_value{true}; std::shared_ptr<NotifyListenerVector> m_valueCallbacks = nullptr; std::atomic<double> m_pulseLength{0.0}; std::shared_ptr<NotifyListenerVector> m_pulseLengthCallbacks = nullptr; std::atomic<HAL_Bool> m_isInput{true}; std::shared_ptr<NotifyListenerVector> m_isInputCallbacks = nullptr; std::atomic<int32_t> m_filterIndex{-1}; std::shared_ptr<NotifyListenerVector> m_filterIndexCallbacks = nullptr; }; extern DIOData* SimDIOData; } // namespace hal
39.383562
80
0.674783
277ac2edb8e0c1e60cf3171b04625cdeb0690da3
8,488
h
C
aws-cpp-sdk-apigatewayv2/include/aws/apigatewayv2/model/MutualTlsAuthenticationInput.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-apigatewayv2/include/aws/apigatewayv2/model/MutualTlsAuthenticationInput.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-apigatewayv2/include/aws/apigatewayv2/model/MutualTlsAuthenticationInput.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/apigatewayv2/ApiGatewayV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ApiGatewayV2 { namespace Model { class AWS_APIGATEWAYV2_API MutualTlsAuthenticationInput { public: MutualTlsAuthenticationInput(); MutualTlsAuthenticationInput(Aws::Utils::Json::JsonView jsonValue); MutualTlsAuthenticationInput& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline const Aws::String& GetTruststoreUri() const{ return m_truststoreUri; } /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline bool TruststoreUriHasBeenSet() const { return m_truststoreUriHasBeenSet; } /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline void SetTruststoreUri(const Aws::String& value) { m_truststoreUriHasBeenSet = true; m_truststoreUri = value; } /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline void SetTruststoreUri(Aws::String&& value) { m_truststoreUriHasBeenSet = true; m_truststoreUri = std::move(value); } /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline void SetTruststoreUri(const char* value) { m_truststoreUriHasBeenSet = true; m_truststoreUri.assign(value); } /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreUri(const Aws::String& value) { SetTruststoreUri(value); return *this;} /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreUri(Aws::String&& value) { SetTruststoreUri(std::move(value)); return *this;} /** * <p>An Amazon S3 URL that specifies the truststore for mutual TLS authentication, * for example, * s3://<replaceable>bucket-name</replaceable>/<replaceable>key-name</replaceable>. * The truststore can contain certificates from public or private certificate * authorities. To update the truststore, upload a new version to S3, and then * update your custom domain name to use the new version. To update the truststore, * you must have permissions to access the S3 object.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreUri(const char* value) { SetTruststoreUri(value); return *this;} /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline const Aws::String& GetTruststoreVersion() const{ return m_truststoreVersion; } /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline bool TruststoreVersionHasBeenSet() const { return m_truststoreVersionHasBeenSet; } /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline void SetTruststoreVersion(const Aws::String& value) { m_truststoreVersionHasBeenSet = true; m_truststoreVersion = value; } /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline void SetTruststoreVersion(Aws::String&& value) { m_truststoreVersionHasBeenSet = true; m_truststoreVersion = std::move(value); } /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline void SetTruststoreVersion(const char* value) { m_truststoreVersionHasBeenSet = true; m_truststoreVersion.assign(value); } /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreVersion(const Aws::String& value) { SetTruststoreVersion(value); return *this;} /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreVersion(Aws::String&& value) { SetTruststoreVersion(std::move(value)); return *this;} /** * <p>The version of the S3 object that contains your truststore. To specify a * version, you must have versioning enabled for the S3 bucket.</p> */ inline MutualTlsAuthenticationInput& WithTruststoreVersion(const char* value) { SetTruststoreVersion(value); return *this;} private: Aws::String m_truststoreUri; bool m_truststoreUriHasBeenSet; Aws::String m_truststoreVersion; bool m_truststoreVersionHasBeenSet; }; } // namespace Model } // namespace ApiGatewayV2 } // namespace Aws
46.130435
140
0.716423
8f65dbe39e900266b6ff68aa7371c59556e291ad
7,079
h
C
Grammar.h
ogorodnikoff2012/LR-parser
cceeab196e17662976f333096ce81b264e9e8b21
[ "MIT-0" ]
null
null
null
Grammar.h
ogorodnikoff2012/LR-parser
cceeab196e17662976f333096ce81b264e9e8b21
[ "MIT-0" ]
null
null
null
Grammar.h
ogorodnikoff2012/LR-parser
cceeab196e17662976f333096ce81b264e9e8b21
[ "MIT-0" ]
null
null
null
// // Created by xenon on 18.11.17. // #ifndef LR1_GRAMMAR_H #define LR1_GRAMMAR_H #include <string> #include <vector> #include <set> #include <unordered_set> #include <unordered_map> #include <map> template <class T> class Grammar { public: typedef int symbol_t; typedef std::pair<symbol_t, std::vector<symbol_t>> Rule; static constexpr symbol_t EOL = 0; private: std::vector<T> terminals; std::vector<std::string> nonterminals; std::vector<Rule> rules; std::set<symbol_t> epsProductive; std::map<symbol_t, std::set<symbol_t>> first; symbol_t rootSymbol; static void firstSetDfs(const std::vector<std::vector<symbol_t>> &gr, symbol_t v, std::unordered_set<symbol_t> &accessible) { accessible.insert(v); if (v < 0) { return; } for (auto u : gr[v]) { if (accessible.find(u) == accessible.end()) { firstSetDfs(gr, u, accessible); } } } public: Grammar() : terminals(), nonterminals(), rules(), epsProductive(), rootSymbol(-1) { newNonterminal("EOL"); } symbol_t getRootSymbol() const { return rootSymbol; } void setRootSymbol(symbol_t rootSymbol) { this->rootSymbol = rootSymbol; } symbol_t newTerminal(const T& c) { terminals.push_back(c); return -static_cast<int>(terminals.size()); } symbol_t newNonterminal(const std::string& name) { nonterminals.push_back(name); return static_cast<int>(nonterminals.size()) - 1; } int addRule(symbol_t leftPart, std::initializer_list<symbol_t> rightPart) { rules.push_back(std::make_pair(leftPart, std::vector<symbol_t>(rightPart))); return rules.size() - 1; } bool isValidSymbol(symbol_t token) const { return (token >= 0 && token < nonterminals.size()) || (token < 0 && -token <= terminals.size()); } void findEpsProductiveSymbols() { epsProductive.clear(); unsigned long epsSize; do { epsSize = epsProductive.size(); for (uint32_t i = 0; i < rules.size(); ++i) { bool isEpsProductive = true; for (symbol_t s : rules[i].second) { isEpsProductive &= epsProductive.find(s) != epsProductive.end(); } if (isEpsProductive) { epsProductive.insert(rules[i].first); } } } while (epsSize != epsProductive.size()); } bool isEpsProductive(symbol_t symbol) const { return epsProductive.find(symbol) != epsProductive.end(); } void findFirstSets() { std::vector<std::vector<symbol_t>> graph(nonterminals.size()); for (uint32_t i = 0; i < rules.size(); ++i) { for (uint32_t j = 0; j < rules[i].second.size(); ++j) { graph[rules[i].first].push_back(rules[i].second[j]); if (!isEpsProductive(rules[i].second[j])) { break; } } } std::vector<std::unordered_set<symbol_t>> accessible(graph.size()); for (uint32_t i = 0; i < graph.size(); ++i) { firstSetDfs(graph, i, accessible[i]); } for (uint32_t i = 0; i < accessible.size(); ++i) { for (symbol_t s : accessible[i]) { if (s < 0) { first[i].insert(s); } } } for (uint32_t i = 0; i < terminals.size(); ++i) { first[kthTerminal(i)] = std::set<symbol_t>{kthTerminal(i)}; } } const std::set<symbol_t>& getFirst(symbol_t symbol) const { return first.at(symbol); } void printRule(int ruleIdx, std::ostream& out = std::cout) const { out << nonterminals[rules[ruleIdx].first]; out << " ->"; for (symbol_t s : rules[ruleIdx].second) { out << ' '; if (s < 0) { out << terminals[-1 - s]; } else { out << nonterminals[s]; } } } symbol_t kthTerminal(uint32_t k) const { return -1 - static_cast<symbol_t>(k); } symbol_t kthNonterminal(uint32_t k) const { return static_cast<symbol_t>(k); } void printDebugInfo(std::ostream& out = std::cout) { out << "### Terminals:" << std::endl; for (uint32_t i = 0; i < terminals.size(); ++i) { symbol_t s = kthTerminal(i); out << s << " '" << terminals[i] << '\'' << std::endl; } out << "### Nonterminals:" << std::endl; for (uint32_t i = 0; i < nonterminals.size(); ++i) { symbol_t s = kthNonterminal(i); out << s << " " << nonterminals[i]; if (isEpsProductive(s)) { out << " (eps-productive)"; } out << std::endl; } out << "### Rules:" << std::endl; for (uint32_t i = 0; i < rules.size(); ++i) { printRule(i, out); out << std::endl; } out << "### First:" << std::endl; for (uint32_t i = 0; i < nonterminals.size(); ++i) { symbol_t s = kthNonterminal(i); out << "First(" << s << ") = {"; if (!first[s].empty()) { auto iter = first[s].begin(); out << *iter; ++iter; while (iter != first[s].end()) { out << ", " << *iter; ++iter; } } out << '}' << std::endl; } } int getRulesCount() const { return rules.size(); } const Rule& getRule(int idx) const { return rules[idx]; } void build() { findEpsProductiveSymbols(); findFirstSets(); } template <class Iter> std::unordered_set<symbol_t> getFirst(Iter begin, Iter end, symbol_t rightContext) const { std::unordered_set<symbol_t> answer; bool foundNotEpsProductive = false; while (begin != end && !foundNotEpsProductive) { symbol_t s = *begin; answer.insert(first.at(s).begin(), first.at(s).end()); if (isEpsProductive(s)) { ++begin; } else { foundNotEpsProductive = true; } } if (!foundNotEpsProductive) { answer.insert(rightContext); } return answer; } const std::vector<Rule>& getRules() const { return rules; } const T& getTerminal(symbol_t s) const { return terminals[-1 - s]; } const std::string& getNonterminal(symbol_t s) const { return nonterminals[s]; } symbol_t getFirstValidSymbol() const { return -terminals.size(); } symbol_t getLastValidSymbol() const { return nonterminals.size() - 1; } uint32_t getTerminalsCount() const { return terminals.size(); } }; #endif //LR1_GRAMMAR_H
28.09127
94
0.511937
e9be7462e78f1d4f699c89e05479f4372b1b9e9c
17,557
c
C
src/elastic-connection.c
Bubu/fts-elastic
164ef965b503b1424f784ba93119f8516c0e39f2
[ "MIT" ]
null
null
null
src/elastic-connection.c
Bubu/fts-elastic
164ef965b503b1424f784ba93119f8516c0e39f2
[ "MIT" ]
null
null
null
src/elastic-connection.c
Bubu/fts-elastic
164ef965b503b1424f784ba93119f8516c0e39f2
[ "MIT" ]
3
2020-08-05T01:53:47.000Z
2021-10-20T03:36:21.000Z
/* Copyright (c) 2006-2014 Dovecot authors, see the included COPYING file */ /* Copyright (c) 2014 Joshua Atkins <josh@ascendantcom.com> */ /* Copyright (c) 2019-2020 Filip Hanes <filip.hanes@gmail.com> */ #include "lib.h" #include "array.h" #include "hash.h" #include "str.h" #include "strescape.h" #include "ioloop.h" #include "istream.h" #include "mail-namespace.h" #include "http-url.h" #include "http-client.h" #include "fts-elastic-plugin.h" #include "elastic-connection.h" #include <json-c/json.h> #include <stdio.h> struct elastic_search_context { pool_t pool; const char *scroll_id; struct fts_result *result; int found; }; struct elastic_connection { struct mail_namespace *ns; const char *username; /* ElasticSearch HTTP API information */ char *http_host; in_port_t http_port; char *http_base_path; char *http_failure; int request_status; /* for streaming processing of results */ struct istream *payload; struct io *io; struct json_tokener *tok; enum elastic_post_type post_type; /* context for the current search */ struct elastic_search_context *ctx; /* if we should send ?refresh=true on update _bulk requests */ unsigned int refresh_on_update:1; unsigned int debug:1; unsigned int http_ssl:1; }; int elastic_connection_init(const struct fts_elastic_settings *set, struct mail_namespace *ns, struct elastic_connection **conn_r, const char **error_r) { FUNC_START(); struct http_client_settings http_set; struct elastic_connection *conn = NULL; struct http_url *http_url = NULL; const char *error = NULL; if (error_r == NULL || set == NULL || conn_r == NULL) { i_debug("fts_elastic: error initialising ElasticSearch connection"); return -1; } /* validate the url */ if (http_url_parse(set->url, NULL, 0, pool_datastack_create(), &http_url, &error) < 0) { *error_r = t_strdup_printf( "fts_elastic: Failed to parse HTTP url: %s", error); return -1; } conn = i_new(struct elastic_connection, 1); conn->ctx = i_new(struct elastic_search_context, 1); conn->ns = ns; conn->username = ns->owner ? ns->owner->username : "-"; #if defined(DOVECOT_PREREQ) && DOVECOT_PREREQ(2,3) conn->http_host = i_strdup(http_url->host.name); #else conn->http_host = i_strdup(http_url->host_name); #endif conn->http_port = http_url->port; conn->http_base_path = i_strdup(http_url->path); conn->http_ssl = http_url->have_ssl; conn->debug = set->debug; conn->refresh_on_update = set->refresh_on_update; conn->tok = json_tokener_new(); /* guard against init being called multiple times */ if (elastic_http_client == NULL) { i_zero(&http_set); http_set.max_idle_time_msecs = 5 * 1000; http_set.max_parallel_connections = 1; http_set.max_pipelined_requests = 1; http_set.max_redirects = 1; http_set.max_attempts = 3; http_set.debug = set->debug; http_set.rawlog_dir = set->rawlog_dir; elastic_http_client = http_client_init(&http_set); } *conn_r = conn; FUNC_END_RET_INT(0); return 0; } void elastic_connection_deinit(struct elastic_connection *conn) { FUNC_START(); if (conn != NULL) { i_free(conn->http_host); i_free(conn->http_base_path); i_free(conn->ctx); json_tokener_free(conn->tok); i_free(conn); } FUNC_END(); } /* Checks response status code from _bulk request */ static void elastic_connection_bulk_response(const struct http_response *response, struct elastic_connection *conn) { FUNC_START(); if (response != NULL && conn != NULL ) { /* 200 OK, 204 continue */ if (response->status / 100 != 2) { i_error("fts_elastic: Indexing failed: %s", response->reason); conn->request_status = -1; } } FUNC_END(); } /* Parses response payload to json from _search request */ static void elastic_connection_payload_input(struct elastic_connection *conn) { FUNC_START(); const unsigned char *data = NULL; json_object *jobj = NULL; enum json_tokener_error jerr; size_t size; int ret = -1; /* continue appending data so long as it is available */ while ((ret = i_stream_read_data(conn->payload, &data, &size, 0)) > 0) { jobj = json_tokener_parse_ex(conn->tok, (const char *)data, size); i_stream_skip(conn->payload, size); jerr = json_tokener_get_error(conn->tok); if (jerr == json_tokener_continue) { if (ret < 0) i_error("fts_elastic: json response not finished"); } else if (jerr == json_tokener_success) { /* extract values from resulting json object */ elastic_connection_json(conn, jobj); } else { i_error("fts_elastic: json tokener error: %s", json_tokener_error_desc(jerr)); break; } } if (ret == 0) { /* we will be called again for more data */ } else { if (conn->payload->stream_errno != 0) { i_error("fts_elastic: failed to read payload from HTTP server: %m"); conn->request_status = -1; } /* clean-up */ io_remove(&conn->io); i_stream_unref(&conn->payload); } FUNC_END(); } /* Parses HTTP response from _search request */ static void elastic_connection_search_response(const struct http_response *response, struct elastic_connection *conn) { FUNC_START(); /* 404's usually mean the index is missing. * it could mean you also hit a non-ES service * 400 means request json is malformed */ if (response->status / 100 != 2) { i_error("fts_elastic: search failed: %d %s", response->status, response->reason); conn->request_status = -1; } if (response->payload == NULL) { i_error("fts_elastic: search failed: empty response payload"); conn->request_status = -1; return; } i_stream_ref(response->payload); conn->payload = response->payload; conn->io = io_add_istream(response->payload, elastic_connection_payload_input, conn); elastic_connection_payload_input(conn); FUNC_END(); } /* Callback from HTTP request * according to post_type decides which callback calls */ static void elastic_connection_http_response(const struct http_response *response, struct elastic_connection *conn) { FUNC_START(); if (response != NULL && conn != NULL) { switch (conn->post_type) { case ELASTIC_POST_TYPE_SEARCH: elastic_connection_search_response(response, conn); break; case ELASTIC_POST_TYPE_BULK: elastic_connection_bulk_response(response, conn); break; case ELASTIC_POST_TYPE_REFRESH: case ELASTIC_POST_TYPE_DELETE: case ELASTIC_POST_TYPE_DELETE_BY_QUERY: /* not implemented */ break; } } FUNC_END(); } /* Performs HTTP POST/DELETE request with callback */ int elastic_connection_post(struct elastic_connection *conn, const char *path, string_t *data) { FUNC_START(); struct http_client_request *http_req = NULL; struct istream *post_payload = NULL; const char *method = "POST"; if (conn == NULL || path == NULL || data == NULL) { i_error("fts_elastic: connection_post: critical error during POST"); return -1; } if (conn->post_type == ELASTIC_POST_TYPE_DELETE) { method = "DELETE"; } http_req = http_client_request(elastic_http_client, method, conn->http_host, path, elastic_connection_http_response, conn); http_client_request_set_port(http_req, conn->http_port); http_client_request_set_ssl(http_req, conn->http_ssl); /* XXX: should be application/x-ndjson for bulk updates, but why when this works? */ http_client_request_add_header(http_req, "Content-Type", "application/json"); post_payload = i_stream_create_from_buffer(data); http_client_request_set_payload(http_req, post_payload, TRUE); i_stream_unref(&post_payload); http_client_request_submit(http_req); conn->request_status = 0; http_client_wait(elastic_http_client); FUNC_END_RET_INT(conn->request_status); return conn->request_status; } /* Iterates over json array hits * and fills fts_result->definite_uids * and fts->result->scores if present */ void elastic_connection_search_hits(struct elastic_search_context *ctx, struct json_object *hits) { FUNC_START(); struct fts_score_map *scores; struct json_object *hit; struct json_object *jval; uint32_t uid = 0; int hits_count = 0; int i = 0; const char *_id; const char *const *id_part; if (ctx == NULL || hits == NULL) { i_error("fts_elastic: select_json: critical error while processing result JSON"); return; } if (json_object_get_type(hits) != json_type_array) { i_error("fts_elastic: select_json: response hits are not array"); return; } hits_count = json_object_array_length(hits); for (i = 0; i < hits_count; i++) { hit = json_object_array_get_idx(hits, i); if (!json_object_object_get_ex(hit, "_id", &jval)) { i_warning("fts_elastic: key _id not in search response hit:%s", json_object_to_json_string(hit)); continue; } _id = json_object_get_string(jval); id_part = t_strsplit_spaces(_id, "/"); if (str_to_uint32(*id_part, &uid) < 0 || uid == 0) { i_warning("fts_elastic: uid <= 0 in _id:\"%s\"", _id); continue; } /* we currently search only in one mbox id_part++; if (*id_part == NULL) { i_warning("fts_elastic: mbox_guid not found in _id:\"%s\"", _id); guid = ""; continue; } if (strcmp(guid, *id_part) != 0) { ctx->result = get_fts_result_by_guid(ctx, *id_part); } else { // We are using already box result from previous hit } */ ctx->found += 1; if (seq_range_array_add(&ctx->result->definite_uids, uid)) { /* duplicate result */ } else if (json_object_object_get_ex(hit, "_score", &jval)) { scores = array_append_space(&ctx->result->scores); scores->uid = uid; scores->score = json_object_get_double(jval); } /* parse user from _id id_part++; if (*id_part == NULL) { i_warning("fts_elastic: user not found in _id:\"%s\"", _id); continue; } user = p_strdup(ctx->pool, *id_part); */ } FUNC_END(); } /* extract values from resulting json object */ void elastic_connection_json(struct elastic_connection *conn, json_object *jobj) { FUNC_START(); struct json_object *jvalue = NULL; i_assert(jobj != NULL); /* Check for error description */ if (json_object_object_get_ex(jobj, "error", &jvalue)) { i_error("fts_elastic: %s", json_object_get_string(jvalue)); return; } /* Check if errors are present in response */ if (json_object_object_get_ex(jobj, "errors", &jvalue)) { i_error("fts_elastic: errors in response"); } /* Check if _scroll_id are present in response */ if (json_object_object_get_ex(jobj, "_scroll_id", &jvalue)) { conn->ctx->scroll_id = p_strdup(conn->ctx->pool, json_object_get_string(jvalue)); } switch (conn->post_type) { case ELASTIC_POST_TYPE_SEARCH: if (!json_object_object_get_ex(jobj, "hits", &jvalue)) { i_error("fts_elastic: no .hits in search response"); break; } if (!json_object_object_get_ex(jvalue, "hits", &jvalue)) { i_error("fts_elastic: no .hits.hits in search response"); break; } elastic_connection_search_hits(conn->ctx, jvalue); break; case ELASTIC_POST_TYPE_BULK: case ELASTIC_POST_TYPE_REFRESH: case ELASTIC_POST_TYPE_DELETE: case ELASTIC_POST_TYPE_DELETE_BY_QUERY: /* not implemented */ break; } FUNC_END(); } /* Performs elastic _bulk request * checking only response status */ int elastic_connection_bulk(struct elastic_connection *conn, string_t *cmd) { FUNC_START(); const char *path = NULL; if (conn == NULL || cmd == NULL) { i_error("fts_elastic: connection_bulk: conn or cmd is NULL"); return -1; } conn->post_type = ELASTIC_POST_TYPE_BULK; path = t_strconcat(conn->http_base_path, "_bulk" "?routing=", conn->username, conn->refresh_on_update ? "&refresh=true" : "", NULL); elastic_connection_post(conn, path, cmd); FUNC_END(); return conn->request_status; } int elastic_connection_refresh(struct elastic_connection *conn) { FUNC_START(); const char *path = NULL; string_t *query = t_str_new_const("", 0); if (conn == NULL) { i_error("fts_elastic: refresh: critical error"); return -1; } conn->post_type = ELASTIC_POST_TYPE_REFRESH; path = t_strconcat(conn->http_base_path, "_refresh", NULL); elastic_connection_post(conn, path, query); if (conn->request_status < 0) return -1; FUNC_END_RET_INT(0); return 0; } /* Performs elastic search query * parses json response * and fills fts_result */ int elastic_connection_search(struct elastic_connection *conn, pool_t pool, string_t *query, struct fts_result *result_r) { FUNC_START(); const char *path = NULL; if (conn == NULL || query == NULL || result_r == NULL) { i_error("fts_elastic: critical error during search"); return -1; } i_zero(conn->ctx); conn->ctx->pool = pool; conn->ctx->result = result_r; conn->ctx->found = 0; conn->post_type = ELASTIC_POST_TYPE_SEARCH; i_free_and_null(conn->http_failure); json_tokener_reset(conn->tok); path = t_strconcat(conn->http_base_path, "_search?routing=", conn->username, NULL); elastic_connection_post(conn, path, query); if (conn->request_status < 0) return -1; FUNC_END_RET_INT(conn->ctx->found); return conn->ctx->found; } /* Performs elastic search query with scroll * parses json response * and fills fts_result */ int elastic_connection_search_scroll(struct elastic_connection *conn, pool_t pool, string_t *query, struct fts_result *result_r) { FUNC_START(); static const char *SCROLL_TIMEOUT = "7s"; const char *path = NULL; if (conn == NULL || query == NULL || result_r == NULL) { i_error("fts_elastic: critical error during search scroll"); return -1; } i_zero(conn->ctx); i_assert(conn->ctx != NULL); conn->ctx->pool = pool; conn->ctx->result = result_r; conn->ctx->found = 0; conn->post_type = ELASTIC_POST_TYPE_SEARCH; i_free_and_null(conn->http_failure); json_tokener_reset(conn->tok); path = t_strconcat(conn->http_base_path, "_search?routing=", conn->username, "&scroll=", SCROLL_TIMEOUT, NULL); elastic_connection_post(conn, path, query); if (conn->ctx->scroll_id == NULL) { i_error("fts_elastic: _scroll_id not found in scroll response"); return 0; } /* TODO: strip index (last segment) from path to allow elastic behind proxy */ path = "/_search/scroll"; while (conn->ctx->found >= 9998) { conn->ctx->found = 0; str_truncate(query, 0); str_printfa(query, "{\"scroll\":\"%s\", \"scroll_id\":\"%s\"}", SCROLL_TIMEOUT, conn->ctx->scroll_id); elastic_connection_post(conn, path, query); } /* DELETE search scroll context */ conn->post_type = ELASTIC_POST_TYPE_DELETE; str_truncate(query, 0); str_printfa(query, "{\"scroll_id\":\"%s\"}", conn->ctx->scroll_id); elastic_connection_post(conn, path, query); if (conn->request_status < 0) return -1; FUNC_END_RET_INT(conn->ctx->found); return conn->ctx->found; } /* Performs elastic search delete by query */ int elastic_connection_delete_by_query(struct elastic_connection *conn, pool_t pool, string_t *query) { FUNC_START(); const char *path = NULL; if (conn == NULL || query == NULL) { i_error("fts_elastic: critical error during search scroll"); return -1; } i_zero(conn->ctx); conn->ctx->pool = pool; conn->post_type = ELASTIC_POST_TYPE_DELETE_BY_QUERY; i_free_and_null(conn->http_failure); path = t_strconcat(conn->http_base_path, "_delete_by_query?routing=", conn->username, NULL); elastic_connection_post(conn, path, query); if (conn->request_status < 0) return -1; FUNC_END_RET_INT(conn->ctx->found); return conn->ctx->found; }
30.640489
90
0.619069
eb648d425c4da7ee75517ac85fe4a498656a24be
336
h
C
Classes/CodeGenerator/Objc/ObjectModel/Types/FLObjcValueType.h
fishlamp-released/FishLamp3
216293cc4d08945853ac271affff0968f8137655
[ "MIT" ]
1
2015-12-30T13:15:11.000Z
2015-12-30T13:15:11.000Z
Classes/CodeGenerator/Objc/ObjectModel/Types/FLObjcValueType.h
fishlamp-released/FishLamp3
216293cc4d08945853ac271affff0968f8137655
[ "MIT" ]
null
null
null
Classes/CodeGenerator/Objc/ObjectModel/Types/FLObjcValueType.h
fishlamp-released/FishLamp3
216293cc4d08945853ac271affff0968f8137655
[ "MIT" ]
null
null
null
// // FLObjcValueType.h // CodeGenerator // // Created by Mike Fullerton on 5/31/13. // Copyright (c) 2013 Mike Fullerton. All rights reserved. // #import "FLObjcType.h" @class FLObjcName; @interface FLObjcValueType : FLObjcType + (id) objcValueType:(FLObjcName*) typeName importFileName:(NSString*) importFileName; @end
19.764706
59
0.714286
7532bab9997625bcf804fe43472ec72c984aa768
598
h
C
plugin_III/game_III/CColSphere.h
gta-chaos-mod/plugin-sdk
e3bf176337774a2afc797a47825f81adde78e899
[ "Zlib" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
plugin_III/game_III/CColSphere.h
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
89
2016-05-08T06:42:36.000Z
2022-03-29T06:49:09.000Z
plugin_III/game_III/CColSphere.h
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto 3) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CSphere.h" #include "tColSurface.h" class PLUGIN_API CColSphere : public CSphere { public: tColSurface m_surface; SUPPORTED_10EN_11EN_STEAM CColSphere(); SUPPORTED_10EN_11EN_STEAM void Set(float radius, CVector &center, unsigned char material, unsigned char flag); }; VALIDATE_SIZE(CColSphere, 0x14); #include "meta/meta.CColSphere.h"
23.92
114
0.742475
55e942282aa9f2ebcc65994c2d38f413ba8c176a
954
c
C
kernel/sched/lock.c
racing19th/MiraiOS
c20de0d33cab1f56b9d44860131fc191eb2d3d22
[ "MIT" ]
12
2017-11-25T04:15:18.000Z
2022-03-12T08:53:34.000Z
kernel/sched/lock.c
racing19th/MiraiOS
c20de0d33cab1f56b9d44860131fc191eb2d3d22
[ "MIT" ]
null
null
null
kernel/sched/lock.c
racing19th/MiraiOS
c20de0d33cab1f56b9d44860131fc191eb2d3d22
[ "MIT" ]
3
2017-11-29T10:15:54.000Z
2021-06-25T17:17:32.000Z
#include <sched/lock.h> #include <sched/spinlock.h> #include <sched/readyqueue.h> #include <stddef.h> void semInit(semaphore_t *semaphore, int value) { semaphore->value = value; } void semWait(semaphore_t *semaphore) { thread_t curThread = getCurrentThread(); acquireSpinlock(&curThread->lock); acquireSpinlock(&semaphore->lock); if (semaphore->value > 0) { semaphore->value--; releaseSpinlock(&semaphore->lock); releaseSpinlock(&curThread->lock); return; } threadQueuePush(&semaphore->queue, curThread); releaseSpinlock(&semaphore->lock); curThread->state = THREADSTATE_LOCKWAIT; kthreadStop(); } void semSignal(semaphore_t *semaphore) { acquireSpinlock(&semaphore->lock); if (semaphore->value > 0) { semaphore->value++; goto end; } struct ThreadQueueEntry *freed = threadQueuePop(&semaphore->queue); if (freed) { readyQueuePush(freed); } else { semaphore->value++; } end: releaseSpinlock(&semaphore->lock); }
21.2
68
0.719078
8a26e6554e14efe83261ede534039d213a4168c9
2,805
h
C
Android/text/SpannableString.h
mxenabled/androidpp
5fd587157232d1d92bcc9402c0b9acfb5e65034b
[ "ICU", "BSD-3-Clause", "Apache-2.0", "MIT" ]
3
2016-03-25T14:11:57.000Z
2021-08-24T19:46:11.000Z
Android/text/SpannableString.h
mxenabled/androidpp
5fd587157232d1d92bcc9402c0b9acfb5e65034b
[ "ICU", "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
Android/text/SpannableString.h
mxenabled/androidpp
5fd587157232d1d92bcc9402c0b9acfb5e65034b
[ "ICU", "BSD-3-Clause", "Apache-2.0", "MIT" ]
2
2018-01-18T04:38:16.000Z
2019-05-29T02:20:44.000Z
// // SpannableString.h // Androidpp // // Created by Saul Howard on 1/15/14. // Copyright (c) 2014 MoneyDesktop. All rights reserved. // #ifndef Androidpp_SpannableString_h #define Androidpp_SpannableString_h #include "AndroidMacros.h" #include "Android/text/SpannableStringInternal.h" #include "Android/text/CharSequence.h" #include "Android/text/GetChars.h" #include "Android/text/Spannable.h" #include <unicode/unistr.h> #include <memory> using namespace icu; using namespace std; ANDROID_BEGIN /** * This is the class for text whose content is immutable but to which * markup objects can be attached and detached. * For mutable text, see {@link SpannableStringBuilder}. */ class SpannableString : public SpannableStringInternal, public enable_shared_from_this<SpannableString>, public virtual CharSequence, public virtual GetChars, public virtual Spannable { public: SpannableString(shared_ptr<CharSequence> source, int start, int end) : SpannableStringInternal(this, source, start, end) { } SpannableString(shared_ptr<CharSequence> source) : SpannableStringInternal(this, source, 0, source->length()) { } static shared_ptr<SpannableString> valueOf(shared_ptr<CharSequence> source); void setSpan(shared_ptr<Object> what, int start, int end, int flags) { SpannableStringInternal::setSpan(shared_from_this(), what, start, end, flags); } void removeSpan(shared_ptr<Object> what) { SpannableStringInternal::removeSpan(shared_from_this(), what); } shared_ptr<CharSequence> subSequence(int start, int end); int length() { return SpannableStringInternal::length(); } UChar charAt(int i) { return SpannableStringInternal::charAt(i); } shared_ptr<String> toString() { return SpannableStringInternal::toString(); } /* subclasses must do subSequence() to preserve type */ void getChars(int start, int end, UnicodeString &dest, int off) { return SpannableStringInternal::getChars(start, end, dest, off); } int getSpanStart(shared_ptr<Object> what) { return SpannableStringInternal::getSpanStart(what); } int getSpanEnd(shared_ptr<Object> what) { return SpannableStringInternal::getSpanEnd(what); } int getSpanFlags(shared_ptr<Object> what) { return SpannableStringInternal::getSpanFlags(what); } vector<shared_ptr<Object>> getSpans(int queryStart, int queryEnd, string kind) { return SpannableStringInternal::getSpans(queryStart, queryEnd, kind); } int nextSpanTransition(int start, int limit, string kind) { return SpannableStringInternal::nextSpanTransition(start, limit, kind); } }; ANDROID_END #endif
28.917526
185
0.7041
8abbacc272b75ef29a2f70ff5b6254bc24640345
1,654
c
C
caf/tests/annealingTest.c
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
209
2016-11-12T14:16:50.000Z
2022-03-30T04:44:11.000Z
caf/tests/annealingTest.c
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
468
2016-11-06T01:16:43.000Z
2022-03-31T16:24:37.000Z
caf/tests/annealingTest.c
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
75
2017-03-09T22:19:27.000Z
2022-03-14T22:03:33.000Z
/* * Copyright (C) 2009-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ #include "CuTest.h" #include "sonLib.h" #include "stCaf.h" #include "stPinchGraphs.h" void stCaf_anneal2(stPinchThreadSet *threadSet, stPinch *(*pinchIterator)(void *), void *extraArg); void stCaf_annealBetweenAdjacencyComponents2(stPinchThreadSet *threadSet, stPinch *(*pinchIterator)(void *), void *extraArg, bool (*filterFn)(stPinchSegment *, stPinchSegment *)); static stPinch *randomPinch(void *extraArg) { if(st_random() < 0.01) { return NULL; } static stPinch pinch; pinch = stPinchThreadSet_getRandomPinch(extraArg); return &pinch; } static void testAnnealing(CuTest *testCase) { //return; for (int64_t test = 0; test < 100; test++) { st_logInfo("Starting annealing random test %" PRIi64 "\n", test); stPinchThreadSet *threadSet = stPinchThreadSet_getRandomEmptyGraph(); stCaf_anneal2(threadSet, randomPinch, threadSet); } } static void testAnnealingBetweenAdjacencyComponents(CuTest *testCase) { //return; for (int64_t test = 0; test < 100; test++) { st_logInfo("Starting annealing between adjacency components random test %" PRIi64 "\n", test); stPinchThreadSet *threadSet = stPinchThreadSet_getRandomGraph(); stCaf_annealBetweenAdjacencyComponents2(threadSet, randomPinch, threadSet, NULL); } } CuSuite* annealingTestSuite(void) { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, testAnnealing); SUITE_ADD_TEST(suite, testAnnealingBetweenAdjacencyComponents); return suite; }
33.08
108
0.712817
8dfe40ca1953e69de3cfbd180dcb04c793fb24c1
1,568
h
C
src/main-computer/infrastructure/peripherals/microcontroller/serial_comm.h
schutzekatze/mewps
c8cf5c6e4d5c824b8dbda2363db6ccdb07d96bb7
[ "Apache-2.0" ]
null
null
null
src/main-computer/infrastructure/peripherals/microcontroller/serial_comm.h
schutzekatze/mewps
c8cf5c6e4d5c824b8dbda2363db6ccdb07d96bb7
[ "Apache-2.0" ]
null
null
null
src/main-computer/infrastructure/peripherals/microcontroller/serial_comm.h
schutzekatze/mewps
c8cf5c6e4d5c824b8dbda2363db6ccdb07d96bb7
[ "Apache-2.0" ]
null
null
null
/* * serial_comm.h * * Copyright 2017 Vladimir Nikolić */ #ifndef INFRASTRUCTURE_PERIPHERALS_HARDWARE_SERIAL_COMM_H #define INFRASTRUCTURE_PERIPHERALS_HARDWARE_SERIAL_COMM_H /* * This header declares routines for serial communication between * the main computer and the microcontroller. * * The mode used is 8N1, 8 bit character size, no parity and 1 stop bit. * All messages are fixed size of 2 bytes in network byte order, * that is, big endian. * Every message is followed by a checksum byte, a simple sum of message bytes. * If on receive the checksum is correct, an ACKNOWLEDGE byte is sent back. * If the checksum is incorrect, a NEGATIVE_ACKNOWLEDGE byte is sent back. * If an error occurs with an acknowledge byte, assume * values greater than 127 to be ACKNOWLEDGE, and less than or equal to 127 * to be NEGATIVE_ACKNOWLEDGE. * On negative acknowledge, the message is resent up to ATTEMPTS_BEFORE_ABORT times. * If all attempts fail, the communication should abort and * an error should be thrown. * Both sides of the communication should include this header, and implement * the send and receive functions specific to their platform. */ #include <stdint.h> constexpr int BAUD_RATE = 9600; const uint8_t ACKNOWLEDGE = 255; const uint8_t NEGATIVE_ACKNOWLEDGE = 0; const int ATTEMPTS_BEFORE_ABORT = 3; // These functions require platform specific implementations to use serial communication. void serial_comm_send(const uint16_t msg); uint16_t serial_comm_receive(); #endif /* INFRASTRUCTURE_PERIPHERALS_HARDWARE_SERIAL_COMM_H */
35.636364
89
0.783163
69f82b1d9fdab36574eaabdd2fba1d5f21014de7
5,902
h
C
talk/examples/login/status.h
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
5
2015-09-16T06:10:59.000Z
2019-12-25T05:30:00.000Z
talk/examples/login/status.h
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
null
null
null
talk/examples/login/status.h
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
3
2015-08-01T11:38:08.000Z
2019-11-01T05:16:09.000Z
/* * Jingle call example * Copyright 2004--2005, Google Inc. * * 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; either version 2 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 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, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _STATUS_H_ #define _STATUS_H_ #include "talk/xmpp/jid.h" #include "talk/xmpp/constants.h" #define GOOGLE_CLIENT_NODE "http://www.google.com/xmpp/client/caps" namespace buzz { class Status { public: Status() : pri_(0), show_(SHOW_NONE), available_(false), e_code_(0), phone_capability_(false), fileshare_capability_(false), know_capabilities_(false), is_google_client_(false), feedback_probation_(false) {}; ~Status() {} // These are arranged in "priority order", i.e., if we see // two statuses at the same priority but with different Shows, // we will show the one with the highest show in the following // order. enum Show { SHOW_NONE = 0, SHOW_OFFLINE = 1, SHOW_XA = 2, SHOW_AWAY = 3, SHOW_DND = 4, SHOW_ONLINE = 5, SHOW_CHAT = 6, }; const Jid & jid() const { return jid_; } int priority() const { return pri_; } Show show() const { return show_; } const std::string & status() const { return status_; } bool available() const { return available_ ; } int error_code() const { return e_code_; } const std::string & error_string() const { return e_str_; } bool know_capabilities() const { return know_capabilities_; } bool phone_capability() const { return phone_capability_; } bool fileshare_capability() const { return fileshare_capability_; } bool is_google_client() const { return is_google_client_; } const std::string & version() const { return version_; } bool feedback_probation() const { return feedback_probation_; } const std::string& sent_time() const { return sent_time_; } void set_jid(const Jid & jid) { jid_ = jid; } void set_priority(int pri) { pri_ = pri; } void set_show(Show show) { show_ = show; } void set_status(const std::string & status) { status_ = status; } void set_available(bool a) { available_ = a; } void set_error(int e_code, const std::string e_str) { e_code_ = e_code; e_str_ = e_str; } void set_know_capabilities(bool f) { know_capabilities_ = f; } void set_phone_capability(bool f) { phone_capability_ = f; } void set_fileshare_capability(bool f) { fileshare_capability_ = f; } void set_is_google_client(bool f) { is_google_client_ = f; } void set_version(const std::string & v) { version_ = v; } void set_feedback_probation(bool f) { feedback_probation_ = f; } void set_sent_time(const std::string& time) { sent_time_ = time; } void UpdateWith(const Status & new_value) { if (!new_value.know_capabilities()) { bool k = know_capabilities(); bool i = is_google_client(); bool p = phone_capability(); std::string v = version(); *this = new_value; set_know_capabilities(k); set_is_google_client(i); set_phone_capability(p); set_version(v); } else { *this = new_value; } } bool HasQuietStatus() const { if (status_.empty()) return false; return !(QuietStatus().empty()); } // Knowledge of other clients' silly automatic status strings - // Don't show these. std::string QuietStatus() const { if (jid_.resource().find("Psi") != std::string::npos) { if (status_ == "Online" || status_.find("Auto Status") != std::string::npos) return STR_EMPTY; } if (jid_.resource().find("Gaim") != std::string::npos) { if (status_ == "Sorry, I ran out for a bit!") return STR_EMPTY; } return TrimStatus(status_); } std::string ExplicitStatus() const { std::string result = QuietStatus(); if (result.empty()) { result = ShowStatus(); } return result; } std::string ShowStatus() const { std::string result; if (!available()) { result = "Offline"; } else { switch (show()) { case SHOW_AWAY: case SHOW_XA: result = "Idle"; break; case SHOW_DND: result = "Busy"; break; case SHOW_CHAT: result = "Chatty"; break; default: result = "Available"; break; } } return result; } static std::string TrimStatus(const std::string & st) { std::string s(st); int j = 0; bool collapsing = true; for (unsigned int i = 0; i < s.length(); i+= 1) { if (s[i] <= ' ' && s[i] >= 0) { if (collapsing) { continue; } else { s[j] = ' '; j += 1; collapsing = true; } } else { s[j] = s[i]; j += 1; collapsing = false; } } if (collapsing && j > 0) { j -= 1; } s.erase(j, s.length()); return s; } private: Jid jid_; int pri_; Show show_; std::string status_; bool available_; int e_code_; std::string e_str_; bool feedback_probation_; // capabilities (valid only if know_capabilities_ bool know_capabilities_; bool phone_capability_; bool fileshare_capability_; bool is_google_client_; std::string version_; std::string sent_time_; // from the jabber:x:delay element }; } #endif
27.70892
76
0.62589
a31885915d7dad8d669f96885c17e0bbbfd74de3
19,655
h
C
include/utils_list.h
openharmony-gitee-mirror/utils_native_lite
d7ab2be0cc7bf7a5af840e9b542eca1d3cf5afd4
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
include/utils_list.h
openharmony-gitee-mirror/utils_native_lite
d7ab2be0cc7bf7a5af840e9b542eca1d3cf5afd4
[ "Apache-2.0" ]
null
null
null
include/utils_list.h
openharmony-gitee-mirror/utils_native_lite
d7ab2be0cc7bf7a5af840e9b542eca1d3cf5afd4
[ "Apache-2.0" ]
1
2021-09-13T12:04:30.000Z
2021-09-13T12:04:30.000Z
/* * Copyright (c) 2020 Huawei Device Co., Ltd. * 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. */ /* * @defgroup utils_list Doubly linked list * @ingroup utils * @attention * <ul> * <li>All of the APIs provided in this module are not thread-safe.</li> * </ul> */ #ifndef _UTILS_LIST_H #define _UTILS_LIST_H #include <stdbool.h> #include "ohos_types.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif /* __cplusplus */ #endif /* __cplusplus */ typedef struct UTILS_DL_LIST { struct UTILS_DL_LIST *pstPrev; /* < Current node's pointer to the previous node */ struct UTILS_DL_LIST *pstNext; /* < Current node's pointer to the next node */ } UTILS_DL_LIST; /* * @ingroup utils_list * * @par Description: * This API is used to initialize a doubly linked list. * @attention * <ul> * <li>The parameter passed in should be ensured to be a legal pointer.</li> * </ul> * * @param list [IN] Node in a doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ static inline void UtilsListInit(UTILS_DL_LIST *list) { list->pstNext = list; list->pstPrev = list; } /* * @ingroup utils_list * @brief Point to the next node pointed to by the current node. * * @par Description: * <ul> * <li>This API is used to point to the next node pointed to by the current node.</li> * </ul> * @attention * <ul> * <li>None.</li> * </ul> * * @param object [IN] Node in the doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_FIRST(object) ((object)->pstNext) /* * @ingroup utils_list * @brief Node is the end of the list. * * @par Description: * <ul> * <li>This API is used to test node is the end of the list.</li> * </ul> * @attention * <ul> * <li>None.</li> * </ul> * * @param object [IN] Node in the doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_IS_END(list, node) ((list) == (node) ? TRUE : FALSE) /* * @ingroup utils_list * @brief Node is on the list. * * @par Description: * <ul> * <li>This API is used to test node is on the list.</li> * </ul> * @attention * <ul> * <li>None.</li> * </ul> * * @param object [IN] Node in the doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_IS_ON_QUEUE(node) ((node)->pstPrev != NULL && (node)->pstNext != NULL) /* * @ingroup utils_list * @brief Point to the previous node pointed to by the current node. * * @par Description: * <ul> * <li>This API is used to point to the previous node pointed to by the current node.</li> * </ul> * @attention * <ul> * <li>None.</li> * </ul> * * @param object [IN] Node in the doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_LAST(object) ((object)->pstPrev) /* * @ingroup utils_list * @brief Insert a new node to a doubly linked list. * * @par Description: * This API is used to insert a new node to a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param list [IN] Doubly linked list where the new node is inserted. * @param node [IN] New node to be inserted. * * @retval None * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListDelete */ static inline void UtilsListAdd(UTILS_DL_LIST *list, UTILS_DL_LIST *node) { node->pstNext = list->pstNext; node->pstPrev = list; list->pstNext->pstPrev = node; list->pstNext = node; } /* * @ingroup utils_list * @brief Insert a node to the tail of a doubly linked list. * * @par Description: * This API is used to insert a new node to the tail of a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param list [IN] Doubly linked list where the new node is inserted. * @param node [IN] New node to be inserted. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListAdd | UtilsListHeadInsert */ static inline void UtilsListTailInsert(UTILS_DL_LIST *list, UTILS_DL_LIST *node) { UtilsListAdd(list->pstPrev, node); } /* * @ingroup utils_list * @brief Insert a node to the head of a doubly linked list. * * @par Description: * This API is used to insert a new node to the head of a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param list [IN] Doubly linked list where the new node is inserted. * @param node [IN] New node to be inserted. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListAdd | UtilsListTailInsert */ static inline void UtilsListHeadInsert(UTILS_DL_LIST *list, UTILS_DL_LIST *node) { UtilsListAdd(list, node); } /* * @ingroup utils_list * * @par Description: * <ul> * <li>This API is used to delete a specified node from a doubly linked list.</li> * </ul> * @attention * <ul> * <li>The parameter passed in should be ensured to be a legal pointer.</li> * </ul> * * @param node [IN] Node to be deleted. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListAdd */ static inline void UtilsListDelete(UTILS_DL_LIST *node) { node->pstNext->pstPrev = node->pstPrev; node->pstPrev->pstNext = node->pstNext; node->pstNext = NULL; node->pstPrev = NULL; } /* * @ingroup utils_list * @brief Identify whether a specified doubly linked list is empty. * * @par Description: * <ul> * <li>This API is used to return whether a doubly linked list is empty.</li> * </ul> * @attention * <ul> * <li>The parameter passed in should be ensured to be a legal pointer.</li> * </ul> * * @param list [IN] Doubly linked list. * * @retval TRUE The doubly linked list is empty. * @retval FALSE The doubly linked list is not empty. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ static inline bool UtilsListEmpty(UTILS_DL_LIST *list) { return (bool)(list->pstNext == list); } /* * @ingroup utils_list * @brief Insert a new list to a doubly linked list. * * @par Description: * This API is used to insert a new list to a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param oldList [IN] Doubly linked list where the new list is inserted. * @param newList [IN] New list to be inserted. * * @retval None * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListDelete */ static inline void UtilsListAddList(UTILS_DL_LIST *oldList, UTILS_DL_LIST *newList) { UTILS_DL_LIST *oldListHead = oldList->pstNext; UTILS_DL_LIST *oldListTail = oldList; UTILS_DL_LIST *newListHead = newList; UTILS_DL_LIST *newListTail = newList->pstPrev; oldListTail->pstNext = newListHead; newListHead->pstPrev = oldListTail; oldListHead->pstPrev = newListTail; newListTail->pstNext = oldListHead; } /* * @ingroup utils_list * @brief Insert a doubly list to the tail of a doubly linked list. * * @par Description: * This API is used to insert a new doubly list to the tail of a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param oldList [IN] Doubly linked list where the new list is inserted. * @param newList [IN] New list to be inserted. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListAddList | UtilsListHeadInsertList */ static inline void UtilsListTailInsertList(UTILS_DL_LIST *oldList, UTILS_DL_LIST *newList) { UtilsListAddList(oldList->pstPrev, newList); } /* * @ingroup utils_list * @brief Insert a doubly list to the head of a doubly linked list. * * @par Description: * This API is used to insert a new doubly list to the head of a doubly linked list. * @attention * <ul> * <li>The parameters passed in should be ensured to be legal pointers.</li> * </ul> * * @param oldList [IN] Doubly linked list where the new list is inserted. * @param newList [IN] New list to be inserted. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see UtilsListAddList | UtilsListTailInsertList */ static inline void UtilsListHeadInsertList(UTILS_DL_LIST *oldList, UTILS_DL_LIST *newList) { UtilsListAddList(oldList, newList); } /* * @ingroup utils_list * @brief Obtain the offset of a field to a structure address. * * @par Description: * This API is used to obtain the offset of a field to a structure address. * @attention * <ul> * <li>None.</li> * </ul> * * @param type [IN] Structure name. * @param field [IN] Name of the field of which the offset is to be measured. * * @retval Offset of the field to the structure address. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define OFFSET_OF_FIELD(type, field) ((unsigned int)&((type *)0)->field) /* * @ingroup utils_list * @brief Obtain the pointer to a doubly linked list in a structure. * * @par Description: * This API is used to obtain the pointer to a doubly linked list in a structure. * @attention * <ul> * <li>None.</li> * </ul> * * @param type [IN] Structure name. * @param member [IN] Member name of the doubly linked list in the structure. * * @retval Pointer to the doubly linked list in the structure. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_OFF_SET_OF(type, member) ((unsigned int)&((type *)0)->member) /* * @ingroup utils_list * @brief Obtain the pointer to a structure that contains a doubly linked list. * * @par Description: * This API is used to obtain the pointer to a structure that contains a doubly linked list. * <ul> * <li>None.</li> * </ul> * @attention * <ul> * <li>None.</li> * </ul> * * @param item [IN] Current node's pointer to the next node. * @param type [IN] Structure name. * @param member [IN] Member name of the doubly linked list in the structure. * * @retval Pointer to the structure that contains the doubly linked list. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_ENTRY(item, type, member) \ ((type *)(void *)((char *)(item) - UTILS_OFF_SET_OF(type, member))) /* * @ingroup utils_list * @brief Iterate over a doubly linked list of given type. * * @par Description: * This API is used to iterate over a doubly linked list of given type. * @attention * <ul> * <li>None.</li> * </ul> * * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. * @param list [IN] Pointer to the doubly linked list to be traversed. * @param type [IN] Structure name. * @param member [IN] Member name of the doubly linked list in the structure. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_FOR_EACH_ENTRY(item, list, type, member) \ for (item = UTILS_DL_LIST_ENTRY((list)->pstNext, type, member); \ &(item)->member != (list); \ item = UTILS_DL_LIST_ENTRY((item)->member.pstNext, type, member)) /* * @ingroup utils_list * @brief iterate over a doubly linked list safe against removal of list entry. * * @par Description: * This API is used to iterate over a doubly linked list safe against removal of list entry. * @attention * <ul> * <li>None.</li> * </ul> * * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. * @param next [IN] Save the next node. * @param list [IN] Pointer to the doubly linked list to be traversed. * @param type [IN] Structure name. * @param member [IN] Member name of the doubly linked list in the structure. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_FOR_EACH_ENTRY_SAFE(item, next, list, type, member) \ for (item = UTILS_DL_LIST_ENTRY((list)->pstNext, type, member), \ next = UTILS_DL_LIST_ENTRY((item)->member.pstNext, type, member); \ &(item)->member != (list); \ item = next, next = UTILS_DL_LIST_ENTRY((item)->member.pstNext, type, member)) /* * @ingroup utils_list * @brief Delete initialize a doubly linked list. * * @par Description: * This API is used to delete initialize a doubly linked list. * @attention * <ul> * <li>The parameter passed in should be ensured to be s legal pointer.</li> * </ul> * * @param list [IN] Doubly linked list. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ static inline void UtilsListDelInit(UTILS_DL_LIST *list) { list->pstNext->pstPrev = list->pstPrev; list->pstPrev->pstNext = list->pstNext; UtilsListInit(list); } /* * @ingroup utils_list * @brief iterate over a doubly linked list. * * @par Description: * This API is used to iterate over a doubly linked list. * @attention * <ul> * <li>None.</li> * </ul> * * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. * @param list [IN] Pointer to the doubly linked list to be traversed. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_FOR_EACH(item, list) \ for (item = (list)->pstNext; \ (item) != (list); \ item = (item)->pstNext) /* * @ingroup utils_list * @brief Iterate over a doubly linked list safe against removal of list entry. * * @par Description: * This API is used to iterate over a doubly linked list safe against removal of list entry. * @attention * <ul> * <li>None.</li> * </ul> * * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. * @param next [IN] Save the next node. * @param list [IN] Pointer to the doubly linked list to be traversed. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_FOR_EACH_SAFE(item, next, list) \ for (item = (list)->pstNext, next = (item)->pstNext; \ (item) != (list); \ item = next, next = (item)->pstNext) /* * @ingroup utils_list * @brief Initialize a double linked list. * * @par Description: * This API is used to initialize a double linked list. * @attention * <ul> * <li>None.</li> * </ul> * * @param list [IN] Pointer to the doubly linked list to be traversed. * * @retval None. * @par Dependency: * <ul><li>utils_list.h: the header file that contains the API declaration.</li></ul> * @see */ #define UTILS_DL_LIST_HEAD(list) UTILS_DL_LIST list = { &(list), &(list) } #define UTILS_ListPeekHeadType(list, type, element) \ do { \ type *__t; \ if ((list)->pstNext == list) { \ __t = NULL; \ } else { \ __t = UTILS_DL_LIST_ENTRY((list)->pstNext, type, element); \ } \ __t; \ } while (0) #define UTILS_ListRemoveHeadType(list, type, element) \ do { \ type *__t; \ if ((list)->pstNext == list) { \ __t = NULL; \ } else { \ __t = UTILS_DL_LIST_ENTRY((list)->pstNext, type, element); \ UtilsListDelete((list)->pstNext); \ } \ __t; \ } while (0) #define UTILS_ListNextType(list, item, type, element) \ do { \ type *__t; \ if ((item)->pstNext == list) { \ __t = NULL; \ } else { \ __t = UTILS_DL_LIST_ENTRY((item)->pstNext, type, element); \ } \ __t; \ } while (0) #ifdef __cplusplus #if __cplusplus } #endif /* __cplusplus */ #endif /* __cplusplus */ #endif /* _UTILS_LIST_H */
31.855754
117
0.590079
ed66758aafc5af606f27d56d5ef4926a2ac01d97
17,040
h
C
src/cc/legendre_decomposition.h
Log-Analysis/Legendre-decomposition
28b4bf785ed5b02b8f88a25aec4f83fe0dcb5eec
[ "MIT" ]
13
2018-12-03T03:16:18.000Z
2021-11-29T06:52:07.000Z
src/cc/legendre_decomposition.h
Log-Analysis/Legendre-decomposition
28b4bf785ed5b02b8f88a25aec4f83fe0dcb5eec
[ "MIT" ]
null
null
null
src/cc/legendre_decomposition.h
Log-Analysis/Legendre-decomposition
28b4bf785ed5b02b8f88a25aec4f83fe0dcb5eec
[ "MIT" ]
4
2018-12-03T03:16:23.000Z
2021-09-30T05:45:54.000Z
// #define EIGEN_USE_MKL_ALL #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <algorithm> #include <list> #include <numeric> #include <random> #include <functional> #include <utility> #include <iomanip> #include <tuple> #include <time.h> #include <chrono> #include <Eigen/Dense> #define Int int32_t #define Tensor vector<vector<vector<double>>> #define Poset vector<vector<vector<node>>> #define PosetIndex vector<vector<pair<Int, Int>>> #define D 3 using namespace std; using namespace Eigen; using namespace std::chrono; double EPSILON = 1e-300; // node structure class node { public: bool nonzero; Int id, id_org; double p, p_tmp; double theta, theta_prev, theta_sum, theta_sum_prev; double eta, eta_prev; }; Poset S_global; // output a tensor ostream &operator<<(ostream& out, const Tensor& X) { for (auto&& mat : X) { for (auto&& vec : mat) { for (Int i = 0; i < (Int)vec.size() - 1; ++i) { out << vec[i] << ", "; } out << vec.back() << endl; } out << endl; } return out; } // for "reverse" in range-based loop template<class Cont> class const_reverse_wrapper { const Cont& container; public: const_reverse_wrapper(const Cont& cont) : container(cont){ } decltype(container.rbegin()) begin() const { return container.rbegin(); } decltype(container.rend()) end() const { return container.rend(); } }; template<class Cont> class reverse_wrapper { Cont& container; public: reverse_wrapper(Cont& cont) : container(cont){ } decltype(container.rbegin()) begin() { return container.rbegin(); } decltype(container.rend()) end() { return container.rend(); } }; template<class Cont> const_reverse_wrapper<Cont> reverse(const Cont& cont) { return const_reverse_wrapper<Cont>(cont); } template<class Cont> reverse_wrapper<Cont> reverse(Cont& cont) { return reverse_wrapper<Cont>(cont); } // for sort struct greaterP { bool operator()(const tuple<Int, Int, Int>& b1, const tuple<Int, Int, Int>& b2) const { return S_global[get<0>(b1)][get<1>(b1)][get<2>(b1)].p > S_global[get<0>(b2)][get<1>(b2)][get<2>(b2)].p; } }; // read a database file void readTensorFromCSV(Tensor& X, Int num_mat, ifstream& ifs) { vector<vector<double>> data; string line; while (getline(ifs, line)) { stringstream lineStream(line); string cell; vector<double> tmp; while (getline(lineStream, cell, ',')) { tmp.push_back(stod(cell)); } data.push_back(tmp); } if (data.size() % num_mat != 0) { cerr << endl << "The size specification of the input tensor (= " << num_mat << ") is invalid!" << endl; exit(1); } X = Tensor(num_mat, vector<vector<double>>(data.size() / num_mat, vector<double>(data.front().size(), 0))); for (Int k = 0; k < num_mat; ++k) { for (Int j = 0; j < X.front().size(); ++j) { for (Int i = 0; i < X.front().front().size(); ++i) { X[k][j][i] = data[j + k * X.front().size()][i]; } } } } // preprocess X by a one step Sinkhorn balancing double preprocess(Tensor& X) { Int n1 = X.size(); Int n2 = X.front().size(); Int n3 = X.front().front().size(); double X_sum = 0.0; for (auto&& mat : X) { for (auto&& vec : mat) { X_sum += accumulate(vec.begin(), vec.end(), 0.0); } } for (auto&& mat : X) { for (auto&& vec : mat) { for (auto&& x : vec) { x /= X_sum; } } } return X_sum; } // make a node index void makePosetIndex(Tensor& X, PosetIndex& idx_tp) { vector<Int> n{(Int)X.size(), (Int)X.front().size(), (Int)X.front().front().size()}; // traverse a matrix in the topological order for (Int ii = 0; ii < D; ++ii) { Int i1 = ii; Int i2 = ii + 1; if (i2 > 2) i2 -= D; Int i3 = ii + 2; if (i3 > 2) i3 -= D; for (Int i = 0; i < n[i2] + n[i3] - 1; ++i) { Int j = i + 1 - n[i2]; if (j < 0) j = 0; for (; j <= min(i, n[i3] - 1); j++) { idx_tp[i1].push_back(make_pair(i - j, j)); } } } } // make a node matrix from eigen matrix void makePosetTensor(Tensor& X, Poset& S) { Int n1 = X.size(); Int n2 = X.front().size(); Int n3 = X.front().front().size(); // initialization for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { S[i][j][k].p = X[i][j][k]; S[i][j][k].theta = 0; S[i][j][k].theta_sum = 0; S[i][j][k].theta_sum_prev = 0; S[i][j][k].eta = 0; S[i][j][k].nonzero = S[i][j][k].p > EPSILON ? true : false; } } } S[0][0][0].nonzero = true; } // make a beta the submanifold void prepareForBeta(Poset& S) { for (Int i = 0; i < S.size(); ++i) { for (Int j = 0; j < S.front().size(); ++j) { for (Int k = 0; k < S.front().front().size(); ++k) { S[i][j][k].p_tmp = S[i][j][k].p; } } } S[0][0][0].p_tmp = -1; } void makeBetaCore(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta, Int core_size, bool random) { Int n1 = S.size(); Int n2 = S.front().size(); Int n3 = S.front().front().size(); // for sorting S_global.resize(n1); for (auto&& s : S_global) { s.resize(n2); for (auto&& u : s) u.resize(n3); } for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { S_global[i][j][k].p = S[i][j][k].p; } } } vector<tuple<Int, Int, Int>> univ; vector<tuple<Int, Int, Int>> s; mt19937 g(1); for (Int i = 0; i < n1; ++i) { univ.clear(); s.clear(); for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { if (S[i][j][k].p_tmp > 0) { univ.push_back(make_tuple(i, j, k)); } } } if (random) shuffle(univ.begin(), univ.end(), g); else sort(univ.begin(), univ.end(), greaterP()); if (core_size > univ.size()) core_size = univ.size(); for (Int c = 0; c < core_size; ++c) { tuple<Int, Int, Int>& b = univ[c]; beta.push_back(make_pair(b, S[get<0>(b)][get<1>(b)][get<2>(b)].eta)); S[get<0>(b)][get<1>(b)][get<2>(b)].p_tmp = -1.0; } } } void makeBetaNorm(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta, Int core_size) { Int n1 = S.size(); Int n2 = S.front().size(); Int n3 = S.front().front().size(); vector<Int> idx1; if (core_size < n1) { Int diff1 = n1 / core_size; for (Int i = 0; i < core_size; ++i) idx1.push_back(i * diff1); } else { idx1.resize(n1); iota(idx1.begin(), idx1.end(), 0); } vector<Int> idx2; if (core_size < n2) { Int diff2 = n2 / core_size; for (Int i = 0; i < core_size; ++i) idx2.push_back(i * diff2); } else { idx2.resize(n2); iota(idx2.begin(), idx2.end(), 0); } vector<Int> idx3; if (core_size < n3) { Int diff3 = n3 / core_size; for (Int i = 0; i < core_size; ++i) idx3.push_back(i * diff3); } else { idx3.resize(n3); iota(idx3.begin(), idx3.end(), 0); } for (Int i = 1; i < n1; ++i) { if (S[i][0][0].p_tmp > 0) { beta.push_back(make_pair(make_tuple(i, 0, 0), S[i][0][0].eta)); S[i][0][0].p_tmp = -1; } } for (Int j = 1; j < n2; ++j) { beta.push_back(make_pair(make_tuple(0, j, 0), S[0][j][0].eta)); S[0][j][0].p_tmp = -1; } for (Int k = 1; k < n3; ++k) { beta.push_back(make_pair(make_tuple(0, 0, k), S[0][0][k].eta)); S[0][0][k].p_tmp = -1; } for (auto&& i : idx1) { for (auto&& j : idx2) { if (S[i][j][0].p_tmp > 0) { beta.push_back(make_pair(make_tuple(i, j, 0), S[i][j][0].eta)); S[i][j][0].p_tmp = -1; } } for (auto&& k : idx3) { if (S[i][0][k].p_tmp > 0) { beta.push_back(make_pair(make_tuple(i, 0, k), S[i][0][k].eta)); S[i][0][k].p_tmp = -1; } } } } // compute eta for all entries void computeEta(Poset& S) { Int n1 = S.size(); Int n2 = S.front().size(); Int n3 = S.front().front().size(); vector<Int> idx_row(n1 - 1); vector<Int> idx_col(n2 - 1); vector<Int> idx_dep(n3 - 1); iota(idx_row.begin(), idx_row.end(), 0); iota(idx_col.begin(), idx_col.end(), 0); iota(idx_dep.begin(), idx_dep.end(), 0); S[idx_row.size()][idx_col.size()][idx_dep.size()].eta = S[idx_row.size()][idx_col.size()][idx_dep.size()].p; for (auto&& i : reverse(idx_row)) S[i][idx_col.size()][idx_dep.size()].eta = S[i][idx_col.size()][idx_dep.size()].p + S[i + 1][idx_col.size()][idx_dep.size()].eta; for (auto&& j : reverse(idx_col)) S[idx_row.size()][j][idx_dep.size()].eta = S[idx_row.size()][j][idx_dep.size()].p + S[idx_row.size()][j + 1][idx_dep.size()].eta; for (auto&& k : reverse(idx_dep)) S[idx_row.size()][idx_col.size()][k].eta = S[idx_row.size()][idx_col.size()][k].p + S[idx_row.size()][idx_col.size()][k + 1].eta; for (auto&& i : reverse(idx_row)) { for (auto&& j : reverse(idx_col)) { S[i][j][idx_dep.size()].eta = S[i][j][idx_dep.size()].p + S[i + 1][j][idx_dep.size()].eta + S[i][j + 1][idx_dep.size()].eta - S[i + 1][j + 1][idx_dep.size()].eta; } } for (auto&& j : reverse(idx_col)) { for (auto&& k : reverse(idx_dep)) { S[idx_row.size()][j][k].eta = S[idx_row.size()][j][k].p + S[idx_row.size()][j + 1][k].eta + S[idx_row.size()][j][k + 1].eta - S[idx_row.size()][j + 1][k + 1].eta; } } for (auto&& k : reverse(idx_dep)) { for (auto&& i : reverse(idx_row)) { S[i][idx_col.size()][k].eta = S[i][idx_col.size()][k].p + S[i + 1][idx_col.size()][k].eta + S[i][idx_col.size()][k + 1].eta - S[i + 1][idx_col.size()][k + 1].eta; } } for (auto&& i : reverse(idx_row)) { for (auto&& j : reverse(idx_col)) { for (auto&& k : reverse(idx_dep)) { S[i][j][k].eta = S[i][j][k].p + S[i + 1][j][k].eta + S[i][j + 1][k].eta + S[i][j][k + 1].eta - S[i + 1][j + 1][k].eta - S[i + 1][j][k + 1].eta - S[i][j + 1][k + 1].eta + S[i + 1][j + 1][k + 1].eta; } } } } // e-projection void computeP(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta) { Int n1 = S.size(); Int n2 = S.front().size(); Int n3 = S.front().front().size(); for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { if (S[i][j][k].p > EPSILON) { double theta_sum = 0.0; double theta_sum_prev = 0.0; for (auto&& b : beta) { if (get<0>(b.first) <= i && get<1>(b.first) <= j && get<2>(b.first) <= k) { theta_sum += S[get<0>(b.first)][get<1>(b.first)][get<2>(b.first)].theta; theta_sum_prev += S[get<0>(b.first)][get<1>(b.first)][get<2>(b.first)].theta_prev; } } S[i][j][k].theta_sum = theta_sum; S[i][j][k].theta_sum_prev = theta_sum_prev; S[i][j][k].p = exp(theta_sum); } } } } } void renormalize(Poset& S) { // total sum double p_sum = 0.0; for (auto&& mat : S) { for (auto&& vec : mat) { for (auto&& x : vec) { if (x.p > EPSILON) p_sum += x.p; } } } // store the previous theta S[0][0][0].theta_prev = S[0][0][0].theta; // update theta(\bot) S[0][0][0].theta = S[0][0][0].theta_prev - log(p_sum); // update p for (auto&& mat : S) { for (auto&& vec : mat) { for (auto&& x : vec) { if (x.p > EPSILON) x.p *= exp(S[0][0][0].theta - S[0][0][0].theta_prev); } } } } void initialize(Poset& S) { Int n1 = S.size(); Int n2 = S.front().size(); Int n3 = S.front().front().size(); double size = 0.0; for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { if (S[i][j][k].nonzero) size += 1.0; } } } for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { S[i][j][k].p = S[i][j][k].nonzero ? 1.0 / size : 0.0; S[i][j][k].theta = 0; S[i][j][k].theta_prev = 0; } } } S[0][0][0].theta = log(S[0][0][0].p); S[0][0][0].theta_prev = log(S[0][0][0].p); computeEta(S); } // ====================================== // // ========== Natural gradient ========== // // ====================================== // void eProject(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta) { Int S_size = 0; for (auto&& mat : S) { for (auto&& vec : mat) { for (auto&& x : vec) { if (x.p > EPSILON) S_size++; } } } VectorXd theta_vec = VectorXd::Zero(beta.size()); VectorXd eta_vec = VectorXd::Zero(beta.size()); for (Int i = 0; i < beta.size(); i++) { theta_vec[i] = S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].theta; eta_vec[i] = S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].eta - beta[i].second; } MatrixXd J(beta.size(), beta.size()); // Jacobian matrix for (Int i1 = 0; i1 < beta.size(); i1++) { for (Int i2 = 0; i2 < beta.size(); i2++) { Int i1_i = get<0>(beta[i1].first); Int i1_j = get<1>(beta[i1].first); Int i1_k = get<2>(beta[i1].first); Int i2_i = get<0>(beta[i2].first); Int i2_j = get<1>(beta[i2].first); Int i2_k = get<2>(beta[i2].first); J(i1, i2) = S[max(i1_i, i2_i)][max(i1_j, i2_j)][max(i1_k, i2_k)].eta; J(i1, i2) -= S[i1_i][i1_j][i1_k].eta * S[i2_i][i2_j][i2_k].eta; } } theta_vec += ((-1 * J).colPivHouseholderQr().solve(eta_vec)); // theta_vec += (-1 * J).fullPivHouseholderQr().solve(eta_vec); // theta_vec += (-1 * J).fullPivLu().solve(eta_vec); // store theta for (Int i = 0; i < beta.size(); i++) { S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].theta_prev = S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].theta; S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].theta = theta_vec[i]; } // update p computeP(S, beta); renormalize(S); computeEta(S); } // ====================================== // // ========== Gradient descent ========== // // ====================================== // void grad(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta) { double eps = 0.1; for (Int i = 0; i < beta.size(); i++) { S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].theta += eps * (beta[i].second - S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].eta); // update p computeP(S, beta); renormalize(S); computeEta(S); } } // compute the residual double computeResidual(Poset& S, vector<pair<tuple<Int, Int, Int>, double>>& beta) { double res = 0.0; for (Int i = 0; i < beta.size(); i++) { res += pow(S[get<0>(beta[i].first)][get<1>(beta[i].first)][get<2>(beta[i].first)].eta - beta[i].second, 2.0); } return sqrt(res); } double computeRMSE(Tensor& X, Tensor& Y) { double rmse = 0.0; for (Int i = 0; i < X.size(); ++i) { for (Int j = 0; j < X.front().size(); ++j) { for (Int k = 0; k < X.front().front().size(); ++k) { rmse += pow(X[i][j][k] - Y[i][j][k], 2.0); } } } rmse /= (double)X.size() * (double)X.front().size() * (double)X.front().front().size(); rmse = sqrt(rmse); return rmse; } // the main function for Legendre decomposition by natural gradient double LegendreDecomposition(Tensor& X, Int core_size, double error_tol, double rep_max, bool verbose, Int type, Int const_type, Int *num_param) { Int n1 = X.size(); Int n2 = X.front().size(); Int n3 = X.front().front().size(); clock_t ts, te; // preprocess double X_sum = preprocess(X); // make a node matrix Poset S = Poset(n1, vector<vector<node>>(n2, vector<node>(n3))); makePosetTensor(X, S); computeEta(S); vector<pair<tuple<Int, Int, Int>, double>> beta; prepareForBeta(S); if (const_type == 1) { makeBetaNorm(S, beta, core_size); makeBetaCore(S, beta, core_size, true); } else if (const_type == 2) { makeBetaCore(S, beta, core_size, false); } else { makeBetaCore(S, beta, core_size, false); } initialize(S); cout << " Number of parameters: " << beta.size() << endl << flush; *num_param = beta.size(); // run Legendre deomposition if (verbose) cout << "----- Start Legendre decomposition -----" << endl << flush; double res = 0.0; double step = 1.0; Int exponent = 0; auto t_start = system_clock::now(); while (step <= rep_max) { if (type == 1) { eProject(S, beta); // perform e-projection } else if (type == 2) { grad(S, beta); // perform gradient descent } else { eProject(S, beta); // perform e-projection } double res_prev = res; res = computeResidual(S, beta); if (res_prev >= EPSILON && res > res_prev) { cout << " Terminate with current residual = " << res << endl; return step; } // output the residual if (verbose) { cout << "Step\t" << step << "\t" << "Residual\t" << res << endl << flush; } else { if (res < pow(10, -1.0 * (double)exponent)) { cout << " Step "; if (step < 10.0) cout << " "; cout << step << ", Residual: " << res << endl; exponent++; } } if (res < error_tol) break; step += 1.0; } if (verbose) cout << "----- End Legendre decomposition -----" << endl; // put results to X for (Int i = 0; i < n1; ++i) { for (Int j = 0; j < n2; ++j) { for (Int k = 0; k < n3; ++k) { X[i][j][k] = S[i][j][k].p * X_sum; } } } return step; }
30.647482
214
0.540434
d46d054e34c218cd747d081f193d2145caca3076
638
c
C
C/VUP10/9.c
MrHighTech/UPRO
1824a9ef4fd136f68459c049619e8feb611d10a2
[ "MIT" ]
null
null
null
C/VUP10/9.c
MrHighTech/UPRO
1824a9ef4fd136f68459c049619e8feb611d10a2
[ "MIT" ]
null
null
null
C/VUP10/9.c
MrHighTech/UPRO
1824a9ef4fd136f68459c049619e8feb611d10a2
[ "MIT" ]
null
null
null
#include <stdio.h> #define MAX_ZN 100 int main(void) { char niz[MAX_ZN + 1]; int n; printf("Upisite niz > "); fgets(niz, MAX_ZN + 1, stdin); int i = 0; while (niz[i] != '\0') { if (niz[i] == '\n') { niz[i] = '\0'; } i++; } printf("Upisite poziciju > "); scanf("%d", &n); if (niz[n - 1] == '\0') { printf("Neispravna pozicija"); } else { for (i = MAX_ZN; i >= n - 1; i--) { if (niz[i] == '\0') { continue; } else { niz[i + 1] = niz[i]; } } niz[n - 1] = 'X'; } printf("%s", niz); return 0; }
17.722222
41
0.39185
377418087de0f64c9a785b28912ca33d1eb84427
24,098
c
C
platform/drm/cog-drm-modeset-renderer.c
jameshilliard/cog
d2720103ff8a5c3c5c056487586ed0b5acdc2b91
[ "MIT" ]
129
2018-05-08T20:57:17.000Z
2022-03-18T17:38:17.000Z
platform/drm/cog-drm-modeset-renderer.c
jameshilliard/cog
d2720103ff8a5c3c5c056487586ed0b5acdc2b91
[ "MIT" ]
298
2018-05-09T13:54:56.000Z
2022-03-31T06:16:54.000Z
platform/drm/cog-drm-modeset-renderer.c
jameshilliard/cog
d2720103ff8a5c3c5c056487586ed0b5acdc2b91
[ "MIT" ]
36
2018-05-15T11:33:43.000Z
2022-03-03T03:23:41.000Z
/* * cog-drm-modeset-renderer.c * Copyright (C) 2021 Igalia S.L. * * Distributed under terms of the MIT license. */ #include "../../core/cog.h" #include "cog-drm-renderer.h" #include <errno.h> #include <gbm.h> #include <wayland-server.h> #include <wpe/fdo.h> #include <xf86drm.h> #include <xf86drmMode.h> typedef struct { GSource base; GPollFD pfd; drmEventContext event_context; } DrmEventSource; static gboolean drm_source_check(GSource *source) { DrmEventSource *self = wl_container_of(source, self, base); return !!self->pfd.revents; } static gboolean drm_source_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) { DrmEventSource *self = wl_container_of(source, self, base); if (self->pfd.revents & (G_IO_ERR | G_IO_HUP)) return FALSE; if (self->pfd.revents & G_IO_IN) drmHandleEvent(self->pfd.fd, &self->event_context); self->pfd.revents = 0; return TRUE; } static void drm_page_flip_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *); static GSource * drm_event_source_new(int fd) { static GSourceFuncs funcs = { .check = drm_source_check, .dispatch = drm_source_dispatch, }; DrmEventSource *self = (DrmEventSource *) g_source_new(&funcs, sizeof(DrmEventSource)); self->event_context = (drmEventContext){ .version = DRM_EVENT_CONTEXT_VERSION, .page_flip_handler = drm_page_flip_handler, }; self->pfd = (GPollFD){ .fd = fd, .events = G_IO_IN | G_IO_ERR | G_IO_HUP, }; g_source_add_poll(&self->base, &self->pfd); g_source_set_name(&self->base, "cog: drm"); g_source_set_can_recurse(&self->base, TRUE); return &self->base; } struct buffer_object { struct wl_list link; struct wl_listener destroy_listener; uint32_t fb_id; struct gbm_bo *bo; struct wl_resource *buffer_resource; struct { struct wl_resource *resource; struct wpe_fdo_shm_exported_buffer *shm_buffer; } export; }; typedef struct { CogDrmRenderer base; GSource *drm_source; struct buffer_object *committed_buffer; struct wl_list buffer_list; /* buffer_object::link */ struct wpe_view_backend_exportable_fdo *exportable; struct gbm_device *gbm_dev; uint32_t crtc_id; uint32_t connector_id; uint32_t plane_id; drmModeModeInfo mode; bool mode_set; bool atomic_modesetting; struct { drmModeObjectProperties *props; drmModePropertyRes **props_info; } connector_props, crtc_props, plane_props; } CogDrmModesetRenderer; static inline int get_drm_fd(CogDrmModesetRenderer *self) { DrmEventSource *s = wl_container_of(self->drm_source, s, base); return s->pfd.fd; } static void destroy_buffer(CogDrmModesetRenderer *renderer, struct buffer_object *buffer) { drmModeRmFB(get_drm_fd(renderer), buffer->fb_id); gbm_bo_destroy(buffer->bo); if (buffer->export.resource) { wpe_view_backend_exportable_fdo_dispatch_release_buffer(renderer->exportable, buffer->export.resource); buffer->export.resource = NULL; } if (buffer->export.shm_buffer) { wpe_view_backend_exportable_fdo_dispatch_release_shm_exported_buffer(renderer->exportable, buffer->export.shm_buffer); buffer->export.shm_buffer = NULL; } g_free(buffer); } static void destroy_buffer_notify(struct wl_listener *listener, void *data) { struct buffer_object *buffer = wl_container_of(listener, buffer, destroy_listener); CogDrmModesetRenderer *renderer = wl_resource_get_user_data(buffer->buffer_resource); if (renderer->committed_buffer == buffer) renderer->committed_buffer = NULL; wl_list_remove(&buffer->link); wl_resource_set_user_data(buffer->buffer_resource, NULL); destroy_buffer(renderer, buffer); } static struct buffer_object * drm_buffer_for_resource(CogDrmModesetRenderer *renderer, struct wl_resource *buffer_resource) { struct buffer_object *buffer; wl_list_for_each(buffer, &renderer->buffer_list, link) { if (buffer->buffer_resource == buffer_resource) return buffer; } return NULL; } static struct buffer_object * drm_create_buffer_for_bo(CogDrmModesetRenderer *self, struct gbm_bo *bo, struct wl_resource *buffer_resource, uint32_t width, uint32_t height, uint32_t format) { uint32_t in_handles[4] = { 0, }; uint32_t in_strides[4] = { 0, }; uint32_t in_offsets[4] = { 0, }; uint64_t in_modifiers[4] = { 0, }; in_modifiers[0] = gbm_bo_get_modifier(bo); int plane_count = MIN(gbm_bo_get_plane_count(bo), 4); for (int i = 0; i < plane_count; ++i) { in_handles[i] = gbm_bo_get_handle_for_plane(bo, i).u32; in_strides[i] = gbm_bo_get_stride_for_plane(bo, i); in_offsets[i] = gbm_bo_get_offset(bo, i); in_modifiers[i] = in_modifiers[0]; } int flags = 0; if (in_modifiers[0]) flags = DRM_MODE_FB_MODIFIERS; uint32_t fb_id = 0; int ret = drmModeAddFB2WithModifiers(get_drm_fd(self), width, height, format, in_handles, in_strides, in_offsets, in_modifiers, &fb_id, flags); if (ret) { in_handles[0] = gbm_bo_get_handle(bo).u32; in_handles[1] = in_handles[2] = in_handles[3] = 0; in_strides[0] = gbm_bo_get_stride(bo); in_strides[1] = in_strides[2] = in_strides[3] = 0; in_offsets[0] = in_offsets[1] = in_offsets[2] = in_offsets[3] = 0; ret = drmModeAddFB2(get_drm_fd(self), width, height, format, in_handles, in_strides, in_offsets, &fb_id, 0); } if (ret) { g_warning("failed to create framebuffer: %s", strerror(errno)); return NULL; } struct buffer_object *buffer = g_new0(struct buffer_object, 1); wl_list_insert(&self->buffer_list, &buffer->link); buffer->destroy_listener.notify = destroy_buffer_notify; wl_resource_add_destroy_listener(buffer_resource, &buffer->destroy_listener); wl_resource_set_user_data(buffer_resource, self); buffer->fb_id = fb_id; buffer->bo = bo; buffer->buffer_resource = buffer_resource; return buffer; } static struct buffer_object * drm_create_buffer_for_shm_buffer(CogDrmModesetRenderer *self, struct wl_resource *buffer_resource, struct wl_shm_buffer *shm_buffer) { uint32_t format = wl_shm_buffer_get_format(shm_buffer); if (format != WL_SHM_FORMAT_ARGB8888 && format != WL_SHM_FORMAT_XRGB8888) { g_warning("failed to handle non-32-bit ARGB/XRGB format"); return NULL; } int32_t width = wl_shm_buffer_get_width(shm_buffer); int32_t height = wl_shm_buffer_get_height(shm_buffer); // TODO: don't ignore the alpha channel in case of ARGB8888 SHM data uint32_t gbm_format = GBM_FORMAT_XRGB8888; struct gbm_bo *bo = gbm_bo_create(self->gbm_dev, width, height, gbm_format, GBM_BO_USE_SCANOUT | GBM_BO_USE_WRITE); if (!bo) { g_warning("failed to create a gbm_bo object"); return NULL; } uint32_t in_handles[4] = { 0, }; uint32_t in_strides[4] = { 0, }; uint32_t in_offsets[4] = { 0, }; in_handles[0] = gbm_bo_get_handle(bo).u32; in_strides[0] = gbm_bo_get_stride(bo); uint32_t fb_id = 0; int ret = drmModeAddFB2(get_drm_fd(self), width, height, gbm_format, in_handles, in_strides, in_offsets, &fb_id, 0); if (ret) { gbm_bo_destroy(bo); g_warning("failed to create framebuffer: %s", g_strerror(errno)); return NULL; } struct buffer_object *buffer = g_new0(struct buffer_object, 1); wl_list_insert(&self->buffer_list, &buffer->link); buffer->destroy_listener.notify = destroy_buffer_notify; wl_resource_add_destroy_listener(buffer_resource, &buffer->destroy_listener); wl_resource_set_user_data(buffer_resource, self); buffer->fb_id = fb_id; buffer->bo = bo; buffer->buffer_resource = buffer_resource; return buffer; } static void drm_copy_shm_buffer_into_bo(struct wl_shm_buffer *shm_buffer, struct gbm_bo *bo) { int32_t width = wl_shm_buffer_get_width(shm_buffer); int32_t height = wl_shm_buffer_get_height(shm_buffer); int32_t stride = wl_shm_buffer_get_stride(shm_buffer); uint32_t bo_stride = 0; void *map_data = NULL; gbm_bo_map(bo, 0, 0, width, height, GBM_BO_TRANSFER_WRITE, &bo_stride, &map_data); if (!map_data) return; wl_shm_buffer_begin_access(shm_buffer); uint8_t *src = wl_shm_buffer_get_data(shm_buffer); uint8_t *dst = map_data; uint32_t bo_width = gbm_bo_get_width(bo); uint32_t bo_height = gbm_bo_get_height(bo); if (!(width == bo_width && height == bo_height && stride == bo_stride)) { for (uint32_t y = 0; y < height; ++y) { for (uint32_t x = 0; x < width; ++x) { dst[bo_stride * y + 4 * x + 0] = src[stride * y + 4 * x + 0]; dst[bo_stride * y + 4 * x + 1] = src[stride * y + 4 * x + 1]; dst[bo_stride * y + 4 * x + 2] = src[stride * y + 4 * x + 2]; dst[bo_stride * y + 4 * x + 3] = src[stride * y + 4 * x + 3]; } } } else memcpy(dst, src, stride * height); wl_shm_buffer_end_access(shm_buffer); gbm_bo_unmap(bo, map_data); } typedef struct { CogDrmModesetRenderer *renderer; struct buffer_object *buffer; } FlipHandlerData; static int drm_commit_buffer_nonatomic(CogDrmModesetRenderer *self, struct buffer_object *buffer) { if (!self->mode_set) { int ret = drmModeSetCrtc(get_drm_fd(self), self->crtc_id, buffer->fb_id, 0, 0, &self->connector_id, 1, &self->mode); if (ret) return -1; self->mode_set = true; } FlipHandlerData *data = g_slice_new(FlipHandlerData); *data = (FlipHandlerData){self, buffer}; return drmModePageFlip(get_drm_fd(self), self->crtc_id, buffer->fb_id, DRM_MODE_PAGE_FLIP_EVENT, data); } static int add_property(drmModeObjectProperties *props, drmModePropertyRes **props_info, drmModeAtomicReq *req, uint32_t obj_id, const char *name, uint64_t value) { for (int i = 0; i < props->count_props; ++i) { if (!g_strcmp0(props_info[i]->name, name)) { int ret = drmModeAtomicAddProperty(req, obj_id, props_info[i]->prop_id, value); return (ret > 0) ? 0 : -1; } } return -1; } static int add_connector_property(CogDrmModesetRenderer *self, drmModeAtomicReq *req, uint32_t obj_id, const char *name, uint64_t value) { return add_property(self->connector_props.props, self->connector_props.props_info, req, obj_id, name, value); } static int add_crtc_property(CogDrmModesetRenderer *self, drmModeAtomicReq *req, uint32_t obj_id, const char *name, uint64_t value) { return add_property(self->crtc_props.props, self->crtc_props.props_info, req, obj_id, name, value); } static int add_plane_property(CogDrmModesetRenderer *self, drmModeAtomicReq *req, uint32_t obj_id, const char *name, uint64_t value) { return add_property(self->plane_props.props, self->plane_props.props_info, req, obj_id, name, value); } static int drm_commit_buffer_atomic(CogDrmModesetRenderer *self, struct buffer_object *buffer) { int ret = 0; uint32_t flags = DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_NONBLOCK; drmModeAtomicReq *req = drmModeAtomicAlloc(); if (!self->mode_set) { flags |= DRM_MODE_ATOMIC_ALLOW_MODESET; uint32_t blob_id; ret = drmModeCreatePropertyBlob(get_drm_fd(self), &self->mode, sizeof(drmModeModeInfo), &blob_id); if (ret) { drmModeAtomicFree(req); return -1; } ret |= add_connector_property(self, req, self->connector_id, "CRTC_ID", self->crtc_id); ret |= add_crtc_property(self, req, self->crtc_id, "MODE_ID", blob_id); ret |= add_crtc_property(self, req, self->crtc_id, "ACTIVE", 1); if (ret) { drmModeAtomicFree(req); return -1; } self->mode_set = true; } ret |= add_plane_property(self, req, self->plane_id, "FB_ID", buffer->fb_id); ret |= add_plane_property(self, req, self->plane_id, "CRTC_ID", self->crtc_id); ret |= add_plane_property(self, req, self->plane_id, "SRC_X", 0); ret |= add_plane_property(self, req, self->plane_id, "SRC_Y", 0); ret |= add_plane_property(self, req, self->plane_id, "SRC_W", ((uint64_t) self->mode.hdisplay) << 16); ret |= add_plane_property(self, req, self->plane_id, "SRC_H", ((uint64_t) self->mode.vdisplay) << 16); ret |= add_plane_property(self, req, self->plane_id, "CRTC_X", 0); ret |= add_plane_property(self, req, self->plane_id, "CRTC_Y", 0); ret |= add_plane_property(self, req, self->plane_id, "CRTC_W", self->mode.hdisplay); ret |= add_plane_property(self, req, self->plane_id, "CRTC_H", self->mode.vdisplay); if (ret) { drmModeAtomicFree(req); return -1; } FlipHandlerData *data = g_slice_new(FlipHandlerData); *data = (FlipHandlerData){self, buffer}; ret = drmModeAtomicCommit(get_drm_fd(self), req, flags, data); if (ret) { drmModeAtomicFree(req); return -1; } drmModeAtomicFree(req); return 0; } static void drm_commit_buffer(CogDrmModesetRenderer *self, struct buffer_object *buffer) { int ret; if (self->atomic_modesetting) ret = drm_commit_buffer_atomic(self, buffer); else ret = drm_commit_buffer_nonatomic(self, buffer); if (ret) g_warning("failed to schedule a page flip: %s", g_strerror(errno)); } static void on_export_buffer_resource(void *data, struct wl_resource *buffer_resource) { CogDrmModesetRenderer *self = data; struct buffer_object *buffer = drm_buffer_for_resource(self, buffer_resource); if (buffer) { buffer->export.resource = buffer_resource; drm_commit_buffer(self, buffer); return; } struct gbm_bo *bo = gbm_bo_import(self->gbm_dev, GBM_BO_IMPORT_WL_BUFFER, (void *) buffer_resource, GBM_BO_USE_SCANOUT); if (!bo) { g_warning("failed to import a wl_buffer resource into gbm_bo"); return; } uint32_t width = gbm_bo_get_width(bo); uint32_t height = gbm_bo_get_height(bo); uint32_t format = gbm_bo_get_format(bo); buffer = drm_create_buffer_for_bo(self, bo, buffer_resource, width, height, format); if (buffer) { buffer->export.resource = buffer_resource; drm_commit_buffer(self, buffer); } } static void on_export_dmabuf_resource(void *data, struct wpe_view_backend_exportable_fdo_dmabuf_resource *dmabuf_resource) { CogDrmModesetRenderer *self = data; struct buffer_object *buffer = drm_buffer_for_resource(self, dmabuf_resource->buffer_resource); if (buffer) { buffer->export.resource = dmabuf_resource->buffer_resource; drm_commit_buffer(self, buffer); return; } struct gbm_import_fd_modifier_data modifier_data = { .width = dmabuf_resource->width, .height = dmabuf_resource->height, .format = dmabuf_resource->format, .num_fds = dmabuf_resource->n_planes, .modifier = dmabuf_resource->modifiers[0], }; for (uint32_t i = 0; i < modifier_data.num_fds; ++i) { modifier_data.fds[i] = dmabuf_resource->fds[i]; modifier_data.strides[i] = dmabuf_resource->strides[i]; modifier_data.offsets[i] = dmabuf_resource->offsets[i]; } struct gbm_bo *bo = gbm_bo_import(self->gbm_dev, GBM_BO_IMPORT_FD_MODIFIER, (void *) (&modifier_data), GBM_BO_USE_SCANOUT); if (!bo) { g_warning("failed to import a dma-buf resource into gbm_bo"); return; } buffer = drm_create_buffer_for_bo(self, bo, dmabuf_resource->buffer_resource, dmabuf_resource->width, dmabuf_resource->height, dmabuf_resource->format); if (buffer) { buffer->export.resource = dmabuf_resource->buffer_resource; drm_commit_buffer(self, buffer); } } static void on_export_shm_buffer(void *data, struct wpe_fdo_shm_exported_buffer *exported_buffer) { CogDrmModesetRenderer *self = data; struct wl_resource *exported_resource = wpe_fdo_shm_exported_buffer_get_resource(exported_buffer); struct wl_shm_buffer *exported_shm_buffer = wpe_fdo_shm_exported_buffer_get_shm_buffer(exported_buffer); struct buffer_object *buffer = drm_buffer_for_resource(self, exported_resource); if (buffer) { drm_copy_shm_buffer_into_bo(exported_shm_buffer, buffer->bo); buffer->export.shm_buffer = exported_buffer; drm_commit_buffer(self, buffer); return; } buffer = drm_create_buffer_for_shm_buffer(self, exported_resource, exported_shm_buffer); if (buffer) { drm_copy_shm_buffer_into_bo(exported_shm_buffer, buffer->bo); buffer->export.shm_buffer = exported_buffer; drm_commit_buffer(self, buffer); } } static void drm_page_flip_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data) { CogDrmModesetRenderer *self = ((FlipHandlerData *) data)->renderer; struct buffer_object *buffer = ((FlipHandlerData *) data)->buffer; g_slice_free(FlipHandlerData, data); if (self->committed_buffer) { struct buffer_object *buffer = self->committed_buffer; if (buffer->export.resource) { wpe_view_backend_exportable_fdo_dispatch_release_buffer(self->exportable, buffer->export.resource); buffer->export.resource = NULL; } if (buffer->export.shm_buffer) { wpe_view_backend_exportable_fdo_dispatch_release_shm_exported_buffer(self->exportable, buffer->export.shm_buffer); buffer->export.shm_buffer = NULL; } } self->committed_buffer = buffer; wpe_view_backend_exportable_fdo_dispatch_frame_complete(self->exportable); } static bool cog_drm_modeset_renderer_initialize(CogDrmRenderer *renderer, GError **error) { CogDrmModesetRenderer *self = wl_container_of(renderer, self, base); g_source_attach(self->drm_source, g_main_context_get_thread_default()); return true; } static void cog_drm_modeset_renderer_destroy(CogDrmRenderer *renderer) { CogDrmModesetRenderer *self = wl_container_of(renderer, self, base); struct buffer_object *buffer, *tmp; wl_list_for_each_safe(buffer, tmp, &self->buffer_list, link) { wl_list_remove(&buffer->link); wl_list_remove(&buffer->destroy_listener.link); destroy_buffer(self, buffer); } wl_list_init(&self->buffer_list); self->committed_buffer = NULL; if (self->connector_props.props_info) { for (uint32_t i = 0; i < self->connector_props.props->count_props; i++) drmModeFreeProperty(self->connector_props.props_info[i]); } g_clear_pointer(&self->connector_props.props, drmModeFreeObjectProperties); g_clear_pointer(&self->connector_props.props_info, g_free); if (self->crtc_props.props_info) { for (uint32_t i = 0; i < self->crtc_props.props->count_props; ++i) drmModeFreeProperty(self->crtc_props.props_info[i]); } g_clear_pointer(&self->crtc_props.props, drmModeFreeObjectProperties); g_clear_pointer(&self->crtc_props.props_info, g_free); if (self->plane_props.props_info) { for (uint32_t i = 0; i < self->plane_props.props->count_props; ++i) drmModeFreeProperty(self->plane_props.props_info[i]); } g_clear_pointer(&self->plane_props.props, drmModeFreeObjectProperties); g_clear_pointer(&self->plane_props.props_info, g_free); g_clear_pointer(&self->gbm_dev, gbm_device_destroy); g_slice_free(CogDrmModesetRenderer, renderer); } static struct wpe_view_backend_exportable_fdo * cog_drm_modeset_renderer_create_exportable(CogDrmRenderer *renderer, uint32_t width, uint32_t height) { static const struct wpe_view_backend_exportable_fdo_client client = { .export_buffer_resource = on_export_buffer_resource, .export_dmabuf_resource = on_export_dmabuf_resource, .export_shm_buffer = on_export_shm_buffer, }; CogDrmModesetRenderer *self = wl_container_of(renderer, self, base); return (self->exportable = wpe_view_backend_exportable_fdo_create(&client, renderer, width, height)); } CogDrmRenderer * cog_drm_modeset_renderer_new(struct gbm_device *gbm_dev, uint32_t plane_id, uint32_t crtc_id, uint32_t connector_id, const drmModeModeInfo *mode, bool atomic_modesetting) { CogDrmModesetRenderer *self = g_slice_new0(CogDrmModesetRenderer); *self = (CogDrmModesetRenderer){ .base.name = "modeset", .base.initialize = cog_drm_modeset_renderer_initialize, .base.destroy = cog_drm_modeset_renderer_destroy, .base.create_exportable = cog_drm_modeset_renderer_create_exportable, .drm_source = drm_event_source_new(gbm_device_get_fd(gbm_dev)), .gbm_dev = gbm_dev, .crtc_id = crtc_id, .connector_id = connector_id, .plane_id = plane_id, .atomic_modesetting = atomic_modesetting, }; wl_list_init(&self->buffer_list); memcpy(&self->mode, mode, sizeof(drmModeModeInfo)); self->connector_props.props = drmModeObjectGetProperties(get_drm_fd(self), self->connector_id, DRM_MODE_OBJECT_CONNECTOR); if (self->connector_props.props) { self->connector_props.props_info = g_new0(drmModePropertyRes *, self->connector_props.props->count_props); for (uint32_t i = 0; i < self->connector_props.props->count_props; i++) self->connector_props.props_info[i] = drmModeGetProperty(get_drm_fd(self), self->connector_props.props->props[i]); } self->crtc_props.props = drmModeObjectGetProperties(get_drm_fd(self), self->crtc_id, DRM_MODE_OBJECT_CRTC); if (self->crtc_props.props) { self->crtc_props.props_info = g_new0(drmModePropertyRes *, self->crtc_props.props->count_props); for (uint32_t i = 0; i < self->crtc_props.props->count_props; i++) self->crtc_props.props_info[i] = drmModeGetProperty(get_drm_fd(self), self->crtc_props.props->props[i]); } self->plane_props.props = drmModeObjectGetProperties(get_drm_fd(self), self->plane_id, DRM_MODE_OBJECT_PLANE); if (self->plane_props.props) { self->plane_props.props_info = g_new0(drmModePropertyRes *, self->plane_props.props->count_props); for (uint32_t i = 0; i < self->plane_props.props->count_props; i++) self->plane_props.props_info[i] = drmModeGetProperty(get_drm_fd(self), self->plane_props.props->props[i]); } g_debug("%s: Using plane #%" PRIu32 ", crtc #%" PRIu32 ", connector #%" PRIu32 " (%s).", __func__, plane_id, crtc_id, connector_id, atomic_modesetting ? "atomic" : "legacy"); return &self->base; }
34.673381
120
0.657399
a6a9dcad6949c2621315818d4e30e54ff44a67f0
2,701
h
C
src/FedSrv/FedSrvApp.h
AllegianceZone/Allegiance
ef69a16638fb35e34cbb51f6aee891080f71d38b
[ "MIT" ]
11
2015-01-11T08:45:18.000Z
2022-01-28T09:20:54.000Z
src/FedSrv/FedSrvApp.h
AllegianceZone/Allegiance
ef69a16638fb35e34cbb51f6aee891080f71d38b
[ "MIT" ]
15
2015-05-25T20:22:41.000Z
2017-08-14T17:10:57.000Z
src/FedSrv/FedSrvApp.h
FreeAllegiance/Allegiance-AZ
1d8678ddff9e2efc79ed449de6d47544989bc091
[ "MIT" ]
3
2015-07-12T05:50:54.000Z
2017-08-13T06:42:50.000Z
#pragma once /*------------------------------------------------------------------------- * FedSrvApp *------------------------------------------------------------------------- * Purpose: * This class is called by the assert code when an assert happens */ #define FED_DEBUG_DEBUGOUT 1 #define FED_DEBUG_FILE 2 // mmf log to file on SRVLOG define as well as _DEBUG #ifdef _DEBUG #define SRVLOG #endif #ifdef SRVLOG // mmf changed this from _DEBUG class FedSrvApp : public Win32App { public: FedSrvApp(void) : m_hFile(NULL), m_dwDebug(FED_DEBUG_DEBUGOUT) { } ~FedSrvApp(void) { CloseLogFile(); } virtual void OpenLogFile(void) { CloseLogFile(); // mmf server logfilename set here // mmf changed to use logfile mechanism from client (Win32app.cpp) // char bfr[200]; // GetModuleFileName(NULL, bfr, 150); // char* p = strrchr(bfr, '.'); // if (p) // *(p + 1) = '\0'; // //_itoa(Time::Now().clock(), bfr + strlen(bfr), 10); // strcat(bfr, "txt"); time_t longTime; time(&longTime); tm* t = localtime(&longTime); char logFileName[MAX_PATH + 16]; GetModuleFileNameA(NULL, logFileName, MAX_PATH); char* p = strrchr(logFileName, '\\'); if (!p) p = logFileName; else p++; const char* months[] = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; strcpy(p, months[t->tm_mon]); sprintf(p + 3, "%02d%02d%02d%02d.txt", t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); m_hFile = CreateFileA(logFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_FLAG_OVERLAPPED, NULL); assert(m_hFile); m_overlapped.Offset = 0; m_overlapped.OffsetHigh = 0; m_overlapped.hEvent = NULL; m_nOffset = 0; } virtual void CloseLogFile(void) { if (m_hFile) { CloseHandle(m_hFile); m_hFile = NULL; } } virtual void DebugOutput(const char *psz); virtual bool OnAssert(const char* psz, const char* pszFile, int line, const char* pszModule); virtual void OnAssertBreak(); void SetDebug(DWORD dw) { if (!(m_dwDebug & FED_DEBUG_FILE) && (dw & FED_DEBUG_FILE)) OpenLogFile(); else if ((m_dwDebug & FED_DEBUG_FILE) && !(dw & FED_DEBUG_FILE)) CloseLogFile(); char buff[640]; sprintf(buff, "Debug level set from %u to %u.\n", m_dwDebug, dw); m_dwDebug = dw; DebugOutput(buff); } DWORD GetDebug() { return m_dwDebug; } private: void AsyncFileOut(const char *psz); HANDLE m_hFile; OVERLAPPED m_overlapped; DWORD m_dwDebug; // See FED_* above #pragma pack(push, 4) LONG m_nOffset; #pragma pack(pop) }; extern FedSrvApp g_app; #endif
22.139344
155
0.609774
a6af91499e0e812fabff794d08045c54d156aa35
22,192
c
C
packages/PIPS/pips/src/Libs/comp_sections/propagate.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
51
2015-01-31T01:51:39.000Z
2022-02-18T02:01:50.000Z
packages/PIPS/pips/src/Libs/comp_sections/propagate.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
7
2017-05-29T09:29:00.000Z
2019-03-11T16:01:39.000Z
packages/PIPS/pips/src/Libs/comp_sections/propagate.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
12
2015-03-26T08:05:38.000Z
2022-02-18T02:01:51.000Z
/* $Id$ Copyright 1989-2014 MINES ParisTech This file is part of PIPS. PIPS 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, either version 3 of the License, or any later version. PIPS 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 PIPS. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "pips_config.h" #endif /* {{{ banner*/ /* package complementary sections : Manjunathaiah M , 18-4-96 * * This File contains the functions computing the regions of a module : * proper, local and global. * * */ /* }}} */ #include "all.h" #define IS_EG TRUE #define NOT_EG FALSE #define PHI_FIRST TRUE #define NOT_PHI_FIRST FALSE /* global static variable local_regions_map, and its access functions */ DEFINE_CURRENT_MAPPING(local_comp_regions, list) /* {{{ auxilliary functions*/ void CheckStride(loop __attribute__ ((unused)) Loop) { /* expression Stride = range_increment(loop_range(Loop)); */ } /* just concatentate list for now : change later */ list CompRegionsExactUnion(list l1, list l2, bool __attribute__ ((unused)) (*union_combinable_p)(effect,effect)) { return(gen_nconc(l1,l2)); } /* just concatentate list for now : change later */ list CompRegionsMayUnion(list l1, list l2, bool __attribute__ ((unused)) (*union_combinable_p)(effect,effect)) { return(gen_nconc(l1,l2)); } /* }}} */ /* {{{ process the body of a procedure*/ /* =============================================================================== * * INTRAPROCEDURAL ARRAY REGIONS ANALYSIS * * =============================================================================== */ /* {{{ intra procedural entry point "complementary_sections" calls comp_regions*/ /* {{{ comments*/ /* bool regions(const char* module_name) * input : the name of the current module * output : nothing. * modifies : computes the local regions of a module. * comment : local regions can contain local variables. */ /* }}} */ bool comp_regions(const char* module_name) { /* {{{ code*/ /* {{{ initialize*/ /* regions_init(); */ /* get the current properties concerning regions */ get_regions_properties(); /* Get the code of the module. */ set_current_module_statement( (statement) db_get_memory_resource(DBR_CODE, module_name, true) ); /* }}} */ /* {{{ transformers and preconditions*/ /* Get the transformers and preconditions of the module. */ set_transformer_map( (statement_mapping) db_get_memory_resource(DBR_TRANSFORMERS, module_name, true) ); set_precondition_map( (statement_mapping) db_get_memory_resource(DBR_PRECONDITIONS, module_name, true) ); /* }}} */ /* {{{ predicates for purpose of debugging*/ /* predicates defining summary regions from callees have to be translated into variables local to module */ set_current_module_entity( local_name_to_top_level_entity(module_name) ); set_cumulated_rw_effects((statement_effects) db_get_memory_resource(DBR_CUMULATED_EFFECTS, module_name, true)); module_to_value_mappings(get_current_module_entity()); debug_on("COMP_REGIONS_DEBUG_LEVEL"); pips_debug(3, "begin\n"); /* }}} */ /* }}} */ /* Compute the regions of the module. */ set_local_comp_regions_map( MAKE_STATEMENT_MAPPING() ); /* {{{ for dependence analysis : currently masked */ /* set_proper_regions_map( MAKE_STATEMENT_MAPPING() ); */ /* }}} */ (void)comp_regions_of_statement(get_current_module_statement()); /* {{{ code*/ /* {{{ debug stmts*/ /* if (op_statistics_p()) print_regions_op_statistics(module_name, R_RW); */ pips_debug(3, "end\n"); debug_off(); /* }}} */ /* {{{ store in database : modify later*/ DB_PUT_MEMORY_RESOURCE(DBR_COMPSEC, strdup(module_name), (char*) listmap_to_compsecs_map(get_local_comp_regions_map()) ); /* DB_PUT_MEMORY_RESOURCE(DBR_PROPER_REGIONS, strdup(module_name), (char*) listmap_to_effectsmap(get_proper_regions_map())); */ /* }}} */ /* {{{ finalise*/ reset_current_module_entity(); reset_current_module_statement(); reset_transformer_map(); reset_precondition_map(); reset_cumulated_rw_effects(); free_local_comp_regions_map(); /* }}} */ /* }}} */ return(true); } /* }}} */ /* {{{ comp_regions_of_statement*/ /* {{{ comments*/ /* list comp_regions_of_statement(statement s) * input : the current statement. * output : a list of regions. * modifies : the local regions_map. * comment : computes the local regions of a statement and stores it * in the local_regions_map. */ /* }}} */ list comp_regions_of_statement(statement s) { /* {{{ code*/ /* {{{ inits*/ transformer t_stat, context; list lreg, lpropreg = NIL; ifdebug(3) { pips_debug(3, "begin\n\tComputation of regions of statement %03td\n", statement_number(s)); } /* }}} */ /* {{{ transformer and preconditions*/ context = load_statement_precondition(s); /* compute the regions on the instruction of the statement */ t_stat = load_statement_transformer(s); /* }}} */ /* }}} */ lreg = comp_regions_of_instruction(statement_instruction(s), t_stat, context, &lpropreg); /* {{{ code*/ /* {{{ store the result : currently masked, modify later*/ /* FI: make a copy to safely store that intermediate state in the mapping */ /* debug_regions_consistency(lreg); debug_regions_consistency(lpropreg); store_statement_proper_regions(s, lpropreg); */ store_statement_local_comp_regions(s, comp_regions_dup(lreg) ); /* }}} */ /* }}} */ return(lreg); } /* }}} */ /* {{{ comp_regions_of_instruction*/ /* {{{ comments*/ /* list comp_regions_of_instruction(instruction i, transformer t_inst, context, * list *plpropreg) * input : the current instruction and the corresponding transformer * and context (i.e. precondition), and a pointer that will contain * the proper regions of the instruction. * output : the corresponding list of regions. * modifies : nothing. */ /* }}} */ list comp_regions_of_instruction(instruction i, transformer t_inst, transformer context, list *plpropreg) { /* {{{ init*/ list lreg = NIL; *plpropreg = NIL; /* }}} */ switch(instruction_tag(i)) { /* {{{ code*/ case is_instruction_goto: /* {{{ code*/ pips_debug(3, "goto\n"); break; /* }}} */ case is_instruction_test: /* {{{ code*/ ifdebug(3) { pips_debug(3, "test : %s\n", words_to_string(words_expression (test_condition(instruction_test(i)), NIL))); } lreg = comp_regions_of_test(instruction_test(i), context, plpropreg); break; /* }}} */ case is_instruction_loop: /* {{{ code*/ ifdebug(3) { pips_debug(3, "loop : index %s\n", entity_local_name(loop_index(instruction_loop(i)))); } lreg = comp_regions_of_loop(instruction_loop(i), t_inst, context, plpropreg); break; /* }}} */ case is_instruction_call: /* {{{ code*/ ifdebug(3) { pips_debug(3, "call : %s\n", module_local_name(call_function(instruction_call(i)))); } lreg = comp_regions_of_call(instruction_call(i), context, plpropreg); break; /* }}} */ case is_instruction_unstructured: /* {{{ code*/ pips_debug(3, "unstructured\n"); lreg = comp_regions_of_unstructured(instruction_unstructured( i ), t_inst); break ; /* }}} */ case is_instruction_block: /* {{{ code*/ pips_debug(3, "inst block\n"); lreg = comp_regions_of_block(instruction_block(i)); break; /* }}} */ default: pips_debug(3, "unexpected tag %d\n", instruction_tag(i)); /* }}} */ } return(lreg); } /* }}} */ /* {{{ comp_region_of_block*/ /* {{{ comment*/ /* list comp_regions_of_block(list linst) * input : a list of instructions, representing a sequential block * of instructions, and the context before the block. * output : a list of regions * modifies : linst. * comment : calls itself recursively to calculate the list of regions. */ /* }}} */ list comp_regions_of_block(list linst) { /* {{{ init*/ statement first_statement; list remaining_block, first_s_regions, lres = NIL; pips_debug(3, "begin\n"); /* }}} */ /* {{{ Is it end of list ? */ if (ENDP(linst)) { user_warning("regions_of_block", "empty block\n"); lres = NIL; } /* }}} */ /* {{{ else process list*/ else { /* {{{ regions of CAR(linst)*/ first_statement = STATEMENT(CAR(linst)); remaining_block = CDR(linst); first_s_regions = comp_regions_of_statement(first_statement); /* }}} */ /* {{{ any more statements in CDR(linst)*/ if (!ENDP(remaining_block)) { /* {{{ load transformer*/ list r_block_regions = NIL; /* }}} */ r_block_regions = comp_regions_of_block(remaining_block); /* {{{ perform union*/ /* {{{ don't know that this means ???*/ /* blocked : check later list current_transformer = load_statement_transformer(first_statement); debug_regions_consistency(r_block_regions); project_regions_with_transformer_inverse(r_block_regions, current_transformer, NIL); debug_regions_consistency(r_block_regions); */ /* }}} */ lres = CompRegionsExactUnion(first_s_regions, r_block_regions, effects_same_action_p); /* debug_regions_consistency(lres); */ /* }}} */ } /* }}} */ /* {{{ if not lres = first_s_regions*/ else lres = first_s_regions; /* }}} */ } /* }}} */ pips_debug(3, "end\n"); return lres; } /* }}} */ /* {{{ comp_regions of test*/ /* list regions_of_test(test t, transformer context, list *plpropreg) * input : a test instruction, the context of the test, and a pointer * toward a list that will contain the proper regions of the test, * which are the regions of its conditionnal part. * output : the corresponding list of regions. * modifies : nothing. */ list comp_regions_of_test(test t, transformer context, list __attribute__ ((unused)) *plpropreg) { /* {{{ init*/ list le, lt, lf, lc, lr; pips_debug(3, "begin\n"); /* }}} */ /* {{{ if-then-else including if-condition*/ /* regions of the true branch */ lt = comp_regions_of_statement(test_true(t)); /* regions of the false branch */ lf = comp_regions_of_statement(test_false(t)); /* regions of the combination of both */ le = CompRegionsMayUnion(lt, lf, effects_same_action_p); /* regions of the condition */ lc = comp_regions_of_expression(test_condition(t), context); /* check later *plpropreg = comp_regions_dup(lc); */ /* }}} */ /* {{{ union the regions : currently just add to the list*/ lr = CompRegionsExactUnion(le, lc, effects_same_action_p); pips_debug(3, "end\n"); /* }}} */ return(lr); } /* }}} */ /* {{{ comp_regions of loop*/ /* list comp_regions_of_loop(loop l, transfomer loop_trans, context, list *plpropreg) * input : a loop, its transformer and its context, and a pointer toward a list, * that will contain the proper regions of the loop, which are the * regions of its range. * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_loop(loop l, transformer __attribute__ ((unused)) loop_trans, transformer context, list __attribute__ ((unused)) *plpropreg) { /* {{{ init*/ list index_reg, body_reg, le; /* list global_reg; entity i = loop_index(l); */ pips_debug(3, "begin\n"); /* }}} */ /* CheckStride(l); */ /* regions of loop index. */ if( execution_sequential_p( loop_execution( l ))) { /* {{{ code*/ /* loop index is must-written but may-read because the loop might execute no iterations. */ reference ref = make_reference(loop_index(l), NIL); index_reg = comp_regions_of_write(ref, context); /* the loop index is must-written */ /* FI, RK: the may-read effect on the index variable is masked by * the intial unconditional write on it (see standard page 11-7, 11.10.3); * if masking is not performed, the read may prevent privatization * somewhere else in the module (12 March 1993) */ /* }}} */ } else index_reg = NIL ; /* {{{ regions of loop induction variable*/ /* regions of loop bound expressions. */ le = CompRegionsExactUnion( index_reg, comp_regions_of_range(loop_range(l), context), effects_same_action_p); /* }}} */ /* *plpropreg = regions_dup(le); */ /* regions of loop body statement. */ body_reg = comp_regions_of_statement(loop_body(l)); /* insert code to eliminate private variables later */ /* projection of regions along the variables modified by the loop; it includes * the projection along the loop index */ pips_debug(7, "elimination of variables modified by the loop.\n"); /* {{{ In simple sections it is called translation !!*/ /* project_regions_with_transformer_inverse(global_reg, loop_trans, CONS(ENTITY,i,NIL)); project_regions_along_loop_index(global_reg, i, loop_range(l)); */ pips_debug(3, "Before Translations surrounding the loop index %s :\n", entity_local_name(loop_index(l))); (void) TranslateRefsToLoop(l, body_reg); le = CompRegionsExactUnion(le, body_reg, effects_same_action_p); ifdebug(3) { pips_debug(3, "After Translations surrounding the loop index %s :\n", entity_local_name(loop_index(l))); PrintCompRegions(le); } pips_debug(3, "end\n"); /* }}} */ return(le); } /* }}} */ /* {{{ comp_regions of call*/ /* list comp_regions_of_call(call c, transformer context, list *plpropreg) * input : a call, which can be a call to a subroutine, but also * to an function, or to an intrinsic, or even an assignement. * And a pointer that will be the proper regions of the call; NIL, * except for an intrinsic (assignment or real FORTRAN intrinsic). * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_call(call c, transformer context, list *plpropreg) { list le = NIL; entity e = call_function(c); tag t = value_tag(entity_initial(e)); const char* n = module_local_name(e); list pc = call_arguments(c); *plpropreg = NIL; pips_debug(3, "begin\n"); switch (t) { /* {{{ code*/ case is_value_code: pips_debug(3, "external function %s\n", n); /* masked now : change later */ /* le = comp_regions_of_external(e, pc, context); */ break; case is_value_intrinsic: pips_debug(3, "intrinsic function %s\n", n); le = comp_regions_of_intrinsic(e, pc, context); /* masked now : *plpropreg = regions_dup(le); */ break; case is_value_symbolic: pips_debug(3, "symbolic\n"); break; case is_value_constant: pips_debug(3, "constant\n"); break; case is_value_unknown: pips_internal_error("unknown function %s", n); break; default: pips_internal_error("unknown tag %d", t); /* }}} */ } pips_debug(3, "end\n"); return(le); } /* }}} */ /* {{{ comp_regions of unstructured*/ /* Computes the effects of the control graph. */ /* list comp_regions_of_unstructured( u , t_unst) * input : an unstructured control flow graph and the corresponding * transformer. * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_unstructured(unstructured u, transformer t_unst) { control ct; list blocs = NIL ; list le = NIL ; pips_debug(3, "begin\n"); ct = unstructured_control( u ); if(control_predecessors(ct) == NIL && control_successors(ct) == NIL) { /* there is only one statement in u; no need for a fix-point */ pips_debug(3, "unique node\n"); le = comp_regions_of_statement(control_statement(ct)); } else { CONTROL_MAP(c, { le = CompRegionsMayUnion(comp_regions_of_statement(control_statement(c)), le, effects_same_action_p) ; },ct, blocs) ; project_regions_along_parameters(le, transformer_arguments(t_unst)); gen_free_list(blocs) ; } pips_debug(3, "end\n"); return( le ) ; } /* }}} */ /* {{{ comp_regions_of_range*/ /* list comp_regions_of_range(range r, context) * input : a loop range (bounds and stride) and the context. * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_range(range r, transformer context) { list le; expression el = range_lower(r); expression eu = range_upper(r); expression ei = range_increment(r); pips_debug(3, "begin\n"); le = comp_regions_of_expression(el, context); le = CompRegionsExactUnion(le, comp_regions_of_expression(eu, context), effects_same_action_p); le = CompRegionsExactUnion(le, comp_regions_of_expression(ei, context), effects_same_action_p); pips_debug(3, "end\n"); return(le); } /* }}} */ /* {{{ comp_regions_of_syntax*/ /* list comp_regions_of_syntax(syntax s, transformer context) * input : * output : * modifies : * comment : */ list comp_regions_of_syntax(syntax s, transformer context) { list le = NIL, lpropreg = NIL; pips_debug(3, "begin\n"); switch(syntax_tag(s)) { /* {{{ code*/ case is_syntax_reference: le = comp_regions_of_read(syntax_reference(s), context); break; case is_syntax_range: le = comp_regions_of_range(syntax_range(s), context); break; case is_syntax_call: le = comp_regions_of_call(syntax_call(s), context, &lpropreg); /* comp_desc_free(lpropreg); */ break; default: pips_internal_error("unexpected tag %d", syntax_tag(s)); /* }}} */ } ifdebug(3) { pips_debug(3, "Regions of expression %s :\n", words_to_string(words_syntax(s, NIL))); print_regions(le); } pips_debug(3, "end\n"); return(le); } /* }}} */ /* {{{ comp_regions_of_expressions*/ /* list comp_regions_of_expressions(list exprs, transformer context) * input : a list of expressions and the current context. * output : the correpsonding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_expressions(list exprs, transformer context) { list le = NIL; pips_debug(3, "begin\n"); MAP(EXPRESSION, exp, { le = CompRegionsExactUnion(le, comp_regions_of_expression(exp, context), effects_same_action_p); }, exprs); pips_debug(5, "end\n"); return(le); } /* {{{ comp_regions_of_expression*/ /* list comp_regions_of_expression(expression e, transformer context) * input : an expression and the current context * output : the correpsonding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_expression(expression e, transformer context) { return(comp_regions_of_syntax(expression_syntax(e), context)); } /* }}} */ /* }}} */ /* {{{ comp_regions_of_read*/ /* list comp_regions_of_read(reference ref, transformer context) * input : a reference that is read, and the current context. * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_read(reference ref, transformer context) { /* {{{ init*/ list inds = reference_indices(ref); list le = NIL; comp_desc Cdesc; entity e = reference_variable(ref); pips_debug(3, "begin\n"); /* }}} */ /* {{{ code*/ /* {{{ this read reference*/ if (! entity_scalar_p(e) ) { Cdesc = InitCompDesc(ref, is_action_read); le = CONS(COMP_DESC, Cdesc, le); } /* }}} */ /* {{{ rest of the references in an expression*/ if (! ENDP(inds)) le = CompRegionsExactUnion(le, comp_regions_of_expressions(inds, context), effects_same_action_p); /* }}} */ /* }}} */ pips_debug(3, "end\n"); return(le); } /* }}} */ /* {{{ comp_regions_of_write*/ /* regions of a reference that is written */ /* list comp_regions_of_write(reference ref, transformer context) * input : a reference that is written, and the current context. * output : the corresponding list of regions. * modifies : nothing. * comment : */ list comp_regions_of_write(reference ref, transformer context) { /* {{{ init*/ comp_desc Cdesc; list le = NIL; entity e = reference_variable(ref); list inds = reference_indices(ref); /* }}} */ pips_debug(3, "begin\n"); /* {{{ this write */ if (! entity_scalar_p(e) ) { Cdesc = InitCompDesc(ref, is_action_write); le = CONS(COMP_DESC, Cdesc, le); } /* }}} */ /* {{{ check for arrays in subscripts*/ if (! ENDP(inds)) le = CompRegionsExactUnion(le, comp_regions_of_expressions(inds, context), effects_same_action_p); /* }}} */ pips_debug(3, "end\n"); return(le); } /* }}} */ /* }}} */
28.306122
112
0.620854
0748893d73bb824ee31dba196ae093c6eaeffde3
368
h
C
src/Wallet/Keychain/KeyDefs.h
yasabi/GrinPlusPlus
8e9a32b3d2171c3dea1d4de833a1fc5cb12981ea
[ "MIT" ]
null
null
null
src/Wallet/Keychain/KeyDefs.h
yasabi/GrinPlusPlus
8e9a32b3d2171c3dea1d4de833a1fc5cb12981ea
[ "MIT" ]
null
null
null
src/Wallet/Keychain/KeyDefs.h
yasabi/GrinPlusPlus
8e9a32b3d2171c3dea1d4de833a1fc5cb12981ea
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include <Crypto/BigInteger.h> namespace KeyDefs { static const uint32_t MINIMUM_HARDENED_INDEX = 2147483648; static const CBigInteger<32> SECP256K1_N = CBigInteger<32>::FromHex("0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141"); static const CBigInteger<32> BIG_INT_ZERO = CBigInteger<32>::ValueOf(0); }
33.454545
146
0.796196
729e14dcd81859241e4d3fb5fb1c6edf3138896a
872
c
C
src/Quiet.X/Commands/standardCommands.c
callwyat/Quiet-Firmware
864c210e44d368a4a683704841067717ebc8ac43
[ "MIT" ]
null
null
null
src/Quiet.X/Commands/standardCommands.c
callwyat/Quiet-Firmware
864c210e44d368a4a683704841067717ebc8ac43
[ "MIT" ]
null
null
null
src/Quiet.X/Commands/standardCommands.c
callwyat/Quiet-Firmware
864c210e44d368a4a683704841067717ebc8ac43
[ "MIT" ]
null
null
null
#include "../constants.h" #include "../CLI/cli.h" #include "../settings.h" void IDNCommand(CliHandle_t *handle, void *v) { if (handle->LastRead == '?') { ReadChar(handle); WriteString(handle, MakeString); WriteChar(handle, ','); WriteString(handle, ModelString); WriteChar(handle, ','); QuietSettings_t settings = GetSettings(); char *snc = settings.SerialNumber; while (*snc != 0x00) handle->Write(*snc++); WriteChar(handle, ','); WriteString(handle, VersionString); } } void RSTCommand(CliHandle_t *handle, void *v) { ClearAllErrors(); RestoreSettings(false); } CommandDefinition_t starCommands[] = { DEFINE_COMMAND("IDN", IDNCommand), DEFINE_COMMAND("RST", RSTCommand), }; CommandDefinition_t StarCommand = DEFINE_BRANCH("*", starCommands);
22.358974
67
0.619266
b0db3fe7cc8fc83a2bc043fa5d87e69970bb7c3b
2,341
h
C
src/HarbourMce.h
monich/harbour-lib
681f7c4654d7a7ac7324dc8da209c8865174d1e0
[ "BSD-3-Clause-Clear" ]
3
2016-06-28T13:12:00.000Z
2022-03-31T07:07:41.000Z
src/HarbourMce.h
monich/harbour-lib
681f7c4654d7a7ac7324dc8da209c8865174d1e0
[ "BSD-3-Clause-Clear" ]
null
null
null
src/HarbourMce.h
monich/harbour-lib
681f7c4654d7a7ac7324dc8da209c8865174d1e0
[ "BSD-3-Clause-Clear" ]
4
2019-07-04T13:18:25.000Z
2022-03-31T07:07:51.000Z
/* * Copyright (C) 2018 Jolla Ltd. * Copyright (C) 2018 Slava Monich <slava.monich@jolla.com> * * You may use this file under the terms of the BSD license as follows: * * 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 Jolla Ltd 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. */ #ifndef HARBOUR_MCE_H #define HARBOUR_MCE_H #include <QDBusConnection> #include <QDBusPendingCall> class HarbourMce : public QObject { Q_OBJECT public: static const QString MCE_SERVICE; static const QString MCE_REQUEST_PATH; static const QString MCE_REQUEST_INTERFACE; static const QString MCE_SIGNAL_PATH; static const QString MCE_SIGNAL_INTERFACE; HarbourMce(QObject* aParent); static QDBusConnection bus(); static QDBusPendingCall request(QString aMethod); void setupProperty(QString aQueryMethod, QString aSignal, const char* aQuerySlot, const char* aSignalSlot); }; #endif // HARBOUR_MCE_H
40.362069
72
0.756941
8e93d59c0ed00a5143b33dd0c2cc206f55c124bd
287
h
C
shpRead_ipad_02/ShapePoint.h
sunhongyue4500/Undergraduate-Graduation-Project
fe489dea9588b3129f7aa0a7bf1c63954bc0bea7
[ "MIT" ]
null
null
null
shpRead_ipad_02/ShapePoint.h
sunhongyue4500/Undergraduate-Graduation-Project
fe489dea9588b3129f7aa0a7bf1c63954bc0bea7
[ "MIT" ]
null
null
null
shpRead_ipad_02/ShapePoint.h
sunhongyue4500/Undergraduate-Graduation-Project
fe489dea9588b3129f7aa0a7bf1c63954bc0bea7
[ "MIT" ]
null
null
null
// // ShapePoint.h // shpRead_ipad_02 // // Created by shy on 15/4/12. // Copyright (c) 2015年 SHY. All rights reserved. // #import <Foundation/Foundation.h> #import "Shapefile.h" @interface ShapePoint : Shapefile { @private @public double m_nEast; double m_nNorth; } @end
11.958333
49
0.675958
fd1d187dc96cb97003199c318deeee6474fb76a5
602
h
C
BanTang/BanTang/Utitls/Store/BTDataBaseManager.h
JMStack/BTApp
4653a47da3be43ee27343c16a2527779518b060f
[ "MIT" ]
1
2016-05-27T02:58:08.000Z
2016-05-27T02:58:08.000Z
BanTang/BanTang/Utitls/Store/BTDataBaseManager.h
JMStack/BTApp
4653a47da3be43ee27343c16a2527779518b060f
[ "MIT" ]
null
null
null
BanTang/BanTang/Utitls/Store/BTDataBaseManager.h
JMStack/BTApp
4653a47da3be43ee27343c16a2527779518b060f
[ "MIT" ]
null
null
null
// // RCDataBaseManager.h // RCloudMessage // // Created by 杜立召 on 15/6/3. // Copyright (c) 2015年 RongCloud. All rights reserved. // #import <Foundation/Foundation.h> @class BTHomePageData,BTHomeBanner; @interface BTDataBaseManager : NSObject + (BTDataBaseManager*)shareInstance; /** 插入homePageData */ - (void)insertHomePageDataToDB:(BTHomePageData *)pageData page:(NSInteger)page; /** 获取homePageData */ - (BTHomePageData *)getPageDataWithPage:(NSInteger)page; /** 插入bannerData */ - (void)inserthomeBannerDataToDB:(NSArray *)pageDataArray; /** 获取bannerData */ - (NSArray *)getbannerData; @end
23.153846
79
0.740864
b079b5b4cad24268e0b75312c6dc3c51a68f0759
352
h
C
Catamaran/View/CATOAuthView.h
Alex601t/Catamaran
b97d053256985bd6e3dd3323be30e30f354d70cb
[ "MIT" ]
45
2016-10-15T10:33:06.000Z
2021-08-02T02:25:53.000Z
Catamaran/View/CATOAuthView.h
Alex601t/Catamaran
b97d053256985bd6e3dd3323be30e30f354d70cb
[ "MIT" ]
6
2016-10-17T05:24:34.000Z
2018-03-11T16:35:03.000Z
Catamaran/View/CATOAuthView.h
Alex601t/Catamaran
b97d053256985bd6e3dd3323be30e30f354d70cb
[ "MIT" ]
8
2016-10-15T07:24:27.000Z
2017-10-09T09:21:53.000Z
#import <UIKit/UIKit.h> @class CATOAuthAppearance; @interface CATOAuthView : UIView @property(nonatomic, strong, readonly) UIWebView *webView; @property(nonatomic, strong, readonly) UIActivityIndicatorView *activityIndicatorView; - (void)configureWithAppearance:(CATOAuthAppearance *)appearance navigationBar:(UINavigationBar *)navigationBar; @end
29.333333
112
0.818182
fc4e13bccb5d28861464dc52386548d9665cccf0
2,509
h
C
src/ui/stick20hiddenvolumedialog.h
daringer/nitrokey-app
65437f2da358527678db8ca2b4cabf4d18009ed5
[ "MIT" ]
1
2018-09-02T16:57:46.000Z
2018-09-02T16:57:46.000Z
src/ui/stick20hiddenvolumedialog.h
daringer/nitrokey-app
65437f2da358527678db8ca2b4cabf4d18009ed5
[ "MIT" ]
null
null
null
src/ui/stick20hiddenvolumedialog.h
daringer/nitrokey-app
65437f2da358527678db8ca2b4cabf4d18009ed5
[ "MIT" ]
1
2021-09-06T16:06:38.000Z
2021-09-06T16:06:38.000Z
/* * Author: Copyright (C) Rudolf Boeddeker Date: 2013-08-13 * Copyright (c) 2013-2018 Nitrokey UG * * This file is part of Nitrokey App. * * Nitrokey App 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, either version 3 of the License, or * any later version. * * Nitrokey App 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 Nitrokey App. If not, see <http://www.gnu.org/licenses/>. * * SPDX-License-Identifier: GPL-3.0 */ #ifndef STICK20HIDDENVOLUMEDIALOG_H #define STICK20HIDDENVOLUMEDIALOG_H #include <QDialog> #include <QAbstractButton> #include "libada.h" #include <atomic> namespace Ui { class stick20HiddenVolumeDialog; } typedef struct { unsigned char SlotNr_u8 = 0; unsigned char StartBlockPercent_u8 = 70; unsigned char EndBlockPercent_u8 = 90; unsigned char HiddenVolumePassword_au8[MAX_HIDDEN_VOLUME_PASSOWORD_SIZE + 1] = {}; } HiddenVolumeSetup_tst; class stick20HiddenVolumeDialog : public QDialog { Q_OBJECT public : explicit stick20HiddenVolumeDialog(QWidget *parent = 0); ~stick20HiddenVolumeDialog(); HiddenVolumeSetup_tst HV_Setup_st; private: int GetCharsetSpace(unsigned char *Password, size_t size); double GetEntropy(unsigned char *Password, size_t size); uint8_t HighWatermarkMin; uint8_t HighWatermarkMax; int sd_size_GB; void setHighWaterMarkText(void); void on_rd_unit_clicked(QString text); private slots: void on_ShowPasswordCheckBox_toggled(bool checked); void on_buttonBox_clicked(QAbstractButton *button); void on_HVPasswordEdit_textChanged(const QString &arg1); void on_rd_percent_clicked(); void on_rd_MB_clicked(); void on_rd_GB_clicked(); void on_StartBlockSpin_valueChanged(double i); void on_EndBlockSpin_valueChanged(double i); private: Ui::stick20HiddenVolumeDialog *ui; void set_spins_min_max(const double min, const double max, const double step); char last = '%'; double i_start_MB = 0; double i_end_MB = 0; double current_min = 0; double current_max = 100; double current_step = 1; std::atomic_bool cancel_BlockSpin_event_propagation {false}; }; #endif // STICK20HIDDENVOLUMEDIALOG_H
28.511364
86
0.765245
5287303a4ed3e23f043ee40755627239d4fafa96
232
h
C
src/types.h
kittrz9/Femur-Fighter-2
1e4254767327cf73bcbd6155a7579ce1bef76134
[ "WTFPL" ]
null
null
null
src/types.h
kittrz9/Femur-Fighter-2
1e4254767327cf73bcbd6155a7579ce1bef76134
[ "WTFPL" ]
null
null
null
src/types.h
kittrz9/Femur-Fighter-2
1e4254767327cf73bcbd6155a7579ce1bef76134
[ "WTFPL" ]
null
null
null
#ifndef TYPES_H #define TYPES_H // Probably should have more types than just vec2f eventually but it's better than having it in the entity file typedef struct { float x, y; } vec2f; #define WIDTH 1600 #define HEIGHT 900 #endif
16.571429
111
0.75431
50979b0c4dcfc296dff71a0c87f57c3cff358673
262
h
C
Core/zoolib/UnicodeCU8.h
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
13
2015-01-28T21:05:09.000Z
2021-11-03T22:21:11.000Z
Core/zoolib/UnicodeCU8.h
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
null
null
null
Core/zoolib/UnicodeCU8.h
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
4
2018-11-16T08:33:33.000Z
2021-12-11T19:40:46.000Z
// Copyright (c) 2012-2020 Andrew Green. MIT License. http://www.zoolib.org #ifndef __ZooLib_UnicodeCU8_h__ #define __ZooLib_UnicodeCU8_h__ 1 #include "zconfig.h" namespace ZooLib { typedef char UTF8; } // namespace ZooLib #endif // __ZooLib_UnicodeCU8_h__
18.714286
75
0.770992
dd9f38c90f0b39ff68f5f3e05877edc69d9fce03
612
h
C
Odin/includes/socket.h
Unam3dd/Train-2018-2020
afb6ae70fe338cbe55a21b74648d91996b818fa2
[ "MIT" ]
4
2021-04-23T15:39:17.000Z
2021-12-27T22:53:24.000Z
includes/socket.h
Unam3dd/Odin
9f775c85fe598e985d0aaf32a643b65b4c819c46
[ "MIT" ]
null
null
null
includes/socket.h
Unam3dd/Odin
9f775c85fe598e985d0aaf32a643b65b4c819c46
[ "MIT" ]
2
2021-04-19T08:28:54.000Z
2022-01-19T13:23:29.000Z
#pragma once #include "console.h" #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> typedef int SOCKET; typedef struct Fdinfo { char *address; int port; } Fdinfo_t; typedef struct ThreadHandle { SOCKET fd; SOCKET *array; int n; } ThreadHandle_t; typedef struct Stream { int in; int out; } Stream_t; SOCKET listen_on_new_port(int port); void *handle_new_client(void *param); void *std_stream(void *param); int shell_session(SOCKET fd); void list_connections(SOCKET *array); void close_all_connections(SOCKET *array,int n); void enter_session(int id,SOCKET *array);
18
48
0.72549
f7ed4945a65eae429cf50f5a17fef866242e26f3
533
h
C
stack.h
Eliex/BrainFplusplus
361bd33a0079b21507184b7dedca76dd7509a299
[ "MIT" ]
null
null
null
stack.h
Eliex/BrainFplusplus
361bd33a0079b21507184b7dedca76dd7509a299
[ "MIT" ]
null
null
null
stack.h
Eliex/BrainFplusplus
361bd33a0079b21507184b7dedca76dd7509a299
[ "MIT" ]
null
null
null
#ifndef STACK_H #define STACK_H #include<stdlib.h> int* g_stack; int g_stack_size; int g_top; __inline void create_stack(int p_size){ g_stack = calloc(p_size, sizeof(int)); g_stack_size = p_size; g_top = 0; } __inline void push(int p_data){ g_stack[g_top++] = p_data; } __inline void pop(){ g_top--; } __inline int top(){ return g_stack[g_top-1]; } __inline int is_stack_empty(){ return (g_top == 0); } __inline int is_stack_full(){ return (g_top == g_stack_size); } __inline clean_stack(){ free(g_stack); } #endif
13.325
39
0.699812
5a60514afc4e0c7703020c512df288a49d5b5412
181
h
C
Pods/Target Support Files/Pods-The Britannia/Pods-The Britannia-umbrella.h
robpeach/test
ef494524d3e14e35a914a1079937ae8b58998ccd
[ "MIT" ]
null
null
null
Pods/Target Support Files/Pods-The Britannia/Pods-The Britannia-umbrella.h
robpeach/test
ef494524d3e14e35a914a1079937ae8b58998ccd
[ "MIT" ]
null
null
null
Pods/Target Support Files/Pods-The Britannia/Pods-The Britannia-umbrella.h
robpeach/test
ef494524d3e14e35a914a1079937ae8b58998ccd
[ "MIT" ]
null
null
null
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_The_BritanniaVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_The_BritanniaVersionString[];
20.111111
72
0.850829
0c7bdc46b69b68a7d1a011a11b56a08125664698
1,723
h
C
include/trace/backend/udp/UdpBackEndControl.h
kotfranek/TraceLog
078f57b034dc80094d3abfb13cff57f38b4a524f
[ "BSD-2-Clause" ]
1
2018-07-21T21:49:46.000Z
2018-07-21T21:49:46.000Z
include/trace/backend/udp/UdpBackEndControl.h
kotfranek/TraceLog
078f57b034dc80094d3abfb13cff57f38b4a524f
[ "BSD-2-Clause" ]
2
2016-02-02T23:15:58.000Z
2016-02-13T01:42:37.000Z
include/trace/backend/udp/UdpBackEndControl.h
kotfranek/TraceLog
078f57b034dc80094d3abfb13cff57f38b4a524f
[ "BSD-2-Clause" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: UdpBackEndNetInterface.h * Author: kret * * Created on February 19, 2016, 3:17 PM */ #ifndef UDPBACKENDNETINTERFACE_H #define UDPBACKENDNETINTERFACE_H #include <stdint.h> namespace trace { namespace backend { namespace udp { /* Presence signal period (us) */ const int64_t UDP_SERVER_HEARTBEAT_PERIOD = 500U * 1000U; /* Maximum time between the Presence Signal (us) */ const int64_t UDP_SERVER_HEARTBEAT_TIMEOUT = 1000U * 1000U; /* UDP Client identification */ const char* UDP_CLIENT_HANDSHAKE = "TL_UDP_CL_HS"; /* UDP Client Disconnect */ const char* UDP_CLIENT_CLOSE = "TL_UDP_CL_CLOSE"; /* UDP Client Disconnect */ const char* UDP_CLIENT_ID = "TL_UDP_CL_ID"; /* UDP Client Present (CURRENTLY NOT USED) */ const char* UDP_CLIENT_PRESENT = "TL_UDP_CL_PR"; /* UDP Server Log Entry prefix */ const char* UDP_SERVER_LOG_ENTRY = "TL_LE"; /* UDP Server identification */ const char* UDP_SERVER_HANDSHAKE = "TL_UDP_SRV_HS"; /* UDP Server Heartbeat signal */ const char* UDP_SERVER_HEARTBEAT = "TL_UDP_SRV_HB"; /* UDP Client Disconnect */ const char* UDP_SERVER_CLOSE = "TL_UDP_SRV_CLOSE"; } } }; #endif /* UDPBACKENDNETINTERFACE_H */
27.790323
79
0.579803
40e991d8cecdfdaa19a2ac109681a428e26a138c
11,567
h
C
private/inet/urlmon/zones/secmgr.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/urlmon/zones/secmgr.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/urlmon/zones/secmgr.h
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
// File: secmgr.h // // Contents: The object that implements the base IInternetSecurityManager interface // // Classes: CSecurityManager // // Functions: // // History: // //---------------------------------------------------------------------------- #ifndef _SECMGR_H_ #define _SECMGR_H_ #pragma warning(disable:4200) #define MAX_SEC_MGR_CACHE 4 #define URLZONE_INVALID URLZONE_USER_MAX+1 #define MUTZ_NOCACHE 0x80000000 // start private flags from high end struct ZONEMAP_COMPONENTS; struct RANGE_ITEM { BYTE bLow[4]; // high byte values for range BYTE bHigh[4]; // low byte values for range TCHAR szName[1]; // actually variable length }; class CSecurityManager : public IInternetSecurityManager { public: // IUnknown methods STDMETHODIMP QueryInterface(REFIID iid, void **ppvObj); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); STDMETHODIMP MapUrlToZone( /* [in] */ LPCWSTR pwszUrl, /* [out] */ DWORD *pdwZone, /* [in] */ DWORD dwReserved); STDMETHODIMP GetSecurityId( /* [in] */ LPCWSTR pwszUrl, /* [size_is][out] */ BYTE* pbSecurityId, /* [out][in] */ DWORD *pcbSecurityId, /* [in] */ DWORD_PTR dwReserved); STDMETHODIMP ProcessUrlAction( /* [in] */ LPCWSTR pwszUrl, /* [in] */ DWORD dwAction, /* [size_is][out] */ BYTE *pPolicy, /* [in] */ DWORD cbPolicy, /* [in] */ BYTE *pContext, /* [in] */ DWORD cbContext, /* [in] */ DWORD dwFlags, /* [in] */ DWORD dwReserved); STDMETHODIMP QueryCustomPolicy( /* [in] */ LPCWSTR pwszUrl, /* [in] */ REFGUID guidKey, /* [size_is][size_is][out] */ BYTE **ppPolicy, /* [out] */ DWORD *pcbPolicy, /* [in] */ BYTE *pContext, /* [in] */ DWORD cbContext, /* [in] */ DWORD dwReserved ); STDMETHODIMP SetSecuritySite( /* [in] */ IInternetSecurityMgrSite *pSite ); STDMETHODIMP GetSecuritySite( /* [out] */ IInternetSecurityMgrSite **ppSite ); STDMETHODIMP SetZoneMapping( /* [in] */ DWORD dwZone, /* [in] */ LPCWSTR lpszPattern, /* [in] */ DWORD dwFlags); STDMETHODIMP GetZoneMappings( /* [in] */ DWORD dwZone, /* [out] */ IEnumString **ppEnumString, /* [in] */ DWORD dwFlags); // Constructors/destructors public: CSecurityManager(IUnknown *pUnkOuter, IUnknown **ppUnkInner); virtual ~CSecurityManager(); static BOOL GlobalInit( ) ; static BOOL GlobalCleanup( ); // Aggregation and RefCount support. protected: CRefCount m_ref; class CPrivUnknown : public IUnknown { public: STDMETHOD(QueryInterface) ( REFIID riid, LPVOID FAR* ppvObj); STDMETHOD_(ULONG,AddRef) (void); STDMETHOD_(ULONG,Release) (void); ~CPrivUnknown() {} CPrivUnknown() : m_ref () {} private: CRefCount m_ref; // the total refcount of this object }; friend class CPrivUnknown; CPrivUnknown m_Unknown; IUnknown* m_pUnkOuter; STDMETHODIMP_(ULONG) PrivAddRef() { return m_Unknown.AddRef(); } STDMETHODIMP_(ULONG) PrivRelease() { return m_Unknown.Release(); } protected: BOOL EnsureZoneManager(); VOID PickZCString(ZONEMAP_COMPONENTS *pzc, LPCWSTR *ppwsz, DWORD *pcch, LPCWSTR pwszDocDomain); // Helper methods to deal with IP Rules HRESULT ReadAllIPRules( ); HRESULT AddDeleteIPRule(ZONEMAP_COMPONENTS *pzc, DWORD dwZone, DWORD dwFlags); // helper methods to do GetZoneMappings. HRESULT AddUrlsToEnum(CRegKey *pRegKey, DWORD dwZone, LPCTSTR lpsz, int cch, BOOL bAddWildCard, CEnumString *); HRESULT AddIPRulesToEnum(DWORD dwZone, CEnumString *); static HRESULT ComposeUrlSansProtocol(LPCTSTR pszDomain, int cchDomain, LPCTSTR pszSite, int cchSite, LPTSTR * ppszRet, int * cchRet); static HRESULT ComposeUrl(LPCTSTR pszUrlSansProt, int cchUrlSansProt, LPCTSTR pszProt, int cchProt, BOOL bAddWildCard, LPTSTR * ppszRet, int * cchRet); protected: // UI related definitions. enum { MAX_ALERT_SIZE = 256 }; // Return values from DialogProc's enum { ZALERT_NO = 0 /* should be 0*/ , ZALERT_YES, ZALERT_YESPERSIST }; // This structure is used to exchange data between the security manager // and the dialog proc's. struct DlgData { DWORD dwAction; DWORD dwZone; LPWSTR pstr; DWORD dwFlags; }; typedef DlgData * LPDLGDATA; // helper methods to display generic UI. static DWORD GetAlertIdForAction(DWORD dwAction); static DWORD GetWarnIdForAction(DWORD dwAction); // Dialog proc's etc. static INT_PTR ZonesAlertDialogProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); static INT_PTR ZonesWarnDialogProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); static inline BOOL IsFormsSubmitAction(DWORD dwAction); static INT_PTR FormsAlertDialogProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); INT CSecurityManager::ShowFormsAlertDialog(HWND hwndParent, LPDLGDATA lpDlgData); protected: // Methods to help Map a URL to a zone. HRESULT MapUrlToZone (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, DWORD dwFlags, BOOL *pfMarked = NULL, LPWSTR *ppszURLMark = NULL); HRESULT CheckAddressAgainstRanges (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); HRESULT CheckSiteAndDomainMappings (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); HRESULT CheckUNCAsIntranet (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); HRESULT CheckIntranetName (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); HRESULT CheckProxyBypassRule (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); HRESULT CheckMKURL (ZONEMAP_COMPONENTS* pzc, DWORD* pdwZone, LPCTSTR pszProt); protected: // Class to remember persistent actions. class CPersistAnswers { public: CPersistAnswers( ) : m_pAnswerEntry(NULL) { }; ~CPersistAnswers( ); public: BOOL GetPrevAnswer(LPCWSTR pszUrl, DWORD dwAction, INT* piAnswer); VOID RememberAnswer(LPCWSTR pszUrl, DWORD dwAction, INT iAnswer); static inline BOOL IsPersistentAnswerAction(DWORD dwAction); private: struct CAnswerEntry { // Construction CAnswerEntry(LPCWSTR pszUrl, DWORD dwAction, INT iAnswer); ~CAnswerEntry( ); // Methods. BOOL MatchEntry (LPCWSTR pszUrl, DWORD dwAction); INT GetAnswer( ) const { return m_iAnswer; } LPCWSTR GetUrl( ) const { return m_pszUrl; } CAnswerEntry * GetNext( ) const { return m_pNext; } VOID SetNext(CAnswerEntry * pNext) { m_pNext = pNext; } private: CAnswerEntry * m_pNext; LPWSTR m_pszUrl; DWORD m_dwAction; INT m_iAnswer; }; CAnswerEntry* m_pAnswerEntry; }; CPersistAnswers m_persistAnswers; // Methods/members to support caching so we optimize MapUrlToZone, etc. protected: class CSecMgrCache { public: CSecMgrCache(void); ~CSecMgrCache(void); BOOL Lookup(LPCWSTR pwszURL, DWORD *pdwZone = NULL, BOOL *pfMarked = NULL, BYTE *pbSecurityID = NULL, DWORD *pcbSecurityID = NULL, LPCWSTR pwszDocDomain = NULL); void Add(LPCWSTR pwszURL, DWORD dwZone, BOOL fMarked, const BYTE *pbSecurityID = NULL, DWORD cbSecurityID = NULL, LPCWSTR pwszDocDomain = NULL ); void Flush(void); static VOID IncrementGlobalCounter( ); protected: // Counters to flag cross-process cache invalidation. DWORD m_dwPrevCounter ; // Global counter so we can correctly invalidate the cache if // user changes options. static HANDLE s_hMutexCounter; // mutex controlling access to shared memory counter BOOL IsCounterEqual() const; VOID SetToCurrentCounter(); // The body of the cache is this array of cache entries. // Cross-thread access control for the array is by critical section. CRITICAL_SECTION m_csectZoneCache; // assumes only one, static instance of the cache struct CSecMgrCacheEntry { CSecMgrCacheEntry(void) : m_pwszURL(NULL), m_pbSecurityID(NULL), m_cbSecurityID(NULL), m_dwZone(URLZONE_INVALID), m_fMarked(FALSE), m_pwszDocDomain(NULL) {}; ~CSecMgrCacheEntry(void) { Flush(); }; void Set(LPCWSTR pwszURL, DWORD dwZone, BOOL fMarked, const BYTE *pbSecurityID, DWORD cbSecurityID, LPCWSTR pwszDocDomain); void Flush(void); LPWSTR m_pwszURL; BYTE* m_pbSecurityID; DWORD m_cbSecurityID; DWORD m_dwZone; BOOL m_fMarked; LPWSTR m_pwszDocDomain; }; // CSecMgrCacheEntry CSecMgrCacheEntry m_asmce[MAX_SEC_MGR_CACHE]; int m_iAdd; // index in m_asmce to add the next element BOOL FindCacheEntry( LPCWSTR pwszURL, int& riEntry ); // must be called under critical section. }; // CSecMgrCache static CSecMgrCache s_smcache; protected: // Methods to manage List of Allowed ActiveX controls static BOOL EnsureListReady(BOOL bForce = FALSE); static void IntializeAllowedControls(); static HRESULT GetControlPermissions(BYTE * raw_CLSID, DWORD & dwPerm); // Get the final decision on the whether to run a CLSID (for this zone, etc) static HRESULT GetActiveXRunPermissions(BYTE * raw_CLSID, DWORD & dwPerm); public: static VOID IncrementGlobalCounter( ); private: IInternetSecurityMgrSite* m_pSite; IInternetZoneManager* m_pZoneManager; IInternetSecurityManager* m_pDelegateSecMgr; CRegKey m_regZoneMap; // Static members to do remember the correct IP Ranges. static BOOL s_bIPInit; // have we read the IP ranges. static BYTE* s_pRanges; // array of range items static DWORD s_cNumRanges; // number of range items static DWORD s_cbRangeItem; // size of each range item static DWORD s_dwNextRangeIndex; // Next index to use to add numbers in the range entry. static CRITICAL_SECTION s_csectIP; // crit section to protect it all. static BOOL s_bcsectInit; static CLSID * s_clsidAllowedList; static CRITICAL_SECTION s_csectAList; static DWORD s_dwNumAllowedControls; }; #pragma warning(default:4200) #endif // _SECMGR_H_
32.767705
123
0.60223
e5a37fb96d666ab73d8f7aa25c26dd2f9c0ff8d5
3,235
h
C
include/ha/param_tool_box/convert/linear.h
hansen-audio/param-tool-box
1437eac90a4b85f92dc067a66d15881d46b7ec8c
[ "MIT" ]
null
null
null
include/ha/param_tool_box/convert/linear.h
hansen-audio/param-tool-box
1437eac90a4b85f92dc067a66d15881d46b7ec8c
[ "MIT" ]
null
null
null
include/ha/param_tool_box/convert/linear.h
hansen-audio/param-tool-box
1437eac90a4b85f92dc067a66d15881d46b7ec8c
[ "MIT" ]
null
null
null
// Copyright(c) 2021 Hansen Audio. #pragma once #include "ha/param_tool_box/convert/detail/lin_scale.h" #include "ha/param_tool_box/core/clamp.h" #include "ha/param_tool_box/core/to_string.h" #include "ha/param_tool_box/core/types.h" #include <functional> namespace ha::ptb::convert { //----------------------------------------------------------------------------- /** * linear */ template <typename RealType> class linear { public: //------------------------------------------------------------------------- using value_type = RealType const; using mut_value_type = RealType; using fn_precision = std::function<i32(value_type)>; static i32 const STANDARD_PRECISION = 2; linear(value_type min, value_type max); value_type to_physical(value_type normalized) const; value_type to_normalized(value_type physical) const; string_type to_string(value_type physical, fn_precision const& precision_func = nullptr) const; value_type from_string(string_type const& value_string) const; //------------------------------------------------------------------------- private: using scale_type = detail::lin_scale<mut_value_type>; typename scale_type::context cx; }; //----------------------------------------------------------------------------- // linear //----------------------------------------------------------------------------- template <typename RealType> linear<RealType>::linear(value_type min, value_type max) { cx = scale_type::create(min, max); } //----------------------------------------------------------------------------- template <typename RealType> typename linear<RealType>::value_type linear<RealType>::to_physical(value_type normalized) const { value_type clamped = clamp(normalized, cx.norm_min, cx.norm_max); return scale_type::scale(cx, clamped); } //----------------------------------------------------------------------------- template <typename RealType> typename linear<RealType>::value_type linear<RealType>::to_normalized(value_type physical) const { value_type clamped = clamp(physical, cx.phys_min, cx.phys_max); return scale_type::scale_inverted(cx, clamped); } //----------------------------------------------------------------------------- template <typename RealType> string_type linear<RealType>::to_string(value_type physical, fn_precision const& precision_func) const { value_type tmp_physical = clamp(physical, cx.phys_min, cx.phys_max); i32 const precision = precision_func ? precision_func(tmp_physical) : STANDARD_PRECISION; return to_string_with_precision(tmp_physical, precision); } //----------------------------------------------------------------------------- template <typename RealType> typename linear<RealType>::value_type linear<RealType>::from_string(string_type const& value_string) const { // TODO: Make this more robust to non-digit inputs. value_type const value = static_cast<value_type>(std::stod(value_string)); return clamp(value, cx.phys_min, cx.phys_max); } //----------------------------------------------------------------------------- } // namespace ha::ptb::convert
34.784946
99
0.550232
3cd54f3af0545880c946cd9d31b4e2625f60ea24
15,423
c
C
wovo/bmptk/tools/micronucleus/micronucleus.c
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
wovo/bmptk/tools/micronucleus/micronucleus.c
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
wovo/bmptk/tools/micronucleus/micronucleus.c
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
/* Created: September 2012 (c) 2012 by ihsan Kehribar <ihsan@kehribar.me> Changes for Micronucleus protocol version V2.x (c) 2014 T. Bo"scke 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 <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "micronucleus_lib.h" #include "littleWire_util.h" #define FILE_TYPE_INTEL_HEX 1 #define FILE_TYPE_RAW 2 #define CONNECT_WAIT 250 /* milliseconds to wait after detecting device on usb bus - probably excessive */ /****************************************************************************** * Global definitions ******************************************************************************/ unsigned char dataBuffer[65536 + 256]; /* buffer for file data */ /*****************************************************************************/ /****************************************************************************** * Function prototypes ******************************************************************************/ static int parseRaw(char *hexfile, unsigned char *buffer, int *startAddr, int *endAddr); static int parseIntelHex(char *hexfile, unsigned char *buffer, int *startAddr, int *endAddr); /* taken from bootloadHID example from obdev */ static int parseUntilColon(FILE *fp); /* taken from bootloadHID example from obdev */ static int parseHex(FILE *fp, int numDigits); /* taken from bootloadHID example from obdev */ static void printProgress(float progress); static void setProgressData(char* friendly, int step); static int progress_step = 0; // current step static int progress_total_steps = 0; // total steps for upload static char* progress_friendly_name; // name of progress section static int dump_progress = 0; // output computer friendly progress info static int use_ansi = 0; // output ansi control character stuff static int erase_only = 0; // only erase, dont't write file static int fast_mode = 0; // normal mode adds 2ms to page writing times and waits longer for connect. static int timeout = 0; /*****************************************************************************/ /****************************************************************************** * Main function! ******************************************************************************/ int main(int argc, char **argv) { int res; char *file = NULL; micronucleus *my_device = NULL; // parse arguments int run = 0; int file_type = FILE_TYPE_INTEL_HEX; int arg_pointer = 1; #if defined(WIN) char* usage = "usage: micronucleus [--help] [--run] [--dump-progress] [--fast-mode] [--type intel-hex|raw] [--timeout integer] (--erase-only | filename)"; #else char* usage = "usage: micronucleus [--help] [--run] [--dump-progress] [--fast-mode] [--type intel-hex|raw] [--timeout integer] [--no-ansi] (--erase-only | filename)"; #endif progress_step = 0; progress_total_steps = 5; // steps: waiting, connecting, parsing, erasing, writing, (running)? dump_progress = 0; erase_only = 0; fast_mode=0; timeout = 0; // no timeout by default #if defined(WIN) use_ansi = 0; #else use_ansi = 1; #endif while (arg_pointer < argc) { if (strcmp(argv[arg_pointer], "--run") == 0) { run = 1; progress_total_steps += 1; } else if (strcmp(argv[arg_pointer], "--type") == 0) { arg_pointer += 1; if (strcmp(argv[arg_pointer], "intel-hex") == 0) { file_type = FILE_TYPE_INTEL_HEX; } else if (strcmp(argv[arg_pointer], "raw") == 0) { file_type = FILE_TYPE_RAW; } else { printf("Unknown File Type specified with --type option"); return EXIT_FAILURE; } } else if (strcmp(argv[arg_pointer], "--help") == 0 || strcmp(argv[arg_pointer], "-h") == 0) { puts(usage); puts(""); puts(" --type [intel-hex, raw]: Set upload file type to either intel hex or raw"); puts(" bytes (intel hex is default)"); puts(" --dump-progress: Output progress data in computer-friendly form"); puts(" for driving GUIs"); puts(" --erase-only: Erase the device without programming. Fills the"); puts(" program memory with 0xFFFF. Any files are ignored."); puts(" --fast-mode: Speed up the timing of micronucleus. Do not use if"); puts(" you encounter USB errors. "); puts(" --run: Ask bootloader to run the program when finished"); puts(" uploading provided program"); #ifndef WIN puts(" --no-ansi: Don't use ANSI in terminal output"); #endif puts(" --timeout [integer]: Timeout after waiting specified number of seconds"); puts(" filename: Path to intel hex or raw data file to upload,"); puts(" or \"-\" to read from stdin"); puts(""); puts(MICRONUCLEUS_COMMANDLINE_VERSION); return EXIT_SUCCESS; } else if (strcmp(argv[arg_pointer], "--dump-progress") == 0) { dump_progress = 1; } else if (strcmp(argv[arg_pointer], "--no-ansi") == 0) { use_ansi = 0; } else if (strcmp(argv[arg_pointer], "--fast-mode") == 0) { fast_mode = 1; } else if (strcmp(argv[arg_pointer], "--erase-only") == 0) { erase_only = 1; progress_total_steps -= 1; } else if (strcmp(argv[arg_pointer], "--timeout") == 0) { arg_pointer += 1; if (sscanf(argv[arg_pointer], "%d", &timeout) != 1) { printf("Did not understand --timeout value\n"); return EXIT_FAILURE; } } else { file = argv[arg_pointer]; } arg_pointer += 1; } if (file == NULL && erase_only == 0) { printf("Neither filename nor --erase-only given!\n\n"); puts(usage); return EXIT_FAILURE; } setProgressData("waiting", 1); if (dump_progress) printProgress(0.5); printf("> Please plug in the device ... \n"); printf("> Press CTRL+C to terminate the program.\n"); time_t start_time, current_time; time(&start_time); while (my_device == NULL) { delay(100); my_device = micronucleus_connect(fast_mode); time(&current_time); if (timeout && start_time + timeout < current_time) { break; } } if (my_device == NULL) { printf("> Device search timed out\n"); return EXIT_FAILURE; } printf("> Device is found!\n"); if (!fast_mode) { // wait for CONNECT_WAIT milliseconds with progress output float wait = 0.0f; setProgressData("connecting", 2); while (wait < CONNECT_WAIT) { printProgress((wait / ((float) CONNECT_WAIT)) * 0.9f); wait += 50.0f; delay(50); } } printProgress(1.0); printf("> Device has firmware version %d.%d\n",my_device->version.major,my_device->version.minor); if (my_device->signature1) printf("> Device signature: 0x1e%02x%02x \n",(int)my_device->signature1,(int)my_device->signature2); printf("> Available space for user applications: %d bytes\n", my_device->flash_size); printf("> Suggested sleep time between sending pages: %ums\n", my_device->write_sleep); printf("> Whole page count: %d page size: %d\n", my_device->pages,my_device->page_size); printf("> Erase function sleep duration: %dms\n", my_device->erase_sleep); int startAddress = 1, endAddress = 0; if (!erase_only) { setProgressData("parsing", 3); printProgress(0.0); memset(dataBuffer, 0xFF, sizeof(dataBuffer)); if (file_type == FILE_TYPE_INTEL_HEX) { if (parseIntelHex(file, dataBuffer, &startAddress, &endAddress)) { printf("> Error loading or parsing hex file.\n"); return EXIT_FAILURE; } } else if (file_type == FILE_TYPE_RAW) { if (parseRaw(file, dataBuffer, &startAddress, &endAddress)) { printf("> Error loading raw file.\n"); return EXIT_FAILURE; } } printProgress(1.0); if (startAddress >= endAddress) { printf("> No data in input file, exiting.\n"); return EXIT_FAILURE; } if (endAddress > my_device->flash_size) { printf("> Program file is %d bytes too big for the bootloader!\n", endAddress - my_device->flash_size); return EXIT_FAILURE; } } printProgress(1.0); setProgressData("erasing", 4); printf("> Erasing the memory ...\n"); res = micronucleus_eraseFlash(my_device, printProgress); if (res == 1) { // erase disconnection bug workaround printf(">> Eep! Connection to device lost during erase! Not to worry\n"); printf(">> This happens on some computers - reconnecting...\n"); my_device = NULL; delay(CONNECT_WAIT); int deciseconds_till_reconnect_notice = 50; // notice after 5 seconds while (my_device == NULL) { delay(100); my_device = micronucleus_connect(fast_mode); deciseconds_till_reconnect_notice -= 1; if (deciseconds_till_reconnect_notice == 0) { printf(">> (!) Automatic reconnection not working. Unplug and reconnect\n"); printf(" device usb connector, or reset it some other way to continue.\n"); } } printf(">> Reconnected! Continuing upload sequence...\n"); } else if (res != 0) { printf(">> Flash erase error %d has occured ...\n", res); printf(">> Please unplug the device and restart the program.\n"); return EXIT_FAILURE; } printProgress(1.0); if (!erase_only) { printf("> Starting to upload ...\n"); setProgressData("writing", 5); res = micronucleus_writeFlash(my_device, endAddress, dataBuffer, printProgress); if (res != 0) { printf(">> Flash write error %d has occured ...\n", res); printf(">> Please unplug the device and restart the program.\n"); return EXIT_FAILURE; } } if (run) { printf("> Starting the user app ...\n"); setProgressData("running", 6); printProgress(0.0); res = micronucleus_startApp(my_device); if (res != 0) { printf(">> Run error %d has occured ...\n", res); printf(">> Please unplug the device and restart the program. \n"); return EXIT_FAILURE; } printProgress(1.0); } printf(">> Micronucleus done. Thank you!\n"); return EXIT_SUCCESS; } /******************************************************************************/ /******************************************************************************/ static void printProgress(float progress) { static int last_step; static int last_integer_total_progress; if (dump_progress) { printf("{status:\"%s\",step:%d,steps:%d,progress:%f}\n", progress_friendly_name, progress_step, progress_total_steps, progress); } else { if (last_step == progress_step && use_ansi) { #ifndef WIN printf("\033[1F\033[2K"); // move cursor to previous line and erase last update in this progress sequence #else printf("\r"); // return carriage to start of line so we can type over existing text #endif } float total_progress = ((float) progress_step - 1.0f) / (float) progress_total_steps; total_progress += progress / (float) progress_total_steps; int integer_total_progress = total_progress * 100.0f; if (use_ansi || integer_total_progress >= last_integer_total_progress + 5) { printf("%s: %d%% complete\n", progress_friendly_name, integer_total_progress); last_integer_total_progress = integer_total_progress; } } last_step = progress_step; } static void setProgressData(char* friendly, int step) { progress_friendly_name = friendly; progress_step = step; } /******************************************************************************/ /******************************************************************************/ static int parseUntilColon(FILE *file_pointer) { int character; do { character = getc(file_pointer); } while(character != ':' && character != EOF); return character; } /******************************************************************************/ /******************************************************************************/ static int parseHex(FILE *file_pointer, int num_digits) { int iter; char temp[9]; for(iter = 0; iter < num_digits; iter++) { temp[iter] = getc(file_pointer); } temp[iter] = 0; return strtol(temp, NULL, 16); } /******************************************************************************/ /******************************************************************************/ static int parseIntelHex(char *hexfile, unsigned char *buffer, int *startAddr, int *endAddr) { int address, base, d, segment, i, lineLen, sum; FILE *input; input = strcmp(hexfile, "-") == 0 ? stdin : fopen(hexfile, "r"); if (input == NULL) { printf("> Error opening %s: %s\n", hexfile, strerror(errno)); return 1; } while (parseUntilColon(input) == ':') { sum = 0; sum += lineLen = parseHex(input, 2); base = address = parseHex(input, 4); sum += address >> 8; sum += address; sum += segment = parseHex(input, 2); /* segment value? */ if (segment != 0) { /* ignore lines where this byte is not 0 */ continue; } for (i = 0; i < lineLen; i++) { d = parseHex(input, 2); buffer[address++] = d; sum += d; } sum += parseHex(input, 2); if ((sum & 0xff) != 0) { printf("> Warning: Checksum error between address 0x%x and 0x%x\n", base, address); } if(*startAddr > base) { *startAddr = base; } if(*endAddr < address) { *endAddr = address; } } fclose(input); return 0; } /******************************************************************************/ /******************************************************************************/ static int parseRaw(char *filename, unsigned char *data_buffer, int *start_address, int *end_address) { FILE *input; input = strcmp(filename, "-") == 0 ? stdin : fopen(filename, "r"); if (input == NULL) { printf("> Error reading %s: %s\n", filename, strerror(errno)); return 1; } *start_address = 0; *end_address = 0; // read in bytes from file int byte = 0; while (1) { byte = getc(input); if (byte == EOF) break; *data_buffer = byte; data_buffer += 1; *end_address += 1; } fclose(input); return 0; } /******************************************************************************/
35.373853
168
0.576801
292704baf6a3ed0539bf43a797e06c35fd820d4e
13,138
c
C
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-F90/sidl_opaque_fStub.c
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
75
2015-07-06T18:14:20.000Z
2022-01-24T02:54:32.000Z
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-F90/sidl_opaque_fStub.c
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
15
2017-04-07T18:09:58.000Z
2022-02-28T01:48:33.000Z
linux_packages/source/hypre-2.9.0b/src/babel/bHYPREClient-F90/sidl_opaque_fStub.c
pangkeji/warp3d
8b273b337e557f734298940a63291697cd561d02
[ "NCSA" ]
41
2015-05-24T23:24:54.000Z
2021-12-13T22:07:45.000Z
/********************************************************************* * File: sidl_opaque_fStub.c * Copyright: (C) 2001-2004 The Regents of the University of California * Description: FORTRAN API for arrays of opaque * Revision: $Revision: 1.1 $ * * AUTOMATICALLY GENERATED BY genfortranarrays.py **********************************************************************/ #include "sidl_header.h" #ifndef included_babel_config_h #include "babel_config.h" #endif #include "sidlfortran.h" #ifndef included_sidlType_h #include "sidlType.h" #endif #ifndef included_sidlArray_h #include "sidlArray.h" #endif #ifndef FORTRAN90_DISABLED #include "sidlf90array.h" #endif #include <stdlib.h> #include <stddef.h> #ifndef FORTRAN90_DISABLED /*---------------------------------------------------------------------* * Fortran 90 Array Routines *---------------------------------------------------------------------*/ #include "sidl_opaque_fAbbrev.h" void SIDLFortran90Symbol(sidl_opaque__array_createcol_m, SIDL_OPAQUE__ARRAY_CREATECOL_M, sidl_opaque__array_createCol_m) (int32_t *dimen, int32_t lower[], int32_t upper[], int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_createCol(*dimen, lower, upper); } void SIDLFortran90Symbol(sidl_opaque__array_createrow_m, SIDL_OPAQUE__ARRAY_CREATEROW_M, sidl_opaque__array_createRow_m) (int32_t *dimen, int32_t lower[], int32_t upper[], int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_createRow(*dimen, lower, upper); } void SIDLFortran90Symbol(sidl_opaque__array_create1d_m, SIDL_OPAQUE__ARRAY_CREATE1D_M, sidl_opaque__array_create1d_m) (int32_t *len, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_create1d(*len); } void SIDLFortran90Symbol(sidl_opaque__array_create2drow_m, SIDL_OPAQUE__ARRAY_CREATE2DROW_M, sidl_opaque__array_create2dRow_m) (int32_t *m, int32_t *n, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_create2dRow(*m, *n); } void SIDLFortran90Symbol(sidl_opaque__array_create2dcol_m, SIDL_OPAQUE__ARRAY_CREATE2DCOL_M, sidl_opaque__array_create2dCol_m) (int32_t *m, int32_t *n, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_create2dCol(*m, *n); } void SIDLFortran90Symbol(sidl_opaque__array_ensure_m, SIDL_OPAQUE__ARRAY_ENSURE_M, sidl_opaque__array_ensure_m) (int64_t *src, int32_t *dimen, int32_t *ordering, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_ensure((struct sidl_opaque__array*)(ptrdiff_t)*src, *dimen, (int)*ordering); } void SIDLFortran90Symbol(sidl_opaque__array_smartcopy_m, SIDL_OPAQUE__ARRAY_SMARTCOPY_M, sidl_opaque__array_smartCopy_m) (int64_t *src, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_smartCopy((struct sidl_opaque__array*)(ptrdiff_t)*src); } void SIDLFortran90Symbol(sidl_opaque__array_slice_m, SIDL_OPAQUE__ARRAY_SLICE_M, sidl_opaque__array_slice_m) (int64_t *src, int32_t *dimen, int32_t numElem[], int32_t srcStart[], int32_t srcStride[], int32_t newStart[], int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_slice((struct sidl_opaque__array *)(ptrdiff_t)*src, *dimen, numElem, srcStart, srcStride, newStart); } void SIDLFortran90Symbol(sidl_opaque__array_cast_m, SIDL_OPAQUE__ARRAY_CAST_M, sidl_opaque__array_cast_m) (int64_t *array, int32_t *dimen, int64_t *result) { struct sidl_opaque__array *tmp = sidl_opaque__array_cast((struct sidl__array *)(ptrdiff_t)*array); *result = ((tmp && (sidlArrayDim(tmp) == *dimen)) ? (ptrdiff_t)tmp : 0); } void SIDLFortran90Symbol(sidl_opaque__array_copy_m, SIDL_OPAQUE__ARRAY_COPY_M, sidl_opaque__array_copy_m) (int64_t *src, int64_t *dest) { sidl_opaque__array_copy((struct sidl_opaque__array*)(ptrdiff_t)*src, (struct sidl_opaque__array*)(ptrdiff_t)*dest); } void SIDLFortran90Symbol(sidl_opaque__array_iscolumnorder_m, SIDL_OPAQUE__ARRAY_ISCOLUMNORDER_M, sidl_opaque__array_isColumnOrder_m) (int64_t *array, sidl_bool *result) { *result = ( sidl_opaque__array_isColumnOrder((struct sidl_opaque__array *)(ptrdiff_t)*array) ? SIDL_F90_TRUE : SIDL_F90_FALSE); } void SIDLFortran90Symbol(sidl_opaque__array_isroworder_m, SIDL_OPAQUE__ARRAY_ISROWORDER_M, sidl_opaque__array_isRowOrder_m) (int64_t *array, sidl_bool *result) { *result = ( sidl_opaque__array_isRowOrder((struct sidl_opaque__array *)(ptrdiff_t)*array) ? SIDL_F90_TRUE : SIDL_F90_FALSE); } void SIDLFortran90Symbol(sidl_opaque__array_dimen_m, SIDL_OPAQUE__ARRAY_DIMEN_M, sidl_opaque__array_dimen_m) (int64_t *array, int32_t *result) { *result = sidl_opaque__array_dimen((struct sidl_opaque__array *)(ptrdiff_t)*array); } void SIDLFortran90Symbol(sidl_opaque__array_stride_m, SIDL_OPAQUE__ARRAY_STRIDE_M, sidl_opaque__array_stride_m) (int64_t *array, int32_t *index, int32_t *result) { *result = sidl_opaque__array_stride((struct sidl_opaque__array *)(ptrdiff_t)*array, *index); } void SIDLFortran90Symbol(sidl_opaque__array_lower_m, SIDL_OPAQUE__ARRAY_LOWER_M, sidl_opaque__array_lower_m) (int64_t *array, int32_t*ind, int32_t *result) { *result = sidl_opaque__array_lower((struct sidl_opaque__array *)(ptrdiff_t)*array, *ind); } void SIDLFortran90Symbol(sidl_opaque__array_upper_m, SIDL_OPAQUE__ARRAY_UPPER_M, sidl_opaque__array_upper_m) (int64_t *array, int32_t *ind, int32_t *result) { *result = sidl_opaque__array_upper((struct sidl_opaque__array *)(ptrdiff_t)*array, *ind); } void SIDLFortran90Symbol(sidl_opaque__array_length_m, SIDL_OPAQUE__ARRAY_LENGTH_M, sidl_opaque__array_length_m) (int64_t *array, int32_t *ind, int32_t *result) { *result = sidl_opaque__array_length((struct sidl_opaque__array *)(ptrdiff_t)*array, *ind); } void SIDLFortran90Symbol(sidl_opaque__array_deleteref_m, SIDL_OPAQUE__ARRAY_DELETEREF_M, sidl_opaque__array_deleteRef_m) (int64_t *array) { sidl_opaque__array_deleteRef((struct sidl_opaque__array*)(ptrdiff_t)*array); } void SIDLFortran90Symbol(sidl_opaque__array_addref_m, SIDL_OPAQUE__ARRAY_ADDREF_M, sidl_opaque__array_addRef_m) (int64_t *array) { sidl_opaque__array_addRef((struct sidl_opaque__array*)(ptrdiff_t)*array); } void SIDLFortran90Symbol(sidl_opaque__array_get1_m, SIDL_OPAQUE__ARRAY_GET1_M, sidl_opaque__array_get1_m) (int64_t *array, int32_t *i1, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get1((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1); } void SIDLFortran90Symbol(sidl_opaque__array_set1_m, SIDL_OPAQUE__ARRAY_SET1_M, sidl_opaque__array_set1_m) (int64_t *array, int32_t *i1, int64_t *value) { sidl_opaque__array_set1((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get2_m, SIDL_OPAQUE__ARRAY_GET2_M, sidl_opaque__array_get2_m) (int64_t *array, int32_t *i1, int32_t *i2, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get2((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2); } void SIDLFortran90Symbol(sidl_opaque__array_set2_m, SIDL_OPAQUE__ARRAY_SET2_M, sidl_opaque__array_set2_m) (int64_t *array, int32_t *i1, int32_t *i2, int64_t *value) { sidl_opaque__array_set2((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get3_m, SIDL_OPAQUE__ARRAY_GET3_M, sidl_opaque__array_get3_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get3((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3); } void SIDLFortran90Symbol(sidl_opaque__array_set3_m, SIDL_OPAQUE__ARRAY_SET3_M, sidl_opaque__array_set3_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int64_t *value) { sidl_opaque__array_set3((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get4_m, SIDL_OPAQUE__ARRAY_GET4_M, sidl_opaque__array_get4_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get4((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4); } void SIDLFortran90Symbol(sidl_opaque__array_set4_m, SIDL_OPAQUE__ARRAY_SET4_M, sidl_opaque__array_set4_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int64_t *value) { sidl_opaque__array_set4((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get5_m, SIDL_OPAQUE__ARRAY_GET5_M, sidl_opaque__array_get5_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get5((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5); } void SIDLFortran90Symbol(sidl_opaque__array_set5_m, SIDL_OPAQUE__ARRAY_SET5_M, sidl_opaque__array_set5_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int64_t *value) { sidl_opaque__array_set5((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get6_m, SIDL_OPAQUE__ARRAY_GET6_M, sidl_opaque__array_get6_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int32_t *i6, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get6((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5, *i6); } void SIDLFortran90Symbol(sidl_opaque__array_set6_m, SIDL_OPAQUE__ARRAY_SET6_M, sidl_opaque__array_set6_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int32_t *i6, int64_t *value) { sidl_opaque__array_set6((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5, *i6, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_get7_m, SIDL_OPAQUE__ARRAY_GET7_M, sidl_opaque__array_get7_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int32_t *i6, int32_t *i7, int64_t *result) { *result = (ptrdiff_t) sidl_opaque__array_get7((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5, *i6, *i7); } void SIDLFortran90Symbol(sidl_opaque__array_set7_m, SIDL_OPAQUE__ARRAY_SET7_M, sidl_opaque__array_set7_m) (int64_t *array, int32_t *i1, int32_t *i2, int32_t *i3, int32_t *i4, int32_t *i5, int32_t *i6, int32_t *i7, int64_t *value) { sidl_opaque__array_set7((struct sidl_opaque__array *)(ptrdiff_t)*array, *i1, *i2, *i3, *i4, *i5, *i6, *i7, (void *)(ptrdiff_t)*value); } void SIDLFortran90Symbol(sidl_opaque__array_set_m, SIDL_OPAQUE__ARRAY_SET_M, sidl_opaque__array_set_m) (int64_t *array, int32_t indices[], int64_t *value) { sidl_opaque__array_set((struct sidl_opaque__array *)(ptrdiff_t)*array, indices, (void *)(ptrdiff_t) *value); } void SIDLFortran90Symbol(sidl_opaque__array_get_m, SIDL_OPAQUE__ARRAY_GET_M, sidl_opaque__array_get_m) (int64_t *array, int32_t indices[], int64_t *value) { *value = (ptrdiff_t) sidl_opaque__array_get((struct sidl_opaque__array *)(ptrdiff_t)*array, indices); } #endif /* not FORTRAN90_DISABLED */
24.602996
110
0.649794
5db94ff9e2d183fcbdd592522e659ba5d3969b1a
3,529
c
C
src/b6b_evloop.c
dimkr/b6b
ee12b6fa2c7a39c9f30f80470d5258e4bf8810f5
[ "Apache-2.0" ]
10
2017-07-07T18:20:49.000Z
2021-01-09T19:40:25.000Z
src/b6b_evloop.c
dimkr/b6b
ee12b6fa2c7a39c9f30f80470d5258e4bf8810f5
[ "Apache-2.0" ]
4
2018-09-09T19:03:20.000Z
2020-10-01T03:52:54.000Z
src/b6b_evloop.c
dimkr/b6b
ee12b6fa2c7a39c9f30f80470d5258e4bf8810f5
[ "Apache-2.0" ]
3
2018-01-29T18:28:39.000Z
2020-10-01T03:28:31.000Z
/* * This file is part of b6b. * * Copyright 2017, 2018 Dima Krasner * * 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 <b6b.h> #define B6B_EVLOOP_REMOVE \ "{$try {" \ "{$local fd [$2 fd]}\n" \ "{[$list.index $. 0] remove $fd}\n" \ "{$map d [$list.range $. 1 5] {" \ "{$dict.unset $d $fd}" \ "}}" \ "} {} {" \ "{$2 close}" \ "}}" #define B6B_EVLOOP_ADD \ "{$local fd [$2 fd]}\n" \ "{$dict.set [$list.index $. 1] $fd $2}\n" \ "{$dict.set [$list.index $. 2] $fd $3}\n" \ "{$dict.set [$list.index $. 3] $fd $4}\n" \ "{$dict.set [$list.index $. 4] $fd $5}\n" \ "{$if [$&& $3 $4] {" \ "{[$list.index $. 0] add $fd $POLLINOUT}" \ "} {" \ "{$if $3 {" \ "{[$list.index $. 0] add $fd $POLLIN}" \ "} {" \ "{[$list.index $. 0] add $fd $POLLOUT}" \ "}}" \ "}}" #define B6B_EVLOOP_UPDATE \ "{[$list.index $. 0] remove [$2 fd]}\n" \ "{$0 add $2 $3 $4 $5}" #define B6B_EVLOOP_AFTER \ "{$0 add [$timer $2] [$proc _ {" \ "{$call $.}\n" \ "{$throw}" \ "} [$list.new [$list.new $3]]] {} {}}" #define B6B_EVLOOP_EVERY \ "{$0 add [$timer $2] [$proc _ {" \ "{$1 read}\n" \ "{$call $.}" \ "} [$list.new [$list.new $3]]] {} {}}" #define B6B_EVLOOP_WAIT \ "{$loop {" \ "{$map {p strms inps outps errps} $. {" \ "{$local n [$list.len $strms]}\n" \ "{$if [$== $n 0] {" \ "{$return}" \ "}}\n" \ "{$map {rfds wfds efds} [$p wait [$* $n 1.5] $2] {" \ "{$map fd $efds {" \ "{$local strm [$dict.get $strms $fd {}]}\n" \ "{$if $strm {" \ "{$try {" \ "{[$dict.get $errps $fd] $strm}" \ "} {} {" \ "{$0 remove $strm}" \ "}}" \ "}}" \ "}}\n" \ "{$map fd $wfds {" \ "{$local strm [$dict.get $strms $fd {}]}\n" \ "{$if $strm {" \ "{$try {" \ "{[$dict.get $outps $fd] $strm}" \ "} {" \ "{$0 remove $strm}" \ "}}" \ "}}" \ "}}\n" \ "{$map fd $rfds {" \ "{$local strm [$dict.get $strms $fd {}]}\n" \ "{$if $strm {" \ "{$try {" \ "{[$dict.get $inps $fd] $strm}" \ "} {" \ "{$0 remove $strm}" \ "}}" \ "}}" \ "}}" \ "}}" \ "}}" \ "}}" #define B6B_EVLOOP_BODY \ "{$proc evloop {" \ "{$proc _ {" \ "{$if [$== $1 remove] {" \ B6B_EVLOOP_REMOVE \ "} {" \ "{$if [$== $1 add] {" \ B6B_EVLOOP_ADD \ "} {" \ "{$if [$== $1 update] {" \ B6B_EVLOOP_UPDATE \ "} {" \ "{$if [$== $1 after] {" \ B6B_EVLOOP_AFTER \ "} {" \ "{$if [$== $1 every] {" \ B6B_EVLOOP_EVERY \ "} {" \ "{$if [$== $1 wait] {" \ B6B_EVLOOP_WAIT \ "} {" \ "{$throw {bad evloop op}}" \ "}}" \ "}}" \ "}}" \ "}}" \ "}}" \ "}}" \ "} [$list.new [$poll] {} {} {} {}]}" \ "}}" static int b6b_evloop_init(struct b6b_interp *interp) { return b6b_call_copy(interp, B6B_EVLOOP_BODY, sizeof(B6B_EVLOOP_BODY) - 1) == B6B_OK; } __b6b_init(b6b_evloop_init);
24.506944
75
0.449702
51b827d990b6364344988d7f2deac5ed01a6e591
332
h
C
src/UIState/SeeVersion.h
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
1
2021-07-14T15:16:04.000Z
2021-07-14T15:16:04.000Z
src/UIState/SeeVersion.h
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
1
2021-05-10T05:41:39.000Z
2021-05-10T05:41:39.000Z
src/UIState/SeeVersion.h
IDzyre/TankController
60ccdd6d4023be7a0e0155b508e8b067603bf8b2
[ "MIT" ]
null
null
null
/** * SeeVersion.h * * Display the tankController Version */ #pragma once #include "UIState.h" class SeeVersion : public UIState { public: SeeVersion(TankControllerLib* tc) : UIState(tc) { } void start(); const char* name() { return "SeeVersion"; } const char* prompt() { return "Software Version"; }; };
15.809524
51
0.641566
8e03634b6aed9348b656c88f0e9f1b7abff816b9
164
c
C
0x04-more_functions_nested_loops/1-isdigit.c
adeyinkaezra123/alx-low_level_programming
7980b72cc1df70b00be0a56ad2e3612cb8aef4e2
[ "MIT" ]
null
null
null
0x04-more_functions_nested_loops/1-isdigit.c
adeyinkaezra123/alx-low_level_programming
7980b72cc1df70b00be0a56ad2e3612cb8aef4e2
[ "MIT" ]
null
null
null
0x04-more_functions_nested_loops/1-isdigit.c
adeyinkaezra123/alx-low_level_programming
7980b72cc1df70b00be0a56ad2e3612cb8aef4e2
[ "MIT" ]
null
null
null
#include "holberton.h" /** * _isdigit - check for a digit * @c : character to check * Return:0 or 1 */ int _isdigit(int c) { return (c >= 48 && c <= 57); }
11.714286
31
0.567073
99cf4b96b2bc67402f74cb42f9e337638eb7dba1
3,879
h
C
PR_BCI_team/Team_RobotArm/BHLee/Kinovarobotics-matlab_Kinovaapi_wrapper-e51b887/JACO2Communicator/JACO2SDK/JacoSDKWrapper.h
PatternRecognition/OpenBMI
d9291ddb81f4319fb3764d7192e0363939a62ee9
[ "MIT" ]
217
2015-11-02T11:10:29.000Z
2022-03-22T07:01:12.000Z
PR_BCI_team/Team_RobotArm/BHLee/Kinovarobotics-matlab_Kinovaapi_wrapper-e51b887/JACO2Communicator/JACO2SDK/JacoSDKWrapper.h
deep-bci-g/OpenBMI
75daf901b2dbe215852cbff243606dcfcd10f05c
[ "MIT" ]
24
2015-11-02T11:10:45.000Z
2021-09-08T11:10:33.000Z
PR_BCI_team/Team_RobotArm/BHLee/Kinovarobotics-matlab_Kinovaapi_wrapper-e51b887/JACO2Communicator/JACO2SDK/JacoSDKWrapper.h
deep-bci-g/OpenBMI
75daf901b2dbe215852cbff243606dcfcd10f05c
[ "MIT" ]
112
2016-01-22T01:45:44.000Z
2022-03-22T07:08:19.000Z
#ifndef JACO_SDK_WRAPPER_H_ #define JACO_SDK_WRAPPER_H_ #include <Windows.h> #include "CommunicationLayerWindows.h" #include "CommandLayer.h" #include <conio.h> #include "KinovaTypes.h" #include <iostream> #define NUM_JOINTS 7 #define NUM_FINGERS 3 #define JACO_SDK_WRAPPER_TINY_NUMBER 0.00001 #define JACO_SDK_WRAPPER_PI 3.14159265358979323846f const float kDeg2rad = JACO_SDK_WRAPPER_PI / 180.0f; const float kRad2deg = 180.0f/JACO_SDK_WRAPPER_PI; enum class FunctionIndices { kOpenLibrary = 0, kCloseLibrary = 1, kGetJointsPosition = 2, kGetJointsVelocity = 3, kGetJointsTorque = 4, kGetJointsTemperature = 5, kGetEndEffectorPose = 6, kGetEndEffectorWrench = 7, kMoveToHomePosition = 8, kSetPositionControlMode = 9, kSetDirectTorqueControlMode = 10, kRunGravityCalibration = 11, kInitializeFingers = 12, kSendJointPositions = 13, kSendJointAndFingerPositions = 14, kSendJointVelocities = 15, kSendJointTorques = 16, kSendFingerPositions = 17, kSendCartesianPositions = 18, kSendCartesianVelocity = 19, kGetDOF = 20, kStartForceControl = 21, kStopForceControl = 22, kGetEndEffectorOffset = 23, kSetEndEffectorOffset = 24, kGetProtectionZone = 25, kEraseProtectionZones = 26, kSetProtectionZone = 27, kGetGlobalTrajectoryInfo = 28, }; /* Load library */ extern "C" bool openKinovaLibrary(); /* Close library */ extern "C" bool closeKinovaLibrary(); /* Get joints position in rad */ extern "C" bool getJointsPosition(double *pos); /* Get joints velocity in rad/s */ extern "C" bool getJointsVelocity(double *vel); /* Get joints torque in N*m */ extern "C" bool getJointsTorque(double *torque); /* Get actuator temperature in C */ extern "C" bool getJointsTemperature(double *temp); /* Get end effector pose [px py pz ex ey ez] */ /* The orientation is defined by Euler angles (convention XYZ) */ extern "C" bool getEndEffectorPose(double *pose); /* Get end effector wrench [fx fy fz tx ty tz] */ extern "C" bool getEndEffectorWrench(double *wrench); /* Send robot to home position */ extern "C" bool moveToHomePosition(void); /* Set position control mode */ extern "C" bool setPositionControlMode(void); /* Set torque control mode */ extern "C" bool setDirectTorqueControlMode(void); /* Do gravity calibration sequence, be sure to have 1.5 meters of free space*/ extern "C" bool runGravityCalibration(void); /* Initialize gripper */ extern "C" bool initializeFingers(void); /* Send Joint positions in [rad] */ extern "C" bool sendJointPositions(double *pos); /* Send joint and finger positions (fingers in [rad]) */ extern "C" bool sendJointAndFingerPositions(double *jpos, double *fpos); /* Send joint velocities in [rad/s]*/ extern "C" bool sendJointVelocities(double *vel); /* Send joint torques*/ extern "C" bool sendJointTorques(double *torque); /* Send finger positions*/ extern "C" bool sendFingerPositions(double *pos); /* Send cartesian positions*/ extern "C" bool sendCartesianPositions(double *pos); /* Send cartesian velocity*/ extern "C" bool sendCartesianVelocity(double *vel); /* Get number of Degree Of Freedom */ extern "C" bool GetDOF (double *DOF); /* Start Admitance mode */ extern "C" bool startForceControl(); /* Stop Admitance mode*/ extern "C" bool stopForceControl(); /* Get end effector offset */ extern "C" bool getEndEffectorOffset(double *offset); /* Set end effector offset */ extern "C" bool setEndEffectorOffset(double *offset); /* Get number of protection zones */ extern "C" bool getProtectionZone(double *zone); /* Delete all protection zones */ extern "C" bool eraseAllProtectionZones(); /* GAdd and set a new protection zone */ extern "C" bool setProtectionZone(double *zone); /* Get FIFO informations */ extern "C" bool getGlobalTrajectoryInfo(double *info); #endif
26.209459
78
0.728023
6607c0482c8b1c706eb231edc65303f33b9e79a3
1,132
h
C
vkCraft/vkCraft/Device.h
tentone/vkCraft
01c329e35d043c9fa828e21f70afb805a78d46c4
[ "MIT" ]
39
2018-10-07T15:44:02.000Z
2022-01-14T22:09:28.000Z
vkCraft/vkCraft/Device.h
tentone/vkCraft
01c329e35d043c9fa828e21f70afb805a78d46c4
[ "MIT" ]
null
null
null
vkCraft/vkCraft/Device.h
tentone/vkCraft
01c329e35d043c9fa828e21f70afb805a78d46c4
[ "MIT" ]
3
2020-11-03T15:21:05.000Z
2021-12-19T15:56:39.000Z
#pragma once #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <stdexcept> #include <vector> #include <iostream> #include "QueueFamilyIndices.h" /** * The device class handles everything related with logical and physical device configuration. */ class Device { public: /** * The physical device is mostly used to check for the GPU hardware capabilities. */ VkPhysicalDevice physical = VK_NULL_HANDLE; /** * The logical device is used to execute all the vulkan operations. */ VkDevice logical = VK_NULL_HANDLE; Device(); Device(VkPhysicalDevice _physical); Device(VkPhysicalDevice _physical, VkDevice _logical); /** * Dispose device and all the buffers, pools associated with it. */ void dispose(); /** * Check which queue families are supported by the physical device. * * We only need it to support graphics rendering to a surface. */ QueueFamilyIndices getQueueFamilyIndices(VkSurfaceKHR surface); /** * Find a proper memory type for data defined by the memory properties specified. */ uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties); };
22.196078
94
0.745583
19f080d88565481f8be9127b8342b70e99733d24
2,666
c
C
test/zmq_client.c
ouistiti-project/jsonrpc
c486962ca80c9f30d773b26bf18cafca4426cddb
[ "MIT" ]
null
null
null
test/zmq_client.c
ouistiti-project/jsonrpc
c486962ca80c9f30d773b26bf18cafca4426cddb
[ "MIT" ]
null
null
null
test/zmq_client.c
ouistiti-project/jsonrpc
c486962ca80c9f30d773b26bf18cafca4426cddb
[ "MIT" ]
null
null
null
#include <unistd.h> #include <string.h> #include <pthread.h> #include <assert.h> #include <zmq.h> #include "jsonrpc.h" #include "test.h" void wait_msg(struct user_context_t *userctx) { unsigned int rc; zmq_msg_t msg; zmq_msg_init(&msg); rc = zmq_msg_recv(&msg, userctx->sock, 0); char *output = jsonrpc_handler((char *)zmq_msg_data(&msg), zmq_msg_size(&msg), method_table, (char *)userctx); if (output != NULL) { printf("error: %s\n", output); free(output); } zmq_msg_close(&msg); } void *_thread(void *arg) { int run = 1; struct user_context_t *userctx = (struct user_context_t *)arg; while (run) { wait_msg(userctx); } return NULL; } int start_event(struct user_context_t * userctx) { pthread_t pthread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&pthread, &attr, _thread, userctx); pthread_detach(pthread); return 0; } int treatmsg(struct user_context_t *userctx, char *request) { int rc; rc = zmq_send(userctx->sock, request, strlen(request), 0); wait_msg(userctx); return rc; } typedef int (*treatmsg_t)(struct user_context_t *userctx, char *request); int client_loop(treatmsg_t treatmsg, struct user_context_t *userctx) { int ret; while (1) { fd_set rfds; int maxfd = 0; FD_ZERO(&rfds); FD_SET(0, &rfds); ret = select(maxfd + 1, &rfds, NULL, NULL, NULL); if (ret > 0) { if (FD_ISSET(0, &rfds)) { char buff[256]; ret = read(0, buff, sizeof(buff)); if (ret > 0) { char *request = NULL; json_t *params = NULL; unsigned long id; buff[ret] = 0; if (buff[ret-1] = '\n') buff[ret-1] = 0; if (!strncmp(buff, "quit", 4)) { break; } request = jsonrpc_request(buff, strlen(buff), method_table, (char *)userctx, &id); if (request != NULL) { treatmsg(userctx, request); free(request); request = NULL; } } } } } return ret; } json_t *client_error_handler(json_t *json_id, json_t *json_error) { json_t *data = json_object_get(json_error, "data"); if (json_is_string(data)) printf("error :%s\n", json_string_value(data)); return NULL; } int main() { void *ctx = zmq_ctx_new(); void *sock = zmq_socket(ctx, ZMQ_PAIR); int rc = zmq_connect(sock, "tcp://127.0.0.1:10000"); assert(rc!=-1); struct jsonrpc_method_entry_t *entry; for (entry=method_table; entry->name!=NULL; entry++) { if (entry->type == 'a') { printf("try: %s\n", entry->name); } } struct user_context_t userctx = {.count = 0, .sock = sock}; jsonrpc_set_errorhandler(client_error_handler); client_loop(treatmsg, &userctx); zmq_close(sock); zmq_ctx_destroy(ctx); return 0; }
19.318841
73
0.646287
616341a98b6fe8d50c64afc99fe6c3330417f636
211
h
C
WxxKit/WxxKitFrameWork/wxxiOSCode/view/WxxFileUtil.h
wengxianxun/WxxKit
582d1ae48baf1c4adde0eb27f678ce276780a87c
[ "MIT" ]
null
null
null
WxxKit/WxxKitFrameWork/wxxiOSCode/view/WxxFileUtil.h
wengxianxun/WxxKit
582d1ae48baf1c4adde0eb27f678ce276780a87c
[ "MIT" ]
null
null
null
WxxKit/WxxKitFrameWork/wxxiOSCode/view/WxxFileUtil.h
wengxianxun/WxxKit
582d1ae48baf1c4adde0eb27f678ce276780a87c
[ "MIT" ]
null
null
null
// // WxxFileUtil.h // WxxReadClient // // Created by weng xiangxun on 2017/4/3. // Copyright © 2017年 wxx. All rights reserved. // #import <Foundation/Foundation.h> @interface WxxFileUtil : NSObject @end
15.071429
47
0.691943
e832b5d0e80cfa870cd383949792bcafe9e77588
43
h
C
Algorithms/Threshold/Threshold_defaults.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/Threshold/Threshold_defaults.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
Algorithms/Threshold/Threshold_defaults.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
static const int kDefaultThreshold = 2400;
21.5
42
0.813953
e85b542d789851880d7071149c075f6f7aace90e
138
h
C
sdl/sensor.h
akiross/go-sdl2
5437d9fc5f28714259f2728ae28984eed52c23d9
[ "BSD-3-Clause" ]
null
null
null
sdl/sensor.h
akiross/go-sdl2
5437d9fc5f28714259f2728ae28984eed52c23d9
[ "BSD-3-Clause" ]
null
null
null
sdl/sensor.h
akiross/go-sdl2
5437d9fc5f28714259f2728ae28984eed52c23d9
[ "BSD-3-Clause" ]
null
null
null
#ifndef _GO_SDL_SENSOR_H #define _GO_SDL_SENSOR_H #if !SDL_VERSION_ATLEAST(2,0,9) extern const float SDL_STANDARD_GRAVITY; #endif #endif
17.25
40
0.826087
95fa6b9b167882e930b10652243142ca2db1f6b4
2,387
h
C
thread_version/space_comm.h
drjones2010/space-invaders
175fc3eee780803843612d2f8875b42ed969fe4b
[ "MIT" ]
2
2021-12-13T14:14:24.000Z
2021-12-23T17:23:57.000Z
thread_version/space_comm.h
drjones2010/space-invaders
175fc3eee780803843612d2f8875b42ed969fe4b
[ "MIT" ]
null
null
null
thread_version/space_comm.h
drjones2010/space-invaders
175fc3eee780803843612d2f8875b42ed969fe4b
[ "MIT" ]
null
null
null
/** Space Invaders: 8 bit attack! * * File: * * Contiene: */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <curses.h> #include <pthread.h> #ifndef SPACE_THREAD_H #define SPACE_THREAD_H #define COUNTER 0 #define WAIT 0 #define TRYWAIT 1 #define NOMSG 12345 #include "space_game.h" /*Funzioni*/ void insertBuffer(EntityParams[], int*, pthread_mutex_t*, sem_t*, EntityParams); EntityParams removeBuffer(EntityParams[], int*, pthread_mutex_t*, sem_t*, int); /*Variabili di comunicazione*/ pthread_t thread_starship; pthread_t thread_enemy[M]; pthread_mutex_t mutex_mainBuffer; //Mutex di ingresso nella sezione critica del buffer pthread_mutex_t mutex_starshipBuffer; pthread_mutex_t mutex_enemyBuffer[M]; pthread_mutex_t mutex_enemyTimerBuffer[M]; pthread_mutex_t mutex_entityList; //Mutex per leggere sulla entityList pthread_mutex_t mutex_curses; //Mutex per scrivere sullo schermo pthread_mutex_t mutex_fprintf; //Mutex per l'output su file sem_t semaphore_mainBuffer; //Semaphore che mette il consumatore del mainBuffer in attesa di riempimento sem_t semaphore_starshipBuffer; //Semaphore che mette il consumatore del starshipBuffer in attesa di riempimento sem_t semaphore_enemyBuffer[M]; //Semaphore che mette il consumatore del enemyBuffer[k] in attesa di riempimento sem_t semaphore_enemyTimerBuffer[M]; //Semaphore che mette il consumatore del enemyTimerBuffer[k] in attesa di riempimento int counter_mainBuffer; //Posizioni vuote rimanenti del mainBuffer int counter_starshipBuffer; //Posizioni vuote rimanenti dello starshipBuffer int counter_enemyBuffer[M]; //Posizioni vuote rimanenti del enemyBuffer[k] int counter_enemyTimerBuffer[M]; //Posizioni vuote rimanenti del enemyTimerBuffer[k] EntityParams mainBuffer[DIM_BUFFER]; //Buffer del mainLoop, alla posizione zero viene salvato il contatore EntityParams starshipBuffer[DIM_BUFFER]; //Buffer dell'astronave, alla posizione zero viene salvato il contatore EntityParams enemyBuffer[M][DIM_BUFFER]; //Buffer dei nemici, la prima dimensione identifica il numero di nemico e alla posizione zero della seconda dimensione viene salvato il contatore EntityParams enemyTimerBuffer[M][DIM_BUFFER]; //Buffer dei timer dei nemici, la prima dimensione identifica il numero di nemico e alla posizione zero della seconda dimensione viene salvato il contatore #endif
39.783333
201
0.802681
bf8e7ad8288bfca7a0b7b1da28514fd752313170
1,555
h
C
inc/drivers/system.h
rhn/PIC32-debug-tool
552392d2d1990d6804675e708dd83634d2c9a3fa
[ "Apache-2.0" ]
null
null
null
inc/drivers/system.h
rhn/PIC32-debug-tool
552392d2d1990d6804675e708dd83634d2c9a3fa
[ "Apache-2.0" ]
1
2020-03-31T13:37:26.000Z
2020-04-01T11:36:03.000Z
inc/drivers/system.h
rhn/PIC32-debug-tool
552392d2d1990d6804675e708dd83634d2c9a3fa
[ "Apache-2.0" ]
1
2020-04-01T11:44:46.000Z
2020-04-01T11:44:46.000Z
#ifndef SYSTEM_H_3215b7a61b384819b6127a53816114fe #define SYSTEM_H_3215b7a61b384819b6127a53816114fe #include <p32xxxx.h> #include <const.h> #include <inttypes.h> typedef enum SystemClocksErrorEnum { Error_None = 0, Error_RequestedFrequencyTooHigh = 1, Error_NoCombinationFound = 2, } SystemClocksError; typedef struct SystemClocksSettingsStruct { uint8_t PLLIDIV; uint8_t PLLODIV; uint8_t PLLMULT; uint8_t PBDIV; #ifdef EXTENDED_TEST_CASE // Error state SystemClocksError error; #endif } SystemClocksSettings; void SystemUnlock(); void SystemLock(); void SystemReset(); void SystemSleep(); void SystemIdle(); void SystemClocksReadSettings(SystemClocksSettings *s); uint32_t SystemClocksGetCpuFrequency(const SystemClocksSettings *s); uint32_t SystemClocksGetPeripheralFrequency(const SystemClocksSettings *s); void SystemClocksCalcCpuClockSettings(SystemClocksSettings *s, uint32_t cpuFrequency); void SystemClocksCalcPeripheralClockSettings(SystemClocksSettings *s, uint32_t peripheralFrequency); void SystemClocksWriteSettings(const SystemClocksSettings *s); uint32_t GetSystemClock(void); uint32_t GetPeripheralClock(); void SystemConfig(uint32_t cpuCoreFrequency, uint32_t peripheralFreqDiv); void SystemSetPeripheralClock(uint32_t peripheralFrequency); uint32_t MIPS32 GetCP0Count(); void MIPS32 SetCP0Count(uint32_t count); void MIPS32 INTEnableSystemMultiVectoredInt(void); #endif /* __SYSTEM_H_3215b7a6-1b38-4819-b612-7a53816114fe */
31.1
75
0.789068
c75760c0671ee96fa5c85685b47ff98c93547896
663
c
C
lib/Runtime/operator/squeeze.c
LiuLeif/onnc
3f69e46172a9c33cc04541ff7fd78d5d7b6bdbba
[ "BSD-3-Clause" ]
450
2018-08-03T08:17:03.000Z
2022-03-17T17:21:06.000Z
lib/Runtime/operator/squeeze.c
LiuLeif/onnc
3f69e46172a9c33cc04541ff7fd78d5d7b6bdbba
[ "BSD-3-Clause" ]
104
2018-08-13T07:31:50.000Z
2021-08-24T11:24:40.000Z
lib/Runtime/operator/squeeze.c
LiuLeif/onnc
3f69e46172a9c33cc04541ff7fd78d5d7b6bdbba
[ "BSD-3-Clause" ]
100
2018-08-12T04:27:39.000Z
2022-03-11T04:17:42.000Z
#include <onnc/Runtime/operator/squeeze.h> #include <stdint.h> #include <stdbool.h> void ONNC_RUNTIME_squeeze_float( void * restrict onnc_runtime_context ,const float * restrict input_data ,int32_t input_data_ndim, const int32_t * restrict input_data_dims ,float * restrict output_squeezed ,int32_t output_squeezed_ndim, const int32_t * restrict output_squeezed_dims ,int32_t * restrict axes ,int32_t number_of_axes ) { int32_t size_N = 1; // total counts of elements for(int32_t i = 0; i < input_data_ndim; ++i) { size_N *= input_data_dims[i]; } for(int32_t i = 0; i < size_N; ++i) { output_squeezed[i] = input_data[i]; } }
25.5
78
0.720965
2464f0b60a3494c211e7e982fd09ba71db23cbe8
333
h
C
astatine/notifications/notification/notificationview.h
blackaddah/astatine
2d591c0de77fce635385826dcdbd40074576d293
[ "MIT" ]
null
null
null
astatine/notifications/notification/notificationview.h
blackaddah/astatine
2d591c0de77fce635385826dcdbd40074576d293
[ "MIT" ]
null
null
null
astatine/notifications/notification/notificationview.h
blackaddah/astatine
2d591c0de77fce635385826dcdbd40074576d293
[ "MIT" ]
null
null
null
#ifndef NOTIFICATIONVIEW_H #define NOTIFICATIONVIEW_H #include <QWebView> #include <QMouseEvent> class NotificationView : public QWebView { Q_OBJECT public: NotificationView(NotificationView::QWidget *parent); void mousePressEvent(QMouseEvent *event); signals: void rightClick(); }; #endif // NOTIFICATIONVIEW_H
16.65
56
0.762763
a7e06323c56487795f8309f619e14304998a795b
2,680
h
C
com/ole32/olecnv32/error.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/olecnv32/error.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/olecnv32/error.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**************************************************************************** Unit Error; Interface ***************************************************************************** Error handles all the interpretation, metafile creation, or read failures that may occur during the course of the translation. Module Prefix: Er *****************************************************************************/ /********************* Exported Data ***************************************/ #define ErNoError NOERR #define ErInvalidVersion 1 /* file is not version 1 or 2 */ #define ErInvalidVersionID 2 /* PICT 2 version ID invalid */ #define ErBadHeaderSequence 3 /* PICT 2 HeaderOp not found */ #define ErInvalidPrefsHeader 4 /* Preferences header invalid */ #define ErNoSourceFormat 5 /* no source filename/handle given */ #define ErMemoryFull 10 /* GlobalAlloc() fail */ #define ErMemoryFail 11 /* GlobalLock() fail */ #define ErCreateMetafileFail 12 /* CreateMetafile() fail */ #define ErCloseMetafileFail 13 /* CloseMetafile() fail */ #define ErEmptyPicture 20 /* no primitives found in file */ #define ErNullBoundingRect 30 /* BBox defines NULL area */ #define Er32KBoundingRect 31 /* BBox extents exceed 32K */ #define ErReadPastEOF 40 /* Attempt to read past end of file */ #define ErOpenFail 41 /* OpenFile() failed */ #define ErReadFail 42 /* read from disk failed */ #define ErNonSquarePen 50 /* non-square pen & user pref abort */ #define ErPatternedPen 51 /* patterned pen & user pref abort */ #define ErInvalidXferMode 52 /* invalid transfer mode & abort */ #define ErNonRectRegion 53 /* non-rectangular region abort */ #define ErNoDialogBox 60 /* unable to run status dialog box */ extern OSErr globalError; /*********************** Exported Function Definitions **********************/ #define ErSetGlobalError( /* OSErr */ error ) \ /* callback function that allows any routine to set a global error state */ \ globalError = error #define ErGetGlobalError( /* void */ ) \ /* callback function that allows any routine to get global error state */ \ globalError OSErr ErInternalErrorToAldus( void ); /* returns the appropriate Aldus error code given the current global error */ 
47.017544
79
0.520149
b422c6283dc45d1d3db5cb1b0609cfb6e372e8fd
2,044
h
C
source/keyboard.h
PeterSilie24/GamepadMouse
fd3ef4e34ae84d6b7cea8126bdc6d87d8d64b720
[ "MIT" ]
null
null
null
source/keyboard.h
PeterSilie24/GamepadMouse
fd3ef4e34ae84d6b7cea8126bdc6d87d8d64b720
[ "MIT" ]
null
null
null
source/keyboard.h
PeterSilie24/GamepadMouse
fd3ef4e34ae84d6b7cea8126bdc6d87d8d64b720
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 Phil Badura * * 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. */ #pragma once #include <stdio.h> #include <stdlib.h> #include <Windows.h> #include <shellapi.h> extern void openOnScreenKeyboard(); extern void closeOnScreenKeyboard(); extern void toggleOnScreenKeyboard(); extern void keyboardPressKey(WORD wVk); extern void keyboardReleaseKey(WORD wVk); extern void keyboardPressReturn(); extern void keyboardReleaseReturn(); extern void keyboardPressControl(); extern void keyboardReleaseControl(); extern void keyboardPressUp(); extern void keyboardReleaseUp(); extern void keyboardPressDown(); extern void keyboardReleaseDown(); extern void keyboardPressLeft(); extern void keyboardReleaseLeft(); extern void keyboardPressRight(); extern void keyboardReleaseRight(); extern void keyboardShortcut(WORD wVk1, WORD wVk2); extern void keyboardShortcutExtended(WORD wVk1, WORD wVk2, WORD wVk3); extern void switchWindows(); extern void takeScreenshot();
27.621622
81
0.772994
247eb09f617b505ec01edcfba82cefc8452be0af
700
c
C
src/random.c
cyzchina/logistic_regression_mbsgd
6410a05bc120afded5a3536950f2649a09c5c0e2
[ "Apache-2.0" ]
1
2020-03-17T07:21:08.000Z
2020-03-17T07:21:08.000Z
src/random.c
cyzchina/logistic_regression_mbsgd
6410a05bc120afded5a3536950f2649a09c5c0e2
[ "Apache-2.0" ]
null
null
null
src/random.c
cyzchina/logistic_regression_mbsgd
6410a05bc120afded5a3536950f2649a09c5c0e2
[ "Apache-2.0" ]
null
null
null
#include "base.h" bool create_randoms(uint32_t *randoms, size_t size) { int fd_random; if (-1 == (fd_random = open("/dev/urandom", O_RDONLY))) { //if (-1 == (fd_random = open("/dev/random", O_RDONLY))) { printf("open /dev/urandoom error\n"); return false; } read(fd_random, randoms, sizeof(uint32_t) * size); close(fd_random); return true; } void shuffle(uint32_t *array, uint32_t *randoms, size_t n) { if (n < 1) { return; } create_randoms(randoms, n - 1); size_t i, j; uint32_t t; for (i = n - 1; i > 0; --i) { j = randoms[i] % (i + 1); if (j == i) { continue; } t = array[j]; array[j] = array[i]; array[i] = t; } }
17.948718
60
0.554286
24b31bce7acba82e914b515060e0c1afe3121a9d
2,284
c
C
compiler/sources/writing.c
ollevche/corewar
ff03457f666b54e5a2f8cb4e6510cbc51ea4a88d
[ "MIT" ]
null
null
null
compiler/sources/writing.c
ollevche/corewar
ff03457f666b54e5a2f8cb4e6510cbc51ea4a88d
[ "MIT" ]
1
2018-07-19T09:07:57.000Z
2018-07-19T09:07:57.000Z
compiler/sources/writing.c
ollevche/corewar
ff03457f666b54e5a2f8cb4e6510cbc51ea4a88d
[ "MIT" ]
2
2018-07-19T08:42:14.000Z
2018-08-20T13:55:47.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* writing.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ollevche <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/21 17:27:29 by ollevche #+# #+# */ /* Updated: 2018/09/21 17:27:29 by ollevche ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" static char *add_extension(char *filename) { int len; char *new; len = ft_strlen(filename); if (filename[len - 2] == '.' && filename[len - 1] == 's') len -= 2; new = ft_strnew(len + 4); IF_RET(!new, false); ft_strcpy(new, filename); ft_strcpy(new + len, ".cor"); return (new); } t_item *write_header(int fd, t_item *items) { t_item *name; t_item *comment; t_uchar byte; name = get_item_by_type(NAME_T, items); comment = get_item_by_type(COMM_T, items); write(fd, "\x00\xea\x83\xf3", 4); write(fd, name->bytecode, name->size); write(fd, "\x00\x00\x00\x00", 4); byte = (g_codesize & 0xff000000) >> 24; write(fd, &byte, 1); byte = (g_codesize & 0xff0000) >> 16; write(fd, &byte, 1); byte = (g_codesize & 0xff00) >> 8; write(fd, &byte, 1); byte = g_codesize & 0xff; write(fd, &byte, 1); write(fd, comment->bytecode, comment->size); write(fd, "\x00\x00\x00\x00", 4); return (items->next->next); } bool write_corfile(char *filename, t_item *items) { int fd; char *updated_fname; updated_fname = add_extension(filename); ft_printf("Writing output program to %s\n", updated_fname); fd = open(updated_fname, O_WRONLY | O_TRUNC | O_CREAT, 0644); free(updated_fname); IF_RET(!fd, false); items = write_header(fd, items); while (items) { write(fd, items->bytecode, items->size); items = items->next; } close(fd); return (true); }
31.287671
80
0.437391