hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
1b916a9365fe5056b9e8a58548ef523d35493463
91,849
c
C
linux-imx6/drivers/mxc/ipu3/ipu_disp.c
ub-rms/rushmore
9e6c06e94420349f94fa9c1529e1817efd547c7d
[ "BSD-2-Clause" ]
1
2022-02-21T07:09:11.000Z
2022-02-21T07:09:11.000Z
linux-imx6/drivers/mxc/ipu3/ipu_disp.c
ub-rms/rushmore
9e6c06e94420349f94fa9c1529e1817efd547c7d
[ "BSD-2-Clause" ]
null
null
null
linux-imx6/drivers/mxc/ipu3/ipu_disp.c
ub-rms/rushmore
9e6c06e94420349f94fa9c1529e1817efd547c7d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2005-2015 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ /*! * @file ipu_disp.c * * @brief IPU display submodule API functions * * @ingroup IPU */ #include <linux/clk.h> #include <linux/clk-provider.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/io.h> #include <linux/ipu-v3.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/types.h> #include <asm/atomic.h> #include "ipu_param_mem.h" #include "ipu_regs.h" struct dp_csc_param_t { int mode; const void *coeff; }; #define SYNC_WAVE 0 #define NULL_WAVE (-1) #define ASYNC_SER_WAVE 6 /* DC display ID assignments */ #define DC_DISP_ID_SYNC(di) (di) #define DC_DISP_ID_SERIAL 2 #define DC_DISP_ID_ASYNC 3 /* DC microcode address */ #define DC_MCODE_DI0 0 /* 0 - 6 */ #define MCI_I 0 #define MCI_NL 1 #define MCI_EOL 2 #define MCI_EOL2 3 #define MCI_NEW_DATA 4 #define MCI_EVEN_UGDE 5 #define MCI_ODD_UGDE 6 #define DC_MCODE_DI1 7 /* 7-13 */ #define DC_MCODE_ASYNC_NEW_DATA 0x64 #define DC_MCODE_BT656_START 101 #define DC_MCODE_BT656_VSYNC_FF 141 #define DC_MCODE_BT656_EOFIELD 167 #define DC_MCODE_BT656_DATA_W 173 #define DC_MCODE_BT656_NL 179 #define VYUY_IF_DI_MSB 23 #define BT1120_IF_DI_MSB 23 #define BT656_IF_DI_MSB 23 /* For 8 bits BT656: 23 for DISP_DAT23 ~ DISP_DAT16; 7 for DISP_DAT7 ~ DISP_DAT0 */ /* For 16 bits BT1120: 23 for DISP_DAT23 ~ DISP_DAT8; 15 for DISP_DAT15 ~ DISP_DAT0 */ int dmfc_type_setup; void _ipu_dmfc_init(struct ipu_soc *ipu, int dmfc_type, int first) { u32 dmfc_wr_chan, dmfc_dp_chan; if (first) { if (dmfc_type_setup > dmfc_type) dmfc_type = dmfc_type_setup; else dmfc_type_setup = dmfc_type; /* disable DMFC-IC channel*/ ipu_dmfc_write(ipu, 0x2, DMFC_IC_CTRL); } else if (dmfc_type_setup >= DMFC_HIGH_RESOLUTION_DC) { dev_dbg(ipu->dev, "DMFC high resolution has set, will not change\n"); return; } else dmfc_type_setup = dmfc_type; if (dmfc_type == DMFC_HIGH_RESOLUTION_DC) { /* 1 - segment 0~3; * 5B - segement 4, 5; * 5F - segement 6, 7; * 1C, 2C and 6B, 6F unused; */ dev_info(ipu->dev, "IPU DMFC DC HIGH RESOLUTION: 1(0~3), 5B(4,5), 5F(6,7)\n"); dmfc_wr_chan = 0x00000088; dmfc_dp_chan = 0x00009694; ipu->dmfc_size_28 = 256*4; ipu->dmfc_size_29 = 0; ipu->dmfc_size_24 = 0; ipu->dmfc_size_27 = 128*4; ipu->dmfc_size_23 = 128*4; } else if (dmfc_type == DMFC_HIGH_RESOLUTION_DP) { /* 1 - segment 0, 1; * 5B - segement 2~5; * 5F - segement 6,7; * 1C, 2C and 6B, 6F unused; */ dev_info(ipu->dev, "IPU DMFC DP HIGH RESOLUTION: 1(0,1), 5B(2~5), 5F(6,7)\n"); dmfc_wr_chan = 0x00000090; dmfc_dp_chan = 0x0000968a; ipu->dmfc_size_28 = 128*4; ipu->dmfc_size_29 = 0; ipu->dmfc_size_24 = 0; ipu->dmfc_size_27 = 128*4; ipu->dmfc_size_23 = 256*4; } else if (dmfc_type == DMFC_HIGH_RESOLUTION_ONLY_DP) { /* 5B - segement 0~3; * 5F - segement 4~7; * 1, 1C, 2C and 6B, 6F unused; */ dev_info(ipu->dev, "IPU DMFC ONLY-DP HIGH RESOLUTION: 5B(0~3), 5F(4~7)\n"); dmfc_wr_chan = 0x00000000; dmfc_dp_chan = 0x00008c88; ipu->dmfc_size_28 = 0; ipu->dmfc_size_29 = 0; ipu->dmfc_size_24 = 0; ipu->dmfc_size_27 = 256*4; ipu->dmfc_size_23 = 256*4; } else { /* 1 - segment 0, 1; * 5B - segement 4, 5; * 5F - segement 6, 7; * 1C, 2C and 6B, 6F unused; */ dev_info(ipu->dev, "IPU DMFC NORMAL mode: 1(0~1), 5B(4,5), 5F(6,7)\n"); dmfc_wr_chan = 0x00000090; dmfc_dp_chan = 0x00009694; ipu->dmfc_size_28 = 128*4; ipu->dmfc_size_29 = 0; ipu->dmfc_size_24 = 0; ipu->dmfc_size_27 = 128*4; ipu->dmfc_size_23 = 128*4; } ipu_dmfc_write(ipu, dmfc_wr_chan, DMFC_WR_CHAN); ipu_dmfc_write(ipu, 0x202020F6, DMFC_WR_CHAN_DEF); ipu_dmfc_write(ipu, dmfc_dp_chan, DMFC_DP_CHAN); /* Enable chan 5 watermark set at 5 bursts and clear at 7 bursts */ ipu_dmfc_write(ipu, 0x2020F6F6, DMFC_DP_CHAN_DEF); } static int __init dmfc_setup(char *options) { get_option(&options, &dmfc_type_setup); if (dmfc_type_setup > DMFC_HIGH_RESOLUTION_ONLY_DP) dmfc_type_setup = DMFC_HIGH_RESOLUTION_ONLY_DP; return 1; } __setup("dmfc=", dmfc_setup); void _ipu_dmfc_set_wait4eot(struct ipu_soc *ipu, int dma_chan, int width) { u32 dmfc_gen1 = ipu_dmfc_read(ipu, DMFC_GENERAL1); if (width >= HIGH_RESOLUTION_WIDTH) { if (dma_chan == 23) _ipu_dmfc_init(ipu, DMFC_HIGH_RESOLUTION_DP, 0); else if (dma_chan == 28) _ipu_dmfc_init(ipu, DMFC_HIGH_RESOLUTION_DC, 0); } if (dma_chan == 23) { /*5B*/ if (ipu->dmfc_size_23/width > 3) dmfc_gen1 |= 1UL << 20; else dmfc_gen1 &= ~(1UL << 20); } else if (dma_chan == 24) { /*6B*/ if (ipu->dmfc_size_24/width > 1) dmfc_gen1 |= 1UL << 22; else dmfc_gen1 &= ~(1UL << 22); } else if (dma_chan == 27) { /*5F*/ if (ipu->dmfc_size_27/width > 2) dmfc_gen1 |= 1UL << 21; else dmfc_gen1 &= ~(1UL << 21); } else if (dma_chan == 28) { /*1*/ if (ipu->dmfc_size_28/width > 2) dmfc_gen1 |= 1UL << 16; else dmfc_gen1 &= ~(1UL << 16); } else if (dma_chan == 29) { /*6F*/ if (ipu->dmfc_size_29/width > 1) dmfc_gen1 |= 1UL << 23; else dmfc_gen1 &= ~(1UL << 23); } ipu_dmfc_write(ipu, dmfc_gen1, DMFC_GENERAL1); } void _ipu_dmfc_set_burst_size(struct ipu_soc *ipu, int dma_chan, int burst_size) { u32 dmfc_wr_chan = ipu_dmfc_read(ipu, DMFC_WR_CHAN); u32 dmfc_dp_chan = ipu_dmfc_read(ipu, DMFC_DP_CHAN); int dmfc_bs = 0; switch (burst_size) { case 64: dmfc_bs = 0x40; break; case 32: case 20: dmfc_bs = 0x80; break; case 16: dmfc_bs = 0xc0; break; default: dev_err(ipu->dev, "Unsupported burst size %d\n", burst_size); return; } if (dma_chan == 23) { /*5B*/ dmfc_dp_chan &= ~(0xc0); dmfc_dp_chan |= dmfc_bs; } else if (dma_chan == 27) { /*5F*/ dmfc_dp_chan &= ~(0xc000); dmfc_dp_chan |= (dmfc_bs << 8); } else if (dma_chan == 28) { /*1*/ dmfc_wr_chan &= ~(0xc0); dmfc_wr_chan |= dmfc_bs; } ipu_dmfc_write(ipu, dmfc_wr_chan, DMFC_WR_CHAN); ipu_dmfc_write(ipu, dmfc_dp_chan, DMFC_DP_CHAN); } static void _ipu_di_data_wave_config(struct ipu_soc *ipu, int di, int wave_gen, int access_size, int component_size) { u32 reg; reg = (access_size << DI_DW_GEN_ACCESS_SIZE_OFFSET) | (component_size << DI_DW_GEN_COMPONENT_SIZE_OFFSET); ipu_di_write(ipu, di, reg, DI_DW_GEN(wave_gen)); } static void _ipu_di_data_pin_config(struct ipu_soc *ipu, int di, int wave_gen, int di_pin, int set, int up, int down) { u32 reg; reg = ipu_di_read(ipu, di, DI_DW_GEN(wave_gen)); reg &= ~(0x3 << (di_pin * 2)); reg |= set << (di_pin * 2); ipu_di_write(ipu, di, reg, DI_DW_GEN(wave_gen)); ipu_di_write(ipu, di, (down << 16) | up, DI_DW_SET(wave_gen, set)); } static void _ipu_di_sync_config(struct ipu_soc *ipu, int di, int wave_gen, int run_count, int run_src, int offset_count, int offset_src, int repeat_count, int cnt_clr_src, int cnt_polarity_gen_en, int cnt_polarity_clr_src, int cnt_polarity_trigger_src, int cnt_up, int cnt_down) { u32 reg; if ((run_count >= 0x1000) || (offset_count >= 0x1000) || (repeat_count >= 0x1000) || (cnt_up >= 0x200) || (cnt_down >= 0x200)) { dev_err(ipu->dev, "DI%d counters out of range.\n", di); return; } reg = (run_count << 19) | (++run_src << 16) | (offset_count << 3) | ++offset_src; ipu_di_write(ipu, di, reg, DI_SW_GEN0(wave_gen)); reg = (cnt_polarity_gen_en << 29) | (++cnt_clr_src << 25) | (++cnt_polarity_trigger_src << 12) | (++cnt_polarity_clr_src << 9); reg |= (cnt_down << 16) | cnt_up; if (repeat_count == 0) { /* Enable auto reload */ reg |= 0x10000000; } ipu_di_write(ipu, di, reg, DI_SW_GEN1(wave_gen)); reg = ipu_di_read(ipu, di, DI_STP_REP(wave_gen)); reg &= ~(0xFFFF << (16 * ((wave_gen - 1) & 0x1))); reg |= repeat_count << (16 * ((wave_gen - 1) & 0x1)); ipu_di_write(ipu, di, reg, DI_STP_REP(wave_gen)); } static void _ipu_dc_write_tmpl(struct ipu_soc *ipu, int word, u32 opcode, u32 operand, int map, int wave, int glue, int sync, int stop, int lf, int af) { u32 reg, opcmd; switch(opcode) { case WROD: reg = sync; reg |= (glue << 4); reg |= (++wave << 11); reg |= (++map << 15); reg |= (operand << 20) & 0xFFF00000; ipu_dc_tmpl_write(ipu, reg, word * 8); opcmd = 0x18 | (lf << 1); reg = (operand >> 12); reg |= opcmd << 4; reg |= (stop << 9); ipu_dc_tmpl_write(ipu, reg, word * 8 + 4); break; case WRG: reg = sync; reg |= (glue << 4); reg |= (++wave << 11); reg |= ((operand & 0x1FFFF) << 15); ipu_dc_tmpl_write(ipu, reg, word * 8); opcmd = 0x01; reg = (operand >> 17); reg |= opcmd << 7; reg |= (stop << 9); ipu_dc_tmpl_write(ipu, reg, word * 8 + 4); break; case HMA: reg = (operand << 5); ipu_dc_tmpl_write(ipu, reg, word * 8); opcmd = 0x02; reg = (opcmd << 5); reg |= (stop << 9); ipu_dc_tmpl_write(ipu, reg, word * 8 + 4); break; case HMA1: reg = (operand << 5); ipu_dc_tmpl_write(ipu, reg, word * 8); opcmd = 0x01; reg = (opcmd << 5); reg |= (stop << 9); ipu_dc_tmpl_write(ipu, reg, word * 8 + 4); break; case BMA: reg = sync; reg |= (operand << 5); ipu_dc_tmpl_write(ipu, reg, word * 8); opcmd = 0x03; reg = (af << 3); reg |= (lf << 4); reg |= (opcmd << 5); reg |= (stop << 9); ipu_dc_tmpl_write(ipu, reg, word * 8 + 4); break; default: dev_err(ipu->dev, "WARNING: unsupported opcode.\n"); break; } } static void _ipu_dc_link_event(struct ipu_soc *ipu, int chan, int event, int addr, int priority) { u32 reg; u32 address_shift; if (event < DC_EVEN_UGDE0) { reg = ipu_dc_read(ipu, DC_RL_CH(chan, event)); reg &= ~(0xFFFF << (16 * (event & 0x1))); reg |= ((addr << 8) | priority) << (16 * (event & 0x1)); ipu_dc_write(ipu, reg, DC_RL_CH(chan, event)); } else { reg = ipu_dc_read(ipu, DC_UGDE_0((event - DC_EVEN_UGDE0) / 2)); if ((event - DC_EVEN_UGDE0) & 0x1) { reg &= ~(0x2FF << 16); reg |= (addr << 16); reg |= priority ? (2 << 24) : 0x0; } else { reg &= ~0xFC00FFFF; if (priority) chan = (chan >> 1) + ((((chan & 0x1) + ((chan & 0x2) >> 1))) | (chan >> 3)); else chan = 0x7; address_shift = ((event - DC_EVEN_UGDE0) >> 1) ? 7 : 8; reg |= (addr << address_shift) | (priority << 3) | chan; } ipu_dc_write(ipu, reg, DC_UGDE_0((event - DC_EVEN_UGDE0) / 2)); } } /* Y = R * 1.200 + G * 2.343 + B * .453 + 0.250; U = R * -.672 + G * -1.328 + B * 2.000 + 512.250.; V = R * 2.000 + G * -1.672 + B * -.328 + 512.250.;*/ static const int rgb2ycbcr_coeff[5][3] = { {0x4D, 0x96, 0x1D}, {-0x2B, -0x55, 0x80}, {0x80, -0x6B, -0x15}, {0x0000, 0x0200, 0x0200}, /* B0, B1, B2 */ {0x2, 0x2, 0x2}, /* S0, S1, S2 */ }; /* R = (1.164 * (Y - 16)) + (1.596 * (Cr - 128)); G = (1.164 * (Y - 16)) - (0.392 * (Cb - 128)) - (0.813 * (Cr - 128)); B = (1.164 * (Y - 16)) + (2.017 * (Cb - 128); */ static const int ycbcr2rgb_coeff[5][3] = { {0x095, 0x000, 0x0CC}, {0x095, 0x3CE, 0x398}, {0x095, 0x0FF, 0x000}, {0x3E42, 0x010A, 0x3DD6}, /*B0,B1,B2 */ {0x1, 0x1, 0x1}, /*S0,S1,S2 */ }; #define mask_a(a) ((u32)(a) & 0x3FF) #define mask_b(b) ((u32)(b) & 0x3FFF) /* Pls keep S0, S1 and S2 as 0x2 by using this convertion */ static int _rgb_to_yuv(int n, int red, int green, int blue) { int c; c = red * rgb2ycbcr_coeff[n][0]; c += green * rgb2ycbcr_coeff[n][1]; c += blue * rgb2ycbcr_coeff[n][2]; c /= 16; c += rgb2ycbcr_coeff[3][n] * 4; c += 8; c /= 16; if (c < 0) c = 0; if (c > 255) c = 255; return c; } /* * Row is for BG: RGB2YUV YUV2RGB RGB2RGB YUV2YUV CSC_NONE * Column is for FG: RGB2YUV YUV2RGB RGB2RGB YUV2YUV CSC_NONE */ static struct dp_csc_param_t dp_csc_array[CSC_NUM][CSC_NUM] = { { {DP_COM_CONF_CSC_DEF_BOTH, (void *)&rgb2ycbcr_coeff}, {0, 0}, {0, 0}, {DP_COM_CONF_CSC_DEF_BG, (void *)&rgb2ycbcr_coeff}, {DP_COM_CONF_CSC_DEF_BG, (void *)&rgb2ycbcr_coeff} }, { {0, 0}, {DP_COM_CONF_CSC_DEF_BOTH, (void *)&ycbcr2rgb_coeff}, {DP_COM_CONF_CSC_DEF_BG, (void *)&ycbcr2rgb_coeff}, {0, 0}, {DP_COM_CONF_CSC_DEF_BG, (void *)&ycbcr2rgb_coeff} }, { {0, 0}, {DP_COM_CONF_CSC_DEF_FG, (void *)&ycbcr2rgb_coeff}, {0, 0}, {0, 0}, {0, 0} }, { {DP_COM_CONF_CSC_DEF_FG, (void *)&rgb2ycbcr_coeff}, {0, 0}, {0, 0}, {0, 0}, {0, 0} }, { {DP_COM_CONF_CSC_DEF_FG, (void *)&rgb2ycbcr_coeff}, {DP_COM_CONF_CSC_DEF_FG, (void *)&ycbcr2rgb_coeff}, {0, 0}, {0, 0}, {0, 0} } }; void __ipu_dp_csc_setup(struct ipu_soc *ipu, int dp, struct dp_csc_param_t dp_csc_param, bool srm_mode_update) { u32 reg; const int (*coeff)[5][3]; if (dp_csc_param.mode >= 0) { reg = ipu_dp_read(ipu, DP_COM_CONF(dp)); reg &= ~DP_COM_CONF_CSC_DEF_MASK; reg |= dp_csc_param.mode; ipu_dp_write(ipu, reg, DP_COM_CONF(dp)); } coeff = dp_csc_param.coeff; if (coeff) { ipu_dp_write(ipu, mask_a((*coeff)[0][0]) | (mask_a((*coeff)[0][1]) << 16), DP_CSC_A_0(dp)); ipu_dp_write(ipu, mask_a((*coeff)[0][2]) | (mask_a((*coeff)[1][0]) << 16), DP_CSC_A_1(dp)); ipu_dp_write(ipu, mask_a((*coeff)[1][1]) | (mask_a((*coeff)[1][2]) << 16), DP_CSC_A_2(dp)); ipu_dp_write(ipu, mask_a((*coeff)[2][0]) | (mask_a((*coeff)[2][1]) << 16), DP_CSC_A_3(dp)); ipu_dp_write(ipu, mask_a((*coeff)[2][2]) | (mask_b((*coeff)[3][0]) << 16) | ((*coeff)[4][0] << 30), DP_CSC_0(dp)); ipu_dp_write(ipu, mask_b((*coeff)[3][1]) | ((*coeff)[4][1] << 14) | (mask_b((*coeff)[3][2]) << 16) | ((*coeff)[4][2] << 30), DP_CSC_1(dp)); } if (srm_mode_update) { reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); } } int _ipu_dp_init(struct ipu_soc *ipu, ipu_channel_t channel, uint32_t in_pixel_fmt, uint32_t out_pixel_fmt) { int in_fmt, out_fmt; int dp; int partial = false; uint32_t reg; enum csc_type_t csc_type; struct dp_csc_param_t param; if (channel == MEM_FG_SYNC) { dp = DP_SYNC; partial = true; } else if (channel == MEM_BG_SYNC) { dp = DP_SYNC; partial = false; } else if (channel == MEM_BG_ASYNC0) { dp = DP_ASYNC0; partial = false; } else { return -EINVAL; } in_fmt = format_to_colorspace(in_pixel_fmt); out_fmt = format_to_colorspace(out_pixel_fmt); csc_type = (in_fmt == RGB) ? ((out_fmt == RGB) ? RGB2RGB : RGB2YUV) : ((out_fmt == RGB) ? YUV2RGB : YUV2YUV); if (partial) ipu->fg_csc_type = csc_type; else ipu->bg_csc_type = csc_type; /* Transform color key from rgb to yuv if CSC is enabled */ reg = ipu_dp_read(ipu, DP_COM_CONF(dp)); if (ipu->color_key_4rgb && (reg & DP_COM_CONF_GWCKE) && (((ipu->fg_csc_type == RGB2YUV) && (ipu->bg_csc_type == YUV2YUV)) || ((ipu->fg_csc_type == YUV2YUV) && (ipu->bg_csc_type == RGB2YUV)) || ((ipu->fg_csc_type == YUV2YUV) && (ipu->bg_csc_type == YUV2YUV)) || ((ipu->fg_csc_type == YUV2RGB) && (ipu->bg_csc_type == YUV2RGB)))) { int red, green, blue; int y, u, v; uint32_t color_key = ipu_dp_read(ipu, DP_GRAPH_WIND_CTRL(dp)) & 0xFFFFFFL; dev_dbg(ipu->dev, "_ipu_dp_init color key 0x%x need change to yuv fmt!\n", color_key); red = (color_key >> 16) & 0xFF; green = (color_key >> 8) & 0xFF; blue = color_key & 0xFF; y = _rgb_to_yuv(0, red, green, blue); u = _rgb_to_yuv(1, red, green, blue); v = _rgb_to_yuv(2, red, green, blue); color_key = (y << 16) | (u << 8) | v; reg = ipu_dp_read(ipu, DP_GRAPH_WIND_CTRL(dp)) & 0xFF000000L; ipu_dp_write(ipu, reg | color_key, DP_GRAPH_WIND_CTRL(dp)); ipu->color_key_4rgb = false; dev_dbg(ipu->dev, "_ipu_dp_init color key change to yuv fmt 0x%x!\n", color_key); } param = dp_csc_array[ipu->bg_csc_type][ipu->fg_csc_type]; if ((ipu->fg_csc_type == RGB2YUV) || (ipu->bg_csc_type == RGB2YUV)) param.mode |= (1 << 11); /* Y range 16-235, U/V range 16-240. */ __ipu_dp_csc_setup(ipu, dp, param, true); return 0; } void _ipu_dp_uninit(struct ipu_soc *ipu, ipu_channel_t channel) { int dp; int partial = false; if (channel == MEM_FG_SYNC) { dp = DP_SYNC; partial = true; } else if (channel == MEM_BG_SYNC) { dp = DP_SYNC; partial = false; } else if (channel == MEM_BG_ASYNC0) { dp = DP_ASYNC0; partial = false; } else { return; } if (partial) ipu->fg_csc_type = CSC_NONE; else ipu->bg_csc_type = CSC_NONE; __ipu_dp_csc_setup(ipu, dp, dp_csc_array[ipu->bg_csc_type][ipu->fg_csc_type], false); } void _ipu_dc_init(struct ipu_soc *ipu, int dc_chan, int di, bool interlaced, uint32_t pixel_fmt) { u32 reg = 0; int mc = di ? DC_MCODE_DI1 : DC_MCODE_DI0; if ((dc_chan == 1) || (dc_chan == 5)) { if (interlaced) { if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NL, DC_MCODE_BT656_NL, 2); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NF, DC_MCODE_BT656_VSYNC_FF, 5); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOF, DC_MCODE_BT656_START, 4); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOFIELD, DC_MCODE_BT656_EOFIELD, 3); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA, DC_MCODE_BT656_DATA_W, 0); } else { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NL, mc + MCI_I, 3); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOL, mc + MCI_I, 2); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA, mc + MCI_I, 1); if ((pixel_fmt == IPU_PIX_FMT_YUYV) || (pixel_fmt == IPU_PIX_FMT_UYVY) || (pixel_fmt == IPU_PIX_FMT_YVYU) || (pixel_fmt == IPU_PIX_FMT_VYUY)) { _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE0, mc + MCI_EVEN_UGDE, 5); _ipu_dc_link_event(ipu, dc_chan, DC_ODD_UGDE0, mc + MCI_ODD_UGDE, 5); } } } else { int evt = di ? DC_EVEN_UGDE1 : DC_EVEN_UGDE0; _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NL, mc + MCI_NL, 3); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOL, mc + MCI_EOL, 2); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA, mc + MCI_NEW_DATA, 1); if ((pixel_fmt == IPU_PIX_FMT_YUYV) || (pixel_fmt == IPU_PIX_FMT_UYVY) || (pixel_fmt == IPU_PIX_FMT_YVYU) || (pixel_fmt == IPU_PIX_FMT_VYUY)) { _ipu_dc_link_event(ipu, dc_chan, evt, mc + MCI_EVEN_UGDE, 5); _ipu_dc_link_event(ipu, dc_chan, evt + 1, mc + MCI_ODD_UGDE, 5); } } if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOL, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NFIELD, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR, 0, 0); if (di) { _ipu_dc_link_event(ipu, dc_chan, DC_ODD_UGDE1, DC_MCODE_BT656_DATA_W, 1); if(pixel_fmt == IPU_PIX_FMT_BT656) _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE1, DC_MCODE_BT656_DATA_W + 3, 1); else _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE1, DC_MCODE_BT656_DATA_W + 1, 1); } else { _ipu_dc_link_event(ipu, dc_chan, DC_ODD_UGDE0, DC_MCODE_BT656_DATA_W, 1); if(pixel_fmt == IPU_PIX_FMT_BT656) _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE0, DC_MCODE_BT656_DATA_W + 3, 1); else _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE0, DC_MCODE_BT656_DATA_W + 1, 1); } } else { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NF, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NFIELD, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOF, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOFIELD, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR, 0, 0); } reg = 0x2; reg |= DC_DISP_ID_SYNC(di) << DC_WR_CH_CONF_PROG_DISP_ID_OFFSET; reg |= di << 2; if (interlaced) reg |= DC_WR_CH_CONF_FIELD_MODE; } else if ((dc_chan == 8) || (dc_chan == 9)) { /* async channels */ _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_W_0, DC_MCODE_ASYNC_NEW_DATA, 1); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_W_1, DC_MCODE_ASYNC_NEW_DATA, 1); reg = 0x3; reg |= DC_DISP_ID_SERIAL << DC_WR_CH_CONF_PROG_DISP_ID_OFFSET; } ipu_dc_write(ipu, reg, DC_WR_CH_CONF(dc_chan)); ipu_dc_write(ipu, 0x00000000, DC_WR_CH_ADDR(dc_chan)); ipu_dc_write(ipu, 0x00000084, DC_GEN); } void _ipu_dc_uninit(struct ipu_soc *ipu, int dc_chan, int di) { if ((dc_chan == 1) || (dc_chan == 5)) { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NL, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOL, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NF, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NFIELD, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOF, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_EOFIELD, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR, 0, 0); if (di == 0) { _ipu_dc_link_event(ipu, dc_chan, DC_ODD_UGDE0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE0, 0, 0); } else if (di == 1) { _ipu_dc_link_event(ipu, dc_chan, DC_ODD_UGDE1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVEN_UGDE1, 0, 0); } } else if ((dc_chan == 8) || (dc_chan == 9)) { _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR_W_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR_W_1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN_W_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN_W_1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_W_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_W_1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR_R_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_ADDR_R_1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN_R_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_CHAN_R_1, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_R_0, 0, 0); _ipu_dc_link_event(ipu, dc_chan, DC_EVT_NEW_DATA_R_1, 0, 0); } } int _ipu_disp_chan_is_interlaced(struct ipu_soc *ipu, ipu_channel_t channel) { if (channel == MEM_DC_SYNC) return !!(ipu_dc_read(ipu, DC_WR_CH_CONF_1) & DC_WR_CH_CONF_FIELD_MODE); else if ((channel == MEM_BG_SYNC) || (channel == MEM_FG_SYNC)) return !!(ipu_dc_read(ipu, DC_WR_CH_CONF_5) & DC_WR_CH_CONF_FIELD_MODE); return 0; } void _ipu_dp_dc_enable(struct ipu_soc *ipu, ipu_channel_t channel) { int di; uint32_t reg; uint32_t dc_chan; int irq = 0; if (channel == MEM_FG_SYNC) irq = IPU_IRQ_DP_SF_END; else if (channel == MEM_DC_SYNC) dc_chan = 1; else if (channel == MEM_BG_SYNC) dc_chan = 5; else return; if (channel == MEM_FG_SYNC) { /* Enable FG channel */ reg = ipu_dp_read(ipu, DP_COM_CONF(DP_SYNC)); ipu_dp_write(ipu, reg | DP_COM_CONF_FG_EN, DP_COM_CONF(DP_SYNC)); reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); return; } else if (channel == MEM_BG_SYNC) { reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); } di = ipu->dc_di_assignment[dc_chan]; /* Make sure other DC sync channel is not assigned same DI */ reg = ipu_dc_read(ipu, DC_WR_CH_CONF(6 - dc_chan)); if ((di << 2) == (reg & DC_WR_CH_CONF_PROG_DI_ID)) { reg &= ~DC_WR_CH_CONF_PROG_DI_ID; reg |= di ? 0 : DC_WR_CH_CONF_PROG_DI_ID; ipu_dc_write(ipu, reg, DC_WR_CH_CONF(6 - dc_chan)); } reg = ipu_dc_read(ipu, DC_WR_CH_CONF(dc_chan)); reg |= 4 << DC_WR_CH_CONF_PROG_TYPE_OFFSET; ipu_dc_write(ipu, reg, DC_WR_CH_CONF(dc_chan)); clk_prepare_enable(ipu->pixel_clk[di]); ipu->pixel_clk_en[ipu->dc_di_assignment[dc_chan]] = true; } static irqreturn_t dc_irq_handler(int irq, void *dev_id) { struct ipu_soc *ipu = dev_id; struct completion *comp = &ipu->dc_comp; uint32_t reg; uint32_t dc_chan; if (irq == IPU_IRQ_DC_FC_1) dc_chan = 1; else dc_chan = 5; if (!ipu->dc_swap) { reg = ipu_dc_read(ipu, DC_WR_CH_CONF(dc_chan)); reg &= ~DC_WR_CH_CONF_PROG_TYPE_MASK; ipu_dc_write(ipu, reg, DC_WR_CH_CONF(dc_chan)); reg = ipu_cm_read(ipu, IPU_DISP_GEN); if (ipu->dc_di_assignment[dc_chan]) reg &= ~DI1_COUNTER_RELEASE; else reg &= ~DI0_COUNTER_RELEASE; ipu_cm_write(ipu, reg, IPU_DISP_GEN); } complete(comp); return IRQ_HANDLED; } void _ipu_dp_dc_disable(struct ipu_soc *ipu, ipu_channel_t channel, bool swap) { int ret; uint32_t reg; uint32_t csc; uint32_t dc_chan; int irq = 0; int timeout = 50; ipu->dc_swap = swap; if (channel == MEM_DC_SYNC) { dc_chan = 1; irq = IPU_IRQ_DC_FC_1; } else if (channel == MEM_BG_SYNC) { dc_chan = 5; irq = IPU_IRQ_DP_SF_END; } else if (channel == MEM_FG_SYNC) { /* Disable FG channel */ dc_chan = 5; reg = ipu_dp_read(ipu, DP_COM_CONF(DP_SYNC)); csc = reg & DP_COM_CONF_CSC_DEF_MASK; if (csc == DP_COM_CONF_CSC_DEF_FG) reg &= ~DP_COM_CONF_CSC_DEF_MASK; reg &= ~DP_COM_CONF_FG_EN; ipu_dp_write(ipu, reg, DP_COM_CONF(DP_SYNC)); reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); if (ipu_is_channel_busy(ipu, MEM_BG_SYNC)) { ipu_cm_write(ipu, IPUIRQ_2_MASK(IPU_IRQ_DP_SF_END), IPUIRQ_2_STATREG(ipu->devtype, IPU_IRQ_DP_SF_END)); while ((ipu_cm_read(ipu, IPUIRQ_2_STATREG(ipu->devtype, IPU_IRQ_DP_SF_END)) & IPUIRQ_2_MASK(IPU_IRQ_DP_SF_END)) == 0) { msleep(2); timeout -= 2; if (timeout <= 0) break; } } return; } else { return; } init_completion(&ipu->dc_comp); ret = ipu_request_irq(ipu, irq, dc_irq_handler, 0, NULL, ipu); if (ret < 0) { dev_err(ipu->dev, "DC irq %d in use\n", irq); return; } ret = wait_for_completion_timeout(&ipu->dc_comp, msecs_to_jiffies(50)); ipu_free_irq(ipu, irq, ipu); dev_dbg(ipu->dev, "DC stop timeout - %d * 10ms\n", 5 - ret); if (ipu->dc_swap) { /* Swap DC channel 1 and 5 settings, and disable old dc chan */ reg = ipu_dc_read(ipu, DC_WR_CH_CONF(dc_chan)); ipu_dc_write(ipu, reg, DC_WR_CH_CONF(6 - dc_chan)); reg &= ~DC_WR_CH_CONF_PROG_TYPE_MASK; reg ^= DC_WR_CH_CONF_PROG_DI_ID; ipu_dc_write(ipu, reg, DC_WR_CH_CONF(dc_chan)); } } struct offset_mask { u8 offset; u8 mask; }; struct f_mapping { struct offset_mask om[3]; }; enum { I_IPU_PIX_FMT_RGB24, I_IPU_PIX_FMT_BGR24, I_IPU_PIX_FMT_GBR24, I_IPU_PIX_FMT_RGB666, I_IPU_PIX_FMT_RGB565, I_IPU_PIX_FMT_LVDS666, I_IPU_PIX_FMT_YUV444, I_IPU_PIX_FMT_2CYCLE_START, I_IPU_PIX_FMT_VYUYa_1 = I_IPU_PIX_FMT_2CYCLE_START, I_IPU_PIX_FMT_VYUYa_2, /* 16bit width for BT1120 */ I_IPU_PIX_FMT_BT1120_1, I_IPU_PIX_FMT_BT1120_2, I_IPU_PIX_FMT_VYUY_1, I_IPU_PIX_FMT_VYUY_2, I_IPU_PIX_FMT_UYVY_1, I_IPU_PIX_FMT_UYVY_2, I_IPU_PIX_FMT_YUYV_1, I_IPU_PIX_FMT_YUYV_2, I_IPU_PIX_FMT_YVYU_1, I_IPU_PIX_FMT_YVYU_2, /* 8bit width for BT656 */ I_IPU_PIX_FMT_3CYCLE_START, I_IPU_PIX_FMT_BT656_1 = I_IPU_PIX_FMT_3CYCLE_START, I_IPU_PIX_FMT_BT656_2, I_IPU_PIX_FMT_BT656_3, }; static struct f_mapping fmt_mappings[] = { /* RGB formats are named from High bits to low bits */ /* YUV formats are named from low bits to high bits */ /* B G R */ [I_IPU_PIX_FMT_RGB24] = {{{7, 0xFF}, {15, 0xFF}, {23, 0xFF}}}, [I_IPU_PIX_FMT_BGR24] = {{{23, 0xFF}, {15, 0xFF}, {7, 0xFF}}}, [I_IPU_PIX_FMT_GBR24] = {{{15, 0xFF}, {23, 0xFF}, {7, 0xFF}}}, [I_IPU_PIX_FMT_RGB666] = {{{5, 0xFC}, {11, 0xFC}, {17, 0xFC}}}, [I_IPU_PIX_FMT_RGB565] = {{{4, 0xF8}, {10, 0xFC}, {15, 0xF8}}}, [I_IPU_PIX_FMT_LVDS666] = {{{5, 0xFC}, {13, 0xFC}, {21, 0xFC}}}, /* V U Y */ [I_IPU_PIX_FMT_YUV444] = {{{23, 0xFF}, {15, 0xFF}, {7, 0xFF}}}, [I_IPU_PIX_FMT_VYUYa_1] = {{{VYUY_IF_DI_MSB - 8, 0xFF}, {0, 0x0}, {VYUY_IF_DI_MSB, 0xFF}}}, [I_IPU_PIX_FMT_VYUYa_2] = {{{0, 0x0}, {VYUY_IF_DI_MSB - 8, 0xFF}, {VYUY_IF_DI_MSB, 0xFF}}}, /* 16bit width for BT1120 */ [I_IPU_PIX_FMT_BT1120_1] = {{{0, 0x0}, {BT1120_IF_DI_MSB - 8, 0xFF}, {BT1120_IF_DI_MSB, 0xFF}}}, [I_IPU_PIX_FMT_BT1120_2] = {{{BT1120_IF_DI_MSB - 8, 0xFF}, {0, 0x0}, {BT1120_IF_DI_MSB, 0xFF}}}, /* V U Y */ [I_IPU_PIX_FMT_VYUY_1] = {{{7, 0xFF}, {0, 0x0}, {15, 0xFF}}}, [I_IPU_PIX_FMT_VYUY_2] = {{{0, 0x0}, {7, 0xFF}, {15, 0xFF}}}, [I_IPU_PIX_FMT_UYVY_1] = {{{0, 0x0}, {7, 0xFF}, {15, 0xFF}}}, [I_IPU_PIX_FMT_UYVY_2] = {{{7, 0xFF}, {0, 0x0}, {15, 0xFF}}}, [I_IPU_PIX_FMT_YUYV_1] = {{{0, 0x0}, {15, 0xFF}, {7, 0xFF}}}, [I_IPU_PIX_FMT_YUYV_2] = {{{15, 0xFF}, {0, 0x0}, {7, 0xFF}}}, [I_IPU_PIX_FMT_YVYU_1] = {{{15, 0xFF}, {0, 0x0}, {7, 0xFF}}}, [I_IPU_PIX_FMT_YVYU_2] = {{{0, 0x0}, {15, 0xFF}, {7, 0xFF}}}, /* 8bit width for BT656 */ [I_IPU_PIX_FMT_BT656_1] = {{{0, 0x0}, {BT656_IF_DI_MSB, 0xFF}, {0, 0x0}}}, /* U */ [I_IPU_PIX_FMT_BT656_2] = {{{0, 0x0}, {0, 0x0}, {BT656_IF_DI_MSB, 0xFF}}}, /* Y */ [I_IPU_PIX_FMT_BT656_3] = {{{BT656_IF_DI_MSB, 0xFF}, {0, 0x0}, {0, 0x0}}}, /* V */ }; static int g_di_msb = BT656_IF_DI_MSB; int ipu_update_bt656_mapping(int di_msb) { struct f_mapping *fm = fmt_mappings; fm[I_IPU_PIX_FMT_BT656_1].om[1].offset = di_msb; fm[I_IPU_PIX_FMT_BT656_2].om[2].offset = di_msb; fm[I_IPU_PIX_FMT_BT656_3].om[0].offset = di_msb; g_di_msb = di_msb; return 0; } static int find_field(struct ipu_soc *ipu, u32 val, u32 reg_offset, unsigned long* bitmap, int max) { int i = 0; u32 reg; unsigned long lock_flags; while (i <= max) { if (!test_bit(i, bitmap)) break; reg = ipu_dc_read(ipu, reg_offset + ((i >> 1) << 2)); if (val == (reg & 0xffff)) return i; i++; if (!test_bit(i, bitmap)) break; if (val == (reg >> 16)) return i; i++; } spin_lock_irqsave(&ipu->rdy_reg_spin_lock, lock_flags); i = ffz(*bitmap); if (i > max) { spin_unlock_irqrestore(&ipu->rdy_reg_spin_lock, lock_flags); dev_err(ipu->dev, "out of mappings, max=%d\n", max); return -EINVAL; } reg = ipu_dc_read(ipu, reg_offset + ((i >> 1) << 2)); reg &= ~(0xFFFF << (16 * (i & 0x1))); reg |= val << (16 * (i & 0x1)); ipu_dc_write(ipu, reg, reg_offset + ((i >> 1) << 2)); set_bit(i, bitmap); spin_unlock_irqrestore(&ipu->rdy_reg_spin_lock, lock_flags); pr_info("%s: [%d] = 0x%x, max=%d\n", __func__, i, val, max); return i; } int find_om(struct ipu_soc *ipu, struct offset_mask *om) { return find_field(ipu, (om->offset << 8) | om->mask, DC_MAP_CONF_VAL(0), &ipu->offset_mask_bitmap, DC_MAPPING_VAL_MAX); } static int find_mptr(struct ipu_soc *ipu, u32 val) { return find_field(ipu, val, DC_MAP_CONF_PTR(0), &ipu->mapping_bitmap, DC_MAPPING_PTR_MAX); } int do_mapping(struct ipu_soc *ipu, int i) { struct f_mapping *fm = &fmt_mappings[i]; u32 t = 0; for (i = 0; i < 3; i++) { int m = find_om(ipu, &fm->om[i]); if (m < 0) return m; t = (t >> 5) | (m << 10); } return find_mptr(ipu, t); } int pixfmt_to_i(uint32_t fmt) { switch (fmt) { case IPU_PIX_FMT_GENERIC: case IPU_PIX_FMT_RGB24: return I_IPU_PIX_FMT_RGB24; case IPU_PIX_FMT_RGB666: return I_IPU_PIX_FMT_RGB666; case IPU_PIX_FMT_YUV444: return I_IPU_PIX_FMT_YUV444; case IPU_PIX_FMT_RGB565: return I_IPU_PIX_FMT_RGB565; case IPU_PIX_FMT_LVDS666: return I_IPU_PIX_FMT_LVDS666; case IPU_PIX_FMT_VYUY: return I_IPU_PIX_FMT_VYUY_1; case IPU_PIX_FMT_BT1120: return I_IPU_PIX_FMT_BT1120_1; case IPU_PIX_FMT_BT656: return I_IPU_PIX_FMT_BT656_1; case IPU_PIX_FMT_UYVY: return I_IPU_PIX_FMT_UYVY_1; case IPU_PIX_FMT_YUYV: return I_IPU_PIX_FMT_YUYV_1; case IPU_PIX_FMT_YVYU: return I_IPU_PIX_FMT_YVYU_1; case IPU_PIX_FMT_GBR24: case IPU_PIX_FMT_VYU444: return I_IPU_PIX_FMT_GBR24; case IPU_PIX_FMT_BGR24: return I_IPU_PIX_FMT_BGR24; } return -EINVAL; } int _ipu_pixfmt_to_map(struct ipu_soc *ipu, uint32_t fmt, int *mappings) { int i = pixfmt_to_i(fmt); int ret; if (i < 0) return i; ret = do_mapping(ipu, i++); if (ret < 0) return ret; *mappings++ = ret; if (i > I_IPU_PIX_FMT_2CYCLE_START) { ret = do_mapping(ipu, i++); if (ret < 0) return ret; *mappings++ = ret; if (i > I_IPU_PIX_FMT_3CYCLE_START) { ret = do_mapping(ipu, i++); if (ret < 0) return ret; *mappings++ = ret; } } return 0; } /*! * This function sets the colorspace for of dp. * modes. * * @param ipu ipu handler * @param channel Input parameter for the logical channel ID. * * @param param If it's not NULL, update the csc table * with this parameter. * * @return N/A */ void _ipu_dp_set_csc_coefficients(struct ipu_soc *ipu, ipu_channel_t channel, int32_t param[][3]) { int dp; struct dp_csc_param_t dp_csc_param; if (channel == MEM_FG_SYNC) dp = DP_SYNC; else if (channel == MEM_BG_SYNC) dp = DP_SYNC; else if (channel == MEM_BG_ASYNC0) dp = DP_ASYNC0; else return; dp_csc_param.mode = -1; dp_csc_param.coeff = param; __ipu_dp_csc_setup(ipu, dp, dp_csc_param, true); } static void _ipu_dc_setup_bt656_interlaced(struct ipu_soc *ipu, int map0, int map1, int map2, bool is_bt1120, int di_msb, uint32_t bt656_h_start_width, uint32_t bt656_v_start_width_field0, uint32_t bt656_v_end_width_field0, uint32_t bt656_v_start_width_field1, uint32_t bt656_v_end_width_field1) { uint32_t microcode_addr_FirstPart, microcode_addr_SecondPart; uint32_t microcode_addr_EOFIELD, microcode_addr_DataW, microcode_addr_NL, microcode_addr_FirstPartSF; uint32_t microcode_addr_SAV0, microcode_addr_SAV1, microcode_addr_SAVff; uint32_t microcode_addr_BlankDone, microcode_addr_VsyncSyncFF, microcode_addr_VsyncSyncCont; uint32_t loop_N_times, loop_BL0_times, loop_BL1_times, loop_BL2_times, loop_BL3_times; uint32_t microcode_start_addr, microcode_addr; uint32_t second_offset = 0x50, second_field; uint32_t vsync_sync_cont = 0x30; second_field = (vsync_sync_cont - 1 + second_offset); microcode_addr = microcode_start_addr = DC_MCODE_BT656_START; microcode_addr_FirstPart = microcode_start_addr + 0x1; microcode_addr_SAV0 = microcode_start_addr + 0xB; microcode_addr_SecondPart = microcode_start_addr + 0x13; microcode_addr_SAV1 = microcode_start_addr + 0x20; microcode_addr_VsyncSyncFF = microcode_start_addr + 0x28; //DC_MCODE_BT656_VSYNC_FF microcode_addr_VsyncSyncCont = microcode_start_addr + vsync_sync_cont; microcode_addr_SAVff = microcode_start_addr + 0x3A; microcode_addr_EOFIELD = microcode_start_addr + 0x48 - 6; //DATA_W - 6, DC_MCODE_BT656_EOFIELD microcode_addr_DataW = microcode_start_addr + 0x48; //DC_MCODE_BT656_DATA_W microcode_addr_NL = microcode_start_addr + 0x48 + 6; //DATA_W + 6, DC_MCODE_BT656_NL microcode_addr_FirstPartSF = microcode_start_addr + second_offset; microcode_addr_BlankDone = microcode_start_addr + second_field - 0x2; if(is_bt1120) loop_N_times = (bt656_h_start_width - 8) - 1; //horizontal blanking else loop_N_times = (bt656_h_start_width - 8) / 2 - 1; //horizontal blanking loop_BL0_times = bt656_v_end_width_field1 - 1; //vertical blanking type 0 loop_BL1_times = bt656_v_start_width_field0 - 1; //vertical blanking type 1 loop_BL2_times = bt656_v_end_width_field0 - 1; //vertical blanking type 2 loop_BL3_times = bt656_v_start_width_field1 - 1; //vertical blanking type 3 _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map1, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //First part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_SAV0, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait he, send eav_0[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //wait he, send eav_0[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_0[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_0[3] //Blanking aferr FIELD1 F=1 V=1 H=1 P3=0 P2=0 P1=0 P0=1 =>11110001 => 0xF1 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xF1 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0 HEAD_LOOP_0 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_0: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; //LOOP: //Jump Store jump address 0 N_TIMES //else jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 1, 1); microcode_addr = microcode_addr_SAV0; //Sav0: //wait ipp clk, send sav_0[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: First part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_FirstPart, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[3] //Blanking aferr FIELD1 F=1 V=1 H=0 P3=1 P2=1 P1=0 P0=0 =>11101100 => 0xEC _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xEC << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0 sencond part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SecondPart, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 1 BL0_TIMES //else jump Store jump address 0 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_BL0_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SecondPart; //Second part //wait he, send eav_1[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //store jump address0 Sav_1 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SAV1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xB6 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 HEAD_LOOP_1 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_1: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; //LOOP: //Jump Store jump address 1 N_TIMES //else jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SAV1; //Sav1: //wait ipp clk, send sav_1[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0: Second part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SecondPart, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xAB << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 blank done _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_BlankDone, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 0 BL1_TIMES //else jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_BL1_times, 0, 0, 0, 0, 0, 1, 1); //New vsync microcode_addr = microcode_addr_VsyncSyncFF; //if nf //Start here, no blank //Store jump address 0 VSYNC_SYNC_CONT _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_VsyncSyncCont, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait for synchronization //wait ve, send eav_FF[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_AFIELD, 0, 0, 0); microcode_addr ++; //Jump Store jump address 0 // go to vsync_sync_cont _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, 0, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_VsyncSyncCont - 1; //First field //wait he, send eav_FF[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //vync_sync_cont: //wait ipp clk, send eav_FF[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0: sav_ff _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SAVff, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_FF[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_FF[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x9D << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: Header_loop_ff _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_FF: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; //LOOP: //Jump Store jump address 1 N_TIMES //else jump Store jump address 0 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SAVff; //Savff: //wait ipp clk, send sav_ff[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: data_w _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_DataW, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 blank done _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_VsyncSyncCont - 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 0 data_w _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, 0, 0, 0, 0, 0, 0, 1, 1); //share routine //EOField: last data of first field if not NF microcode_addr = microcode_addr_EOFIELD; _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map1, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 FIRST_PART_SF _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_FirstPartSF, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 0 FIRST_PART_SF _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, 0, 0, 0, 0, 0, 0, 1, 1); //regular data sending microcode_addr = microcode_addr_DataW; if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map0, 0, 0, DI_BT656_SYNC_BASECLK, 1, 0, 0); microcode_addr ++; _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map1, 0, 0, DI_BT656_SYNC_BASECLK, 1, 0, 0); } else { //wait ipp clk, send data[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send data[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map1, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send data[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map2, 0, 0, DI_BT656_SYNC_BASECLK, 1, 0, 0); microcode_addr ++; //wait ipp clk, send data[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WROD, 0, map1, 0, 0, DI_BT656_SYNC_BASECLK, 1, 0, 0); } microcode_addr = microcode_addr_NL; //N_L: new line with data if not NF //Jump Store jump address 0 //go to FIRST_FIELD/SECOND_FIELD _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, 0, 0, 0, 0, 0, 0, 0, 0); /////////////////////////////////////// // Second field /////////////////////////////////////// microcode_addr = microcode_start_addr + second_offset; // microcode_addr_FirstPartSF //First part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_SAV0 + second_offset, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait he, send eav_0[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_0[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_0[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_0[3] //Blanking aferr FIELD0 F=0 V=1 H=1 P3=0 P2=1 P1=1 P0=0 =>10110110 => 0xB6 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xB6 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0 HEAD_LOOP_0 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_0: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 1, 1); microcode_addr = microcode_addr_SAV0 + second_offset; //Sav0: //wait ipp clk, send sav_0[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: First part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_FirstPartSF, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_0[3] //Blanking aferr FIELD0 F=0 V=1 H=0 P3=1 P2=0 P1=1 P0=1 =>10101011 => 0xAB _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xAB << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0 sencond part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SecondPart + second_offset, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 1 BL0_TIMES //else jump Store jump address 0 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_BL2_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SecondPart + second_offset; //Second part //wait he, send eav_1[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //store jump address0 Sav_1 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SAV1 + second_offset, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_1[3] //Blanking before field1 F=1 V=1 H=1 P3=0 P2=0 P1=0 P0=1 =>11110001=>0XF1 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xF1 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 HEAD_LOOP_1 _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_1: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; //LOOP: //Jump Store jump address 1 N_TIMES //else jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SAV1 + second_offset; //Sav1: //wait ipp clk, send sav_1[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0: Second part _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SecondPart + second_offset, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_1[3] //Blanking before field1 F=1 V=1 H=0 P3=1 P2=1 P1=0 P0=0 =>11101100=>0XEC _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xEC << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1 blank done _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_BlankDone, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 0 BL1_TIMES //else jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_BL3_times, 0, 0, 0, 0, 0, 1, 1); microcode_addr = microcode_addr_BlankDone; //Store jump address 0 second field _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_BlankDone + 2, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; // Stop _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 1, 0, 0); microcode_addr ++; //SECOND FIELD microcode_addr_BlankDone+2 //wait he, send eav_FF[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_HSYNC, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_FF[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0: sav_ff _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_SAVff + second_offset, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_FF[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send eav_FF[3] //H Blanking in field1 F=1, V=0, H=1, P3=1,P2=0, P1=0, P0=1=>11011010=>0xda _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xDA << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: Header_loop_ff _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr + 1, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //HEAD_LOOP_FF: if(is_bt1120) { _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x1080 << (di_msb - 15)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } else { //wait ipp_clk, send 0x80 //First 8 bit word in blanking _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x80 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp_clk, send 0x10 _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0x10 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); } microcode_addr ++; //LOOP: //Jump Store jump address 1 N_TIMES //else jump Store jump address 0 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, loop_N_times, 0, 0, 0, 0, 0, 0, 0); microcode_addr = microcode_addr_SAVff + second_offset; //Savff: //wait ipp clk, send sav_ff[0] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xFF << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[1] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 1: data_w _ipu_dc_write_tmpl(ipu, microcode_addr, HMA1, microcode_addr_DataW, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[2] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, 0x00, 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //wait ipp clk, send sav_ff[3] _ipu_dc_write_tmpl(ipu, microcode_addr, WRG, (0xC7 << (di_msb - 7)), 0, 0, 0, DI_BT656_SYNC_BASECLK, 0, 0, 0); microcode_addr ++; //Store jump address 0 second field _ipu_dc_write_tmpl(ipu, microcode_addr, HMA, microcode_addr_BlankDone + 2, 0, 0, 0, 0, 0, 0, 0); microcode_addr ++; //Jump Store jump address 1 _ipu_dc_write_tmpl(ipu, microcode_addr, BMA, 0, 0, 0, 0, 0, 0, 1, 1); } void ipu_set_csc_coefficients(struct ipu_soc *ipu, ipu_channel_t channel, int32_t param[][3]) { _ipu_dp_set_csc_coefficients(ipu, channel, param); } EXPORT_SYMBOL(ipu_set_csc_coefficients); /*! * This function is called to adapt synchronous LCD panel to IPU restriction. * */ void adapt_panel_to_ipu_restricitions(struct ipu_soc *ipu, uint16_t *v_start_width, uint16_t *v_sync_width, uint16_t *v_end_width) { if (*v_end_width < 2) { uint16_t diff = 2 - *v_end_width; if (*v_start_width >= diff) { *v_end_width = 2; *v_start_width = *v_start_width - diff; } else if (*v_sync_width > diff) { *v_end_width = 2; *v_sync_width = *v_sync_width - diff; } else dev_err(ipu->dev, "WARNING: try to adapt timming, but failed\n"); dev_err(ipu->dev, "WARNING: adapt panel end blank lines\n"); } } /*! * This function is called to initialize a synchronous LCD panel. * * @param ipu ipu handler * @param disp The DI the panel is attached to. * * @param pixel_clk Desired pixel clock frequency in Hz. * * @param pixel_fmt Input parameter for pixel format of buffer. * Pixel format is a FOURCC ASCII code. * * @param width The width of panel in pixels. * * @param height The height of panel in pixels. * * @param hStartWidth The number of pixel clocks between the HSYNC * signal pulse and the start of valid data. * * @param hSyncWidth The width of the HSYNC signal in units of pixel * clocks. * * @param hEndWidth The number of pixel clocks between the end of * valid data and the HSYNC signal for next line. * * @param vStartWidth The number of lines between the VSYNC * signal pulse and the start of valid data. * * @param vSyncWidth The width of the VSYNC signal in units of lines * * @param vEndWidth The number of lines between the end of valid * data and the VSYNC signal for next frame. * * @param sig Bitfield of signal polarities for LCD interface. * * @return This function returns 0 on success or negative error code on * fail. */ int32_t ipu_init_sync_panel(struct ipu_soc *ipu, int disp, uint32_t pixel_clk, uint16_t width, uint16_t height, uint32_t pixel_fmt, uint16_t h_start_width, uint16_t h_sync_width, uint16_t h_end_width, uint16_t v_start_width, uint16_t v_sync_width, uint16_t v_end_width, uint32_t v_to_h_sync, ipu_di_signal_cfg_t sig) { uint32_t field0_offset = 0; uint32_t field1_offset; uint32_t reg; uint32_t di_gen, vsync_cnt; uint32_t div, rounded_pixel_clk; uint32_t h_total, v_total; int map[3]; int ret; struct clk *clk540m; struct clk *di_parent, *dipp; uint32_t bt656_h_start_width = 0; uint32_t bt656_v_start_width_field0 = 0, bt656_v_end_width_field0 = 0; uint32_t bt656_v_start_width_field1 = 0, bt656_v_end_width_field1 = 0; bool special = false; dev_dbg(ipu->dev, "panel size = %d x %d\n", width, height); if ((v_sync_width == 0) || (h_sync_width == 0)) return -EINVAL; if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { bt656_h_start_width = h_sync_width; bt656_v_start_width_field0 = h_start_width; bt656_v_end_width_field0 = h_end_width; bt656_v_start_width_field1 =v_start_width ; bt656_v_end_width_field1 = v_end_width; v_total = height + bt656_v_start_width_field0 + bt656_v_end_width_field0 + bt656_v_start_width_field1 + bt656_v_end_width_field1; if(pixel_fmt == IPU_PIX_FMT_BT656) { /* BT656 */ h_total = bt656_h_start_width + width * 2; } else { /* BT1120 */ h_total = bt656_h_start_width + width; } } else { adapt_panel_to_ipu_restricitions(ipu, &v_start_width, &v_sync_width, &v_end_width); h_total = width + h_sync_width + h_start_width + h_end_width; v_total = height + v_sync_width + v_start_width + v_end_width; } /* Init clocking */ dev_dbg(ipu->dev, "pixel clk = %d\n", pixel_clk); di_parent = clk_get_parent(ipu->di_clk_sel[disp]); if (!di_parent) { dev_err(ipu->dev, "get di clk parent fail\n"); return -EINVAL; } dipp = clk_get_parent(di_parent); if (IS_ERR(dipp)) { dev_err(ipu->dev, "get dipp fail\n"); return PTR_ERR(dipp); } clk540m = clk_get(ipu->dev, "540m"); if (!IS_ERR(clk540m)) { uint32_t clk540m_rate = clk_get_rate(clk540m); uint32_t rem = clk540m_rate % pixel_clk; struct clk *ldb_di0_clk = NULL; struct clk *ldb_di1_clk = NULL; if (!rem) { int div; ret = clk_set_parent(dipp, clk540m); if (ret) { dev_err(ipu->dev, "set parent error:%d\n", ret); return ret; } div = clk540m_rate / pixel_clk; if (!(div & 1)) div >>= 1; if (!(div & 1)) div >>= 1; dev_info(ipu->dev, "%s=%ld\n", __clk_get_name(dipp), clk_get_rate(dipp)); ret = clk_set_rate(di_parent, clk540m_rate / div); if (ret) { dev_warn(ipu->dev, "set rate error:%d\n", ret); rem = 1; } } clk_put(clk540m); if (rem) { struct clk *clk_video = clk_get(ipu->dev, "video_pll"); if (IS_ERR(clk_video)) { dev_err(ipu->dev, "clk_get video_pll failed"); return PTR_ERR(clk_video); } ret = clk_set_parent(dipp, clk_video); clk_put(clk_video); } ldb_di0_clk = clk_get(ipu->dev, "ldb_di0"); if (IS_ERR(ldb_di0_clk)) { dev_err(ipu->dev, "clk_get di0 failed"); return PTR_ERR(ldb_di0_clk); } ldb_di1_clk = clk_get(ipu->dev, "ldb_di1"); if (IS_ERR(ldb_di1_clk)) { dev_err(ipu->dev, "clk_get di1 failed"); return PTR_ERR(ldb_di1_clk); } special = !strcmp(__clk_get_name(di_parent), __clk_get_name(ldb_di0_clk)) || !strcmp(__clk_get_name(di_parent), __clk_get_name(ldb_di1_clk)) || !rem; clk_put(ldb_di0_clk); clk_put(ldb_di1_clk); } if (special) { /* if di clk parent is tve/ldb, then keep it;*/ dev_info(ipu->dev, "use special clk parent\n"); ret = clk_set_parent(ipu->pixel_clk_sel[disp], ipu->di_clk[disp]); if (ret) { dev_err(ipu->dev, "set pixel clk error:%d\n", ret); return ret; } } else { /* try ipu clk first*/ dev_info(ipu->dev, "try ipu internal clk\n"); ret = clk_set_parent(ipu->pixel_clk_sel[disp], ipu->ipu_clk); if (ret) { dev_err(ipu->dev, "set pixel clk error:%d\n", ret); return ret; } rounded_pixel_clk = clk_round_rate(ipu->pixel_clk[disp], pixel_clk); dev_dbg(ipu->dev, "rounded pix clk:%d\n", rounded_pixel_clk); /* * we will only use 1/2 fraction for ipu clk, * so if the clk rate is not fit, try ext clk. */ if (!sig.int_clk && ((rounded_pixel_clk >= pixel_clk + pixel_clk/200) || (rounded_pixel_clk <= pixel_clk - pixel_clk/200))) { dev_dbg(ipu->dev, "try ipu ext di clk\n"); rounded_pixel_clk = clk_round_rate(ipu->di_clk[disp], pixel_clk); ret = clk_set_rate(ipu->di_clk[disp], rounded_pixel_clk); if (ret) { dev_err(ipu->dev, "set di clk rate error:%d\n", ret); return ret; } dev_dbg(ipu->dev, "di clk:%d\n", rounded_pixel_clk); ret = clk_set_parent(ipu->pixel_clk_sel[disp], ipu->di_clk[disp]); if (ret) { dev_err(ipu->dev, "set pixel clk parent error:%d\n", ret); return ret; } } } rounded_pixel_clk = clk_round_rate(ipu->pixel_clk[disp], pixel_clk); dev_dbg(ipu->dev, "round pixel clk:%d\n", rounded_pixel_clk); ret = clk_set_rate(ipu->pixel_clk[disp], rounded_pixel_clk); if (ret) { dev_err(ipu->dev, "set pixel clk rate error:%d\n", ret); return ret; } msleep(5); /* Get integer portion of divider */ div = clk_get_rate(clk_get_parent(ipu->pixel_clk_sel[disp])) / rounded_pixel_clk; dev_info(ipu->dev, "disp=%d, pixel_clk=%d %d parent=%ld div=%d\n", disp, pixel_clk, rounded_pixel_clk, clk_get_rate(clk_get_parent(ipu->pixel_clk_sel[disp])), div); if (!div) { dev_err(ipu->dev, "invalid pixel clk div = 0\n"); return -EINVAL; } mutex_lock(&ipu->mutex_lock); _ipu_di_data_wave_config(ipu, disp, SYNC_WAVE, div - 1, div - 1); _ipu_di_data_pin_config(ipu, disp, SYNC_WAVE, DI_PIN15, 3, 0, div * 2); ret = _ipu_pixfmt_to_map(ipu, pixel_fmt, map); if (ret < 0) { dev_dbg(ipu->dev, "IPU_DISP: No MAP\n"); mutex_unlock(&ipu->mutex_lock); return ret; } if(pixel_fmt == IPU_PIX_FMT_BT656) h_total = bt656_h_start_width + width * 2; else if(pixel_fmt == IPU_PIX_FMT_BT1120) h_total = bt656_h_start_width + width; /*clear DI*/ di_gen = ipu_di_read(ipu, disp, DI_GENERAL); di_gen &= (0x3 << 20); ipu_di_write(ipu, disp, di_gen, DI_GENERAL); if (sig.interlaced) { if (ipu->devtype >= IPUv3EX) { if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { /* COUNTER_1: basic clock */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_BASECLK, /* counter */ 0, /* run count */ DI_SYNC_CLK, /* run_resolution */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* COUNTER_2: HSYNC for each line */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_HSYNC, /* counter */ h_total - 1, /* run count */ DI_SYNC_CLK, /* run_resolution */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 2*div /* COUNT DOWN */ ); /* COUNTER_3: internal VSYNC for each frame */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_IVSYNC, /* counter */ v_total - 1, /* run count */ DI_BT656_SYNC_HSYNC, /* run_resolution */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); vsync_cnt = DI_BT656_SYNC_VSYNC; /* COUNTER_4: VSYNC for field1 only */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_VSYNC, /* counter */ 0, /* run count */ DI_BT656_SYNC_HSYNC, /* run_resolution */ bt656_v_start_width_field0 + height / 2 + bt656_v_end_width_field0, /* offset */ DI_BT656_SYNC_HSYNC, /* offset resolution */ 1, /* repeat count */ DI_BT656_SYNC_IVSYNC, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 2*div /* COUNT DOWN */ ); /* COUNTER_5: first active line for field0 */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_AFIELD, /* counter */ 0, /* run count */ DI_BT656_SYNC_HSYNC, /* run_resolution */ bt656_v_start_width_field0 + height / 2 + bt656_v_end_width_field0 + 2, /* offset */ DI_BT656_SYNC_HSYNC, /* offset resolution */ 1, /* repeat count */ DI_BT656_SYNC_IVSYNC, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* COUNTER_9: VSYNC for field0 only */ _ipu_di_sync_config(ipu, disp, /* display */ DI_BT656_SYNC_NVSYNC, /* counter */ 0, /* run count */ DI_BT656_SYNC_HSYNC - 1, /* run_resolution, the counter#9 setting is different with others , no necessary to +1! */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 1, /* repeat count */ DI_BT656_SYNC_IVSYNC - 1, /* CNT_CLR_SEL, the counter#9 setting is different with others , no necessary to +1! */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 2*div /* COUNT DOWN */ ); /* set gentime select and tag sel */ reg = ipu_di_read(ipu, disp, DI_SW_GEN1(9)); reg &= 0x1FFFFFFF; reg |= (DI_BT656_SYNC_VSYNC - 1) << 29; ipu_di_write(ipu, disp, reg, DI_SW_GEN1(9)); ipu_di_write(ipu, disp, height / 2 + bt656_v_start_width_field0 + bt656_v_end_width_field0 - 1, DI_SCR_CONF); /* set y_sel = DI_BT656_SYNC_HSYNC - 1 */ di_gen |= ((DI_BT656_SYNC_HSYNC - 1) << 28); } else { /* Internal VSYNC for each frame */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_COUNT_1, /* counter */ v_total*2 - 1, /* run count */ (3 - 1), /* run_resolution, counter 1 can reference to counter 6,7,8 with run_resolution=2,3,4 */ 1, /* offset */ (3 - 1), /* offset resolution, 3=counter 7 */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* HSYNC waveform on DI_PIN02 */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_HSYNC, /* counter */ h_total - 1, /* run count */ DI_SYNC_CLK, /* run_resolution, counter 2 can reference to counter 5,7 with run_resolution=3,4 */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 1, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_CLK, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 2*h_sync_width /* COUNT DOWN */ ); /* VSYNC waveform on DI_PIN03 */ vsync_cnt = DI_SYNC_VSYNC; _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_VSYNC, /* counter */ v_total - 1, /* run count */ (4 - 1), /* run_resolution, counter 3 can reference to counter 7 with run_resolution=4 */ 1, /* offset */ (4 - 1), /* offset resolution, 4=counter 7 */ 2, /* repeat count */ DI_SYNC_COUNT_1, /* CNT_CLR_SEL */ 1, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ (4 - 1), /* CNT_POLARITY_TRIGGER_SEL, 4=counter 7 */ 0, /* COUNT UP */ 2*v_sync_width /* COUNT DOWN */ ); /* Active Field */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_AFIELD, /* counter */ (v_total/2 + 1) - 1, /* run count */ DI_SYNC_HSYNC, /* run_resolution */ h_total/2, /* offset */ DI_SYNC_CLK, /* offset resolution */ 2, /* repeat count */ DI_SYNC_COUNT_1, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* Active Line */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_ALINE, /* counter */ 0, /* run count */ DI_SYNC_HSYNC, /* run_resolution */ (v_start_width + v_sync_width) / 2, /* offset */ DI_SYNC_HSYNC, /* offset resolution */ height/2, /* repeat count */ DI_SYNC_AFIELD, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* Active Pixel */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_APIXEL, /* counter */ 0, /* run count */ DI_SYNC_CLK, /* run_resolution */ h_start_width + h_sync_width, /* offset */ DI_SYNC_CLK, /* offset resolution */ width, /* repeat count */ DI_SYNC_ALINE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); /* Half line HSYNC */ _ipu_di_sync_config(ipu, disp, /* display */ DI_SYNC_COUNT_7, /* counter */ h_total/2 - 1, /* run count */ DI_SYNC_CLK, /* run_resolution */ 0, /* offset */ DI_SYNC_NONE, /* offset resolution */ 0, /* repeat count */ DI_SYNC_NONE, /* CNT_CLR_SEL */ 0, /* CNT_POLARITY_GEN_EN */ DI_SYNC_NONE, /* CNT_POLARITY_CLR_SEL */ DI_SYNC_NONE, /* CNT_POLARITY_TRIGGER_SEL */ 0, /* COUNT UP */ 0 /* COUNT DOWN */ ); ipu_di_write(ipu, disp, v_total / 2 - 1, DI_SCR_CONF); /* set y_sel = 1 */ di_gen |= ((DI_SYNC_HSYNC-1)<<28); } } else { /* Internal HSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_INT_HSYNC, h_total - 1, DI_SYNC_CLK, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); field1_offset = v_sync_width + v_start_width + height / 2 + v_end_width; if (sig.odd_field_first) { field0_offset = field1_offset - 1; field1_offset = 0; } v_total += v_start_width + v_end_width; /* HSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_HSYNC, h_total - 1, DI_SYNC_CLK, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 4); /* Field 1 VSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_VSYNC, v_total - 1, DI_SYNC_INT_HSYNC, field0_offset, field0_offset ? DI_SYNC_INT_HSYNC : DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 4); /* Active Field */ _ipu_di_sync_config(ipu, disp, DI_SYNC_AFIELD, field0_offset ? field0_offset : field1_offset - 2, DI_SYNC_INT_HSYNC, v_start_width + v_sync_width, DI_SYNC_INT_HSYNC, 2, DI_SYNC_VSYNC, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* Active Line */ _ipu_di_sync_config(ipu, disp, DI_SYNC_ALINE, 0, DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, height / 2, DI_SYNC_AFIELD, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* Active Pixel */ _ipu_di_sync_config(ipu, disp, DI_SYNC_APIXEL, 0, DI_SYNC_CLK, h_sync_width + h_start_width, DI_SYNC_CLK, width, DI_SYNC_ALINE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* DC VSYNC waveform */ vsync_cnt = DI_SYNC_COUNT_7; _ipu_di_sync_config(ipu, disp, DI_SYNC_COUNT_7, 0, DI_SYNC_INT_HSYNC, field1_offset, field1_offset ? DI_SYNC_INT_HSYNC : DI_SYNC_NONE, 1, DI_SYNC_VSYNC, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* Field 0 VSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_COUNT_8, v_total - 1, DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* ??? */ _ipu_di_sync_config(ipu, disp, DI_SYNC_COUNT_9, v_total - 1, (DI_SYNC_HSYNC - 1), 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 6, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); reg = ipu_di_read(ipu, disp, DI_SW_GEN1(9)); reg |= 0x8000; ipu_di_write(ipu, disp, reg, DI_SW_GEN1(9)); ipu_di_write(ipu, disp, v_sync_width + v_start_width + v_end_width + height / 2 - 1, DI_SCR_CONF); } if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { /* Init template microcode */ if(pixel_fmt == IPU_PIX_FMT_BT656) { _ipu_dc_setup_bt656_interlaced(ipu, map[0], map[1], map[2], 0, g_di_msb, bt656_h_start_width, bt656_v_start_width_field0, bt656_v_end_width_field0, bt656_v_start_width_field1, bt656_v_end_width_field1); } else { _ipu_dc_setup_bt656_interlaced(ipu, map[0], map[1], map[2], 1, g_di_msb, bt656_h_start_width, bt656_v_start_width_field0, bt656_v_end_width_field0, bt656_v_start_width_field1, bt656_v_end_width_field1); } ipu_dc_write(ipu, (width - 1), DC_UGDE_3(disp)); if (sig.Hsync_pol) di_gen |= DI_GEN_POLARITY_2; if (sig.Vsync_pol) di_gen |= DI_GEN_POLARITY_3; } else { int mc = disp ? DC_MCODE_DI1 : DC_MCODE_DI0; /* Init template microcode */ _ipu_dc_write_tmpl(ipu, mc + MCI_I, WROD, 0, map[0], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); if ((pixel_fmt == IPU_PIX_FMT_YUYV) || (pixel_fmt == IPU_PIX_FMT_UYVY) || (pixel_fmt == IPU_PIX_FMT_YVYU) || (pixel_fmt == IPU_PIX_FMT_VYUY)) { _ipu_dc_write_tmpl(ipu, mc + MCI_EVEN_UGDE, WROD, 0, map[0], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); _ipu_dc_write_tmpl(ipu, mc + MCI_ODD_UGDE, WROD, 0, map[1], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); /* configure user events according to DISP NUM */ ipu_dc_write(ipu, width - 1, DC_UGDE_3(disp)); } if (sig.Hsync_pol) di_gen |= DI_GEN_POLARITY_2; if (sig.Vsync_pol) di_gen |= DI_GEN_POLARITY_3; } } else { int mc = disp ? DC_MCODE_DI1 : DC_MCODE_DI0; /* Setup internal HSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_INT_HSYNC, h_total - 1, DI_SYNC_CLK, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* Setup external (delayed) HSYNC waveform */ _ipu_di_sync_config(ipu, disp, DI_SYNC_HSYNC, h_total - 1, DI_SYNC_CLK, div * v_to_h_sync, DI_SYNC_CLK, 0, DI_SYNC_NONE, 1, DI_SYNC_NONE, DI_SYNC_CLK, 0, h_sync_width * 2); /* Setup VSYNC waveform */ vsync_cnt = DI_SYNC_VSYNC; _ipu_di_sync_config(ipu, disp, DI_SYNC_VSYNC, v_total - 1, DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, 0, DI_SYNC_NONE, 1, DI_SYNC_NONE, DI_SYNC_INT_HSYNC, 0, v_sync_width * 2); ipu_di_write(ipu, disp, v_total - 1, DI_SCR_CONF); /* Setup active data waveform to sync with DC */ _ipu_di_sync_config(ipu, disp, DI_SYNC_ALINE, 0, DI_SYNC_HSYNC, v_sync_width + v_start_width, DI_SYNC_HSYNC, height, DI_SYNC_VSYNC, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); _ipu_di_sync_config(ipu, disp, DI_SYNC_APIXEL, 0, DI_SYNC_CLK, h_sync_width + h_start_width, DI_SYNC_CLK, width, DI_SYNC_ALINE, 0, DI_SYNC_NONE, DI_SYNC_NONE, 0, 0); /* set VGA delayed hsync/vsync no matter VGA enabled */ if (disp) { /* couter 7 for VGA delay HSYNC */ _ipu_di_sync_config(ipu, disp, DI_SYNC_COUNT_7, h_total - 1, DI_SYNC_CLK, 18, DI_SYNC_CLK, 0, DI_SYNC_NONE, 1, DI_SYNC_NONE, DI_SYNC_CLK, 0, h_sync_width * 2); /* couter 8 for VGA delay VSYNC */ _ipu_di_sync_config(ipu, disp, DI_SYNC_COUNT_8, v_total - 1, DI_SYNC_INT_HSYNC, 1, DI_SYNC_INT_HSYNC, 0, DI_SYNC_NONE, 1, DI_SYNC_NONE, DI_SYNC_INT_HSYNC, 0, v_sync_width * 2); } /* reset all unused counters */ if (!disp) { ipu_di_write(ipu, disp, 0, DI_SW_GEN0(7)); ipu_di_write(ipu, disp, 0, DI_SW_GEN1(7)); ipu_di_write(ipu, disp, 0, DI_STP_REP(7)); ipu_di_write(ipu, disp, 0, DI_SW_GEN0(8)); ipu_di_write(ipu, disp, 0, DI_SW_GEN1(8)); ipu_di_write(ipu, disp, 0, DI_STP_REP(8)); } ipu_di_write(ipu, disp, 0, DI_SW_GEN0(9)); ipu_di_write(ipu, disp, 0, DI_SW_GEN1(9)); ipu_di_write(ipu, disp, 0, DI_STP_REP(9)); /* Init template microcode */ if ((pixel_fmt == IPU_PIX_FMT_YUYV) || (pixel_fmt == IPU_PIX_FMT_UYVY) || (pixel_fmt == IPU_PIX_FMT_YVYU) || (pixel_fmt == IPU_PIX_FMT_VYUY)) { _ipu_dc_write_tmpl(ipu, mc + MCI_EVEN_UGDE, WROD, 0, map[0], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); _ipu_dc_write_tmpl(ipu, mc + MCI_ODD_UGDE, WROD, 0, map[1], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); /* configure user events according to DISP NUM */ ipu_dc_write(ipu, width - 1, DC_UGDE_3(disp)); } _ipu_dc_write_tmpl(ipu, mc + MCI_NL, WROD, 0, map[0], SYNC_WAVE, 8, DI_SYNC_APIXEL, 1, 0, 0); _ipu_dc_write_tmpl(ipu, mc + MCI_EOL, WROD, 0, map[0], SYNC_WAVE, 4, DI_SYNC_APIXEL, 0, 0, 0); _ipu_dc_write_tmpl(ipu, mc + MCI_EOL2, WRG, 0, map[0], NULL_WAVE, 0, DI_SYNC_CLK, 1, 0, 0); _ipu_dc_write_tmpl(ipu, mc + MCI_NEW_DATA, WROD, 0, map[0], SYNC_WAVE, 0, DI_SYNC_APIXEL, 1, 0, 0); if (sig.Hsync_pol) { di_gen |= DI_GEN_POLARITY_2; if (disp) di_gen |= DI_GEN_POLARITY_7; } if (sig.Vsync_pol) { di_gen |= DI_GEN_POLARITY_3; if (disp) di_gen |= DI_GEN_POLARITY_8; } } /* changinc DISP_CLK polarity: it can be wrong for some applications */ /* if ((pixel_fmt == IPU_PIX_FMT_YUYV) || (pixel_fmt == IPU_PIX_FMT_UYVY) || (pixel_fmt == IPU_PIX_FMT_YVYU) || (pixel_fmt == IPU_PIX_FMT_VYUY)) di_gen |= 0x00020000; */ if (!sig.clk_pol) di_gen |= DI_GEN_POLARITY_DISP_CLK; if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) { /* select external VSYNC for DI error recovery */ di_gen |= (1 << 10); } ipu_di_write(ipu, disp, di_gen, DI_GENERAL); if((pixel_fmt == IPU_PIX_FMT_BT656) || (pixel_fmt == IPU_PIX_FMT_BT1120)) ipu_di_write(ipu, disp, (--vsync_cnt << DI_VSYNC_SEL_OFFSET), DI_SYNC_AS_GEN); else ipu_di_write(ipu, disp, (--vsync_cnt << DI_VSYNC_SEL_OFFSET) | 0x00000002, DI_SYNC_AS_GEN); reg = ipu_di_read(ipu, disp, DI_POL); reg &= ~(DI_POL_DRDY_DATA_POLARITY | DI_POL_DRDY_POLARITY_15); if (sig.enable_pol) reg |= DI_POL_DRDY_POLARITY_15; if (sig.data_pol) reg |= DI_POL_DRDY_DATA_POLARITY; ipu_di_write(ipu, disp, reg, DI_POL); ipu_dc_write(ipu, width, DC_DISP_CONF2(DC_DISP_ID_SYNC(disp))); mutex_unlock(&ipu->mutex_lock); return 0; } EXPORT_SYMBOL(ipu_init_sync_panel); void ipu_uninit_sync_panel(struct ipu_soc *ipu, int disp) { uint32_t reg; uint32_t di_gen; if (disp != 0 && disp != 1) return; mutex_lock(&ipu->mutex_lock); di_gen = ipu_di_read(ipu, disp, DI_GENERAL); di_gen |= 0x3ff | DI_GEN_POLARITY_DISP_CLK; ipu_di_write(ipu, disp, di_gen, DI_GENERAL); reg = ipu_di_read(ipu, disp, DI_POL); reg |= 0x3ffffff; ipu_di_write(ipu, disp, reg, DI_POL); mutex_unlock(&ipu->mutex_lock); } EXPORT_SYMBOL(ipu_uninit_sync_panel); int ipu_init_async_panel(struct ipu_soc *ipu, int disp, int type, uint32_t cycle_time, uint32_t pixel_fmt, ipu_adc_sig_cfg_t sig) { int map[3]; int ret; u32 ser_conf = 0; u32 div; u32 di_clk = clk_get_rate(ipu->ipu_clk); /* round up cycle_time, then calcalate the divider using scaled math */ cycle_time += (1000000000UL / di_clk) - 1; div = (cycle_time * (di_clk / 256UL)) / (1000000000UL / 256UL); ret = _ipu_pixfmt_to_map(ipu, pixel_fmt, map); if (ret < 0) return ret; mutex_lock(&ipu->mutex_lock); if (type == IPU_PANEL_SERIAL) { ipu_di_write(ipu, disp, (div << 24) | ((sig.ifc_width - 1) << 4), DI_DW_GEN(ASYNC_SER_WAVE)); _ipu_di_data_pin_config(ipu, disp, ASYNC_SER_WAVE, DI_PIN_CS, 0, 0, (div * 2) + 1); _ipu_di_data_pin_config(ipu, disp, ASYNC_SER_WAVE, DI_PIN_SER_CLK, 1, div, div * 2); _ipu_di_data_pin_config(ipu, disp, ASYNC_SER_WAVE, DI_PIN_SER_RS, 2, 0, 0); _ipu_dc_write_tmpl(ipu, DC_MCODE_ASYNC_NEW_DATA, WROD, 0, map[0], ASYNC_SER_WAVE, 0, 0, 1, 0, 0); /* Configure DC for serial panel */ ipu_dc_write(ipu, 0x14, DC_DISP_CONF1(DC_DISP_ID_SERIAL)); if (sig.clk_pol) ser_conf |= DI_SER_CONF_SERIAL_CLK_POL; if (sig.data_pol) ser_conf |= DI_SER_CONF_SERIAL_DATA_POL; if (sig.rs_pol) ser_conf |= DI_SER_CONF_SERIAL_RS_POL; if (sig.cs_pol) ser_conf |= DI_SER_CONF_SERIAL_CS_POL; ipu_di_write(ipu, disp, ser_conf, DI_SER_CONF); } mutex_unlock(&ipu->mutex_lock); return 0; } EXPORT_SYMBOL(ipu_init_async_panel); /*! * This function sets the foreground and background plane global alpha blending * modes. This function also sets the DP graphic plane according to the * parameter of IPUv3 DP channel. * * @param ipu ipu handler * @param channel IPUv3 DP channel * * @param enable Boolean to enable or disable global alpha * blending. If disabled, local blending is used. * * @param alpha Global alpha value. * * @return Returns 0 on success or negative error code on fail */ int32_t ipu_disp_set_global_alpha(struct ipu_soc *ipu, ipu_channel_t channel, bool enable, uint8_t alpha) { uint32_t reg; uint32_t flow; bool bg_chan; if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) flow = DP_SYNC; else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) flow = DP_ASYNC0; else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) flow = DP_ASYNC1; else return -EINVAL; if (channel == MEM_BG_SYNC || channel == MEM_BG_ASYNC0 || channel == MEM_BG_ASYNC1) bg_chan = true; else bg_chan = false; _ipu_get(ipu); mutex_lock(&ipu->mutex_lock); if (bg_chan) { reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg & ~DP_COM_CONF_GWSEL, DP_COM_CONF(flow)); } else { reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg | DP_COM_CONF_GWSEL, DP_COM_CONF(flow)); } if (enable) { reg = ipu_dp_read(ipu, DP_GRAPH_WIND_CTRL(flow)) & 0x00FFFFFFL; ipu_dp_write(ipu, reg | ((uint32_t) alpha << 24), DP_GRAPH_WIND_CTRL(flow)); reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg | DP_COM_CONF_GWAM, DP_COM_CONF(flow)); } else { reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg & ~DP_COM_CONF_GWAM, DP_COM_CONF(flow)); } reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); mutex_unlock(&ipu->mutex_lock); _ipu_put(ipu); return 0; } EXPORT_SYMBOL(ipu_disp_set_global_alpha); /*! * This function sets the transparent color key for SDC graphic plane. * * @param ipu ipu handler * @param channel Input parameter for the logical channel ID. * * @param enable Boolean to enable or disable color key * * @param colorKey 24-bit RGB color for transparent color key. * * @return Returns 0 on success or negative error code on fail */ int32_t ipu_disp_set_color_key(struct ipu_soc *ipu, ipu_channel_t channel, bool enable, uint32_t color_key) { uint32_t reg, flow; int y, u, v; int red, green, blue; if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) flow = DP_SYNC; else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) flow = DP_ASYNC0; else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) flow = DP_ASYNC1; else return -EINVAL; _ipu_get(ipu); mutex_lock(&ipu->mutex_lock); ipu->color_key_4rgb = true; /* Transform color key from rgb to yuv if CSC is enabled */ if (((ipu->fg_csc_type == RGB2YUV) && (ipu->bg_csc_type == YUV2YUV)) || ((ipu->fg_csc_type == YUV2YUV) && (ipu->bg_csc_type == RGB2YUV)) || ((ipu->fg_csc_type == YUV2YUV) && (ipu->bg_csc_type == YUV2YUV)) || ((ipu->fg_csc_type == YUV2RGB) && (ipu->bg_csc_type == YUV2RGB))) { dev_dbg(ipu->dev, "color key 0x%x need change to yuv fmt\n", color_key); red = (color_key >> 16) & 0xFF; green = (color_key >> 8) & 0xFF; blue = color_key & 0xFF; y = _rgb_to_yuv(0, red, green, blue); u = _rgb_to_yuv(1, red, green, blue); v = _rgb_to_yuv(2, red, green, blue); color_key = (y << 16) | (u << 8) | v; ipu->color_key_4rgb = false; dev_dbg(ipu->dev, "color key change to yuv fmt 0x%x\n", color_key); } if (enable) { reg = ipu_dp_read(ipu, DP_GRAPH_WIND_CTRL(flow)) & 0xFF000000L; ipu_dp_write(ipu, reg | color_key, DP_GRAPH_WIND_CTRL(flow)); reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg | DP_COM_CONF_GWCKE, DP_COM_CONF(flow)); } else { reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); ipu_dp_write(ipu, reg & ~DP_COM_CONF_GWCKE, DP_COM_CONF(flow)); } reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); mutex_unlock(&ipu->mutex_lock); _ipu_put(ipu); return 0; } EXPORT_SYMBOL(ipu_disp_set_color_key); /*! * This function sets the gamma correction for DP output. * * @param ipu ipu handler * @param channel Input parameter for the logical channel ID. * * @param enable Boolean to enable or disable gamma correction. * * @param constk Gamma piecewise linear approximation constk coeff. * * @param slopek Gamma piecewise linear approximation slopek coeff. * * @return Returns 0 on success or negative error code on fail */ int32_t ipu_disp_set_gamma_correction(struct ipu_soc *ipu, ipu_channel_t channel, bool enable, int constk[], int slopek[]) { uint32_t reg, flow, i; if (channel == MEM_BG_SYNC || channel == MEM_FG_SYNC) flow = DP_SYNC; else if (channel == MEM_BG_ASYNC0 || channel == MEM_FG_ASYNC0) flow = DP_ASYNC0; else if (channel == MEM_BG_ASYNC1 || channel == MEM_FG_ASYNC1) flow = DP_ASYNC1; else return -EINVAL; _ipu_get(ipu); mutex_lock(&ipu->mutex_lock); for (i = 0; i < 8; i++) ipu_dp_write(ipu, (constk[2*i] & 0x1ff) | ((constk[2*i+1] & 0x1ff) << 16), DP_GAMMA_C(flow, i)); for (i = 0; i < 4; i++) ipu_dp_write(ipu, (slopek[4*i] & 0xff) | ((slopek[4*i+1] & 0xff) << 8) | ((slopek[4*i+2] & 0xff) << 16) | ((slopek[4*i+3] & 0xff) << 24), DP_GAMMA_S(flow, i)); reg = ipu_dp_read(ipu, DP_COM_CONF(flow)); if (enable) { if ((ipu->bg_csc_type == RGB2YUV) || (ipu->bg_csc_type == YUV2YUV)) reg |= DP_COM_CONF_GAMMA_YUV_EN; else reg &= ~DP_COM_CONF_GAMMA_YUV_EN; ipu_dp_write(ipu, reg | DP_COM_CONF_GAMMA_EN, DP_COM_CONF(flow)); } else ipu_dp_write(ipu, reg & ~DP_COM_CONF_GAMMA_EN, DP_COM_CONF(flow)); reg = ipu_cm_read(ipu, IPU_SRM_PRI2) | 0x8; ipu_cm_write(ipu, reg, IPU_SRM_PRI2); mutex_unlock(&ipu->mutex_lock); _ipu_put(ipu); return 0; } EXPORT_SYMBOL(ipu_disp_set_gamma_correction); /*! * This function sets the window position of the foreground or background plane. * modes. * * @param ipu ipu handler * @param channel Input parameter for the logical channel ID. * * @param x_pos The X coordinate position to place window at. * The position is relative to the top left corner. * * @param y_pos The Y coordinate position to place window at. * The position is relative to the top left corner. * * @return Returns 0 on success or negative error code on fail */ int32_t _ipu_disp_set_window_pos(struct ipu_soc *ipu, ipu_channel_t channel, int16_t x_pos, int16_t y_pos) { u32 reg; uint32_t flow = 0; uint32_t dp_srm_shift; if ((channel == MEM_FG_SYNC) || (channel == MEM_BG_SYNC)) { flow = DP_SYNC; dp_srm_shift = 3; } else if (channel == MEM_FG_ASYNC0) { flow = DP_ASYNC0; dp_srm_shift = 5; } else if (channel == MEM_FG_ASYNC1) { flow = DP_ASYNC1; dp_srm_shift = 7; } else return -EINVAL; ipu_dp_write(ipu, (x_pos << 16) | y_pos, DP_FG_POS(flow)); if (ipu_is_channel_busy(ipu, channel)) { /* controled by FSU if channel enabled */ reg = ipu_cm_read(ipu, IPU_SRM_PRI2) & (~(0x3 << dp_srm_shift)); reg |= (0x1 << dp_srm_shift); ipu_cm_write(ipu, reg, IPU_SRM_PRI2); } else { /* disable auto swap, controled by MCU if channel disabled */ reg = ipu_cm_read(ipu, IPU_SRM_PRI2) & (~(0x3 << dp_srm_shift)); ipu_cm_write(ipu, reg, IPU_SRM_PRI2); } return 0; } int32_t ipu_disp_set_window_pos(struct ipu_soc *ipu, ipu_channel_t channel, int16_t x_pos, int16_t y_pos) { int ret; _ipu_get(ipu); mutex_lock(&ipu->mutex_lock); ret = _ipu_disp_set_window_pos(ipu, channel, x_pos, y_pos); mutex_unlock(&ipu->mutex_lock); _ipu_put(ipu); return ret; } EXPORT_SYMBOL(ipu_disp_set_window_pos); int32_t _ipu_disp_get_window_pos(struct ipu_soc *ipu, ipu_channel_t channel, int16_t *x_pos, int16_t *y_pos) { u32 reg; uint32_t flow = 0; if (channel == MEM_FG_SYNC) flow = DP_SYNC; else if (channel == MEM_FG_ASYNC0) flow = DP_ASYNC0; else if (channel == MEM_FG_ASYNC1) flow = DP_ASYNC1; else return -EINVAL; reg = ipu_dp_read(ipu, DP_FG_POS(flow)); *x_pos = (reg >> 16) & 0x7FF; *y_pos = reg & 0x7FF; return 0; } int32_t ipu_disp_get_window_pos(struct ipu_soc *ipu, ipu_channel_t channel, int16_t *x_pos, int16_t *y_pos) { int ret; _ipu_get(ipu); mutex_lock(&ipu->mutex_lock); ret = _ipu_disp_get_window_pos(ipu, channel, x_pos, y_pos); mutex_unlock(&ipu->mutex_lock); _ipu_put(ipu); return ret; } EXPORT_SYMBOL(ipu_disp_get_window_pos); void ipu_reset_disp_panel(struct ipu_soc *ipu) { uint32_t tmp; tmp = ipu_di_read(ipu, 1, DI_GENERAL); ipu_di_write(ipu, 1, tmp | 0x08, DI_GENERAL); msleep(10); /* tRES >= 100us */ tmp = ipu_di_read(ipu, 1, DI_GENERAL); ipu_di_write(ipu, 1, tmp & ~0x08, DI_GENERAL); msleep(60); return; } EXPORT_SYMBOL(ipu_reset_disp_panel); void ipu_disp_init(struct ipu_soc *ipu) { ipu->fg_csc_type = ipu->bg_csc_type = CSC_NONE; ipu->color_key_4rgb = true; _ipu_dmfc_init(ipu, DMFC_NORMAL, 1); }
31.925269
131
0.668445
[ "transform" ]
1bace22ba0b1c14bcd2fd824df5cd384f8a634a8
2,672
h
C
Benchmarks/FeatureClassification/WorkerThreadInfo.h
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
8
2015-03-16T18:16:35.000Z
2020-10-30T06:35:31.000Z
Benchmarks/FeatureClassification/WorkerThreadInfo.h
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
null
null
null
Benchmarks/FeatureClassification/WorkerThreadInfo.h
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
3
2016-03-17T08:27:13.000Z
2020-10-30T06:46:50.000Z
/* * Copyright (c) 2006-2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * */ /* * WorkerThreadInfo.h * * Created on: Apr 30, 2011 * Author: jlclemon */ #ifndef WORKERTHREADINFO_H_ #define WORKERTHREADINFO_H_ #include "ThreadManager.h" #include "MultiThreadedMatResult.h" #include "FeatureClassification.hpp" #include "MultiThreadAlgorithmData.h" struct FeatureClassificationConfig; struct WorkerThreadInfo { Thread * myThread; FeatureClassificationConfig * myFeatureClassificationInfo; int verticalThreadId; int horizontalThreadId; int descriptorStartIndex; Mat descriptorsToProcess; bool standAlone; bool coordinator; bool done; vector<KeyPoint> keyPointsToProcess; MultiThreadedMatchResult * multiThreadMatchResults; MultiThreadedMatResult* multiThreadResults; FeatureClassificationConfig * featureClassificationInfo; ThreadManager * threadManager; Mat * allTrainDescriptors; Mat * allQueryDescriptors; vector<KeyPoint> * allTrainKeypoints; vector<KeyPoint> * allQueryKeypoints; Mat * trainImage; Mat * queryImage; struct MultiThreadAlgorithmData * multiThreadAlgorithmData; }; #endif /* WORKERTHREADINFO_H_ */
31.809524
73
0.787051
[ "vector" ]
1bb5897db693d27068b94a94f9325dc8b172452a
462
c
C
DayZSurvival.chernarusplus/ScriptedMods/Modules/CustomBuildings/SpawnedBuilding.c
ChawDinky/VanillaPlusPlus
0b22645acd0fd0b4e4558a1b058a92c74963cab5
[ "0BSD" ]
2
2020-06-17T21:31:03.000Z
2021-01-31T17:15:28.000Z
DayZSurvival.chernarusplus/ScriptedMods/Modules/CustomBuildings/SpawnedBuilding.c
ChawDinky/VanillaPlusPlus
0b22645acd0fd0b4e4558a1b058a92c74963cab5
[ "0BSD" ]
null
null
null
DayZSurvival.chernarusplus/ScriptedMods/Modules/CustomBuildings/SpawnedBuilding.c
ChawDinky/VanillaPlusPlus
0b22645acd0fd0b4e4558a1b058a92c74963cab5
[ "0BSD" ]
null
null
null
class SpawnedBuilding { string m_name; vector m_location; vector orientation; void SpawnedBuilding(string building_name, vector location, vector orientation) { this.m_name = building_name; this.m_location = location; this.orientation = orientation; } void ~SpawnedBuilding() { } string getName() { return this.m_name; } vector getLocation() { return this.m_location; } vector getOrientation() { return this.orientation; } };
14
80
0.71645
[ "vector" ]
1bbe6a425fa9a426c91309021eb29c961d8ed779
6,090
h
C
engine/runtime/engine/include/component.h
aejsmith/orion
0e172e1829c0f4522a4af1ddb4afcd2ed046ca49
[ "ISC" ]
5
2015-08-02T18:20:19.000Z
2020-03-10T10:39:51.000Z
engine/runtime/engine/include/component.h
aejsmith/orion
0e172e1829c0f4522a4af1ddb4afcd2ed046ca49
[ "ISC" ]
1
2018-04-25T15:12:35.000Z
2018-04-25T15:12:35.000Z
engine/runtime/engine/include/component.h
aejsmith/orion
0e172e1829c0f4522a4af1ddb4afcd2ed046ca49
[ "ISC" ]
null
null
null
/* * Copyright (C) 2015-2016 Alex Smith * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * @file * @brief Component class. */ #pragma once #include "engine/entity.h" #include "engine/world.h" class Component; class Entity; /** * Class implementing a component. * * Components implement the behaviour of an entity in the game world. An Entity * only provides some minimal properties such as a transformation. All other * functionality is implemented in components which are attached to an Entity. * * Components have a number of hook functions that get called from the Entity * to which they are attached, which can be overridden by derived classes to * implement their behaviour. * * Components should always be created through Entity::createComponent(). This * constructs the component and handles attaching it to the entity. They should * only be destroyed by calling destroy(). The function call sequence for * creating a component is: * * Entity::createComponent() * |-> constructors * |-> Entity::addComponent() * |-> Component::transformed() * * The call sequence for destroying a component is: * * Component::destroy() * |-> Component::deactivated() (if currently active) * |-> Entity::removeComponent() * |-> destructors (once no other references remain) * * As can be seen, this ensures that the hook functions are called when the * component is fully constructed. */ class Component : public Object { public: CLASS(); void destroy(); VPROPERTY(bool, active); void setActive(bool active); /** @return Entity that the component is attached to. */ Entity *entity() const { return m_entity; } /** @return Whether the component is active. */ bool active() const { return m_active; } bool activeInWorld() const; /** * Entity property shortcut functions. */ /** @return World that the entity belongs to. */ World *world() const { return m_entity->world(); } /** * Get a world system. * * Gets a global per-world system for the world this component belongs to. * If the world doesn't yet have the specified system, it will be created. * * @tparam Type Type of the system. * * @return Reference to the world system. */ template <typename Type> Type &getSystem() { return m_entity->world()->getSystem<Type>(); } /** @return Transformation for the entity. */ const Transform &transform() const { return m_entity->transform(); } /** @return Entity relative position. */ const glm::vec3 &position() const { return m_entity->position(); } /** @return Entity relative orientation. */ const glm::quat &orientation() const { return m_entity->orientation(); } /** @return Entity relative scale. */ const glm::vec3 &scale() const { return m_entity->scale(); } /** @return Entity local-to-world transformation matrix. */ const Transform &worldTransform() const { return m_entity->worldTransform(); } /** @return Entity absolute position. */ const glm::vec3 &worldPosition() const { return m_entity->worldPosition(); } /** @return Entity absolute orientation. */ const glm::quat &worldOrientation() const { return m_entity->worldOrientation(); } /** @return Entity absolute scale. */ const glm::vec3 &worldScale() const { return m_entity->worldScale(); } /** * Hook functions. */ /** Called when the entity's transformation is changed. * @param changed Flags indicating changes made (see * Entity::TransformFlags). */ virtual void transformed(unsigned changed) {} /** Called when the component becomes active in the world. */ virtual void activated() {} /** Called when the component becomes inactive in the world. */ virtual void deactivated() {} /** * Update the component. * * Called every frame while the component is active in the world to perform * per-frame updates. The supplied time delta is the time since the last * call to this function. This function is not called at a fixed interval, * it is dependent on the frame rate. Therefore, the time delta should be * used to make updates independent of the frame rate. * * @param dt Time delta since last update in seconds. */ virtual void tick(float dt) {} protected: Component(); ~Component(); void serialise(Serialiser &serialiser) const override; void deserialise(Serialiser &serialiser) override; private: EntityPtr m_entity; /**< Entity that the component is attached to. */ bool m_active; /**< Whether the component is active. */ friend class Entity; }; /** Type of a pointer to a component. */ using ComponentPtr = ReferencePtr<Component>; /* * Entity template methods which are dependent on Component's definition. */ /** Call the specified function on all active components. * @param func Function to call. */ template <typename Func> inline void Entity::visitActiveComponents(Func func) { for (Component *component : m_components) { if (component->active()) func(component); } }
35.823529
95
0.659278
[ "object", "transform" ]
1bdca8cc4b8a94fda7d5f871a7a535157a376cd5
6,016
h
C
inc/Topology.h
I3ck/lib_2d
b13267e8b06f8b1908f6681a983bddf5c10ca05a
[ "MIT" ]
51
2015-01-26T23:09:10.000Z
2021-12-16T05:43:59.000Z
inc/Topology.h
I3ck/lib_2d
b13267e8b06f8b1908f6681a983bddf5c10ca05a
[ "MIT" ]
1
2016-01-08T11:38:42.000Z
2016-01-09T12:10:30.000Z
inc/Topology.h
I3ck/lib_2d
b13267e8b06f8b1908f6681a983bddf5c10ca05a
[ "MIT" ]
1
2017-09-28T09:06:45.000Z
2017-09-28T09:06:45.000Z
/* Copyright (c) 2015 Martin Buck 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. */ /** * \file Topology.h * \author Martin Buck * \date October 2015 * \version 1.0 * \brief contains the class Topology which defines ordered points / lines / triangles / quads etc. */ #ifndef TOPOLOGY_H_INCLUDED #define TOPOLOGY_H_INCLUDED #include <vector> #include <set> #include <fstream> #include <algorithm> #include <utility> #include <array> #include "Point.h" namespace lib_2d { template <size_t ELEMENTSIZE> class Topology { using Element = std::array<size_t, ELEMENTSIZE>; protected: std::vector < Element > elements; public: Topology(){} Topology(Element e) { elements.push_back(e); } Topology(unsigned int nElements) { elements.reserve(nElements); } template<class InputIterator> Topology(InputIterator first, InputIterator last) { while(first != last) { elements.push_back(*first); ++first; } } ~Topology(){} //------------------------------------------------------------------------------ Topology& push_back(const Element &e) { elements.push_back(e); return *this; } Topology& push_back(const Topology &other) { for(auto e = other.cbegin(); e != other.cend(); ++e) elements.push_back(*e); return *this; } Topology& emplace_back(Element e) { elements.emplace_back(e); return *this; } Topology& emplace_back(const Topology &other) { for(auto e : other) elements.emplace_back(e); return *this; } //------------------------------------------------------------------------------ Topology& pop_back() { elements.pop_back(); return *this; } //------------------------------------------------------------------------------ inline size_t n_elements() const { return elements.size(); } //------------------------------------------------------------------------------ Element first() const { return elements[0]; } Element last() const { return elements[elements.size() - 1]; } //------------------------------------------------------------------------------ bool empty() const { return elements.empty(); } //------------------------------------------------------------------------------ void reserve_elements(size_t i) { elements.reserve(i); } //------------------------------------------------------------------------------ Topology& clear() { elements.clear(); return *this; } //------------------------------------------------------------------------------ Topology& reverse() { ///@todo several versions (reverse element order, reverse each element) std::reverse(elements.begin(), elements.end()); return *this; } //------------------------------------------------------------------------------ bool equal_to (const Topology &other) const { if(elements.size() != other.elements.size()) return false; for(size_t i = 0; i < elements.size(); ++i) { if(elements[i] != elements.top[i]) return false; } return true; } //------------------------------------------------------------------------------ Topology& remove_from(unsigned int index) { if(n_elements() < index) return *this; elements.erase(elements.begin() + index, elements.end()); return *this; } Topology& remove_until(unsigned int index) { if(n_elements() < index) elements.clear(); else elements.erase(elements.begin(), elements.begin() + index); return *this; } //------------------------------------------------------------------------------ typename std::vector <Element>::iterator begin() { return elements.begin(); } typename std::vector <Element>::iterator end() { return elements.end(); } typename std::vector <Element>::const_iterator cbegin() const { return elements.cbegin(); } typename std::vector <Element>::const_iterator cend() const { return elements.cend(); } typename std::vector <Element>::reverse_iterator rbegin() { return elements.rbegin(); } typename std::vector <Element>::reverse_iterator rend() { return elements.rend(); } //------------------------------------------------------------------------------ Element operator [] (unsigned int i) const { return elements[i]; } Element& operator [] (unsigned int i) { return elements[i]; } Topology& operator += (const Topology &other) { push_back(other); return *this; } Topology& operator += (Element other) { push_back(other); return *this; } }; } //lib_2d #endif // TOPOLOGY_H_INCLUDED
27.59633
151
0.519614
[ "vector" ]
1be41fd1e2173f96a2ebd85f088b939831d56696
1,218
h
C
inc/observer.h
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
3
2016-12-14T01:22:27.000Z
2020-04-07T05:15:04.000Z
inc/observer.h
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
7
2017-01-12T15:20:57.000Z
2017-07-02T16:09:37.000Z
inc/observer.h
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
1
2020-04-07T05:15:05.000Z
2020-04-07T05:15:05.000Z
#pragma once #include <Eigen/Core> #include "types.h" #include "discrete_linear.h" namespace observer { using real_t = model::real_t; /* This class cannot be instantiated and does not allow polymorphic deletion through a base pointer.*/ class ObserverBase { protected: ~ObserverBase() { } }; template <typename T> class Observer : private ObserverBase { static_assert(std::is_base_of<model::DiscreteLinearBase, T>::value, "Invalid template parameter type for Observer"); public: using model_t = T; using state_t = typename T::state_t; using input_t = typename T::input_t; using measurement_t = typename T::output_t; virtual void reset() = 0; virtual void update_state(const input_t& u, const measurement_t& z) = 0; virtual void set_state(const state_t& x) { m_x = m_system.normalize_state(x); } virtual T& system() const { return m_system; } virtual real_t dt() const { return m_system.dt(); } virtual const state_t& state() const { return m_x; } protected: T& m_system; state_t m_x; Observer(T& system, const state_t& x) : m_system(system), m_x(x) { } }; } // namespace observer
29
120
0.66092
[ "model" ]
1be605f2bce8409e3883e4611c6c34f900ce0cb3
654
h
C
src/parameters/member.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
null
null
null
src/parameters/member.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
5
2015-11-04T21:56:04.000Z
2015-11-10T19:58:18.000Z
src/parameters/member.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
null
null
null
#ifndef ICAL_PARAMETERS_MEMBER_H #define ICAL_PARAMETERS_MEMBER_H #include <ostream> #include <vector> #include <regex> #include "core/genericpropertyparameter.h" #include "parserexception.h" namespace ical { namespace parameters { class Member { private: std::vector<std::string> value; public: static const std::string NAME; Member() {} const std::vector<std::string> &getValue() const noexcept { return value; } void print(std::ostream &out) const; static Member parse(const core::WithPos<core::GenericPropertyParameter> &generic); }; } // namespace parameters } // namespace ical #endif // ICAL_PARAMETERS_MEMBER_H
18.685714
86
0.730887
[ "vector" ]
1bfc7531d8f5cf393ed5d44612639eee2b05b07a
3,660
h
C
include/dynamic.h
radiasoft/electroncooling
7fd086442916bd8fd73580a574280fb7d0f5d598
[ "Unlicense" ]
null
null
null
include/dynamic.h
radiasoft/electroncooling
7fd086442916bd8fd73580a574280fb7d0f5d598
[ "Unlicense" ]
8
2019-11-09T00:10:09.000Z
2021-08-13T19:53:55.000Z
include/dynamic.h
radiasoft/electroncooling
7fd086442916bd8fd73580a574280fb7d0f5d598
[ "Unlicense" ]
null
null
null
#ifndef DYNAMIC_H #define DYNAMIC_H #include <fstream> #include <iostream> #include <string> #include "beam.h" #include "ecooling.h" #include "ibs.h" #include "ring.h" #include "cooler.h" using std::string; enum class DynamicModel {RMS, PARTICLE, MODEL_BEAM = PARTICLE, TURN_BY_TURN}; class Luminosity { double dx_ = 0; double dy_ = 0; double np_1_ = 0; double np_2_ = 0; double freq_ = 1; double sigma_x1_ = 0; double sigma_y1_ = 0; double sigma_x2_ = 0; double sigma_y2_ = 0; double bet_x1_ = 0; double bet_y1_ = 0; double bet_x2_ = 0; double bet_y2_ = 0; double geo_emit_x1_ = 0; double geo_emit_y1_ = 0; double geo_emit_x2_ = 0; double geo_emit_y2_ = 0; bool use_ion_emittance_ = true; public: void set_distance(double dx, double dy){dx_=dx; dy_=dy;} void set_freq(double f){freq_=f;} void set_use_ion_emit(bool b){use_ion_emittance_ = b;} void set_geo_emit(double emit_x, double emit_y, int i); void set_beam_size(double sigma_x, double sigma_y, int i); void set_particle_number(double n, int i); void set_bet(double bet_x, double bet_y, int i); bool use_ion_emittance(){return use_ion_emittance_;} double luminosity(); }; class DynamicParas{ double time_; int n_step_; int n_sample_; double dt_; bool ibs_ = true; bool ecool_ = true; bool fixed_bunch_length_ = false; bool reset_time_ = true; bool overwrite_ = true; bool calc_luminosity_ = false; int output_intvl_ = 1; int ion_save_intvl_ = -1; string filename_ = "output_dynamic.txt"; DynamicModel model_ = DynamicModel::RMS; bool test_ = false; // int n_sample_; public: Twiss twiss_ref; int n_step(){return n_step_;} double time(){return time_;} double dt(){return dt_;} bool ibs(){return ibs_;} bool ecool(){return ecool_;} bool fixed_bunch_length(){return fixed_bunch_length_;} bool reset_time(){return reset_time_;} bool overwrite(){return overwrite_;} bool calc_lum(){return calc_luminosity_;} bool test(){return test_;} int output_intval(){return output_intvl_;} int ion_save_intvl(){return ion_save_intvl_;} int n_sample(){return n_sample_;} // int n_sample() {assert(model_==DynamicModel::MODEL_BEAM); return n_sample_;}; DynamicModel model(){return model_;} void set_model(DynamicModel model){model_ = model; } void set_ion_save(int x){ion_save_intvl_ = x; } void set_output_file(string filename){filename_ = filename; } void set_output_intvl(int x){output_intvl_ = x; } void set_n_sample(int x){n_sample_ = x; } void set_fixed_bunch_length(bool b){fixed_bunch_length_ = b; } void set_reset_time(bool b){reset_time_ = b; } void set_overwrite(bool b) {overwrite_ = b; } void set_calc_lum(bool b) {calc_luminosity_ = b; } void set_test(bool b) {test_ = b; } string output_file(){return filename_;} DynamicParas(double time, int n_step):time_(time),n_step_(n_step){dt_ = time_/n_step_;} DynamicParas(double time, int n_step, bool ibs, bool ecool): time_(time),n_step_(n_step),ibs_(ibs),ecool_(ecool){dt_ = time_/n_step_;} DynamicParas(double time, int n_step, bool ibs, bool ecool, DynamicModel model): time_(time),n_step_(n_step),ibs_(ibs),ecool_(ecool), model_(model){dt_ = time_/n_step_;} }; //int dynamic(Beam &ion, Cooler &cooler, EBeam &ebeam, Ring &ring, std::ofstream &outfile); int dynamic(Beam &ion, Cooler &cooler, EBeam &ebeam, Ring &ring); #endif // DYNAMIC_H
35.192308
97
0.668579
[ "model" ]
40032ba3a2ff72a0f2fbc4a318c97382a17031ff
499
h
C
src/cpp/pacmangameconsole/enums.h
mwpowellhtx/simple-pacman-game
80d8fa4cc33a2041da6a1e98811071615eb8d64d
[ "MIT" ]
null
null
null
src/cpp/pacmangameconsole/enums.h
mwpowellhtx/simple-pacman-game
80d8fa4cc33a2041da6a1e98811071615eb8d64d
[ "MIT" ]
null
null
null
src/cpp/pacmangameconsole/enums.h
mwpowellhtx/simple-pacman-game
80d8fa4cc33a2041da6a1e98811071615eb8d64d
[ "MIT" ]
null
null
null
#ifndef _ENUMS_H_ #define _ENUMS_H_ #include <vector> namespace pacman { enum board_state : char { one = '1' , two = '2' , wall = '#' , pill = '*' , empty = ' ' }; extern bool is_torsoidal(board_state value); enum move_choice { none , up , down , left , right }; extern std::vector<move_choice> get_move_choices(); extern board_state to_board_state(char value); } #endif //_ENUMS_H_
15.59375
55
0.533066
[ "vector" ]
400619002e08d8536dd682ff1192228194b92344
19,194
c
C
usr/src/lib/udapl/udapl_tavor/common/dapl_name_service.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/lib/udapl/udapl_tavor/common/dapl_name_service.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/lib/udapl/udapl_tavor/common/dapl_name_service.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2002-2003, Network Appliance, Inc. All rights reserved. */ /* * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. */ /* * * MODULE: dapl_name_service.c * * PURPOSE: Provide simple, file base name services in the absence * of DNS hooks for a particular transport type. If an * InfiniBand implementation supports IPoIB, this should * not be used. * * Description: Interfaces in this file are completely described in * dapl_name_service.h */ /* * Include files for setting up a network name */ #include "dapl.h" #include "dapl_name_service.h" #include <netinet/in.h> #include <sys/sockio.h> #include <net/if.h> #include <net/if_dl.h> #include <net/if_arp.h> #include <net/if_types.h> #include <arpa/inet.h> #include <poll.h> #include <ibd/ibd.h> #ifdef IBHOSTS_NAMING #define MAP_FILE "/etc/dapl/ibhosts" #define MAX_GID_ENTRIES 32 DAPL_GID_MAP g_gid_map_table[MAX_GID_ENTRIES]; DAT_RETURN dapli_ns_create_gid_map(void); DAT_RETURN dapli_ns_add_address(IN DAPL_GID_MAP *gme); #endif /* IBHOSTS_NAMING */ /* * dapls_ns_init * * Initialize naming services * * Input: * none * * Output: * none * * Returns: * DAT_SUCCESS * DAT_INVALID_PARAMETER */ DAT_RETURN dapls_ns_init(void) { DAT_RETURN dat_status; dat_status = DAT_SUCCESS; #ifdef IBHOSTS_NAMING dat_status = dapli_ns_create_gid_map(); #endif /* IBHOSTS_NAMING */ return (dat_status); } #ifdef IBHOSTS_NAMING /* * dapls_create_gid_map() * * Read /usr/local/etc/ibhosts to obtain host names and GIDs. * Create a table containing IP addresses and GIDs which can * be used for lookups. * * This implementation is a simple method providing name services * when more advanced mechanisms do not exist. The proper way * to obtain these mappings is to use a name service such as is * provided by IPoIB on InfiniBand. * * Input: * device_name Name of device as reported by the provider * * Output: * none * * Returns: * char * to string number */ DAT_RETURN dapli_ns_create_gid_map(void) { FILE *f; ib_gid_t gid; char hostname[128]; int rc; struct addrinfo *addr; struct sockaddr_in *si; DAPL_GID_MAP gmt; f = fopen(MAP_FILE, "r"); if (f == NULL) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ERROR: Must have file <%s> " "for IP/GID mappings\n", MAP_FILE); return (DAT_ERROR(DAT_INTERNAL_ERROR, 0)); } rc = fscanf(f, "%s " F64x " " F64x, hostname, &gid.gid_prefix, &gid.gid_guid); while (rc != EOF) { rc = dapls_osd_getaddrinfo(hostname, &addr); if (rc != 0) { /* * hostname not registered in DNS, * provide a dummy value */ dapl_dbg_log(DAPL_DBG_TYPE_ERR, "WARNING: <%s> not registered in " "DNS, using dummy IP value\n", hostname); gmt.ip_address = 0x01020304; } else { /* * Load into the ip/gid mapping table */ si = (struct sockaddr_in *)addr->ai_addr; if (AF_INET == addr->ai_addr->sa_family) { gmt.ip_address = si->sin_addr.s_addr; } else { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "WARNING: <%s> Address family " "not supported, using dummy " "IP value\n", hostname); gmt.ip_address = 0x01020304; } dapls_osd_freeaddrinfo(addr); } gmt.gid.gid_prefix = gid.gid_prefix; gmt.gid.gid_guid = gid.gid_guid; dapli_ns_add_address(&gmt); rc = fscanf(f, "%s " F64x " " F64x, hostname, &gid.gid_prefix, &gid.gid_guid); } (void) fclose(f); return (DAT_SUCCESS); } /* * dapli_ns_add_address * * Add a table entry to the gid_map_table. * * Input: * remote_ia_address remote IP address * gid pointer to output gid * * Output: * gid filled in GID * * Returns: * DAT_SUCCESS * DAT_INSUFFICIENT_RESOURCES * DAT_INVALID_PARAMETER */ DAT_RETURN dapli_ns_add_address( IN DAPL_GID_MAP *gme) { DAPL_GID_MAP *gmt; int count; gmt = g_gid_map_table; for (count = 0, gmt = g_gid_map_table; gmt->ip_address; gmt++) { count++; } if (count > MAX_GID_ENTRIES) { return (DAT_ERROR(DAT_INSUFFICIENT_RESOURCES, 0)); } *gmt = *gme; return (DAT_SUCCESS); } /* * dapls_ns_lookup_address * * Look up the provided IA_ADDRESS in the gid_map_table. Return * the gid if found. * * Input: * remote_ia_address remote IP address * gid pointer to output gid * timeout timeout in microseconds * * Output: * gid filled in GID * * Returns: * DAT_SUCCESS * DAT_INSUFFICIENT_RESOURCES * DAT_INVALID_PARAMETER */ DAT_RETURN dapls_ns_lookup_address( IN DAPL_IA *ia_ptr, IN DAT_IA_ADDRESS_PTR remote_ia_address, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid) { DAPL_GID_MAP *gmt; struct sockaddr_in *si; /* unused here */ ia_ptr = ia_ptr; si = (struct sockaddr_in *)remote_ia_address; for (gmt = g_gid_map_table; gmt->ip_address; gmt++) { if (gmt->ip_address == si->sin_addr.s_addr) { gid->gid_guid = gmt->gid.gid_guid; gid->gid_prefix = gmt->gid.gid_prefix; return (DAT_SUCCESS); } } return (DAT_ERROR(DAT_INVALID_PARAMETER, 0)); } #endif /* IBHOSTS_NAMING */ /* * utility function for printing a socket */ char * dapls_inet_ntop(struct sockaddr *addr, char *buf, size_t len) { void *addr_ptr; if (addr->sa_family == AF_INET) { /* LINTED: E_BAD_PTR_CAST_ALIGN */ addr_ptr = (void *)&((struct sockaddr_in *)addr)->sin_addr; } else if (addr->sa_family == AF_INET6) { /* LINTED: E_BAD_PTR_CAST_ALIGN */ addr_ptr = (void *)&((struct sockaddr_in6 *)addr)->sin6_addr; } else { if (len > strlen("bad address")) { (void) sprintf(buf, "bad address"); } return (buf); } return ((char *)inet_ntop(addr->sa_family, addr_ptr, buf, len)); } /* * dapls_ns_lookup_address * * translates an IP address into a GID * * Input: * ia_ptr pointer to IA object * remote_ia_address remote IP address * gid pointer to output gid * timeout timeout in microseconds * * Output: * gid filled in GID * * Returns: * DAT_SUCCESS * DAT_INVALID_ADDRRESS * DAT_INVALID_PARAMETER * DAT_INTERNAL_ERROR */ #define NS_MAX_RETRIES 60 DAT_RETURN dapls_ns_lookup_v4( IN DAPL_IA *ia_ptr, IN struct sockaddr_in *addr, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid); DAT_RETURN dapls_ns_lookup_v6( IN DAPL_IA *ia_ptr, IN struct sockaddr_in6 *addr, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid); static int dapls_ns_subnet_match_v4(int s, DAPL_IA *ia_ptr, struct sockaddr_in *addr); static int dapls_ns_subnet_match_v6(int s, DAPL_IA *ia_ptr, struct sockaddr_in6 *addr); static int dapls_ns_send_packet_v6(int s, struct sockaddr_in6 *addr); static int dapls_ns_resolve_addr(int af, struct sockaddr *addr, DAT_TIMEOUT timeout); DAT_RETURN dapls_ns_lookup_address( IN DAPL_IA *ia_ptr, IN DAT_IA_ADDRESS_PTR remote_ia_address, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid) { DAT_RETURN dat_status; struct sockaddr *sock = (struct sockaddr *)remote_ia_address; if (sock->sa_family == AF_INET) { dat_status = dapls_ns_lookup_v4(ia_ptr, /* LINTED: E_BAD_PTR_CAST_ALIGN */ (struct sockaddr_in *)sock, timeout, gid); } else if (sock->sa_family == AF_INET6) { dat_status = dapls_ns_lookup_v6(ia_ptr, /* LINTED: E_BAD_PTR_CAST_ALIGN */ (struct sockaddr_in6 *)sock, timeout, gid); } else { dat_status = DAT_INVALID_PARAMETER; } return (dat_status); } DAT_RETURN dapls_ns_lookup_v4( IN DAPL_IA *ia_ptr, IN struct sockaddr_in *addr, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid) { struct xarpreq ar; struct sockaddr_in *sin; uchar_t *mac; int s, retries = 0; (void) dapl_os_memzero(&ar, sizeof (ar)); sin = (struct sockaddr_in *)&ar.xarp_pa; sin->sin_family = AF_INET; sin->sin_addr.s_addr = addr->sin_addr.s_addr; ar.xarp_ha.sdl_family = AF_LINK; s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v4: socket: %s\n", strerror(errno)); return (DAT_INTERNAL_ERROR); } if (dapls_ns_subnet_match_v4(s, ia_ptr, addr) != 0) { (void) close(s); return (DAT_INVALID_ADDRESS); } again:; if (ioctl(s, SIOCGXARP, (caddr_t)&ar) < 0) { /* * if SIOCGXARP failed, we force the ARP * cache to be filled by connecting to the * destination IP address. */ if (retries <= NS_MAX_RETRIES && dapls_ns_resolve_addr(AF_INET, (struct sockaddr *)addr, timeout) == 0) { retries++; goto again; } dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v4: giving up\n"); (void) close(s); return (DAT_ERROR(DAT_INVALID_ADDRESS, DAT_INVALID_ADDRESS_UNREACHABLE)); } if ((ar.xarp_flags & ATF_COM) == 0 && ar.xarp_ha.sdl_type == IFT_IB && retries <= NS_MAX_RETRIES) { /* * we get here if arp resolution is still incomplete */ retries++; (void) sleep(1); goto again; } (void) close(s); mac = (uchar_t *)LLADDR(&ar.xarp_ha); if (ar.xarp_flags & ATF_COM && ar.xarp_ha.sdl_type == IFT_IB && ar.xarp_ha.sdl_alen >= sizeof (ipoib_mac_t)) { ib_gid_t tmp_gid; /* LINTED: E_BAD_PTR_CAST_ALIGN */ (void) dapl_os_memcpy(&tmp_gid, &((ipoib_mac_t *)mac)->ipoib_gidpref, sizeof (ib_gid_t)); /* * gids from the ARP table are in network order, convert * the gids from network order to host byte order */ gid->gid_prefix = BETOH_64(tmp_gid.gid_prefix); gid->gid_guid = BETOH_64(tmp_gid.gid_guid); } else { int i, len; len = ar.xarp_ha.sdl_alen; dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v4: failed, non IB address: " "len = %d, addr = 0x", len); if (len > 0) { for (i = 0; i < len; i++) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "%02x", (int)mac[i] & 0xff); } } else { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "0"); } dapl_dbg_log(DAPL_DBG_TYPE_ERR, "\n"); return (DAT_INVALID_ADDRESS); } return (DAT_SUCCESS); } DAT_RETURN dapls_ns_lookup_v6( IN DAPL_IA *ia_ptr, IN struct sockaddr_in6 *addr, IN DAT_TIMEOUT timeout, OUT ib_gid_t *gid) { struct lifreq lifr; uchar_t *mac; int s, retries = 0; s = socket(AF_INET6, SOCK_DGRAM, 0); if (s < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v6: socket: %s\n", strerror(errno)); return (DAT_INTERNAL_ERROR); } if (dapls_ns_subnet_match_v6(s, ia_ptr, addr) != 0) { (void) close(s); return (DAT_INVALID_ADDRESS); } (void) dapl_os_memzero(&lifr, sizeof (lifr)); (void) dapl_os_memcpy(&lifr.lifr_nd.lnr_addr, addr, sizeof (*addr)); (void) dapl_os_strcpy(lifr.lifr_name, ia_ptr->hca_ptr->name); again:; if (ioctl(s, SIOCLIFGETND, (caddr_t)&lifr) < 0) { /* * if SIOCLIFGETND failed, we force the ND * cache to be filled by connecting to the * destination IP address. */ if (retries < NS_MAX_RETRIES && dapls_ns_send_packet_v6(s, addr) == 0 && dapls_ns_resolve_addr(AF_INET6, (struct sockaddr *)addr, timeout) == 0) { retries++; goto again; } dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v6: giving up\n"); (void) close(s); return (DAT_ERROR(DAT_INVALID_ADDRESS, DAT_INVALID_ADDRESS_UNREACHABLE)); } if (lifr.lifr_nd.lnr_hdw_len == 0 && retries <= NS_MAX_RETRIES) { /* * lnr_hdw_len == 0 means that the ND entry * is still incomplete. we need to retry the ioctl. */ retries++; (void) sleep(1); goto again; } (void) close(s); mac = (uchar_t *)lifr.lifr_nd.lnr_hdw_addr; if (lifr.lifr_nd.lnr_hdw_len >= sizeof (ipoib_mac_t)) { ib_gid_t tmp_gid; /* LINTED: E_BAD_PTR_CAST_ALIGN */ (void) dapl_os_memcpy(&tmp_gid, &((ipoib_mac_t *)mac)->ipoib_gidpref, sizeof (ib_gid_t)); /* * gids from the ND table are in network order, convert * the gids from network order to host byte order */ gid->gid_prefix = BETOH_64(tmp_gid.gid_prefix); gid->gid_guid = BETOH_64(tmp_gid.gid_guid); } else { int i, len; len = lifr.lifr_nd.lnr_hdw_len; dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_lookup_v6: failed, non IB address: " "len = %d, addr = 0x", len); if (len > 0) { for (i = 0; i < len; i++) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "%02x", (int)mac[i] & 0xff); } } else { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "0"); } dapl_dbg_log(DAPL_DBG_TYPE_ERR, "\n"); return (DAT_INVALID_ADDRESS); } return (DAT_SUCCESS); } static int dapls_ns_send_packet_v6(int s, struct sockaddr_in6 *addr) { if (sendto(s, NULL, 0, MSG_DONTROUTE, (struct sockaddr *)addr, sizeof (*addr)) < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_send_packet_v6: failed: %s\n", strerror(errno)); return (-1); } return (0); } static int dapls_ns_subnet_match_v4(int s, DAPL_IA *ia_ptr, struct sockaddr_in *addr) { struct lifreq lifreq; int retval; uint32_t netmask, netaddr, netaddr_dest; (void) dapl_os_strcpy(lifreq.lifr_name, ia_ptr->hca_ptr->name); retval = ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifreq); if (retval < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v4: cannot get netmask: %s\n", strerror(errno)); return (-1); } netmask = ((struct sockaddr_in *)&lifreq.lifr_addr)-> sin_addr.s_addr; /* * we need to get the interface address here because the * address in ia_ptr->hca_ptr->hca_address might not * necessarily be an IPv4 address. */ retval = ioctl(s, SIOCGLIFADDR, (caddr_t)&lifreq); if (retval < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v4: cannot get local addr: %s\n", strerror(errno)); return (-1); } netaddr = ((struct sockaddr_in *)&lifreq.lifr_addr)-> sin_addr.s_addr & netmask; netaddr_dest = addr->sin_addr.s_addr & netmask; if (netaddr != netaddr_dest) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v4: netaddrs don't match: " "local %x, remote %x\n", netaddr, netaddr_dest); return (-1); } return (0); } static int dapls_ns_subnet_match_v6(int s, DAPL_IA *ia_ptr, struct sockaddr_in6 *addr) { struct lifreq lifreq; struct sockaddr_in6 netmask_sock; uchar_t *netmask, *local_addr, *dest_addr; int i, retval; (void) dapl_os_strcpy(lifreq.lifr_name, ia_ptr->hca_ptr->name); retval = ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifreq); if (retval < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v6: cannot get netmask: %s\n", strerror(errno)); return (-1); } (void) dapl_os_memcpy(&netmask_sock, &lifreq.lifr_addr, sizeof (netmask_sock)); /* * we need to get the interface address here because the * address in ia_ptr->hca_ptr->hca_address might not * necessarily be an IPv6 address. */ retval = ioctl(s, SIOCGLIFADDR, (caddr_t)&lifreq); if (retval < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v6: cannot get local addr: %s\n", strerror(errno)); return (-1); } netmask = (uchar_t *)&netmask_sock.sin6_addr; local_addr = (uchar_t *)&((struct sockaddr_in6 *)&lifreq.lifr_addr)-> sin6_addr; dest_addr = (uchar_t *)&addr->sin6_addr; for (i = 0; i < sizeof (addr->sin6_addr); i++) { if (((local_addr[i] ^ dest_addr[i]) & netmask[i]) != 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_subnet_match_v6: subnets do not match\n"); return (-1); } } return (0); } static int dapls_ns_resolve_addr(int af, struct sockaddr *addr, DAT_TIMEOUT timeout) { struct sockaddr_storage sock; struct sockaddr_in *v4dest; struct sockaddr_in6 *v6dest; struct pollfd pollfd; int fd, retval; int tmo; int ip_version; if (af == AF_INET) { ip_version = 4; } else if (af == AF_INET6) { ip_version = 6; } else { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: invalid af %d\n", af); return (-1); } fd = socket(af, SOCK_STREAM, 0); if (fd < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: ipv%d, cannot create socket %s\n", ip_version, strerror(errno)); return (-1); } /* * set socket to non-blocking mode */ retval = fcntl(fd, F_SETFL, O_NONBLOCK); if (retval < 0) { dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: ipv%d, fcntl failed: %s\n", ip_version, strerror(errno)); (void) close(fd); return (-1); } /* * connect to the discard port (9) at the dest IP */ (void) dapl_os_memzero(&sock, sizeof (sock)); if (af == AF_INET) { v4dest = (struct sockaddr_in *)&sock; v4dest->sin_family = AF_INET; v4dest->sin_addr.s_addr = /* LINTED: E_BAD_PTR_CAST_ALIGN */ ((struct sockaddr_in *)addr)->sin_addr.s_addr; v4dest->sin_port = htons(9); retval = connect(fd, (struct sockaddr *)v4dest, sizeof (struct sockaddr_in)); } else { v6dest = (struct sockaddr_in6 *)&sock; v6dest->sin6_family = AF_INET6; /* LINTED: E_BAD_PTR_CAST_ALIGN */ (void) dapl_os_memcpy(&v6dest->sin6_addr, &((struct sockaddr_in6 *)addr)->sin6_addr, sizeof (struct sockaddr_in6)); v6dest->sin6_port = htons(9); retval = connect(fd, (struct sockaddr *)v6dest, sizeof (struct sockaddr_in6)); } /* * we can return immediately if connect succeeds */ if (retval == 0) { (void) close(fd); return (0); } /* * receiving a RST means that the arp/nd entry should * already be resolved */ if (retval < 0 && errno == ECONNREFUSED) { errno = 0; (void) close(fd); return (0); } /* * for all other cases, we poll on the fd */ pollfd.fd = fd; pollfd.events = POLLIN | POLLOUT; pollfd.revents = 0; if (timeout == DAT_TIMEOUT_INFINITE || timeout == 0) { /* * -1 means infinite */ tmo = -1; } else { /* * convert timeout from usecs to msecs */ tmo = timeout/1000; } retval = poll(&pollfd, 1, tmo); if (retval > 0) { int so_error = 0, len = sizeof (so_error); retval = getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &len); if (retval == 0) { /* * we only return 0 if so_error == 0 or * so_error == ECONNREFUSED. for all other * cases retval is non-zero. */ if (so_error != 0 && so_error != ECONNREFUSED) { retval = -1; errno = so_error; dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: ipv%d, so_error: %s\n", ip_version, strerror(errno)); } } else { /* * if retval != 0, it must be -1. and errno must * have been set by getsockopt. */ dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: ipv%d, getsockopt: %s\n", ip_version, strerror(errno)); } } else { if (retval == 0) { errno = ETIMEDOUT; } retval = -1; dapl_dbg_log(DAPL_DBG_TYPE_ERR, "ns_resolve_addr: ipv%d, poll: %s\n", ip_version, strerror(errno)); } (void) close(fd); return (retval); }
24.734536
79
0.671772
[ "object" ]
4014e31812d1e2f17974f6a89513656b91b6e500
22,897
h
C
Examples/SDKLibrary/interface/common/portable/address_space/ivariable_node_t.h
beeond/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
1
2018-03-29T21:03:31.000Z
2018-03-29T21:03:31.000Z
Examples/SDKLibrary/interface/common/portable/address_space/ivariable_node_t.h
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
null
null
null
Examples/SDKLibrary/interface/common/portable/address_space/ivariable_node_t.h
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
4
2018-04-05T21:16:55.000Z
2019-10-15T19:01:46.000Z
/* ----------------------------------------------------------------------------------------------------------------- COPYRIGHT (c) 2009 - 2017 HONEYWELL INC., ALL RIGHTS RESERVED This software is a copyrighted work and/or information protected as a trade secret. Legal rights of Honeywell Inc. in this software are distinct from ownership of any medium in which the software is embodied. Copyright or trade secret notices included must be reproduced in any copies authorized by Honeywell Inc. The information in this software is subject to change without notice and should not be considered as a commitment by Honeywell Inc. ----------------------------------------------------------------------------------------------------------------- */ #ifndef _IVARIABLE_NODE_T_ #define _IVARIABLE_NODE_T_ #include "uasdk_includes.h" #include "opcua_timestamps_to_return_t.h" #include "opcua_double_t.h" #include "opcua_node_class_t.h" #include "inode_t.h" namespace uasdk { class IVariableTypeNode_t; class INodeValueAttributeReaderWriter_t; class ICallbackNodeValueAttributeAccessCompleted_t; class UInt32_t; class DataValue_t; class AccessLevel_t; class Duration_t; class IndexRange_t; class DiagnosticInfo_t; template<typename T> class ArrayUA_t; template<typename T> class ArrayRef_t; /** \addtogroup grpAddressSpace *@{*/ /*****************************************************************************/ /** \brief Variable Node Interface * * A class that represents a Variable node in the address space. * Implementations of this interface must be thread safe. * */ class IVariableNode_t : public virtual INode_t { public: UA_DECLARE_RUNTIME_TYPE(IVariableNode_t); virtual ~IVariableNode_t() {} /*****************************************************************************/ /** Get the Value attribute of the node * * Nodes can provide value attributes in a number of ways. All data types * except for LocalizedText_t can be placed in the Value attribute for * synchronous access by users of the node. The value can be unchanged, * the owner of the node can update the value in an event driven fashion or the * owner can register an attribute about to be read listener with the node * and update the value on demand when a user of the node attempts a read. * Similarly the node owner can register an attribute changed listener with * the node to be notified when the value has been changed. * * For value attributes that cannot be accessed synchronously due to a slow * data source the node owner can register a value attribute reader and * writer to perform the value attribute access asynchronously so as not to * block the thread pool. * * If this value is set then the Read Service will read the value synchronously * rather than attempting to obtain the value asynchronously. * * @return * An intrusive reference counting Boost-style smart pointer to the Value * of the node. The caller must test the pointer before dereferencing it. */ virtual IntrusivePtr_t<const DataValue_t> Value(void) const = 0; /*****************************************************************************/ /** Set the Value attribute of the node * * Nodes can provide value attributes in a number of ways. All data types * except for LocalizedText_t can be placed in the Value attribute for * synchronous access by users of the node. The value can be unchanged, * the owner of the node can update the value in an event driven fashion or the * owner can register an attribute about to be read listener with the node * and update the value on demand when a user of the node attempts a read. * Similarly the node owner can register an attribute changed listener with * the node to be notified when the value has been changed. * * For value attributes that cannot be accessed synchronously due to a slow * data source the node owner can register a value attribute reader and * writer to perform the value attribute access asynchronously so as not to * block the thread pool. * * If this value is set then the Read Service will read the value synchronously * rather than attempting to obtain the value asynchronously. * * @param[in] value * An intrusive reference counting Boost-style smart pointer to the Value * of the node. The value provided must satisfy a number of rules. * 1) If set, the DataValue_t must have been created * dynamically using a SafeRefCount_t (to ensure thread safety). * 2) The value pointer can be set or empty. Passing an empty pointer to this * function removes the value from the node. * * @return * The result of the operation. */ virtual Status_t Value(IntrusivePtr_t<const DataValue_t> value) = 0; /*****************************************************************************/ /** Get the DataType attribute of the node * * @return * An intrusive reference counting Boost-style smart pointer to the DataType * of the node. All nodes have a DataType however the caller must test the * pointer before dereferencing it. */ virtual IntrusivePtr_t<const NodeId_t> DataType(void) const = 0; /*****************************************************************************/ /** Set the DataType attribute of the node * * @param[in] value * An intrusive reference counting Boost-style smart pointer to the DataType * of the node. The value provided must satisfy a number of rules. * 1) No non-const references to the NodeId_t must exist, i.e. it must * be immutable (to ensure thread safety). * 2) The NodeId_t must have been created dynamically using a * SafeRefCount_t (to ensure thread safety). * 3) The value must be set (i.e. pointing to an actual object) as all * variable type nodes require a DataType. * * @return * The result of the operation. */ virtual Status_t DataType(IntrusivePtr_t<const NodeId_t> value) = 0; /*****************************************************************************/ /** Get the ValueRank attribute of the node * * @return * The ValueRank of the node. */ virtual int32_t ValueRank(void) const = 0; /*****************************************************************************/ /** Set the ValueRank attribute of the node * * @param[in] value * The required ValueRank of the node. * * @return * The result of the operation. */ virtual Status_t ValueRank(int32_t value) = 0; /*****************************************************************************/ /** Get the ArrayDimensions attribute of the node * * @return * An intrusive reference counting Boost-style smart pointer to the * ArrayDimensions of the node. All variable type nodes do not have * ArrayDimensions and the caller must test the pointer before dereferencing it. */ virtual IntrusivePtr_t<const ArrayUA_t<UInt32_t> > ArrayDimensions(void) const = 0; /*****************************************************************************/ /** Set the ArrayDimensions attribute of the node * * @param[in] value * An intrusive reference counting Boost-style smart pointer to the ArrayDimensions * of the node. The value provided must satisfy a number of rules. * 1) If set, no non-const references to the ArrayUA_t<UInt32_t> must exist, * i.e. it must be immutable (to ensure thread safety). * 2) If set, the ArrayUA_t<UInt32_t> must have been created dynamically using a * SafeRefCount_t (to ensure thread safety). * 3) The value pointer can be set or empty. Passing an empty pointer to the * method removes the ArrayDimensions attribute from the node. * * @return * The result of the operation. */ virtual Status_t ArrayDimensions(IntrusivePtr_t<const ArrayUA_t<UInt32_t> > value) = 0; /*****************************************************************************/ /** Get the AccessLevel attribute of the node * * @return * The AccessLevel of the node. */ virtual AccessLevel_t AccessLevel(void) const = 0; /*****************************************************************************/ /** Set the AccessLevel attribute of the node * * @param[in] value * The required AccessLevel of the node. * * @return * The result of the operation. */ virtual Status_t AccessLevel(AccessLevel_t value) = 0; /*****************************************************************************/ /** Get the UserAccessLevel attribute of the node * * @param[in] userPermissions * An object used to identify a specific user and authenticate that user's * access permissions. * * @return * The UserAccessLevel of the node. */ virtual AccessLevel_t UserAccessLevel(const IUserPermissions_t& userPermissions) const = 0; /*****************************************************************************/ /** Set the UserAccessLevel attribute of the node * * @param[in] value * The required UserAccessLevel of the node * * @param[in] userPermissions * An object used to identify a specific user and authenticate that user's * access permissions. * * @return * The result of the operation. */ virtual Status_t UserAccessLevel(AccessLevel_t value, IUserPermissions_t& userPermissions) = 0; /*****************************************************************************/ /** Get the MinimumSamplingInterval attribute of the node * * @return * The MinimumSamplingInterval of the node. */ virtual Duration_t MinimumSamplingInterval(void) const = 0; /*****************************************************************************/ /** Set the MinimumSamplingInterval attribute of the node * * @param[in] value * The required MinimumSamplingInterval of the node. * * @return * The result of the operation. */ virtual Status_t MinimumSamplingInterval(Duration_t value) = 0; /*****************************************************************************/ /** Get the Historizing attribute of the node * * @return * The Historizing of the node. */ virtual bool Historizing(void) const = 0; /*****************************************************************************/ /** Set the Historizing attribute of the node * * @param[in] value * The required Historizing of the node. * * @return * The result of the operation. */ virtual Status_t Historizing(bool value) = 0; /*****************************************************************************/ /** Is monitored item value attribute sampling disabled? * * For nodes with very large value attributes monitored item sampling of the * value attribute can be disabled to protect the platform resources from * exhaustion. * * @return * "true" if sampling is disabled. */ virtual bool DisableSampling(void) const = 0; /*****************************************************************************/ /** Set monitored item value attribute sampling disabled * * For nodes with very large value attributes monitored item sampling of the * value attribute can be disabled to protect the platform resources from * exhaustion. * * @param[in] value * "true" if sampling is disabled. * * @return * The result of the operation. */ virtual Status_t DisableSampling(bool value) = 0; /*****************************************************************************/ /** Get the value attribute reader/writer of the node * * @return * An intrusive reference counting Boost-style smart pointer to the * ValueAttributeReaderWriter of the node. */ virtual IntrusivePtr_t<INodeValueAttributeReaderWriter_t> ValueAttributeReaderWriter(void) = 0; /*****************************************************************************/ /** Set the value attribute reader/writer of the node * * Nodes can provide value attributes in a number of ways. All data types * except for LocalizedText_t can be placed in the Value attribute for * synchronous access by users of the node. The value can be unchanged, * the owner of the node can update the value in an event driven fashion or the * owner can register an attribute about to be read listener with the node * and update the value on demand when a user of the node attempts a read. * * For value attributes that cannot be accessed synchronously due to a slow * data source the node owner can register a value attribute reader and * writer to perform the value attribute access asynchronously so as not to * block the thread pool. * * The value attribute reader is used by the node to read the value * attribute. Only a single reader can be registered at any given time. * Any software component registering a reader with the node is responsible * for removing the reader if required. * * Limitations: * 1. If the Value attribute is stored in the address space, then value cannot be retrived * with the help of ValueAttributeReaderWriter * 2. If the Node's value is retrived from the ValueAttributeReaderWriter, and if there is * a value attribute changed listener then changed listner will not be trigerred. * * @param[in] value * An intrusive reference counting Boost-style smart pointer to the reader * of the node. The value provided must satisfy a number of rules. * 1) If set, the INodeValueAttributeReader_t must have been created dynamically using a * SafeRefCount_t (to ensure thread safety). * 2) The value pointer can be set or empty. Passing an empty pointer to this * function removes the reader from the node. * * @return * The result of the operation. */ virtual Status_t ValueAttributeReaderWriter(IntrusivePtr_t<INodeValueAttributeReaderWriter_t> value) = 0; /*****************************************************************************/ /** Can the value attribute be read synchronously? * * Value attribute for variable node can be read synchronously or asynchronously * using this function before reading the value attribute, developer can identify * whether the value attribute can be read synchronously * * @return * returns true if the value attribute can be read synchronously */ virtual bool CanReadValueSynchronously(void) const = 0; /*****************************************************************************/ /** Begins reading the value attribute of the node asynchronously * * This function internally calls the value attribute reader registered with * the node. If this function returns a good status code * completedCallback.ReadValueAttributeCompleted() will be called by the reader * when the read has completed. If this function returns a bad status code * completedCallback.ReadValueAttributeCompleted() will not be called by the * reader. * * @param[in] maxAge * The maxAge of the value in milliseconds provided by the Read Service. The reader * can optionally consider this when replying to the caller. * Should be set to zero where no maxAge is provided. * * @param[in] timestampsToReturn * The timestamps to return in the data value. * * @param[in] locales * A list of locales in order of preference to use when reading LocalizedText. * * @param[in] indexRange * The index range to apply to the value if it is an array. * * @param[in] transactionId * A non-zero unique identifier for a collection of nodes being read as a * group (typically by the Read Service). Can be optionally used in conjunction * with a transaction listener to optimise processing of read operations by the * application. If reading the node outside of the Read Service should be set * to zero. * * @param[in] timeoutHint * The timeoutHint in milliseconds provided by the Read Service. The reader * can optionally consider this hint when replying to the caller. * Should be set to zero where no timeoutHint is provided. * * @param[out] completedCallback * The ReadValueAttributeCompleted() function of this interface will be called by the * reader if this function returns a good status code. * * @return * The result of the operation. If the status code is good then the reader * has been successfully launched and will return the read result in due course. If * the status code is bad the reader was not successfully launched. * */ virtual Status_t BeginReadValue( uint32_t maxAge, TimestampsToReturn_t::Enum_t timestampsToReturn, IntrusivePtr_t<const ArrayUA_t<String_t> >& locales, IntrusivePtr_t<const ArrayRef_t<IndexRange_t> >& indexRange, uint32_t transactionId, uint32_t timeoutHint, IntrusivePtr_t<ICallbackNodeValueAttributeAccessCompleted_t> completedCallback) const = 0; /*****************************************************************************/ /** Reading the value attribute of the node synchronously * * @param[in] maxAge * The maxAge of the value in milliseconds provided by the Read Service. The reader * can optionally consider this when replying to the caller. * Should be set to zero where no maxAge is provided. * * @param[in] timestampsToReturn * The timestamps to return in the data value. * * @param[in] locales * A list of locales in order of preference to use when reading LocalizedText. * * @param[in] indexRange * The index range to apply to the value if it is an array. * * @param[out] dataValue * That read from the node will be update to the dataValue * * @param[in] transactionId * A non-zero unique identifier for a collection of nodes being read as a * group (typically by the Read Service). Can be optionally used in conjunction * with a transaction listener to optimise processing of read operations by the * application. If reading the node outside of the Read Service should be set * to zero. * * @param[in] timeoutHint * The timeoutHint in milliseconds provided by the Read Service. The reader * can optionally consider this hint when replying to the caller. * Should be set to zero where no timeoutHint is provided. * * @return * The result of the operation. * */ virtual Status_t ReadValue( uint32_t maxAge, TimestampsToReturn_t::Enum_t timestampsToReturn, const ArrayUA_t<String_t>& locales, const Array_t<IndexRange_t>& indexRange, uint32_t transactionId, uint32_t timeoutHint, IntrusivePtr_t<DataValue_t>& dataValue, IntrusivePtr_t<DiagnosticInfo_t>& diagnosticInfo) const = 0; /*****************************************************************************/ /** Can the value attribute be written synchronously? * * Value attribute for variable node can be written synchronously or asynchronously * using this function before writing the value attribute, developer can identify * whether the value attribute can be written synchronously * * @return * returns true if the value attribute can be written synchronously */ virtual bool CanWriteValueSynchronously(void) const = 0; /*****************************************************************************/ /** Begins writing the value attribute of the node asynchronously * * This function internally calls the value attribute writer registered with * the node. If this function returns a good status code * completedCallback.WriteValueAttributeCompleted() will be called by the writer * when the write has completed. If this function returns a bad status code * completedCallback.WriteValueAttributeCompleted() will not be called by the * writer. * * @param[in] indexRange * The index range to apply to the value if it is an array. * * @param[in] dataValue * The value to be written. * * @param[in] transactionId * A non-zero unique identifier for a collection of nodes being written as a * group (typically by the Write Service). Can be optionally used in conjunction * with a transaction listener to optimise processing of write operations by the * application. If writing the node outside of the WriteService should be set * to zero. * * @param[in] timeoutHint * The timeoutHint in milliseconds provided by the Write Service. The writer * can optionally consider this hint when replying to the caller. * Should be set to zero where no timeoutHint is provided. * * @param[out] completedCallback * The WriteValueAttributeCompleted() function of this interface will be called by the * writer if this function returns a good status code. * * @return * The result of the operation. If the status code is good then the writer * has been successfully launched and will return the write result in due course. If * the status code is bad the writer was not successfully launched. * */ virtual Status_t BeginWriteValue( IntrusivePtr_t<const ArrayRef_t<IndexRange_t> >& indexRange, IntrusivePtr_t<const DataValue_t> dataValue, uint32_t transactionId, uint32_t timeoutHint, IntrusivePtr_t<ICallbackNodeValueAttributeAccessCompleted_t> completedCallback) = 0; /*****************************************************************************/ /** Writing the value attribute of the node Synchronously * * @param[in] indexRange * The index range to apply to the value if it is an array. * * @param[in] dataValue * The value to be written. * * @param[in] transactionId * A non-zero unique identifier for a collection of nodes being written as a * group (typically by the Write Service). Can be optionally used in conjunction * with a transaction listener to optimise processing of write operations by the * application. If writing the node outside of the WriteService should be set * to zero. * * @param[in] timeoutHint * The timeoutHint in milliseconds provided by the Write Service. The writer * can optionally consider this hint when replying to the caller. * Should be set to zero where no timeoutHint is provided. * * @return * The result of the operation. * */ virtual Status_t WriteValue( const Array_t<IndexRange_t>& indexRange, IntrusivePtr_t<const DataValue_t> dataValue, uint32_t transactionId, uint32_t timeoutHint, IntrusivePtr_t<DiagnosticInfo_t>& diagnosticInfo) = 0; }; /** @} */ } #endif // _IVARIABLE_NODE_T_
40.8875
116
0.639341
[ "object" ]
4015ac2389a3bc867c399cd36dce29a9eee60c94
1,714
h
C
include/kiui/Object/String/mkString.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
include/kiui/Object/String/mkString.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
include/kiui/Object/String/mkString.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifndef MK_STRING_H_INCLUDED #define MK_STRING_H_INCLUDED /* Basic headers */ #include <Object/mkObjectForward.h> #include <Object/mkTypeUtils.h> #include <string> #include <vector> #include <type_traits> namespace mk { template <class T, bool isobject = std::is_base_of<Object, typename BareType<T>::type>::value, bool isenum = std::is_enum<T>::value> struct StringConverter {}; template <class T> inline void fromString(const string& str, T& val) { StringConverter<T>::from(str, val); } template <class T> inline T fromString(const string& str) { T val; fromString<T>(str, val); return val; } template <class T> inline void toString(const T& val, string& str) { return StringConverter<T>::to(val, str); } template <class T> inline string toString(const T& val) { string str; toString<T>(val, str); return str; } // string - string conversion template <> inline string fromString<string>(const string& str) { return str; } template <> inline void fromString<string>(const string& str, string& val) { val = str; } template <> inline string toString<string>(const string& val){ return val; } template <> inline void toString<string>(const string& val, string& str){ str = val; } typedef std::vector<string> StringVector; MK_OBJECT_EXPORT StringVector splitString(const string& str, const string& separator); MK_OBJECT_EXPORT string replaceAll(string const& original, string const& before, string const& after); } #endif // mkSTRING_H_INCLUDED
34.979592
133
0.733956
[ "object", "vector" ]
40174e188e53dcdb89974b1f1d3afe8ab2271a14
4,116
h
C
src/vt/context/runnable_context/td.h
DARMA-tasking/vt
1286d6f3d383b7a78707921fb08df48e1430f5a5
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
src/vt/context/runnable_context/td.h
DARMA-tasking/vt
1286d6f3d383b7a78707921fb08df48e1430f5a5
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
src/vt/context/runnable_context/td.h
DARMA-tasking/vt
1286d6f3d383b7a78707921fb08df48e1430f5a5
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // td.h // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #if !defined INCLUDED_VT_CONTEXT_RUNNABLE_CONTEXT_TD_H #define INCLUDED_VT_CONTEXT_RUNNABLE_CONTEXT_TD_H #include "vt/context/runnable_context/base.h" #include "vt/configs/types/types_type.h" #include "vt/configs/types/types_sentinels.h" #include <vector> namespace vt { namespace ctx { /** * \struct TD * * \brief Context for termination detection to be preserved with a task. Manages * the epoch stack associated with running tasks. Produces and consumes in the * constructor and destructor to ensure termination is not detected early. */ struct TD final : Base { /** * \brief Construct with a given epoch; produce on that epoch. * * \param[in] in_ep the epoch */ explicit TD(EpochType in_ep); /** * \brief When destroyed, consume the epoch held by the context. */ virtual ~TD(); /** * \brief Construct with a message to extract the epoch; produce on that * epoch. * * \param[in] msg the message to extract the epoch from */ template <typename MsgPtrT> explicit TD(MsgPtrT msg); /** * \brief During begin \c TD will capture the epoch stack size and push \c ep_ */ void begin() final override; /** * \brief During end \c TD will pop all epochs off of the stack down to the * size in captured in \c begin() */ void end() final override; /** * \brief When suspended, \c TD will preserve any epochs pushed on the stack * after begin and restore the stack back to the state before begin was * invoked */ void suspend() final override; /** * \brief When resumed, \c TD will restore the stack back from when it was * suspended */ void resume() final override; private: EpochType ep_ = no_epoch; /**< The epoch for the task */ std::size_t base_epoch_stack_size_ = 0; /**< Epoch stack size at start */ std::vector<EpochType> suspended_epochs_; /**< Suspended epoch stack */ }; }} /* end namespace vt::ctx */ #include "vt/context/runnable_context/td.impl.h" #endif /*INCLUDED_VT_CONTEXT_RUNNABLE_CONTEXT_TD_H*/
34.3
81
0.68173
[ "vector" ]
4018fde5f9c847fc91ccd6ba70042249a680653d
2,185
h
C
src/assets/ChAssetLevel.h
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
1
2020-02-16T16:52:08.000Z
2020-02-16T16:52:08.000Z
src/assets/ChAssetLevel.h
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
src/assets/ChAssetLevel.h
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2012 Alessandro Tasora // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #ifndef CHASSETLEVEL_H #define CHASSETLEVEL_H /////////////////////////////////////////////////// // // ChAssetLevel.h // // Base class grouping assets // // HEADER file for CHRONO, // Multibody dynamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "assets/ChAsset.h" #include "core/ChFrame.h" namespace chrono { /// Base class for grouping assets in a level. The /// level is like a 'subdirectory'. A level can contain /// assets; amnog these, also further levels, etc. (but please /// avoid circular loops!) /// A level can have custom rotation and translation respect /// its parent level. class ChApi ChAssetLevel : public ChAsset { protected: // // DATA // ChFrame<> levelframe; std::vector< ChSharedPtr<ChAsset> > assets; public: // // CONSTRUCTORS // ChAssetLevel () : levelframe(chrono::CSYSNORM) { }; virtual ~ChAssetLevel () {}; // // FUNCTIONS // // Access the coordinate sytem information of the level, for setting/getting its position // and rotation respect to its parent. ChFrame<>& GetFrame() {return levelframe;} /// Access to the list of children assets. std::vector< ChSharedPtr<ChAsset> >& GetAssets () { return this->assets;} /// Get the Nth asset in list ChSharedPtr<ChAsset> GetAssetN (unsigned int num) { if (num<assets.size()) return assets[num]; else {ChSharedPtr<ChAsset> none; return none;};} /// Add an asset void AddAsset (ChSharedPtr<ChAsset> masset) { this->assets.push_back(masset);} }; ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// } // END_OF_NAMESPACE____ #endif
23
144
0.580778
[ "vector" ]
40233c263c808b8235b4a023e827b84be101426c
779
h
C
Sources/Client/Graphics/VertexArray.h
killowatt/WatchtowerCPP
efa5fed380897ad3e25c200dc5e4974e0bad9119
[ "Zlib" ]
1
2022-01-07T04:53:09.000Z
2022-01-07T04:53:09.000Z
Sources/Client/Graphics/VertexArray.h
killowatt/WatchtowerCPP
efa5fed380897ad3e25c200dc5e4974e0bad9119
[ "Zlib" ]
null
null
null
Sources/Client/Graphics/VertexArray.h
killowatt/WatchtowerCPP
efa5fed380897ad3e25c200dc5e4974e0bad9119
[ "Zlib" ]
null
null
null
#pragma once #include "VertexBuffer.h" #include <vector> namespace Watchtower { class VertexArray { unsigned int vertexArrayObject; unsigned int indexBufferObject; std::vector<unsigned int> indexBuffer; MemoryHint indexBufferMemoryHint; public: void AttachBuffer(VertexBuffer& buffer, int index); void RemoveBuffer(int index); unsigned int GetVertexArrayObject() const; void SetIndexBuffer(const std::vector<unsigned int>& data, MemoryHint hint); void RemoveIndexBuffer(); std::vector<unsigned int> GetIndexBuffer() const; std::size_t GetIndexBufferSize() const; MemoryHint GetIndexBufferMemoryHint() const; VertexArray& operator=(const VertexArray&) = delete; VertexArray(); VertexArray(const VertexArray&) = delete; ~VertexArray(); }; }
25.129032
78
0.759949
[ "vector" ]
402896de215effb7b23dda5c5a1e65abda162596
44,675
c
C
exomizer209/src/exo_main.c
visy/c64demo2017
6ff438f2b331aefec346156ded4f62d437c26652
[ "WTFPL" ]
12
2016-04-20T06:08:11.000Z
2021-10-12T10:43:39.000Z
exomizer209/src/exo_main.c
visy/c64demo2017
6ff438f2b331aefec346156ded4f62d437c26652
[ "WTFPL" ]
3
2016-09-21T14:39:11.000Z
2021-04-12T16:54:40.000Z
compressors/exomizer/src/exo_main.c
maxim-zhao/bmp2tilecompressors
1d0e475820731359165deb198aa834f8b177048a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2002 - 2007 Magnus Lind. * * 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, alter it and re- * distribute it freely for any non-commercial, non-profit purpose 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 distribution. * * 4. The names of this software and/or it's copyright holders may not be * used to endorse or promote products derived from this software without * specific prior written permission. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include "log.h" #include "search.h" #include "optimal.h" #include "output.h" #include "getflag.h" #include "membuf_io.h" #include "exo_helper.h" #include "exo_util.h" #include "parse.h" #include "named_buffer.h" #include "desfx.h" extern struct membuf sfxdecr[]; #define DEFAULT_OUTFILE "a.out" static void load_plain_file(const char *name, struct membuf *mb) { int file_len; int read_len; int offset = 0; int len = -1; FILE *in; in = fopen(name, "rb"); if(in == NULL) { char *p = strrchr(name, ','); if(p == NULL) { /* not found and no comma */ LOG(LOG_ERROR, ("Error: file not found.\n")); exit(-1); } *p = '\0'; if(str_to_int(p + 1, &offset)) { LOG(LOG_ERROR, ("Error: invalid value for plain file offset.\n")); exit(-1); } in = fopen(name, "rb"); if(in == NULL) { p = strrchr(name, ','); len = offset; if(len < 0) { LOG(LOG_ERROR, ("Error, value for plain file " "len must not be negative.\n")); exit(-1); } *p = '\0'; if(str_to_int(p + 1, &offset)) { LOG(LOG_ERROR, ("Error: invalid value for plain file offset.\n")); exit(-1); } in = fopen(name, "rb"); if(in == NULL) { /* really not found */ LOG(LOG_ERROR, ("Error: file not found.\n")); exit(-1); } } } /* get the real length of the file and validate the offset*/ if(fseek(in, 0, SEEK_END)) { LOG(LOG_ERROR, ("Error: can't seek to EOF.\n")); fclose(in); exit(-1); } file_len = ftell(in); if(offset < 0) { offset += file_len; } if(len < 0) { len = file_len - offset; } if(fseek(in, offset, SEEK_SET)) { LOG(LOG_ERROR, ("Error: can't seek to offset %d.\n", offset)); fclose(in); exit(-1); } if(offset + len > file_len) { LOG(LOG_ERROR, ("Error: can't read %d bytes from offset %d.\n", len, offset)); fclose(in); exit(-1); } LOG(LOG_VERBOSE, ("Reading %d bytes from offset %d.\n", len, offset)); do { char buf[1024]; int r = 1024 < len? 1024: len; read_len = fread(buf, 1, r, in); if(read_len < r) { LOG(LOG_ERROR, ("Error: tried to read %d bytes but got %d.\n", r, read_len)); fclose(in); exit(-1); } membuf_append(mb, buf, r); len -= r; } while(len > 0); fclose(in); } static int do_load(char *file_name, struct membuf *mem) { struct load_info info[1]; unsigned char *p; membuf_clear(mem); membuf_append(mem, NULL, 65536); p = membuf_get(mem); info->basic_txt_start = -1; load_located(file_name, p, info); /* move memory to beginning of buffer */ membuf_truncate(mem, info->end); membuf_trim(mem, info->start); LOG(LOG_NORMAL, (" crunching from $%04X to $%04X ", info->start, info->end)); return info->start; } struct target_info { int id; int sys_token; int basic_txt_start; int end_of_ram; const char *model; }; static int do_loads(int filec, char *filev[], struct membuf *mem, int basic_txt_start, int sys_token, int *basic_var_startp, int *runp) { int run = -1; int min_start = 65537; int max_end = -1; int basic_code = 0; int i; unsigned char *p; struct load_info info[1]; membuf_clear(mem); membuf_append(mem, NULL, 65536); p = membuf_get(mem); for (i = 0; i < filec; ++i) { info->basic_txt_start = basic_txt_start; load_located(filev[i], p, info); run = info->run; if(run != -1 && runp != NULL) { LOG(LOG_DEBUG, ("Propagating found run address $%04X.\n", info->run)); *runp = info->run; } /* do we expect any basic file? */ if(basic_txt_start >= 0) { if(info->basic_var_start >= 0) { basic_code = 1; if(basic_var_startp != NULL) { *basic_var_startp = info->basic_var_start; } if(runp != NULL && run == -1) { /* only if we didn't get run address from load_located * (run is not -1 if we did) */ run = find_sys(p + basic_txt_start, sys_token); *runp = run; } } } if (info->start < min_start) { min_start = info->start; } if (info->end > max_end) { max_end = info->end; } if(info->basic_var_start != -1) { info->basic_var_start = info->basic_var_start; } if(info->run != -1) { info->run = info->run; } } if(basic_txt_start >= 0 && !basic_code && run == -1) { /* no program loaded to the basic start */ LOG(LOG_ERROR, ("\nError: nothing loaded at the start of basic " "text address ($%04X).\n", basic_txt_start)); exit(-1); } /* if we have a basic code loaded and we are doing a proper basic start * (the caller don't expect a sys address so runp is NULL */ if(basic_code && runp == NULL) { int valuepos = basic_txt_start - 1; /* the byte immediatley preceeding the basic start must be 0 * for basic to function properly. */ if(min_start > valuepos) { /* It not covered by the files to crunch. Since the * default fill value is 0 we don't need to set it but we * need to include that location in the crunch as well. */ min_start = valuepos; } else { int value = p[valuepos]; /* it has been covered by at least one file. Let's check * if it is zero. */ if(value != 0) { /* Hm, its not, danger Will Robinson! */ LOG(LOG_WARNING, ("Warning, basic will probably not work since the value of" " the location \npreceeding the basic start ($%04X)" " is not 0 but %d.\n", valuepos, value)); } } } /* move memory to beginning of buffer */ membuf_truncate(mem, max_end); membuf_trim(mem, min_start); return min_start; } static void print_command_usage(const char *appl, enum log_level level) { /* done */ LOG(level, ("usage: %s level|mem|sfx|raw|desfx [option]... infile[,<address>]...\n" " see the individual commands for more help.\n", appl)); } static void print_level_usage(const char *appl, enum log_level level, const char *default_outfile) { /* done */ LOG(level, ("usage: %s level [option]... infile[,<address>]...\n" " The level command generates outfiles that are intended to be decrunched on\n" " the fly while being read.\n", appl)); LOG(level, (" -f crunch forward\n")); print_crunch_flags(level, default_outfile); LOG(level, (" All infiles are crunched separately and concatenated in the outfile in the\n" " order they are given on the command-line.\n")); } static void print_mem_usage(const char *appl, enum log_level level, const char *default_outfile) { /* done */ LOG(level, ("usage: %s mem [option]... infile[,<address>]...\n" " The mem command generates outfiles that are intended to be decrunched from\n" " memory after being loaded or assembled there.\n", appl)); LOG(level, (" -l <address> adds load address to the outfile, using \"none\" as <address>\n" " will skip the load address.\n")); LOG(level, (" -f crunch forward\n")); print_crunch_flags(level, default_outfile); LOG(level, (" All infiles are merged into the outfile. They are loaded in the order\n" " they are given on the command-line, from left to right.\n")); } static void print_raw_usage(const char *appl, enum log_level level, const char *default_out_name) { LOG(level, ("usage: %s [option]... infile\n", appl)); LOG(level, (" -b crunch/decrunch backwards\n" " -r write outfile in reverse order\n" " -d decrunch (instead of crunch)\n")); print_crunch_flags(level, default_out_name); } static void print_sfx_usage(const char *appl, enum log_level level, const char *default_outfile) { /* done */ LOG(level, ("usage: %s sfx basic[,<start>[,<end>[,<high>]]]|sys[,<start>]|<jmpaddress> [option]... infile[,<address>]...\n" " The sfx command generates outfiles that are intended to decrunch themselves.\n" " The basic start argument will start a basic program.\n" " The sys start argument will auto detect the start address by searching the\n" " basic start for a sys command.\n" " the <jmpaddress> start argument will jmp to the given address.\n" " -t<target> sets the decruncher target, must be one of 1, 20, 23, 52, 55\n", appl)); LOG(level, (" 16, 4, 64, 128, 162 or 168, default is 64\n" " -X<custom slow effect assembler fragment>\n" " -x[1-3]|<custom fast effect assembler fragment>\n" " decrunch effect, assembler fragment (don't change X-reg, Y-reg\n" " or carry) or 1 - 3 for different fast border flash effects\n" " -n no effect, can't be combined with -X or -x\n" " -D<symbol>=<value>\n" " predefines symbols for the sfx assembler\n")); LOG(level, (" -s<custom enter assembler fragment>\n" " -f<custom exit assembler fragment>\n")); print_crunch_flags(level, default_outfile); LOG(level, (" All infiles are merged into the outfile. They are loaded in the order\n" " they are given on the command-line, from left to right.\n")); } static void print_desfx_usage(const char *appl, enum log_level level, const char *default_outfile) { /* done */ LOG(level, ("usage: %s desfx [option]... infile\n" " The desfx command decrunches files that previously been crunched using the\n" " sfx command.\n", appl)); LOG(level, (" -e <address> overrides the automatic entry point detection, using \"load\" as\n" " <address> sets it to the load address of the infile\n")); print_base_flags(level, default_outfile); } static void level(const char *appl, int argc, char *argv[]) { char flags_arr[32]; int forward_mode = 0; int literal_sequences_used = 0; int max_safety = 0; int c; int infilec; char **infilev; struct crunch_options options[1] = { CRUNCH_OPTIONS_DEFAULT }; struct common_flags flags[1] = {{NULL, DEFAULT_OUTFILE}}; struct membuf in[1]; struct membuf out[1]; flags->options = options; LOG(LOG_DUMP, ("flagind %d\n", flagind)); sprintf(flags_arr, "f%s", CRUNCH_FLAGS); while ((c = getflag(argc, argv, flags_arr)) != -1) { LOG(LOG_DUMP, (" flagind %d flagopt '%c'\n", flagind, c)); switch (c) { case 'f': forward_mode = 1; break; default: handle_crunch_flags(c, flagarg, print_level_usage, appl, flags); } } membuf_init(in); membuf_init(out); infilev = argv + flagind; infilec = argc - flagind; if (infilec == 0) { LOG(LOG_ERROR, ("Error: no input files to process.\n")); print_level_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } /* append the files instead of merging them */ for(c = 0; c < infilec; ++c) { struct crunch_info info[1]; int in_load; int in_len; int out_pos; out_pos = membuf_memlen(out); in_load = do_load(infilev[c], in); in_len = membuf_memlen(in); if(forward_mode) { /* append the starting address of decrunching */ membuf_append_char(out, in_load >> 8); membuf_append_char(out, in_load & 255); crunch(in, out, options, info); } else { crunch_backwards(in, out, options, info); /* append the starting address of decrunching */ membuf_append_char(out, (in_load + in_len) & 255); membuf_append_char(out, (in_load + in_len) >> 8); /* reverse the just appended segment of the out buffer */ reverse_buffer((char*)membuf_get(out) + out_pos, membuf_memlen(out) - out_pos); } if(info->literal_sequences_used) { literal_sequences_used = 1; } if(info->needed_safety_offset > max_safety) { max_safety = info->needed_safety_offset; } } LOG(LOG_NORMAL, (" Literal sequences are %sused and", literal_sequences_used ? "" : "not ")); LOG(LOG_NORMAL, (" the largest safety offset is %d.\n", max_safety)); write_file(flags->outfile, out); membuf_free(out); membuf_free(in); } static void mem(const char *appl, int argc, char *argv[]) { char flags_arr[32]; int forward_mode = 0; int load_addr = -1; int prepend_load_addr = 1; int c; int infilec; char **infilev; struct crunch_options options[1] = { CRUNCH_OPTIONS_DEFAULT }; struct common_flags flags[1] = {{NULL, DEFAULT_OUTFILE}}; struct membuf in[1]; struct membuf out[1]; flags->options = options; LOG(LOG_DUMP, ("flagind %d\n", flagind)); sprintf(flags_arr, "fl:%s", CRUNCH_FLAGS); while ((c = getflag(argc, argv, flags_arr)) != -1) { LOG(LOG_DUMP, (" flagind %d flagopt '%c'\n", flagind, c)); switch(c) { case 'f': forward_mode = 1; break; case 'l': if(strcmp(flagarg, "none") == 0) { prepend_load_addr = 0; } else if(str_to_int(flagarg, &load_addr) != 0 || load_addr < 0 || load_addr >= 65536) { LOG(LOG_ERROR, ("Error: invalid address for -l option, " "must be in the range of [0 - 0xffff]\n")); print_mem_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } break; default: handle_crunch_flags(c, flagarg, print_mem_usage, appl, flags); } } membuf_init(in); membuf_init(out); infilev = argv + flagind; infilec = argc - flagind; if (infilec == 0) { LOG(LOG_ERROR, ("Error: no input files to process.\n")); print_mem_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } { struct crunch_info info[1]; int in_load; int in_len; int safety; in_load = do_loads(infilec, infilev, in, -1, -1, NULL, NULL); in_len = membuf_memlen(in); LOG(LOG_NORMAL, (" crunching from $%04X to $%04X ", in_load, in_load + in_len)); /* make room for load addr */ if(prepend_load_addr) { membuf_append(out, NULL, 2); } if(forward_mode) { /* append the in_loading address of decrunching */ membuf_append_char(out, in_load >> 8); membuf_append_char(out, in_load & 255); crunch(in, out, options, info); safety = info->needed_safety_offset; } else { crunch_backwards(in, out, options, info); safety = info->needed_safety_offset; /* append the in_loading address of decrunching */ membuf_append_char(out, (in_load + in_len) & 255); membuf_append_char(out, (in_load + in_len) >> 8); } /* prepend load addr */ if(prepend_load_addr) { char *p; if(load_addr < 0) { /* auto load addr specified */ load_addr = in_load; if(forward_mode) { load_addr += in_len + safety - membuf_memlen(out) + 2; } else { load_addr -= safety; } } p = membuf_get(out); p[0] = load_addr & 255; p[1] = load_addr >> 8; LOG(LOG_NORMAL, (" The load address is $%04X - $%04X.\n", load_addr, load_addr + membuf_memlen(out) - 2)); } else { LOG(LOG_NORMAL, (" No load address, data length is $%04X.\n", membuf_memlen(out))); } LOG(LOG_NORMAL, (" Literal sequences are %sused and", info->literal_sequences_used ? "" : "not ")); LOG(LOG_NORMAL, (" the safety offset is %d.\n", info->needed_safety_offset)); } write_file(flags->outfile, out); membuf_free(out); membuf_free(in); } static const struct target_info * get_target_info(int target) { static const struct target_info targets[] = { {1, 0xbf, 0x0501, 0x10000, "Oric"}, {20, 0x9e, 0x1001, 0x2000, "Vic20"}, {23, 0x9e, 0x0401, 0x2000, "Vic20+3kB"}, {52, 0x9e, 0x1201, 0x8000, "Vic20+32kB"}, {55, 0x9e, 0x1201, 0x8000, "Vic20+3kB+32kB"}, {16, 0x9e, 0x1001, 0x4000, "C16"}, {4, 0x9e, 0x1001, 0xfd00, "plus4"}, {64, 0x9e, 0x0801, 0x10000, "C64"}, {128, 0x9e, 0x1c01, 0xff00, "C128"}, {162, 0x8c, 0x0801, 0xc000, "Apple ][+"}, {168, -1, 0x2000, 0xd000, "Atari 400/800 XL/XE"}, {0, -1, -1, -1, NULL} }; const struct target_info *targetp; for(targetp = targets; targetp->id != 0; ++targetp) { if(target == targetp->id) { break; } } if(targetp->id == 0) { targetp = NULL; } return targetp; } static void do_effect(const char *appl, int no_effect, char *fast, char *slow) { struct membuf *fx = NULL; if(no_effect + (fast != NULL) + (slow != NULL) > 1) { LOG(LOG_ERROR, ("Error: can't combine any of the -n, -x or -X flags.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } if(no_effect) { set_initial_symbol("i_effect", -1); } else if(fast != NULL) { int value; if(str_to_int(fast, &value) == 0) { if(value == 1) set_initial_symbol("i_effect", 1); else if(value == 2) set_initial_symbol("i_effect", 2); else if(value == 3) set_initial_symbol("i_effect", 3); else { LOG(LOG_ERROR, ("Error: invalid range for effect shorthand, " "must be in the range of [1 - 3]\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } } else { set_initial_symbol("i_effect_custom", 1); fx = new_initial_named_buffer("effect_custom"); membuf_append(fx, fast, strlen(fast)); } set_initial_symbol("i_effect_speed", 1); } else if(slow != NULL) { int value; if(str_to_int(slow, &value) == 0) { LOG(LOG_ERROR, ("Error: Can't use shorthand for -X flag.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } else { set_initial_symbol("i_effect_custom", 1); fx = new_initial_named_buffer("effect_custom"); membuf_append(fx, slow, strlen(slow)); set_initial_symbol("i_effect_speed", 0); } } else { set_initial_symbol("i_effect", 0); set_initial_symbol("i_effect_speed", 0); } } static void sfx(const char *appl, int argc, char *argv[]) { int in_load; int in_len; int basic_txt_start = -1; int basic_var_start = -1; int basic_highest_addr = -1; int decr_target = 64; int sys_addr = -1; int no_effect = 0; char *fast = NULL; char *slow = NULL; char *enter_custom = NULL; char *exit_custom = NULL; char flags_arr[32]; int c; int infilec; char **infilev; struct crunch_info info[1]; struct crunch_options options[1] = { CRUNCH_OPTIONS_DEFAULT }; struct common_flags flags[1] = {{NULL, DEFAULT_OUTFILE}}; const struct target_info *targetp; struct membuf buf1[1]; struct membuf *in; struct membuf *out; flags->options = options; if(argc <= 1) { LOG(LOG_ERROR, ("Error: no start argument given.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } parse_init(); /* required argument: how to start the crunched program */ do { char *p = strtok(argv[1], ","); if (strcmp(p, "sys") == 0) { /* we should look for a basic sys command. */ sys_addr = -1; p = strtok(NULL, ","); /* look for an optional basic start address */ if(p == NULL) break; if(str_to_int(p, &basic_txt_start) != 0) { LOG(LOG_ERROR, ("Error: invalid value for the start of basic text " "address.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } } else if(strcmp(p, "basic") == 0) { /* we should start a basic program. */ sys_addr = -2; p = strtok(NULL, ","); /* look for an optional basic start address */ if(p == NULL) break; if(str_to_int(p, &basic_txt_start) != 0) { LOG(LOG_ERROR, ("Error: invalid value for the start of basic text " "address.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } p = strtok(NULL, ","); /* look for an optional basic end address */ if(p == NULL) break; if(str_to_int(p, &basic_var_start) != 0) { LOG(LOG_ERROR, ("Error: invalid value for the start of basic " "variables address.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } p = strtok(NULL, ","); /* look for an optional highest address used by basic */ if(p == NULL) break; if(str_to_int(p, &basic_highest_addr) != 0) { LOG(LOG_ERROR, ("Error: invalid value for the highest address used " "by basic address.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } } else if(str_to_int(p, &sys_addr) != 0 || sys_addr < 0 || sys_addr >= 65536) { /* we got an address we should jmp to. */ LOG(LOG_ERROR, ("Error: invalid address for <start>, " "must be in the range of [0 - 0xffff]\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } } while(0); LOG(LOG_DUMP, ("flagind %d\n", flagind)); sprintf(flags_arr, "nD:t:x:X:s:f:%s", CRUNCH_FLAGS); while ((c = getflag(argc, argv, flags_arr)) != -1) { char *p; LOG(LOG_DUMP, (" flagind %d flagopt '%c'\n", flagind, c)); switch(c) { case 't': if (str_to_int(flagarg, &decr_target) != 0 || get_target_info(decr_target) == NULL) { LOG(LOG_ERROR, ("error: invalid value, %d, for -t option, must be one of " "1, 20, 23, 52, 55, 16, 4, 64, 128, 162 or 168.\n", decr_target)); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } break; case 'n': no_effect = 1; break; case 'x': fast = strdup(flagarg); break; case 'X': slow = strdup(flagarg); break; case 's': enter_custom = strdup(flagarg); break; case 'f': exit_custom = strdup(flagarg); break; case 'D': p = strrchr(flagarg, '='); if(p != NULL) { int value; if(str_to_int(p + 1, &value) != 0) { LOG(LOG_ERROR, ("Error: invalid value for -D " "<symbol>[=<value>] option.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } /* This is ugly, we really should allocate our own * copy of the symbol string. */ *p = '\0'; set_initial_symbol(flagarg, value); } else { LOG(LOG_ERROR, ("Error: invalid value for -D " "<symbol>=<value> option.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } break; default: handle_crunch_flags(c, flagarg, print_sfx_usage, appl, flags); } } do_effect(appl, no_effect, fast, slow); if(enter_custom != NULL) { set_initial_symbol("i_enter_custom", 1); membuf_append(new_initial_named_buffer("enter_custom"), enter_custom, strlen(enter_custom)); } if(exit_custom != NULL) { set_initial_symbol("i_exit_custom", 1); membuf_append(new_initial_named_buffer("exit_custom"), exit_custom, strlen(exit_custom)); } membuf_init(buf1); in = buf1; out = new_initial_named_buffer("crunched_data"); infilev = argv + flagind + 1; infilec = argc - flagind - 1; if (infilec == 0) { LOG(LOG_ERROR, ("Error: no input files to process.\n")); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } targetp = get_target_info(decr_target); if(sys_addr == -2 && targetp->id == 168) { /* basic start not implemented for Apple and Atari targets */ LOG(LOG_ERROR, ("Start address \"basic\" is not supported for " "the %s target.\n", targetp->model)); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } if(sys_addr == -1 && targetp->id == 162) { /* auto detecting of start address not implemented for Apple target */ LOG(LOG_ERROR, ("Start address \"sys\" is not supported for " "the %s target\n", targetp->model)); print_sfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } if(basic_txt_start == -1) { basic_txt_start = targetp->basic_txt_start; } { int safety; int *basic_var_startp; int *sys_addrp; int basic_start; sys_addrp = NULL; basic_var_startp = NULL; if(sys_addr == -2 && basic_var_start == -1) { basic_var_startp = &basic_var_start; } basic_start = -1; if(sys_addr < 0) { basic_start = basic_txt_start; if(sys_addr == -1) { sys_addrp = &sys_addr; } } in_load = do_loads(infilec, infilev, in, basic_start, targetp->sys_token, basic_var_startp, sys_addrp); in_len = membuf_memlen(in); if(in_load + in_len > targetp->end_of_ram) { LOG(LOG_ERROR, ("Error:\n The memory of the %s target ends at " "$%04X and can't hold the uncrunched data\n " "that covers $%04X to $%04X.\n", targetp->model, targetp->end_of_ram, in_load, in_load + in_len)); exit(-1); } LOG(LOG_NORMAL, (" crunching from $%04X to $%04X ", in_load, in_load + in_len)); if(decr_target == 20 || decr_target == 52) { /* these are vic20 targets with a memory hole from * $0400-$1000. Each page is filled with the value of the * high-byte of its address. */ if(in_load >= 0x0400 && in_load + in_len <= 0x1000) { /* all the loaded data is in the memory hole.*/ LOG(LOG_ERROR, ("Error: all data loaded to the memory hole.\n")); exit(-1); } else if(in_load >= 0x0400 && in_load < 0x1000 && in_load + in_len > 0x1000) { /* The data starts in the memory hole and ends in * RAM. We need to adjust the start. */ int diff = 0x1000 - in_load; in_load += diff; in_len -= diff; membuf_trim(in, diff); LOG(LOG_WARNING, ("Warning, trimming address interval to $%04X-$%04X.\n", in_load, in_load + in_len)); } else if(in_load < 0x0400 && in_load + in_len >= 0x0400 && in_load + in_len < 0x1000) { /* The data starts in RAM and ends in the memory * hole. We need to adjust the end. */ int diff = in_load + in_len - 0x0400; in_len -= diff; membuf_truncate(in, in_len); LOG(LOG_WARNING, ("Warning, trimming address interval to $%04X-$%04X.\n", in_load, in_load + in_len)); } else if(in_load < 0x0400 && in_load + in_len > 0x1000) { /* The data starts in RAM covers the memory hole and * ends in RAM. */ int hi, lo; char *p; p = membuf_get(in); for(hi = 0x04; hi < 0x10; hi += 0x01) { for(lo = 0; lo < 256; ++lo) { int addr = (hi << 8) | lo; p[addr - in_load] = hi; } } LOG(LOG_NORMAL, ("Memory hole at interval $0400-$1000 " "included in crunch..\n")); } } /* make room for load addr */ membuf_append(out, NULL, 2); crunch_backwards(in, out, options, info); safety = info->needed_safety_offset; /* append the in_loading address of decrunching */ membuf_append_char(out, (in_load + in_len) & 255); membuf_append_char(out, (in_load + in_len) >> 8); /* prepend load addr */ { char *p; p = membuf_get(out); p[0] = (in_load - safety) & 255; p[1] = (in_load - safety) >> 8; } } LOG(LOG_NORMAL, (" Target is self-decrunching %s executable", targetp->model)); if(sys_addr == -1) { LOG(LOG_ERROR, ("\nError: can't find sys address (token $%02X)" " at basic text start ($%04X).\n", targetp->sys_token, basic_txt_start)); exit(-1); } if(sys_addr != -2) { LOG(LOG_NORMAL, (",\n jmp address $%04X.\n", sys_addr)); } else { LOG(LOG_NORMAL, (",\n basic start ($%04X-$%04X).\n", basic_txt_start, basic_var_start)); } { /* add decruncher */ struct membuf source[1]; membuf_init(source); decrunch(LOG_DEBUG, sfxdecr, source); in = out; out = buf1; membuf_clear(out); set_initial_symbol("r_start_addr", sys_addr); /*initial_symbol_dump( LOG_NORMAL, "r_start_addr");*/ set_initial_symbol("r_target", decr_target); /*initial_symbol_dump( LOG_NORMAL, "r_target");*/ set_initial_symbol("r_in_load", in_load); /*initial_symbol_dump( LOG_NORMAL, "r_in_addr");*/ set_initial_symbol("r_in_len", in_len); /*initial_symbol_dump( LOG_NORMAL, "r_in_len");*/ if(sys_addr == -2) { /* only set this if its changed from the default. */ if(basic_txt_start != targetp->basic_txt_start) { set_initial_symbol("i_basic_txt_start", basic_txt_start); initial_symbol_dump( LOG_DEBUG, "i_basic_txt_start"); } /* only set this if we've been given a value for it. */ if(basic_var_start != -1) { set_initial_symbol("i_basic_var_start", basic_var_start); initial_symbol_dump(LOG_DEBUG, "i_basic_var_start"); } /* only set this if we've been given a value for it. */ if(basic_highest_addr != -1) { set_initial_symbol("i_basic_highest_addr", basic_highest_addr); initial_symbol_dump(LOG_DEBUG, "i_basic_highest_addr"); } } if(info->literal_sequences_used) { set_initial_symbol("i_literal_sequences_used", 1); initial_symbol_dump(LOG_DEBUG, "i_literal_sequences_used"); } if(assemble(source, out) != 0) { LOG(LOG_ERROR, ("Parse failure.\n")); } else { i32 v_safety_addr; i32 transfer_len; i32 i_table_addr; i32 i_effect; i32 c_effect_color; i32 cover_start = in_load; resolve_symbol("v_safety_addr", NULL, &v_safety_addr); resolve_symbol("transfer_len", NULL, &transfer_len); resolve_symbol("i_table_addr", NULL, &i_table_addr); resolve_symbol("i_effect2", NULL, &i_effect); if(transfer_len != 0) { cover_start = v_safety_addr; } LOG(LOG_NORMAL, ("Memory layout:\n")); LOG(LOG_NORMAL, (" Data covers $%04X to $%04X.\n", cover_start, in_load + in_len)); LOG(LOG_NORMAL, (" Decrunch table is located at $%04X to $%04X.\n", i_table_addr, i_table_addr + 156)); if(i_effect == 0 && !resolve_symbol("i_effect_custom", NULL, NULL)) { resolve_symbol("c_effect_color", NULL, &c_effect_color); LOG(LOG_NORMAL, (" Decrunch effect writes to $%04X.\n", c_effect_color)); } } membuf_free(source); } write_file(flags->outfile, out); membuf_free(buf1); parse_free(); } static void raw(const char *appl, int argc, char *argv[]) { char flags_arr[32]; int decrunch_mode = 0; int backwards_mode = 0; int reverse_mode = 0; int c, infilec; char **infilev; static struct crunch_options options[1] = { CRUNCH_OPTIONS_DEFAULT }; struct common_flags flags[1] = { {options, DEFAULT_OUTFILE} }; struct membuf inbuf[1]; struct membuf outbuf[1]; LOG(LOG_DUMP, ("flagind %d\n", flagind)); sprintf(flags_arr, "bdr%s", CRUNCH_FLAGS); while ((c = getflag(argc, argv, flags_arr)) != -1) { LOG(LOG_DUMP, (" flagind %d flagopt '%c'\n", flagind, c)); switch (c) { case 'b': backwards_mode = 1; break; case 'r': reverse_mode = 1; break; case 'd': decrunch_mode = 1; break; default: handle_crunch_flags(c, flagarg, print_raw_usage, appl, flags); } } infilev = argv + flagind; infilec = argc - flagind; if (infilec != 1) { LOG(LOG_ERROR, ("Error: exactly one input file must be given.\n")); print_raw_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } membuf_init(inbuf); membuf_init(outbuf); load_plain_file(infilev[0], inbuf); if(decrunch_mode) { int seems_backward = 0; int seems_forward = 0; unsigned char *p; p = membuf_get(inbuf); if(p[0] == 0x80 && p[1] == 0x0) { seems_backward = 1; } p += membuf_memlen(inbuf); if(p[-1] == 0x80 && p[-2] == 0x0) { seems_forward = 1; } /* do we know what way it was crunched? */ if((seems_backward ^ seems_forward) != 0) { /* yes, override option. */ backwards_mode = seems_backward; } if(backwards_mode) { LOG(LOG_NORMAL, ("Decrunching infile \"%s\" to outfile \"%s\" " " backwards.\n", infilev[0], flags->outfile)); decrunch_backwards(LOG_NORMAL, inbuf, outbuf); } else { LOG(LOG_NORMAL, ("Decrunching infile \"%s\" to outfile \"%s\".\n", infilev[0], flags->outfile)); decrunch(LOG_NORMAL, inbuf, outbuf); } } else { struct crunch_info info[1]; if(backwards_mode) { LOG(LOG_NORMAL, ("Crunching infile \"%s\" to outfile \"%s\" " "backwards.\n", infilev[0], flags->outfile)); crunch_backwards(inbuf, outbuf, options, info); } else { LOG(LOG_NORMAL, ("Crunching infile \"%s\" to outfile \"%s\".\n", infilev[0], flags->outfile)); crunch(inbuf, outbuf, options, info); } LOG(LOG_NORMAL, (" Literal sequences are %sused and", info->literal_sequences_used ? "" : "not ")); LOG(LOG_NORMAL, (" the safety offset is %d.\n", info->needed_safety_offset)); } if(reverse_mode) { reverse_buffer(membuf_get(outbuf), membuf_memlen(outbuf)); } write_file(flags->outfile, outbuf); membuf_free(outbuf); membuf_free(inbuf); } static void desfx(const char *appl, int argc, char *argv[]) { char flags_arr[32]; struct load_info info[1]; struct membuf mem[1]; const char *outfile = DEFAULT_OUTFILE; int c, infilec; char **infilev; u8 *p; u16 start; u16 end; int cookedend; int entry = -1; LOG(LOG_DUMP, ("flagind %d\n", flagind)); sprintf(flags_arr, "e:%s", BASE_FLAGS); while ((c = getflag(argc, argv, flags_arr)) != -1) { LOG(LOG_DUMP, (" flagind %d flagopt '%c'\n", flagind, c)); switch (c) { case 'e': if(strcmp(flagarg,"load") == 0) { entry = -2; } else if(str_to_int(flagarg, &entry) != 0 || entry < 0 || entry >= 65536) { LOG(LOG_ERROR,("Error: invalid address for -e option, " "must be in the range of [0 - 0xffff]\n")); print_desfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } break; default: handle_base_flags(c, flagarg, print_desfx_usage, appl, &outfile); } } infilev = argv + flagind; infilec = argc - flagind; if (infilec != 1) { LOG(LOG_ERROR, ("Error: exactly one input file must be given.\n")); print_desfx_usage(appl, LOG_NORMAL, DEFAULT_OUTFILE); exit(-1); } membuf_init(mem); membuf_append(mem, NULL, 65536); p = membuf_get(mem); /* load file, don't care about tracking basic*/ info->basic_txt_start = -1; load_located(infilev[0], p, info); if(entry == -1) { /* use detected address */ entry = info->run; } else if(entry == -2) { /* use load address */ entry = info->start; } /* no start address from load */ if(entry == -1) { /* look for sys line */ entry = find_sys(p + info->start, -1); } if(entry == -1) { LOG(LOG_ERROR, ("Error, can't find entry point.\n")); exit(-1); } LOG(LOG_NORMAL, (" crunched file entry point $%04X\n", entry)); entry = decrunch_sfx(p, entry, &start, &end); /* change 0x0 into 0x10000 */ cookedend = ((end - 1) & 0xffff) + 1; LOG(LOG_NORMAL, (" decrunched entry point $%04X, from $%04X to $%04X\n", entry, start, cookedend)); membuf_truncate(mem, cookedend); membuf_trim(mem, start); membuf_insert(mem, 0, NULL, 2); p = membuf_get(mem); p[0] = start; p[1] = start >> 8; write_file(outfile, mem); membuf_free(mem); } int main(int argc, char *argv[]) { const char *appl; /* init logging */ LOG_INIT_CONSOLE(LOG_NORMAL); appl = fixup_appl(argv[0]); if(argc < 2) { /* missing required command */ LOG(LOG_ERROR, ("Error: required command is missing.\n")); print_command_usage(appl, LOG_ERROR); exit(-1); } ++argv; --argc; if(strcmp(argv[0], "level") == 0) { level(appl, argc, argv); } else if(strcmp(argv[0], "mem") == 0) { mem(appl, argc, argv); } else if(strcmp(argv[0], "sfx") == 0) { sfx(appl, argc, argv); } else if(strcmp(argv[0], "raw") == 0) { raw(appl, argc, argv); } else if(strcmp(argv[0], "desfx") == 0) { desfx(appl, argc, argv); } else if(strcmp(argv[0], "-v") == 0) { print_license(); } else if(strcmp(argv[0], "-?") == 0) { print_command_usage(appl, LOG_NORMAL); } else { /* unknown command */ LOG(LOG_ERROR, ("Error: unrecognised command \"%s\".\n", argv[0])); print_command_usage(appl, LOG_ERROR); exit(-1); } LOG_FREE; return 0; }
30.043712
120
0.508965
[ "model" ]
4029fe8e00f035866be96ad0a2a8164fada16415
4,585
h
C
aws-cpp-sdk-globalaccelerator/include/aws/globalaccelerator/model/AddCustomRoutingEndpointsResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-globalaccelerator/include/aws/globalaccelerator/model/AddCustomRoutingEndpointsResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-globalaccelerator/include/aws/globalaccelerator/model/AddCustomRoutingEndpointsResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/globalaccelerator/GlobalAccelerator_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/globalaccelerator/model/CustomRoutingEndpointDescription.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace GlobalAccelerator { namespace Model { class AWS_GLOBALACCELERATOR_API AddCustomRoutingEndpointsResult { public: AddCustomRoutingEndpointsResult(); AddCustomRoutingEndpointsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AddCustomRoutingEndpointsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline const Aws::Vector<CustomRoutingEndpointDescription>& GetEndpointDescriptions() const{ return m_endpointDescriptions; } /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline void SetEndpointDescriptions(const Aws::Vector<CustomRoutingEndpointDescription>& value) { m_endpointDescriptions = value; } /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline void SetEndpointDescriptions(Aws::Vector<CustomRoutingEndpointDescription>&& value) { m_endpointDescriptions = std::move(value); } /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline AddCustomRoutingEndpointsResult& WithEndpointDescriptions(const Aws::Vector<CustomRoutingEndpointDescription>& value) { SetEndpointDescriptions(value); return *this;} /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline AddCustomRoutingEndpointsResult& WithEndpointDescriptions(Aws::Vector<CustomRoutingEndpointDescription>&& value) { SetEndpointDescriptions(std::move(value)); return *this;} /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline AddCustomRoutingEndpointsResult& AddEndpointDescriptions(const CustomRoutingEndpointDescription& value) { m_endpointDescriptions.push_back(value); return *this; } /** * <p>The endpoint objects added to the custom routing accelerator.</p> */ inline AddCustomRoutingEndpointsResult& AddEndpointDescriptions(CustomRoutingEndpointDescription&& value) { m_endpointDescriptions.push_back(std::move(value)); return *this; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline const Aws::String& GetEndpointGroupArn() const{ return m_endpointGroupArn; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline void SetEndpointGroupArn(const Aws::String& value) { m_endpointGroupArn = value; } /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline void SetEndpointGroupArn(Aws::String&& value) { m_endpointGroupArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline void SetEndpointGroupArn(const char* value) { m_endpointGroupArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline AddCustomRoutingEndpointsResult& WithEndpointGroupArn(const Aws::String& value) { SetEndpointGroupArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline AddCustomRoutingEndpointsResult& WithEndpointGroupArn(Aws::String&& value) { SetEndpointGroupArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the endpoint group for the custom routing * endpoint.</p> */ inline AddCustomRoutingEndpointsResult& WithEndpointGroupArn(const char* value) { SetEndpointGroupArn(value); return *this;} private: Aws::Vector<CustomRoutingEndpointDescription> m_endpointDescriptions; Aws::String m_endpointGroupArn; }; } // namespace Model } // namespace GlobalAccelerator } // namespace Aws
36.68
183
0.724755
[ "vector", "model" ]
72d45bf58b43f35dcb2896a464d64aaf40b65479
502
h
C
morphs/morph_opensimplex/include/morph_opensimplex.h
syntheticmagus/polymorph_proto_simplex_mountains
1a11c5e1d4cdefd652bd64166a261fbdfa4f2b89
[ "MIT" ]
null
null
null
morphs/morph_opensimplex/include/morph_opensimplex.h
syntheticmagus/polymorph_proto_simplex_mountains
1a11c5e1d4cdefd652bd64166a261fbdfa4f2b89
[ "MIT" ]
null
null
null
morphs/morph_opensimplex/include/morph_opensimplex.h
syntheticmagus/polymorph_proto_simplex_mountains
1a11c5e1d4cdefd652bd64166a261fbdfa4f2b89
[ "MIT" ]
1
2021-05-05T17:21:00.000Z
2021-05-05T17:21:00.000Z
#pragma once #include <pipeline.h> #include <vector> namespace morph_opensimplex { PIPELINE_TYPE(Width, size_t); PIPELINE_TYPE(Height, size_t); PIPELINE_TYPE(Frequency, double); PIPELINE_TYPE(Values, std::vector<double>); using InContract = IN_CONTRACT(Width, Height, Frequency); using OutContract = OUT_CONTRACT(Values); } PIPELINE_CONTEXT(GenerateOpenSimplexMap, morph_opensimplex::InContract, morph_opensimplex::OutContract); void Run(GenerateOpenSimplexMap&);
23.904762
61
0.752988
[ "vector" ]
72d998267fff93e65fa1a9ee3dc6708cefe6c396
3,971
h
C
src/mongo/db/geo/geoparser.h
wentingwang/morphus
af40299a5f07fd3157946112738f602a566a9908
[ "Apache-2.0" ]
24
2015-10-15T00:03:57.000Z
2021-04-25T18:21:31.000Z
src/mongo/db/geo/geoparser.h
stennie/mongo
9ff44ae9ad16a70e49517a78279260a37d31ac7c
[ "Apache-2.0" ]
1
2015-06-02T12:19:19.000Z
2015-06-02T12:19:19.000Z
src/mongo/db/geo/geoparser.h
stennie/mongo
9ff44ae9ad16a70e49517a78279260a37d31ac7c
[ "Apache-2.0" ]
3
2017-07-26T11:17:11.000Z
2021-11-30T00:11:32.000Z
/** * Copyright (C) 2008-2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "mongo/db/jsobj.h" #include <vector> #include "third_party/s2/s2.h" #include "mongo/db/geo/shapes.h" class S2Cap; class S2Cell; class S2Polyline; class S2Polygon; namespace mongo { // This class parses geographic data. // It parses a subset of GeoJSON and creates S2 shapes from it. // See http://geojson.org/geojson-spec.html for the spec. // // This class also parses the ad-hoc geo formats that MongoDB introduced. // // The parseFoo methods that return a bool internally call isFoo and return true // if the foo is parsed correctly. // The parseFoo methods that do not return a bool assume isFoo is true. // // We assume that if you're trying to parse something, you know it's valid. class GeoParser { public: // Try to parse GeoJSON, then try legacy format, return true if either succeed. // These call the various isPoint and parsePoint methods below. // You can just use these bool parsePoint(...) methods. static bool parsePoint(const BSONObj &obj, S2Point *out); static bool parsePoint(const BSONObj &obj, S2Cell *out); static bool parsePoint(const BSONObj &obj, Point *out); // Check to see if it's GeoJSON or if it's legacy geo. static bool isPoint(const BSONObj &obj); static bool isGeoJSONPoint(const BSONObj &obj); static void parseGeoJSONPoint(const BSONObj &obj, S2Point *out); static void parseGeoJSONPoint(const BSONObj &obj, S2Cell *out); static void parseGeoJSONPoint(const BSONObj &obj, Point *out); static bool isLegacyPoint(const BSONObj &obj); static void parseLegacyPoint(const BSONObj &obj, S2Point *out); static void parseLegacyPoint(const BSONObj &obj, Point *out); static bool parseLineString(const BSONObj &obj, S2Polyline *out); static bool isLineString(const BSONObj &obj); static bool isGeoJSONLineString(const BSONObj &obj); static void parseGeoJSONLineString(const BSONObj &obj, S2Polyline *out); static bool parsePolygon(const BSONObj &obj, S2Polygon *out); static bool parsePolygon(const BSONObj &obj, Polygon *out); static bool isPolygon(const BSONObj &obj); static bool isGeoJSONPolygon(const BSONObj &obj); static bool isLegacyPolygon(const BSONObj &obj); static void parseGeoJSONPolygon(const BSONObj &obj, S2Polygon *out); static void parseLegacyPolygon(const BSONObj &obj, Polygon *out); static bool isLegacyBox(const BSONObj &obj); static void parseLegacyBox(const BSONObj &obj, Box *out); static bool isLegacyCenter(const BSONObj &obj); static void parseLegacyCenter(const BSONObj &obj, Circle *out); static bool isLegacyCenterSphere(const BSONObj &obj); static void parseLegacyCenterSphere(const BSONObj &obj, S2Cap *out); // Return true if the CRS field is 1. missing, or 2. is well-formed and // has a datum we accept. Otherwise, return false. // NOTE(hk): If this is ever used anywhere but internally, consider // returning states: missing, invalid, unknown, ok, etc. -- whatever // needed. static bool crsIsOK(const BSONObj& obj); }; } // namespace mongo
43.637363
87
0.69101
[ "vector" ]
72e173dd5887bf41b34edebf147ce3231bfd4c21
3,296
h
C
Source/fnt/fnt_tool.h
HiPhish/XeenTools
e4774adaba2688cb187bbafaa380386b3843ff4a
[ "MIT" ]
12
2015-06-02T16:05:54.000Z
2021-07-08T21:43:27.000Z
Source/fnt/fnt_tool.h
HiPhish/XeenTools
e4774adaba2688cb187bbafaa380386b3843ff4a
[ "MIT" ]
null
null
null
Source/fnt/fnt_tool.h
HiPhish/XeenTools
e4774adaba2688cb187bbafaa380386b3843ff4a
[ "MIT" ]
null
null
null
#ifndef XEEN_FNT_TOOL_H #define XEEN_FNT_TOOL_H /** @file fnt_tool.h * * Interface for FNT font files. * * A font file is a file named simply *FNT*, without extension. All font files * have the same size: the number of ASCII characters times two times times * the number of lines per character times two bytes. * * Let's break this down: for every ASCII character there are two glyphs, one * regular sized and one smaller sized. Every glyph is made of eight * horizontal lines and every line is made of two bytes. That's a total of * 4.096 bytes. * * For every glyph there is also spacing information, always stored as one * byte each. * * The glyph array is therefore a three-dimensional array: The outer dimension * is the ASCII character, the middle dimension the variant (large or small) * and the inner array are the lines. * * Every line is 16 bits large and every glyph pixel is stored as two bits, * that's eight bits per line. Every pixel can have a value between 0 and 3, * with 0 being transparent. That means a character can have three different * colours. Lines are stored form left to right. * * To decode the pixel of a line mask the two bits first and then push them to * the right. In general, given a line and an index * @code * uint16_t l; * int i; // i < XEEN_GLYPH_LINE_PIXELS * @endcode * we need a mask * @code * uint16_t mask = (0xC000 >> XEEN_GLYPH_PIXEL_SIZE * i) * @code * to get the two bits we want. Then we must right-shift the bits * @code * uint8_t pixel = (l&mask) >> XEEN_GLYPH_PIXEL_SIZE*(XEEN_GLYPH_LINE_PIXELS-i-1); * @endcode * to get the pixel, as a byte in this case. * * Aside from the glyphs themselves there is also spacing information stored * in the FNT file. There is one byte for every glyph, indexed first by the * character, second by the typeface. */ #include <stdint.h> #include <stdio.h> /** Number of characters stored in a FNT file */ #define XEEN_FNT_CHARS 128 /** Typefaces for a character */ enum xeen_typeface { XEEN_TYPE_LARGE, /**< Larger glyph typeface. */ XEEN_TYPE_SMALL, /**< Smaller glyph typeface. */ XEEN_TYPEFACES , /**< Number of typefaces. */ }; /** Lines per glyph. */ #define XEEN_GLYPH_LINES 8 /** Pixels per glyph line. */ #define XEEN_GLYPH_LINE_PIXELS 8 /** Size of a glyph pixels in bits (not bytes). */ #define XEEN_GLYPH_PIXEL_SIZE 2 /** Font structure. */ typedef struct xeen_font { uint16_t glyph[XEEN_FNT_CHARS][XEEN_TYPEFACES][XEEN_GLYPH_LINES]; /**< Glyphs. */ uint8_t space[XEEN_FNT_CHARS][XEEN_TYPEFACES]; /**< Spacing. */ } XeenFont; /** Read the contents of a FNT file. * * @param fp * @param o * @param fnt * * @return Error code: * - 0: Success * - 1: Invalid arguments * - 2: Failed reading file * * @pre The pointers must be valid. * * @post The font will be assigned. * * This function will mutate the font even if it fails, so be careful when * passing it a pointer. */ int xeen_read_font(FILE *fp, long o, XeenFont *fnt); /** Initialise an empty font object. * * This function just returns an empty font object where every member is zero. */ XeenFont xeen_fnt_init(); #endif /* XEEN_FNT_TOOL_H */
31.09434
87
0.684466
[ "object" ]
72eee8b0abd5570639ddd243f8a5147d78da18f7
18,059
c
C
rip.c
mgorse/urogue1.03
1c9bf818984c071eba04417927dc3934b11d3ad7
[ "BSD-3-Clause" ]
null
null
null
rip.c
mgorse/urogue1.03
1c9bf818984c071eba04417927dc3934b11d3ad7
[ "BSD-3-Clause" ]
null
null
null
rip.c
mgorse/urogue1.03
1c9bf818984c071eba04417927dc3934b11d3ad7
[ "BSD-3-Clause" ]
1
2022-03-27T23:35:48.000Z
2022-03-27T23:35:48.000Z
/* rip.c - File for the fun ends Death or a total win UltraRogue: The Ultimate Adventure in the Dungeons of Doom Copyright (C) 1985, 1986, 1992, 1993, 1995 Herb Chong All rights reserved. Based on "Advanced Rogue" Copyright (C) 1984, 1985 Michael Morgan, Ken Dalka All rights reserved. Based on "Rogue: Exploring the Dungeons of Doom" Copyright (C) 1980, 1981 Michael Toy, Ken Arnold and Glenn Wichman All rights reserved. See the file LICENSE.TXT for full copyright and licensing information. */ #include <string.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include <unistd.h> #include "rogue.h" static struct sc_ent { int sc_lvl; long sc_score; char sc_name[76]; long sc_gold; int sc_flags; int sc_level; int sc_artifacts; int sc_monster; } top_ten[10]; static const char *rip[] = { " __________", " / \\", " / REST \\", " / IN \\", " / PEACE \\", " / \\", " | |", " | |", " | killed by |", " | |", " | 1993 |", " *| * * * | *", " ________)/\\\\_//(\\/(/\\)/\\//\\/|_)_______", 0 }; /* death() Do something really fun when he dies */ void death(int monst) { char **dp = (char **) rip, *killer; struct tm *lt; time_t date; char buf[80]; int c; if (is_wearing(R_RESURRECT) || rnd(wizard ? 3 : 67) == 0) { int die = TRUE; if (resurrect-- == 0) msg("You've run out of lives."); else if (!save_resurrect(ring_value(R_RESURRECT))) msg("Your attempt to return from the grave fails."); else { struct linked_list *item; struct linked_list *next_item; struct object *obj; int rm, flags; coord pos; die = FALSE; msg("You feel a sudden warmth and then nothingness."); teleport(); if (ring_value(R_RESURRECT) > 1 && rnd(10)) { pstats.s_hpt = 2 * pstats.s_const; pstats.s_const = max(pstats.s_const - 1, 3); } else { for (item = pack; item != NULL; item = next_item) { obj = OBJPTR(item); if (obj->o_flags & ISOWNED || obj->o_flags & ISPROT) { next_item = next(item); continue; } flags = obj->o_flags; obj->o_flags &= ~ISCURSED; dropcheck(obj); obj->o_flags = flags; next_item = next(item); rem_pack(obj); if (obj->o_type == ARTIFACT) has_artifact &= ~(1 << obj->o_which); do { rm = rnd_room(); rnd_pos(&rooms[rm], &pos); } while(winat(pos.y, pos.x) != FLOOR); obj->o_pos = pos; add_obj(item, obj->o_pos.y, obj->o_pos.x); } pstats.s_hpt = pstats.s_const; pstats.s_const = max(pstats.s_const - roll(2, 2), 3); } chg_str(roll(1, 4), TRUE, FALSE); pstats.s_lvl = max(pstats.s_lvl, 1); no_command += 2 + rnd(4); if (on(player, ISHUH)) lengthen_fuse(FUSE_UNCONFUSE, rnd(8) + HUHDURATION); else light_fuse(FUSE_UNCONFUSE, 0, rnd(8) + HUHDURATION, AFTER); turn_on(player, ISHUH); light(&hero); } if (die) { wmove(cw, mpos, 0); waddstr(cw, morestr); wrefresh(cw); wait_for(' '); } else return; } time(&date); lt = localtime(&date); clear(); wclear(cw); move(8, 0); while (*dp) printw("%s\n", *dp++); mvaddstr(14, 28 - ((int)(strlen(whoami) + 1) / 2), whoami); sprintf(buf, "%d+%ld Points", pstats.s_lvl, pstats.s_exp); mvaddstr(15, 28 - ((int)(strlen(buf) + 1) / 2), buf); killer = killname(monst,buf); mvaddstr(17, 28 - ((int)(strlen(killer) + 1) / 2), killer); mvaddstr(18, 28, (sprintf(prbuf, "%2d", lt->tm_year), prbuf)); move(ur_lines - 1, 0); mvaddstr(ur_lines - 1, 0, retstr); while ((c = readcharw(stdscr)) != '\n' && c != '\r') continue; idenpack(); wrefresh(cw); refresh(); score(pstats.s_exp, pstats.s_lvl, KILLED, monst); byebye(); } /* score() figure score and post it. */ void score(long amount, int lvl, int flags, int monst) /*ARGSUSED*/ { struct sc_ent *scp=NULL, *sc2=NULL; int i; char *killer; char buf[1024]; static const char *reason[] = { "killed", "quit", "a winner", "a total winner" }; char *packend; if (flags != WINNER && flags != TOTAL && flags != SCOREIT) { if (flags == CHICKEN) packend = "when you quit"; else packend = "at your untimely demise"; noecho(); nl(); refresh(); showpack(packend); } /* Open file and read list */ if (fd_score == NULL) { printf("No score file opened\n"); return; } for (scp = top_ten; scp < &top_ten[10]; scp++) { scp->sc_lvl = 0L; scp->sc_score = 0L; for (i = 0; i < 76; i++) scp->sc_name[i] = ucrnd(255); scp->sc_gold = 0L; scp->sc_flags = rnd(10); scp->sc_level = rnd(10); scp->sc_monster = srnd(10); scp->sc_artifacts = 0; } if (flags != SCOREIT) { mvaddstr(ur_lines - 1, 0, retstr); refresh(); fflush(stdout); wait_for('\n'); } fseek(fd_score, 0L, SEEK_SET); fread(top_ten, sizeof(top_ten), 1, fd_score); /* Insert player in list if need be */ if (!waswizard) { for (scp = top_ten; scp < &top_ten[10]; scp++) { if (lvl > scp->sc_lvl) break; if (lvl == scp->sc_lvl && amount > scp->sc_score) break; } if (scp < &top_ten[10]) { if (flags == WINNER) sc2 = &top_ten[9]; /* LAST WINNER ALWAYS MAKES IT */ while (sc2 > scp) { *sc2 = sc2[-1]; sc2--; } scp->sc_lvl = lvl; scp->sc_gold = purse; scp->sc_score = amount; strcpy(scp->sc_name, whoami); strcat(scp->sc_name,", "); strcat(scp->sc_name, which_class(player.t_ctype)); scp->sc_flags = flags; if (flags == WINNER) scp->sc_level = max_level; else scp->sc_level = level; scp->sc_monster = monst; scp->sc_artifacts = has_artifact; sc2 = scp; } } if (flags != SCOREIT) { clear(); refresh(); endwin(); } /* Print the list */ printf("\nTop Ten Adventurers:\n%4s %15s %10s %s\n", "Rank", "Score", "Gold", "Name"); for (scp = top_ten; scp < &top_ten[10]; scp++) { if (scp->sc_score) { char lev[20]; sprintf(lev, "%ld+%ld", scp->sc_lvl, scp->sc_score); printf("%4d %15s %10ld %s:", scp - top_ten + 1, lev, scp->sc_gold, scp->sc_name); if (scp->sc_artifacts) { char thangs[80]; int n; int first = TRUE; thangs[0] = '\0'; for (n = 0; n <= maxartifact; n++) { if (scp->sc_artifacts & (1 << n)) { if (strlen(thangs)) strcat(thangs, ", "); if (first) { strcat(thangs, "retrieved "); first = FALSE; } if (45 - strlen(thangs) < strlen(arts[n].ar_name)) { printf("%s\n%32s", thangs," "); thangs[0] = '\0'; } strcat(thangs, arts[n].ar_name); } } if (strlen(thangs)) printf("%s,", thangs); printf("\n%32s"," "); } printf("%s on level %d",reason[scp->sc_flags],scp->sc_level); if (scp->sc_flags == 0) { printf(" by \n%32s"," "); killer = killname(scp->sc_monster, buf); printf(" %s", killer); } putchar('\n'); } } if (sc2 != NULL) { fseek(fd_score, 0L, SEEK_SET); /* Update the list file */ fwrite(top_ten, sizeof(top_ten), 1, fd_score); } fclose(fd_score); /* * delete old autosave file when we win or quit */ if (autosave == TRUE && flags != SCOREIT) { char fname[200]; strcpy(fname, home); strcat(fname, "rogue.asave"); if (access(fname, F_OK) == -0) unlink(fname); } } void total_winner(void) { struct linked_list *item; struct object *obj; int worth, oldpurse; char c; struct linked_list *bag = NULL; clear(); standout(); addstr(" \n"); addstr(" @ @ @ @ @ @@@ @ @ \n"); addstr(" @ @ @@ @@ @ @ @ @ \n"); addstr(" @ @ @@@ @ @ @ @ @ @@@ @@@@ @@@ @ @@@ @ \n"); addstr(" @@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ \n"); addstr(" @ @ @ @ @ @ @ @@@@ @ @ @@@@@ @ @ @ \n"); addstr(" @ @ @ @ @ @@ @ @ @ @ @ @ @ @ @ @ \n"); addstr(" @@@ @@@ @@ @ @ @ @@@@ @@@@ @@@ @@@ @@ @ \n"); addstr(" \n"); addstr(" Congratulations, you have made it to the light of day! \n"); standend(); addstr("\nYou have joined the elite ranks of those who have \n"); addstr("escaped the Dungeons of Doom alive. You journey home \n"); addstr("and sell all your loot at a great profit.\n"); addstr("The White Council approves the recommendation of\n"); if (player.t_ctype == C_FIGHTER) addstr("the fighters guild and appoints you Lord Protector\n"); else if (player.t_ctype == C_ASSASIN) addstr("the assassins guild and appoints you Master Murderer\n"); else if (player.t_ctype == C_NINJA) addstr("the ninja guild and appoints you Master of the Wind\n"); else if (player.t_ctype == C_ILLUSION) addstr("the illusionists guild and appoints you Master Wizard\n"); else if (player.t_ctype == C_MAGICIAN) addstr("the magicians guild and appoints you Master Wizard\n"); else if (player.t_ctype == C_CLERIC) addstr("the temple priests and appoints you Master of the Flowers\n"); else if (player.t_ctype == C_DRUID) addstr("the temple priests and appoints you Master of the Flowers\n"); else if (player.t_ctype == C_RANGER) addstr("the rangers guild and appoints you Master Ranger\n"); else if (player.t_ctype == C_PALADIN) addstr("the paladins guild and appoints you Master Paladin\n"); else if (player.t_ctype == C_THIEF) { addstr("the thieves guild under protest and appoints you\n"); addstr("Master of the Highways\n"); } addstr("of the Land Between the Mountains.\n"); mvaddstr(ur_lines - 1, 0, spacemsg); refresh(); wait_for(' '); clear(); idenpack(); oldpurse = purse; mvaddstr(0, 0, " Worth Item"); for (c = 'a', item = pack; item != NULL; c++, item = next(item)) { obj = OBJPTR(item); worth = get_worth(obj); purse += worth; if (obj->o_type == ARTIFACT && obj->o_which == TR_PURSE) bag = obj->o_bag; mvprintw(c - 'a' + 1, 0, "%c) %8d %s", c, worth, inv_name(obj, UPPERCASE)); } if (bag != NULL) { mvaddstr(ur_lines - 1, 0, morestr); refresh(); wait_for(' '); clear(); mvprintw(0, 0, "Contents of the Magic Purse of Yendor:\n"); for (c = 'a', item = bag; item != NULL; c++, item = next(item)) { obj = OBJPTR(item); worth = get_worth(obj); whatis(item); purse += worth; mvprintw(c - 'a' + 1, 0, "%c) %8d %s\n", c, worth, inv_name(obj, UPPERCASE)); } } mvprintw(c - 'a' + 1, 0, " %6d Gold Pieces ", oldpurse); refresh(); if (has_artifact == 255) score(pstats.s_exp, pstats.s_lvl, TOTAL, 0); else score(pstats.s_exp, pstats.s_lvl, WINNER, 0); byebye(); } char * killname(int monst, char *buf) { if (buf == NULL) return("A bug in UltraRogue #102"); if (monst >= 0) { switch (monsters[monst].m_name[0]) { case 'a': case 'e': case 'i': case 'o': case 'u': sprintf(buf, "an %s", monsters[monst].m_name); break; default: sprintf(buf, "a %s", monsters[monst].m_name); } return(buf); } else switch(monst) { case D_ARROW: strcpy(buf, "an arrow"); break; case D_DART: strcpy(buf, "a dart"); break; case D_BOLT: strcpy(buf, "a bolt"); break; case D_POISON: strcpy(buf, "poison"); break; case D_POTION: strcpy(buf, "a cursed potion"); break; case D_PETRIFY: strcpy(buf, "petrification"); break; case D_SUFFOCATION: strcpy(buf, "suffocation"); break; case D_INFESTATION: strcpy(buf, "a parasite"); break; case D_DROWN: strcpy(buf, "drowning"); break; case D_FALL: strcpy(buf, "falling"); break; case D_FIRE: strcpy(buf, "slow boiling in oil"); break; case D_SPELLFUMBLE: strcpy(buf, "a botched spell"); break; case D_DRAINLIFE: strcpy(buf, "a drain life spell"); break; case D_ARTIFACT: strcpy(buf, "an artifact of the gods"); break; case D_GODWRATH: strcpy(buf, "divine retribution"); break; case D_CLUMSY: strcpy(buf, "excessive clumsyness"); break; default: strcpy(buf, "stupidity"); break; } return(buf); } /* showpack() Display the contents of the hero's pack */ void showpack(char *howso) { char *iname; unsigned int worth; int cnt, ch, oldpurse; struct linked_list *item; struct object *obj; struct linked_list *bag = NULL; cnt = 1; clear(); mvprintw(0, 0, "Contents of your pack %s:\n", howso); ch = 0; oldpurse = purse; purse = 0; for (item = pack; item != NULL; item = next(item)) { obj = OBJPTR(item); worth = get_worth(obj); whatis(item); purse += worth; if (obj->o_type == ARTIFACT && obj->o_which == TR_PURSE) bag = obj->o_bag; iname = inv_name(obj, UPPERCASE); mvprintw(cnt, 0, "%d) %s\n", ch, iname); ch += 1; if (++cnt > ur_lines - 5 && next(item) != NULL) { cnt = 1; mvaddstr(ur_lines - 1, 0, morestr); refresh(); wait_for(' '); clear(); } } if (bag != NULL) { mvaddstr(ur_lines - 1, 0, morestr); refresh(); wait_for(' '); clear(); cnt = 1; ch = 0; mvprintw(0, 0, "Contents of the Magic Purse of Yendor %s:\n", howso); for (item = bag; item != NULL; item = next(item)) { obj = OBJPTR(item); worth = get_worth(obj); whatis(item); purse += worth; mvprintw(cnt, 0, "%d) %s\n", ch, inv_name(obj, UPPERCASE)); ch += 1; if (++cnt > ur_lines - 5 && next(item) != NULL) { cnt = 1; mvaddstr(ur_lines - 1, 0, morestr); refresh(); wait_for(' '); clear(); } } } mvprintw(cnt + 1, 0, "Carrying %d gold pieces", oldpurse); mvprintw(cnt + 2, 0, "Carrying objects worth %d gold pieces", purse); purse += oldpurse; refresh(); } void byebye(void) { endwin(); printf("\n"); exit(0); } /* save_resurrect() chance of resurrection according to modifed D&D probabilities */ int save_resurrect(int bonus) { int need, adjust; adjust = pstats.s_const + bonus - luck; if (adjust > 17) return(TRUE); else if (adjust < 14) need = 5 * (adjust + 5); else need = 90 + 2 * (adjust - 13); return(roll(1, 100) < need); }
26.714497
80
0.444986
[ "object" ]
f400bab5e651e2d008c4aff1191db43504a82ab3
1,408
h
C
micro/model/argument.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
4,756
2018-06-28T01:42:29.000Z
2022-03-31T11:27:43.000Z
micro/model/argument.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
725
2018-06-28T08:09:18.000Z
2022-03-29T06:37:01.000Z
micro/model/argument.h
fantasyRqg/mace
6901d36099e533148952f8d403d28000fa240153
[ "Apache-2.0" ]
878
2018-06-28T01:42:33.000Z
2022-03-31T07:08:50.000Z
// Copyright 2020 The MACE 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 MICRO_MODEL_ARGUMENT_H_ #define MICRO_MODEL_ARGUMENT_H_ #include "micro/base/serialize.h" namespace micro { namespace model { class Argument : public Serialize { public: MACE_DEFINE_HARD_CODE_MAGIC(Argument) MACE_DECLARE_STRING_FUNC(name); MACE_DECLARE_OBJECT_FUNC(float, f); MACE_DECLARE_OBJECT_FUNC(int32_t, i); MACE_DECLARE_BYTES_FUNC(s); MACE_DECLARE_ARRAY_FUNC(float, floats); MACE_DECLARE_ARRAY_BASE_PTR_FUNC(float, floats); MACE_DECLARE_ARRAY_FUNC(int32_t, ints); MACE_DECLARE_ARRAY_BASE_PTR_FUNC(int32_t, ints); private: SerialString name_; SerialFloat f_; SerialInt32 i_; SerialBytes s_; SerialArray<SerialFloat> floats_; SerialArray<SerialInt32> ints_; }; } // namespace model } // namespace micro #endif // MICRO_MODEL_ARGUMENT_H_
28.734694
75
0.769886
[ "model" ]
f402ad4e2472ba7995e785610258824f624ab24a
7,160
h
C
Library/include/CommandLine.h
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/include/CommandLine.h
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/include/CommandLine.h
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
#pragma once namespace Plato { /// <summary> /// The main purpose of this class is to parse command line /// options and arguments into a hashtable of (key,value) pairs /// for the options and an array for the arguments. /// </summary> /// <remarks> Command line syntax: /// <list type="table"> /// <item><description> [executable] [ options ] [ arguments ] </description></item> /// <item><description> options: [ options ] ' ' option </description></item> /// <item><description> option: '-'['-'] identifer [ '=' value ] </description></item> /// <item><description> arguments: [ arguments ] ' ' argument </description></item> /// <item><description> argument: string </description></item> /// </list> /// </remarks> class CommandLine { public: /// <summary> /// The hashtable type for storing (string, value) pairs. /// </summary> typedef hash_map <Strings::ConstStringPtr, Strings::ConstStringPtr, StringHashArgs> HashMap; #pragma region // Class Variables. private: /// <summary> /// This is normally set to the application's command-line arguments. /// </summary> static char** mDefaultCommandLineArguments; /// <summary> /// Indicates when the default arguments starts with the executable path. /// </summary> static bool mDefaultHasExecutable; #pragma endregion #pragma region // Instance Variables. private: /// <summary> /// The command line options preceeding any arguments after they have been split /// into (key=string*,value=string*) pairs. /// The key is the corresponding ClassProperties derived class variable name. /// </summary> HashMap* mCommandLineOptions; /// <summary> /// The arguments found on the command line. /// </summary> vector<const string*>* mArguments; /// <summary> /// The original command line arguments before any processing. /// </summary> char** mRawCommandLineArguments; /// <summary> /// Indicates whether the raw command line arguments includes an initial executable element. /// </summary> bool mHasExecutable; /// <summary> /// A cache of the command line executable - if there was one, otherwise NULL. /// </summary> const string* mExecutable; #pragma endregion #pragma region // Constructor. public: /// <summary> /// Constructor for parsing the given list of options and arguments. /// </summary> /// <param name="rawCommandLineArguments">The options and arguments to parse. /// If NULL, this will be set to the default command line arguments.</param> /// <param name="hasExecutable">When true, indicates that the first element is the application executable.</param> CommandLine(char** rawCommandLineArguments=mDefaultCommandLineArguments, bool hasExecutable=mDefaultHasExecutable); /// <summary> /// Deallocate options hash map etc. /// </summary> ~CommandLine(); #pragma endregion #pragma region // Accessors. public: /// <summary> /// Accessor for the default command line arguments. /// By default, this is set to Environment.GetCommandLineArgs(). /// An application may override this at startup before Configuration /// is called. /// </summary> static void SetDefaultCommandLineArguments(char** arguments, bool hasExecutable); /// <summary> /// Gets the default command line arguments. /// </summary> /// <remarks>These will either be the environment arguments, /// or an alternative set of arguments that was set by the application.</remarks> /// <returns>Returns the command line arguments as a string array.</returns> char** GetDefaultCommandLineArguments(); /// <summary> /// Gets the command line arguments as they would be given on the command line. /// </summary> /// <returns>Returns the command line arguments as a string array.</returns> char** GetCommandLineArguments(); /// <summary> /// Gets the value of the command line option with the given name. /// </summary> /// <param name="optionName">Option name to get value of.</param> /// <returns>Returns the value of the named option as a string, or NULL if value not set.</returns> const string* GetOptionValue(const string& optionName); /// <summary> /// Gets the value of the command line option with the given name. /// Returns the default value if option not found. /// </summary> /// <param name="optionName">Option name to get value of.</param> /// <param name="defaultValue">The default value for the option if not found.</param> /// <returns>Returns the value cast to a string.</returns> const string& GetOptionValue(const string& optionName, const string& defaultValue); /// <summary> /// Gets the value of the command line option with the given name. /// Returns the default value if option not found. /// </summary> /// <param name="optionName">Option name to get value of.</param> /// <param name="defaultValue">The default value for the option if not found.</param> /// <returns>Returns the value cast to a long.</returns> long GetOptionValue(const string& optionName, long defaultValue); /// <summary> /// Gets the value of the command line option with the given name. /// Returns the default value if option not found. /// </summary> /// <param name="optionName">Option name to get value of.</param> /// <param name="defaultValue">The default value for the option if not found.</param> /// <returns>Returns the value cast to a bool.</returns> bool GetOptionValue(const string& optionName, bool defaultValue); /// <summary> /// Gets the command line executable, if there was one. /// </summary> /// <returns>Returns the executable or NULL if none present.</returns> const string* GetExecutable(); /// <summary> /// Gets the arguments, i.e. non-options. /// </summary> /// <returns>Returns a vector of the arguments found, which may be empty.</returns> vector<const string*>& GetArguments(); /// <summary> /// Gets the command line options. /// </summary> /// <returns>Returns the options in a CommandLine::HashMap.</returns> HashMap& GetCommandLineOptions(); #pragma endregion #pragma region // Public methods. public: /// <summary> /// Checks whether a command line option is present. /// </summary> /// <param name="optionName">Option name to check for.</param> /// <returns>Returns true if option is present.</returns> bool ContainsOption(const string& optionName); #pragma endregion }; }
41.627907
123
0.619832
[ "vector" ]
f42bb8c0ebd269ea3c980f51241746fcc96499fe
1,601
h
C
src/read_vcf.h
rwtourdot/mlinker
406c18a4727a16739d6300f08e218aec4779be97
[ "MIT" ]
1
2021-08-24T15:35:40.000Z
2021-08-24T15:35:40.000Z
src/read_vcf.h
rwtourdot/mlinker
406c18a4727a16739d6300f08e218aec4779be97
[ "MIT" ]
1
2021-08-10T02:58:45.000Z
2021-08-10T20:23:19.000Z
src/read_vcf.h
rwtourdot/mlinker
406c18a4727a16739d6300f08e218aec4779be97
[ "MIT" ]
2
2021-03-18T16:03:56.000Z
2021-03-18T16:05:41.000Z
#ifndef READ_VCF_H #define READ_VCF_H //////////////// c++ include ////////////////// #include <iostream> #include <sstream> #include <fstream> #include <string> #include <map> #include <list> #include <algorithm> using namespace std; ///////////// het filtering cutoffs /// #define minimum_cov 50 #define maximum_cov 200 #define minimum_frac 0.25 /////////////// definitions /////////////////// #define DEBUG 0 //#define DEBUG 1 #define het_cutoff 1000 //////////////// linker include //////////////// #include "variant_site.h" //////////////// htslib //////////////////////// #include <htslib/vcf.h> #include <htslib/vcfutils.h> #include <htslib/hts.h> #include <htslib/kstring.h> #include <htslib/kseq.h> extern "C" { #include "htslib/vcf.h" #include "htslib/vcfutils.h" #include "htslib/synced_bcf_reader.h" } ////////////////////////////////////////////// //std::list<std::string> allowed_base_list = { "A","T","C","G"}; /////////////// functions ///////////////////// std::vector<vcf_entry> load_and_filter_vcf_file( std::string input_vcf_file, int chromosome, std::string chr_string, std::string hetfilterFile ); std::vector<vcf_entry> load_vcf_file( std::string input_vcf_file, int chromosome ); std::vector<vcf_entry> load_vcf_file_coverage( std::string input_vcf_file, int chromosome ); std::vector<vcf_entry> load_vcf_file_total( std::string input_vcf_file ); std::map<std::string,int> load_vcf_file_header( std::string input_vcf_file, std::map<std::string,int>& chr_str_map ); void subset_het_sites( vcf_vector& vvec, int start_bound, int end_bound ); #endif // READ_VCF_H
30.788462
145
0.642099
[ "vector" ]
f42dd8575bb480b86efeffc2322436dde42b67bd
2,163
c
C
src/kissmalloc/kissmalloc/tools/bench/main.c
anonymouscode1/djxperf
b6073a761753aa7a6247f2618977ca3a2633e78a
[ "MIT" ]
50
2019-08-30T13:20:19.000Z
2022-02-12T16:25:38.000Z
src/kissmalloc/kissmalloc/tools/bench/main.c
anonymouscode1/djxperf
b6073a761753aa7a6247f2618977ca3a2633e78a
[ "MIT" ]
5
2019-09-02T17:42:07.000Z
2020-07-17T09:30:47.000Z
src/kissmalloc/kissmalloc/tools/bench/main.c
anonymouscode1/djxperf
b6073a761753aa7a6247f2618977ca3a2633e78a
[ "MIT" ]
4
2020-03-30T02:57:51.000Z
2021-08-24T09:20:51.000Z
/* * Copyright (C) 2019 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see kissmalloc/LICENSE). * */ #include <kissmalloc.h> #include <stdio.h> #include <inttypes.h> #include <string.h> #include <time.h> static int random_get(const int a, const int b) { const unsigned m = (1u << 31) - 1; static unsigned x = 7; x = (16807 * x) % m; return ((uint64_t)x * (b - a)) / (m - 1) + a; } static double time_get() { struct timespec ts; timespec_get(&ts, TIME_UTC); return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; } int main(int argc, char **argv) { const int object_count = 50000000; const int size_min = 12; const int size_max = 130; void **object = malloc(object_count * sizeof(void *)); int *object_size = malloc(object_count * sizeof(int)); for (int i = 0; i < object_count; ++i) object_size[i] = random_get(size_min, size_max); printf( "kissmalloc malloc()/free() benchmark\n" "------------------------------------\n" "\n" "n = %d (number of objects)\n" "\n", object_count ); { double t = time_get(); for (int i = 0; i < object_count; ++i) object[i] = malloc(object_size[i]); t = time_get() - t; printf("malloc() burst speed:\n"); printf(" t = %f s (test duration)\n", t); printf(" n/t = %f MHz (average number of allocations per second)\n", object_count / t / 1e6); printf(" t/n = %f ns (average latency of an allocation)\n", t / object_count * 1e9); printf("\n"); } { double t = time_get(); for (int i = object_count - 1; i >= 0; --i) free(object[i]); t = time_get() - t; printf("free() burst speed:\n"); printf(" t = %f s (test duration)\n", t); printf(" n/t = %f MHz (average number of deallocations per second)\n", object_count / t / 1e6); printf(" t/n = %f ns (average latency of a deallocation)\n", t / object_count * 1e9); printf("\n"); } free(object); free(object_size); return 0; }
24.862069
104
0.543689
[ "object" ]
f434adc511f1788f93fd122f6e8effcebbb746ae
4,338
h
C
vendor/chromium/base/sampling_heap_profiler/module_cache.h
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
5,411
2017-04-14T08:57:56.000Z
2022-03-30T19:35:15.000Z
vendor/chromium/base/sampling_heap_profiler/module_cache.h
big-rip/fivem-1
c08af22110802e77816dfdde29df1662f8dea563
[ "MIT" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
vendor/chromium/base/sampling_heap_profiler/module_cache.h
big-rip/fivem-1
c08af22110802e77816dfdde29df1662f8dea563
[ "MIT" ]
2,011
2017-04-14T09:44:15.000Z
2022-03-31T15:40:39.000Z
// Copyright 2018 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 BASE_SAMPLING_HEAP_PROFILER_MODULE_CACHE_H_ #define BASE_SAMPLING_HEAP_PROFILER_MODULE_CACHE_H_ #include <memory> #include <string> #include <vector> #include "base/base_export.h" #include "base/files/file_path.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif namespace base { // Supports cached lookup of modules by address, with caching based on module // address ranges. // // Cached lookup is necessary on Mac for performance, due to an inefficient // dladdr implementation. See https://crrev.com/487092. // // Cached lookup is beneficial on Windows to minimize use of the loader // lock. Note however that the cache retains a handle to looked-up modules for // its lifetime, which may result in pinning modules in memory that were // transiently loaded by the OS. class BASE_EXPORT ModuleCache { public: // Module represents a binary module (executable or library) and its // associated state. class BASE_EXPORT Module { public: Module() = default; virtual ~Module() = default; Module(const Module&) = delete; Module& operator=(const Module&) = delete; // Gets the base address of the module. virtual uintptr_t GetBaseAddress() const = 0; // Gets the opaque binary string that uniquely identifies a particular // program version with high probability. This is parsed from headers of the // loaded module. // For binaries generated by GNU tools: // Contents of the .note.gnu.build-id field. // On Windows: // GUID + AGE in the debug image headers of a module. virtual std::string GetId() const = 0; // Gets the debug basename of the module. This is the basename of the PDB // file on Windows and the basename of the binary on other platforms. virtual FilePath GetDebugBasename() const = 0; // Gets the size of the module. virtual size_t GetSize() const = 0; // True if this is a native module. virtual bool IsNative() const = 0; }; ModuleCache(); // CFX-EDIT: shut up deleted function bits ModuleCache(const ModuleCache&) = delete; ModuleCache& operator=(const ModuleCache&) = delete; ~ModuleCache(); // Gets the module containing |address| or nullptr if |address| is not within // a module. The returned module remains owned by and has the same lifetime as // the ModuleCache object. const Module* GetModuleForAddress(uintptr_t address); std::vector<const Module*> GetModules() const; // Add a non-native module to the cache. Non-native modules represent regions // of non-native executable code, like v8 generated code or compiled // Java. // // Note that non-native modules may be embedded within native modules, as in // the case of v8 builtin code compiled within Chrome. In that case // GetModuleForAddress() will return the non-native module rather than the // native module for the memory region it occupies. void AddNonNativeModule(std::unique_ptr<Module> module); void InjectModuleForTesting(std::unique_ptr<Module> module); private: // Looks for a module containing |address| in |modules| returns the module if // found, or null if not. static Module* FindModuleForAddress( const std::vector<std::unique_ptr<Module>>& modules, uintptr_t address); // Creates a Module object for the specified memory address. Returns null if // the address does not belong to a module. static std::unique_ptr<Module> CreateModuleForAddress(uintptr_t address); // Unsorted vector of cached native modules. The number of loaded modules is // generally much less than 100, and more frequently seen modules will tend to // be added earlier and thus be closer to the front to the vector. So linear // search to find modules should be acceptable. std::vector<std::unique_ptr<Module>> native_modules_; // Unsorted vector of non-native modules. Separate from native_modules_ to // support preferential lookup of non-native modules embedded in native // modules. See comment on AddNonNativeModule(). std::vector<std::unique_ptr<Module>> non_native_modules_; }; } // namespace base #endif // BASE_SAMPLING_HEAP_PROFILER_MODULE_CACHE_H_
36.762712
80
0.733979
[ "object", "vector" ]
f43acc5e31e81020594fc0e693bb897f6f16265c
454
h
C
vegastrike/src/cmd/fg_util.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/fg_util.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/fg_util.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
namespace fg_util { std::string MakeFactionKey( int faction ); std::string MakeFGKey( const std::string &fgname, int faction ); std::string MakeStarSystemFGKey( const std::string &starsystem ); unsigned int ShipListOffset(); unsigned int PerShipDataSize(); bool IsFGKey( const std::string &fgcandidate ); bool CheckFG( std::vector< std::string > &data ); void PurgeZeroShips( SaveGame *sg, unsigned int faction ); void PurgeZeroShips( SaveGame *sg ); }
32.428571
65
0.755507
[ "vector" ]
f44c427bce782018f7bd9257d2ee91b4dfbd2c1d
8,653
h
C
include/ouster/lines.h
lbwanghr/ousterK
959d2f0eb747cf31c44cb23308e3fbf0d7b1f102
[ "Unlicense" ]
null
null
null
include/ouster/lines.h
lbwanghr/ousterK
959d2f0eb747cf31c44cb23308e3fbf0d7b1f102
[ "Unlicense" ]
null
null
null
include/ouster/lines.h
lbwanghr/ousterK
959d2f0eb747cf31c44cb23308e3fbf0d7b1f102
[ "Unlicense" ]
null
null
null
#pragma once #include <unistd.h> #include <atomic> #include <cmath> #include <csignal> #include <cstdlib> #include <Eigen/Eigen> #include <fstream> #include <iostream> #include <iterator> #include <memory> #include <sstream> #include <string> #include <thread> #include <vector> #include <iomanip> #include "ouster/os1.h" #include "ouster/os1_packet.h" #include "ouster/os1_util.h" #include "ouster/lidar_scan.h" namespace OS1 = ouster::OS1; const int W = 512; const int H = OS1::pixels_per_column; const std::string hostname = "192.168.50.120";//"192.168.1.5";//"192.168.50.120"; const std::string udp_dest_host = "192.168.50.211"; //"192.168.1.15 ";//"192.168.50.231"; const OS1::lidar_mode mode = OS1::MODE_512x10; const std::vector<double> beam_altitude_angles = { 16.611, 16.084, 15.557, 15.029, 14.502, 13.975, 13.447, 12.920, 12.393, 11.865, 11.338, 10.811, 10.283, 9.756, 9.229, 8.701, 8.174, 7.646, 7.119, 6.592, 6.064, 5.537, 5.010, 4.482, 3.955, 3.428, 2.900, 2.373, 1.846, 1.318, 0.791, 0.264, -0.264, -0.791, -1.318, -1.846, -2.373, -2.900, -3.428, -3.955, -4.482, -5.010, -5.537, -6.064, -6.592, -7.119, -7.646, -8.174, -8.701, -9.229, -9.756, -10.283, -10.811, -11.338, -11.865, -12.393, -12.920, -13.447, -13.975, -14.502, -15.029, -15.557, -16.084, -16.611, }; const std::vector<double> beam_azimuth_angles = { 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, 3.164, 1.055, -1.055, -3.164, }; double data_[88]; double min_val_in_array(double* array, int begin, int end) { double result = 100; if(begin > end) { for(int i = 0; i <= end; i++) { result = result < array[i] ? result : array[i]; } for(int i = begin; i < 512; i++) { result = result < array[i] ? result : array[i]; } } else { for(int i = begin; i <= end; i++) { result = result < array[i] ? result : array[i]; } } return result; } void max100to10(double arr[], int size) { for(int i=0; i<size;i++) { arr[i] = arr[i] < 10 ? arr[i] : 0; } } void rsh(double a[], double tmp[], int k, int size)//数组向右移动k { for (int i = 0; i<k; i++) { tmp[i] = a[i + size - k]; } for (int i = k; i<size; i++) { tmp[i] = a[i - k]; } } void reversal(double arr[], int n) { double temp; for (int i = 0; i<n / 2; i++) { temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } } void downSample(Eigen::MatrixXd xyz, double result_88[]) //xyz:65535*3 { double result_512[512]; int height = xyz.rows(); //32768 double current_min = 100; /**************downSample 32768*3 to 512*1**************/ bool line64is0 = true; for(int i=0; i < height; i++) { double d = sqrt(xyz(i,0)*xyz(i,0) + xyz(i,1)*xyz(i,1)); if(fabs(d - 0.0f) > 0.0001) { current_min = d < current_min ? d : current_min; line64is0 = false; } if((i+1) % 64 == 0) { if( line64is0 ) result_512[(i+1)/64 - 1] = 0; else { if(current_min == 100) result_512[(i+1)/64 - 1] = 0; else result_512[(i+1)/64 - 1] = current_min; } current_min = 100; line64is0 = true; } } /**************downSample from 512*1 to 64*1*************/ double result_64[64]; int height_64 = sizeof(result_64)/sizeof(*result_64); for(int i=0; i < height_64; i++) { //result_64[i] = min_val_in_array(result_1024, (i*16 - 7 + 1024) % 1024, (i*16 + 8) % 1024); result_64[i] = result_512[i*8]; } /**********change lidar sequence to adjust traning environment*********/ double result_64_shiftR[64]; memcpy(result_64_shiftR, result_64, height_64 * sizeof(*result_64)); rsh( result_64, result_64_shiftR, 16, height_64); reversal(result_64_shiftR, height_64); /*********************choose 24*1 from 64*1 ***************************/ double result_24[24]; memcpy(result_24, result_64_shiftR + 3, sizeof(result_24)); //for(int i=0;i<sizeof(result_24)/sizeof(*result_24); i++) std::cout<< result_24[i] <<" "; //std::cout<<std::endl; //std::cout<<"100100100100100100"<<std::endl; max100to10(result_24, 24); //for(int i=0;i<sizeof(result_24)/sizeof(*result_24); i++) std::cout<< result_24[i] <<" "; //std::cout<<std::endl; //std::cout<<"1010101010101010101010"<<std::endl; /**************************64*1 + 24*1 = 88*1**************************/ memcpy(result_88, result_64_shiftR, sizeof(result_64_shiftR)); memcpy(result_88 + 64, result_24, sizeof(result_24)); std::ofstream f1("sampledata/loop_1.txt",std::ios::app); for(int i=0;i<88; i++) f1<< result_88[i] <<" "; f1<<std::endl; std::cout<<"88888888888888888888888"<<std::endl; } void print_help() { std::cout << "Usage: viz [options] [hostname] [udp_destination]\n" << "Options:\n" << " -m <512x10 | 512x20 | 1024x10 | 1024x20 | 2048x10> : lidar mode, " "default 1024x10\n" << " -f <path> : use provided metadata file; do not configure via TCP" << std::endl; } void* lidar_thread( void* args ) { std::shared_ptr<OS1::client> cli = OS1::init_client(hostname, udp_dest_host, mode); if (!cli) { std::cerr << "Failed to initialize client" << std::endl; print_help(); std::exit(EXIT_FAILURE); } uint8_t lidar_buf[OS1::lidar_packet_bytes + 1]; uint8_t imu_buf[OS1::imu_packet_bytes + 1]; auto ls = std::unique_ptr<ouster::LidarScan>(new ouster::LidarScan(W, H)); auto xyz_lut = OS1::make_xyz_lut(W, H, beam_azimuth_angles, beam_altitude_angles); // Use to signal termination std::atomic_bool end_program{false}; // auto it = std::back_inserter(*ls); auto it = ls->begin(); // callback that calls update with filled lidar scan Eigen::MatrixXd xyz(W * H, 3); auto batch_and_update = OS1::batch_to_iter<ouster::LidarScan::iterator>( xyz_lut, W, H, ouster::LidarScan::Point::Zero(), &ouster::LidarScan::make_val, [&](uint64_t) { /***************************init xyz1 Eigen***************************/ //xyz1.col(0) = ls->x(); //xyz1.col(1) = ls->y(); //xyz1.col(2) = ls->z(); //xyz1.col(3).setOnes(); //std::cout << xyz1.rows() << " " << xyz1.cols() << std::endl; /***************************init xyz1 Eigen***************************/ /******************Transform xyz1 to sensor coordinate****************/ //xyz1_in_sensor = lidar_to_sensor * xyz1.transpose() ; /**********************Transform xyz1 to sensor coordinate************/ /**********************Eigen 65536*3 to double 64********************/ xyz.col(0) = ls->x(); xyz.col(1) = ls->y(); xyz.col(2) = ls->z(); downSample(xyz, data_); std::cout<<std::setw(13); for(int i=0;i<64;i++) { std::cout << data_[i] << std::setw(13); if(i==15) std::cout<<std::endl; if(i==31) std::cout<<std::endl; if(i==47) std::cout<<std::endl; } std::cout << std::endl; for(int i=64;i<88;i++) { std::cout << data_[i] << " "; } std::cout << std::endl<<"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" << std::endl; /**********************Eigen 65536*3 to double 64********************/ // swap lidar scan and point it to new buffer it = ls->begin(); }); while (true) { // Poll the client for data and add to our lidar scan OS1::client_state st = OS1::poll_client(*cli); if (st & OS1::client_state::ERROR) { std::cerr << "Client returned error state" << std::endl; std::exit(EXIT_FAILURE); } if (st & OS1::client_state::LIDAR_DATA) { if (OS1::read_lidar_packet(*cli, lidar_buf)) batch_and_update(lidar_buf, it); } if (st & OS1::client_state::IMU_DATA) { OS1::read_imu_packet(*cli, imu_buf); } } //pthread_exit( NULL ); } //函数返回的是函数指针,便于后面作为参数 class Lines { public: void run(); void getData(double data[]); }; void Lines::run() { pthread_t tid1; int ret = pthread_create( &tid1, NULL, lidar_thread, (void*)0 ); //传入到参数必须强转为void*类型,即无类型指针,&i表示取i的地址,即指向i的指针 if( ret != 0 ) //创建线程成功返回0 { std::cout << "pthread_create error:error_code=" << ret << std::endl; } //pthread_detach(pthread_self()); //pthread_detach(tid1); pthread_join(tid1, NULL); } void Lines::getData(double data[]) { memcpy(data, data_, sizeof(data_)); }
26.956386
110
0.565931
[ "vector", "transform" ]
f45003afedfbde648741a29849ae24a8c89280b0
453
h
C
src/Systems/CameraHandler.h
tmarrec/cowboy-engine
55ee5a6cabe1834e62c1bd2497cce0fd63114c94
[ "MIT" ]
null
null
null
src/Systems/CameraHandler.h
tmarrec/cowboy-engine
55ee5a6cabe1834e62c1bd2497cce0fd63114c94
[ "MIT" ]
null
null
null
src/Systems/CameraHandler.h
tmarrec/cowboy-engine
55ee5a6cabe1834e62c1bd2497cce0fd63114c94
[ "MIT" ]
null
null
null
#pragma once #include "../Core/Subsystems/ECS/System.h" #include "../Components/Transform.h" #include "../Components/Camera.h" class CameraHandler : public System { public: void Update(const float dt); const Camera& camera() const; const Transform& transform() const; private: bool positionMovements(Transform& transform, const Camera& camera, const float dt); bool lookAtMovements(Camera& camera); bool _init = false; };
21.571429
87
0.706402
[ "transform" ]
f453e1f8067a93b2190a626ae6c14331e51c4f26
2,366
h
C
vegastrike/src/python/unit_from_to_python.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/python/unit_from_to_python.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/python/unit_from_to_python.h
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#ifndef _UNIT_FROM_TO_PYTHON_H_ #define _UNIT_FROM_TO_PYTHON_H_ #include <boost/version.hpp> #if BOOST_VERSION != 102800 //#include <boost/python/converter/arg_from_python.hpp> #include "init.h" BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE BOOST_PYTHON_TO_PYTHON_BY_VALUE( Unit*, ::boost::python::to_python_value< UnitWrapper > () ( UnitWrapper( x ) ) ); template < > struct default_result_converter::apply< Unit* > { //typedef boost::python::to_python_value<Unit *> type; typedef::boost::python::default_result_converter::apply< UnitWrapper >::type type; }; /*namespace converter{ * * template <> * struct arg_rvalue_from_python <Vector> * { * // typedef typename boost::add_reference< * // typename boost::add_const<Vector>::type * // >::type result_type; * typedef Vector result_type; * * arg_rvalue_from_python(PyObject*p); * bool convertible() const {return true;} * * result_type operator()(PyObject*p) { * Vector vec(0,0,0); * PyArg_ParseTuple(p,"fff",&vec.i,&vec.j,&vec.k); * return vec; * } * * private: * rvalue_from_python_data<result_type> m_data; * }; * * template <> * struct arg_rvalue_from_python <QVector> * { * // typedef typename boost::add_reference< * // typename boost::add_const<QVector>::type * // >::type result_type; * typedef QVector result_type; * * arg_rvalue_from_python(PyObject*p); * bool convertible() const {return true;} * * result_type operator()(PyObject*p) { * QVector vec(0,0,0); * PyArg_ParseTuple(p,"ddd",&vec.i,&vec.j,&vec.k); * return vec; * } * * private: * rvalue_from_python_data<result_type> m_data; * }; * * } */ BOOST_PYTHON_END_CONVERSION_NAMESPACE #else TO_PYTHON_SMART_POINTER( UnitWrapper ); TO_PYTHON_SMART_POINTER( Cargo ); PYTHON_INIT_GLOBALS( Unit, UnitWrapper ) BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE inline PyObject*to_python( Unit*un ) { return to_python( UnitWrapper( un ) ); } inline Unit * from_python( PyObject *p, boost::python::type< Unit* >) { UnitWrapper uw = ( from_python( p, boost::python::type< UnitWrapper& > () ) ); return uw.GetUnit(); } BOOST_PYTHON_END_CONVERSION_NAMESPACE #endif #endif
28.166667
132
0.64328
[ "vector" ]
f45f136b0aadcd932ef77ab9c96a09434169d1b8
2,508
h
C
src/sui/renderer.h
tiffany352/sui
522013da168d133ca44f4250d2e6865c055fc6a9
[ "MIT" ]
null
null
null
src/sui/renderer.h
tiffany352/sui
522013da168d133ca44f4250d2e6865c055fc6a9
[ "MIT" ]
null
null
null
src/sui/renderer.h
tiffany352/sui
522013da168d133ca44f4250d2e6865c055fc6a9
[ "MIT" ]
null
null
null
#ifndef SUI_RENDERER_H #define SUI_RENDERER_H #include <stdlib.h> #include <ft2build.h> #include FT_FREETYPE_H #include <hb.h> #include <hb-ft.h> #include <fontconfig/fontconfig.h> #include "tgl/tgl.h" #include "util.h" #include "widgets.h" struct sui_font; typedef struct sui_glyph { // key uint32_t codepoint; unsigned size; struct sui_font *font; // data GLuint tex; // from freetype unsigned width, rows; unsigned left, top; } sui_glyph; typedef struct sui_font { FT_Face face; hb_font_t *hb_font; hb_face_t *hb_face; } sui_font; typedef struct sui_layout_format { sui_align align; sui_direction dir; unsigned size; const char *lang, *script; } sui_layout_format; typedef struct sui_layout { hb_buffer_t *buffer; unsigned count; hb_glyph_info_t *infos; hb_glyph_position_t *positions; sui_font *font; sui_layout_format fmt; sui_point origin, size; } sui_layout; typedef struct sui_library { FT_Library library; } sui_library; typedef struct sui_renderer { tgl_vao vao; tgl_quad vbo; struct sui_renderer_rect { tgl_shader shader; GLint mvp, upos, ucolor; } rect; struct sui_renderer_text { sui_library *library; tgl_shader shader; GLint mvp, upos, ucolor, usampler; sui_glyph *glyphs; unsigned glyphs_size, glyphs_capacity; } text; } sui_renderer; bool sui_layout_init(sui_layout *layout, sui_font *font, const sui_layout_format *fmt, const char *text, size_t length, char **error) WARN_UNUSED; void sui_layout_free(sui_layout *layout); bool sui_font_fromfile(sui_font *font, sui_library *l, char **error, const char *path) WARN_UNUSED; bool sui_font_fromdata(sui_font *font, sui_library *l, char **error, const void *buf, size_t len) WARN_UNUSED; bool sui_font_fromfc(sui_font *font, sui_library *l, char **error, FcPattern *pattern) WARN_UNUSED; bool sui_font_fromfamily(sui_font *font, sui_library *l, char **error, const char *family) WARN_UNUSED; void sui_font_free(sui_font *font); bool sui_library_init(sui_library *l, char **error) WARN_UNUSED; void sui_library_free(sui_library *l); bool sui_renderer_init(sui_renderer *r, char **error, sui_library *library) WARN_UNUSED; void sui_renderer_free(sui_renderer *r); void sui_renderer_draw(sui_renderer *r, unsigned w, unsigned h, struct sui_cmd *cmds, size_t len, const float transform[16], bool transpose); #endif
27.56044
110
0.71571
[ "transform" ]
f45f6f1af60f882b75e3cd023be01ec70be6790d
3,460
h
C
build/php5/ice/db/driver/mongo.zep.h
ajbm6/framework
865ab9a32dec647e786ee7abab527cbb384b58f4
[ "BSD-3-Clause" ]
null
null
null
build/php5/ice/db/driver/mongo.zep.h
ajbm6/framework
865ab9a32dec647e786ee7abab527cbb384b58f4
[ "BSD-3-Clause" ]
null
null
null
build/php5/ice/db/driver/mongo.zep.h
ajbm6/framework
865ab9a32dec647e786ee7abab527cbb384b58f4
[ "BSD-3-Clause" ]
1
2019-12-30T13:04:25.000Z
2019-12-30T13:04:25.000Z
extern zend_class_entry *ice_db_driver_mongo_ce; ZEPHIR_INIT_CLASS(Ice_Db_Driver_Mongo); PHP_METHOD(Ice_Db_Driver_Mongo, getId); PHP_METHOD(Ice_Db_Driver_Mongo, getType); PHP_METHOD(Ice_Db_Driver_Mongo, getClient); PHP_METHOD(Ice_Db_Driver_Mongo, getLastInsertId); PHP_METHOD(Ice_Db_Driver_Mongo, __construct); PHP_METHOD(Ice_Db_Driver_Mongo, getIdValue); PHP_METHOD(Ice_Db_Driver_Mongo, getDateTime); PHP_METHOD(Ice_Db_Driver_Mongo, findOne); PHP_METHOD(Ice_Db_Driver_Mongo, find); PHP_METHOD(Ice_Db_Driver_Mongo, select); PHP_METHOD(Ice_Db_Driver_Mongo, insert); PHP_METHOD(Ice_Db_Driver_Mongo, update); PHP_METHOD(Ice_Db_Driver_Mongo, remove); PHP_METHOD(Ice_Db_Driver_Mongo, getError); ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo___construct, 0, 0, 1) ZEND_ARG_INFO(0, dsn) ZEND_ARG_INFO(0, dbname) ZEND_ARG_ARRAY_INFO(0, options, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_getidvalue, 0, 0, 1) ZEND_ARG_INFO(0, id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_getdatetime, 0, 0, 0) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_findone, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, filters) ZEND_ARG_ARRAY_INFO(0, options, 1) ZEND_ARG_ARRAY_INFO(0, fields, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_find, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, filters) ZEND_ARG_ARRAY_INFO(0, options, 1) ZEND_ARG_ARRAY_INFO(0, fields, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_select, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, filters) ZEND_ARG_ARRAY_INFO(0, options, 1) ZEND_ARG_ARRAY_INFO(0, fields, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_insert, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_ARRAY_INFO(0, fields, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_update, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, filters) ZEND_ARG_ARRAY_INFO(0, fields, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_db_driver_mongo_remove, 0, 0, 1) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, filters) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(ice_db_driver_mongo_method_entry) { PHP_ME(Ice_Db_Driver_Mongo, getId, NULL, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, getType, NULL, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, getClient, NULL, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, getLastInsertId, NULL, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, __construct, arginfo_ice_db_driver_mongo___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Ice_Db_Driver_Mongo, getIdValue, arginfo_ice_db_driver_mongo_getidvalue, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, getDateTime, arginfo_ice_db_driver_mongo_getdatetime, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, findOne, arginfo_ice_db_driver_mongo_findone, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, find, arginfo_ice_db_driver_mongo_find, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, select, arginfo_ice_db_driver_mongo_select, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, insert, arginfo_ice_db_driver_mongo_insert, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, update, arginfo_ice_db_driver_mongo_update, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, remove, arginfo_ice_db_driver_mongo_remove, ZEND_ACC_PUBLIC) PHP_ME(Ice_Db_Driver_Mongo, getError, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
38.444444
113
0.845954
[ "model" ]
f46fc18f9a17aea43ff4f5b5630fe65c645a5f1f
5,601
h
C
SlowServoPWMExpander.h
DIYEmbeddedSystems/WebsocketController
4828b5868785b8129e566995c7e135e2c91215a6
[ "MIT" ]
2
2020-07-26T13:22:15.000Z
2021-08-09T17:17:32.000Z
SlowServoPWMExpander.h
EtienneHamelin/WebsocketController
4828b5868785b8129e566995c7e135e2c91215a6
[ "MIT" ]
null
null
null
SlowServoPWMExpander.h
EtienneHamelin/WebsocketController
4828b5868785b8129e566995c7e135e2c91215a6
[ "MIT" ]
1
2021-08-09T17:17:34.000Z
2021-08-09T17:17:34.000Z
/** * @file SlowServoPWMExpander.h * * @brief An Arduino library for SlowServo behind PWM expander (PCA9685). * * @author Etienne Hamelin (etienne.hamelin@gmail.com ; www.github.com/etiennehamelin) * * @licence * You may freely use, compile, link, copy, modify, or distribute this software, * as long as you keep this author & license header. * Happy hacking! * * */ #include <Wire.h> // I2C communication with PCA9685 I2C hardware PWM controller #include <Adafruit_PWMServoDriver.h> // PCA9685 I2C hardware PWM controller driver // maximum allowed speed (600 degree per second) #define MAX_DPS_DEFAULT 600 #ifdef SERVO_EXTENDED_RANGE // Extended servo range: input values from -120° to 120°, pulse lengths from 600us to 2400us #define SERVO_MIN (-120) #define SERVO_MAX (120) #define MIN_PULSE (122) #define MAX_PULSE (491) #else // Standard servo range: input values from -90° to 90°, pulse lengths from 700us to 2300us #define SERVO_MIN (-90) #define SERVO_MAX (90) #define MIN_PULSE (143) #define MAX_PULSE (471) #endif #define MED_PULSE ((MIN_PULSE + MAX_PULSE)/2) class SlowServo { public: //private: int16_t _curr_pulse, _last_pulse, _start_pulse, _end_pulse; int16_t _min_pulse, _max_pulse; long int _start_ms, _end_ms; int _num; int16_t _max_dps; int8_t _inverted; static bool _pwm_started; static Adafruit_PWMServoDriver _pwm; //public: /** * \brief Constructor * * \param num The servo identifier * \param max_dps maximum allowed speed, in degree per second (dps) * \param min_deg soft limit for min position (in degrees) * \param max_deg soft limit for max position (in degrees) * \param inverted whether input position shall be interpreted negative:wq */ SlowServo(int num = 0, int16_t max_dps = MAX_DPS_DEFAULT, int16_t min_deg = -90, int16_t max_deg = 90, int8_t inverted = 0) : _num(num), _max_dps(max_dps), _last_pulse(-1), _curr_pulse(MED_PULSE), _start_pulse(MED_PULSE), _end_pulse(MED_PULSE), _inverted(inverted) { _min_pulse = deg2pulse(min_deg); _max_pulse = deg2pulse(max_deg); // if necessary, initialize PWM expander IC if (!_pwm_started) { _pwm.begin(); _pwm.setPWMFreq(50); _pwm_started = true; if (!Serial) { Serial.begin(115200); // required if I want to use Serial during object initialization } } Serial.printf("Servo controller initialized \n num %d, max_dps %d, min_p %d, max_p %d\n", _num, _max_dps, _min_pulse, _max_pulse); } /** * Utilities */ int16_t deg2pulse(int16_t deg) { return map(deg, SERVO_MIN, SERVO_MAX, MIN_PULSE, MAX_PULSE); } int16_t pulse2deg(int16_t pulse) { return map(pulse, MIN_PULSE, MAX_PULSE, SERVO_MIN, SERVO_MAX); } int16_t get_min_deg() { return pulse2deg(_min_pulse); } int16_t get_max_deg() { return pulse2deg(_max_pulse); } /** * @brief Set servo to move towards given position in given delay * @param degree: servo set position * @param delay_ms: how much time the servo should take to arrive at set pos */ void write_delay(int16_t degree, long int delay_ms = 0) { if (_inverted) { degree = -degree; } delay_ms = constrain(delay_ms, 0, 60000); // make sure delay is between 0 ms and < 1 minute write_pulse(deg2pulse(degree), delay_ms); } /** * @brief Set servo to move towards given position at given speed * @param degree: servo set position * @param speed_dps: angular velocity in degree per second */ void write(int16_t degree, int16_t speed_dps = MAX_DPS_DEFAULT) { if (_inverted) { degree = -degree; } degree = constrain(degree, SERVO_MIN, SERVO_MAX); speed_dps = constrain(speed_dps, 1, MAX_DPS_DEFAULT); /* arbitrary max 360°/s */ int16_t pulse = deg2pulse(degree); // delay_ms = degrees / deg_per_ms = 1000 * deg/deg_per_s; long int delay_ms = abs(degree - read()) * 1000 / speed_dps; write_pulse(pulse, delay_ms); } void write_pulse(int16_t pulse, long int delay_ms) { _start_pulse = _curr_pulse; _end_pulse = constrain(pulse, _min_pulse, _max_pulse); _start_ms = millis(); _end_ms = _start_ms + delay_ms; } int16_t read_pulse() { return _curr_pulse; } int16_t read() { if (_inverted) { return -pulse2deg(_curr_pulse); } return pulse2deg(_curr_pulse); } bool is_moving() { return _curr_pulse == _end_pulse; } // Make sure the update() function is called frequently, e.g. every few milliseconds void update() { long int now = millis(); if ((signed)(now - _end_ms) >= 0) { // controlled move is finished _curr_pulse = _end_pulse; _end_ms = now - 1; // keep updating so that comparison is negative } else { // still moving _curr_pulse = map(now, _start_ms, _end_ms, _start_pulse, _end_pulse); // linear interpolation during movement _curr_pulse = constrain(_curr_pulse, _min_pulse, _max_pulse); // enforce soft limits } // Send update to PWM Extender only when necessary if (_curr_pulse != _last_pulse) { int16_t offset = 0; //_num << 8; // each servo on PWM extender has a specific offset, so that high pulses are equally distributed in 20ms period _pwm.setPWM(_num, offset, ((1 << 12) - 1) & (offset + _curr_pulse)); _last_pulse = _curr_pulse; } } }; // Initialization of static members bool SlowServo::_pwm_started = false; Adafruit_PWMServoDriver SlowServo::_pwm = Adafruit_PWMServoDriver();
30.112903
150
0.677915
[ "object" ]
f472cf234fc39f76926f13b84f2484d334bcc8be
2,200
h
C
MatrixKit/Controllers/MXKRoomSettingsViewController.h
dougmcbride/matrix-ios-kit
1ed280e1312e1bbde8f8c8d4528926e122b621fa
[ "Apache-2.0" ]
null
null
null
MatrixKit/Controllers/MXKRoomSettingsViewController.h
dougmcbride/matrix-ios-kit
1ed280e1312e1bbde8f8c8d4528926e122b621fa
[ "Apache-2.0" ]
null
null
null
MatrixKit/Controllers/MXKRoomSettingsViewController.h
dougmcbride/matrix-ios-kit
1ed280e1312e1bbde8f8c8d4528926e122b621fa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #import <SwiftMatrixSDK/MatrixSDK.h> #import "MXKTableViewController.h" /** This view controller displays the room settings. */ @interface MXKRoomSettingsViewController : MXKTableViewController { @protected // the dedicated room MXRoom* mxRoom; // the room state MXRoomState* mxRoomState; } /** The dedicated roomId. */ @property (nonatomic, readonly) NSString *roomId; #pragma mark - Class methods /** Returns the `UINib` object initialized for a `MXKRoomSettingsViewController`. @return The initialized `UINib` object or `nil` if there were errors during initialization or the nib file could not be located. @discussion You may override this method to provide a customized nib. If you do, you should also override `roomViewController` to return your view controller loaded from your custom nib. */ + (UINib *)nib; /** Creates and returns a new `MXKRoomSettingsViewController` object. @discussion This is the designated initializer for programmatic instantiation. @return An initialized `MXKRoomSettingsViewController` object if successful, `nil` otherwise. */ + (instancetype)roomSettingsViewController; /** Set the dedicated session and the room Id */ - (void)initWithSession:(MXSession*)session andRoomId:(NSString*)roomId; /** Refresh the displayed room settings. By default this method reload the table view. @discusion You may override this method to handle the table refresh. */ - (void)refreshRoomSettings; /** Updates the display with a new room state. @param newRoomState the new room state. */ - (void)updateRoomState:(MXRoomState*)newRoomState; @end
26.829268
94
0.758636
[ "object" ]
f482ff45beda790a482e22c1664e8cef43122390
344
h
C
Deadlock/RWCache.h
huang-kun/Deadlock
2ad030bf3463b30b05d595214ff83b492a026d33
[ "MIT" ]
1
2021-05-11T05:14:55.000Z
2021-05-11T05:14:55.000Z
Deadlock/RWCache.h
huang-kun/Deadlock
2ad030bf3463b30b05d595214ff83b492a026d33
[ "MIT" ]
null
null
null
Deadlock/RWCache.h
huang-kun/Deadlock
2ad030bf3463b30b05d595214ff83b492a026d33
[ "MIT" ]
null
null
null
// // RWCache.h // Deadlock // // Created by huangkun on 2019/8/1. // Copyright © 2019 huangkun. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface RWCache : NSObject - (void)setObject:(id)object forKey:(id <NSCopying>)key; - (id)objectForKey:(id <NSCopying>)key; @end NS_ASSUME_NONNULL_END
15.636364
56
0.715116
[ "object" ]
f48422cf9f7fc3a25003c9ec2b352cfe9594cbe4
18,244
h
C
cabi/include/symbolic.h
mstange/symbolic
b88be51896439e494f30eef2abcfa6cc11ce3bdb
[ "MIT" ]
null
null
null
cabi/include/symbolic.h
mstange/symbolic
b88be51896439e494f30eef2abcfa6cc11ce3bdb
[ "MIT" ]
null
null
null
cabi/include/symbolic.h
mstange/symbolic
b88be51896439e494f30eef2abcfa6cc11ce3bdb
[ "MIT" ]
null
null
null
/* c bindings to the symbolic library */ #ifndef SYMBOLIC_H_INCLUDED #define SYMBOLIC_H_INCLUDED #include <stdint.h> #include <stdlib.h> #include <stdbool.h> /* * Represents all possible error codes. */ enum SymbolicErrorCode { SYMBOLIC_ERROR_CODE_NO_ERROR = 0, SYMBOLIC_ERROR_CODE_PANIC = 1, SYMBOLIC_ERROR_CODE_UNKNOWN = 2, SYMBOLIC_ERROR_CODE_IO_ERROR = 101, SYMBOLIC_ERROR_CODE_UNKNOWN_ARCH_ERROR = 1001, SYMBOLIC_ERROR_CODE_UNKNOWN_LANGUAGE_ERROR = 1002, SYMBOLIC_ERROR_CODE_UNKNOWN_OBJECT_KIND_ERROR = 1003, SYMBOLIC_ERROR_CODE_UNKNOWN_OBJECT_CLASS_ERROR = 1004, SYMBOLIC_ERROR_CODE_UNKNOWN_DEBUG_KIND_ERROR = 1005, SYMBOLIC_ERROR_CODE_PARSE_BREAKPAD_ERROR = 2001, SYMBOLIC_ERROR_CODE_PARSE_DEBUG_ID_ERROR = 2002, SYMBOLIC_ERROR_CODE_OBJECT_ERROR_UNSUPPORTED_OBJECT = 2003, SYMBOLIC_ERROR_CODE_OBJECT_ERROR_BAD_OBJECT = 2004, SYMBOLIC_ERROR_CODE_OBJECT_ERROR_UNSUPPORTED_SYMBOL_TABLE = 2005, SYMBOLIC_ERROR_CODE_CFI_ERROR_MISSING_DEBUG_INFO = 3001, SYMBOLIC_ERROR_CODE_CFI_ERROR_UNSUPPORTED_DEBUG_FORMAT = 3002, SYMBOLIC_ERROR_CODE_CFI_ERROR_BAD_DEBUG_INFO = 3003, SYMBOLIC_ERROR_CODE_CFI_ERROR_UNSUPPORTED_ARCH = 3004, SYMBOLIC_ERROR_CODE_CFI_ERROR_WRITE_ERROR = 3005, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_MINIDUMP_NOT_FOUND = 4001, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_NO_MINIDUMP_HEADER = 4002, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_NO_THREAD_LIST = 4003, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_INVALID_THREAD_INDEX = 4004, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_INVALID_THREAD_ID = 4005, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_DUPLICATE_REQUESTING_THREADS = 4006, SYMBOLIC_ERROR_CODE_PROCESS_MINIDUMP_ERROR_SYMBOL_SUPPLIER_INTERRUPTED = 4007, SYMBOLIC_ERROR_CODE_PARSE_SOURCE_MAP_ERROR = 5001, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_BAD_FILE_MAGIC = 6001, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_BAD_FILE_HEADER = 6002, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_BAD_SEGMENT = 6003, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_BAD_CACHE_FILE = 6004, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_UNSUPPORTED_VERSION = 6005, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_BAD_DEBUG_FILE = 6006, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_MISSING_DEBUG_SECTION = 6007, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_MISSING_DEBUG_INFO = 6008, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_UNSUPPORTED_DEBUG_KIND = 6009, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_VALUE_TOO_LARGE = 6010, SYMBOLIC_ERROR_CODE_SYM_CACHE_ERROR_WRITE_FAILED = 6011, }; typedef uint32_t SymbolicErrorCode; /* * Indicates how well the instruction pointer derived during stack walking is trusted. */ enum SymbolicFrameTrust { SYMBOLIC_FRAME_TRUST_NONE, SYMBOLIC_FRAME_TRUST_SCAN, SYMBOLIC_FRAME_TRUST_CFI_SCAN, SYMBOLIC_FRAME_TRUST_FP, SYMBOLIC_FRAME_TRUST_CFI, SYMBOLIC_FRAME_TRUST_PREWALKED, SYMBOLIC_FRAME_TRUST_CONTEXT, }; typedef uint32_t SymbolicFrameTrust; /* * A potential multi arch object. */ typedef struct SymbolicFatObject SymbolicFatObject; /* * Contains stack frame information (CFI) for images. */ typedef struct SymbolicFrameInfoMap SymbolicFrameInfoMap; /* * A single arch object. */ typedef struct SymbolicObject SymbolicObject; /* * Represents a proguard mapping view. */ typedef struct SymbolicProguardMappingView SymbolicProguardMappingView; /* * Represents a sourcemap view. */ typedef struct SymbolicSourceMapView SymbolicSourceMapView; /* * Represents a source view. */ typedef struct SymbolicSourceView SymbolicSourceView; /* * Represents a symbolic sym cache. */ typedef struct SymbolicSymCache SymbolicSymCache; /* * CABI wrapper around a Rust string. */ typedef struct { char *data; uintptr_t len; bool owned; } SymbolicStr; /* * ELF architecture. */ typedef struct { uint16_t machine; } SymbolicElfArch; /* * Mach-O architecture. */ typedef struct { uint32_t cputype; uint32_t cpusubtype; } SymbolicMachoArch; typedef struct { uint8_t *bytes; uintptr_t len; } SymbolicCfiCache; /* * Represents an instruction info. */ typedef struct { /* * The address of the instruction we want to use as a base. */ uint64_t addr; /* * The architecture we are dealing with. */ const SymbolicStr *arch; /* * This is true if the frame is the cause of the crash. */ bool crashing_frame; /* * If a signal is know that triggers the crash, it can be stored here (0 if unknown) */ uint32_t signal; /* * The optional value of the IP register (0 if unknown). */ uint64_t ip_reg; } SymbolicInstructionInfo; /* * Represents a single symbol after lookup. */ typedef struct { uint64_t sym_addr; uint64_t line_addr; uint64_t instr_addr; uint32_t line; SymbolicStr lang; SymbolicStr symbol; SymbolicStr filename; SymbolicStr base_dir; SymbolicStr comp_dir; } SymbolicLineInfo; /* * Represents a lookup result of one or more items. */ typedef struct { SymbolicLineInfo *items; uintptr_t len; } SymbolicLookupResult; /* * OS and CPU information in a minidump. */ typedef struct { SymbolicStr os_name; SymbolicStr os_version; SymbolicStr os_build; SymbolicStr cpu_family; SymbolicStr cpu_info; uint32_t cpu_count; } SymbolicSystemInfo; /* * Carries information about a code module loaded into the process during the crash. */ typedef struct { SymbolicStr id; uint64_t addr; uint64_t size; SymbolicStr name; } SymbolicCodeModule; /* * The CPU register value of a stack frame. */ typedef struct { SymbolicStr name; SymbolicStr value; } SymbolicRegVal; /* * Contains the absolute instruction address and image information of a stack frame. */ typedef struct { uint64_t return_address; uint64_t instruction; SymbolicFrameTrust trust; SymbolicCodeModule module; SymbolicRegVal *registers; uintptr_t register_count; } SymbolicStackFrame; /* * Represents a thread of the process state which holds a list of stack frames. */ typedef struct { uint32_t thread_id; SymbolicStackFrame *frames; uintptr_t frame_count; } SymbolicCallStack; /* * State of a crashed process in a minidump. */ typedef struct { int32_t requesting_thread; uint64_t timestamp; bool crashed; uint64_t crash_address; SymbolicStr crash_reason; SymbolicStr assertion; SymbolicSystemInfo system_info; SymbolicCallStack *threads; uintptr_t thread_count; SymbolicCodeModule *modules; uintptr_t module_count; } SymbolicProcessState; /* * CABI wrapper around a UUID. */ typedef struct { uint8_t data[16]; } SymbolicUuid; /* * Represents a single token after lookup. */ typedef struct { uint32_t src_line; uint32_t src_col; uint32_t dst_line; uint32_t dst_col; uint32_t src_id; SymbolicStr name; SymbolicStr src; SymbolicStr function_name; } SymbolicTokenMatch; /* * Parses a Breakpad architecture. */ SymbolicStr symbolic_arch_from_breakpad(const SymbolicStr *arch); /* * Parses an ELF architecture. */ SymbolicStr symbolic_arch_from_elf(const SymbolicElfArch *arch); /* * Parses a Mach-O architecture. */ SymbolicStr symbolic_arch_from_macho(const SymbolicMachoArch *arch); /* * Returns the name of the instruction pointer if known. */ SymbolicStr symbolic_arch_ip_reg_name(const SymbolicStr *arch); /* * Checks if an architecture is known. */ bool symbolic_arch_is_known(const SymbolicStr *arch); /* * Returns the breakpad name for an architecture. */ SymbolicStr symbolic_arch_to_breakpad(const SymbolicStr *arch); /* * Releases memory held by an unmanaged `SymbolicCfiCache` instance. */ void symbolic_cfi_cache_free(SymbolicCfiCache *scache); /* * Extracts call frame information (CFI) from an Object in ASCII format. * * To use this, create a `SymbolicFrameInfoMap` and pass it CFI for referenced modules during * minidump processing to receive improved stack traces. */ SymbolicCfiCache *symbolic_cfi_cache_from_object(const SymbolicObject *sobj); /* * Demangles a given identifier. * * This demangles with the default behavior in symbolic. If no language * is specified, it will be auto-detected. */ SymbolicStr symbolic_demangle(const SymbolicStr *ident, const SymbolicStr *lang); /* * Demangles a given identifier. * * This is similar to `symbolic_demangle` but does not demangle the * arguments and instead strips them. If no language is specified, it * will be auto-detected. */ SymbolicStr symbolic_demangle_no_args(const SymbolicStr *ident, const SymbolicStr *lang); /* * Clears the last error. */ void symbolic_err_clear(void); /* * Returns the panic information as string. */ SymbolicStr symbolic_err_get_backtrace(void); /* * Returns the last error code. * * If there is no error, 0 is returned. */ SymbolicErrorCode symbolic_err_get_last_code(void); /* * Returns the last error message. * * If there is no error an empty string is returned. This allocates new memory * that needs to be freed with `symbolic_str_free`. */ SymbolicStr symbolic_err_get_last_message(void); /* * Frees the given fat object. */ void symbolic_fatobject_free(SymbolicFatObject *sfo); /* * Returns the n-th object. */ SymbolicObject *symbolic_fatobject_get_object(const SymbolicFatObject *sfo, uintptr_t idx); /* * Returns the number of contained objects. */ uintptr_t symbolic_fatobject_object_count(const SymbolicFatObject *sfo); /* * Loads a fat object from a given path. */ SymbolicFatObject *symbolic_fatobject_open(const char *path); /* * Return the best instruction for an isntruction info. */ uint64_t symbolic_find_best_instruction(const SymbolicInstructionInfo *ii); /* * Adds CFI for a code module specified by the `sid` argument. */ void symbolic_frame_info_map_add(const SymbolicFrameInfoMap *smap, const SymbolicStr *sid, const char *path); /* * Frees a frame info map object. */ void symbolic_frame_info_map_free(SymbolicFrameInfoMap *smap); /* * Creates a new frame info map. */ SymbolicFrameInfoMap *symbolic_frame_info_map_new(void); /* * Converts a Breakpad CodeModuleId to DebugId. */ SymbolicStr symbolic_id_from_breakpad(const SymbolicStr *sid); /* * Initializes the symbolic library. */ void symbolic_init(void); /* * Frees a lookup result. */ void symbolic_lookup_result_free(SymbolicLookupResult *slr); /* * Normalizes a debug identifier to default representation. */ SymbolicStr symbolic_normalize_debug_id(const SymbolicStr *sid); /* * Frees an object returned from a fat object. */ void symbolic_object_free(SymbolicObject *so); /* * Returns the architecture of the object. */ SymbolicStr symbolic_object_get_arch(const SymbolicObject *so); /* * Returns the kind of debug data contained in this object file, if any (e.g. DWARF). */ SymbolicStr symbolic_object_get_debug_kind(const SymbolicObject *so); /* * Returns the debug identifier of the object. */ SymbolicStr symbolic_object_get_id(const SymbolicObject *so); /* * Returns the object kind (e.g. MachO, ELF, ...). */ SymbolicStr symbolic_object_get_kind(const SymbolicObject *so); /* * Returns the desiganted use of the object file and hints at its contents (e.g. debug, * executable, ...). */ SymbolicStr symbolic_object_get_type(const SymbolicObject *so); /* * Processes a minidump with optional CFI information and returns the state * of the process at the time of the crash. */ SymbolicProcessState *symbolic_process_minidump(const char *path, const SymbolicFrameInfoMap *smap); /* * Processes a minidump with optional CFI information and returns the state * of the process at the time of the crash. */ SymbolicProcessState *symbolic_process_minidump_buffer(const char *buffer, uintptr_t length, const SymbolicFrameInfoMap *smap); /* * Frees a process state object. */ void symbolic_process_state_free(SymbolicProcessState *sstate); /* * Converts a dotted path at a line number. */ SymbolicStr symbolic_proguardmappingview_convert_dotted_path(const SymbolicProguardMappingView *spmv, const SymbolicStr *path, uint32_t lineno); /* * Frees a proguard mapping view. */ void symbolic_proguardmappingview_free(SymbolicProguardMappingView *spmv); /* * Creates a proguard mapping view from bytes. * * This shares the underlying memory and does not copy it. */ SymbolicProguardMappingView *symbolic_proguardmappingview_from_bytes(const char *bytes, uintptr_t len); /* * Creates a proguard mapping view from a path. */ SymbolicProguardMappingView *symbolic_proguardmappingview_from_path(const char *path); /* * Returns the UUID of a proguard mapping file. */ SymbolicUuid symbolic_proguardmappingview_get_uuid(SymbolicProguardMappingView *spmv); /* * Returns true if the mapping file has line infos. */ bool symbolic_proguardmappingview_has_line_info(const SymbolicProguardMappingView *spmv); /* * Frees a source map view. */ void symbolic_sourcemapview_free(const SymbolicSourceMapView *smv); /* * Loads a sourcemap from a JSON byte slice. */ SymbolicSourceMapView *symbolic_sourcemapview_from_json_slice(const char *data, uintptr_t len); /* * Return the number of sources. */ uint32_t symbolic_sourcemapview_get_source_count(const SymbolicSourceMapView *ssm); /* * Return the source name for an index. */ SymbolicStr symbolic_sourcemapview_get_source_name(const SymbolicSourceMapView *ssm, uint32_t index); /* * Return the sourceview for a given source. */ const SymbolicSourceView *symbolic_sourcemapview_get_sourceview(const SymbolicSourceMapView *ssm, uint32_t index); /* * Returns a specific token. */ SymbolicTokenMatch *symbolic_sourcemapview_get_token(const SymbolicSourceMapView *ssm, uint32_t idx); /* * Returns the number of tokens. */ uint32_t symbolic_sourcemapview_get_tokens(const SymbolicSourceMapView *ssm); /* * Looks up a token. */ SymbolicTokenMatch *symbolic_sourcemapview_lookup_token(const SymbolicSourceMapView *ssm, uint32_t line, uint32_t col); /* * Looks up a token. */ SymbolicTokenMatch *symbolic_sourcemapview_lookup_token_with_function_name(const SymbolicSourceMapView *ssm, uint32_t line, uint32_t col, const SymbolicStr *minified_name, const SymbolicSourceView *ssv); /* * Returns the underlying source (borrowed). */ SymbolicStr symbolic_sourceview_as_str(const SymbolicSourceView *ssv); /* * Frees a source view. */ void symbolic_sourceview_free(SymbolicSourceView *ssv); /* * Creates a source view from a given path. * * This shares the underlying memory and does not copy it if that is * possible. Will ignore utf-8 decoding errors. */ SymbolicSourceView *symbolic_sourceview_from_bytes(const char *bytes, uintptr_t len); /* * Returns a specific line. */ SymbolicStr symbolic_sourceview_get_line(const SymbolicSourceView *ssv, uint32_t idx); /* * Returns the number of lines. */ uint32_t symbolic_sourceview_get_line_count(const SymbolicSourceView *ssv); /* * Frees a symbolic str. * * If the string is marked as not owned then this function does not * do anything. */ void symbolic_str_free(SymbolicStr *s); /* * Creates a symbolic string from a raw C string. * * This sets the string to owned. In case it's not owned you either have * to make sure you are not freeing the memory or you need to set the * owned flag to false. */ SymbolicStr symbolic_str_from_cstr(const char *s); /* * Returns the version of the cache file. */ uint32_t symbolic_symcache_file_format_version(const SymbolicSymCache *scache); /* * Frees a symcache object. */ void symbolic_symcache_free(SymbolicSymCache *scache); /* * Creates a symcache from a byte buffer. */ SymbolicSymCache *symbolic_symcache_from_bytes(const uint8_t *bytes, uintptr_t len); /* * Creates a symcache from a given object. */ SymbolicSymCache *symbolic_symcache_from_object(const SymbolicObject *sobj); /* * Creates a symcache from a given path. */ SymbolicSymCache *symbolic_symcache_from_path(const char *path); /* * Returns the architecture of the symcache. */ SymbolicStr symbolic_symcache_get_arch(const SymbolicSymCache *scache); /* * Returns the internal buffer of the symcache. * * The internal buffer is exactly `symbolic_symcache_get_size` bytes long. */ const uint8_t *symbolic_symcache_get_bytes(const SymbolicSymCache *scache); /* * Returns the architecture of the symcache. */ SymbolicStr symbolic_symcache_get_id(const SymbolicSymCache *scache); /* * Returns the size in bytes of the symcache. */ uintptr_t symbolic_symcache_get_size(const SymbolicSymCache *scache); /* * Returns true if the symcache has file infos. */ bool symbolic_symcache_has_file_info(const SymbolicSymCache *scache); /* * Returns true if the symcache has line infos. */ bool symbolic_symcache_has_line_info(const SymbolicSymCache *scache); /* * Returns the version of the cache file. */ uint32_t symbolic_symcache_latest_file_format_version(void); /* * Looks up a single symbol. */ SymbolicLookupResult symbolic_symcache_lookup(const SymbolicSymCache *scache, uint64_t addr); /* * Free a token match. */ void symbolic_token_match_free(SymbolicTokenMatch *stm); /* * Returns true if the uuid is nil. */ bool symbolic_uuid_is_nil(const SymbolicUuid *uuid); /* * Formats the UUID into a string. * * The string is newly allocated and needs to be released with * `symbolic_cstr_free`. */ SymbolicStr symbolic_uuid_to_str(const SymbolicUuid *uuid); #endif /* SYMBOLIC_H_INCLUDED */
26.517442
108
0.737832
[ "object" ]
f4861eba3f54225714d31f01b3fee6963789af5e
3,184
h
C
Code/Framework/AzCore/AzCore/Math/MathStringConversions.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Code/Framework/AzCore/AzCore/Math/MathStringConversions.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/AzCore/Math/MathStringConversions.h
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/std/functional.h> #include <AzCore/std/string/conversions.h> #include <AzCore/std/string/string.h> namespace AZ { class Aabb; class Color; class Matrix3x3; class Matrix4x4; class Quaternion; class Transform; class Vector2; class Vector3; class Vector4; } // namespace AZ namespace AZStd { //! Prints a Vector2 with precision to 8 decimal places. void to_string(string& str, const AZ::Vector2& value); //! Prints a Vector3 with precision to 8 decimal places. void to_string(string& str, const AZ::Vector3& value); //! Prints a Vector4 with precision to 8 decimal places. void to_string(string& str, const AZ::Vector4& value); //! Prints a Quaternion with precision to 8 decimal places. void to_string(string& str, const AZ::Quaternion& value); //! Prints a 3x3 matrix in row major order over three lines with precision to 8 decimal places. void to_string(string& str, const AZ::Matrix3x3& value); //! Prints a 4x4 matrix in row major order over four lines with precision to 8 decimal places. void to_string(string& str, const AZ::Matrix4x4& value); //! Prints a transform as a 3x4 matrix in row major order over four lines with precision to 8 decimal places. void to_string(string& str, const AZ::Transform& value); //! Prints an AABB as a pair of Vector3s with precision to 8 decimal places. void to_string(string& str, const AZ::Aabb& value); //! Prints a Color as four unsigned ints representing RGBA. void to_string(string& str, const AZ::Color& value); inline AZStd::string to_string(const AZ::Vector2& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Vector3& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Vector4& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Quaternion& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Matrix3x3& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Matrix4x4& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Transform& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Aabb& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Color& val) { AZStd::string str; to_string(str, val); return str; } } // namespace AZStd
26.756303
113
0.640704
[ "transform", "3d" ]
f4b39fd6795e189395d6428b5ca258e193669490
5,204
h
C
timsort-cpp/include/tim/utils.h
PASSIONLab/MaskedSpGEMM
af15e2efe041f618618d6925d63dbdbb3e6c776b
[ "Apache-2.0" ]
3
2021-11-23T02:47:33.000Z
2022-01-04T06:59:03.000Z
timsort-cpp/include/tim/utils.h
PASSIONLab/MaskedSpGEMM
af15e2efe041f618618d6925d63dbdbb3e6c776b
[ "Apache-2.0" ]
null
null
null
timsort-cpp/include/tim/utils.h
PASSIONLab/MaskedSpGEMM
af15e2efe041f618618d6925d63dbdbb3e6c776b
[ "Apache-2.0" ]
1
2022-01-05T15:16:43.000Z
2022-01-05T15:16:43.000Z
#ifndef UTILS_H #define UTILS_H #include <algorithm> #include "compiler.h" #include "memcpy_algos.h" #include "iter.h" #include "minrun.h" namespace tim { namespace internal { /** * Number of consecutive elements for which galloping would be a win over * either linear or binary search. */ inline constexpr const std::size_t gallop_win_dist = 7; /** * Function object type implementing a generic operator<. * This is used instead of std::less<> to stay consistent with std::sort() and * std::stable_sort() when std::less<>::operator() is specialized. This isn't * necessary in general, because specializing member functions of types defined * in namespace std is undefined behavior, but it doesn't hurt either. */ struct DefaultComparator { template <class Left, class Right> inline bool operator()(Left&& left, Right&& right) const { return std::forward<Left>(left) < std::forward<Right>(right); } }; /** * @brief Semantically equivalent to std::upper_bound(), except requires * random access iterators. * @param begin Iterator to the first element in the range to search. * @param end Past-the-end iterator to the range to search. * @param value The value to search for. * @param comp The comparison function to use. * * Similar to std::upper_bound, but first finds the k such that * comp(value, begin[2**(k - 1) - 1]) and not comp(begin[2**k - 1], value) * and then returns the equivalent of * std::upper_bound(begin + 2**(k - 1), begin + 2**k - 1, value, comp) * */ template <class It, class T, class Comp> inline It gallop_upper_bound(It begin, It end, const T& value, Comp comp) { std::size_t i = 0; std::size_t len = end - begin; for(; i < len and not comp(value, begin[i]); i = 2 * i + 1) { /* LOOP */ } if(len > i) len = i; len -= (i / 2); begin += (i / 2); // hand-rolled std::upper_bound. for(; len > 0;) { i = len / 2; if (comp(value, begin[i])) len = i; else { begin += (i + 1); len -= (i + 1); } } return begin; } /** * @brief Performs a leftwards rotation by one. * @param begin Random access iterator to the first element in the range * to be rotated. * @param end Past-the-end random access iterator to the range to be * rotated. * * Semantically equivalent to std::rotate(begin, begin + 1, end) except * random access iterators are required. */ template <class It> inline void rotate_left(It begin, It end) { // heuristic for deciding whether to use a temporary + range-move // if a type is smaller than a 'pointer-size-capacity' type like std::vector or std::string, // then implement the rotate as: // move-to-temporary -> std::move_backward -> move-from-temporary // otherwise implement as a series of swaps. // // this heuristic is, of course, evaluated at compile-time // // benchmarking across a number of different cases shows that this usually wins over // a call to std::rotate() using value_type = iterator_value_type_t<It>; constexpr std::size_t use_temporary_upper_limit = 3 * sizeof(void*); constexpr bool use_temporary = sizeof(value_type) < use_temporary_upper_limit; if constexpr(use_temporary) { // for small types, implement using a temporary. if(end - begin > 1) { value_type temp = std::move(end[-1]); std::move_backward(begin, end - 1, end); *begin = std::move(temp); } } else { // for large types, implement as a series of adjacent swaps for(end -= (end > begin); end > begin; --end) std::swap(end[-1], *end); } } /** * @brief Insertion sort the range [begin, end), where [begin, mid) is * already sorted. * @param begin Random access iterator to the first element in the range. * @param begin Random access iterator to the first out-of-order element * in the range. * @param end Past-the-end random access iterator to the range. * @param comp Comparator to use. * */ template <class It, class Comp> void finish_insertion_sort(It begin, It mid, It end, Comp comp) { using value_type = iterator_value_type_t<It>; if constexpr(std::is_scalar_v<value_type> and ( std::is_same_v<Comp, std::less<>> or std::is_same_v<Comp, std::less<value_type>> or std::is_same_v<Comp, std::greater<>> or std::is_same_v<Comp, std::greater<value_type>> or std::is_same_v<Comp, DefaultComparator>) ) { // if types are cheap to compare and cheap to copy, do a linear search // instead of a binary search while(mid < end) { for(auto pos = mid; pos > begin and comp(*pos, pos[-1]); --pos) std::swap(pos[-1], *pos); ++mid; } } else { // do the canonical 'swap it with the one before it' insertion sort up // to max_minrun<value_type>() / 4 elements for(const auto stop = begin + std::min(max_minrun<value_type>() / 4, std::size_t(end - begin)); mid < stop; ++mid) for(auto pos = mid; pos > begin and comp(*pos, pos[-1]); --pos) std::swap(pos[-1], *pos); // finish it off with a binary insertion sort for(; mid < end; ++mid) rotate_left(std::upper_bound(begin, mid, *mid, comp), mid + 1); } } } /* namespace internal */ } /* namespace tim */ #endif /* UTILS_H */
30.080925
116
0.658148
[ "object", "vector" ]
3c811ff780df9d90372b97e8a64b382f3a9f960b
2,023
h
C
Sources/IBPCollectionViewCompositionalLayout/include/IBPNSCollectionLayoutDecorationItem.h
RbBtSn0w/IBPCollectionViewCompositionalLayout
6f8a997b7108766e537a0538cd751befc79547ff
[ "MIT" ]
null
null
null
Sources/IBPCollectionViewCompositionalLayout/include/IBPNSCollectionLayoutDecorationItem.h
RbBtSn0w/IBPCollectionViewCompositionalLayout
6f8a997b7108766e537a0538cd751befc79547ff
[ "MIT" ]
null
null
null
Sources/IBPCollectionViewCompositionalLayout/include/IBPNSCollectionLayoutDecorationItem.h
RbBtSn0w/IBPCollectionViewCompositionalLayout
6f8a997b7108766e537a0538cd751befc79547ff
[ "MIT" ]
null
null
null
#import <UIKit/UIKit.h> #import <IBPCollectionViewCompositionalLayout/IBPNSDirectionalEdgeInsets.h> NS_ASSUME_NONNULL_BEGIN @interface IBPNSCollectionLayoutDecorationItem : NSObject<NSCopying> // Useful for setting a background decoration view behind a section's content area. // // contentInset can also be applied as-needed. // Register the elementKind with the layout instance to associate with your custom view class/nib // // +----------------------------------+ // | | // | +----------------------------+ | +--------------------------------+ // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | |Background Decoration Item | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~<--+------|* contentInsets applied | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | +--------------------------------+ // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | +--------------------------------+ // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| |<-----| Section Geometry | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | +--------------------------------+ // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | // | +----------------------------+ | // | | // +----------------------------------+ + (instancetype)backgroundDecorationItemWithElementKind:(NSString *)elementKind NS_SWIFT_NAME(background(elementKind:)); - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; @property (nonatomic) NSInteger zIndex; // default is 0; all other section items will be automatically be promoted to zIndex=1 @property (nonatomic, readonly) NSString *elementKind; @property (nonatomic) IBPNSDirectionalEdgeInsets contentInsets; @end NS_ASSUME_NONNULL_END
43.978261
126
0.394958
[ "geometry" ]
3c99ebf07ea52737ea7a290f09264747754071ce
17,170
h
C
stats_arginfo.h
php/pecl-math-stats
fac78cf926bb00c9974379c7131c58b7545e5b15
[ "PHP-3.01" ]
2
2016-12-20T16:38:13.000Z
2021-01-15T03:13:51.000Z
stats_arginfo.h
php/pecl-math-stats
fac78cf926bb00c9974379c7131c58b7545e5b15
[ "PHP-3.01" ]
3
2018-10-03T04:38:37.000Z
2022-03-09T14:16:41.000Z
stats_arginfo.h
php/pecl-math-stats
fac78cf926bb00c9974379c7131c58b7545e5b15
[ "PHP-3.01" ]
11
2016-06-01T13:04:07.000Z
2021-06-04T10:17:43.000Z
/* This is a generated file, edit the .stub.php file instead. * Stub hash: e6cfe06b9c3e187348f16fd6a34bb7eafc5042d9 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_cdf_t, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, par1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par2, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, which, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_cdf_normal, 0, 4, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, par1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par2, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par3, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, which, IS_LONG, 0) ZEND_END_ARG_INFO() #define arginfo_stats_cdf_gamma arginfo_stats_cdf_normal #define arginfo_stats_cdf_chisquare arginfo_stats_cdf_t #define arginfo_stats_cdf_beta arginfo_stats_cdf_normal #define arginfo_stats_cdf_binomial arginfo_stats_cdf_normal #define arginfo_stats_cdf_noncentral_chisquare arginfo_stats_cdf_normal #define arginfo_stats_cdf_f arginfo_stats_cdf_normal ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_cdf_noncentral_f, 0, 5, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, par1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par2, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par3, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, par4, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, which, IS_LONG, 0) ZEND_END_ARG_INFO() #define arginfo_stats_cdf_noncentral_t arginfo_stats_cdf_normal #define arginfo_stats_cdf_negative_binomial arginfo_stats_cdf_normal #define arginfo_stats_cdf_poisson arginfo_stats_cdf_t #define arginfo_stats_cdf_laplace arginfo_stats_cdf_normal #define arginfo_stats_cdf_cauchy arginfo_stats_cdf_normal #define arginfo_stats_cdf_logistic arginfo_stats_cdf_normal #define arginfo_stats_cdf_weibull arginfo_stats_cdf_normal #define arginfo_stats_cdf_uniform arginfo_stats_cdf_normal #define arginfo_stats_cdf_exponential arginfo_stats_cdf_t ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stats_rand_setall, 0, 2, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, iseed1, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, iseed2, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stats_rand_getsd, 0, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_iuniform, 0, 2, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, low, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, high, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_funiform, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, low, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, high, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stats_rand_ignlgi, 0, 0, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_ranf, 0, 0, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_beta, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, a, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, b, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_chisquare, 0, 1, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, df, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_exponential, 0, 1, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, av, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_f, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, dfn, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, dfd, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_gamma, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, a, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, r, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_noncentral_chisquare, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, df, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, xnonc, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_noncentral_f, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, dfn, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, dfd, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, xnonc, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_rand_gen_noncenral_f arginfo_stats_rand_gen_noncentral_f ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_normal, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, av, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, sd, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_phrase_to_seeds, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, phrase, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_ibinomial, 0, 2, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, n, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, pp, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_ibinomial_negative, 0, 2, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, n, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, p, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_ipoisson, 0, 1, MAY_BE_LONG|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, mu, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_rand_gen_noncentral_t arginfo_stats_rand_gen_noncentral_chisquare ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_rand_gen_t, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, df, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_normal, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, ave, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, stdev, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_dens_cauchy arginfo_stats_dens_normal #define arginfo_stats_dens_laplace arginfo_stats_dens_normal #define arginfo_stats_dens_logistic arginfo_stats_dens_normal ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_beta, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, a, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, b, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_dens_weibull arginfo_stats_dens_beta #define arginfo_stats_dens_uniform arginfo_stats_dens_beta ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_chisquare, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, dfr, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_dens_t arginfo_stats_dens_chisquare ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_gamma, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, shape, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, scale, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_exponential, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, scale, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_f, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, dfr1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, dfr2, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_pmf_binomial, 0, 3, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, n, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, pi, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_pmf_poisson, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, lb, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_dens_pmf_negative_binomial arginfo_stats_dens_pmf_binomial ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_dens_pmf_hypergeometric, 0, 4, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, n1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, n2, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, N1, IS_DOUBLE, 0) ZEND_ARG_TYPE_INFO(0, N2, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_stat_powersum, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, arr, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO(0, power, IS_DOUBLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_stat_innerproduct, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, arr1, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO(0, arr2, IS_ARRAY, 0) ZEND_END_ARG_INFO() #define arginfo_stats_stat_independent_t arginfo_stats_stat_innerproduct #define arginfo_stats_stat_paired_t arginfo_stats_stat_innerproduct ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_stat_percentile, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, arr, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO(0, perc, IS_DOUBLE, 0) ZEND_END_ARG_INFO() #define arginfo_stats_stat_correlation arginfo_stats_stat_innerproduct ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_stat_binomial_coef, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, x, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, n, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_stat_factorial, 0, 1, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, n, IS_LONG, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_variance, 0, 1, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, a, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, sample, _IS_BOOL, 0, "false") ZEND_END_ARG_INFO() #define arginfo_stats_standard_deviation arginfo_stats_variance ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_absolute_deviation, 0, 1, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, a, IS_ARRAY, 0) ZEND_END_ARG_INFO() #define arginfo_stats_harmonic_mean arginfo_stats_absolute_deviation #define arginfo_stats_skew arginfo_stats_absolute_deviation #define arginfo_stats_kurtosis arginfo_stats_absolute_deviation ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_stats_covariance, 0, 2, MAY_BE_DOUBLE|MAY_BE_FALSE) ZEND_ARG_TYPE_INFO(0, a, IS_ARRAY, 0) ZEND_ARG_TYPE_INFO(0, b, IS_ARRAY, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(stats_cdf_t); ZEND_FUNCTION(stats_cdf_normal); ZEND_FUNCTION(stats_cdf_gamma); ZEND_FUNCTION(stats_cdf_chisquare); ZEND_FUNCTION(stats_cdf_beta); ZEND_FUNCTION(stats_cdf_binomial); ZEND_FUNCTION(stats_cdf_noncentral_chisquare); ZEND_FUNCTION(stats_cdf_f); ZEND_FUNCTION(stats_cdf_noncentral_f); ZEND_FUNCTION(stats_cdf_noncentral_t); ZEND_FUNCTION(stats_cdf_negative_binomial); ZEND_FUNCTION(stats_cdf_poisson); ZEND_FUNCTION(stats_cdf_laplace); ZEND_FUNCTION(stats_cdf_cauchy); ZEND_FUNCTION(stats_cdf_logistic); ZEND_FUNCTION(stats_cdf_weibull); ZEND_FUNCTION(stats_cdf_uniform); ZEND_FUNCTION(stats_cdf_exponential); ZEND_FUNCTION(stats_rand_setall); ZEND_FUNCTION(stats_rand_getsd); ZEND_FUNCTION(stats_rand_gen_iuniform); ZEND_FUNCTION(stats_rand_gen_funiform); ZEND_FUNCTION(stats_rand_ignlgi); ZEND_FUNCTION(stats_rand_ranf); ZEND_FUNCTION(stats_rand_gen_beta); ZEND_FUNCTION(stats_rand_gen_chisquare); ZEND_FUNCTION(stats_rand_gen_exponential); ZEND_FUNCTION(stats_rand_gen_f); ZEND_FUNCTION(stats_rand_gen_gamma); ZEND_FUNCTION(stats_rand_gen_noncentral_chisquare); ZEND_FUNCTION(stats_rand_gen_noncentral_f); ZEND_FUNCTION(stats_rand_gen_normal); ZEND_FUNCTION(stats_rand_phrase_to_seeds); ZEND_FUNCTION(stats_rand_ibinomial); ZEND_FUNCTION(stats_rand_ibinomial_negative); ZEND_FUNCTION(stats_rand_gen_ipoisson); ZEND_FUNCTION(stats_rand_gen_noncentral_t); ZEND_FUNCTION(stats_rand_gen_t); ZEND_FUNCTION(stats_dens_normal); ZEND_FUNCTION(stats_dens_cauchy); ZEND_FUNCTION(stats_dens_laplace); ZEND_FUNCTION(stats_dens_logistic); ZEND_FUNCTION(stats_dens_beta); ZEND_FUNCTION(stats_dens_weibull); ZEND_FUNCTION(stats_dens_uniform); ZEND_FUNCTION(stats_dens_chisquare); ZEND_FUNCTION(stats_dens_t); ZEND_FUNCTION(stats_dens_gamma); ZEND_FUNCTION(stats_dens_exponential); ZEND_FUNCTION(stats_dens_f); ZEND_FUNCTION(stats_dens_pmf_binomial); ZEND_FUNCTION(stats_dens_pmf_poisson); ZEND_FUNCTION(stats_dens_pmf_negative_binomial); ZEND_FUNCTION(stats_dens_pmf_hypergeometric); ZEND_FUNCTION(stats_stat_powersum); ZEND_FUNCTION(stats_stat_innerproduct); ZEND_FUNCTION(stats_stat_independent_t); ZEND_FUNCTION(stats_stat_paired_t); ZEND_FUNCTION(stats_stat_percentile); ZEND_FUNCTION(stats_stat_correlation); ZEND_FUNCTION(stats_stat_binomial_coef); ZEND_FUNCTION(stats_stat_factorial); ZEND_FUNCTION(stats_variance); ZEND_FUNCTION(stats_standard_deviation); ZEND_FUNCTION(stats_absolute_deviation); ZEND_FUNCTION(stats_harmonic_mean); ZEND_FUNCTION(stats_skew); ZEND_FUNCTION(stats_kurtosis); ZEND_FUNCTION(stats_covariance); static const zend_function_entry ext_functions[] = { ZEND_FE(stats_cdf_t, arginfo_stats_cdf_t) ZEND_FE(stats_cdf_normal, arginfo_stats_cdf_normal) ZEND_FE(stats_cdf_gamma, arginfo_stats_cdf_gamma) ZEND_FE(stats_cdf_chisquare, arginfo_stats_cdf_chisquare) ZEND_FE(stats_cdf_beta, arginfo_stats_cdf_beta) ZEND_FE(stats_cdf_binomial, arginfo_stats_cdf_binomial) ZEND_FE(stats_cdf_noncentral_chisquare, arginfo_stats_cdf_noncentral_chisquare) ZEND_FE(stats_cdf_f, arginfo_stats_cdf_f) ZEND_FE(stats_cdf_noncentral_f, arginfo_stats_cdf_noncentral_f) ZEND_FE(stats_cdf_noncentral_t, arginfo_stats_cdf_noncentral_t) ZEND_FE(stats_cdf_negative_binomial, arginfo_stats_cdf_negative_binomial) ZEND_FE(stats_cdf_poisson, arginfo_stats_cdf_poisson) ZEND_FE(stats_cdf_laplace, arginfo_stats_cdf_laplace) ZEND_FE(stats_cdf_cauchy, arginfo_stats_cdf_cauchy) ZEND_FE(stats_cdf_logistic, arginfo_stats_cdf_logistic) ZEND_FE(stats_cdf_weibull, arginfo_stats_cdf_weibull) ZEND_FE(stats_cdf_uniform, arginfo_stats_cdf_uniform) ZEND_FE(stats_cdf_exponential, arginfo_stats_cdf_exponential) ZEND_FE(stats_rand_setall, arginfo_stats_rand_setall) ZEND_FE(stats_rand_getsd, arginfo_stats_rand_getsd) ZEND_FE(stats_rand_gen_iuniform, arginfo_stats_rand_gen_iuniform) ZEND_FE(stats_rand_gen_funiform, arginfo_stats_rand_gen_funiform) ZEND_FE(stats_rand_ignlgi, arginfo_stats_rand_ignlgi) ZEND_FE(stats_rand_ranf, arginfo_stats_rand_ranf) ZEND_FE(stats_rand_gen_beta, arginfo_stats_rand_gen_beta) ZEND_FE(stats_rand_gen_chisquare, arginfo_stats_rand_gen_chisquare) ZEND_FE(stats_rand_gen_exponential, arginfo_stats_rand_gen_exponential) ZEND_FE(stats_rand_gen_f, arginfo_stats_rand_gen_f) ZEND_FE(stats_rand_gen_gamma, arginfo_stats_rand_gen_gamma) ZEND_FE(stats_rand_gen_noncentral_chisquare, arginfo_stats_rand_gen_noncentral_chisquare) ZEND_FE(stats_rand_gen_noncentral_f, arginfo_stats_rand_gen_noncentral_f) ZEND_FALIAS(stats_rand_gen_noncenral_f, stats_rand_gen_noncentral_f, arginfo_stats_rand_gen_noncenral_f) ZEND_FE(stats_rand_gen_normal, arginfo_stats_rand_gen_normal) ZEND_FE(stats_rand_phrase_to_seeds, arginfo_stats_rand_phrase_to_seeds) ZEND_FE(stats_rand_ibinomial, arginfo_stats_rand_ibinomial) ZEND_FE(stats_rand_ibinomial_negative, arginfo_stats_rand_ibinomial_negative) ZEND_FE(stats_rand_gen_ipoisson, arginfo_stats_rand_gen_ipoisson) ZEND_FE(stats_rand_gen_noncentral_t, arginfo_stats_rand_gen_noncentral_t) ZEND_FE(stats_rand_gen_t, arginfo_stats_rand_gen_t) ZEND_FE(stats_dens_normal, arginfo_stats_dens_normal) ZEND_FE(stats_dens_cauchy, arginfo_stats_dens_cauchy) ZEND_FE(stats_dens_laplace, arginfo_stats_dens_laplace) ZEND_FE(stats_dens_logistic, arginfo_stats_dens_logistic) ZEND_FE(stats_dens_beta, arginfo_stats_dens_beta) ZEND_FE(stats_dens_weibull, arginfo_stats_dens_weibull) ZEND_FE(stats_dens_uniform, arginfo_stats_dens_uniform) ZEND_FE(stats_dens_chisquare, arginfo_stats_dens_chisquare) ZEND_FE(stats_dens_t, arginfo_stats_dens_t) ZEND_FE(stats_dens_gamma, arginfo_stats_dens_gamma) ZEND_FE(stats_dens_exponential, arginfo_stats_dens_exponential) ZEND_FE(stats_dens_f, arginfo_stats_dens_f) ZEND_FE(stats_dens_pmf_binomial, arginfo_stats_dens_pmf_binomial) ZEND_FE(stats_dens_pmf_poisson, arginfo_stats_dens_pmf_poisson) ZEND_FE(stats_dens_pmf_negative_binomial, arginfo_stats_dens_pmf_negative_binomial) ZEND_FE(stats_dens_pmf_hypergeometric, arginfo_stats_dens_pmf_hypergeometric) ZEND_FE(stats_stat_powersum, arginfo_stats_stat_powersum) ZEND_FE(stats_stat_innerproduct, arginfo_stats_stat_innerproduct) ZEND_FE(stats_stat_independent_t, arginfo_stats_stat_independent_t) ZEND_FE(stats_stat_paired_t, arginfo_stats_stat_paired_t) ZEND_FE(stats_stat_percentile, arginfo_stats_stat_percentile) ZEND_FE(stats_stat_correlation, arginfo_stats_stat_correlation) ZEND_FE(stats_stat_binomial_coef, arginfo_stats_stat_binomial_coef) ZEND_FE(stats_stat_factorial, arginfo_stats_stat_factorial) ZEND_FE(stats_variance, arginfo_stats_variance) ZEND_FE(stats_standard_deviation, arginfo_stats_standard_deviation) ZEND_FE(stats_absolute_deviation, arginfo_stats_absolute_deviation) ZEND_FE(stats_harmonic_mean, arginfo_stats_harmonic_mean) ZEND_FE(stats_skew, arginfo_stats_skew) ZEND_FE(stats_kurtosis, arginfo_stats_kurtosis) ZEND_FE(stats_covariance, arginfo_stats_covariance) ZEND_FE_END };
42.186732
118
0.869423
[ "shape" ]
3ca274bf448547c047b13506dfaa95b1cc291163
1,516
h
C
MyMatrix/MatrixDiag.h
ccecka/squishy
431fc4f99c46b6c16467a0a8ff873d44b6e31679
[ "MIT" ]
null
null
null
MyMatrix/MatrixDiag.h
ccecka/squishy
431fc4f99c46b6c16467a0a8ff873d44b6e31679
[ "MIT" ]
null
null
null
MyMatrix/MatrixDiag.h
ccecka/squishy
431fc4f99c46b6c16467a0a8ff873d44b6e31679
[ "MIT" ]
3
2018-05-19T04:44:46.000Z
2021-07-31T07:51:08.000Z
#ifndef MATRIXDIAG_H #define MATRIXDIAG_H #include "Matrix_Base.h" template <typename T> class dmatrix : virtual public matrix_base<T> { protected: using matrix_base<T>::n_rows; // Num Rows using matrix_base<T>::val; // Val array public: using matrix_base<T>::NOT_STORED; // Constructors dmatrix() : matrix_base<T>() {} dmatrix( int N ) : matrix_base<T>(N,N,N) {} dmatrix( int N, T v ) : matrix_base<T>(N,N,N,v) {} // Destructor virtual ~dmatrix() {} static string name() { return "MatDiag"; } // Compute y = Ax void prod( const vector<T>& x, vector<T>& y ) const { for( int i = 0; i < n_rows; ++i ) y[i] = val[i] * x[i]; } // Matrix indexing inline int IJtoK( int i, int j ) const { assert( i >= 0 && i < n_rows && j >= 0 && j < n_rows ); if( i == j ) return i; else return NOT_STORED; } using matrix_base<T>::operator=; // Output friend ostream& operator<<( ostream& os, const dmatrix<T>& A ) { ios::fmtflags olda = os.setf(ios::left,ios::adjustfield); ios::fmtflags oldf = os.setf(ios::fixed,ios::floatfield); int oldp = os.precision(6); int ichars = ceil( log10( A.nRows() ) ); for( int i = 0; i < A.nRows(); ++i ) { os << "("; os.width( ichars ); os << i << ","; os.width( ichars ); os << i << "): " << A(i,i) << endl; } os.setf(olda,ios::adjustfield); os.setf(oldf,ios::floatfield); os.precision(oldp); return os; } }; #endif
19.688312
64
0.558047
[ "vector" ]
3ca41fcb2a79eae5ca30e3ea3fd3b47ef334fb38
10,925
h
C
Generic/TermCom/termCom.h
Krugaroo/TermCom
7b523f6867f564ee74386395b8b2986c31f5eba9
[ "Unlicense" ]
null
null
null
Generic/TermCom/termCom.h
Krugaroo/TermCom
7b523f6867f564ee74386395b8b2986c31f5eba9
[ "Unlicense" ]
null
null
null
Generic/TermCom/termCom.h
Krugaroo/TermCom
7b523f6867f564ee74386395b8b2986c31f5eba9
[ "Unlicense" ]
null
null
null
/* * Name: TermCom.h * Author: Michael Kruger * Brief: * * A terminal is a program to send and receive serial data from embedded devices. * An example of this is the "Serial Monitor" in Arduino, but PuTTy and TeraTerm are also commonly used. * Some of these terminals support commands so you can, for instance, change the colour of the text, make the computer beep, * tell the computer to print, change the cursor position and resize the window. You can even ask the computer to give you the mouse position. * * These commands are useful for debugging or getting feedback from your project: If something is good print it in green, if something requires * your attention maximize the window or beep the computer, and if you are waiting for something display the progress in the progress bar. * * ARDUINO'S "SERIAL MONITOR" SUPPORTS VERY LITTLE OF THESE COMMANDS. TO MAKE FULL USE OF THESE COMMANDS, DOWNLOAD AND USE A FULL TERMINAL, EG. TERATERM OR PUTTY. * * This file contains defines and macros for commands: * - Text/Highlight Colour codes * - Text Formatting/Blinking codes * - Commands to clear screen, backspace, enter, beep computer etc. * - Commands to control and get the cursor position. * - Commands to minimize, maximize, resize, move, title and restore the terminal window. * - Commands to send terminal contents to printer, echo typed input and copy text to clipboard (for pasting). * - Macros to show progress as a percentage or progress bar. * * Copyright 2015 Krugaroo Technology * More Info: www.krugaroo.com#openSource/TermCom * * License: MIT License * * Copyright (c) 2015 Michael Kruger, Krugaroo Interactive Technology * * 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 H_TERM_COM #define H_TERM_COM /************************************** * INTERNAL DEFINES, MACROS & ENUMS **************************************/ /* To support the progress bar and percentage printf is needed */ #define TERM_INCLUDE_PRINTF /************************************** * INCLUDE FILES **************************************/ #ifdef TERM_INCLUDE_PRINTF #include <stdio.h> #endif /************************************** * EXTERNAL DEFINES, MACROS & ENUMS **************************************/ /* Remove formatting */ #define TERM_RESET "\x1b[0m" /* Change the colour of text after to specified colour */ #define TERM_COL_BLACK "\x1b[30m" #define TERM_COL_RED "\x1b[31m" #define TERM_COL_GREEN "\x1b[32m" #define TERM_COL_YELLOW "\x1b[33m" #define TERM_COL_BLUE "\x1b[34m" #define TERM_COL_MAGNETA "\x1b[35m" #define TERM_COL_CYAN "\x1b[36m" #define TERM_COL_WHITE "\x1b[37m" /* Change the background colour of text after to specified colour */ #define TERM_HIGHLIGHT_BLACK "\x1b[40m" #define TERM_HIGHLIGHT_RED "\x1b[41m" #define TERM_HIGHLIGHT_GREEN "\x1b[42m" #define TERM_HIGHLIGHT_YELLOW "\x1b[43m" #define TERM_HIGHLIGHT_BLUE "\x1b[44m" #define TERM_HIGHLIGHT_MAGNETA "\x1b[45m" #define TERM_HIGHLIGHT_CYAN "\x1b[46m" #define TERM_HIGHLIGHT_WHITE "\x1b[47m" #define TERM_COL_GOOD TERM_COL_GREEN #define TERM_COL_WARN TERM_COL_YELLOW #define TERM_COL_BAD TERM_COL_RED /* Call this Macro with the message to colour message to either good, warning or bad */ #define TERM_GOOD(msg) TERM_COL_GOOD msg TERM_RESET #define TERM_WARN(msg) TERM_COL_WARN msg TERM_RESET #define TERM_BAD(msg) TERM_COL_BAD msg TERM_RESET /* Make the text following bold, faint, italic or underline*/ #define TERM_BOLD "\x1b[1m" #define TERM_FAINT "\x1b[2m" #define TERM_ITALIC "\x1b[3m" #define TERM_UNDERLINE "\x1b[4m" /* Inverts the background and text colour */ /* Writing TERM_INVERT and TERM_UNINVERT alternatively flashes the screen. */ #define TERM_INVERT "\x1b[?5h" #define TERM_UNINVERT "\x1b[?5l" /* Useful Commands */ #define TERM_BACKSPACE "\x08" #define TERM_ENTER "\r\n" #define TERM_RETURN "\r" #define TERM_CLEAR "\x1b[2J \x1b[;H" //clear the entire screen #define TERM_BEEP "\a\r\n" //plays a bell sound on computer /* Commands to control the cursor */ #define TERM_CURSOR_SET(x,y) "\x1b["x";"y"H" //set cursor position #define TERM_CURSOR_BLOCK "\x1b[1 q" //set cursor style to block #define TERM_CURSOR_UNDERLINE "\x1b[3 q" //set cursor style to underlined #define TERM_CURSOR_VERTICAL "\x1b[5 q" //set cursor style to vertical #define TERM_CURSOR_COORD_CLICK(on) (on)? "\x1b[?1000h" : "\x1b[?1000l" //mouse track on CLICK /* Pass the captured string and a TERM_mouseData type to this macro to decode the data into the mouseX and mouseY */ #define TERM_INTERPRET_MOUSE_REPORT(string,data) if(strlen((const char*)string)>=6 && string[0]==0x1B && \ string[1]=='[' && string[2]=='M' && \ (string[3]=='#' || string[3]==0x20) && \ string[4]>=0x21 && string[5]>=0x21) \ { \ data.valid = 1; \ data.mouseX = (string[4]-0x21); \ data.mouseY = (string[5]-0x21); \ } \ else \ { \ data.valid = 0; \ } \ /* Commands to control the window of the terminal */ #define TERM_WIN_MINIMIZE "\x1b[2;;t" #define TERM_WIN_RESTORE "\x1b[9;0;t" #define TERM_WIN_SIZE(x,y,w,h) "\x1b[3;"x";"y"t\x1b[8;"h";"w"t" //move the window to x,y and size it w and h, columns and lines #define TERM_WIN_MAXIMIZE "\x1b[9;1;t" #define TERM_WIN_TITLE(title) "\x1b]0;" title "\x1b\\" //give the window a title /* Useful utilities */ #define TERM_COPY(data) "\x1b]52;;" data "\x1b\\" //copies the given data to the clipboard (data is base64) #define TERM_PRINT "\x1b[0i" //prompts the user to print the screen to the printer! #define TERM_ECHO_ON "\x1b[12l" //see everything typed in the terminal #define TERM_ECHO_OFF "\x1b[12h" //stop seeing everything typed in the terminal /* These macros are only supported if printf is included */ #ifdef TERM_INCLUDE_PRINTF /* Shows a percentage that stays on the same spot, call when updating percentage Do not write any serial output in between. The first parameter is a function to call that writes strings to the serial. Requires 10 bytes on stack */ #define TERM_PERCENT(func, per) { \ char lvBuff[10]={0}; \ sprintf(lvBuff,"\r%3d %%",per); \ func(lvBuff); \ } /* Shows a progress bar that fills up second parameter is total steps. Third parameter is amount that is done. Do not write any serial output in between. The first parameter is a function to call that writes strings to the serial. Requires 60 bytes on stack and has max 50 steps */ #define TERM_PROGRESS(func, total, done) { \ int i=0; \ char lvBuff[60]={0}; \ if(total<=50 && done<=total) { \ lvBuff[0] = '\r'; \ for(i=1;i<=done;i++){lvBuff[i]='#';} \ for(i=1;i<=(total-done);i++){lvBuff[done+i]='-';} \ sprintf((char *)(lvBuff+total+1),"%2d/%2d",done,total); \ func(lvBuff); } \ } #else #define TERM_PERCENT(func,per) #define TERM_PROGRESS(func,total,done) #endif /************************************** * TYPE DEFINITIONS **************************************/ typedef struct{ bool valid; int mouseX; int mouseY; } TERM_mouseData; /************************************** * INTERFACES **************************************/ /* NONE */ /************************************** * PUBLIC FUNCTION PROTOTYPES **************************************/ /* NONE */ /************************************** * VARIABLE DECLARATIONS **************************************/ /* NONE */ #endif //H_TERM_COM
49.659091
161
0.519725
[ "3d" ]
3cc5a2182f97ccab035dbf4ab32889b0adb18a8a
12,458
h
C
src/ac_variable.h
madedit/aclang
698ea6a56812f3702d63b6b4235a5eee8eaa0773
[ "MIT" ]
10
2015-01-27T09:16:29.000Z
2021-05-07T16:39:05.000Z
src/ac_variable.h
madedit/aclang
698ea6a56812f3702d63b6b4235a5eee8eaa0773
[ "MIT" ]
null
null
null
src/ac_variable.h
madedit/aclang
698ea6a56812f3702d63b6b4235a5eee8eaa0773
[ "MIT" ]
4
2015-01-27T09:45:05.000Z
2021-05-07T16:39:06.000Z
/* see copyright notice in aclang.h */ #ifndef AC_VARIABLE_H #define AC_VARIABLE_H #include "ac_config.h" #include "ac_codegen.h" #include "ac_hashvalue.h" #include <llvm/IR/Function.h> #include <llvm/IR/Constants.h> #include <list> #include <map> #include <string> #include <vector> class acVM; class acGarbageCollector; struct acGCObject; struct acString; struct acArray; struct acTable; struct acFunction; struct acFuncBinder; struct acFunctionData; enum acVarType { acVT_NULL = 0, //primitive data acVT_BOOL, acVT_INT32, acVT_INT64, acVT_FLOAT, acVT_DOUBLE, //gc object acVT_VAR, acVT_STRING, acVT_ARRAY, acVT_TABLE, acVT_FUNCTION, acVT_DELEGATE, //user data acVT_USERDATA, acVT_USERFUNC, //helper data, internal use only acVT_FUNCBINDER, acVT_FUNCTIONDATA, }; enum acBaseFunc { acBF_TOBOOL, acBF_TOINT32, acBF_TOINT64, acBF_TOFLOAT, acBF_TODOUBLE, acBF_TOSTR, acBF_CALL, acBF_MAX }; enum acOperatorFunc { acOF_NEW,// new "_new" acOF_ADD,// + "_add" acOF_SUB,// - "_sub" acOF_MUL,// * "_mul" acOF_DIV,// / "_div" acOF_MOD,// % "_mod" acOF_MAX, }; #pragma pack(1) struct acGCObject { acVarType m_objType : 8; acUInt8 m_gcColor; acGCObject() { } acGCObject(acVarType type) : m_objType(type) { } }; #pragma pack() #pragma pack(1) struct acVariable : acGCObject { acVarType m_valueType : 8; union //value { acInt32 m_int32; acInt64 m_int64; acFloat m_float; acDouble m_double; acGCObject* m_gcobj; }; acHashValue m_hash; void** m_baseFuncPtrs; acVariable() { setNull(); } void setNull() { memset(this, 0, sizeof(acVariable)); m_objType = acVT_VAR; setBaseFuncPtrs(this); } void setValue(bool v) { m_valueType = acVT_BOOL; m_int64 = 0; m_int32 = v; setBaseFuncPtrs(this); } void setValue(acInt32 v) { m_valueType = acVT_INT32; m_int64 = 0; m_int32 = v; setBaseFuncPtrs(this); } void setValue(acInt64 v) { m_valueType = acVT_INT64; m_int64 = v; setBaseFuncPtrs(this); } void setValue(acFloat v) { m_valueType = acVT_FLOAT; m_int64 = 0; m_float = v; setBaseFuncPtrs(this); } void setValue(acDouble v) { m_valueType = acVT_DOUBLE; m_double = v; setBaseFuncPtrs(this); } void setValue(acVariable* v) { assignFrom(v); } void setValue(acGCObject* v) { m_valueType = v->m_objType; m_gcobj = v; setBaseFuncPtrs(this); } void setValue(const char* str, acVM* vm); void assignFrom(acVariable* v); void cloneTo(acVariable* v, acVM* vm); acHashValue& getHash(); static void getHash(acInt32 value, acHashValue& hash); static void getHash(acInt64 value, acHashValue& hash); static void getHash(const char* str, acHashValue& hash); static void setBaseFuncPtrs(acVariable* var); //return >0, =0, <0 int compare(acVariable* v, acVM* vm); //get child var by index/key. for array & table. acVariable* get(acInt32 idx); acVariable* get(acInt64 idx); acVariable* get(const char* key); acVariable* get(acVariable* key); acString* toString() { return (acString*)m_gcobj; } acArray* toArray() { return (acArray*)m_gcobj; } acTable* toTable() { return (acTable*)m_gcobj; } }; #pragma pack() struct acString : acGCObject { acUInt32 m_hash; acUInt32 m_sum; std::string m_data; int m_iteratorIndex;//for foreach() acString() : acGCObject(acVT_STRING) , m_hash(0) { } acString(acChar* begin, acChar* end) : acGCObject(acVT_STRING) , m_data(begin, end) { hash(); } void setData(const std::string& data) { m_data = data; hash(); } const char* c_str() const { return m_data.c_str(); } void hash(); void initIter() { m_iteratorIndex = 0; } bool iterate(acVariable* idx, acVariable* value) { if(m_iteratorIndex < 0 || m_iteratorIndex >= (int)m_data.size()) return false; if(idx != 0) idx->setValue(m_iteratorIndex); if(value != 0) value->setValue((int)m_data[m_iteratorIndex]); ++m_iteratorIndex; return true; } }; struct acArray : acGCObject { std::vector<acVariable*> m_data; typedef std::vector<acVariable*>::iterator DataIterator; int m_iteratorIndex;//for foreach() acArray() : acGCObject(acVT_ARRAY) , m_iteratorIndex(-1) { } int size() { return m_data.size(); } void add(acVariable* var) { m_data.push_back(var); } acVariable* get(int idx) { return m_data[idx]; } void set(int idx, acVariable* var) { m_data[idx] = var; } void fillAndSet(int idx, acVariable* var, acVM* vm); acVariable* fillAndGet(int idx, acVM* vm); void initIter() { m_iteratorIndex = 0; } bool iterate(acVariable* idx, acVariable* value) { if(m_iteratorIndex < 0 || m_iteratorIndex >= size()) return false; if(idx != 0) idx->setValue(m_iteratorIndex); if(value != 0) value->setValue(m_data[m_iteratorIndex]); ++m_iteratorIndex; return true; } void cloneTo(acArray* other, acVM* vm); }; struct acTable : acGCObject { struct KeyValue { acVariable* key; acVariable* value; KeyValue(acVariable* k, acVariable* v) : key(k) , value(v) { } }; std::map<acHashValue, KeyValue> m_data; typedef std::map<acHashValue, KeyValue>::iterator DataIterator; DataIterator m_iterator;//for foreach() acFuncBinder* m_funcBinder; acTable() : acGCObject(acVT_TABLE) , m_iterator(m_data.end()) , m_funcBinder(0) { } void add(acVariable* key, acVariable* var) { acHashValue& hash = key->getHash(); DataIterator it = m_data.find(hash); if(it == m_data.end()) { m_data.insert(std::make_pair(hash, KeyValue(key, var))); } else { it->second = KeyValue(key, var); } } //helper functions for add kv void add(const char* key, const char* value, acVM* vm); void add(const char* key, int value, acVM* vm); void add(int key, const char* value, acVM* vm); void add(int key, int value, acVM* vm); void remove(acInt32 idx) { acHashValue hash; acVariable::getHash(idx, hash); m_data.erase(hash); } void remove(acInt64 idx) { acHashValue hash; acVariable::getHash(idx, hash); m_data.erase(hash); } void remove(const char* key) { acHashValue hash; acVariable::getHash(key, hash); m_data.erase(hash); } void remove(acVariable* key) { m_data.erase(key->getHash()); } //get value by int32 acVariable* get(acInt32 idx) { acHashValue hash; acVariable::getHash(idx, hash); DataIterator it = m_data.find(hash); if(it == m_data.end()) return 0; return it->second.value; } //get value by int64 acVariable* get(acInt64 idx) { acHashValue hash; acVariable::getHash(idx, hash); DataIterator it = m_data.find(hash); if(it == m_data.end()) return 0; return it->second.value; } //get value by string acVariable* get(const char* key) { acHashValue hash; acVariable::getHash(key, hash); DataIterator it = m_data.find(hash); if(it == m_data.end()) return 0; return it->second.value; } //get value by var acVariable* get(acVariable* key) { acHashValue& hash = key->getHash(); DataIterator it = m_data.find(hash); if(it == m_data.end()) return 0; return it->second.value; } void initIter() { m_iterator = m_data.begin(); } bool iterate(acVariable* key, acVariable* value) { if(m_iterator == m_data.end()) return false; KeyValue& kv = m_iterator->second; if(key != 0) key->setValue(kv.key); if(value != 0) value->setValue(kv.value); ++m_iterator; return true; } void cloneTo(acTable* other, acVM* vm); void copyDataTo(acTable* other, acVM* vm); void bindFunc(char* name, acVariable* func); void bindFunc(acVariable* key, acVariable* func, acVM* vm); void bindFunc(acTable* table, acVM* vm); acVariable* getBindFunc(acOperatorFunc func); acVariable* getBindFunc(const char* name); acVariable* getBindFunc(acVariable* key); }; struct acFunction : acGCObject { acFunctionData* m_funcData; acTable* m_upValueTable; std::list<acGCObject*>* m_createdFuncDataList; acFunction() : acGCObject(acVT_FUNCTION) , m_funcData(0) , m_upValueTable(0) , m_createdFuncDataList(0) { } }; struct acDelegate : acGCObject { acVariable* m_thisVar; acVariable* m_funcVar; acDelegate() : acGCObject(acVT_DELEGATE) , m_thisVar(0) , m_funcVar(0) { } }; struct acUserFunc : acGCObject { void* m_funcPtr; acUserFunc() : acGCObject(acVT_USERFUNC) , m_funcPtr(0) { } }; struct acFuncBinder : acGCObject { acTable* m_funcTable; acVariable* m_funcArray[acOF_MAX];//function or userfunc acFuncBinder() : acGCObject(acVT_FUNCBINDER) , m_funcTable(0) { memset(m_funcArray, 0, sizeof(m_funcArray)); } void cloneTo(acFuncBinder* dest, acVM* vm); void bindFunc(acVariable* key, acVariable* func); void bindFunc(acTable* table, acVM* vm); acOperatorFunc getOpFunc(acVariable* var); }; struct acFunctionData : acGCObject { llvm::Function* m_llvmFunc; void* m_funcPtr; std::list<std::string>* m_stringList; std::list<acDebugInfo>* m_debugInfoList; acFunctionData() : acGCObject(acVT_FUNCTIONDATA) , m_llvmFunc(0) , m_funcPtr(0) , m_stringList(0) , m_debugInfoList(0) { } }; std::string getVarTypeStr(acVarType vt); bool toBool(acVariable* var, acVM* vm); acInt32 toInt32(acVariable* var, acVM* vm); acInt64 toInt64(acVariable* var, acVM* vm); acFloat toFloat(acVariable* var, acVM* vm); acDouble toDouble(acVariable* var, acVM* vm); std::string toString(acVariable* var, acVM* vm); void callFunction(acVariable* var, acVariable* thisVar, acArray* argArray, acVM* vm); void addInt32(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void subInt32(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void mulInt32(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void divInt32(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void modInt32(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void addInt64(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void subInt64(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void mulInt64(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void divInt64(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void modInt64(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void addFloat(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void subFloat(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void mulFloat(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void divFloat(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void modFloat(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void addDouble(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void subDouble(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void mulDouble(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void divDouble(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void modDouble(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); void addString(acVariable* ret, acVariable* v1, acVariable* v2, acVM* vm); #endif //AC_VARIABLE_H
24.427451
85
0.615749
[ "object", "vector" ]
3cc7f3d5f9d24c82bca00b684cc3c2d3b654f4d6
2,067
h
C
include/kernel/spi.h
cryingheart/t2_dlna
ce30bea1664d32e56a82e9e1ac74cf561d652992
[ "Apache-2.0" ]
null
null
null
include/kernel/spi.h
cryingheart/t2_dlna
ce30bea1664d32e56a82e9e1ac74cf561d652992
[ "Apache-2.0" ]
null
null
null
include/kernel/spi.h
cryingheart/t2_dlna
ce30bea1664d32e56a82e9e1ac74cf561d652992
[ "Apache-2.0" ]
null
null
null
/** * @addtogroup drv_spi * @{ */ #pragma once #include <kernel/dma.h> #include <kernel/bitops.h> /** * Type of the object representing a SPI bus. */ struct spi_bus { struct os_semaphore sb_sem; struct os_waitq sb_waitq; struct spi_device *sb_bus_holder; }; /** * Type for objects representing a SPI device attached to @ref spi_bus. */ struct spi_device { struct spi_bus *sd_bus; bool sd_open; unsigned int sd_device_id; unsigned int sd_max_freq; unsigned int sd_mode; }; struct spi_req { uint8_t sr_cmd_mode; uint8_t sr_cmd; uint8_t sr_addr_mode; uint8_t sr_addr_bits; uint32_t sr_addr; uint8_t sr_mode_bits; uint8_t sr_dummy_bits; uint8_t sr_data_mode; }; void spi_acquire_bus(struct spi_bus* bus, struct spi_device* dev); void spi_bus_init(struct spi_bus* bus); void spi_close_device(struct spi_device* dev); void spi_init_device(struct spi_device* dev, struct spi_bus* bus, unsigned int device_id, unsigned int max_freq, unsigned int mode); void spi_open_device(struct spi_device* dev); unsigned int spi_read_shift_reg(struct spi_bus* bus); void spi_release_bus(struct spi_bus* bus); void spi_set_device_id(struct spi_bus* bus, unsigned int device_id); void spi_set_freq(struct spi_bus* bus, unsigned int max_freq); void spi_set_mode(struct spi_bus* bus, unsigned int mode); void spi_wait(struct spi_bus* bus); void spi_wr32(struct spi_device* dev, uint32_t out); void spi_wr24(struct spi_device* dev, uint32_t out); void spi_wr16(struct spi_device* dev, uint32_t out); void spi_wr8(struct spi_device* dev, uint8_t out); void spi_wr8_rd32(struct spi_device* dev, uint8_t out, uint32_t* in); void spi_wr8_rd8(struct spi_device* dev, uint8_t out, uint8_t* in); void spi_wr8_rd16(struct spi_device* dev, uint8_t out, uint16_t *in); void spi_xfer_dma(struct spi_device *dev, const struct spi_req *req, struct dma_desc *data); /** @} */
23.488636
71
0.698113
[ "object" ]
3ccff569e3757bbd00971280d6c97adf6ee1a20c
681
h
C
include/ClassificationState.h
JGSS-GabrielSousa/LoL-Manager
a63a4b039941a990eda5f3f3f1181ec5b5b93860
[ "MIT" ]
null
null
null
include/ClassificationState.h
JGSS-GabrielSousa/LoL-Manager
a63a4b039941a990eda5f3f3f1181ec5b5b93860
[ "MIT" ]
null
null
null
include/ClassificationState.h
JGSS-GabrielSousa/LoL-Manager
a63a4b039941a990eda5f3f3f1181ec5b5b93860
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #include "State.h" #include "Game.h" using namespace std; class ClassificationState : public State{ typedef struct tableRow{ sf::RectangleShape nameBox; sf::RectangleShape ptsBox; sf::Text textName; sf::Text textPts; }tableRow; public: ClassificationState(GameDataRef data,string team,string league); void Init(); void HandleInput(); void Update(float dt); void Draw(float dt); void RoundRobinTable(); void PlayoffTable(); private: GameDataRef _data; League* league; string actualTeam; bool leagueChanged = true; vector<tableRow> slot; };
17.025
68
0.66373
[ "vector" ]
3cd52619589dc6f5946083b895eb6f8a68a09b41
1,062
h
C
src/plugins/compare/compare.h
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
2
2018-10-18T16:10:21.000Z
2020-05-28T01:52:24.000Z
src/plugins/compare/compare.h
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
null
null
null
src/plugins/compare/compare.h
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
4
2017-12-13T07:39:18.000Z
2021-05-29T13:13:48.000Z
#ifndef COMPARE_H #define COMPARE_H #include <set> #include <boost/weak_ptr.hpp> #include "pluginsystem/iplugin.h" class QAction; class QWidget; class Core; class CloudList; class LayerList; class FlatView; class GLWidget; class MainWindow; class Layer; class QLineEdit; class Compare : public IPlugin { Q_INTERFACES(IPlugin) Q_OBJECT Q_PLUGIN_METADATA(IID "za.co.circlingthesun.cloudclean.compare" FILE "compare.json") public: QString getName(); void initialize(Core * core); void cleanup(); ~Compare(); signals: void enabling(); private slots: void enable(); void disable(); void compare(); private: Core * core_; CloudList * cl_; LayerList * ll_; GLWidget * glwidget_; FlatView * flatview_; MainWindow * mw_; QAction * enable_; QWidget * settings_; bool is_enabled_; QLineEdit * precision_; QLineEdit * recall_; float radius_; std::vector<boost::weak_ptr<Layer> > layers1_; std::vector<boost::weak_ptr<Layer> > layers2_; }; #endif // COMPARE_H
18.631579
88
0.681733
[ "vector" ]
3cd5eae653f698e74520fd386050da28ea34ce2b
1,889
h
C
src/js.h
BonsaiDen/wombat
805e60cb9d06d63bf29e493586babe8cd30b8e47
[ "MIT" ]
1
2015-04-19T17:07:15.000Z
2015-04-19T17:07:15.000Z
src/js.h
BonsaiDen/wombat
805e60cb9d06d63bf29e493586babe8cd30b8e47
[ "MIT" ]
null
null
null
src/js.h
BonsaiDen/wombat
805e60cb9d06d63bf29e493586babe8cd30b8e47
[ "MIT" ]
null
null
null
// Copyright (c) 2012 Ivo Wetzel. // // 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 JS_H #define JS_H #include <v8.h> #include <string> v8::Handle<v8::Script> loadScript(const char *name); v8::Handle<v8::Value> requireScript(const v8::Arguments& args); v8::Handle<v8::Value> executeScript(const v8::Handle<v8::Script> &script); v8::Persistent<v8::Object> JSObject(); void handleException(const v8::TryCatch &tryCatch); inline int ToInt32(const v8::Handle<v8::Value> &i) { return i->Int32Value(); } inline float ToFloat(const v8::Handle<v8::Value> &f) { return static_cast<float>(f->NumberValue()); } inline float ToBoolean(const v8::Handle<v8::Value> &f) { return f->BooleanValue(); } inline std::string ToString(const v8::Handle<v8::Value> &f) { v8::String::Utf8Value raw(f->ToString()); return std::string(*raw); } #endif
36.326923
80
0.734251
[ "object" ]
3cdc6cfd5600916ac9ce6494f210622d014635d5
2,728
h
C
compiler/src/CFCParamList.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
7
2015-04-04T08:35:51.000Z
2021-11-10T15:44:30.000Z
compiler/src/CFCParamList.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
24
2015-04-22T14:35:06.000Z
2016-07-22T14:05:53.000Z
compiler/src/CFCParamList.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
13
2015-04-20T17:22:24.000Z
2021-11-10T15:42:43.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. */ /** Clownfish::CFC::Model::ParamList - parameter list. */ #ifndef H_CFCPARAMLIST #define H_CFCPARAMLIST #ifdef __cplusplus extern "C" { #endif typedef struct CFCParamList CFCParamList; struct CFCClass; struct CFCVariable; struct CFCType; /** * @param variadic Should be true if the function is variadic. */ CFCParamList* CFCParamList_new(int variadic); CFCParamList* CFCParamList_init(CFCParamList *self, int variadic); void CFCParamList_resolve_types(CFCParamList *self); void CFCParamList_destroy(CFCParamList *self); /** Add a parameter to the ParamList. * * @param variable A Clownfish::CFC::Model::Variable. * @param value The parameter's default value, which should be NULL * if there is no default and thus the parameter is required. */ void CFCParamList_add_param(CFCParamList *self, struct CFCVariable *variable, const char *value); struct CFCVariable** CFCParamList_get_variables(CFCParamList *self); const char** CFCParamList_get_initial_values(CFCParamList *self); void CFCParamList_set_variadic(CFCParamList *self, int variadic); int CFCParamList_variadic(CFCParamList *self); /** Return the number of variables in the ParamList, including "self" for * methods. */ int CFCParamList_num_vars(CFCParamList *self); /** Return a list of the variable's types and names, joined by commas. For * example: * * Obj* self, Foo* foo, Bar* bar */ const char* CFCParamList_to_c(CFCParamList *self); /** Return the variable's names, joined by commas. For example: * * self, foo, bar */ const char* CFCParamList_name_list(CFCParamList *self); /** Return the name of the parameter at position `tick`. */ const char* CFCParamList_param_name(CFCParamList *self, int tick); /** Return the type of the parameter at position `tick`. */ struct CFCType* CFCParamList_param_type(CFCParamList *self, int tick); #ifdef __cplusplus } #endif #endif /* H_CFCPARAMLIST */
25.495327
75
0.750367
[ "model" ]
3ce10891d6aa21f76a3fcc67add6b722dba963d2
5,718
h
C
frameworks/core/gestures/gesture_recognizer.h
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/core/gestures/gesture_recognizer.h
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/core/gestures/gesture_recognizer.h
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
1
2021-09-13T11:17:50.000Z
2021-09-13T11:17:50.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_GESTURES_GESTURE_RECOGNIZER_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_GESTURES_GESTURE_RECOGNIZER_H #include <map> #include <memory> #include <set> #include "gesture_referee.h" #include "core/event/touch_event.h" #include "core/gestures/gesture_info.h" namespace OHOS::Ace { enum class DetectState { READY, DETECTING, DETECTED }; enum class RefereeState { DETECTING, PENDING, BLOCKED, SUCCEED, FAIL }; class GestureRecognizer : public TouchEventTarget { DECLARE_ACE_TYPE(GestureRecognizer, TouchEventTarget) public: // Called when request of handling gesture sequence is accepted by gesture referee. virtual void OnAccepted(size_t touchId) = 0; // Called when request of handling gesture sequence is rejected by gesture referee. virtual void OnRejected(size_t touchId) = 0; // Called when request of handling gesture sequence is rejected by gesture referee. virtual void OnPending(size_t touchId) {} // Reconiciles the state from the given recognizer into this. The // implementation must check that the given recognizer type matches the // current one. The return value should be false if the reconciliation fails // and true if it succeeds virtual bool ReconcileFrom(const RefPtr<GestureRecognizer>& recognizer) { return true; } bool DispatchEvent(const TouchPoint& point) override { return true; } bool HandleEvent(const TouchPoint& point) override; // Coordinate offset is used to calculate the local location of the touch point in the render node. void SetCoordinateOffset(const Offset& coordinateOffset) { coordinateOffset_ = coordinateOffset; } // Gets the coordinate offset to calculate the local location of the touch point by manually. const Offset& GetCoordinateOffset() const { return coordinateOffset_; } GesturePriority GetPriority() const { return priority_; } void SetPriority(GesturePriority priority) { priority_ = priority; } GestureMask GetPriorityMask() const { return priorityMask_; } void SetPriorityMask(GestureMask priorityMask) { priorityMask_ = priorityMask; } RefereeState GetRefereeState() const { return refereeState_; } void SetRefereeState(RefereeState refereeState) { refereeState_ = refereeState; } DetectState GetDetectState() const { return state_; } void SetGestureGroup(const WeakPtr<GestureRecognizer>& gestureGroup) { gestureGroup_ = gestureGroup; } void SetOnAction(const GestureEventFunc& onAction) { onAction_ = std::make_unique<GestureEventFunc>(onAction); } void SetOnActionStart(const GestureEventFunc& onActionStart) { onActionStart_ = std::make_unique<GestureEventFunc>(onActionStart); } void SetOnActionUpdate(const GestureEventFunc& onActionUpdate) { onActionUpdate_ = std::make_unique<GestureEventFunc>(onActionUpdate); } void SetOnActionEnd(const GestureEventFunc& onActionEnd) { onActionEnd_ = std::make_unique<GestureEventFunc>(onActionEnd); } void SetOnActionCancel(const GestureEventNoParameter& onActionCancel) { onActionCancel_ = std::make_unique<GestureEventNoParameter>(onActionCancel); } inline void SendCancelMsg() { if (onActionCancel_ && *onActionCancel_) { (*onActionCancel_)(); } } void SetIsExternalGesture(bool isExternalGesture) { isExternalGesture_ = isExternalGesture; } bool GetIsExternalGesture() const { return isExternalGesture_; } protected: virtual void HandleTouchDownEvent(const TouchPoint& event) = 0; virtual void HandleTouchUpEvent(const TouchPoint& event) = 0; virtual void HandleTouchMoveEvent(const TouchPoint& event) = 0; virtual void HandleTouchCancelEvent(const TouchPoint& event) = 0; virtual void AddToReferee(size_t touchId, const RefPtr<GestureRecognizer>& recognizer); virtual void DelFromReferee(size_t touchId, const RefPtr<GestureRecognizer>& recognizer); virtual void BatchAdjudicate( const std::set<size_t>& touchIds, const RefPtr<GestureRecognizer>& recognizer, GestureDisposal disposal); Offset coordinateOffset_; DetectState state_ { DetectState::READY }; RefereeState refereeState_ { RefereeState::DETECTING }; GesturePriority priority_ = GesturePriority::Low; GestureMask priorityMask_ = GestureMask::Normal; int32_t fingers_ = 1; bool isExternalGesture_ = false; std::unique_ptr<GestureEventFunc> onAction_; std::unique_ptr<GestureEventFunc> onActionStart_; std::unique_ptr<GestureEventFunc> onActionUpdate_; std::unique_ptr<GestureEventFunc> onActionEnd_; std::unique_ptr<GestureEventNoParameter> onActionCancel_; private: WeakPtr<GestureRecognizer> gestureGroup_; }; } // namespace OHOS::Ace #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_GESTURES_GESTURE_RECOGNIZER_H
30.253968
113
0.723155
[ "render" ]
3ceef459f9cc332ead7d3a62922708978c4f492f
11,654
h
C
SpatialGDK/Source/SpatialGDK/Public/Utils/SpatialDebugger.h
AshHipgrave/UnrealGDK
21c819d3782280e9cf3674f9616d749de0443b82
[ "MIT" ]
1
2020-07-15T12:43:02.000Z
2020-07-15T12:43:02.000Z
SpatialGDK/Source/SpatialGDK/Public/Utils/SpatialDebugger.h
AshHipgrave/UnrealGDK
21c819d3782280e9cf3674f9616d749de0443b82
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDK/Public/Utils/SpatialDebugger.h
AshHipgrave/UnrealGDK
21c819d3782280e9cf3674f9616d749de0443b82
[ "MIT" ]
null
null
null
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #pragma once #include "LoadBalancing/WorkerRegion.h" #include "SpatialCommonTypes.h" #include "SpatialDebuggerConfigUI.h" #include "Containers/Map.h" #include "CoreMinimal.h" #include "Engine/Canvas.h" #include "GameFramework/Info.h" #include "Materials/Material.h" #include "Math/Box2D.h" #include "Math/Color.h" #include "SpatialDebugger.generated.h" class APawn; class APlayerController; class APlayerState; class USpatialNetDriver; class UFont; class UTexture2D; DECLARE_LOG_CATEGORY_EXTERN(LogSpatialDebugger, Log, All); DECLARE_STATS_GROUP(TEXT("SpatialDebugger"), STATGROUP_SpatialDebugger, STATCAT_Advanced); DECLARE_CYCLE_STAT(TEXT("DrawDebug"), STAT_DrawDebug, STATGROUP_SpatialDebugger); DECLARE_CYCLE_STAT(TEXT("DrawTag"), STAT_DrawTag, STATGROUP_SpatialDebugger); DECLARE_CYCLE_STAT(TEXT("Projection"), STAT_Projection, STATGROUP_SpatialDebugger); DECLARE_CYCLE_STAT(TEXT("DrawIcons"), STAT_DrawIcons, STATGROUP_SpatialDebugger); DECLARE_CYCLE_STAT(TEXT("DrawText"), STAT_DrawText, STATGROUP_SpatialDebugger); DECLARE_CYCLE_STAT(TEXT("BuildText"), STAT_BuildText, STATGROUP_SpatialDebugger); namespace SpatialGDK { class SpatialDebuggerSystem; } USTRUCT() struct FWorkerRegionInfo { GENERATED_BODY() UPROPERTY() FColor Color; UPROPERTY() FBox2D Extents; UPROPERTY() FString WorkerName; UPROPERTY() uint32 VirtualWorkerID; }; UENUM() namespace EActorTagDrawMode { enum Type { None, LocalPlayer, All }; } // namespace EActorTagDrawMode DECLARE_DYNAMIC_DELEGATE(FOnConfigUIClosedDelegate); /** * Visualise spatial information at runtime and in the editor */ UCLASS(SpatialType = (NotPersistent), Blueprintable, NotPlaceable, Transient) class SPATIALGDK_API ASpatialDebugger : public AInfo { GENERATED_UCLASS_BODY() public: virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; virtual void Tick(float DeltaSeconds) override; virtual void BeginPlay() override; virtual void Destroyed() override; void OnEntityAdded(AActor* Actor); virtual void OnAuthorityGained() override; UFUNCTION(Exec, Category = "SpatialGDK", BlueprintCallable) void SpatialToggleDebugger(); UFUNCTION(Category = "SpatialGDK", BlueprintCallable, BlueprintPure) bool IsEnabled(); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = UI, meta = (ToolTip = "Key to open configuration UI for the debugger at runtime")) FKey ConfigUIToggleKey = EKeys::F9; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = UI, meta = (ToolTip = "Key to select actor when debugging in game")) FKey SelectActorKey = EKeys::RightMouseButton; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = UI, meta = (ToolTip = "Key to highlight next actor under cursor when debugging in game")) FKey HighlightActorKey = EKeys::MouseWheelAxis; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = UI, meta = (ToolTip = "In-game configuration UI widget")) TSubclassOf<USpatialDebuggerConfigUI> ConfigUIClass; FOnConfigUIClosedDelegate OnConfigUIClosed; // TODO: Expose these through a runtime UI: https://improbableio.atlassian.net/browse/UNR-2359. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LocalPlayer, meta = (ToolTip = "X location of player data panel")) int PlayerPanelStartX = 64; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LocalPlayer, meta = (ToolTip = "Y location of player data panel")) int PlayerPanelStartY = 64; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = General, meta = (ToolTip = "Maximum range from local player that tags will be drawn out to")) float MaxRange = 100.0f * 100.0f; // 100m UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (Tooltip = "Which Actor tags to show")) TEnumAsByte<EActorTagDrawMode::Type> ActorTagDrawMode = EActorTagDrawMode::All; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (Tooltip = "Show all replicated Actors in the player controller's hierarchy, or just state/controller/pawn")) bool bShowPlayerHierarchy = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show server authority for every entity in range")) bool bShowAuth = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show authority intent for every entity in range")) bool bShowAuthIntent = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show lock status for every entity in range")) bool bShowLock = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show EntityId for every entity in range")) bool bShowEntityId = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show Actor Name for every entity in range")) bool bShowActorName = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Show glowing mesh when selecting actors.")) bool bShowHighlight = false; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Select the object types you want to query when selecting actors")) TArray<TEnumAsByte<ECollisionChannel>> SelectCollisionTypesToQuery = { ECollisionChannel::ECC_WorldStatic, ECollisionChannel::ECC_WorldDynamic, ECollisionChannel::ECC_Pawn, ECollisionChannel::ECC_Destructible, ECollisionChannel::ECC_Vehicle, ECollisionChannel::ECC_PhysicsBody }; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = StartUp, meta = (ToolTip = "Show the Spatial Debugger automatically at startup")) bool bAutoStart = false; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Show a transparent Worker Region cuboid representing the area of authority for each server worker")) bool bShowWorkerRegions = false; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Height at which the origin of each worker region cuboid is placed")) float WorkerRegionHeight = 30.0f; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "Vertical scale to apply to each worker region cuboid")) float WorkerRegionVerticalScale = 1.0f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Opacity of the worker region cuboids")) float WorkerRegionOpacity = 0.7f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Texture to use for the Auth Icon")) UTexture2D* AuthTexture; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Texture to use for the Auth Intent Icon")) UTexture2D* AuthIntentTexture; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Texture to use for the Unlocked Icon")) UTexture2D* UnlockedTexture; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Texture to use for the Locked Icon")) UTexture2D* LockedTexture; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Visualization, meta = (ToolTip = "Texture to use for the Box Icon")) UTexture2D* BoxTexture; // This will be drawn instead of the mouse cursor when selecting an actor UPROPERTY(EditDefaultsOnly, Category = Visualization, meta = (ToolTip = "Texture to use when selecting an actor")) UTexture2D* CrosshairTexture; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Visualization, meta = (ToolTip = "WorldSpace offset of tag from actor pivot")) FVector WorldSpaceActorTagOffset = FVector(0.0f, 0.0f, 200.0f); UPROPERTY(EditDefaultsOnly, Category = Visualization, meta = (ToolTip = "Color used for any server with an unresolved name")) FColor InvalidServerTintColor = FColor::Magenta; UPROPERTY(ReplicatedUsing = OnRep_SetWorkerRegions) TArray<FWorkerRegionInfo> WorkerRegions; UFUNCTION() virtual void OnRep_SetWorkerRegions(); UFUNCTION() void OnToggleConfigUI(); UFUNCTION(BlueprintCallable, Category = Visualization) void ToggleSelectActor(); UFUNCTION() void OnSelectActor(); UFUNCTION() void OnHighlightActor(); UFUNCTION(BlueprintCallable, BlueprintPure, Category = Visualization) bool IsSelectActorEnabled() const; private: UFUNCTION() void DefaultOnConfigUIClosed(); public: UFUNCTION(BlueprintCallable, Category = Visualization) void SetShowWorkerRegions(const bool bNewShow); #if WITH_EDITOR void EditorRefreshWorkerRegions(); static void EditorRefreshDisplay(); bool EditorAllowWorkerBoundaries() const; void EditorSpatialToggleDebugger(bool bEnabled); #endif private: void LoadIcons(); // FDebugDrawDelegate void DrawDebug(UCanvas* Canvas, APlayerController* Controller); bool ProjectActorToScreen(const FVector& ActorLocation, const FVector& PlayerLocation, FVector2D& OutLocation, const UCanvas* Canvas); FVector GetLocalPawnLocation(); // Allow user to select actor(s) for debugging - the mesh on the actor must have collision presets enabled to block on at least one of // the object channels void SelectActorsToTag(UCanvas* Canvas); void HighlightActorUnderCursor(TWeakObjectPtr<AActor>& NewHoverActor); TWeakObjectPtr<AActor> GetActorAtPosition(const FVector2D& MousePosition, const UCanvas* Canvas); TWeakObjectPtr<AActor> GetHitActor(); bool CanProjectActorLocationToScreen(const FVector& ActorLocation, const FVector& PlayerLocation, const UCanvas* Canvas); void RevertHoverMaterials(); void DrawTag(UCanvas* Canvas, const FVector2D& ScreenLocation, const Worker_EntityId EntityId, const FString& ActorName, const bool bCentre); void DrawDebugLocalPlayer(UCanvas* Canvas); void CreateWorkerRegions(); void DestroyWorkerRegions(); FColor GetTextColorForBackgroundColor(const FColor& BackgroundColor) const; int32 GetNumberOfDigitsIn(int32 SomeNumber) const; #if WITH_EDITOR void EditorInitialiseWorkerRegions(); virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif static const int PLAYER_TAG_VERTICAL_OFFSET = 18; enum EIcon { ICON_AUTH, ICON_AUTH_INTENT, ICON_UNLOCKED, ICON_LOCKED, ICON_BOX, ICON_MAX }; USpatialNetDriver* NetDriver; SpatialGDK::SpatialDebuggerSystem* GetDebuggerSystem() const; FDelegateHandle DrawDebugDelegateHandle; TWeakObjectPtr<APawn> LocalPawn; TWeakObjectPtr<APlayerController> LocalPlayerController; TWeakObjectPtr<APlayerState> LocalPlayerState; UFont* RenderFont; FFontRenderInfo FontRenderInfo; FCanvasIcon Icons[ICON_MAX]; USpatialDebuggerConfigUI* ConfigUIWidget; // Mode for selecting actors under the cursor - should only be visible in the runtime config UI bool bSelectActor = false; // Actors selected by user for debugging TArray<TWeakObjectPtr<AActor>> SelectedActors; // Highlighted actor under the mouse cursor TWeakObjectPtr<AActor> HoverActor; // Highlighted actor original materials and components TArray<TWeakObjectPtr<UMaterialInterface>> ActorMeshMaterials; TArray<TWeakObjectPtr<UMeshComponent>> ActorMeshComponents; // Material for highlighting actor UPROPERTY() UMaterialInterface* WireFrameMaterial; // All actors under the mouse cursor TArray<TWeakObjectPtr<AActor>> HitActors; // Index for selecting the highlighted actor when multiple are under the mouse cursor int32 HoverIndex; // Mouse position to avoid unnecessary raytracing when mouse has not moved FVector2D MousePosition; // Select actor object types to query FCollisionObjectQueryParams CollisionObjectParams; };
35.208459
136
0.790973
[ "mesh", "object" ]
a7062d07b82e44c326f12983e29f269c7df5f480
4,110
h
C
plugins/datatools/include/datatools/misc/FrechetDistance.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/datatools/include/datatools/misc/FrechetDistance.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/datatools/include/datatools/misc/FrechetDistance.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
#pragma once #include <functional> #include <vector> // http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf namespace { template<typename T, typename V> inline T c(std::vector<T>& ca, typename std::vector<V>::size_type width, typename std::vector<V>::size_type i, typename std::vector<V>::size_type j, std::vector<V> const& a, std::vector<V> const& b, std::function<T(V const&, V const&)> const& dist) { // auto dist = [](T const& a, T const& b) -> T { return std::abs(a - b); }; if (ca[i + j * a.size()] > static_cast<T>(-1)) { return ca[i + j * a.size()]; } else if (i == 0 && j == 0) { ca[i + j * a.size()] = dist(a[0], b[0]); } else if (i > 0 && j == 0) { ca[i + j * a.size()] = std::max<T>(c(ca, width, i - 1, 0, a, b, dist), dist(a[i], b[0])); } else if (i == 0 && j > 0) { ca[i + j * a.size()] = std::max<T>(c(ca, width, 0, j - 1, a, b, dist), dist(a[0], b[j])); } else if (i > 0 && j > 0) { ca[i + j * a.size()] = std::max<T>(std::min<T>(c(ca, width, i - 1, j, a, b, dist), std::min<T>(c(ca, width, i - 1, j - 1, a, b, dist), c(ca, width, i, j - 1, a, b, dist))), dist(a[i], b[j])); } else { return std::numeric_limits<T>::infinity(); } return ca[i + j * a.size()]; } template<typename T> inline T c(std::vector<T>& ca, std::size_t width, std::size_t i, std::size_t j, std::function<T(std::size_t, std::size_t)> const& dist) { // auto dist = [](T const& a, T const& b) -> T { return std::abs(a - b); }; if (ca[i + j * width] > static_cast<T>(-1.0f)) { return ca[i + j * width]; } else if (i == 0 && j == 0) { ca[i + j * width] = dist(0, 0); } else if (i > 0 && j == 0) { ca[i + j * width] = std::max<T>(c(ca, width, i - 1, 0, dist), dist(i, 0)); } else if (i == 0 && j > 0) { ca[i + j * width] = std::max<T>(c(ca, width, 0, j - 1, dist), dist(0, j)); } else if (i > 0 && j > 0) { ca[i + j * width] = std::max<T>(std::min<T>(c(ca, width, i - 1, j, dist), std::min<T>(c(ca, width, i - 1, j - 1, dist), c(ca, width, i, j - 1, dist))), dist(i, j)); } else { return std::numeric_limits<T>::infinity(); } return ca[i + j * width]; } } // namespace namespace megamol::datatools::misc { template<typename T, typename V> inline T frechet_distance( std::vector<V> const& a, std::vector<V> const& b, std::function<T(V const&, V const&)> const& dist) { auto const total_size = a.size() * b.size(); std::vector<T> ca(total_size, static_cast<T>(-1)); return c<T, V>(ca, a.size(), a.size() - 1, b.size() - 1, a, b, dist); } template<typename T> inline T frechet_distance(std::size_t sample_count, std::function<T(std::size_t, std::size_t)> const& dist) { auto const total_size = sample_count * sample_count; std::vector<T> ca(total_size, static_cast<T>(-1)); ca[0] = dist(0, 0); for (std::size_t i = 1; i < sample_count; ++i) { ca[i] = std::max<T>(ca[i - 1], dist(i, 0)); ca[i * sample_count] = std::max<T>(ca[(i - 1) * sample_count], dist(0, i)); } for (std::size_t i = 1; i < sample_count; ++i) { for (std::size_t j = 1; j < sample_count; ++j) { auto const c_0 = ca[i - 1 + j * sample_count]; auto const c_1 = ca[i - 1 + (j - 1) * sample_count]; auto const c_2 = ca[i + (j - 1) * sample_count]; ca[i + j * sample_count] = std::max<T>(std::min<T>(c_0, std::min<T>(c_1, c_2)), dist(i, j)); } } //return ca[sample_count - 1 + (sample_count - 1) * sample_count]; return ca[sample_count * sample_count - 1]; } template<typename T> inline T frechet_distance_2(std::size_t sample_count, std::function<T(std::size_t, std::size_t)> const& dist) { auto const total_size = sample_count * sample_count; std::vector<T> ca(total_size, static_cast<T>(-1)); return c<T>(ca, sample_count, sample_count - 1, sample_count - 1, dist); } } // namespace megamol::datatools::misc
41.938776
117
0.527494
[ "vector" ]
a7070b2e4e144a961b16c4af5c63d24f99cf613b
5,378
h
C
camera/hal/buffer_manager/test/unittest/buffer_manager_utest.h
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
camera/hal/buffer_manager/test/unittest/buffer_manager_utest.h
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
null
null
null
camera/hal/buffer_manager/test/unittest/buffer_manager_utest.h
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
[ "Apache-2.0" ]
2
2021-09-13T10:12:47.000Z
2021-09-13T11:16:31.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CAMERA_DEMO_TEST_H #define CAMERA_DEMO_TEST_H #include <list> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include <gtest/gtest.h> #include "display_type.h" #include "ibuffer.h" #include "ibuffer_pool.h" #include "surface.h" #include "ibuffer_consumer_listener.h" namespace OHOS::CameraUtest { using namespace OHOS::Camera; class BufferManagerTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(void); void TearDown(void); public: class Stream { public: Stream() = default; ~Stream() = default; #ifdef CAMERA_BUILT_ON_OHOS_LITE bool Init(std::shared_ptr<OHOS::Surface>& producer); #else bool Init(OHOS::sptr<OHOS::IBufferProducer>& producer); #endif void StartStream(); void StopStream(); void EnqueueBufferNonBlock(); void DequeueBuffer(std::shared_ptr<IBuffer>& buffer); std::shared_ptr<IBufferPool> GetBufferPool() const; int64_t GetPoolId() const { return bufferPoolId_; } private: void StartInnerStream() const; void StartExternalStream(); private: std::mutex lock_; #ifdef CAMERA_BUILT_ON_OHOS_LITE std::shared_ptr<OHOS::Surface> producer_ = nullptr; #else OHOS::sptr<OHOS::Surface> producer_ = nullptr; #endif uint32_t width_ = 1920; uint32_t height_ = 1080; uint32_t queueSize_ = 7; uint64_t usage_ = CAMERA_USAGE_SW_WRITE_OFTEN | CAMERA_USAGE_SW_READ_OFTEN | CAMERA_USAGE_MEM_DMA; uint32_t format_ = CAMERA_FORMAT_YCBCR_420_SP; int64_t bufferPoolId_ = -1; std::shared_ptr<IBufferPool> bufferPool_ = nullptr; #ifdef CAMERA_BUILT_ON_OHOS_LITE std::vector<std::pair<OHOS::SurfaceBuffer*, std::shared_ptr<IBuffer>>> bufferVec_ = {}; #else std::vector<std::pair<OHOS::sptr<OHOS::SurfaceBuffer>, std::shared_ptr<IBuffer>>> bufferVec_ = {}; int32_t releaseFence_ = 0; OHOS::BufferRequestConfig requestConfig_ = {}; OHOS::BufferFlushConfig flushConfig_ = {}; #endif }; #ifndef CAMERA_BUILT_ON_OHOS_LITE class TestBufferConsumerListener: public IBufferConsumerListener { public: TestBufferConsumerListener() { } ~TestBufferConsumerListener() { } void OnBufferAvailable() { } }; #endif class Node { public: explicit Node(const std::string name) { name_ = name; } virtual ~Node() = default; virtual void Connect(std::shared_ptr<Node>& nextNode); virtual void Deliver(std::shared_ptr<IBuffer>& buffer); virtual void Receive(std::shared_ptr<IBuffer>& buffer); virtual void Process(std::shared_ptr<IBuffer>& buffer); virtual std::string GetName() const; private: std::string name_ = ""; std::shared_ptr<Node> nextNode_ = nullptr; private: Node() = default; }; class SinkNode : public Node { public: SinkNode(const std::string name) : Node(name) {} ~SinkNode() {} void Deliver(std::shared_ptr<IBuffer>& buffer) override; void BindCallback(std::function<void(std::shared_ptr<IBuffer>&)> callback); private: std::function<void(std::shared_ptr<IBuffer>&)> callback_ = nullptr; }; class SourceNode : public Node { public: SourceNode(const std::string name) : Node(name) {} void Process(std::shared_ptr<IBuffer>& buffer) override; ~SourceNode() {} private: int cacheSize_ = 3; std::list<std::shared_ptr<IBuffer>> cache_ = {}; }; class Pipeline { public: Pipeline() = default; ~Pipeline() = default; bool AddStream(std::shared_ptr<Stream>& stream); void StartStream(); void StopStream(); private: void CollectBuffers(); void DeliverBuffer(); void DeliverBuffer(std::shared_ptr<IBuffer>& buffer); bool BuildPipeline(); private: bool running = true; std::mutex streamLock_; std::thread* collectThread_ = nullptr; std::shared_ptr<Node> sourceNode_ = nullptr; uint64_t frameNumber = 0; struct LocalStream { std::mutex deviceLock_; std::shared_ptr<Stream> stream_ = nullptr; std::thread* deliverThread_ = nullptr; std::list<std::shared_ptr<IBuffer>> deviceBufferList_ = {}; }; std::shared_ptr<LocalStream> localStream_ = nullptr; }; }; } // namespace OHOS::CameraUtest #endif // CAMERA_DEMO_TEST_H
28.759358
106
0.637412
[ "vector" ]
a707be3ee2088ed3526703b42ce16860d7e71949
546
h
C
app/EQPModule/View/EImageView.h
zhang651651/ipad
cf3ebc2854bd5f28d7828498ba63936d21aa43ee
[ "MIT" ]
1
2019-04-06T15:21:53.000Z
2019-04-06T15:21:53.000Z
app/EQPModule/View/EImageView.h
zhang651651/ipad
cf3ebc2854bd5f28d7828498ba63936d21aa43ee
[ "MIT" ]
null
null
null
app/EQPModule/View/EImageView.h
zhang651651/ipad
cf3ebc2854bd5f28d7828498ba63936d21aa43ee
[ "MIT" ]
null
null
null
// // EImageView.h // ipad // // Created by Zhang Xinrong on 2018/11/10. // Copyright © 2018 nil. All rights reserved. // #import <UIKit/UIKit.h> #import "YSEQPImageModel.h" NS_ASSUME_NONNULL_BEGIN @interface EImageView : UIView //type 0:生态 1:未检 -(instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type; @property(nonatomic,strong)UILabel *titleLabel1; @property(nonatomic,strong)UILabel *titleLabel2; @property(nonatomic,strong)UIButton *btn1; @property (nonatomic, strong) YSEQPImageModel *model; @end NS_ASSUME_NONNULL_END
19.5
64
0.75641
[ "model" ]
a7085ac6893e73c673fbbbac2185817f69b4c2d1
828
h
C
SwanUI/Zobrist.h
mathias-dietrich/Swan
a0023c1ccafffc4518404683c6cc1912b8e5a3bf
[ "Apache-2.0" ]
null
null
null
SwanUI/Zobrist.h
mathias-dietrich/Swan
a0023c1ccafffc4518404683c6cc1912b8e5a3bf
[ "Apache-2.0" ]
null
null
null
SwanUI/Zobrist.h
mathias-dietrich/Swan
a0023c1ccafffc4518404683c6cc1912b8e5a3bf
[ "Apache-2.0" ]
null
null
null
// // Zobrist.h // SwanUI // // Created by Mathias Dietrich on 04.10.20. // #ifndef Zobrist_h #define Zobrist_h // // Zobrist.hpp // Blackbird // // Created by Mathias Dietrich on 6/24/18. // Copyright © 2018 Mathias Dietrich. All rights reserved. // https://wikivisually.com/wiki/Zobrist_hashing // https://github.com/lemire/zobristhashing #pragma once #include <string> #include <vector> #include <stdlib.h> #include "Type.hpp" #include "pg_key.h" #include "Board.hpp" #include "Fen.hpp" using namespace std; class Zobrist{ public: pg_key *key = new pg_key(); Fen *fenParser = new Fen(); uint64_t hash(string fen){ return key->findHash(fen); } uint64_t hash(Board * board){ return key->findHash(fenParser->parse(board)); } }; #endif /* Zobrist_h */
16.56
59
0.644928
[ "vector" ]
a70b28aae97ac6d64b37cdc910bd70b1358c2dad
1,344
h
C
panda/src/physx/physxRaycastHit.h
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/physx/physxRaycastHit.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/physx/physxRaycastHit.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: physxRaycastHit.h // Created by: enn0x (21Oct09) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef PHYSXRAYCASTHIT_H #define PHYSXRAYCASTHIT_H #include "pandabase.h" #include "luse.h" #include "config_physx.h" class PhysxShape; //////////////////////////////////////////////////////////////////// // Class : PhysxRaycastHit // Description : This structure captures results for a single // raycast query. See PhysxScene for raycasting // methods. //////////////////////////////////////////////////////////////////// class EXPCL_PANDAPHYSX PhysxRaycastHit { PUBLISHED: INLINE PhysxRaycastHit(const NxRaycastHit hit); INLINE ~PhysxRaycastHit(); bool is_empty() const; PhysxShape *get_shape() const; LPoint3f get_impact_pos() const; LVector3f get_impact_normal() const; float get_distance() const; private: NxRaycastHit _hit; }; #include "physxRaycastHit.I" #endif // PHYSXRAYCASTHIT_H
26.352941
70
0.575149
[ "3d" ]
a7106b16d794fd68361b64a34c151e09077b39ec
3,650
h
C
VkLayer_profiler_layer/profiler/profiler_data_aggregator.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
1
2021-03-11T12:10:20.000Z
2021-03-11T12:10:20.000Z
VkLayer_profiler_layer/profiler/profiler_data_aggregator.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
10
2020-12-09T15:14:11.000Z
2021-01-23T18:52:26.000Z
VkLayer_profiler_layer/profiler/profiler_data_aggregator.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Lukasz Stalmirski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include "profiler_data.h" #include "profiler_command_buffer.h" #include <list> #include <map> #include <mutex> #include <unordered_set> #include <unordered_map> // Import extension structures #include "profiler_ext/VkProfilerEXT.h" namespace Profiler { class DeviceProfiler; struct DeviceProfilerSubmit { std::vector<ProfilerCommandBuffer*> m_pCommandBuffers; std::vector<VkSemaphore> m_SignalSemaphores = {}; std::vector<VkSemaphore> m_WaitSemaphores = {}; }; struct DeviceProfilerSubmitBatch { VkQueue m_Handle = {}; ContainerType<DeviceProfilerSubmit> m_Submits = {}; std::chrono::high_resolution_clock::time_point m_Timestamp = {}; uint32_t m_ThreadId = {}; }; /***********************************************************************************\ Class: ProfilerDataAggregator Description: Merges data from multiple command buffers \***********************************************************************************/ class ProfilerDataAggregator { public: VkResult Initialize( DeviceProfiler* ); void AppendSubmit( const DeviceProfilerSubmitBatch& ); void AppendData( ProfilerCommandBuffer*, const DeviceProfilerCommandBufferData& ); void Aggregate(); void Reset(); DeviceProfilerFrameData GetAggregatedData() const; private: DeviceProfiler* m_pProfiler; std::list<DeviceProfilerSubmitBatch> m_Submits; std::list<DeviceProfilerSubmitBatchData> m_AggregatedData; std::unordered_map<ProfilerCommandBuffer*, DeviceProfilerCommandBufferData> m_Data; std::mutex m_Mutex; // Vendor-specific metric properties std::vector<VkProfilerPerformanceCounterPropertiesEXT> m_VendorMetricProperties; std::vector<VkProfilerPerformanceCounterResultEXT> AggregateVendorMetrics() const; std::list<DeviceProfilerPipelineData> CollectTopPipelines() const; void CollectPipelinesFromCommandBuffer( const DeviceProfilerCommandBufferData&, std::unordered_map<uint32_t, DeviceProfilerPipelineData>& ) const; void CollectPipeline( const DeviceProfilerPipelineData&, std::unordered_map<uint32_t, DeviceProfilerPipelineData>& ) const; }; }
36.868687
91
0.656712
[ "vector" ]
a7139597c465f72f4fd1df9e523710bc73675561
2,836
h
C
ToolKit/SkinFramework/XTPSkinObjectToolBar.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/SkinFramework/XTPSkinObjectToolBar.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/SkinFramework/XTPSkinObjectToolBar.h
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPSkinObjectToolBar.h: interface for the CXTPSkinObjectToolBar class. // // This file is a part of the XTREME SKINFRAMEWORK MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPSKINOBJECTTOOLBAR_H__) #define __XTPSKINOBJECTTOOLBAR_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "XTPSkinObject.h" #include "XTPSkinObjectFrame.h" //=========================================================================== // Summary: // CXTPSkinObjectToolBar is a CXTPSkinObjectFrame derived class. // It implements standard toolbar control //=========================================================================== class _XTP_EXT_CLASS CXTPSkinObjectToolBar : public CXTPSkinObjectFrame { DECLARE_DYNCREATE(CXTPSkinObjectToolBar) public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTPSkinObjectToolBar object. //----------------------------------------------------------------------- CXTPSkinObjectToolBar(); //----------------------------------------------------------------------- // Summary: // Destroys a CXTPSkinObjectToolBar object, handles cleanup and deallocation. //----------------------------------------------------------------------- virtual ~CXTPSkinObjectToolBar(); protected: void DrawToolbarH(CDC* pDC); void DrawButton(CDC* pDC, int nIndex); HIMAGELIST GetImageList(int iMode, int iIndex); BOOL HasDropDownArrow(LPTBBUTTON ptbb); BOOL HasSplitDropDown(LPTBBUTTON ptbb); void DrawButtonImage(CDC* pDC, int x, int y, int nIndex); BOOL HasButtonImage(LPTBBUTTON ptbb); BOOL IsAlphaImageList(HIMAGELIST himl); void UpdateToolTipsPos(); protected: //{{AFX_CODEJOCK_PRIVATE DECLARE_MESSAGE_MAP() LRESULT CustomDrawNotify(DWORD dwDrawStage, NMCUSTOMDRAW* pnmcd); //{{AFX_VIRTUAL(CXTPSkinObjectToolBar) //}}AFX_VIRTUAL //{{AFX_MSG(CXTPSkinObjectToolBar) void OnPaint(); BOOL OnEraseBkgnd(CDC* pDC); //}}AFX_MSG BOOL IsSpecialSystemToolbar(); int m_nSpecialToolbar; CMap<HIMAGELIST, HIMAGELIST, BOOL, BOOL> m_mapAlphaImageList; //}}AFX_CODEJOCK_PRIVATE }; #endif // !defined(__XTPSKINOBJECTTOOLBAR_H__)
31.164835
82
0.627292
[ "object" ]
a71948f820546445b4e87fe6d150a346b49c63f8
6,184
h
C
cdb/include/tencentcloud/cdb/v20170320/model/ParamRecord.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cdb/include/tencentcloud/cdb/v20170320/model/ParamRecord.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cdb/include/tencentcloud/cdb/v20170320/model/ParamRecord.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_CDB_V20170320_MODEL_PARAMRECORD_H_ #define TENCENTCLOUD_CDB_V20170320_MODEL_PARAMRECORD_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cdb { namespace V20170320 { namespace Model { /** * 参数修改记录 */ class ParamRecord : public AbstractModel { public: ParamRecord(); ~ParamRecord() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取实例ID * @return InstanceId 实例ID */ std::string GetInstanceId() const; /** * 设置实例ID * @param InstanceId 实例ID */ void SetInstanceId(const std::string& _instanceId); /** * 判断参数 InstanceId 是否已赋值 * @return InstanceId 是否已赋值 */ bool InstanceIdHasBeenSet() const; /** * 获取参数名称 * @return ParamName 参数名称 */ std::string GetParamName() const; /** * 设置参数名称 * @param ParamName 参数名称 */ void SetParamName(const std::string& _paramName); /** * 判断参数 ParamName 是否已赋值 * @return ParamName 是否已赋值 */ bool ParamNameHasBeenSet() const; /** * 获取参数修改前的值 * @return OldValue 参数修改前的值 */ std::string GetOldValue() const; /** * 设置参数修改前的值 * @param OldValue 参数修改前的值 */ void SetOldValue(const std::string& _oldValue); /** * 判断参数 OldValue 是否已赋值 * @return OldValue 是否已赋值 */ bool OldValueHasBeenSet() const; /** * 获取参数修改后的值 * @return NewValue 参数修改后的值 */ std::string GetNewValue() const; /** * 设置参数修改后的值 * @param NewValue 参数修改后的值 */ void SetNewValue(const std::string& _newValue); /** * 判断参数 NewValue 是否已赋值 * @return NewValue 是否已赋值 */ bool NewValueHasBeenSet() const; /** * 获取参数是否修改成功 * @return IsSucess 参数是否修改成功 */ bool GetIsSucess() const; /** * 设置参数是否修改成功 * @param IsSucess 参数是否修改成功 */ void SetIsSucess(const bool& _isSucess); /** * 判断参数 IsSucess 是否已赋值 * @return IsSucess 是否已赋值 */ bool IsSucessHasBeenSet() const; /** * 获取修改时间 * @return ModifyTime 修改时间 */ std::string GetModifyTime() const; /** * 设置修改时间 * @param ModifyTime 修改时间 */ void SetModifyTime(const std::string& _modifyTime); /** * 判断参数 ModifyTime 是否已赋值 * @return ModifyTime 是否已赋值 */ bool ModifyTimeHasBeenSet() const; private: /** * 实例ID */ std::string m_instanceId; bool m_instanceIdHasBeenSet; /** * 参数名称 */ std::string m_paramName; bool m_paramNameHasBeenSet; /** * 参数修改前的值 */ std::string m_oldValue; bool m_oldValueHasBeenSet; /** * 参数修改后的值 */ std::string m_newValue; bool m_newValueHasBeenSet; /** * 参数是否修改成功 */ bool m_isSucess; bool m_isSucessHasBeenSet; /** * 修改时间 */ std::string m_modifyTime; bool m_modifyTimeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CDB_V20170320_MODEL_PARAMRECORD_H_
30.613861
116
0.410091
[ "vector", "model" ]
a719b1e6fdb307b23079e2d4ab3e4432158f7915
1,137
c
C
src/graphtransformer.c
jkrishnavs/OpenMPGraphAlgorithms
313d655afc1f072ff085e447493f042aed4cce0e
[ "MIT" ]
null
null
null
src/graphtransformer.c
jkrishnavs/OpenMPGraphAlgorithms
313d655afc1f072ff085e447493f042aed4cce0e
[ "MIT" ]
null
null
null
src/graphtransformer.c
jkrishnavs/OpenMPGraphAlgorithms
313d655afc1f072ff085e447493f042aed4cce0e
[ "MIT" ]
null
null
null
/***** * Original base algorithm from GTGraph. ****/ #include<unistd.h> #include"graph.h" #include "mainFunctions.h" #include "print.h" #include "powerperformacetracking.h" typedef enum GraphModel { Random, ErdosRenyi, RMAT, SSCA } GraphModel; GraphModel model; boolean weighted; nodes_t numNodes; edges_t numEdges; /*** Random Parameters ***/ boolean selfloop; /***** Erdos Renyi *****/ double edgeProbability; /***** RMAT **********/ double a,b,c,d; /********** Graph prop value *******/ /** NOTE: These parameters has higher preference over numEdges and numNodes. if these values contradict with the numEdges and numNodes we update the numNodes and numEdges based on these values. **/ double degree; double density; double clusteringCoeff; double aed; /*****************/ /** Acceptable error as a percentage. the final graph properties will be in the range (prop*(1-err), prop*(1+err)). **/ double err; // TODO device a time out mechanism /*** Weight parameters ****/ int maxWeight; int minWeight; void setdefaultValues() { selfloop = false; } int runalgo(int argc, char** argv) { }
16.014085
73
0.667546
[ "model" ]
a71aa7dbe7b28b57868d41dc411615189cffc6b6
3,500
h
C
jni/mcpe/client/screen/AbstractScreen.h
SmartDEVTeam/ExNihiloPE
8a3636ff72456a6ae156f23ea79d871fa3721754
[ "Apache-2.0" ]
5
2017-03-02T18:58:02.000Z
2017-07-14T06:26:52.000Z
jni/mcpe/client/screen/AbstractScreen.h
Virtualoso/ExNihiloPE
8a3636ff72456a6ae156f23ea79d871fa3721754
[ "Apache-2.0" ]
3
2017-03-06T19:37:43.000Z
2017-06-09T17:48:39.000Z
jni/mcpe/client/screen/AbstractScreen.h
Virtualoso/ExNihiloPE
8a3636ff72456a6ae156f23ea79d871fa3721754
[ "Apache-2.0" ]
5
2017-03-05T03:50:19.000Z
2017-06-12T09:57:31.000Z
#pragma once #include <string> class BlockPos; class ScreenContext; class UIScreenContext; class InputMode; class HoloUIInputMode; class DirectionId; class VoiceCommand; class RenderGraphContext; class FocusImpact; class RawInputType; class ButtonState; class PointerLocationEventData; class AABB; class TextCharEventData; class Tessellator; class RectangleArea; namespace ui { class GameEventNotification; }; class AbstractScreen { public: virtual ~AbstractScreen(); virtual void _init(int, int) = 0; virtual void setSize(int, int) = 0; virtual void onSetKeyboardHeight(float) = 0; virtual void setAssociatedBlockPos(BlockPos const&) = 0; virtual void onInternetUpdate() = 0; virtual void onFocusGained() = 0; virtual void onFocusLost() = 0; virtual void terminate() = 0; virtual void onGameEventNotification(ui::GameEventNotification); virtual void _handleDirtyVisualTree(bool); virtual void leaveScreen(); virtual void tick(); virtual void tick(int, int) = 0; virtual void updateEvents() = 0; virtual void applyInput(float); virtual void preRenderUpdate(RenderGraphContext&); virtual void render(ScreenContext&) = 0; virtual void postRenderUpdate(RenderGraphContext&); virtual void setupAndRender(UIScreenContext&); virtual void handleInputModeChanged(InputMode) = 0; virtual void handleHoloInputModeChanged(HoloUIInputMode) = 0; virtual void handleButtonPress(short, FocusImpact) = 0; virtual void handleButtonRelease(short, FocusImpact) = 0; virtual void handleRawInputEvent(int, RawInputType, ButtonState, bool) = 0; virtual void handlePointerLocation(PointerLocationEventData const&, FocusImpact) = 0; virtual void handlePointerPressed(bool) = 0; virtual void handleDirection(DirectionId, float, float, FocusImpact) = 0; virtual void handleBackEvent(bool) = 0; virtual void handleTextChar(std::string const&, bool, FocusImpact) = 0; virtual void handleCaretLocation(int, FocusImpact) = 0; virtual void setTextboxText(std::string const&) = 0; virtual void handleLicenseChanged() = 0; virtual void handleIdentityGained() = 0; virtual void handleIdentityLost() = 0; virtual void handleGazeGestureInput(short, float, float, float, FocusImpact) = 0; virtual void handleDictationEvent(std::string const&); virtual void handleCommandEvent(VoiceCommand const&) = 0; virtual bool renderGameBehind() const = 0; virtual bool absorbsInput() const = 0; virtual bool closeOnPlayerHurt() const = 0; virtual bool isModal() const; virtual bool isShowingMenu() const; virtual bool shouldStealMouse() const; virtual bool screenIsNotFlushable() const; virtual bool screenDrawsLast() const; virtual void getFocusedControl(); virtual bool isWorldViewer() const; virtual bool isPauseScreen() const; virtual bool isPlayScreen() const; virtual bool renderOnlyWhenTopMost() const; virtual bool lowFreqRendering() const; virtual bool ignoreAsTop() const; virtual int getWidth() = 0; virtual int getHeight() = 0; virtual AABB* getRenderingAABB(); virtual int getNumberOfRenderPasses() const; virtual void getEyeRenderingMode() const; virtual std::string getScreenName() const = 0; virtual std::string getScreenNameW() const = 0; virtual void getSendEvents(); virtual void getEventProperties() const; virtual void processBufferedTextCharEvents(std::vector<TextCharEventData> const&); void drawRectangleArea(Tessellator&, RectangleArea const&, int, int, float, float); //the only function that isn't virtual, all alone :( static void* mEmptyRect; };
37.234043
86
0.782571
[ "render", "vector" ]
a72050c5b94f0dee6cbf80b913055a68876173f5
2,144
h
C
Classes/NKTLine.h
allending/Notekata
4fc32a2bd0b2da453c12bb1d0d60976b85496bb7
[ "MIT" ]
1
2015-09-30T13:35:03.000Z
2015-09-30T13:35:03.000Z
Classes/NKTLine.h
allending/Notekata
4fc32a2bd0b2da453c12bb1d0d60976b85496bb7
[ "MIT" ]
null
null
null
Classes/NKTLine.h
allending/Notekata
4fc32a2bd0b2da453c12bb1d0d60976b85496bb7
[ "MIT" ]
null
null
null
// // Copyright 2010 Allen Ding. All rights reserved. // #import "KobaUI.h" #import "KobaText.h" @class NKTTextPosition; @class NKTTextRange; @protocol NKTLineDelegate; // NKTLine represents a typesetted line that renders a range of text. @interface NKTLine : NSObject { @private id <NKTLineDelegate> delegate_; NSUInteger index_; NSAttributedString *text_; NKTTextRange *textRange_; CGPoint baselineOrigin_; CGFloat width_; CGFloat height_; CTLineRef line_; BOOL lastLine_; } #pragma mark Initializing - (id)initWithDelegate:(id <NKTLineDelegate>)delegate index:(NSUInteger)index text:(NSAttributedString *)text textRange:(NKTTextRange *)textRange baselineOrigin:(CGPoint)origin width:(CGFloat)width height:(CGFloat)height lastLine:(BOOL)lastLine; #pragma mark - #pragma mark Memory - (void)purgeCachedResources; #pragma mark Accessing the Index @property (nonatomic, readonly) NSUInteger index; #pragma mark Accessing the Text Range @property (nonatomic, readonly) NKTTextRange *textRange; #pragma mark Line Geometry @property (nonatomic, readonly) CGPoint baselineOrigin; - (CGRect)rectForTextRange:(NKTTextRange *)textRange; #pragma mark Getting Line Typographic Information @property (nonatomic, readonly) CGFloat ascent; @property (nonatomic, readonly) CGFloat descent; @property (nonatomic, readonly) CGFloat leading; #pragma mark Getting Character Positions - (CGFloat)offsetForCharAtTextPosition:(NKTTextPosition *)textPosition; - (CGPoint)baselineOriginForCharAtTextPosition:(NKTTextPosition *)textPosition; #pragma mark Hit-Testing // The point needs to be in the space of the line's parent. - (NKTTextPosition *)closestTextPositionForCaretToPoint:(CGPoint)point; - (BOOL)containsCaretAtTextPosition:(NKTTextPosition *)textPosition; #pragma mark Drawing - (void)drawInContext:(CGContextRef)context; @end #pragma mark - // NKTLineDelegate @protocol NKTLineDelegate #pragma mark Getting the Typesetter @property (nonatomic, readonly) CTTypesetterRef typesetter; @end
23.56044
79
0.745336
[ "geometry" ]
a721dbc8b00a5cb7cbf2b3ecfc23eefd50a29bb9
12,070
c
C
binding/hdfs/src/hdfs_lstore.c
onealbao/lstore
9a4d925deff5f474547bc015a45dec7f7fb0fb54
[ "Apache-2.0" ]
1
2016-09-06T13:36:37.000Z
2016-09-06T13:36:37.000Z
binding/hdfs/src/hdfs_lstore.c
onealbao/lstore
9a4d925deff5f474547bc015a45dec7f7fb0fb54
[ "Apache-2.0" ]
null
null
null
binding/hdfs/src/hdfs_lstore.c
onealbao/lstore
9a4d925deff5f474547bc015a45dec7f7fb0fb54
[ "Apache-2.0" ]
1
2016-09-06T13:50:48.000Z
2016-09-06T13:50:48.000Z
/* Copyright 2016 Vanderbilt University 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. */ //*********************************************************************** // hdfs_lstore - HDFS module supporting the use of LStore files //*********************************************************************** #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <gop/gop.h> #include <lio/lio.h> #include <tbx/constructor_wrapper.h> #include <tbx/fmttypes.h> #include <tbx/type_malloc.h> #include "visibility.h" #include "hdfs_lstore.h" struct hdfs_lstore_s { lio_config_t *lc; }; struct hdfsl_fd_s { lio_fd_t *fd; hdfs_lstore_t *ctx; lio_path_tuple_t tuple; }; struct hdfsl_fstat_iter_s { hdfs_lstore_t *ctx; char *val[6]; int v_size[6]; os_object_iter_t *it; lio_os_regex_table_t *rp; lio_path_tuple_t tuple; }; //*********************************************************************** // lstore_activate - Start LIO subsystem when loading the shared library //*********************************************************************** hdfs_lstore_t *lstore_activate(int *argc, char ***argv) { hdfs_lstore_t *ctx; lio_init(argc, argv); if (!lio_gc) { log_printf(-1,"Failed to load LStore\n"); exit(1); } tbx_type_malloc_clear(ctx, hdfs_lstore_t, 1); ctx->lc = lio_gc; tbx_log_flush(); return(ctx); } //*********************************************************************** // lstore_deactivate - Shutdown LStore //*********************************************************************** void lstore_deactivate(hdfs_lstore_t *ctx) { tbx_log_flush(); lio_shutdown(); free(ctx); } //*********************************************************************** // lstore_delete - Remove a file and optionally recurse the path //*********************************************************************** int lstore_delete(hdfs_lstore_t *ctx, char *path, int recurse_depth) { int obj_types = OS_OBJECT_FILE_FLAG|OS_OBJECT_DIR_FLAG|OS_OBJECT_SYMLINK_FLAG; int err; lio_path_tuple_t tuple; lio_os_regex_table_t *rpath; if ((strcmp(path, "/") == 0) || (strcmp(path, "/*") == 0)) { fprintf(stderr, "Recursive delete from / not supported!\n"); return(1); } tuple = lio_path_resolve(ctx->lc->auto_translate, path); rpath = lio_os_path_glob2regex(tuple.path); err = gop_sync_exec(lio_remove_regex_gop(ctx->lc, tuple.creds, rpath, NULL, obj_types, recurse_depth, 100)); lio_path_release(&tuple); lio_os_regex_table_destroy(rpath); return(err == OP_STATE_SUCCESS ? 0 : 1); } //*********************************************************************** // lstore_fstat_parse - Parse the returned attibutes and stores them in // the HDFS fstat struct //*********************************************************************** int lstore_fstat_parse(hdfsl_fstat_t *fstat, char **val, int *v_size) { int ts; ex_off_t len; if (v_size[0] > 0) { fstat->user = val[0]; val[0] = NULL; } if (v_size[1] > 0) { fstat->group = val[1]; val[1] = NULL; } len = 0; if (v_size[2] > 0) { sscanf(val[2], XOT, &len); } fstat->len = len; ts = 0; if (v_size[3] > 0) lio_get_timestamp(val[3], &ts, NULL); fstat->modify_time_ms = ts * 1000; if (v_size[4] > 0) { fstat->symlink = val[4]; val[4] = NULL; } fstat->objtype = 0; if (v_size[5] > 0) sscanf(val[5], "%d", &fstat->objtype); return(0); } //*********************************************************************** // lstore_fstat - File stat for HDFS //*********************************************************************** int lstore_fstat(hdfs_lstore_t *ctx, char *path, hdfsl_fstat_t *fstat) { char *keys[] = { "system.owner", "system.group", "system.exnode.size", "system.modify_data", "os.link", "os.type" }; char *vals[6]; int v_size[6]; lio_path_tuple_t tuple; int i, err; memset(fstat, 0, sizeof(hdfsl_fstat_t)); fstat->path = path; tuple = lio_path_resolve(ctx->lc->auto_translate, path); for (i=0; i<6; i++) v_size[i] = -ctx->lc->max_attr; err = lio_get_multiple_attrs(tuple.lc, tuple.creds, tuple.path, NULL, keys, (void **)vals, v_size, 6); lio_path_release(&tuple); if (err != OP_STATE_SUCCESS) { return(1); } err = lstore_fstat_parse(fstat, vals, v_size); for (i=0; i<6; i++) if (vals[i]) free(vals[i]); return(err); } //*********************************************************************** // lstore_fstat_iter - Returns an fstat iterator //*********************************************************************** hdfsl_fstat_iter_t *lstore_fstat_iter(hdfs_lstore_t *ctx, char *path, int recurse_depth) { hdfsl_fstat_iter_t *it; char fpath[4096]; char *keys[] = { "system.owner", "system.group", "system.exnode.size", "system.modify_data", "os.link", "os.type" }; int i; int obj_types = OS_OBJECT_FILE_FLAG|OS_OBJECT_DIR_FLAG|OS_OBJECT_SYMLINK_FLAG; tbx_type_malloc_clear(it, hdfsl_fstat_iter_t, 1); snprintf(fpath, sizeof(fpath), "%s/*", path); it->tuple = lio_path_resolve(ctx->lc->auto_translate, fpath); it->rp = lio_os_path_glob2regex(it->tuple.path); it->ctx = ctx; for (i=0; i<6; i++) it->v_size[i] = -ctx->lc->max_attr; it->it = lio_create_object_iter_alist(it->tuple.lc, it->tuple.creds, it->rp, NULL, obj_types, recurse_depth, keys, (void **)it->val, it->v_size, 6); return(it); } //*********************************************************************** // lstore_fstat_iter_next - Returns the next iterator object //*********************************************************************** int lstore_fstat_iter_next(hdfsl_fstat_iter_t *it, hdfsl_fstat_t *fstat) { int ftype, prefix_len, err, i; memset(fstat, 0, sizeof(hdfsl_fstat_t)); err = 0; ftype = lio_next_object(it->tuple.lc, it->it, &fstat->path, &prefix_len); if (ftype == 0) return(-1); err = lstore_fstat_parse(fstat, it->val, it->v_size); for (i=0; i<6; i++) it->v_size[i] = -it->ctx->lc->max_attr; for (i=0; i<6; i++) if (it->val[i]) free(it->val[i]); return(err); } //*********************************************************************** // lstore_fstat_iter - Destroys an fstat iterator //*********************************************************************** void lstore_fstat_iter_destroy(hdfsl_fstat_iter_t *it) { lio_destroy_object_iter(it->ctx->lc, it->it); lio_os_regex_table_destroy(it->rp); lio_path_release(&it->tuple); free(it); } //*********************************************************************** // lstore_mkdir - Make a directory //*********************************************************************** int lstore_mkdir(hdfs_lstore_t *ctx, char *path) { int ftype, err; char *dpath, *fpath; lio_path_tuple_t tuple; tuple = lio_path_resolve(ctx->lc->auto_translate, path); //** Make sure it doesn't exist ftype = lio_exists(tuple.lc, tuple.creds, tuple.path); if (ftype > 0) { //** The file exists err = 1; } else if (ftype < 0) { err = 2; } else { //** Now create the object err = gop_sync_exec(lio_create_gop(tuple.lc, tuple.creds, tuple.path, OS_OBJECT_DIR_FLAG, NULL, NULL)); if (err != OP_STATE_SUCCESS) { //** Failed so try and recurse back up/down to make the intermediate dirs lio_os_path_split(tuple.path, &dpath, &fpath); err = lstore_mkdir(ctx, dpath); if (dpath) free(dpath); if (fpath) free(fpath); if (err == 0) { //** Successfully made the parent directory err = gop_sync_exec(lio_create_gop(tuple.lc, tuple.creds, tuple.path, OS_OBJECT_DIR_FLAG, NULL, NULL)); err = (err == OP_STATE_SUCCESS) ? 0 : 1; } } else { err = 0; } } lio_path_release(&tuple); return(err); } //*********************************************************************** // lstore_rename - Rename an object //*********************************************************************** int lstore_rename(hdfs_lstore_t *ctx, char *src_path, char *dest_path) { int err; lio_path_tuple_t stuple, dtuple; stuple = lio_path_resolve(ctx->lc->auto_translate, src_path); dtuple = lio_path_resolve(ctx->lc->auto_translate, dest_path); err = gop_sync_exec(lio_move_object_gop(stuple.lc, stuple.creds, stuple.path, dtuple.path)); lio_path_release(&stuple); lio_path_release(&dtuple); return(err == OP_STATE_SUCCESS ? 0 : 1); } //*********************************************************************** // lstore_open - Opens an existing object //*********************************************************************** hdfsl_fd_t *lstore_open(hdfs_lstore_t *ctx, char *path, int mode) { hdfsl_fd_t *fd; int lmode; tbx_type_malloc_clear(fd, hdfsl_fd_t, 1); fd->ctx = ctx; fd->tuple = lio_path_resolve(lio_gc->auto_translate, path); switch(mode) { case HDFSL_OPEN_READ: lmode = LIO_READ_MODE; break; case HDFSL_OPEN_WRITE: lmode = LIO_WRITE_MODE | LIO_TRUNCATE_MODE | LIO_CREATE_MODE; break; case HDFSL_OPEN_APPEND: lmode = LIO_WRITE_MODE | LIO_CREATE_MODE; break; default: lio_path_release(&fd->tuple); free(fd); return(NULL); } gop_sync_exec(lio_open_gop(ctx->lc, ctx->lc->creds, fd->tuple.path, lmode, NULL, &fd->fd, 60)); if (fd->fd == NULL) { lio_path_release(&fd->tuple); free(fd); return(NULL); } if (mode == HDFSL_OPEN_APPEND) { lio_seek(fd->fd, 0, SEEK_END); } else { lio_seek(fd->fd, 0, SEEK_SET); } return(fd); } //*********************************************************************** // lstore_close - Close the target //*********************************************************************** void lstore_close(hdfsl_fd_t *fd) { gop_sync_exec(lio_close_gop(fd->fd)); lio_path_release(&fd->tuple); free(fd); } //*********************************************************************** // lstore_read - Read data from the target //*********************************************************************** int lstore_read(hdfsl_fd_t *fd, char *buf, int64_t length) { int err; err = lio_read(fd->fd, buf, length, -1, NULL); return((err == length) ? 0 : 1); } //*********************************************************************** // lstore_write - Read data from the target //*********************************************************************** int lstore_write(hdfsl_fd_t *fd, char *buf, int64_t length) { int err; err = lio_write(fd->fd, buf, length, -1, NULL); return((err == length) ? 0 : 1); } //*********************************************************************** // lstore_seek - Set the current file position //*********************************************************************** void lstore_seek(hdfsl_fd_t *fd, int64_t off) { lio_seek(fd->fd, off, SEEK_SET); return; } //*********************************************************************** // lstore_getpos - Get the current position //*********************************************************************** int64_t lstore_getpos(hdfsl_fd_t *fd) { return(lio_tell(fd->fd)); }
30.175
152
0.509528
[ "object" ]
a72af67cf9cd79e478ea46a8b47bb1228e13ac3f
1,071
h
C
PointCloudRegistration/features.h
P-Chao/SAC-IA
780ea3001be8c9fed8d12cf0ef2e744619bb0b2a
[ "BSD-3-Clause" ]
40
2017-08-11T03:05:58.000Z
2022-03-20T13:59:13.000Z
PointCloudRegistration/features.h
P-Chao/SAC-IA
780ea3001be8c9fed8d12cf0ef2e744619bb0b2a
[ "BSD-3-Clause" ]
null
null
null
PointCloudRegistration/features.h
P-Chao/SAC-IA
780ea3001be8c9fed8d12cf0ef2e744619bb0b2a
[ "BSD-3-Clause" ]
19
2017-08-17T02:32:54.000Z
2021-05-24T02:02:18.000Z
#pragma once #include <iostream> #include <time.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/registration/icp.h> #include <pcl/registration/ia_ransac.h> #include <pcl/point_types.h> #include <pcl/features/normal_3d.h> #include <pcl/point_types.h> #include <pcl/features/pfh.h> #include <pcl/filters/passthrough.h> #include <pcl/visualization/cloud_viewer.h> #include <limits> #include <fstream> #include <vector> #include <Eigen/Core> #include "pcl/point_cloud.h" #include "pcl/kdtree/kdtree_flann.h" #include "pcl/filters/passthrough.h" #include "pcl/filters/voxel_grid.h" #include "pcl/features/fpfh.h" pcl::PointCloud<pcl::FPFHSignature33>::Ptr getFeatures(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, pcl::PointCloud<pcl::Normal>::Ptr normals, double feature_radius = 50.0); pcl::PointCloud<pcl::Normal>::Ptr getNormals(pcl::PointCloud<pcl::PointXYZ>::Ptr incloud, double normals_radius = 20.0); pcl::PointCloud<pcl::PointNormal>::Ptr getPointNormals(pcl::PointCloud<pcl::PointXYZ>::Ptr incloud, int k = 30);
39.666667
172
0.738562
[ "vector" ]
a72c56302b71b305ac18fa79031d0aefbdf6cab1
7,965
h
C
include/wlr/render/egl.h
raj47i/wlroots-eglstreams
c7c414985a91bbd43c00e8874d041501f580e653
[ "MIT" ]
1
2021-12-12T20:57:12.000Z
2021-12-12T20:57:12.000Z
include/wlr/render/egl.h
raj47i/wlroots-eglstreams
c7c414985a91bbd43c00e8874d041501f580e653
[ "MIT" ]
null
null
null
include/wlr/render/egl.h
raj47i/wlroots-eglstreams
c7c414985a91bbd43c00e8874d041501f580e653
[ "MIT" ]
1
2021-12-12T20:58:59.000Z
2021-12-12T20:58:59.000Z
/* * This an unstable interface of wlroots. No guarantees are made regarding the * future consistency of this API. */ #ifndef WLR_USE_UNSTABLE #error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" #endif #ifndef WLR_RENDER_EGL_H #define WLR_RENDER_EGL_H #ifndef MESA_EGL_NO_X11_HEADERS #define MESA_EGL_NO_X11_HEADERS #endif #ifndef EGL_NO_X11 #define EGL_NO_X11 #endif #ifndef EGL_NO_PLATFORM_SPECIFIC_TYPES #define EGL_NO_PLATFORM_SPECIFIC_TYPES #endif #include <wlr/config.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include <pixman.h> #include <stdbool.h> #include <wayland-server-core.h> #include <wlr/render/dmabuf.h> #include <wlr/render/drm_format_set.h> #ifndef EGL_NV_stream_attrib #define EGL_NV_stream_attrib 1 typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMATTRIBNVPROC)(EGLDisplay dpy, const EGLAttrib *attrib_list); typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMATTRIBNVPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value); typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMATTRIBNVPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value); typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC)(EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEATTRIBNVPROC)(EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMATTRIBNV)(EGLDisplay, EGLStreamKHR, EGLenum, EGLAttrib *); typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHR)(EGLDisplay, EGLStreamKHR); #endif /* EGL_NV_stream_attrib */ #ifndef EGL_EXT_stream_acquire_mode #define EGL_EXT_stream_acquire_mode 1 #define EGL_CONSUMER_AUTO_ACQUIRE_EXT 0x332B typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBEXTPROC)(EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); #endif /* EGL_EXT_stream_acquire_mode */ #ifndef EGL_NV_output_drm_flip_event #define EGL_NV_output_drm_flip_event 1 #define EGL_DRM_FLIP_EVENT_DATA_NV 0x333E #endif /* EGL_NV_output_drm_flip_event */ #ifndef EGL_DRM_MASTER_FD_EXT #define EGL_DRM_MASTER_FD_EXT 0x333C #endif /* EGL_DRM_MASTER_FD_EXT */ #ifndef EGL_WL_wayland_eglstream #define EGL_WL_wayland_eglstream 1 #define EGL_WAYLAND_EGLSTREAM_WL 0x334B #endif /* EGL_WL_wayland_eglstream */ #ifndef EGL_RESOURCE_BUSY_EXT #define EGL_RESOURCE_BUSY_EXT 0x3353 #endif /* EGL_RESOURCE_BUSY_EXT */ struct wlr_egl_context { EGLDisplay display; EGLContext context; EGLSurface draw_surface; EGLSurface read_surface; }; struct wlr_eglstream { struct wlr_drm_backend *drm; struct wlr_egl *egl; EGLStreamKHR stream; EGLSurface surface; bool busy; // true for e.g. modeset in progress }; struct wlr_egl { EGLDisplay display; EGLContext context; EGLDeviceEXT device; // may be EGL_NO_DEVICE_EXT struct gbm_device *gbm_device; EGLConfig egl_config; // For setting up EGLStreams context struct wlr_eglstream *current_eglstream; // Non-null for EGLStream frame struct { // Display extensions bool bind_wayland_display_wl; bool image_base_khr; bool image_dmabuf_import_ext; bool image_dmabuf_import_modifiers_ext; // Device extensions bool device_drm_ext; } exts; struct { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR; PFNEGLQUERYWAYLANDBUFFERWL eglQueryWaylandBufferWL; PFNEGLBINDWAYLANDDISPLAYWL eglBindWaylandDisplayWL; PFNEGLUNBINDWAYLANDDISPLAYWL eglUnbindWaylandDisplayWL; PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; PFNEGLQUERYDMABUFMODIFIERSEXTPROC eglQueryDmaBufModifiersEXT; PFNEGLDEBUGMESSAGECONTROLKHRPROC eglDebugMessageControlKHR; PFNEGLQUERYDISPLAYATTRIBEXTPROC eglQueryDisplayAttribEXT; PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; // EGLStreams PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; PFNEGLGETOUTPUTLAYERSEXTPROC eglGetOutputLayersEXT; PFNEGLCREATESTREAMKHRPROC eglCreateStreamKHR; PFNEGLDESTROYSTREAMKHRPROC eglDestroyStreamKHR; PFNEGLSTREAMCONSUMEROUTPUTEXTPROC eglStreamConsumerOutputEXT; PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC eglCreateStreamProducerSurfaceKHR; PFNEGLSTREAMCONSUMERACQUIREATTRIBNVPROC eglStreamConsumerAcquireAttribNV; PFNEGLQUERYSTREAMATTRIBNV eglQueryStreamAttribNV; PFNEGLSTREAMCONSUMERRELEASEKHR eglStreamConsumerReleaseKHR; PFNEGLQUERYSTREAMKHRPROC eglQueryStreamKHR; PFNEGLCREATESTREAMATTRIBNVPROC eglCreateStreamAttribNV; PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC eglStreamConsumerGLTextureExternalKHR; PFNEGLSTREAMFLUSHNVPROC eglStreamFlushNV; } procs; struct wl_display *wl_display; struct wlr_drm_format_set dmabuf_texture_formats; struct wlr_drm_format_set dmabuf_render_formats; }; /** * Initializes an EGL context for the given platform and remote display. * Will attempt to load all possibly required api functions. */ struct wlr_egl *wlr_egl_create(EGLenum platform, void *remote_display); /** * Frees all related EGL resources, makes the context not-current and * unbinds a bound wayland display. */ void wlr_egl_destroy(struct wlr_egl *egl); /** * Binds the given display to the EGL instance. * This will allow clients to create EGL surfaces from wayland ones and render * to it. */ bool wlr_egl_bind_display(struct wlr_egl *egl, struct wl_display *local_display); /** * Creates an EGL image from the given wl_drm buffer resource. */ EGLImageKHR wlr_egl_create_image_from_wl_drm(struct wlr_egl *egl, struct wl_resource *data, EGLint *fmt, int *width, int *height, bool *inverted_y); /** * Creates an EGL image from the given dmabuf attributes. Check usability * of the dmabuf with wlr_egl_check_import_dmabuf once first. */ EGLImageKHR wlr_egl_create_image_from_dmabuf(struct wlr_egl *egl, struct wlr_dmabuf_attributes *attributes, bool *external_only); /** * Get DMA-BUF formats suitable for sampling usage. */ const struct wlr_drm_format_set *wlr_egl_get_dmabuf_texture_formats( struct wlr_egl *egl); /** * Get DMA-BUF formats suitable for rendering usage. */ const struct wlr_drm_format_set *wlr_egl_get_dmabuf_render_formats( struct wlr_egl *egl); bool wlr_egl_export_image_to_dmabuf(struct wlr_egl *egl, EGLImageKHR image, int32_t width, int32_t height, uint32_t flags, struct wlr_dmabuf_attributes *attribs); /** * Destroys an EGL image created with the given wlr_egl. */ bool wlr_egl_destroy_image(struct wlr_egl *egl, EGLImageKHR image); /** * Make the EGL context current. * * Callers are expected to clear the current context when they are done by * calling wlr_egl_unset_current. */ bool wlr_egl_make_current(struct wlr_egl *egl); bool wlr_egl_unset_current(struct wlr_egl *egl); bool wlr_egl_is_current(struct wlr_egl *egl); /** * Save the current EGL context to the structure provided in the argument. * * This includes display, context, draw surface and read surface. */ void wlr_egl_save_context(struct wlr_egl_context *context); /** * Restore EGL context that was previously saved using wlr_egl_save_current(). */ bool wlr_egl_restore_context(struct wlr_egl_context *context); int wlr_egl_dup_drm_fd(struct wlr_egl *egl); /** * Sets up EGLSurface for passed egl_stream * Expects egl_stream->drm and egl_stream->egl to be valid */ bool wlr_egl_create_eglstreams_surface(struct wlr_eglstream *egl_stream, uint32_t plane_id, int width, int height); /** * Destroys egl_stream and frees resources used */ void wlr_egl_destroy_eglstreams_surface(struct wlr_eglstream *egl_stream); /** * Flips EGLStream for presentation. Updated buffers ages. * Expects EGLStream surface to be current */ struct wlr_output; bool wlr_egl_flip_eglstreams_page(struct wlr_output *output); /** * Load and initialized nvidia eglstream controller. * for mapping client EGL surfaces. */ void init_eglstream_controller(struct wl_display *display); #endif
33.1875
142
0.821971
[ "render" ]
a73b76402c3f128774d2dba24a40b76955a569cb
3,762
h
C
ace/tao/tao_idl/be_include/be_visitor_amh_pre_proc.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tao_idl/be_include/be_visitor_amh_pre_proc.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tao_idl/be_include/be_visitor_amh_pre_proc.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
//============================================================================= /** * @file be_visitor_amh_pre_proc.h * * be_visitor_amh_pre_proc.h,v 1.1 2001/05/17 10:49:55 brunsch Exp * * This visitor creates for AMH implied IDL constructs the appropriate AST * (Abstract Syntax Tree) node, sets the corresponding interface or operation * strategy on it and enteres the nodes into the AST. * * @author Darrell Brunsch <brunsch@cs.wustl.edu> */ //============================================================================= #ifndef TAO_BE_VISITOR_AMH_PRE_PROC_H #define TAO_BE_VISITOR_AMH_PRE_PROC_H #include "idl.h" #include "idl_extern.h" #include "be.h" #include "be_root.h" #include "be_module.h" #include "be_interface.h" #include "be_visitor_scope.h" /** * @class be_visitor_amh_pre_proc * * @brief Adds AMH implied IDL code into the AST */ class be_visitor_amh_pre_proc : public be_visitor_scope { private: typedef AST_Interface *AST_Interface_ptr; typedef enum { NORMAL, GET_OPERATION, SET_OPERATION } Operation_Kind; public: be_visitor_amh_pre_proc (be_visitor_context *ctx); virtual ~be_visitor_amh_pre_proc (void); virtual int visit_root (be_root *node); virtual int visit_module (be_module *node); virtual int visit_interface (be_interface *node); virtual int visit_operation (be_operation *node); virtual int visit_attribute (be_attribute *node); private: /// Creates a raise operation from node and inserts it in /// excep_holder, while obeying if it is a normal operation /// or a set or get attribute. int create_raise_operation (be_decl *node, be_valuetype *excep_holder, Operation_Kind operation_kind); /// Creates the AMH version of the interface be_interface *create_amh_class (be_interface *node); /// Create a method in the AMH tree int create_amh_operation (be_operation *node, be_interface *amh_class); /// Create the reponse handler interface be_interface *create_response_handler (be_interface *node, be_valuetype *excep_holder); /// Create the exception holder valuetype be_valuetype *create_exception_holder (be_interface *node); /// Create a method with "sendc_" prepended, if for_arguments /// equals one the sendc operation contains also the /// object reference to the response handler as the first argument, /// but this should not be marhaled, therefore we need the switch // be_operation *create_sendc_operation (be_operation *node, // int for_arguments); /// Create a method with "_excep" appended // int create_excep_operation (be_operation *node, // be_interface *response_handler, // be_valuetype *excep_holder); /// Create an operation with only the OUT and INOUT arguments // int create_response_handler_operation (be_operation *node, // be_interface *response_handler); /// Specialized visit_scope int visit_scope (be_scope *node); /// Concatenate 3 strings into one. int generate_name (ACE_CString &destination, const char *prefix, const char *middle_name, const char *suffix); /// Generate a get operation out of the attribute. be_operation *generate_get_operation (be_attribute *node); /// Generate a set operation out of the attribute. be_operation *generate_set_operation (be_attribute *node); }; #endif // TAO_BE_VISITOR_AMH_PRE_PROC_H
32.713043
80
0.635832
[ "object" ]
56521ca4a40ba1a94c8ad6a5af54249d334da2ba
3,667
h
C
Corby/src/Engine/Renderer/Buffer.h
nepp95/Corby
8fb46b0479431be6f74263db0ffa8446c8baa9c5
[ "Apache-2.0" ]
null
null
null
Corby/src/Engine/Renderer/Buffer.h
nepp95/Corby
8fb46b0479431be6f74263db0ffa8446c8baa9c5
[ "Apache-2.0" ]
2
2021-11-14T19:36:25.000Z
2021-12-17T16:01:23.000Z
Corby/src/Engine/Renderer/Buffer.h
nepp95/Corby
8fb46b0479431be6f74263db0ffa8446c8baa9c5
[ "Apache-2.0" ]
null
null
null
#pragma once namespace Engine { // ----------------------------------------- // // ShaderDataType // ShaderDataTypeSize // // ----------------------------------------- enum class ShaderDataType { None = 0, Float, Float2, Float3, Float4, Mat3, Mat4, Int, Int2, Int3, Int4, Bool }; static unsigned int ShaderDataTypeSize(ShaderDataType type) { switch (type) { case ShaderDataType::Float: return 4; case ShaderDataType::Float2: return 4 * 2; case ShaderDataType::Float3: return 4 * 3; case ShaderDataType::Float4: return 4 * 4; case ShaderDataType::Mat3: return 4 * 3 * 3; case ShaderDataType::Mat4: return 4 * 4 * 4; case ShaderDataType::Int: return 4; case ShaderDataType::Int2: return 4 * 2; case ShaderDataType::Int3: return 4 * 3; case ShaderDataType::Int4: return 4 * 4; case ShaderDataType::Bool: return 1; } ENG_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; } // ----------------------------------------- // // BufferElement // BufferLayout // // ----------------------------------------- struct BufferElement { ShaderDataType Type; std::string Name; uint32_t Size; size_t Offset; bool Normalized; BufferElement() {} BufferElement(ShaderDataType type, const std::string& name, bool normalized = false) : Name(name), Type(type), Size(ShaderDataTypeSize(type)), Offset(0), Normalized(normalized) {} unsigned int GetComponentCount() const { switch (Type) { case ShaderDataType::Float: return 1; case ShaderDataType::Float2: return 2; case ShaderDataType::Float3: return 3; case ShaderDataType::Float4: return 4; case ShaderDataType::Mat3: return 3; case ShaderDataType::Mat4: return 4; case ShaderDataType::Int: return 1; case ShaderDataType::Int2: return 2; case ShaderDataType::Int3: return 3; case ShaderDataType::Int4: return 4; case ShaderDataType::Bool: return 1; } ENG_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; } }; class BufferLayout { public: BufferLayout() {} BufferLayout(std::initializer_list<BufferElement> elements); unsigned int GetStride() const { return m_stride; } const std::vector<BufferElement>& GetElements() const { return m_elements; } std::vector<BufferElement>::iterator begin() { return m_elements.begin(); } std::vector<BufferElement>::iterator end() { return m_elements.end(); } std::vector<BufferElement>::const_iterator begin() const { return m_elements.begin(); } std::vector<BufferElement>::const_iterator end() const { return m_elements.end(); } private: void CalculateOffsetsAndStride(); private: std::vector<BufferElement> m_elements; unsigned int m_stride; }; // ----------------------------------------- // // VertexBuffer // // ----------------------------------------- class VertexBuffer { public: virtual ~VertexBuffer() {} virtual void Bind() const = 0; virtual void Unbind() const = 0; virtual void SetData(const void* data, uint32_t size) = 0; virtual const BufferLayout& GetLayout() const = 0; virtual void SetLayout(const BufferLayout& layout) = 0; static Ref<VertexBuffer> Create(uint32_t size); static Ref<VertexBuffer> Create(float* vertices, unsigned int size); }; // ----------------------------------------- // // IndexBuffer // // ----------------------------------------- class IndexBuffer { public: virtual ~IndexBuffer() {} virtual void Bind() const = 0; virtual void Unbind() const = 0; virtual unsigned int GetCount() const = 0; static Ref<IndexBuffer> Create(unsigned int* indices, unsigned int count); }; }
26.572464
181
0.62258
[ "vector" ]
565d5af697c5f5efd6fca13f85399a49887b327d
9,983
c
C
DB21M/install/hardware/software/i2c/i2c_machine.c
kjoelovelife/Duckietown_manually
41cea52d3d2c31f70a731ce0d7ac56b5d2eb457a
[ "MIT" ]
null
null
null
DB21M/install/hardware/software/i2c/i2c_machine.c
kjoelovelife/Duckietown_manually
41cea52d3d2c31f70a731ce0d7ac56b5d2eb457a
[ "MIT" ]
null
null
null
DB21M/install/hardware/software/i2c/i2c_machine.c
kjoelovelife/Duckietown_manually
41cea52d3d2c31f70a731ce0d7ac56b5d2eb457a
[ "MIT" ]
null
null
null
/* * Copyright Brian Starkey 2014 <stark3y@gmail.com> * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ //#define DEBUG #include <avr/io.h> #include <avr/interrupt.h> #include <stdint.h> #include "i2c_slave_defs.h" #include "i2c_machine.h" #define I2C_SDA_DIR_OUT 1 #define I2C_SDA_DIR_IN 0 #define NAK() USIDR = 0x80 #define ACK() USIDR = 0x00 #define I2C_STATE_ADDR_MATCH 0 #define I2C_STATE_REG_ADDR 1 #define I2C_STATE_MASTER_READ 2 #define I2C_STATE_MASTER_WRITE 3 #define I2C_STATE_IDLE 4 uint8_t volatile i2c_reg[I2C_N_SLAVES][I2C_N_REG]; volatile uint8_t I2C_SLAVE_ADDR[I2C_N_SLAVES]={0x40,0x60}; // #ifdef DEBUG // #define LED_ON() PORTB |= 0x2 // #define LED_OFF() PORTB &= ~0x2 // #define LED_FLICKER() LED_OFF(); LED_ON() // #else // #define LED_ON() // #define LED_OFF() // #define LED_FLICKER() // #endif volatile uint8_t i2c_update[I2C_N_SLAVES] = {0}; //byte count written in the last i2c write command volatile uint8_t i2c_current_Slave=0; //current slave index, which is communicating at the moment, 0xFF means no slave! //these variables are just there once and are used all emulated slaves. //because there is just one state machine and the i2c master can just //talk to one slave at a time. volatile uint8_t i2c_state = 0; //state of the i2c state machine, see below volatile uint8_t i2c_offset = 0; //read or write array index of the current operation //this function translates an I2C register index to an array index (e.g. to save memory because there could be gaps in the i2c address registers) //PCA9685 has registers 0-69dez and 250-255dez. To Save memory, the registers 250-255dez are mapped to 70-75! This is achieved with this function. uint16_t I2CAddressToArrayIndex(uint8_t I2CAddress) //Error= 0xFFFF { if (I2CAddress <= 0x45)//i2c 0-69dez --> Index 0-69dez { return I2CAddress; } else if (I2CAddress >= 0xFA && I2CAddress <= 0XFF)// i2c 250-255dez --> Index 70-25dez { return I2CAddress - 0xFA+0x46;// the address 0xFA (250dez) should give 0x46 (70dez) } else { return 0xFFFF;//Error } } /* USI i2c Slave State Machine * =========================== * * 5 States: * 0 I2C_STATE_ADDR_MATCH * Waiting for address (start) * * 1 I2C_STATE_REG_ADDR * Receive register address* * * 2 I2C_STATE_MASTER_READ * Transmit data to master * * 3 I2C_STATE_MASTER_WRITE * Receive data from master * * 4 I2C_STATE_IDLE * Bus idle/address not matched * * Valid state transitions: * __To__________ * 0 1 2 3 4 * F 0| a b h * r 1| d ci * o 2| f e * m 3| g c * 4| j * * Transition j - Start of transaction * I2C_STATE_IDLE -> I2C_STATE_ADDR_MATCH * Cond: Start condition interrupt * Action: None. * * Transition h - Address not matched. * I2C_STATE_ADDR_MATCH -> I2C_STATE_IDLE * Cond: Pre-ack. Address doesn't match * Action: NAK. * * Transition a - Address matched, write mode * I2C_STATE_ADDR_MATCH -> I2C_STATE_REG_ADDR * Cond: Pre-ack. Address matches, bit0 == 0 * Action: ACK, Reset reg pointer. * * Transition b - Address matched, read mode * I2C_STATE_ADDR_MATCH -> I2C_STATE_MASTER_READ * Cond: Pre-ack. Address matches, bit0 == 1 * Action: ACK. * * Transition c - Write finished * I2C_STATE_XXX -> I2C_STATE_IDLE * Cond: Stop flag is set. * Action: None. * * Transition d - Initialise write * I2C_STATE_REG_ADDR -> I2C_STATE_MASTER_WRITE * Cond: Pre-ack. * Action: ACK, reg_ptr = USIDR. * * Transition i - Invalid reg addr * I2C_STATE_REG_ADDR -> I2C_STATE_IDLE * Cond: Pre-ack, USIDR > N_REG - 1 * Action: NAK. * * Transition e - Read finished * I2C_STATE_MASTER_READ -> I2C_STATE_IDLE * Cond: Post-ack. Master NAK'd. * Action: None. * * Transition f - Read continues * I2C_STATE_MASTER_READ -> I2C_STATE_MASTER_READ * Cond: Post-ack. Master ACK'd. * Action: USIDR = *reg_ptr++ * * Transition g - Write continues * I2C_STATE_MASTER_WRITE -> I2C_STATE_MASTER_WRITE * Cond: Pre-ack. * Action: ACK, *reg_ptr++ = USIDR * */ /* * For some reason, avr-libc uses different vector names for the USI * on different chips! We have to workaround that here */ //I2C Start Interrupt #if defined(USI_START_vect) ISR(USI_START_vect) #elif defined(USI_STRT_vect) ISR(USI_STRT_vect) #else #error "Couldn't figure out what i2c start interrupt to use!" #endif { i2c_state = 0; while (USI_PIN & (1 << I2C_SCL)); USISR = 0xF0; } //I2C Overflow Interrupt #if defined(USI_OVERFLOW_vect) ISR(USI_OVERFLOW_vect) #elif defined(USI_OVF_vect) ISR(USI_OVF_vect) #else #error "Couldn't figure out what i2c overflow interrupt to use!" #endif { static uint8_t post_ack = 0; /* Writing USISR directly has side effects! */ uint8_t usisr_tmp = 0xD0; uint8_t sda_direction; uint8_t tmp; if (!post_ack) { /* Work that needs to be done before the ACK cycle */ sda_direction = I2C_SDA_DIR_OUT; switch (i2c_state) { case I2C_STATE_ADDR_MATCH: tmp = USIDR >> 1;//tmp=slave address i2c_current_Slave=0xFF;//set slave address invalid //check if the actual slave is in the slave address array for(uint8_t i=0;i<I2C_N_SLAVES;i++) { if (I2C_SLAVE_ADDR[i]==tmp) { //if slave address is found, stop searching and save index i2c_current_Slave=i; break; } } //Slave is found if current address is not initial value and temp is not 0 if (tmp==0 || i2c_current_Slave==0xFF) { /* Transition h: Address not matched */ i2c_state = I2C_STATE_IDLE; NAK(); } else { if (USIDR & 1) { /* Transition b: Address matched, read mode */ i2c_state = I2C_STATE_MASTER_READ; } else { /* Transition a: Address matched, write mode */ i2c_offset = 0; i2c_state = I2C_STATE_REG_ADDR; i2c_update[i2c_current_Slave] = 1; } ACK(); } break; case I2C_STATE_REG_ADDR: if (I2CAddressToArrayIndex(USIDR)==0xFFFF) { /* Transition i: Invalid reg addr*/ i2c_state = I2C_STATE_IDLE; NAK(); } else { /* Transition d: Initialise write*/ i2c_offset = I2CAddressToArrayIndex(USIDR); i2c_state = I2C_STATE_MASTER_WRITE; ACK(); } break; case I2C_STATE_MASTER_READ: USIDR = 0; /* Listen for master NAK */ sda_direction = I2C_SDA_DIR_IN; break; case I2C_STATE_MASTER_WRITE: #if defined(I2C_GLOBAL_WRITE_MASK) tmp = I2C_GLOBAL_WRITE_MASK; #else tmp = i2c_w_mask[i2c_offset]; #endif if (tmp) { /* Only heed writeable bits */ i2c_reg[i2c_current_Slave][i2c_offset] &= ~tmp; i2c_reg[i2c_current_Slave][i2c_offset] |= USIDR & tmp; } i2c_update[i2c_current_Slave]++; i2c_offset++; ACK(); break; default: NAK(); } /* Counter will overflow again after ACK cycle */ usisr_tmp |= 14 << USICNT0; post_ack = 1; } else { /* Work that needs to be done after the ACK cycle */ sda_direction = I2C_SDA_DIR_IN; switch (i2c_state) { case I2C_STATE_MASTER_READ: if (USIDR) { /* Transition e: Read finished */ i2c_offset = 0; i2c_state = I2C_STATE_IDLE; } else { /* Transition f: Read continues */ sda_direction = I2C_SDA_DIR_OUT; USIDR = i2c_reg[i2c_current_Slave][i2c_offset++]; } break; } post_ack = 0; } if (i2c_offset > (I2C_N_REG - 1)) i2c_offset = 0; /* Set up SDA direction for next operation */ if (sda_direction == I2C_SDA_DIR_OUT) { USI_DDR |= (1 << I2C_SDA); } else { USI_DDR &= ~(1 << I2C_SDA); } /* Clear flags and set counter */ USISR = usisr_tmp; } /* Initialise the USI and I2C state machine */ void i2c_init( void ) { i2c_state = 0; USICR = (1 << USISIE) | (1 << USIOIE) | (3 << USIWM0) | (1 << USICS1); USI_DDR |= (1 << I2C_SCL); USI_DDR &= ~(1 << I2C_SDA); USI_PORT |= (1 << I2C_SDA) | (1 << I2C_SCL); USISR = 0xF0; } /* * Return non-zero if a transaction is ongoing * A transaction is considered ongoing if the slave address has * been matched, but a stop has not been received yet. */ uint8_t i2c_transaction_ongoing( void ) { if ((i2c_state != I2C_STATE_IDLE) && (i2c_state != I2C_STATE_ADDR_MATCH)) { return 1; } else { return 0; } } /* * Check for and handle a stop condition. * Returns non-zero if any registers have been changed */ uint8_t i2c_check_stop(int8_t SlaveIndex) { uint8_t ret = 0; if ((i2c_state == I2C_STATE_MASTER_WRITE) && i2c_update[SlaveIndex]) { cli(); uint8_t tmp = USISR; if (tmp & (1 << USIPF)) { i2c_state = I2C_STATE_IDLE; ret = i2c_update[SlaveIndex]; i2c_update[SlaveIndex] = 0; } sei(); } return ret; } //calculates the PWM Value (0-255) from a PWM Channel of the PCA9685 emlulated slave uint8_t getI2CPWMValue(uint8_t Slave, uint8_t PWMChannel)//from 0 to 15 { if (PWMChannel>=0 && PWMChannel<=15) { int RegisterStartAddress=PWMChannel*BytesPerLedPwmChannel+FirstRegisterAddress;//LEDx_ON_L is in register x*4+6 int16_t iOn=(i2c_reg[Slave][RegisterStartAddress+1]<<8) + i2c_reg[Slave][RegisterStartAddress]; int16_t iOff=(i2c_reg[Slave][RegisterStartAddress+3]<<8) + i2c_reg[Slave][RegisterStartAddress+2]; int16_t iOnTime=iOff-iOn;//can be from -4095 to +4095 if (iOnTime<0) { iOnTime=iOnTime+4096; //is now from 0 to +4095 } if (iOnTime>4095) { iOnTime=4095; } uint8_t ret = (iOnTime>>4); //is now from 0 to 255 return ret; } else { return 0; } }
25.597436
146
0.676951
[ "vector" ]
56733d8ccf97cd98f311d81ade85d15190ac16dc
954
h
C
src/mafGUI/mafGUIRegistration.h
tartarini/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2021-05-10T19:01:48.000Z
2021-05-10T19:01:48.000Z
src/mafGUI/mafGUIRegistration.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
null
null
null
src/mafGUI/mafGUIRegistration.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2018-02-06T03:51:57.000Z
2018-02-06T03:51:57.000Z
/* * mafGUIRegistration.h * mafGUI * * Created by Paolo Quadrani on 26/10/10. * Copyright 2010 SCS-B3C. All rights reserved. * * See Licence at: http://tiny.cc/QXJ4D * */ #ifndef MAFGUIREGISTRATION_H #define MAFGUIREGISTRATION_H #include "mafGUIDefinitions.h" namespace mafGUI { /** Class name: mafGUIRegistration This class allows object rigisteration for all the classes present in mafGUI module. @sa mafObjectFactory mafCoreRegistration mafResourcesRegistration mafSerializationRegistration */ class mafGUIRegistration { public: /// Register all the concrete objects that can be instantiated by the mafObjectFactory. /** This registration is needed to instantiate object by using the mafNEWFromString macro present in objectFactory which needs as input the object type to instantiate as string.*/ MAFGUISHARED_EXPORT static void registerGUIObjects(); }; } // namespace mafGUI #endif // MAFGUIREGISTRATION_H
27.257143
104
0.766247
[ "object" ]
56784b38b04d1f1104c74513f15a43caad839984
2,852
h
C
Source/FSD/Public/DiscordWrapper.h
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Public/DiscordWrapper.h
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Public/DiscordWrapper.h
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#pragma once #include "CoreMinimal.h" #include "UObject/Object.h" #include "DiscordServerInviteData.h" #include "DiscordRewardNotification.h" #include "DiscordServerData.h" #include "DiscordEoMData.h" #include "DiscordWrapper.generated.h" UDELEGATE(BlueprintCallable) DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FDiscordWrapperOnResponseSuccessChanged, bool, resp); UDELEGATE(BlueprintCallable) DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FDiscordWrapperOnDiscordUserInServer, bool, isInServer); UDELEGATE(BlueprintCallable) DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FDiscordWrapperOnDiscordEoMDataEvent, bool, HasEoM); UDELEGATE(BlueprintCallable) DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDiscordWrapperOnDiscordServerInfoLoaded); UDELEGATE(BlueprintCallable) DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FDiscordWrapperOnDiscordServerCountLoaded, const FDiscordServerData&, discordServerCount); UCLASS(BlueprintType) class UDiscordWrapper : public UObject { GENERATED_BODY() public: protected: UPROPERTY(BlueprintReadOnly) FDiscordServerInviteData ServerInfo; UPROPERTY(BlueprintAssignable) FDiscordWrapperOnResponseSuccessChanged OnResponseSuccessChanged; UPROPERTY(BlueprintReadOnly) bool LastResponseSuccessful; UPROPERTY(BlueprintAssignable) FDiscordWrapperOnDiscordEoMDataEvent OnDiscordEoMDataEvent; UPROPERTY(BlueprintReadOnly) bool UserIn; UPROPERTY(BlueprintReadWrite) FDiscordRewardNotification rewardNotification; UPROPERTY(BlueprintReadOnly) int32 UserInStatus; UPROPERTY(BlueprintReadOnly) bool HasEoM; UPROPERTY(BlueprintReadOnly) FDiscordEoMData EoMData; public: UPROPERTY(BlueprintReadOnly) bool IsConnected; UPROPERTY(BlueprintReadOnly) bool ServerInfoLoaded; UPROPERTY(BlueprintAssignable) FDiscordWrapperOnDiscordServerInfoLoaded OnDiscordServerInfoLoaded; UPROPERTY(BlueprintAssignable) FDiscordWrapperOnDiscordServerCountLoaded OnDiscordServerCountLoaded; UPROPERTY(BlueprintAssignable) FDiscordWrapperOnDiscordUserInServer OnDiscordUserInServer; UFUNCTION(BlueprintCallable) void RequestUserInServer(); UFUNCTION(BlueprintCallable) void RequestFactionAdjustment(int32 Faction, bool force); UFUNCTION(BlueprintCallable) void RequestEoMData(); UFUNCTION(BlueprintCallable) void RequestDiscordServerInfo(); UFUNCTION(BlueprintCallable) void RejectInviteSignature(); UFUNCTION(BlueprintCallable) void IgnoreInviteSignature(); UFUNCTION(BlueprintCallable, BlueprintPure) FString GetAvatarURL(); UFUNCTION(BlueprintCallable) void AdjustFaction(); UFUNCTION(BlueprintCallable) void AcceptInviteSignature(); UDiscordWrapper(); };
30.340426
163
0.789972
[ "object" ]
5678e4bf0f10e8939ab95e9ea0ad2cadb6f4488c
3,370
h
C
v7/Engine/ProgramGlobals.h
c224/spfv7
c82ec42701ccfcdbbc00a074bf34f03fe93a71aa
[ "Unlicense" ]
null
null
null
v7/Engine/ProgramGlobals.h
c224/spfv7
c82ec42701ccfcdbbc00a074bf34f03fe93a71aa
[ "Unlicense" ]
null
null
null
v7/Engine/ProgramGlobals.h
c224/spfv7
c82ec42701ccfcdbbc00a074bf34f03fe93a71aa
[ "Unlicense" ]
null
null
null
/** \ingroup SPF */ /*@{*/ /*! \file ProgramGlobals.h * */ #ifndef SPF_ProgramGlobals_H #define SPF_ProgramGlobals_H #include "Map.h" #include "Vector.h" #include "PsimagLite.h" namespace Spf { class ProgramGlobals { public: enum {DIRX=0,DIRY=1,DIRXPY=2,DIRXMY=3,DIRZ=0}; template<typename SomeVectorType> static typename PsimagLite::EnableIf<PsimagLite::IsVectorLike<SomeVectorType>::True, void>::Type checkMcWindow(const SomeVectorType& mcWindow, SizeType i) { if (i < mcWindow.size()) return; PsimagLite::String str("checkMcWindow(): MonteCarloWindow must have"); str += "at least " + ttos(i+1) + " entries.\n"; throw PsimagLite::RuntimeError(str); } template<typename T> static void printGeometry(std::ostream& os,const T& g) { SizeType n = g.volume(); for (SizeType d=0;d<g.distances();++d) { os<<"#Distance Number="<<d<<"\n"; for (SizeType i=0;i<n;++i) { std::cout<<"Neighbors of "<<i<<" are "; for (SizeType k=0;k<g.z(d+1);k++) { SizeType j = g.neighbor(i,k,d+1).first; os<<j<<" "; } os<<"\n"; } } } template<typename T> static T square(const T& t) { return t*t; } template<typename VectorType, typename VectorType2> static typename PsimagLite::EnableIf<PsimagLite::IsVectorLike<VectorType>::True && PsimagLite::IsVectorLike<VectorType2>::True, void>::Type vectorPlus(VectorType& a, const VectorType& b, const VectorType2& c) { const SizeType n = b.size(); a.resize(n); if (n != c.size()) err("Vector of different sizes\n"); for (SizeType i = 0; i < n; ++i) a[i] = b[i] + c[i]; } template<typename VectorType, typename VectorType2> static typename PsimagLite::EnableIf<PsimagLite::IsVectorLike<VectorType>::True && PsimagLite::IsVectorLike<VectorType2>::True, void>::Type vectorPlus(VectorType& a, const VectorType& b, const VectorType2& c, const VectorType2& d) { const SizeType n = b.size(); if (n != c.size() || n != d.size()) err("Vector of different sizes\n"); a.resize(n); for (SizeType i = 0; i < n; ++i) a[i] = b[i] + c[i] + d[i]; } template<typename VectorType, typename VectorType2> static typename PsimagLite::EnableIf<PsimagLite::IsVectorLike<VectorType>::True && PsimagLite::IsVectorLike<VectorType2>::True, void>::Type vectorFour(VectorType& a, typename VectorType::value_type bs, const VectorType& b, typename VectorType::value_type cs, const VectorType& c, typename VectorType::value_type ds, const VectorType2& d, typename VectorType::value_type es, const VectorType2& e) { const SizeType n = b.size(); if (n != c.size() || n != d.size() || n != e.size()) err("Vector of different sizes\n"); a.resize(n); for (SizeType i = 0; i < n; ++i) a[i] = bs*b[i] + cs*c[i] + ds*d[i] + es*e[i]; } template<typename VectorType, typename VectorType2> static typename PsimagLite::EnableIf<PsimagLite::IsVectorLike<VectorType>::True && PsimagLite::IsVectorLike<VectorType2>::True, void>::Type vectorMinus(VectorType& a, const VectorType& b, const VectorType2& c) { const SizeType n = b.size(); a.resize(n); if (n != c.size()) err("Vector of different sizes\n"); for (SizeType i = 0; i < n; ++i) a[i] = b[i] - c[i]; } }; // ProgramGlobals } // namespace Spf /*@}*/ #endif // SPF_ProgramGlobals_H
26.328125
91
0.644214
[ "vector" ]
567d0a354b02ba24217847236be503900624c777
6,501
h
C
include/HMM.h
davidar/polya
b796e38f39c8d5d82db67275423127d774fde171
[ "MIT" ]
6
2015-09-10T14:35:03.000Z
2021-01-16T09:32:00.000Z
include/HMM.h
davidar/polya
b796e38f39c8d5d82db67275423127d774fde171
[ "MIT" ]
null
null
null
include/HMM.h
davidar/polya
b796e38f39c8d5d82db67275423127d774fde171
[ "MIT" ]
1
2017-09-13T19:10:35.000Z
2017-09-13T19:10:35.000Z
#pragma once #include <vector> #include <string> #include "util.h" #include "rand.h" #include "Exchangeable.h" #include "LogR.h" #include "DynDict.h" #include "Trie.h" class HMM { typedef N S; // state space std::vector<Exchangeable*> emit; typedef DynDict<std::vector<X>,Exchangeable*> T; T transition; void e_observe(N t, S s) { emit[s]->observe(text[t]); } void e_forget (N t, S s) { emit[s]->forget (text[t]); } R e_predict (N t, S s) DO(emit[s]->predict(text[t])) Exchangeable *trans(N t) { N start = (t<M) ? 0 : t-M; std::vector<S> u(states.begin() + start, states.begin() + t); return transition[u]; } void t_observe(N t, S s) { trans(t)->observe(s); } void t_forget (N t, S s) { trans(t)->forget (s); } R t_predict (N t, S s) DO(trans(t)->predict(s)) inline N horz(N t) { // index of next state independent of the current position t N z = t + M + 1; if(z > states.size()) return states.size(); return z; } R resample_state(N t) { // posterior distribution over states R post[K]; R norm = 0; FOR(s, K) { states[t] = s; R p = e_predict(t,s); FOR(i, t,horz(t)) p *= t_predict(i, states[i]); norm += post[s] = p; } FOR(s, K) post[s] /= norm; // sample new state from posterior states[t] = sample(post, K); return post[states[t]]; } public: const N M, K; // context length, maximum number of states std::vector<S> states; std::vector<X> text; HMM(N context_len, N num_states, std::vector<X> text, std::vector<Exchangeable*> emit, T::F f, void *user_data) : M(context_len), K(num_states), text(text), emit(emit), transition(f,user_data) {} void train(std::vector<S> ss) { states = ss; FOR(t, text.size()) { t_observe(t,states[t]); e_observe(t,states[t]); } } R resample() { LogR post(1); FOR(t, states.size()) { // forget old state, and states depending on it e_forget(t, states[t]); FOR(i, t,horz(t)) t_forget(i, states[i]); post *= resample_state(t); // update model e_observe(t, states[t]); FOR(i, t,horz(t)) t_observe(i, states[i]); } return log(post); } R resample(std::vector<N> ts) { #define FOR_TGRAMS \ FOR(i,ts.size()) \ LET(N start = (i == 0 || horz(ts[i-1]) <= ts[i]) \ ? ts[i] : horz(ts[i-1])) \ FOR(t, start,horz(ts[i])) LogR joint(1); // forget old states for(N t : ts) e_forget(t, states[t]); FOR_TGRAMS t_forget(t, states[t]); // posterior LogR lpost[K]; LogR norm = 0; FOR(s, K) { LogR p = 1; for(N t : ts) { states[t] = s; p *= e_predict(t,s); e_observe(t,s); } FOR_TGRAMS { p *= t_predict(t, states[t]); t_observe(t, states[t]); } norm += lpost[s] = p; // rollback for(N t : ts) e_forget(t, states[t]); FOR_TGRAMS t_forget(t, states[t]); } // sample new state R post[K]; FOR(s, K) post[s] = (R)(lpost[s] / norm); S s = sample(post, K); for(N t : ts) { states[t] = s; joint *= post[s]; } // update model for(N t : ts) e_observe(t, states[t]); FOR_TGRAMS t_observe(t, states[t]); return log(joint); } R predict(std::vector<X> xs) { assert(M == 2); // TODO: generalise // alpha[i][j] = p(s_n = j, s_n-1 = i | x_1..n) R alpha[K][K]; memset(alpha, 0, sizeof alpha); alpha[0][0] = 1; LogR prob(1); for(X x : xs) { R alpha_new[K][K]; memset(alpha_new, 0, sizeof alpha_new); R px = 0; FOR(k,K) { R p_emit = emit[k]->predict(x); FOR(j,K) { R p = 0; FOR(i,K) p += transition[{i,j}]->predict(k) * alpha[i][j]; p *= p_emit; px += alpha_new[j][k] = p; } } prob *= px; FOR(k,K) FOR(j,K) alpha[j][k] = alpha_new[j][k] / px; } return log(prob); } R predict(std::string text, std::vector<Trie*> tries, const N maxr) { assert(M == 2); // TODO: generalise LogR prob(1); // alpha[r][i][j] = p(word started at t-r, s_t = j, s_t-r-1 = i | x_1..t) R alpha[maxr][K][K]; memset(alpha, 0, sizeof alpha); char c = text[0]; R pc = 0; FOR(k,K) pc += alpha[0][0][k] = tries[k]->predict(c) * transition[{}]->predict(k); FOR(k,K) alpha[0][0][k] /= pc; prob *= pc; FOR(t, 1,text.size()) { c = text[t]; R alpha_new[maxr][K][K]; memset(alpha_new, 0, sizeof alpha_new); pc = 0; FOR(k,K) FOR(j,K) { FOR(r, 1,maxr) { auto start = text.begin() + t - r; if(alpha[r-1][j][k] > 0) { const Trie *trie = tries[k]->lookup(start, r); if(trie == NULL) alpha_new[r][j][k] = 0; else alpha_new[r][j][k] = alpha[r-1][j][k] * trie->predict(c); pc += alpha_new[r][j][k]; } FOR(i,K) if(alpha[r-1][i][j] > 0) { const Trie *trie = tries[j]->lookup(start, r); if(trie != NULL) alpha_new[0][j][k] += alpha[r-1][i][j] * trie->predict() * transition[{i,j}]->predict(k) * tries[k]->predict(c); } } pc += alpha_new[0][j][k]; } FOR(k,K) FOR(j,K) FOR(r,maxr) alpha[r][j][k] = alpha_new[r][j][k] / pc; prob *= pc; } return log(prob); } };
31.558252
81
0.424396
[ "vector", "model" ]
56832dc9c66f5537abefdc965201df14c281ddb0
2,922
h
C
src/lib/common/sol-mainloop-common.h
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
266
2015-06-11T00:21:02.000Z
2022-03-27T20:45:17.000Z
src/lib/common/sol-mainloop-common.h
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
2,224
2015-06-17T17:29:50.000Z
2018-07-20T23:43:40.000Z
src/lib/common/sol-mainloop-common.h
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
151
2015-06-17T14:42:54.000Z
2022-01-27T17:01:35.000Z
/* * This file is part of the Soletta (TM) Project * * Copyright (C) 2015 Intel Corporation. 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. */ #pragma once #include "sol-common-buildopts.h" #ifndef SOL_PLATFORM_ZEPHYR #include <time.h> #endif #include "sol-util-internal.h" #include "sol-vector.h" struct sol_timeout_common { struct timespec timeout; struct timespec expire; const void *data; bool (*cb)(void *data); bool remove_me; }; struct sol_idler_common { const void *data; bool (*cb)(void *data); enum { idler_ready, idler_deleted, idler_ready_on_next_iteration } status; }; /* must be called with mainloop lock held */ static inline void sol_mainloop_ptr_vector_steal(struct sol_ptr_vector *to, struct sol_ptr_vector *from) { #ifdef THREADS *to = *from; sol_ptr_vector_init(from); #endif } /* must be called with mainloop lock held */ static inline void sol_ptr_vector_update(struct sol_ptr_vector *to, struct sol_ptr_vector *from) { #ifdef THREADS void *itr; uint16_t i; SOL_PTR_VECTOR_FOREACH_IDX (from, itr, i) { /* FIXME: Handle when it fails properly */ (void)sol_ptr_vector_append(to, itr); } sol_ptr_vector_clear(from); #endif } bool sol_mainloop_common_loop_check(void); void sol_mainloop_common_loop_set(bool val); void sol_mainloop_common_timeout_process(void); void sol_mainloop_common_idler_process(void); bool sol_mainloop_common_timespec_first(struct timespec *ts); struct sol_idler_common *sol_mainloop_common_idler_first(void); bool sol_mainloop_common_source_prepare(void); bool sol_mainloop_common_source_get_next_timeout(struct timespec *timeout); bool sol_mainloop_common_source_check(void); void sol_mainloop_common_source_dispatch(void); void sol_mainloop_common_source_shutdown(void); /* thread-related platform specific functions */ bool sol_mainloop_impl_main_thread_check(void); void sol_mainloop_impl_main_thread_notify(void); void sol_mainloop_impl_lock(void); void sol_mainloop_impl_unlock(void); /* platform specific mainloop functions */ int sol_mainloop_impl_platform_init(void); void sol_mainloop_impl_platform_shutdown(void); void sol_mainloop_impl_iter(void); static inline void sol_mainloop_common_main_thread_check_notify(void) { #ifdef THREADS if (!sol_mainloop_impl_main_thread_check()) sol_mainloop_impl_main_thread_notify(); #endif }
28.368932
85
0.773785
[ "vector" ]
568d90e0950c24891815267ff50c66bec583f8a6
503
h
C
muBoss.h
jeon109/Forager-Imitation
c58679801bf50197aa03c1aec8f913e2a9287f86
[ "MIT" ]
null
null
null
muBoss.h
jeon109/Forager-Imitation
c58679801bf50197aa03c1aec8f913e2a9287f86
[ "MIT" ]
null
null
null
muBoss.h
jeon109/Forager-Imitation
c58679801bf50197aa03c1aec8f913e2a9287f86
[ "MIT" ]
2
2021-02-08T02:26:33.000Z
2021-02-15T08:26:36.000Z
#pragma once #include "unit.h" enum MUSTATE { MIDLE, CRY }; class muBoss : public enemy { private: MUSTATE _state5; int fireCount; int crashCount; int crashPointCount; int searchCount; int _difficultyLevel; int _spawnCount; bool _canFire; bool _readyToCrash; public: HRESULT init(int p_level); void update() override; void render(HDC hdc) override; void muuAnimation(); void hurt(int damage, bool onlyEffect = false) override; void dead() override; void muBossExplode(); };
13.236842
57
0.725646
[ "render" ]
569472edda620b550684b0750ece4cc0b797d07a
18,666
h
C
3rdparty/ufbx/ufbx.h
jing-interactive/MeshViewer
67fa14d19fea157124edddead2ca3fc54d370691
[ "MIT" ]
28
2018-09-05T06:30:38.000Z
2019-01-16T18:49:08.000Z
3rdparty/ufbx/ufbx.h
jing-interactive/melo
67fa14d19fea157124edddead2ca3fc54d370691
[ "MIT" ]
2
2018-09-11T22:26:56.000Z
2018-11-21T02:55:24.000Z
3rdparty/ufbx/ufbx.h
jing-interactive/melo
67fa14d19fea157124edddead2ca3fc54d370691
[ "MIT" ]
2
2018-09-05T06:30:38.000Z
2018-12-14T21:01:57.000Z
#ifndef UFBX_UFBX_H_INLCUDED #define UFBX_UFBX_H_INLCUDED // -- Headers #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <string.h> // -- Platform #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union #pragma warning(disable: 4505) // unreferenced local function has been removed #define ufbx_inline static __forceinline #elif defined(__GNUC__) #define ufbx_inline static inline __attribute__((always_inline, unused)) #else #define ufbx_inline static #endif // -- Configuration typedef double ufbx_real; #define UFBX_ERROR_STACK_MAX_DEPTH 8 // -- Basic types typedef struct ufbx_string { const char *data; size_t length; } ufbx_string; typedef struct ufbx_vec2 { union { struct { ufbx_real x, y; }; ufbx_real v[2]; }; } ufbx_vec2; typedef struct ufbx_vec3 { union { struct { ufbx_real x, y, z; }; ufbx_real v[3]; }; } ufbx_vec3; typedef struct ufbx_vec4 { union { struct { ufbx_real x, y, z, w; }; ufbx_real v[4]; }; } ufbx_vec4; typedef enum ufbx_rotation_order { UFBX_ROTATION_XYZ, UFBX_ROTATION_XZY, UFBX_ROTATION_YZX, UFBX_ROTATION_YXZ, UFBX_ROTATION_ZXY, UFBX_ROTATION_ZYX, } ufbx_rotation_order; typedef struct ufbx_transform { ufbx_vec3 translation; ufbx_vec4 rotation; ufbx_vec3 scale; } ufbx_transform; typedef struct ufbx_matrix { union { struct { ufbx_real m00, m10, m20; ufbx_real m01, m11, m21; ufbx_real m02, m12, m22; ufbx_real m03, m13, m23; }; ufbx_vec3 cols[4]; ufbx_real v[12]; }; } ufbx_matrix; // -- Properties typedef struct ufbx_prop ufbx_prop; typedef struct ufbx_props ufbx_props; typedef enum ufbx_prop_type { UFBX_PROP_UNKNOWN, UFBX_PROP_BOOLEAN, UFBX_PROP_INTEGER, UFBX_PROP_NUMBER, UFBX_PROP_VECTOR, UFBX_PROP_COLOR, UFBX_PROP_STRING, UFBX_PROP_DATE_TIME, UFBX_PROP_TRANSLATION, UFBX_PROP_ROTATION, UFBX_PROP_SCALING, UFBX_NUM_PROP_TYPES, } ufbx_prop_type; struct ufbx_prop { ufbx_string name; uint32_t imp_key; ufbx_prop_type type; ufbx_string value_str; int64_t value_int; union { ufbx_real value_real_arr[3]; ufbx_real value_real; ufbx_vec2 value_vec2; ufbx_vec3 value_vec3; }; }; struct ufbx_props { ufbx_prop *props; size_t num_props; ufbx_props *defaults; }; // -- Scene data typedef struct ufbx_node ufbx_node; typedef struct ufbx_model ufbx_model; typedef struct ufbx_mesh ufbx_mesh; typedef struct ufbx_light ufbx_light; typedef struct ufbx_bone ufbx_bone; typedef struct ufbx_node_ptr_list { ufbx_node **data; size_t size; } ufbx_node_ptr_list; typedef struct ufbx_model_list { ufbx_model *data; size_t size; } ufbx_model_list; typedef struct ufbx_mesh_list { ufbx_mesh *data; size_t size; } ufbx_mesh_list; typedef struct ufbx_light_list { ufbx_light *data; size_t size; } ufbx_light_list; typedef struct ufbx_bone_list { ufbx_bone *data; size_t size; } ufbx_bone_list; typedef struct ufbx_material ufbx_material; typedef struct ufbx_vertex_void ufbx_vertex_void; typedef struct ufbx_vertex_real ufbx_vertex_real; typedef struct ufbx_vertex_vec2 ufbx_vertex_vec2; typedef struct ufbx_vertex_vec3 ufbx_vertex_vec3; typedef struct ufbx_vertex_vec4 ufbx_vertex_vec4; typedef struct ufbx_uv_set ufbx_uv_set; typedef struct ufbx_color_set ufbx_color_set; typedef struct ufbx_edge ufbx_edge; typedef struct ufbx_face ufbx_face; typedef struct ufbx_skin ufbx_skin; typedef struct ufbx_material_list { ufbx_material *data; size_t size; } ufbx_material_list; typedef struct ufbx_material_ptr_list { ufbx_material **data; size_t size; } ufbx_material_ptr_list; typedef struct ufbx_uv_set_list { ufbx_uv_set *data; size_t size; } ufbx_uv_set_list; typedef struct ufbx_color_set_list { ufbx_color_set *data; size_t size; } ufbx_color_set_list; typedef struct ufbx_skin_list { ufbx_skin *data; size_t size; } ufbx_skin_list; struct ufbx_vertex_void { void *data; int32_t *indices; size_t num_elements; }; struct ufbx_vertex_real { ufbx_real *data; int32_t *indices; size_t num_elements; }; struct ufbx_vertex_vec2 { ufbx_vec2 *data; int32_t *indices; size_t num_elements; }; struct ufbx_vertex_vec3 { ufbx_vec3 *data; int32_t *indices; size_t num_elements; }; struct ufbx_vertex_vec4 { ufbx_vec4 *data; int32_t *indices; size_t num_elements; }; struct ufbx_uv_set { ufbx_string name; int32_t index; ufbx_vertex_vec2 vertex_uv; ufbx_vertex_vec3 vertex_binormal; ufbx_vertex_vec3 vertex_tangent; }; struct ufbx_color_set { ufbx_string name; int32_t index; ufbx_vertex_vec4 vertex_color; }; struct ufbx_edge { uint32_t indices[2]; }; struct ufbx_face { uint32_t index_begin; uint32_t num_indices; }; struct ufbx_skin { ufbx_node *bone; ufbx_matrix mesh_to_bind; ufbx_matrix bind_to_world; size_t num_weights; int32_t *indices; ufbx_real *weights; }; struct ufbx_material { ufbx_string name; ufbx_props props; ufbx_vec3 diffuse_color; ufbx_vec3 specular_color; }; typedef enum ufbx_node_type { UFBX_NODE_UNKNOWN, UFBX_NODE_MODEL, UFBX_NODE_MESH, UFBX_NODE_LIGHT, UFBX_NODE_BONE, } ufbx_node_type; typedef enum ufbx_inherit_type { UFBX_INHERIT_NO_SHEAR, // R*r*S*s UFBX_INHERIT_NORMAL, // R*S*r*s UFBX_INHERIT_NO_SCALE, // R*r*s } ufbx_inherit_type; struct ufbx_node { ufbx_node_type type; ufbx_string name; ufbx_props props; ufbx_node *parent; ufbx_inherit_type inherit_type; ufbx_transform transform; ufbx_transform world_transform; ufbx_matrix to_parent; ufbx_matrix to_root; ufbx_node_ptr_list children; }; struct ufbx_model { ufbx_node node; }; struct ufbx_mesh { ufbx_node node; size_t num_vertices; size_t num_indices; size_t num_triangles; size_t num_faces; size_t num_bad_faces; size_t num_edges; ufbx_face *faces; ufbx_edge *edges; ufbx_vertex_vec3 vertex_position; ufbx_vertex_vec3 vertex_normal; ufbx_vertex_vec3 vertex_binormal; ufbx_vertex_vec3 vertex_tangent; ufbx_vertex_vec2 vertex_uv; ufbx_vertex_vec4 vertex_color; ufbx_vertex_real vertex_crease; bool *edge_smoothing; ufbx_real *edge_crease; bool *face_smoothing; int32_t *face_material; ufbx_uv_set_list uv_sets; ufbx_color_set_list color_sets; ufbx_material_ptr_list materials; ufbx_skin_list skins; }; struct ufbx_light { ufbx_node node; ufbx_vec3 color; ufbx_real intensity; }; struct ufbx_bone { ufbx_node node; ufbx_real length; }; // -- Animations typedef struct ufbx_anim_stack ufbx_anim_stack; typedef struct ufbx_anim_layer ufbx_anim_layer; typedef struct ufbx_anim_prop ufbx_anim_prop; typedef struct ufbx_anim_curve ufbx_anim_curve; typedef struct ufbx_keyframe ufbx_keyframe; typedef struct ufbx_tangent ufbx_tangent; typedef struct ufbx_anim_stack_list { ufbx_anim_stack *data; size_t size; } ufbx_anim_stack_list; typedef struct ufbx_anim_layer_list { ufbx_anim_layer *data; size_t size; } ufbx_anim_layer_list; typedef struct ufbx_anim_layer_ptr_list { ufbx_anim_layer **data; size_t size; } ufbx_anim_layer_ptr_list; typedef struct ufbx_anim_prop_list { ufbx_anim_prop *data; size_t size; } ufbx_anim_prop_list; typedef struct ufbx_anim_curve_list { ufbx_anim_curve *data; size_t size; } ufbx_anim_curve_list; typedef struct ufbx_keyframe_list { ufbx_keyframe *data; size_t size; } ufbx_keyframe_list; struct ufbx_tangent { float dx; float dy; }; typedef enum ufbx_interpolation { UFBX_INTERPOLATION_CONSTANT_PREV, UFBX_INTERPOLATION_CONSTANT_NEXT, UFBX_INTERPOLATION_LINEAR, UFBX_INTERPOLATION_CUBIC, } ufbx_interpolation; typedef enum ufbx_anim_target { UFBX_ANIM_UNKNOWN, UFBX_ANIM_ANIM_LAYER, UFBX_ANIM_MODEL, UFBX_ANIM_MESH, UFBX_ANIM_LIGHT, UFBX_ANIM_MATERIAL, UFBX_ANIM_BONE, UFBX_ANIM_INVALID, } ufbx_anim_target; struct ufbx_anim_stack { ufbx_string name; ufbx_props props; double time_begin; double time_end; ufbx_anim_layer_ptr_list layers; }; struct ufbx_anim_layer { ufbx_string name; ufbx_props layer_props; ufbx_anim_prop_list props; ufbx_real weight; bool compose_rotation; bool compose_scale; }; struct ufbx_anim_curve { ufbx_real default_value; uint32_t index; ufbx_anim_prop *prop; ufbx_keyframe_list keyframes; }; struct ufbx_anim_prop { ufbx_string name; uint32_t imp_key; ufbx_anim_layer *layer; ufbx_anim_target target; uint32_t index; ufbx_anim_curve curves[3]; }; struct ufbx_keyframe { double time; ufbx_real value; ufbx_interpolation interpolation; ufbx_tangent left; ufbx_tangent right; }; // -- Scene typedef struct ufbx_scene ufbx_scene; typedef struct ufbx_metadata { bool ascii; uint32_t version; ufbx_string creator; size_t result_memory_used; size_t temp_memory_used; size_t result_allocs; size_t temp_allocs; size_t num_total_child_refs; size_t num_total_material_refs; size_t num_total_skins; size_t num_skinned_positions; size_t num_skinned_indices; size_t max_skinned_positions; size_t max_skinned_indices; double ktime_to_sec; } ufbx_metadata; struct ufbx_scene { ufbx_metadata metadata; ufbx_model *root; ufbx_node_ptr_list nodes; ufbx_model_list models; ufbx_mesh_list meshes; ufbx_light_list lights; ufbx_bone_list bones; ufbx_material_list materials; ufbx_anim_stack_list anim_stacks; ufbx_anim_layer_list anim_layers; ufbx_anim_prop_list anim_props; ufbx_anim_curve_list anim_curves; }; // -- Loading typedef void *ufbx_alloc_fn(void *user, size_t size); typedef void *ufbx_realloc_fn(void *user, void *old_ptr, size_t old_size, size_t new_size); typedef void ufbx_free_fn(void *user, void *ptr, size_t size); typedef size_t ufbx_read_fn(void *user, void *data, size_t size); typedef struct ufbx_error_frame { uint32_t source_line; const char *function; const char *description; } ufbx_error_frame; typedef struct ufbx_error { uint32_t stack_size; ufbx_error_frame stack[UFBX_ERROR_STACK_MAX_DEPTH]; } ufbx_error; typedef struct ufbx_allocator { ufbx_alloc_fn *alloc_fn; ufbx_realloc_fn *realloc_fn; ufbx_free_fn *free_fn; void *user; } ufbx_allocator; typedef struct ufbx_load_opts { ufbx_allocator temp_allocator; ufbx_allocator result_allocator; // Preferences bool ignore_geometry; bool ignore_animation; // Limits size_t max_temp_memory; size_t max_result_memory; size_t max_temp_allocs; size_t max_result_allocs; size_t temp_huge_size; size_t result_huge_size; size_t max_ascii_token_length; size_t read_buffer_size; size_t max_properties; uint32_t max_string_length; uint32_t max_strings; uint32_t max_node_depth; uint32_t max_node_values; uint32_t max_node_children; uint32_t max_array_size; uint32_t max_child_depth; bool allow_nonexistent_indices; } ufbx_load_opts; typedef struct ufbx_evaluate_opts { ufbx_scene *reuse_scene; ufbx_allocator allocator; bool evaluate_skinned_vertices; const ufbx_anim_layer *layer; } ufbx_evaluate_opts; // -- Inflate typedef struct ufbx_inflate_input ufbx_inflate_input; typedef struct ufbx_inflate_retain ufbx_inflate_retain; struct ufbx_inflate_input { size_t total_size; const void *data; size_t data_size; void *buffer; size_t buffer_size; ufbx_read_fn *read_fn; void *read_user; }; struct ufbx_inflate_retain { bool initialized; uint64_t data[512]; }; // -- API #ifdef __cplusplus extern "C" { #endif extern const ufbx_string ufbx_empty_string; extern const ufbx_matrix ufbx_identity_matrix; extern const ufbx_transform ufbx_identity_transform; ufbx_scene *ufbx_load_memory(const void *data, size_t size, const ufbx_load_opts *opts, ufbx_error *error); ufbx_scene *ufbx_load_file(const char *filename, const ufbx_load_opts *opts, ufbx_error *error); ufbx_scene *ufbx_load_stdio(void *file, const ufbx_load_opts *opts, ufbx_error *error); void ufbx_free_scene(ufbx_scene *scene); ufbx_node *ufbx_find_node_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_mesh *ufbx_find_mesh_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_material *ufbx_find_material_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_light *ufbx_find_light_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_anim_stack *ufbx_find_anim_stack_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_anim_layer *ufbx_find_anim_layer_len(const ufbx_scene *scene, const char *name, size_t name_len); ufbx_prop *ufbx_find_prop_len(const ufbx_props *props, const char *name, size_t name_len); ufbx_anim_prop *ufbx_find_node_anim_prop_begin(const ufbx_scene *scene, const ufbx_anim_layer *layer, const ufbx_node *node); ufbx_face *ufbx_find_face(const ufbx_mesh *mesh, size_t index); ufbx_matrix ufbx_get_transform_matrix(const ufbx_transform *transform); void ufbx_matrix_mul(ufbx_matrix *dst, const ufbx_matrix *l, const ufbx_matrix *r); ufbx_vec3 ufbx_transform_position(const ufbx_matrix *m, ufbx_vec3 v); ufbx_vec3 ufbx_transform_direction(const ufbx_matrix *m, ufbx_vec3 v); ufbx_matrix ufbx_get_normal_matrix(const ufbx_matrix *m); ufbx_matrix ufbx_get_inverse_matrix(const ufbx_matrix *m); ufbx_real ufbx_evaluate_curve(const ufbx_anim_curve *curve, double time); ufbx_transform ufbx_evaluate_transform(const ufbx_scene *scene, const ufbx_node *node, const ufbx_anim_stack *stack, double time); ufbx_scene *ufbx_evaluate_scene(const ufbx_scene *scene, const ufbx_evaluate_opts *opts, double time); ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain); ufbx_vec3 ufbx_rotate_vector(ufbx_vec4 q, ufbx_vec3 v); bool ufbx_triangulate(uint32_t *indices, size_t num_indices, ufbx_mesh *mesh, ufbx_face face); // Utility ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain); // -- Inline API ufbx_inline ufbx_node *ufbx_find_node(const ufbx_scene *scene, const char *name) { return ufbx_find_node_len(scene, name, strlen(name)); } ufbx_inline ufbx_mesh *ufbx_find_mesh(const ufbx_scene *scene, const char *name) { return ufbx_find_mesh_len(scene, name, strlen(name)); } ufbx_inline ufbx_material *ufbx_find_material(const ufbx_scene *scene, const char *name) { return ufbx_find_material_len(scene, name, strlen(name)); } ufbx_inline ufbx_light *ufbx_find_light(const ufbx_scene *scene, const char *name) { return ufbx_find_light_len(scene, name, strlen(name)); } ufbx_inline ufbx_anim_stack *ufbx_find_anim_stack(const ufbx_scene *scene, const char *name) { return ufbx_find_anim_stack_len(scene, name, strlen(name)); } ufbx_inline ufbx_anim_layer *ufbx_find_anim_layer(const ufbx_scene *scene, const char *name) { return ufbx_find_anim_layer_len(scene, name, strlen(name)); } ufbx_inline ufbx_prop *ufbx_find_prop(const ufbx_props *props, const char *name) { return ufbx_find_prop_len(props, name, strlen(name)); } ufbx_inline ufbx_real ufbx_get_vertex_real(const ufbx_vertex_real *v, size_t index) { return v->data[v->indices[index]]; } ufbx_inline ufbx_vec2 ufbx_get_vertex_vec2(const ufbx_vertex_vec2 *v, size_t index) { return v->data[v->indices[index]]; } ufbx_inline ufbx_vec3 ufbx_get_vertex_vec3(const ufbx_vertex_vec3 *v, size_t index) { return v->data[v->indices[index]]; } ufbx_inline ufbx_vec4 ufbx_get_vertex_vec4(const ufbx_vertex_vec4 *v, size_t index) { return v->data[v->indices[index]]; } #ifdef __cplusplus } #endif #ifdef __cplusplus ufbx_inline ufbx_material *begin(const ufbx_material_list &l) { return l.data; } ufbx_inline ufbx_material *end(const ufbx_material_list &l) { return l.data + l.size; } ufbx_inline ufbx_material **begin(const ufbx_material_ptr_list &l) { return l.data; } ufbx_inline ufbx_material **end(const ufbx_material_ptr_list &l) { return l.data + l.size; } ufbx_inline ufbx_uv_set *begin(const ufbx_uv_set_list &l) { return l.data; } ufbx_inline ufbx_uv_set *end(const ufbx_uv_set_list &l) { return l.data + l.size; } ufbx_inline ufbx_color_set *begin(const ufbx_color_set_list &l) { return l.data; } ufbx_inline ufbx_color_set *end(const ufbx_color_set_list &l) { return l.data + l.size; } ufbx_inline ufbx_node **begin(const ufbx_node_ptr_list &l) { return l.data; } ufbx_inline ufbx_node **end(const ufbx_node_ptr_list &l) { return l.data + l.size; } ufbx_inline ufbx_model *begin(const ufbx_model_list &l) { return l.data; } ufbx_inline ufbx_model *end(const ufbx_model_list &l) { return l.data + l.size; } ufbx_inline ufbx_mesh *begin(const ufbx_mesh_list &l) { return l.data; } ufbx_inline ufbx_mesh *end(const ufbx_mesh_list &l) { return l.data + l.size; } ufbx_inline ufbx_light *begin(const ufbx_light_list &l) { return l.data; } ufbx_inline ufbx_light *end(const ufbx_light_list &l) { return l.data + l.size; } ufbx_inline ufbx_bone *begin(const ufbx_bone_list &l) { return l.data; } ufbx_inline ufbx_bone *end(const ufbx_bone_list &l) { return l.data + l.size; } ufbx_inline ufbx_anim_stack *begin(const ufbx_anim_stack_list &l) { return l.data; } ufbx_inline ufbx_anim_stack *end(const ufbx_anim_stack_list &l) { return l.data + l.size; } ufbx_inline ufbx_anim_layer *begin(const ufbx_anim_layer_list &l) { return l.data; } ufbx_inline ufbx_anim_layer *end(const ufbx_anim_layer_list &l) { return l.data + l.size; } ufbx_inline ufbx_anim_layer **begin(const ufbx_anim_layer_ptr_list &l) { return l.data; } ufbx_inline ufbx_anim_layer **end(const ufbx_anim_layer_ptr_list &l) { return l.data + l.size; } ufbx_inline ufbx_anim_prop *begin(const ufbx_anim_prop_list &l) { return l.data; } ufbx_inline ufbx_anim_prop *end(const ufbx_anim_prop_list &l) { return l.data + l.size; } ufbx_inline ufbx_anim_curve *begin(const ufbx_anim_curve_list &l) { return l.data; } ufbx_inline ufbx_anim_curve *end(const ufbx_anim_curve_list &l) { return l.data + l.size; } ufbx_inline ufbx_keyframe *begin(const ufbx_keyframe_list &l) { return l.data; } ufbx_inline ufbx_keyframe *end(const ufbx_keyframe_list &l) { return l.data + l.size; } ufbx_inline ufbx_skin *begin(const ufbx_skin_list& l) { return l.data; } ufbx_inline ufbx_skin *end(const ufbx_skin_list& l) { return l.data + l.size; } #endif #if defined(_MSC_VER) #pragma warning(pop) #endif #endif
28.239032
131
0.768402
[ "mesh", "transform" ]
5694d335197cd6a92e81f9b4c56c4f38e3ca554a
5,444
h
C
Code/Common/itkEventObject.h
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Code/Common/itkEventObject.h
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Code/Common/itkEventObject.h
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkEventObject.h Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __itkEventObject_h #define __itkEventObject_h #include "itkIndent.h" namespace itk { /** \class EventObject * \brief Abstraction of the Events used to communicating among filters and with GUIs. * * EventObject provides a standard coding for sending and receiving messages * indicating things like the initiation of processes, end of processes, * modification of filters. * * EventObjects form a hierarchy similar to the itk::ExceptionObject allowing * to factorize common events in a tree-like structure. Higher detail can * be assigned by users by subclassing existing itk::EventObjects. * * EventObjects are used by itk::Command and itk::Object for implementing the * Observer/Subject design pattern. Observers register their interest in * particular kinds of events produced by a specific itk::Object. This * mechanism decouples classes among them. * * As opposed to itk::Exception, itk::EventObject does not represent error * states, but simply flow of information allowing to trigger actions * as a consequence of changes occurring in state on some itk::Objects. * * itk::EventObject carries information in its own type, it relies on the * appropiate use of the RTTI (Run Time Type Information). * * A set of standard EventObjects is defined near the end of itkEventObject.h. * * \sa itk::Command * \sa itk::ExceptionObject * * \ingroup ITKSystemObjects */ class ITKCommon_EXPORT EventObject { public: /** Constructor and copy constructor. Note that these functions will be * called when children are instantiated. */ EventObject() {} EventObject(const EventObject&){}; /** Virtual destructor needed */ virtual ~EventObject() {} /** Create an Event of this type This method work as a Factory for * creating events of each particular type. */ virtual EventObject* MakeObject() const=0; /** Print Event information. This method can be overridden by * specific Event subtypes. The default is to print out the type of * the event. */ virtual void Print(std::ostream& os) const; /** Return the StringName associated with the event. */ virtual const char * GetEventName(void) const=0; /** Check if given event matches or derives from this event. */ virtual bool CheckEvent(const EventObject*) const=0; protected: /** Methods invoked by Print() to print information about the object * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ virtual void PrintSelf(std::ostream& os, Indent indent) const; virtual void PrintHeader(std::ostream& os, Indent indent) const; virtual void PrintTrailer(std::ostream& os, Indent indent) const; private: typedef EventObject * EventFactoryFunction(); void operator=(const EventObject&); }; /** Generic inserter operator for EventObject and its subclasses. */ inline std::ostream& operator<<(std::ostream& os, EventObject &e) { (&e)->Print(os); return os; } /** * Macro for creating new Events */ #define itkEventMacro( classname , super ) \ /** \class classname */ \ class classname : public super { \ public: \ typedef classname Self; \ typedef super Superclass; \ classname() {} \ virtual ~classname() {} \ virtual const char * GetEventName() const { return #classname; } \ virtual bool CheckEvent(const ::itk::EventObject* e) const \ { return dynamic_cast<const Self*>(e); } \ virtual ::itk::EventObject* MakeObject() const \ { return new Self; } \ classname(const Self&s) :super(s){}; \ private: \ void operator=(const Self&); \ }; /** * Define some common ITK events */ itkEventMacro( NoEvent , EventObject ) itkEventMacro( AnyEvent , EventObject ) itkEventMacro( DeleteEvent , AnyEvent ) itkEventMacro( StartEvent , AnyEvent ) itkEventMacro( EndEvent , AnyEvent ) itkEventMacro( ProgressEvent , AnyEvent ) itkEventMacro( ExitEvent , AnyEvent ) itkEventMacro( AbortEvent , AnyEvent ) itkEventMacro( ModifiedEvent , AnyEvent ) itkEventMacro( InitializeEvent , AnyEvent ) itkEventMacro( IterationEvent , AnyEvent ) itkEventMacro( PickEvent , AnyEvent ) itkEventMacro( StartPickEvent , PickEvent ) itkEventMacro( EndPickEvent , PickEvent ) itkEventMacro( AbortCheckEvent , PickEvent ) itkEventMacro( FunctionEvaluationIterationEvent, IterationEvent ) itkEventMacro( GradientEvaluationIterationEvent, IterationEvent ) itkEventMacro( FunctionAndGradientEvaluationIterationEvent, IterationEvent ) itkEventMacro( UserEvent , AnyEvent ) } // end namespace itk #endif
34.675159
78
0.692506
[ "object" ]
5696cc9d95790711363e5dc7f0a0979e9180369d
837
h
C
src/electron_generators/dummy_electron_list.h
Samthos/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
1
2021-04-06T05:01:47.000Z
2021-04-06T05:01:47.000Z
src/electron_generators/dummy_electron_list.h
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
null
null
null
src/electron_generators/dummy_electron_list.h
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
3
2020-06-09T23:53:28.000Z
2022-03-02T05:44:55.000Z
#ifndef DUMMY_ELECTRON_LIST_H_ #define DUMMY_ELECTRON_LIST_H_ #include "electron_list.h" template <template <typename, typename> typename Container, template <typename> typename Allocator> class Dummy_Electron_List : public Electron_List<Container, Allocator> { public: explicit Dummy_Electron_List(int size); void move(Random& random, const Electron_GTO_Weight& weight) override; bool requires_blocking() override; private: }; template class Dummy_Electron_List<std::vector, std::allocator>; typedef Dummy_Electron_List<std::vector, std::allocator> Dummy_Electron_List_Host; #ifdef HAVE_CUDA template class Dummy_Electron_List<thrust::device_vector, thrust::device_allocator>; typedef Dummy_Electron_List<thrust::device_vector, thrust::device_allocator> Dummy_Electron_List_Device; #endif #endif // DUMMY_ELECTRON_LIST_H_
34.875
104
0.824373
[ "vector" ]
56a15a57b63d358d7cceab8fce7f1493c1ddfc09
1,357
h
C
CosStd/include/cos/File.h
zhuyadong/COS
0056f1b42120614ec25331d9a40349390c1d03fb
[ "Apache-2.0" ]
292
2015-01-03T08:06:47.000Z
2022-03-20T18:28:33.000Z
CosStd/include/cos/File.h
devel-chm/COS
66adcdae7292d384f4ec3034df1236db9c29ee8d
[ "Apache-2.0" ]
25
2015-07-14T13:52:59.000Z
2019-04-23T12:08:52.000Z
CosStd/include/cos/File.h
devel-chm/COS
66adcdae7292d384f4ec3034df1236db9c29ee8d
[ "Apache-2.0" ]
44
2015-09-18T09:09:18.000Z
2022-03-20T18:28:11.000Z
#ifndef COS_FILE_H #define COS_FILE_H /** * C Object System * COS File * * Copyright 2006+ Laurent Deniau <laurent.deniau@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. */ #include <cos/Stream.h> /* NOTE-USER: File classes (wrapper to C FILE*) <- InputStream <- InputFile <- InputOutputFile <- OutputStream <- OutputFile <- OutputInputFile */ #include <stdio.h> // ----- private shared data structure struct file_descriptor_ { FILE *fp; OBJ name; BOOL own; }; // ----- File types defclass(InputFile, InputStream) // r mode struct file_descriptor_ fd; endclass defclass(OutputFile, OutputStream) // w mode struct file_descriptor_ fd; endclass defclass(InputOutputFile, InputFile) // r+ mode endclass defclass(OutputInputFile, OutputFile) // w+ mode endclass #endif // COS_FILE_H
21.539683
75
0.711127
[ "object" ]
4c2b3c2bad25681f129c94ca183dc37ae43ddae5
1,426
h
C
DemoProject/CeilingLamp.h
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
17
2017-04-02T00:17:47.000Z
2021-11-23T21:42:48.000Z
DemoProject/CeilingLamp.h
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
null
null
null
DemoProject/CeilingLamp.h
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
5
2017-08-06T12:47:18.000Z
2020-08-14T14:16:22.000Z
#pragma once #include <FSE/FSEObject/FSEObject.h> #include <LTBL2/src/LightShape.hpp> #include <FSE/AssetLoader.h> #include <LTBL2/src/Sprite.hpp> #include <FSE/Lights/SpotLight.h> class CeilingLamp : public fse::FSEObject { public: CeilingLamp(); explicit CeilingLamp(const sf::Vector2f& spawnPos); ~CeilingLamp() override; void update(float deltaTime) override; void draw(sf::RenderTarget& target) override; void drawNormals(sf::RenderTarget& target) override; void drawSpecular(sf::RenderTarget& target) override; void spawned() override; void onDespawn() override; void setPosition(const sf::Vector2f position) override; sf::FloatRect GetAABBs() const override; float getRotation() const; void setRotation(float rot); private: void shapeFromSprite(); void setAlphaThreshold(int threshold); int getAlphaThreshold() const; void setLimit(float limit); void setAverageCount(int avgCount); float getLimit() const; int getAverageCount() const; fse::Texture texture_; fse::Texture normal_texture_; fse::Texture specular_texture; ltbl::Sprite sprite_; fse::SpotLight spot_light_; ltbl::LightShape* light_shape_; b2Body *anchor_body_; b2Body *phys_body_; std::vector<ltbl::LightShape*> light_shapes_; float limit_ = 0.186f; int avg_count_ = 1; int avg_count_after_ = 0; int alpha_threshold_ = 29; int max_polys_ = 5; RTTR_ENABLE(fse::FSEObject) RTTR_REGISTRATION_FRIEND };
20.371429
56
0.758766
[ "vector" ]
4c37a3d558c9344bc57c42bcfd2a60770f754d6d
1,316
h
C
src/CMPI/providers/Person/Link_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/CMPI/providers/Person/Link_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/CMPI/providers/Person/Link_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
//============================================================================== // // PLEASE DO NOT EDIT THIS FILE; IT WAS AUTOMATICALLY GENEARTED BY GENPROV // //============================================================================== #ifndef _Link_Provider_h #define _Link_Provider_h #include <cimple/cimple.h> #include "Link.h" CIMPLE_NAMESPACE_BEGIN class Link_Provider { public: typedef Link Class; Link_Provider(); CIMPLE_HIDE ~Link_Provider(); CIMPLE_HIDE Load_Status load(); CIMPLE_HIDE Unload_Status unload(); CIMPLE_HIDE Timer_Status timer(uint64& timeout_msec); CIMPLE_HIDE Get_Instance_Status get_instance( const Link* model, Link*& instance); CIMPLE_HIDE Enum_Instances_Status enum_instances( const Link* model, Enum_Instances_Handler<Link>* handler); CIMPLE_HIDE Create_Instance_Status create_instance( const Link* instance); CIMPLE_HIDE Delete_Instance_Status delete_instance( const Link* instance); CIMPLE_HIDE Modify_Instance_Status modify_instance( const Link* instance); static CIMPLE_HIDE int proc( int operation, void* arg0, void* arg1, void* arg2, void* arg3); private: Instance_Map<Link> _map; }; CIMPLE_NAMESPACE_END #endif /* _Link_Provider_h */
22.305085
80
0.629179
[ "model" ]
4c3f5d0372489e8260b9cb81293f81a1c9cf1ea7
1,117
h
C
api/mason/thread_pool.h
ROTARTSI82/Mason
ee5dccc51b2b36288b4115d55b65106cf16ebb58
[ "Apache-2.0" ]
null
null
null
api/mason/thread_pool.h
ROTARTSI82/Mason
ee5dccc51b2b36288b4115d55b65106cf16ebb58
[ "Apache-2.0" ]
null
null
null
api/mason/thread_pool.h
ROTARTSI82/Mason
ee5dccc51b2b36288b4115d55b65106cf16ebb58
[ "Apache-2.0" ]
null
null
null
// // Created by 25granty on 10/12/19. // #pragma once #ifndef __MASON_THREAD_POOL_H #define __MASON_THREAD_POOL_H #include <queue> #include <vector> #include <thread> #include <future> #include "mason/log.h" namespace mason { class thread_pool; struct __MASON_THREAD_POOL_TASK { std::packaged_task<void *(thread_pool *, void *)> func; void *dat; }; class thread_pool { private: static void worker_func(thread_pool *parent); public: constexpr static double thread_mult = 1.0; std::vector<std::thread *> workers; std::queue<__MASON_THREAD_POOL_TASK> tasks; std::mutex task_mutex; volatile bool is_running = false; thread_pool() = default; ~thread_pool(); void push_task(std::packaged_task<void *(thread_pool *, void *)> task, void *usr_dat); void add_worker(); // // // This will block until the task the worker is executing is finished. // void remove_worker(); void start(unsigned limit = 0); void stop(); }; } #endif //__MASON_THREAD_POOL_H
18.932203
94
0.631155
[ "vector" ]
4c465f80979fd5184fb2a7aa6e964d9fd748af49
16,093
c
C
sm64ex-nightly/src/game/behaviors/wiggler.inc.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
2
2022-03-12T08:27:53.000Z
2022-03-12T18:26:06.000Z
src/game/behaviors/wiggler.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
src/game/behaviors/wiggler.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
/** * Behavior for bhvWigglerHead and bhvWigglerBody. * The bhvWigglerHead object controls the wiggler's behavior, and physically manifests * as the wiggler's head. The bhvWigglerBody objects represent the 3 tail body * parts, numbered 1 closest to the head, and 3 at the end of the tail. * Processing order is bhvWigglerHead, then bhvWigglerBody 1, 2, then 3. */ /** * Hitbox for wiggler's non-head body parts. */ static struct ObjectHitbox sWigglerBodyPartHitbox = { /* interactType: */ INTERACT_BOUNCE_TOP, /* downOffset: */ 0, /* damageOrCoinValue: */ 3, /* health: */ 99, // never decreases /* numLootCoins: */ 0, /* radius: */ 20, /* height: */ 20, /* hurtboxRadius: */ 20, /* hurtboxHeight: */ 10, }; /** * Hitbox for wiggler's head. */ static struct ObjectHitbox sWigglerHitbox = { /* interactType: */ INTERACT_BOUNCE_TOP, /* downOffset: */ 0, /* damageOrCoinValue: */ 3, /* health: */ 4, /* numLootCoins: */ 0, /* radius: */ 60, /* height: */ 50, /* hurtboxRadius: */ 30, /* hurtboxHeight: */ 40, }; /** * Attack handler for wiggler while in the walking action. */ static u8 sWigglerAttackHandlers[] = { /* ATTACK_PUNCH: */ ATTACK_HANDLER_KNOCKBACK, /* ATTACK_KICK_OR_TRIP: */ ATTACK_HANDLER_KNOCKBACK, /* ATTACK_FROM_ABOVE: */ ATTACK_HANDLER_SPECIAL_WIGGLER_JUMPED_ON, /* ATTACK_GROUND_POUND_OR_TWIRL: */ ATTACK_HANDLER_SPECIAL_WIGGLER_JUMPED_ON, /* ATTACK_FAST_ATTACK: */ ATTACK_HANDLER_KNOCKBACK, /* ATTACK_FROM_BELOW: */ ATTACK_HANDLER_KNOCKBACK, }; /** * Target speed while walking when wiggler has health 1, 2, 3, and 4. */ static f32 sWigglerSpeeds[] = { 2.0f, 40.0f, 30.0f, 16.0f }; /** * Update function for bhvWigglerBody. * Set object position and angle based on wiggler segment data and avoid falling * through the floor. * Tangible if the wiggler is not in the shrinking action, but does nothing on * attack. */ void bhv_wiggler_body_part_update(void) { f32 dx; f32 dy; f32 dz; f32 dxz; struct ChainSegment *segment = &o->parentObj->oWigglerSegments[o->oBehParams2ndByte]; f32 posOffset; cur_obj_scale(o->parentObj->header.gfx.scale[0]); o->oFaceAnglePitch = segment->pitch; o->oFaceAngleYaw = segment->yaw; // TODO: What is this for? posOffset = -37.5f * o->header.gfx.scale[0]; dy = posOffset * coss(o->oFaceAnglePitch) - posOffset; dxz = posOffset * sins(o->oFaceAnglePitch); dx = dxz * sins(o->oFaceAngleYaw); dz = dxz * coss(o->oFaceAngleYaw); o->oPosX = segment->posX + dx; o->oPosY = segment->posY + dy; o->oPosZ = segment->posZ + dz; if (o->oPosY < o->parentObj->oWigglerFallThroughFloorsHeight) { //! Since position is recomputed each frame, tilting the wiggler up // while on the ground could cause the tail segments to clip through // the floor o->oPosY += -30.0f; cur_obj_update_floor_height(); if (o->oFloorHeight > o->oPosY) // TODO: Check ineq swap { o->oPosY = o->oFloorHeight; } } segment->posY = o->oPosY; // Inherit walking animation speed from wiggler cur_obj_init_animation_with_accel_and_sound(0, o->parentObj->oWigglerWalkAnimSpeed); if (o->parentObj->oWigglerWalkAnimSpeed == 0.0f) { cur_obj_reverse_animation(); } if (o->parentObj->oAction == WIGGLER_ACT_SHRINK) { cur_obj_become_intangible(); } else { obj_check_attacks(&sWigglerBodyPartHitbox, o->oAction); } } /** * Initialize the segment data and spawn the body part objects. */ void wiggler_init_segments(void) { s32 i; struct ChainSegment *segments; struct Object *bodyPart; segments = mem_pool_alloc(gObjectMemoryPool, 4 * sizeof(struct ChainSegment)); if (segments != NULL) { // Each segment represents the global position and orientation of each // object. Segment 0 represents the wiggler's head, and segment i>0 // represents body part i. o->oWigglerSegments = segments; for (i = 0; i <= 3; i++) { chain_segment_init(segments + i); (segments + i)->posX = o->oPosX; (segments + i)->posY = o->oPosY; (segments + i)->posZ = o->oPosZ; (segments + i)->pitch = o->oFaceAnglePitch; (segments + i)->yaw = o->oFaceAngleYaw; } o->header.gfx.unk38.animFrame = -1; // Spawn each body part for (i = 1; i <= 3; i++) { bodyPart = spawn_object_relative(i, 0, 0, 0, o, MODEL_WIGGLER_BODY, bhvWigglerBody); if (bodyPart != NULL) { obj_init_animation_with_sound(bodyPart, wiggler_seg5_anims_0500C874, 0); bodyPart->header.gfx.unk38.animFrame = (23 * i) % 26 - 1; } } o->oAction = WIGGLER_ACT_WALK; cur_obj_unhide(); } #if defined(VERSION_EU) || defined(AVOID_UB) o->oHealth = 4; // This fixes Wiggler reading UB on his first frame of his acceleration, as his health is not set. #endif } /** * Update the tail to reflect changes in the head's yaw and pitch, and ensure * that the distance between parts is exactly the intended distance. * Since these positions are completely recomputed each frame, it is not possible * for a body part to get stuck on geometry and separate from the rest of the * body. */ void wiggler_update_segments(void) { struct ChainSegment *prevBodyPart; struct ChainSegment *bodyPart; f32 dx; f32 dy; f32 dz; s16 dpitch; s16 dyaw; f32 dxz; s32 i; f32 segmentLength; segmentLength = 35.0f * o->header.gfx.scale[0]; for (i = 1; i <= 3; i++) { prevBodyPart = &o->oWigglerSegments[i - 1]; bodyPart = &o->oWigglerSegments[i]; dx = bodyPart->posX - prevBodyPart->posX; dy = bodyPart->posY - prevBodyPart->posY; dz = bodyPart->posZ - prevBodyPart->posZ; // As the head turns, propagate this rotation backward if the difference // is more than 45 degrees dyaw = atan2s(-dz, -dx) - prevBodyPart->yaw; clamp_s16(&dyaw, -0x2000, 0x2000); bodyPart->yaw = prevBodyPart->yaw + dyaw; // As the head tilts, propagate the tilt backward dxz = sqrtf(dx * dx + dz * dz); dpitch = atan2s(dxz, dy) - prevBodyPart->pitch; clamp_s16(&dpitch, -0x2000, 0x2000); bodyPart->pitch = prevBodyPart->pitch + dpitch; // Set the body part's position relative to the previous body part's // position, using the current body part's angles. This means that the // head can rotate up to 45 degrees without the body moving bodyPart->posY = segmentLength * sins(bodyPart->pitch) + prevBodyPart->posY; dxz = segmentLength * coss(bodyPart->pitch); bodyPart->posX = prevBodyPart->posX - dxz * sins(bodyPart->yaw); bodyPart->posZ = prevBodyPart->posZ - dxz * coss(bodyPart->yaw); } } /** * Show text if necessary. Then walk toward mario if not at full health, and * otherwise wander in random directions. * If attacked by mario, enter either the jumped on or knockback action. */ static void wiggler_act_walk(void) { s16 yawTurnSpeed; o->oWigglerWalkAnimSpeed = 0.06f * o->oForwardVel; // Update text if necessary if (o->oWigglerTextStatus < WIGGLER_TEXT_STATUS_COMPLETED_DIALOG) { if (o->oWigglerTextStatus == WIGGLER_TEXT_STATUS_AWAIT_DIALOG) { func_8031FFB4(SEQ_PLAYER_LEVEL, 60, 40); o->oWigglerTextStatus = WIGGLER_TEXT_STATUS_SHOWING_DIALOG; } // If Mario is positioned below the wiggler, assume he entered through the // lower cave entrance, so don't display text. if (gMarioObject->oPosY < o->oPosY || cur_obj_update_dialog_with_cutscene(2, 0, CUTSCENE_DIALOG, DIALOG_150) != 0) { o->oWigglerTextStatus = WIGGLER_TEXT_STATUS_COMPLETED_DIALOG; } } else { //! Every object's health is initially 2048, and wiggler's doesn't change // to 4 until after this runs the first time. It indexes out of bounds // and uses the value 113762.3 for one frame on US. This is fixed up // in wiggler_init_segments if AVOID_UB is defined. obj_forward_vel_approach(sWigglerSpeeds[o->oHealth - 1], 1.0f); if (o->oWigglerWalkAwayFromWallTimer != 0) { o->oWigglerWalkAwayFromWallTimer -= 1; } else { if (o->oDistanceToMario >= 25000.0f) { // If >1200 away from home, turn to home o->oWigglerTargetYaw = o->oAngleToMario; } if (obj_bounce_off_walls_edges_objects(&o->oWigglerTargetYaw)) { //! If the wiggler could self-intersect, or intersect a different // non-mario object, this could potentially be used to force // the wiggler to walk straight - past his usual radius o->oWigglerWalkAwayFromWallTimer = random_linear_offset(30, 30); } else { if (o->oHealth < 4) { o->oWigglerTargetYaw = o->oAngleToMario; } else if (o->oWigglerTimeUntilRandomTurn != 0) { o->oWigglerTimeUntilRandomTurn -= 1; } else { o->oWigglerTargetYaw = o->oMoveAngleYaw + 0x4000 * (s16) random_sign(); o->oWigglerTimeUntilRandomTurn = random_linear_offset(30, 50); } } } // If moving at high speeds, could overflow. But can't reach such speeds // in practice yawTurnSpeed = (s16)(30.0f * o->oForwardVel); cur_obj_rotate_yaw_toward(o->oWigglerTargetYaw, yawTurnSpeed); obj_face_yaw_approach(o->oMoveAngleYaw, 2 * yawTurnSpeed); obj_face_pitch_approach(0, 0x320); // For the first two seconds of walking, stay invulnerable if (o->oTimer < 60) { obj_check_attacks(&sWigglerHitbox, o->oAction); } else if (obj_handle_attacks(&sWigglerHitbox, o->oAction, sWigglerAttackHandlers)) { if (o->oAction != WIGGLER_ACT_JUMPED_ON) { o->oAction = WIGGLER_ACT_KNOCKBACK; } o->oWigglerWalkAwayFromWallTimer = 0; o->oWigglerWalkAnimSpeed = 0.0f; } } } /** * Squish and unsquish, then show text and enter either the walking or shrinking * action. */ static void wiggler_act_jumped_on(void) { // Text to show on first, second, and third attack. s32 attackText[3] = { DIALOG_152, DIALOG_168, DIALOG_151 }; // Shrink until the squish speed becomes 0, then unisquish if (approach_f32_ptr(&o->oWigglerSquishSpeed, 0.0f, 0.05f)) { // Note that 4 is the default scale approach_f32_ptr(&o->header.gfx.scale[1], 4.0f, 0.2f); } else { o->header.gfx.scale[1] -= o->oWigglerSquishSpeed; } // Wait for a second after unsquishing, then show text and either shrink (if // defeated) or go back to walking if (o->header.gfx.scale[1] >= 4.0f) { if (o->oTimer > 30) { if (cur_obj_update_dialog_with_cutscene(2, 0, CUTSCENE_DIALOG, attackText[o->oHealth - 2]) != 0) { // Because we don't want the wiggler to disappear after being // defeated, we leave its health at 1 if (--o->oHealth == 1) { o->oAction = WIGGLER_ACT_SHRINK; cur_obj_become_intangible(); } else { o->oAction = WIGGLER_ACT_WALK; o->oMoveAngleYaw = o->oFaceAngleYaw; if (o->oHealth == 2) { cur_obj_play_sound_2(SOUND_OBJ_WIGGLER_JUMP); o->oForwardVel = 10.0f; o->oVelY = 70.0f; } } } } } else { o->oTimer = 0; } obj_check_attacks(&sWigglerHitbox, o->oAction); } /** * Decelerate to a stop and then enter the walk action. */ static void wiggler_act_knockback(void) { if (o->oVelY > 0.0f) { o->oFaceAnglePitch -= o->oVelY * 30.0f; } else { obj_face_pitch_approach(0, 0x190); } if (obj_forward_vel_approach(0.0f, 1.0f) && o->oFaceAnglePitch == 0) { o->oAction = WIGGLER_ACT_WALK; o->oMoveAngleYaw = o->oFaceAngleYaw; } obj_check_attacks(&sWigglerHitbox, o->oAction); } /** * Shrink, then spawn the star and enter the fall through floor action. */ static void wiggler_act_shrink(void) { if (o->oTimer >= 20) { if (o->oTimer == 20) { cur_obj_play_sound_2(SOUND_OBJ_ENEMY_DEFEAT_SHRINK); } // 4 is the default scale, so shrink to 1/4 of regular size if (approach_f32_ptr(&o->header.gfx.scale[0], 1.0f, 0.1f)) { spawn_default_star(0.0f, 2048.0f, 0.0f); o->oAction = WIGGLER_ACT_FALL_THROUGH_FLOOR; } cur_obj_scale(o->header.gfx.scale[0]); } } /** * Fall through floors until y < 1700, then enter the walking action. */ static void wiggler_act_fall_through_floor(void) { if (o->oTimer == 60) { stop_background_music(SEQUENCE_ARGS(4, SEQ_EVENT_BOSS)); o->oWigglerFallThroughFloorsHeight = 1700.0f; } else if (o->oTimer > 60) { if (o->oPosY < o->oWigglerFallThroughFloorsHeight) { o->oAction = WIGGLER_ACT_WALK; } else { o->oFaceAnglePitch = obj_get_pitch_from_vel(); } cur_obj_move_using_fvel_and_gravity(); } } /** * Attack handler for when wiggler is jumped or ground pounded on. * Stop and enter the jumped on action. */ void wiggler_jumped_on_attack_handler(void) { cur_obj_play_sound_2(SOUND_OBJ_WIGGLER_ATTACKED); o->oAction = WIGGLER_ACT_JUMPED_ON; o->oForwardVel = o->oVelY = 0.0f; o->oWigglerSquishSpeed = 0.4f; } /** * Update function for bhvWigglerHead. */ void bhv_wiggler_update(void) { // PARTIAL_UPDATE if (o->oAction == WIGGLER_ACT_UNINITIALIZED) { wiggler_init_segments(); } else { if (o->oAction == WIGGLER_ACT_FALL_THROUGH_FLOOR) { wiggler_act_fall_through_floor(); } else { treat_far_home_as_mario(1200.0f); // Walking animation and sound cur_obj_init_animation_with_accel_and_sound(0, o->oWigglerWalkAnimSpeed); if (o->oWigglerWalkAnimSpeed != 0.0f) { cur_obj_play_sound_at_anim_range(0, 13, o->oHealth >= 4 ? SOUND_OBJ_WIGGLER_LOW_PITCH : SOUND_OBJ_WIGGLER_HIGH_PITCH); } else { cur_obj_reverse_animation(); } cur_obj_update_floor_and_walls(); switch (o->oAction) { case WIGGLER_ACT_WALK: wiggler_act_walk(); break; case WIGGLER_ACT_KNOCKBACK: wiggler_act_knockback(); break; case WIGGLER_ACT_JUMPED_ON: wiggler_act_jumped_on(); break; case WIGGLER_ACT_SHRINK: wiggler_act_shrink(); break; case WIGGLER_ACT_FALL_THROUGH_FLOOR: wiggler_act_fall_through_floor(); break; } cur_obj_move_standard(-78); } // Update segment 0 with data from the wiggler object o->oWigglerSegments[0].posX = o->oPosX; o->oWigglerSegments[0].posY = o->oPosY; o->oWigglerSegments[0].posZ = o->oPosZ; o->oWigglerSegments[0].pitch = o->oFaceAnglePitch; o->oWigglerSegments[0].yaw = o->oFaceAngleYaw; // Update the rest of the segments to follow segment 0 wiggler_update_segments(); } }
35.447137
124
0.602622
[ "geometry", "object" ]
4c5c157341ceee21512e3dcc8e27d7aa00825596
3,722
h
C
source/gameengine/Rasterizer/RAS_TexVert.h
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/gameengine/Rasterizer/RAS_TexVert.h
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/gameengine/Rasterizer/RAS_TexVert.h
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: RAS_TexVert.h 35072 2011-02-22 12:42:55Z jesterking $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file RAS_TexVert.h * \ingroup bgerast */ #ifndef __RAS_TEXVERT #define __RAS_TEXVERT #include "MT_Point3.h" #include "MT_Point2.h" #include "MT_Transform.h" #ifdef WITH_CXX_GUARDEDALLOC #include "MEM_guardedalloc.h" #endif static MT_Point3 g_pt3; static MT_Point2 g_pt2; class RAS_TexVert { float m_localxyz[3]; // 3*4 = 12 float m_uv1[2]; // 2*4 = 8 float m_uv2[2]; // 2*4 = 8 unsigned int m_rgba; // 4 float m_tangent[4]; // 4*4 = 16 float m_normal[3]; // 3*4 = 12 short m_flag; // 2 short m_softBodyIndex; //2 unsigned int m_unit; // 4 unsigned int m_origindex; // 4 //--------- // 56+6+8+2=72 // 32 bytes total size, fits nice = 56 = not fit nice. public: enum { FLAT = 1, SECOND_UV = 2, MAX_UNIT = 8 }; short getFlag() const; unsigned int getUnit() const; RAS_TexVert()// :m_xyz(0,0,0),m_uv(0,0),m_rgba(0) {} RAS_TexVert(const MT_Point3& xyz, const MT_Point2& uv, const MT_Point2& uv2, const MT_Vector4& tangent, const unsigned int rgba, const MT_Vector3& normal, const bool flat, const unsigned int origindex); ~RAS_TexVert() {}; const float* getUV1 () const { return m_uv1; }; const float* getUV2 () const { return m_uv2; }; const float* getXYZ() const { return m_localxyz; }; const float* getNormal() const { return m_normal; } short int getSoftBodyIndex() const { return m_softBodyIndex; } void setSoftBodyIndex(short int sbIndex) { m_softBodyIndex = sbIndex; } const float* getTangent() const { return m_tangent; } const unsigned char* getRGBA() const { return (unsigned char *) &m_rgba; } unsigned int getOrigIndex() const { return m_origindex; } void SetXYZ(const MT_Point3& xyz); void SetXYZ(const float *xyz); void SetUV(const MT_Point2& uv); void SetUV2(const MT_Point2& uv); void SetRGBA(const unsigned int rgba); void SetNormal(const MT_Vector3& normal); void SetTangent(const MT_Vector3& tangent); void SetFlag(const short flag); void SetUnit(const unsigned u); void SetRGBA(const MT_Vector4& rgba); const MT_Point3& xyz(); void Transform(const class MT_Matrix4x4& mat, const class MT_Matrix4x4& nmat); // compare two vertices, to test if they can be shared, used for // splitting up based on uv's, colors, etc bool closeTo(const RAS_TexVert* other); #ifdef WITH_CXX_GUARDEDALLOC public: void *operator new(size_t num_bytes) { return MEM_mallocN(num_bytes, "GE:RAS_TexVert"); } void operator delete( void *mem ) { MEM_freeN(mem); } #endif }; #endif //__RAS_TEXVERT
23.858974
90
0.668995
[ "transform" ]
4c60e43164d2ef924f3bb36a80de0047917b93b4
32,308
h
C
Visual Mercutio/zBaseLib/PSS_Edit.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zBaseLib/PSS_Edit.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zBaseLib/PSS_Edit.h
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_Edit ------------------------------------------------------------* **************************************************************************** * Description : Provides several edit components * * Developer : Processsoft * ****************************************************************************/ #ifndef PSS_EditH #define PSS_EditH // change the definition of AFX_EXT... to make it import #undef AFX_EXT_CLASS #undef AFX_EXT_API #undef AFX_EXT_DATA #define AFX_EXT_CLASS AFX_CLASS_IMPORT #define AFX_EXT_API AFX_API_IMPORT #define AFX_EXT_DATA AFX_DATA_IMPORT // processsoft #include "PSS_FieldRepository.h" #include "PSS_MaskEditBase.h" #include "PSS_GridCtrl.h" #include "PSS_DragEdit.h" #include "PSS_IntelliEdit.h" #include "PSS_SpecialHelpWnd.h" // class name mapping #ifndef PSS_Document #define PSS_Document ZDDocument #endif // forward classes declaration class PSS_Document; #ifdef _ZBASELIBEXPORT // put the values back to make AFX_EXT_CLASS export again #undef AFX_EXT_CLASS #undef AFX_EXT_API #undef AFX_EXT_DATA #define AFX_EXT_CLASS AFX_CLASS_EXPORT #define AFX_EXT_API AFX_API_EXPORT #define AFX_EXT_DATA AFX_DATA_EXPORT #endif /** * Basic edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_Edit { public: PSS_Edit(); virtual ~PSS_Edit(); /** * Pre-creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void PreCreateEdit(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE) = 0; /** * Checks the edit bounds *@param pDC - device context *@param pParentWnd - parent window *@param rect - rect to check *@return the edit bounds rect */ virtual CRect CheckBounds(CDC* pDC, CWnd *pParentWnd, const CRect& rct); /** * Gets the specialized help functions *@return the specialized help functions */ virtual inline PSS_SpecialHelpWnd* GetSpecialHelp() const; /** * Gets the client rect *@param[out] rect - client rect */ virtual inline void GetClientRect(CRect& Rect) const; /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Sets content is modified flag *@param modify - if TRUE, the content will be set as modified */ virtual inline void SetModify(BOOL modify); /** * Sets the go to next edit flag *@param next - if TRUE, the focus will be set to next available edit on exit */ virtual inline void SetGoNext(BOOL next); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit resources */ virtual void DestroyEdit(); protected: CWnd* m_pParentWnd; PSS_SpecialHelpWnd* m_pSpecialHelp; PSS_PlanFinObject* m_pEditedObj; PSS_Document* m_pDoc; PSS_FieldRepository* m_pFieldRepository; CRect m_Rect; BOOL m_Save; BOOL m_GoNext; BOOL m_AutoCalculateOption; BOOL m_GoNextEditOption; BOOL m_ReadOnly; BOOL m_IsSorted; /** * Gets the value array *@return the value array */ virtual CStringArray* GetArrayOfValues(); /** * Adds string to historic *@param str - string to add */ virtual void AddToHistoric(const CString& str); /** * Loads combobox from historic *@param combobox - combobox to populate with historic */ virtual void LoadFromHistoric(CComboBox& combobox); private: /** * Creates the specialized help functions *@param designer - if TRUE, edit is opened in designer mode */ void CreateSpecialHelp(BOOL designer = FALSE); }; //--------------------------------------------------------------------------- // PSS_Edit //--------------------------------------------------------------------------- PSS_SpecialHelpWnd* PSS_Edit::GetSpecialHelp() const { return m_pSpecialHelp; } //--------------------------------------------------------------------------- void PSS_Edit::GetClientRect(CRect& Rect) const { Rect = m_Rect; } //--------------------------------------------------------------------------- BOOL PSS_Edit::IsWindowVisible() { return FALSE; } //--------------------------------------------------------------------------- void PSS_Edit::SetModify(BOOL modify) { m_Save = modify; } //--------------------------------------------------------------------------- void PSS_Edit::SetGoNext(BOOL next) { m_GoNext = next; } //--------------------------------------------------------------------------- /** * String edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_StrEdit : public PSS_DragEdit, public PSS_Edit { public: /** * Constructor *@param multiline - if TRUE, the edit component will support the multiline *@param maxChar - maximum allowed chars, infinite if -1 */ PSS_StrEdit(BOOL multiLine = FALSE, int maxChar = -1); virtual ~PSS_StrEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_StrEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_MaxChar; BOOL m_MultiLine; }; //--------------------------------------------------------------------------- // PSS_StrEdit //--------------------------------------------------------------------------- BOOL PSS_StrEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_DragEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_StrEdit::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_DragEdit::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Numeric edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_NumEdit : public PSS_DragEdit, public PSS_Edit { public: PSS_NumEdit(); virtual ~PSS_NumEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_NumEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //--------------------------------------------------------------------------- // PSS_NumEdit //--------------------------------------------------------------------------- BOOL PSS_NumEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_DragEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_NumEdit::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_DragEdit::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Calculation edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_CalcEdit : public PSS_DragEdit, public PSS_Edit { public: PSS_CalcEdit(); virtual ~PSS_CalcEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: // Generated message map functions //{{AFX_MSG(PSS_CalcEdit) afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //--------------------------------------------------------------------------- // PSS_CalcEdit //--------------------------------------------------------------------------- BOOL PSS_CalcEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_DragEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_CalcEdit::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_DragEdit::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Time edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_TimeEdit : public PSS_DragEdit, public PSS_Edit { public: PSS_TimeEdit(); virtual ~PSS_TimeEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_TimeEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //--------------------------------------------------------------------------- // PSS_TimeEdit //--------------------------------------------------------------------------- BOOL PSS_TimeEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_DragEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_TimeEdit::MapWindowPoints(CWnd* pwndTo, LPRECT lpRect) { PSS_DragEdit::MapWindowPoints(pwndTo, lpRect); } //--------------------------------------------------------------------------- /** * Historic edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_StrEditHistoric : public PSS_IntelliEdit, public PSS_Edit { public: /** * Constructor *@param maxChar - maximum allowed chars, infinite if -1 */ PSS_StrEditHistoric(int maxChar = -1); virtual ~PSS_StrEditHistoric(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets the maximum char *@return the maximum char */ virtual inline int GetMaxChar() const; /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_StrEditHistoric) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_MaxChar; }; //--------------------------------------------------------------------------- // PSS_StrEditHistoric //--------------------------------------------------------------------------- int PSS_StrEditHistoric::GetMaxChar() const { return m_MaxChar; } //--------------------------------------------------------------------------- BOOL PSS_StrEditHistoric::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_IntelliEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_StrEditHistoric::MapWindowPoints(CWnd* pwndTo, LPRECT lpRect) { PSS_IntelliEdit::MapWindowPoints(pwndTo, lpRect); } //--------------------------------------------------------------------------- /** * Numeric historic edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_NumEditHistoric : public PSS_IntelliEdit, public PSS_Edit { public: PSS_NumEditHistoric(); virtual ~PSS_NumEditHistoric(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_NumEditHistoric) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //--------------------------------------------------------------------------- // PSS_NumEditHistoric //--------------------------------------------------------------------------- BOOL PSS_NumEditHistoric::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_IntelliEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_NumEditHistoric::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_IntelliEdit::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Field name edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_FieldNameEdit : public PSS_IntelliEdit, public PSS_Edit { public: /** * Constructor *@param maxChar - maximum allowed chars, infinite if -1 */ PSS_FieldNameEdit(int maxChar = -1); virtual ~PSS_FieldNameEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_FieldNameEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_MaxChar; }; //--------------------------------------------------------------------------- // PSS_FieldNameEdit //--------------------------------------------------------------------------- BOOL PSS_FieldNameEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_IntelliEdit::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_FieldNameEdit::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_IntelliEdit::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Mask edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_MaskEdit : public PSS_MaskEditBase, public PSS_Edit { public: PSS_MaskEdit(); virtual ~PSS_MaskEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); protected: /// Generated message map functions //{{AFX_MSG(PSS_MaskEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //--------------------------------------------------------------------------- // PSS_MaskEdit //--------------------------------------------------------------------------- BOOL PSS_MaskEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_MaskEditBase::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_MaskEdit::MapWindowPoints(CWnd* pWndTo, LPRECT pRect) { PSS_MaskEditBase::MapWindowPoints(pWndTo, pRect); } //--------------------------------------------------------------------------- /** * Multi-coluns edit component *@author Dominique Aigroz, Jean-Milost Reymond */ class AFX_EXT_CLASS PSS_MultiColumnEdit : public PSS_GridCtrl, public PSS_Edit { public: PSS_MultiColumnEdit(); virtual ~PSS_MultiColumnEdit(); /** * Creates the edit *@param designerMode - if TRUE, the edit will be created in designer mode *@param pParentWnd - parent window *@param pDC - device context to draw to *@param pDoc - document *@param pEditedObj - edited object *@param pFieldRepository - field repository, can be NULL *@param autoCalculateOption - if TRUE, the options will be auto-calculated *@param goNextEditOption - if TRUE, the focus will be set to next available edit on exit */ virtual void Create(BOOL designerMode, CWnd* pParentWnd, CDC* pDC, PSS_Document* pDoc, PSS_PlanFinObject* pEditedObj, PSS_FieldRepository* pFieldRepository = NULL, BOOL autoCalculateOption = FALSE, BOOL goNextEditOption = FALSE); /** * Gets if window is visible *@return TRUE if window is visible, otherwise FALSE */ virtual inline BOOL IsWindowVisible(); /** * Maps the window points *@param pWndTo - window to point to *@param pRect - rect */ virtual inline void MapWindowPoints(CWnd* pWndTo, LPRECT pRect); /** * Destroys the edit */ virtual void DestroyEdit(); /** * Called before editing the cell *@param item - item *@param subItem - sub-item */ virtual void OnBeginLabelEdit(int item, int subItem); /** * Called after having updated the cell *@param pText - text *@param item - item *@param subItem - sub-item */ virtual void OnEndLabelEdit(LPCSTR pText, int item, int subItem); protected: /// Generated message map functions //{{AFX_MSG(PSS_MultiColumnEdit) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_Cx; BOOL m_Edit; BOOL m_ColumnsBuilt; bool m_StartEditCell; /** * Builds the columns */ void BuildColumns(); /** * Fills the control */ void FillControl(); }; //--------------------------------------------------------------------------- // PSS_MultiColumnEdit //--------------------------------------------------------------------------- BOOL PSS_MultiColumnEdit::IsWindowVisible() { return (::IsWindow(GetSafeHwnd()) && PSS_GridCtrl::IsWindowVisible()); } //--------------------------------------------------------------------------- void PSS_MultiColumnEdit::MapWindowPoints(CWnd* pwndTo, LPRECT lpRect) { PSS_GridCtrl::MapWindowPoints(pwndTo, lpRect); } //--------------------------------------------------------------------------- #endif
35.041215
96
0.501021
[ "object" ]
4c66568b817912acfa65af2ef7b1855ba17d9824
1,154
h
C
emulator/src/mame/machine/cat702.h
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/machine/cat702.h
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/machine/cat702.h
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:smf /* CAT702 security chip */ #ifndef MAME_MACHINE_CAT702_H #define MAME_MACHINE_CAT702_H #pragma once DECLARE_DEVICE_TYPE(CAT702, cat702_device) #define MCFG_CAT702_DATAOUT_HANDLER(_devcb) \ devcb = &downcast<cat702_device &>(*device).set_dataout_handler(DEVCB_##_devcb); class cat702_device : public device_t { public: cat702_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); // configuration helpers template <class Object> devcb_base &set_dataout_handler(Object &&cb) { return m_dataout_handler.set_callback(std::forward<Object>(cb)); } DECLARE_WRITE_LINE_MEMBER(write_select); DECLARE_WRITE_LINE_MEMBER(write_datain); DECLARE_WRITE_LINE_MEMBER(write_clock); protected: virtual void device_start() override; private: uint8_t compute_sbox_coef(int sel, int bit); void apply_bit_sbox(int sel); void apply_sbox(const uint8_t *sbox); optional_memory_region m_region; uint8_t m_transform[8]; int m_select; int m_clock; int m_datain; uint8_t m_state; uint8_t m_bit; devcb_write_line m_dataout_handler; }; #endif // MAME_MACHINE_CAT702_H
23.55102
138
0.792894
[ "object" ]
4c6b2f2832293814b8bb7341be3c80e636ec313d
6,600
h
C
src/gates/clifford_generators.h
Alan-Robertson/qecode
fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628
[ "MIT" ]
4
2018-03-07T06:15:32.000Z
2021-11-17T10:50:15.000Z
src/gates/clifford_generators.h
Alan-Robertson/qecode
fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628
[ "MIT" ]
null
null
null
src/gates/clifford_generators.h
Alan-Robertson/qecode
fc01e6f66a7fbe4f6b2bda6b3874fd6e5b10c628
[ "MIT" ]
null
null
null
#ifndef GATE_CLIFFORD_GENERATORS #define GATE_CLIFFORD_GENERATORS #include "gates.h" #include "gate_result.h" #include "../sym.h" #include "../error_models/error_models.h" // ---------------------------------------------------------------------------------------- // STRUCT OBJECTS // These aren't currently needed but are here for if they ever are // ---------------------------------------------------------------------------------------- // typedef struct {} gate_data_cnot_t; // typedef struct {} gate_data_hadamard_t; // typedef struct {} gate_data_phase_t; // typedef struct {} gate_data_identity_t; // ---------------------------------------------------------------------------------------- // FUNCTION DECLARATIONS // ---------------------------------------------------------------------------------------- /* * gate_cnot * Implements a cnot gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the control, [1] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_cnot(const sym* initial_state, const void* gate_data, const unsigned* target_qubits); /* * gate_hadamard * Implements a hadamard gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target qubit * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_hadamard(const sym* initial_state, const void* gate_data, const unsigned* target_qubit); /* * gate_phase * Implements a phase gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_phase(const sym* initial_state, const void* gate_data, const unsigned* target_qubit); /* * gate_identity * Implements an identity gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_identity(const sym* initial_state, const void* gate_data, const unsigned* target_qubits); // ---------------------------------------------------------------------------------------- // FUNCTION DEFINITIONS // ---------------------------------------------------------------------------------------- /* * gate_cnot * Implements a cnot gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the control, [1] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_cnot(const sym* initial_state, const void* gate_data, const unsigned* target_qubits) { sym* final_state = sym_copy(initial_state); uint32_t control = target_qubits[0]; uint32_t target = target_qubits[1]; sym_set_X(final_state, 0, target, sym_get_X(initial_state, 0, control) ^ sym_get_X(initial_state, 0, target)); sym_set_Z(final_state, 0, control, sym_get_Z(initial_state, 0, target) ^ sym_get_Z(initial_state, 0, control)); return gate_result_create_single(1, final_state); } /* * gate_hadamard * Implements a hadamard gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target qubit * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_hadamard(const sym* initial_state, const void* gate_data, const unsigned* target_qubit) { sym* final_state = sym_copy(initial_state); uint32_t target = target_qubit[0]; sym_set_X(final_state, 0, target, sym_get_Z(initial_state, 0, target)); sym_set_Z(final_state, 0, target, sym_get_X(initial_state, 0, target)); return gate_result_create_single(1, final_state);; } /* * gate_phase * Implements a phase gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_phase(const sym* initial_state, const void* gate_data, const unsigned* target_qubit) { sym* final_state = sym_copy(initial_state); uint32_t target = target_qubit[0]; sym_set_Z(final_state, 0, target, sym_get_Z(initial_state, 0, target) ^ sym_get_X(initial_state, 0, target)); return gate_result_create_single(1, final_state); } /* * gate_identity * Implements an identity gate on a sym object and returns the new sym object * :: const sym* initial state :: The state to apply the cnot to * :: const void* gate_data :: Any additional gate data that can be given to a gate (none needed here) * :: const unsigned* target_qubits :: An array of qubits that this gate acts on, [0] is the target * Returns a gate result object containing the new sym object as its only entry */ gate_result* gate_identity(const sym* initial_state, const void* gate_data, const unsigned* target_qubits) { sym* final_state = sym_copy(initial_state); return gate_result_create_single(1, final_state); } #endif
47.482014
120
0.676515
[ "object" ]
4c75ffdfedc6cfc123b60d9debef476fab21ddf4
8,326
h
C
Stardust/include/stardust/ai/graph/Pathfinding.h
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
7
2020-10-08T11:40:53.000Z
2022-03-30T10:40:06.000Z
Stardust/include/stardust/ai/graph/Pathfinding.h
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
1
2020-10-08T11:44:27.000Z
2020-12-01T08:43:19.000Z
Stardust/include/stardust/ai/graph/Pathfinding.h
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
null
null
null
#pragma once #ifndef STARDUST_PATHFINDING_H #define STARDUST_PATHFINDING_H #include <algorithm> #include <functional> #include <limits> #include "stardust/data/Containers.h" #include "stardust/data/Types.h" namespace stardust { namespace ai { template <typename T> [[nodiscard]] HashMap<T, f32> DijkstrasAlgorithm(const Graph<T>& graph, const T& rootNode) { if (!graph.HasNode(rootNode)) { return { }; } HashMap<T, f32> nodeDistances{ }; nodeDistances[rootNode] = 0.0f; constexpr auto NodeDistanceSorter = [](const Pair<T, f32>& lhs, const Pair<T, f32>& rhs) -> bool { return lhs.second > rhs.second; }; Vector<Pair<T, f32>> nodeQueue{ }; const auto allNodes = graph.GetNodes(); for (const auto& node : allNodes) { if (node != rootNode) { nodeDistances[node] = std::numeric_limits<f32>::infinity(); } nodeQueue.push_back({ node, nodeDistances[node] }); std::ranges::sort(nodeQueue, NodeDistanceSorter); } while (!nodeQueue.empty()) { const auto [currentNode, minDistance] = nodeQueue.back(); nodeQueue.pop_back(); const auto adjacentNodes = graph.GetEfficientAdjacentNodes(currentNode); for (const auto& [adjacentNode, distance] : adjacentNodes) { const f32 candidateDistance = nodeDistances[currentNode] + distance; if (candidateDistance < nodeDistances[adjacentNode]) { nodeDistances[adjacentNode] = candidateDistance; std::ranges::find_if(nodeQueue, [adjacentNode](const auto& nodePair) -> bool { return nodePair.first == adjacentNode; })->second = candidateDistance; std::ranges::sort(nodeQueue, NodeDistanceSorter); } } } return nodeDistances; } template <typename T> [[nodiscard]] Vector<T> DijkstrasAlgorithmSearch(const Graph<T>& graph, const T& rootNode, const T& goalNode) { if (!graph.HasNode(rootNode) || !graph.HasNode(goalNode)) { return { }; } HashMap<T, f32> nodeDistances{ }; nodeDistances[rootNode] = 0.0f; constexpr auto NodeDistanceSorter = [](const Pair<T, f32>& lhs, const Pair<T, f32>& rhs) -> bool { return lhs.second > rhs.second; }; HashMap<T, Optional<T>> predecessorNodes{ }; Vector<Pair<T, f32>> nodeQueue{ }; const auto allNodes = graph.GetNodes(); for (const auto& node : allNodes) { if (node != rootNode) { nodeDistances[node] = std::numeric_limits<f32>::infinity(); } predecessorNodes[node] = NullOpt; nodeQueue.push_back({ node, nodeDistances[node] }); std::ranges::sort(nodeQueue, NodeDistanceSorter); } bool wasNodeFound = false; while (!nodeQueue.empty()) { const auto [currentNode, minDistance] = nodeQueue.back(); nodeQueue.pop_back(); const auto adjacentNodes = graph.GetEfficientAdjacentNodes(currentNode); for (const auto& [adjacentNode, distance] : adjacentNodes) { const f32 candidateDistance = nodeDistances[currentNode] + distance; if (candidateDistance < nodeDistances[adjacentNode]) { nodeDistances[adjacentNode] = candidateDistance; predecessorNodes[adjacentNode] = currentNode; std::ranges::find_if(nodeQueue, [adjacentNode](const auto& nodePair) -> bool { return nodePair.first == adjacentNode; })->second = candidateDistance; std::ranges::sort(nodeQueue, NodeDistanceSorter); } } if (currentNode == goalNode && minDistance != std::numeric_limits<f32>::infinity()) { wasNodeFound = true; break; } } if (!wasNodeFound) { return { }; } Vector<T> traversedNodes{ }; Optional<T> currentNode = goalNode; while (currentNode.has_value()) { traversedNodes.push_back(currentNode.value()); currentNode = predecessorNodes[currentNode.value()]; } std::ranges::reverse(traversedNodes); return traversedNodes; } template <typename T> using HeuristicFunction = std::function<f32(const T&, const T&)>; template <typename T> [[nodiscard]] Vector<T> AStarSearch(const Graph<T>& graph, const T& rootNode, const T& goalNode, const HeuristicFunction<T>& heuristicFunction) { if (!graph.HasNode(rootNode) || !graph.HasNode(goalNode)) { return { }; } struct NodeScoreSorter { [[nodiscard]] inline bool operator ()(const Pair<T, f32>& lhs, const Pair<T, f32>& rhs) const noexcept { return lhs.second > rhs.second; } }; PriorityQueue<Pair<T, f32>, NodeScoreSorter> openSet{ }; HashSet<T> visitedNodes{ }; HashMap<T, Optional<T>> predecessorNodes{ }; HashMap<T, f32> fScores{ }; HashMap<T, f32> gScores{ }; fScores[rootNode] = heuristicFunction(rootNode, goalNode); gScores[rootNode] = 0.0f; const auto allNodes = graph.GetNodes(); for (const auto& node : allNodes) { if (node != rootNode) { fScores[node] = std::numeric_limits<f32>::infinity(); gScores[node] = std::numeric_limits<f32>::infinity(); } predecessorNodes[node] = NullOpt; } openSet.push({ rootNode, fScores[rootNode] }); bool wasNodeFound = false; while (!openSet.empty()) { const auto [currentNode, currentFScore] = openSet.top(); openSet.pop(); visitedNodes.insert(currentNode); if (currentNode == goalNode) { wasNodeFound = true; break; } const auto adjacentNodes = graph.GetEfficientAdjacentNodes(currentNode); for (const auto& [adjacentNode, distance] : adjacentNodes) { const f32 tentativeGScore = gScores[currentNode] + distance; if (tentativeGScore < gScores[adjacentNode]) { gScores[adjacentNode] = tentativeGScore; fScores[adjacentNode] = gScores[adjacentNode] + heuristicFunction(adjacentNode, goalNode); predecessorNodes[adjacentNode] = currentNode; if (!visitedNodes.contains(adjacentNode)) { openSet.push({ adjacentNode, fScores[adjacentNode] }); } } } } if (!wasNodeFound) { return { }; } Vector<T> traversedNodes{ }; Optional<T> currentNode = goalNode; while (currentNode.has_value()) { traversedNodes.push_back(currentNode.value()); currentNode = predecessorNodes[currentNode.value()]; } std::ranges::reverse(traversedNodes); return traversedNodes; } } } #endif
32.779528
173
0.498439
[ "vector" ]
4c76e9e5dc6b4280326365d826416ba303f99501
650
h
C
Sample16_5/app/src/main/cpp/bnggdh/Mat4.h
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
5
2020-11-20T00:06:30.000Z
2021-12-07T11:39:17.000Z
Sample16_5/app/src/main/cpp/bnggdh/Mat4.h
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
null
null
null
Sample16_5/app/src/main/cpp/bnggdh/Mat4.h
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
7
2021-01-01T10:54:58.000Z
2022-01-13T02:21:54.000Z
#ifndef _MAT4_H_ #define _MAT4_H_ #include "Vector3f.h" #include "Vector4f.h" class Mat4{ public: float* matrix; float* mulHelper; Mat4(); ~Mat4(); void loadIdentity(); void setTranslation(Vector3f* v); void genRotationFromEulerAngle(Vector3f* angles); Mat4* mul(Mat4* m1, Mat4* m2); void copyFrom(Mat4* m); void genRotateFromQuaternion(Vector4f* v); void invTransformAndRotate(Vector3f* point, Vector3f* v); void transform(Vector3f* point, Vector3f* v); void translate(float x, float y, float z); void rotate(float angle, float x, float y, float z); void scale(float x, float y, float z); static void print_matrix(Mat4 m); }; #endif
26
58
0.732308
[ "transform" ]
4c8067918cb0e25852503f512defe3993d736df0
555
h
C
mogupro/game/include/dessUI/UIs/CollisionUI/CollisionUI.h
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
mogupro/game/include/dessUI/UIs/CollisionUI/CollisionUI.h
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
mogupro/game/include/dessUI/UIs/CollisionUI/CollisionUI.h
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
#pragma once #include"../../UIBase.h" class CollisionUI : public UIBase { private: std::vector<EasingBuf> ease_collision_buf; public: CollisionUI(des::Vec2f _pos, des::Vec2f _size, des::Vec4d _color) :UIBase(_pos,_size,_color) { own_ui = UITYPE::CollisionUI; }; void animation(); void update(); bool collisionToUI(des::Vec2f _pos); bool collisionToUI(des::Vec2f _pos, des::Vec2f _size); void EaseCollisionApply(std::string start, float end[4], std::function<float(float, float, float)> ease, float time); void EaseCollisionUpdate(); };
23.125
118
0.722523
[ "vector" ]
4c818589dcc7cc88dfba7a94e40bb52d5f6bc3a2
1,758
h
C
Example/YQAdDemo/AdDemo/ThirdAdLibs/ChuanAD/BUFoundation.framework/Versions/A/Headers/NSArray+BUUtilities.h
xiaofu666/YQAdvertisement_SDK
d044d14a339a033c825ce4e9845c393bcae49985
[ "MIT" ]
2
2019-03-18T09:21:07.000Z
2019-04-01T02:08:07.000Z
Example/YQAdDemo/AdDemo/ThirdAdLibs/ChuanAD/BUFoundation.framework/Versions/A/Headers/NSArray+BUUtilities.h
xiaofu666/YQAdvertisement_SDK
d044d14a339a033c825ce4e9845c393bcae49985
[ "MIT" ]
null
null
null
Example/YQAdDemo/AdDemo/ThirdAdLibs/ChuanAD/BUFoundation.framework/Versions/A/Headers/NSArray+BUUtilities.h
xiaofu666/YQAdvertisement_SDK
d044d14a339a033c825ce4e9845c393bcae49985
[ "MIT" ]
1
2019-04-03T09:52:54.000Z
2019-04-03T09:52:54.000Z
// // NSMutableArray+Utilities.h // BUAdSDK // // Created by 李盛 on 2018/2/28. // Copyright © 2018年 bytedance. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSMutableArray (BU_Utilities) - (void)bu_safeAddObject:(id)object; - (void)bu_safeAddNilObject; - (void)bu_safeInsertObject:(id)object atIndex:(NSUInteger)index; - (void)bu_safeInsertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes; - (void)bu_safeRemoveObject:(id)object; - (nullable id)bu_objectAtIndexSafely:(NSUInteger)index; - (void)bu_removeObjectAtIndexSafely:(NSUInteger)index; @end @interface NSArray(BU_JSONValue) - (nullable NSString *)bu_JSONRepresentation:(NSError **)error; - (void)bu_forEachWithBlock:(void(^)(id item))block; - (void)bu_forEachWithIndexBlock:(void(^)(id item, NSInteger index))indexBlock; - (NSArray *)bu_mapWithBlock:(id(^)(id item))block; - (NSArray *)bu_mapWithIndexBlock:(id(^)(id item, NSInteger index))indexBlock; - (NSArray *)bu_filterWithConditionBlock:(BOOL(^)(id item))conditionBlock; - (NSArray *)bu_filterWithIndexConditionBlock:(BOOL(^)(id item, NSInteger index))indexConditionBlock; - (BOOL)bu_someWithConditionBlock:(BOOL(^)(id item))conditionBlock; - (BOOL)bu_someWithIndexConditionBlock:(BOOL(^)(id item, NSInteger index))indexConditionBlock; - (BOOL)bu_everyWithConditionBlock:(BOOL(^)(id item))conditionBlock; - (BOOL)bu_everyWithIndexConditionBlock:(BOOL(^)(id item, NSInteger index))indexConditionBlock; - (id)bu_reduceWithBlock:(id(^)(id item1, id item2))block initial:(id)initial; - (id)bu_findWithConditionBlock:(id(^)(id item))conditionBlock; - (id)bu_findWithIndexConditionBlock:(id(^)(id item, NSInteger index))indexConditionBlock; @end NS_ASSUME_NONNULL_END
29.79661
101
0.76678
[ "object" ]
4c828290865df17e5a42e12e392d1df7e3ca51f0
4,207
h
C
tests/minio.h
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
18
2018-01-31T02:47:39.000Z
2021-03-13T15:17:45.000Z
tests/minio.h
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
2
2017-12-03T08:05:40.000Z
2018-06-13T22:05:37.000Z
tests/minio.h
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <cerrno> #include "h5s3/private/utils.h" #include "process.h" namespace fs = std::experimental::filesystem; using process = h5s3::testing::process; class minio { private: std::string m_access_key; std::string m_secret_key; std::string m_test_bucket; std::string m_minio_address; std::string m_region; std::unique_ptr<process> m_minio_proc; fs::path m_minio_root; /** Create a new, unique, temporary directory. */ static fs::path temp_directory() { using namespace h5s3::utils; auto random_char = []() { auto options = "abcdefghijklmnopqrstuvwxyz0123456789"_array; return options[std::rand() % options.size()]; }; // generate a possible temporary directory path auto generate_candidate = [&]() { auto leaf = "h5s3-xxxxxx"_array; std::generate(std::next(leaf.begin(), 5), leaf.end(), random_char); return fs::temp_directory_path() / std::string(leaf.data(), leaf.size()); }; fs::path out; std::error_code ec; while (!fs::create_directory(out = generate_candidate(), ec)) { // The directory couldn't be created; this either means it already // exists or an error occurred. if (ec) { // An error occurred, throw the exception. throw std::runtime_error(ec.message()); } // No error occurred, this means the directory already exists, // try again. } return out; } public: minio() : m_access_key("TESTINGACCESSKEYXXXX"), m_secret_key("TESTINGSECRETKEYXXXXXXXXXXXXXXXXXXXXXXXX"), m_test_bucket("test-bucket"), m_minio_address("localhost:9999"), m_region("us-west-2"), m_minio_root(temp_directory()) { std::string minio_config = m_minio_root / "minio-config/"; // Start minio server. std::vector<std::string> args = { "testbin/minio", "server", "--quiet", "--config-dir", minio_config, "--address", m_minio_address, m_minio_root / "minio-data", }; process::environment env = { {"MINIO_ACCESS_KEY", m_access_key}, {"MINIO_SECRET_KEY", m_secret_key}, {"MINIO_REGION", m_region}, {"PATH", std::getenv("PATH")}, }; m_minio_proc = std::make_unique<process>(args, env); sleep(1); // Give it a second to come up. // Create a bucket with mc. std::string mc_config = m_minio_root / "mc-config"; auto mc_command = [&mc_config](const std::vector<std::string>& extra){ std::vector<std::string> argv = { "testbin/mc", "--quiet", "--config-folder", mc_config, }; argv.insert(argv.end(), extra.begin(), extra.end()); process::environment env = {{"PATH", std::getenv("PATH")}}; process proc(argv, env); auto result = proc.join(); if (result.code != 0) { throw std::runtime_error("failed to run mc"); } }; mc_command({"config", "host", "remove", "h5s3-testing"}); mc_command({"config", "host", "add", "h5s3-testing", "http://" + m_minio_address, m_access_key, m_secret_key}); mc_command({"mb", "--ignore-existing", "--region", m_region, "h5s3-testing/" + m_test_bucket}); } ~minio() { m_minio_proc->terminate(); m_minio_proc->join(); fs::remove_all(m_minio_root); } const std::string& region() const { return m_region; } const std::string& access_key() const { return m_access_key; } const std::string& secret_key() const { return m_secret_key; } const std::string& bucket() const { return m_test_bucket; } const std::string& address() const { return m_minio_address; } };
30.485507
79
0.542905
[ "vector" ]
4c85d4cf7f6e60502cd5f51782018db4d58bc911
85,984
c
C
vkrunner/vr-script.c
janesma/vkrunner
501009d322f7f0b2f56f261d6604a6fa5d5f27a8
[ "MIT" ]
36
2018-03-10T13:00:13.000Z
2021-12-27T06:24:54.000Z
vkrunner/vr-script.c
janesma/vkrunner
501009d322f7f0b2f56f261d6604a6fa5d5f27a8
[ "MIT" ]
66
2018-05-01T07:58:38.000Z
2020-12-22T14:03:25.000Z
vkrunner/vr-script.c
janesma/vkrunner
501009d322f7f0b2f56f261d6604a6fa5d5f27a8
[ "MIT" ]
8
2018-04-30T15:11:17.000Z
2020-07-08T19:22:37.000Z
/* * vkrunner * * Copyright (C) 2018 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <stdio.h> #include <string.h> #include <errno.h> #include <stdbool.h> #include <limits.h> #include <assert.h> #include <stdlib.h> #include "vr-script-private.h" #include "vr-list.h" #include "vr-util.h" #include "vr-buffer.h" #include "vr-error-message.h" #include "vr-window.h" #include "vr-format-private.h" #include "vr-source-private.h" #include "vr-tolerance.h" #include "vr-stream.h" #include "vr-char.h" #include "vr-hex.h" #define DEFAULT_TOLERANCE 0.01 enum section { SECTION_NONE, SECTION_COMMENT, SECTION_REQUIRE, SECTION_SHADER, SECTION_VERTEX_DATA, SECTION_INDICES, SECTION_TEST }; enum parse_result { /* The line is definitely intended to be for this command but * there was an error parsing it. */ PARSE_RESULT_ERROR, /* The command was successfully parsed */ PARSE_RESULT_OK, /* The line does not match the command handled by this * function, continue trying another command. */ PARSE_RESULT_NON_MATCHED, }; struct load_state { const struct vr_config *config; const struct vr_source *source; const char *filename; int line_num; struct vr_script *script; struct vr_buffer buffer; struct vr_buffer line; enum vr_shader_stage current_stage; enum vr_script_source_type current_source_type; enum section current_section; struct vr_buffer commands; struct vr_buffer pipeline_keys; struct vr_buffer buffers; struct vr_pipeline_key current_key; struct vr_buffer indices; float clear_color[4]; float clear_depth; unsigned clear_stencil; struct vr_tolerance tolerance; struct vr_box_layout push_layout; struct vr_box_layout ubo_layout; struct vr_box_layout ssbo_layout; int had_sections; }; typedef enum parse_result (* process_test_line_func)(struct load_state *data, const char *line); static const char * stage_names[VR_SHADER_STAGE_N_STAGES] = { "vertex", "tessellation control", "tessellation evaluation", "geometry", "fragment", "compute", }; static uint32_t vertex_shader_passthrough[] = { 0x07230203, 0x00010000, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, 0x00000000, 0x00000001, 0x0007000f, 0x00000000, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, 0x00000003, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00040047, 0x00000003, 0x0000000b, 0x00000000, 0x00020013, 0x00000004, 0x00030021, 0x00000005, 0x00000004, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008, 0x00000001, 0x00000007, 0x00040020, 0x00000009, 0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000002, 0x00000001, 0x0004003b, 0x00000009, 0x00000003, 0x00000003, 0x00050036, 0x00000004, 0x00000001, 0x00000000, 0x00000005, 0x000200f8, 0x0000000a, 0x0004003d, 0x00000007, 0x0000000b, 0x00000002, 0x0003003e, 0x00000003, 0x0000000b, 0x000100fd, 0x00010038 }; static const struct vr_box_layout default_push_layout = { .std = VR_BOX_LAYOUT_STD_430, .major = VR_BOX_MAJOR_AXIS_COLUMN }; static const struct vr_box_layout default_ubo_layout = { .std = VR_BOX_LAYOUT_STD_140, .major = VR_BOX_MAJOR_AXIS_COLUMN }; static const struct vr_box_layout default_ssbo_layout = { .std = VR_BOX_LAYOUT_STD_430, .major = VR_BOX_MAJOR_AXIS_COLUMN }; static void add_shader(struct vr_script *script, enum vr_shader_stage stage, enum vr_script_source_type source_type, size_t length, const char *source) { struct vr_script_shader *shader; shader = vr_alloc(sizeof *shader + length); shader->length = length; shader->source_type = source_type; memcpy(shader->source, source, length); vr_list_insert(script->stages[stage].prev, &shader->link); } static bool end_shader(struct load_state *data) { add_shader(data->script, data->current_stage, data->current_source_type, data->buffer.length, (const char *) data->buffer.data); return true; } static bool end_vertex_data(struct load_state *data) { data->script->vertex_data = vr_vbo_parse(data->config, (const char *) data->buffer.data, data->buffer.length); return data->script->vertex_data != NULL; } static bool end_section(struct load_state *data) { switch (data->current_section) { case SECTION_NONE: break; case SECTION_COMMENT: break; case SECTION_REQUIRE: break; case SECTION_SHADER: return end_shader(data); case SECTION_VERTEX_DATA: return end_vertex_data(data); case SECTION_INDICES: break; case SECTION_TEST: break; } data->current_section = SECTION_NONE; return true; } static bool is_string(const char *string, const char *start, const char *end) { return (end - start == strlen(string) && !memcmp(start, string, end - start)); } static bool looking_at(const char **p, const char *string) { int len = strlen(string); if (strncmp(*p, string, len) == 0) { *p += len; return true; } return false; } static bool is_end(const char *p) { while (*p && vr_char_is_space(*p)) p++; return *p == '\0'; } static VR_PRINTF_FORMAT(2, 3) void error_at_line(struct load_state *data, const char *format, ...) { struct vr_buffer buffer = VR_BUFFER_STATIC_INIT; vr_buffer_append_printf(&buffer, "%s:%i: ", data->filename, data->line_num); va_list ap; va_start(ap, format); vr_buffer_append_vprintf(&buffer, format, ap); va_end(ap); vr_error_message_string(data->config, (const char *) buffer.data); vr_buffer_destroy(&buffer); } static bool parse_float16s(struct load_state *data, const char **p, uint16_t *out, int n_floats, const char *sep) { char *tail; for (int i = 0; i < n_floats; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; *(out++) = vr_hex_strtohf(&data->config->strtof_data, *p, &tail); if (errno != 0 || tail == *p) return false; *p = tail; if (sep && i < n_floats - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_floats(struct load_state *data, const char **p, float *out, int n_floats, const char *sep) { char *tail; for (int i = 0; i < n_floats; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; *(out++) = vr_strtof(&data->config->strtof_data, *p, &tail); if (errno != 0 || tail == *p) return false; *p = tail; if (sep && i < n_floats - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_doubles(struct load_state *data, const char **p, double *out, int n_doubles, const char *sep) { char *tail; for (int i = 0; i < n_doubles; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; *(out++) = vr_strtod(&data->config->strtof_data, *p, &tail); if (errno != 0 || tail == *p) return false; *p = tail; if (sep && i < n_doubles - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_ints(const char **p, int *out, int n_ints, const char *sep) { long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtol(*p, &tail, 10); if (errno != 0 || tail == *p || v < INT_MIN || v > INT_MAX) return false; *(out++) = (int) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_uints(const char **p, unsigned *out, int n_ints, const char *sep) { unsigned long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoul(*p, &tail, 10); if (errno != 0 || tail == *p || v > UINT_MAX) return false; *(out++) = (unsigned) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_int8s(const char **p, int8_t *out, int n_ints, const char *sep) { long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoll(*p, &tail, 10); if (errno != 0 || tail == *p || v < INT8_MIN || v > INT8_MAX) return false; *(out++) = (int8_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_uint8s(const char **p, uint8_t *out, int n_ints, const char *sep) { long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoll(*p, &tail, 10); if (errno != 0 || tail == *p || v > UINT8_MAX) return false; *(out++) = (uint8_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_int16s(const char **p, int16_t *out, int n_ints, const char *sep) { long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoll(*p, &tail, 10); if (errno != 0 || tail == *p || v < INT16_MIN || v > INT16_MAX) return false; *(out++) = (int16_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_uint16s(const char **p, uint16_t *out, int n_ints, const char *sep) { long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoll(*p, &tail, 10); if (errno != 0 || tail == *p || v > UINT16_MAX) return false; *(out++) = (uint16_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_int64s(const char **p, int64_t *out, int n_ints, const char *sep) { long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoll(*p, &tail, 10); if (errno != 0 || tail == *p || v < INT64_MIN || v > INT64_MAX) return false; *(out++) = (int64_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_uint64s(const char **p, uint64_t *out, int n_ints, const char *sep) { unsigned long long v; char *tail; for (int i = 0; i < n_ints; i++) { while (vr_char_is_space(**p)) (*p)++; errno = 0; v = strtoull(*p, &tail, 10); if (errno != 0 || tail == *p || v > UINT64_MAX) return false; *(out++) = (uint64_t) v; *p = tail; if (sep && i < n_ints - 1) { while (vr_char_is_space(**p)) (*p)++; if (!looking_at(p, sep)) return false; } } return true; } static bool parse_size_t(const char **p, size_t *out) { unsigned long v; char *tail; errno = 0; v = strtoul(*p, &tail, 10); if (errno != 0 || tail == *p || v > SIZE_MAX) return false; *out = v; *p = tail; return true; } static bool parse_desc_set_and_binding(const char **p, unsigned *out) { const char *p_backup = *p; if (!parse_uints(p, out, 2, ":")) { *p = p_backup; out[0] = 0; if (!parse_uints(p, &out[1], 1, NULL)) return false; } return true; } static bool parse_value_type(const char **p, enum vr_box_type *type) { static const struct { const char *name; enum vr_box_type type; } types[] = { { "int ", VR_BOX_TYPE_INT }, { "uint ", VR_BOX_TYPE_UINT }, { "int8_t ", VR_BOX_TYPE_INT8 }, { "uint8_t ", VR_BOX_TYPE_UINT8 }, { "int16_t ", VR_BOX_TYPE_INT16 }, { "uint16_t ", VR_BOX_TYPE_UINT16 }, { "int64_t ", VR_BOX_TYPE_INT64 }, { "uint64_t ", VR_BOX_TYPE_UINT64 }, { "float16_t ", VR_BOX_TYPE_FLOAT16 }, { "float ", VR_BOX_TYPE_FLOAT }, { "double ", VR_BOX_TYPE_DOUBLE }, { "f16vec2 ", VR_BOX_TYPE_F16VEC2 }, { "f16vec3 ", VR_BOX_TYPE_F16VEC3 }, { "f16vec4 ", VR_BOX_TYPE_F16VEC4 }, { "vec2 ", VR_BOX_TYPE_VEC2 }, { "vec3 ", VR_BOX_TYPE_VEC3 }, { "vec4 ", VR_BOX_TYPE_VEC4 }, { "dvec2 ", VR_BOX_TYPE_DVEC2 }, { "dvec3 ", VR_BOX_TYPE_DVEC3 }, { "dvec4 ", VR_BOX_TYPE_DVEC4 }, { "ivec2 ", VR_BOX_TYPE_IVEC2 }, { "ivec3 ", VR_BOX_TYPE_IVEC3 }, { "ivec4 ", VR_BOX_TYPE_IVEC4 }, { "uvec2 ", VR_BOX_TYPE_UVEC2 }, { "uvec3 ", VR_BOX_TYPE_UVEC3 }, { "uvec4 ", VR_BOX_TYPE_UVEC4 }, { "i8vec2 ", VR_BOX_TYPE_I8VEC2 }, { "i8vec3 ", VR_BOX_TYPE_I8VEC3 }, { "i8vec4 ", VR_BOX_TYPE_I8VEC4 }, { "u8vec2 ", VR_BOX_TYPE_U8VEC2 }, { "u8vec3 ", VR_BOX_TYPE_U8VEC3 }, { "u8vec4 ", VR_BOX_TYPE_U8VEC4 }, { "i16vec2 ", VR_BOX_TYPE_I16VEC2 }, { "i16vec3 ", VR_BOX_TYPE_I16VEC3 }, { "i16vec4 ", VR_BOX_TYPE_I16VEC4 }, { "u16vec2 ", VR_BOX_TYPE_U16VEC2 }, { "u16vec3 ", VR_BOX_TYPE_U16VEC3 }, { "u16vec4 ", VR_BOX_TYPE_U16VEC4 }, { "i64vec2 ", VR_BOX_TYPE_I64VEC2 }, { "i64vec3 ", VR_BOX_TYPE_I64VEC3 }, { "i64vec4 ", VR_BOX_TYPE_I64VEC4 }, { "u64vec2 ", VR_BOX_TYPE_U64VEC2 }, { "u64vec3 ", VR_BOX_TYPE_U64VEC3 }, { "u64vec4 ", VR_BOX_TYPE_U64VEC4 }, { "mat2 ", VR_BOX_TYPE_MAT2 }, { "mat2x2 ", VR_BOX_TYPE_MAT2 }, { "mat2x3 ", VR_BOX_TYPE_MAT2X3 }, { "mat2x4 ", VR_BOX_TYPE_MAT2X4 }, { "mat3x2 ", VR_BOX_TYPE_MAT3X2 }, { "mat3 ", VR_BOX_TYPE_MAT3 }, { "mat3x3 ", VR_BOX_TYPE_MAT3 }, { "mat3x4 ", VR_BOX_TYPE_MAT3X4 }, { "mat4x2 ", VR_BOX_TYPE_MAT4X2 }, { "mat4x3 ", VR_BOX_TYPE_MAT4X3 }, { "mat4 ", VR_BOX_TYPE_MAT4 }, { "mat4x4 ", VR_BOX_TYPE_MAT4 }, { "dmat2 ", VR_BOX_TYPE_DMAT2 }, { "dmat2x2 ", VR_BOX_TYPE_DMAT2 }, { "dmat2x3 ", VR_BOX_TYPE_DMAT2X3 }, { "dmat2x4 ", VR_BOX_TYPE_DMAT2X4 }, { "dmat3x2 ", VR_BOX_TYPE_DMAT3X2 }, { "dmat3 ", VR_BOX_TYPE_DMAT3 }, { "dmat3x3 ", VR_BOX_TYPE_DMAT3 }, { "dmat3x4 ", VR_BOX_TYPE_DMAT3X4 }, { "dmat4x2 ", VR_BOX_TYPE_DMAT4X2 }, { "dmat4x3 ", VR_BOX_TYPE_DMAT4X3 }, { "dmat4 ", VR_BOX_TYPE_DMAT4 }, { "dmat4x4 ", VR_BOX_TYPE_DMAT4 }, }; for (int i = 0; i < VR_N_ELEMENTS(types); i++) { if (looking_at(p, types[i].name)) { *type = types[i].type; return true; } } return false; } struct parse_value_closure { struct load_state *data; bool had_error; void *values; const char *p; }; static bool parse_value_cb(enum vr_box_base_type base_type, size_t offset, void *user_data) { struct parse_value_closure *data = user_data; void *value = (uint8_t *) data->values + offset; switch (base_type) { case VR_BOX_BASE_TYPE_INT: if (!parse_ints(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_UINT: if (!parse_uints(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_INT8: if (!parse_int8s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_UINT8: if (!parse_uint8s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_INT16: if (!parse_int16s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_UINT16: if (!parse_uint16s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_INT64: if (!parse_int64s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_UINT64: if (!parse_uint64s(&data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_FLOAT16: if (!parse_float16s(data->data, &data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_FLOAT: if (!parse_floats(data->data, &data->p, value, 1, NULL)) goto error; break; case VR_BOX_BASE_TYPE_DOUBLE: if (!parse_doubles(data->data, &data->p, value, 1, NULL)) goto error; break; } return true; error: data->had_error = true; return false; } static bool parse_value(struct load_state *data, const char **p, enum vr_box_type type, const struct vr_box_layout *layout, void *value) { struct parse_value_closure closure = { .data = data, .values = value, .had_error = false, .p = *p }; vr_box_for_each_component(type, layout, parse_value_cb, &closure); *p = closure.p; return !closure.had_error; } static bool parse_box_values(struct load_state *data, const char **p, enum vr_box_type type, const struct vr_box_layout *layout, size_t array_stride, size_t *size_out, void **buffer_out) { struct vr_buffer buffer = VR_BUFFER_STATIC_INIT; size_t type_size = vr_box_type_size(type, layout); size_t n_values = 0; do { size_t old_length = buffer.length; vr_buffer_set_length(&buffer, n_values * array_stride + type_size); /* Clear the data first so that any bytes not filled * due to padding will have a consistent value */ memset(buffer.data + old_length, 0, buffer.length - old_length); if (!parse_value(data, p, type, layout, buffer.data + buffer.length - type_size)) { vr_buffer_destroy(&buffer); return false; } n_values++; } while (!is_end(*p)); *buffer_out = buffer.data; *size_out = buffer.length; return true; } static bool parse_buffer_subdata(struct load_state *data, const char **p, enum vr_box_type type, const struct vr_box_layout *layout, size_t *size_out, void **buffer_out) { size_t array_stride = vr_box_type_array_stride(type, layout); return parse_box_values(data, p, type, layout, array_stride, size_out, buffer_out); } static bool parse_format(struct load_state *data, const char *p, const struct vr_format **format_out) { while (vr_char_is_space(*p)) p++; const char *end = p; while (*end && !vr_char_is_space(*end)) end++; if (!is_end(end)) { error_at_line(data, "Missing format name"); return false; } char *format_name = vr_strndup(p, end - p); const struct vr_format *format = vr_format_lookup_by_name(format_name); bool ret; if (format == NULL) { error_at_line(data, "Unknown format: %s", format_name); ret = false; } else { *format_out = format; ret = true; } vr_free(format_name); return ret; } static bool parse_fbsize(struct load_state *data, const char *p, struct vr_window_format *format) { unsigned parts[2]; if (!parse_uints(&p, parts, 2, NULL) || parts[0] == 0 || parts[1] == 0 || !is_end(p)) { error_at_line(data, "Invalid fbsize"); return false; } format->width = parts[0]; format->height = parts[1]; return true; } static bool parse_version(struct load_state *data, const char *p, struct vr_requirements *reqs) { unsigned parts[3]; if (!parse_uints(&p, parts, 3, ".") || !is_end(p)) { error_at_line(data, "Invalid version\n"); return false; } vr_requirements_add_version(reqs, parts[0], parts[1], parts[2]); return true; } static enum parse_result process_layout(struct load_state *data, const char *p) { struct vr_box_layout *layout; if (looking_at(&p, "push layout ")) { layout = &data->push_layout; *layout = default_push_layout; } else if (looking_at(&p, "ubo layout ")) { layout = &data->ubo_layout; *layout = default_ubo_layout; } else if (looking_at(&p, "ssbo layout ")) { layout = &data->ssbo_layout; *layout = default_ssbo_layout; } else { return PARSE_RESULT_NON_MATCHED; } while (true) { if (looking_at(&p, "std140")) layout->std = VR_BOX_LAYOUT_STD_140; else if (looking_at(&p, "std430")) layout->std = VR_BOX_LAYOUT_STD_430; else if (looking_at(&p, "row_major")) layout->major = VR_BOX_MAJOR_AXIS_ROW; else if (looking_at(&p, "column_major")) layout->major = VR_BOX_MAJOR_AXIS_COLUMN; else goto error; if (is_end(p)) return PARSE_RESULT_OK; if (!vr_char_is_space(*p)) goto error; while (vr_char_is_space(*p)) p++; } error: error_at_line(data, "Invalid layout command"); return PARSE_RESULT_ERROR; } static bool process_none_line(struct load_state *data) { const char *start = (char *) data->line.data; while (*start && vr_char_is_space(*start)) start++; if (*start != '#' && *start != '\0') { error_at_line(data, "expected empty line"); return false; } return true; } static bool process_require_line(struct load_state *data) { const char *start = (char *) data->line.data, *p = start; while (*start && vr_char_is_space(*start)) start++; if (*start == '#' || *start == '\0') return true; if (looking_at(&p, "framebuffer ")) { struct vr_window_format *format = &data->script->window_format; return parse_format(data, p, &format->color_format); } if (looking_at(&p, "depthstencil ")) { struct vr_window_format *format = &data->script->window_format; return parse_format(data, p, &format->depth_stencil_format); } if (looking_at(&p, "fbsize ")) return parse_fbsize(data, p, &data->script->window_format); if (looking_at(&p, "vulkan ")) { return parse_version(data, p, data->script->requirements); } int extension_len = 0; while (true) { char ch = start[extension_len]; if ((ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '_') break; extension_len++; } if (is_end(start + extension_len)) { char *ext = vr_strndup(start, extension_len); vr_requirements_add(data->script->requirements, ext); vr_free(ext); return true; } error_at_line(data, "Invalid require line"); return false; } static unsigned add_pipeline_key(struct load_state *data, const struct vr_pipeline_key *key) { unsigned n_keys = (data->pipeline_keys.length / sizeof (struct vr_pipeline_key)); const struct vr_pipeline_key *keys = (const struct vr_pipeline_key *) data->pipeline_keys.data; for (unsigned i = 0; i < n_keys; i++) { if (vr_pipeline_key_equal(keys + i, key)) return i; } vr_buffer_set_length(&data->pipeline_keys, data->pipeline_keys.length + sizeof *key); vr_pipeline_key_copy((struct vr_pipeline_key *) data->pipeline_keys.data + n_keys, key); return n_keys; } static struct vr_script_command * add_command(struct load_state *data) { vr_buffer_set_length(&data->commands, data->commands.length + sizeof (struct vr_script_command)); struct vr_script_command *command = (struct vr_script_command *) (data->commands.data + data->commands.length - sizeof (struct vr_script_command)); memset(command, 0, sizeof *command); command->line_num = data->line_num; return command; } static enum parse_result process_draw_rect_command(struct load_state *data, const char *p) { if (!looking_at(&p, "draw rect ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); bool ortho = false; if (looking_at(&p, "ortho ")) ortho = true; struct vr_pipeline_key key; vr_pipeline_key_copy(&key, &data->current_key); key.type = VR_PIPELINE_KEY_TYPE_GRAPHICS; key.source = VR_PIPELINE_KEY_SOURCE_RECTANGLE; if (looking_at(&p, "patch ")) key.topology.i = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; else key.topology.i = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; key.patchControlPoints.i = 4; command->draw_rect.pipeline_key = add_pipeline_key(data, &key); vr_pipeline_key_destroy(&key); float parts[4]; if (!parse_floats(data, &p, parts, 4, NULL) || !is_end(p)) { error_at_line(data, "Invalid draw rect command"); return PARSE_RESULT_ERROR; } command->op = VR_SCRIPT_OP_DRAW_RECT; command->draw_rect.x = parts[0]; command->draw_rect.y = parts[1]; command->draw_rect.w = parts[2]; command->draw_rect.h = parts[3]; if (ortho) { float width = data->script->window_format.width; float height = data->script->window_format.height; command->draw_rect.x = (command->draw_rect.x * 2.0f / width) - 1.0f; command->draw_rect.y = (command->draw_rect.y * 2.0f / height) - 1.0f; command->draw_rect.w *= 2.0f / width; command->draw_rect.h *= 2.0f / height; } return PARSE_RESULT_OK; } static enum parse_result process_probe_command(struct load_state *data, const char *p) { bool relative = false; enum { POINT, RECT, ALL } region_type = POINT; int n_components; if (looking_at(&p, "relative ")) relative = true; if (!looking_at(&p, "probe ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); command->probe_rect.tolerance = data->tolerance; if (looking_at(&p, "rect ")) region_type = RECT; else if (looking_at(&p, "all ")) region_type = ALL; if (looking_at(&p, "rgb ")) { n_components = 3; } else if (looking_at(&p, "rgba ")) { n_components = 4; } else { error_at_line(data, "Expected rgb or rgba in probe command"); return PARSE_RESULT_ERROR; } command->op = VR_SCRIPT_OP_PROBE_RECT; command->probe_rect.n_components = n_components; size_t window_width = data->script->window_format.width; size_t window_height = data->script->window_format.height; if (region_type == ALL) { if (relative) { error_at_line(data, "‘all’ can not be used with " "a relative probe"); return PARSE_RESULT_ERROR; } if (!parse_doubles(data, &p, command->probe_rect.color, n_components, NULL) || !is_end(p)) goto error; command->probe_rect.x = 0; command->probe_rect.y = 0; command->probe_rect.w = window_width; command->probe_rect.h = window_height; return PARSE_RESULT_OK; } while (vr_char_is_space(*p)) p++; if (*p != '(') goto error; p++; if (region_type == POINT) { if (relative) { float rel_pos[2]; if (!parse_floats(data, &p, rel_pos, 2, ",")) goto error; command->probe_rect.x = rel_pos[0] * window_width; command->probe_rect.y = rel_pos[1] * window_height; } else { int parts[2]; if (!parse_ints(&p, parts, 2, ",")) goto error; command->probe_rect.x = parts[0]; command->probe_rect.y = parts[1]; } command->probe_rect.w = 1; command->probe_rect.h = 1; } else { assert(region_type == RECT); if (relative) { float rel_pos[4]; if (!parse_floats(data, &p, rel_pos, 4, ",")) goto error; command->probe_rect.x = rel_pos[0] * window_width; command->probe_rect.y = rel_pos[1] * window_height; command->probe_rect.w = rel_pos[2] * window_width; command->probe_rect.h = rel_pos[3] * window_height; } else { int parts[4]; if (!parse_ints(&p, parts, 4, ",")) goto error; command->probe_rect.x = parts[0]; command->probe_rect.y = parts[1]; command->probe_rect.w = parts[2]; command->probe_rect.h = parts[3]; } } while (vr_char_is_space(*p)) p++; if (*p != ')') goto error; p++; while (vr_char_is_space(*p)) p++; if (*p != '(') goto error; p++; if (!parse_doubles(data, &p, command->probe_rect.color, n_components, ",")) goto error; while (vr_char_is_space(*p)) p++; if (*p != ')') goto error; p++; if (!is_end(p)) goto error; return PARSE_RESULT_OK; error: error_at_line(data, "Invalid probe command"); return PARSE_RESULT_ERROR; } static enum parse_result process_probe_ssbo_command(struct load_state *data, const char *p) { if (!looking_at(&p, "probe ssbo ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); if (!parse_value_type(&p, &command->probe_ssbo.type)) goto error; command->probe_ssbo.layout = data->ssbo_layout; while (vr_char_is_space(*p)) p++; unsigned values[3]; if (!parse_desc_set_and_binding(&p, values) || !parse_uints(&p, &values[2], 1, NULL)) { goto error; } command->probe_ssbo.desc_set = values[0]; command->probe_ssbo.binding = values[1]; command->probe_ssbo.offset = values[2]; while (vr_char_is_space(*p)) p++; static const char *comparison_names[] = { [VR_BOX_COMPARISON_EQUAL] = "==", [VR_BOX_COMPARISON_FUZZY_EQUAL] = "~=", [VR_BOX_COMPARISON_NOT_EQUAL] = "!=", [VR_BOX_COMPARISON_LESS] = "<", [VR_BOX_COMPARISON_GREATER_EQUAL] = ">=", [VR_BOX_COMPARISON_GREATER] = ">", [VR_BOX_COMPARISON_LESS_EQUAL] = "<=", }; for (unsigned i = 0; i < VR_N_ELEMENTS(comparison_names); i++) { if (looking_at(&p, comparison_names[i])) { command->probe_ssbo.comparison = i; goto found_comparison; } } goto error; found_comparison: while (vr_char_is_space(*p)) p++; size_t value_size; size_t type_size = vr_box_type_size(command->probe_ssbo.type, &command->probe_ssbo.layout); if (!parse_box_values(data, &p, command->probe_ssbo.type, &command->probe_ssbo.layout, type_size, /* array_stride (tightly packed) */ &value_size, &command->probe_ssbo.value)) goto error; if (!is_end(p)) { vr_free(command->probe_ssbo.value); goto error; } command->probe_ssbo.n_values = value_size / type_size; command->op = VR_SCRIPT_OP_PROBE_SSBO; command->probe_ssbo.tolerance = data->tolerance; return PARSE_RESULT_OK; error: error_at_line(data, "Invalid probe ssbo command"); return PARSE_RESULT_ERROR; } static enum parse_result process_draw_arrays_command(struct load_state *data, const char *p) { if (!looking_at(&p, "draw arrays ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); int args[3] = { [2] = 1 }; int n_args = 2; command->draw_arrays.indexed = false; while (true) { if (looking_at(&p, "instanced ")) { n_args = 3; continue; } else if (looking_at(&p, "indexed ")) { command->draw_arrays.indexed = true; continue; } break; } VkPrimitiveTopology topology; static const struct { const char *name; VkPrimitiveTopology topology; } topologies[] = { /* GL names used in Piglit */ { "GL_POINTS", VK_PRIMITIVE_TOPOLOGY_POINT_LIST }, { "GL_LINES", VK_PRIMITIVE_TOPOLOGY_LINE_LIST }, { "GL_LINE_STRIP", VK_PRIMITIVE_TOPOLOGY_LINE_STRIP }, { "GL_TRIANGLES", VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST }, { "GL_TRIANGLE_STRIP", VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP }, { "GL_TRIANGLE_FAN", VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN }, { "GL_LINES_ADJACENCY", VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY }, { "GL_LINE_STRIP_ADJACENCY", VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY }, { "GL_TRIANGLES_ADJACENCY", VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY }, { "GL_TRIANGLE_STRIP_ADJACENCY", VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY }, { "GL_PATCHES", VK_PRIMITIVE_TOPOLOGY_PATCH_LIST }, /* Vulkan names */ #define vkname(x) { VR_STRINGIFY(x), VK_PRIMITIVE_TOPOLOGY_ ## x } vkname(POINT_LIST), vkname(LINE_LIST), vkname(LINE_STRIP), vkname(TRIANGLE_LIST), vkname(TRIANGLE_STRIP), vkname(TRIANGLE_FAN), vkname(LINE_LIST_WITH_ADJACENCY), vkname(LINE_STRIP_WITH_ADJACENCY), vkname(TRIANGLE_LIST_WITH_ADJACENCY), vkname(TRIANGLE_STRIP_WITH_ADJACENCY), vkname(PATCH_LIST), #undef vkname }; for (int i = 0; i < VR_N_ELEMENTS(topologies); i++) { if (looking_at(&p, topologies[i].name)) { topology = topologies[i].topology; goto found_topology; } } error_at_line(data, "Unknown topology in draw arrays command"); return PARSE_RESULT_ERROR; found_topology: if (!parse_ints(&p, args, n_args, NULL) || !is_end(p)) { error_at_line(data, "Invalid draw arrays command"); return PARSE_RESULT_ERROR; } struct vr_pipeline_key key; vr_pipeline_key_copy(&key, &data->current_key); key.type = VR_PIPELINE_KEY_TYPE_GRAPHICS; key.source = VR_PIPELINE_KEY_SOURCE_VERTEX_DATA; key.topology.i = topology; command->op = VR_SCRIPT_OP_DRAW_ARRAYS; command->draw_arrays.first_vertex = args[0]; command->draw_arrays.vertex_count = args[1]; command->draw_arrays.first_instance = 0; command->draw_arrays.instance_count = args[2]; command->draw_arrays.pipeline_key = add_pipeline_key(data, &key); vr_pipeline_key_destroy(&key); return PARSE_RESULT_OK; } static enum parse_result process_compute_command(struct load_state *data, const char *p) { if (!looking_at(&p, "compute ")) return PARSE_RESULT_NON_MATCHED; unsigned parts[3]; if (!parse_uints(&p, parts, 3, NULL) || !is_end(p)) { error_at_line(data, "Invalid compute command"); return PARSE_RESULT_ERROR; } struct vr_script_command *command = add_command(data); command->dispatch_compute.x = parts[0]; command->dispatch_compute.y = parts[1]; command->dispatch_compute.z = parts[2]; data->current_key.type = VR_PIPELINE_KEY_TYPE_COMPUTE; command->op = VR_SCRIPT_OP_DISPATCH_COMPUTE; command->dispatch_compute.pipeline_key = add_pipeline_key(data, &data->current_key); return PARSE_RESULT_OK; } static enum parse_result process_push_command(struct load_state *data, const char *p) { if (!looking_at(&p, "uniform ") && !looking_at(&p, "push ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); while (vr_char_is_space(*p)) p++; enum vr_box_type type; if (!parse_value_type(&p, &type) || !parse_size_t(&p, &command->set_push_constant.offset) || !parse_buffer_subdata(data, &p, type, &data->push_layout, &command->set_push_constant.size, &command->set_push_constant.data) || !is_end(p)) { error_at_line(data, "Invalid uniform command"); return PARSE_RESULT_ERROR; } command->op = VR_SCRIPT_OP_SET_PUSH_CONSTANT; return PARSE_RESULT_OK; } static enum parse_result process_clear_command(struct load_state *data, const char *p) { if (!looking_at(&p, "clear")) return PARSE_RESULT_NON_MATCHED; if (!is_end(p)) { error_at_line(data, "The clear command doesn’t take any arguments"); return PARSE_RESULT_ERROR; } struct vr_script_command *command = add_command(data); command->op = VR_SCRIPT_OP_CLEAR; memcpy(command->clear.color, data->clear_color, sizeof data->clear_color); command->clear.depth = data->clear_depth; command->clear.stencil = data->clear_stencil; return PARSE_RESULT_OK; } static bool process_indices_line(struct load_state *data) { const char *p = (char *) data->line.data; while (true) { while (*p && vr_char_is_space(*p)) p++; if (*p == '\0' || *p == '#') return true; vr_buffer_set_length(&data->indices, data->indices.length + sizeof (uint16_t)); errno = 0; char *tail; unsigned value = strtoul(p, &tail, 10); if (errno || value > UINT16_MAX) { error_at_line(data, "Invalid index"); return false; } uint16_t *index = (uint16_t *) (data->indices.data + data->indices.length) - 1; *index = value; p = tail; } return true; } static enum parse_result process_bool_property(struct load_state *data, union vr_pipeline_key_value *value, const char *p) { if (looking_at(&p, "true")) value->i = true; else if (looking_at(&p, "false")) value->i = false; else if (!parse_ints(&p, &value->i, 1, NULL)) goto error; if (!is_end(p)) goto error; return PARSE_RESULT_OK; error: error_at_line(data, "Invalid boolean value"); return PARSE_RESULT_ERROR; } static enum parse_result process_int_property(struct load_state *data, union vr_pipeline_key_value *value, const char *p) { value->i = 0; while (true) { int this_int; while (vr_char_is_space(*p)) p++; if (parse_ints(&p, &this_int, 1, NULL)) { value->i |= this_int; } else if (vr_char_is_alnum(*p)) { const char *end = p + 1; while (vr_char_is_alnum(*end) || *end == '_') end++; char *enum_name = vr_strndup(p, end - p); bool is_enum = vr_pipeline_key_lookup_enum(enum_name, &this_int); free(enum_name); if (!is_enum) goto error; value->i |= this_int; p = end; } else { goto error; } if (is_end(p)) break; while (vr_char_is_space(*p)) p++; if (*p != '|') goto error; p++; } return PARSE_RESULT_OK; error: error_at_line(data, "Invalid int value"); return PARSE_RESULT_ERROR; } static enum parse_result process_float_property(struct load_state *data, union vr_pipeline_key_value *value, const char *p) { while (vr_char_is_space(*p)) p++; if (!parse_floats(data, &p, &value->f, 1, NULL) || !is_end(p)) { error_at_line(data, "Invalid float value"); return PARSE_RESULT_ERROR; } return PARSE_RESULT_OK; } static enum parse_result process_pipeline_property(struct load_state *data, const char *p) { if (!vr_char_is_alnum(*p)) return PARSE_RESULT_NON_MATCHED; const char *end = p + 1; while (vr_char_is_alnum(*end) || *end == '.') end++; char *prop_name = vr_strndup(p, end - p); enum vr_pipeline_key_value_type key_value_type; union vr_pipeline_key_value *key_value = vr_pipeline_key_lookup(&data->current_key, prop_name, &key_value_type); vr_free(prop_name); if (key_value == NULL) return PARSE_RESULT_NON_MATCHED; p = end; while (*p && vr_char_is_space(*p)) p++; switch (key_value_type) { case VR_PIPELINE_KEY_VALUE_TYPE_BOOL: return process_bool_property(data, key_value, p); case VR_PIPELINE_KEY_VALUE_TYPE_INT: return process_int_property(data, key_value, p); case VR_PIPELINE_KEY_VALUE_TYPE_FLOAT: return process_float_property(data, key_value, p); } vr_fatal("Unknown pipeline property type"); } static struct vr_script_buffer * get_buffer(struct load_state *data, unsigned desc_set, unsigned binding, enum vr_script_buffer_type type) { struct vr_script_buffer *buffer = (struct vr_script_buffer *) data->buffers.data; unsigned n_buffers = (data->buffers.length / sizeof (struct vr_script_buffer)); for (unsigned i = 0; i < n_buffers; i++) { if (buffer[i].desc_set == desc_set && buffer[i].binding == binding) { if (buffer[i].type != type) { error_at_line(data, "Buffer binding point " "%u:%u used with different " "types", desc_set, binding); return NULL; } return buffer + i; } } vr_buffer_set_length(&data->buffers, data->buffers.length + sizeof *buffer); buffer = ((struct vr_script_buffer *) (data->buffers.data + data->buffers.length) - 1); buffer->type = type; buffer->size = 0; buffer->desc_set = desc_set; buffer->binding = binding; return buffer; } static const struct vr_box_layout * get_layout_for_buffer_type(struct load_state *data, enum vr_script_buffer_type type) { switch (type) { case VR_SCRIPT_BUFFER_TYPE_UBO: return &data->ubo_layout; case VR_SCRIPT_BUFFER_TYPE_SSBO: return &data->ssbo_layout; } vr_fatal("Unknown buffer type"); } static bool process_set_buffer_subdata(struct load_state *data, unsigned desc_set, unsigned binding, enum vr_script_buffer_type type, const char *p, struct vr_script_command *command) { command->set_buffer_subdata.desc_set = desc_set; command->set_buffer_subdata.binding = binding; struct vr_script_buffer *buffer = get_buffer(data, desc_set, binding, type); if (buffer == NULL) return false; while (vr_char_is_space(*p)) p++; enum vr_box_type value_type; if (!parse_value_type(&p, &value_type)) goto error; if (!parse_size_t(&p, &command->set_buffer_subdata.offset)) goto error; const struct vr_box_layout *layout = get_layout_for_buffer_type(data, type); if (!parse_buffer_subdata(data, &p, value_type, layout, &command->set_buffer_subdata.size, &command->set_buffer_subdata.data)) goto error; if (!is_end(p)) goto error; size_t end = (command->set_buffer_subdata.offset + command->set_buffer_subdata.size); if (end > buffer->size) buffer->size = end; command->op = VR_SCRIPT_OP_SET_BUFFER_SUBDATA; return true; error: error_at_line(data, "Invalid set buffer subdata command"); return false; } static bool process_set_buffer_size(struct load_state *data, unsigned desc_set, unsigned binding, enum vr_script_buffer_type buffer_type, unsigned size) { struct vr_script_buffer *buffer = get_buffer(data, desc_set, binding, buffer_type); if (buffer == NULL) return false; if (size > buffer->size) buffer->size = size; return true; } static enum parse_result process_entrypoint(struct load_state *data, const char *p) { int stage; for (stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) { if (looking_at(&p, stage_names[stage])) goto found_stage; } return PARSE_RESULT_NON_MATCHED; found_stage: if (!looking_at(&p, " entrypoint ")) return PARSE_RESULT_NON_MATCHED; while (*p && vr_char_is_space(*p)) p++; const char *end = p + strlen(p); while (end > p && vr_char_is_space(end[-1])) end--; if (end <= p) { error_at_line(data, "Missing entrypoint name"); return PARSE_RESULT_ERROR; } char *entrypoint = vr_strndup(p, end - p); vr_pipeline_key_set_entrypoint(&data->current_key, stage, entrypoint); vr_free(entrypoint); return PARSE_RESULT_OK; } static enum parse_result process_patch_parameter_vertices(struct load_state *data, const char *p) { if (!looking_at(&p, "patch parameter vertices ")) return PARSE_RESULT_NON_MATCHED; struct vr_pipeline_key *key = &data->current_key; if (!parse_ints(&p, &key->patchControlPoints.i, 1, NULL) || !is_end(p)) { error_at_line(data, "Invalid patch parameter vertices command"); return PARSE_RESULT_ERROR; } return PARSE_RESULT_OK; } static enum parse_result process_clear_values(struct load_state *data, const char *p) { if (!looking_at(&p, "clear ")) return PARSE_RESULT_NON_MATCHED; if (looking_at(&p, "color ")) { if (!parse_floats(data, &p, data->clear_color, 4, NULL) || !is_end(p)) { error_at_line(data, "Invalid clear color command"); return PARSE_RESULT_ERROR; } } else if (looking_at(&p, "depth ")) { if (!parse_floats(data, &p, &data->clear_depth, 1, NULL) || !is_end(p)) { error_at_line(data, "Invalid clear depth command"); return PARSE_RESULT_ERROR; } } else if (looking_at(&p, "stencil ")) { if (!parse_uints(&p, &data->clear_stencil, 1, NULL) || !is_end(p)) { error_at_line(data, "Invalid clear stencil command"); return PARSE_RESULT_ERROR; } } else { return PARSE_RESULT_NON_MATCHED; } return PARSE_RESULT_OK; } static enum parse_result process_buffer_command(struct load_state *data, const char *p) { enum vr_script_buffer_type buffer_type; if (looking_at(&p, "ssbo ")) buffer_type = VR_SCRIPT_BUFFER_TYPE_SSBO; else if (looking_at(&p, "ubo ")) buffer_type = VR_SCRIPT_BUFFER_TYPE_UBO; else return PARSE_RESULT_NON_MATCHED; unsigned binding[2]; if (!parse_desc_set_and_binding(&p, binding)) { error_at_line(data, "Invalid binding in buffer command"); return PARSE_RESULT_ERROR; } while (vr_char_is_space(*p)) p++; if (looking_at(&p, "subdata ")) { struct vr_script_command *command = add_command(data); if (!process_set_buffer_subdata(data, binding[0], binding[1], buffer_type, p, command)) return PARSE_RESULT_ERROR; } else { unsigned size; if (!parse_uints(&p, &size, 1, NULL) || !is_end(p)) { error_at_line(data, "Invalid buffer command"); return PARSE_RESULT_ERROR; } if (!process_set_buffer_size(data, binding[0], binding[1], buffer_type, size)) return PARSE_RESULT_ERROR; } return PARSE_RESULT_OK; } static enum parse_result process_uniform_ubo_command(struct load_state *data, const char *p) { if (!looking_at(&p, "uniform ubo ")) return PARSE_RESULT_NON_MATCHED; struct vr_script_command *command = add_command(data); unsigned values[2]; if (!parse_desc_set_and_binding(&p, values)) { error_at_line(data, "Invalid binding in uniform ubo command"); return PARSE_RESULT_ERROR; } if (!process_set_buffer_subdata(data, values[0], values[1], VR_SCRIPT_BUFFER_TYPE_UBO, p, command)) return PARSE_RESULT_ERROR; return PARSE_RESULT_OK; } static enum parse_result process_tolerance(struct load_state *data, const char *p) { if (!looking_at(&p, "tolerance ")) return PARSE_RESULT_NON_MATCHED; bool parse_percent = false; int n_args; for (n_args = 0; !is_end(p) && n_args < 4; n_args++) { if (!parse_doubles(data, &p, data->tolerance.value + n_args, 1, NULL) || data->tolerance.value[n_args] < 0.0) { error_at_line(data, "invalid tolerance value"); return PARSE_RESULT_ERROR; } while (vr_char_is_space(*p)) p++; if (n_args == 0) { if (*p == '%') { parse_percent = true; p++; } } else if (parse_percent) { if (*p != '%') { error_at_line(data, "either all tolerance " "values must be a percentage " "or none"); return PARSE_RESULT_ERROR; } p++; } } if (n_args == 1) { for (unsigned i = 1; i < 4; i++) data->tolerance.value[i] = data->tolerance.value[0]; } else if (n_args != 4) { error_at_line(data, "there must be either 1 or 4 " "tolerance values"); return PARSE_RESULT_ERROR; } if (!is_end(p)) { error_at_line(data, "tolerance command has extra arguments"); return PARSE_RESULT_ERROR; } data->tolerance.is_percent = parse_percent; return PARSE_RESULT_OK; } static bool process_test_line(struct load_state *data) { const char *p = (char *) data->line.data; while (*p && vr_char_is_space(*p)) p++; if (*p == '#' || *p == '\0') return true; static const process_test_line_func funcs[] = { process_patch_parameter_vertices, process_clear_values, process_layout, process_buffer_command, process_tolerance, process_entrypoint, process_probe_ssbo_command, process_probe_command, process_draw_arrays_command, process_compute_command, process_uniform_ubo_command, process_push_command, process_clear_command, process_draw_rect_command, /* This should be last because it is more expensive to check */ process_pipeline_property, }; for (int i = 0; i < VR_N_ELEMENTS(funcs); i++) { switch (funcs[i](data, p)) { case PARSE_RESULT_NON_MATCHED: break; case PARSE_RESULT_ERROR: return false; case PARSE_RESULT_OK: return true; } } error_at_line(data, "Invalid test command"); return false; } static void set_current_section(struct load_state *data, enum section section) { data->current_section = section; data->had_sections |= (1 << section); } static bool is_stage_section(struct load_state *data, const char *start, const char *end) { static const char tail[] = " shader"; int stage; for (stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) { int len = strlen(stage_names[stage]); if (end - start >= len + (sizeof tail) - 1 && !memcmp(start, stage_names[stage], len) && !memcmp(start + len, tail, (sizeof tail) - 1)) { start += len + (sizeof tail) - 1; goto found_stage; } } return false; found_stage: if (is_string(" spirv", start, end)) data->current_source_type = VR_SCRIPT_SOURCE_TYPE_SPIRV; else if (is_string(" binary", start, end)) data->current_source_type = VR_SCRIPT_SOURCE_TYPE_BINARY; else if (start == end) data->current_source_type = VR_SCRIPT_SOURCE_TYPE_GLSL; else return false; set_current_section(data, SECTION_SHADER); data->current_stage = stage; data->buffer.length = 0; return true; } static bool start_spirv_shader(struct load_state *data, enum vr_shader_stage stage) { if (!vr_list_empty(&data->script->stages[stage])) { error_at_line(data, "SPIR-V source can not be " "linked with other shaders in the " "same stage"); return false; } return true; } static bool is_spirv_shader(enum vr_script_source_type type) { switch (type) { case VR_SCRIPT_SOURCE_TYPE_BINARY: case VR_SCRIPT_SOURCE_TYPE_SPIRV: return true; case VR_SCRIPT_SOURCE_TYPE_GLSL: return false; } vr_fatal("Unexpected source type"); } static bool process_section_header(struct load_state *data) { if (!end_section(data)) return false; const char *start = (char *) data->line.data + 1; const char *end = strchr(start, ']'); if (end == NULL) { error_at_line(data, "Missing ']'"); return false; } if (is_stage_section(data, start, end)) { if (is_spirv_shader(data->current_source_type) && !start_spirv_shader(data, data->current_stage)) return false; return true; } if (is_string("vertex shader passthrough", start, end)) { if (!start_spirv_shader(data, VR_SHADER_STAGE_VERTEX)) return false; set_current_section(data, SECTION_NONE); add_shader(data->script, VR_SHADER_STAGE_VERTEX, VR_SCRIPT_SOURCE_TYPE_BINARY, sizeof vertex_shader_passthrough, (const char *) vertex_shader_passthrough); return true; } if (is_string("comment", start, end)) { set_current_section(data, SECTION_COMMENT); return true; } if (is_string("require", start, end)) { /* The “require” section must come first because the * “test” section uses the window size while parsing * the commands. */ if ((data->had_sections & ~(1 << SECTION_COMMENT)) != 0) { error_at_line(data, "[require] must be the first section"); return false; } set_current_section(data, SECTION_REQUIRE); return true; } if (is_string("test", start, end)) { set_current_section(data, SECTION_TEST); return true; } if (is_string("indices", start, end)) { set_current_section(data, SECTION_INDICES); return true; } if (is_string("vertex data", start, end)) { if (data->script->vertex_data) { error_at_line(data, "Duplicate vertex data section"); return false; } set_current_section(data, SECTION_VERTEX_DATA); data->buffer.length = 0; return true; } error_at_line(data, "Unknown section “%.*s”", (int) (end - start), start); return false; } static int hex_value(char ch) { if (ch < '0') return -1; if (ch <= '9') return ch - '0'; if (ch < 'A') return -1; if (ch <= 'F') return ch - 'A' + 10; if (ch < 'a') return -1; if (ch <= 'f') return ch - 'a' + 10; return -1; } static bool decode_binary(struct load_state *data, const char *line, size_t length) { const char *end = line + length; while (true) { /* Skip spaces and finish if we encounter the end of * the line */ while (true) { if (line >= end) return true; if (!vr_char_is_space(*line)) break; line++; } /* Skip comments */ if (*line == '#') return true; /* If it’s not a space then it must be a hex digit */ int digit = hex_value(*(line++)); if (digit == -1) { error_at_line(data, "Invalid character in binary data"); return false; } uint32_t value = digit; while (line < end) { digit = hex_value(*line); if (digit == -1) break; value = (value << 4) | digit; line++; } vr_buffer_append(&data->buffer, &value, sizeof value); } } static bool process_line(struct load_state *data) { if (*data->line.data == '[') return process_section_header(data); switch (data->current_section) { case SECTION_NONE: return process_none_line(data); case SECTION_COMMENT: return true; case SECTION_REQUIRE: return process_require_line(data); case SECTION_SHADER: if (data->current_source_type == VR_SCRIPT_SOURCE_TYPE_BINARY) { if (!decode_binary(data, (const char *) data->line.data, data->line.length)) return false; } else { vr_buffer_append(&data->buffer, data->line.data, data->line.length); } return true; case SECTION_VERTEX_DATA: vr_buffer_append(&data->buffer, data->line.data, data->line.length); return true; case SECTION_INDICES: return process_indices_line(data); case SECTION_TEST: return process_test_line(data); } return true; } static int compare_buffer_set_and_binding(const void *a, const void *b) { const struct vr_script_buffer *buffer_a = (const struct vr_script_buffer *) a; const struct vr_script_buffer *buffer_b = (const struct vr_script_buffer *) b; if ((int) buffer_a->desc_set == (int) buffer_b->desc_set) return ((int) buffer_a->binding - (int) buffer_b->binding); return ((int) buffer_a->desc_set - (int) buffer_b->desc_set); } static bool find_replacement(const struct vr_list *replacements, struct vr_buffer *line, int pos) { const struct vr_source_token_replacement *tr; vr_list_for_each(tr, replacements, link) { int len = strlen(tr->token); if (pos + len <= line->length && !memcmp(line->data + pos, tr->token, len)) { int repl_len = strlen(tr->replacement); int new_line_len = line->length + repl_len - len; /* The extra “1” is to preserve the null terminator */ vr_buffer_ensure_size(line, new_line_len + 1); memmove(line->data + pos + repl_len, line->data + pos + len, line->length - pos - len + 1); memcpy(line->data + pos, tr->replacement, repl_len); vr_buffer_set_length(line, new_line_len); return true; } } return false; } static bool process_token_replacements(struct load_state *data) { int count = 0; for (int i = 0; i < data->line.length; i++) { while (find_replacement(&data->source->token_replacements, &data->line, i)) { count++; if (count > 1000) { fprintf(stderr, "%s:%i: infinite recursion suspected " "while replacing tokens\n", data->filename, data->line_num); return false; } } } return true; } static bool load_script_from_stream(struct load_state *data, struct vr_stream *stream) { bool res = true; do { int lines_consumed = vr_stream_read_line(stream, &data->line); if (lines_consumed == 0) break; if (!process_token_replacements(data)) { res = false; break; } res = process_line(data); data->line_num += lines_consumed; } while (res); if (res) res = end_section(data); return res; } static bool load_script_from_file(struct load_state *data, const char *filename) { FILE *f = fopen(filename, "r"); if (f == NULL) { vr_error_message(data->config, "%s: %s", filename, strerror(errno)); return false; } struct vr_stream stream; vr_stream_init_file(&stream, f); bool res = load_script_from_stream(data, &stream); fclose(f); return res; } static bool load_script_from_string(struct load_state *data, const char *string) { struct vr_stream stream; vr_stream_init_string(&stream, string); bool res = load_script_from_stream(data, &stream); return res; } struct vr_script * vr_script_load(const struct vr_config *config, const struct vr_source *source) { struct vr_script *script = vr_calloc(sizeof (struct vr_script)); struct load_state data = { .config = config, .source = source, .line_num = 1, .script = script, .current_stage = -1, .current_section = SECTION_NONE, .clear_depth = 1.0f, .line = VR_BUFFER_STATIC_INIT, .buffer = VR_BUFFER_STATIC_INIT, .commands = VR_BUFFER_STATIC_INIT, .pipeline_keys = VR_BUFFER_STATIC_INIT, .buffers = VR_BUFFER_STATIC_INIT, .tolerance = { .value = { DEFAULT_TOLERANCE, DEFAULT_TOLERANCE, DEFAULT_TOLERANCE, DEFAULT_TOLERANCE, }, .is_percent = false, }, .push_layout = default_push_layout, .ubo_layout = default_ubo_layout, .ssbo_layout = default_ssbo_layout, }; vr_pipeline_key_init(&data.current_key); script->window_format.width = 250; script->window_format.height = 250; script->window_format.color_format = vr_format_lookup_by_vk_format(VK_FORMAT_B8G8R8A8_UNORM); assert(script->window_format.color_format != NULL); for (int stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) vr_list_init(&script->stages[stage]); script->requirements = vr_requirements_new(); bool res = false; switch (source->type) { case VR_SOURCE_TYPE_FILE: data.filename = source->string; script->filename = vr_strdup(data.filename); res = load_script_from_file(&data, source->string); break; case VR_SOURCE_TYPE_STRING: data.filename = "(string script)"; script->filename = vr_strdup(data.filename); res = load_script_from_string(&data, source->string); break; } script->commands = (struct vr_script_command *) data.commands.data; script->n_commands = (data.commands.length / sizeof (struct vr_script_command)); script->pipeline_keys = (struct vr_pipeline_key *) data.pipeline_keys.data; script->n_pipeline_keys = (data.pipeline_keys.length / sizeof (struct vr_pipeline_key)); script->indices = (uint16_t *) data.indices.data; script->n_indices = data.indices.length / sizeof (uint16_t); script->buffers = (struct vr_script_buffer *) data.buffers.data; script->n_buffers = (data.buffers.length / sizeof (struct vr_script_buffer)); qsort(script->buffers, script->n_buffers, sizeof script->buffers[0], compare_buffer_set_and_binding); vr_buffer_destroy(&data.buffer); vr_buffer_destroy(&data.line); vr_pipeline_key_destroy(&data.current_key); if (res) { return script; } else { vr_script_free(script); return NULL; } } void vr_script_free(struct vr_script *script) { int stage; struct vr_script_shader *shader, *tmp; for (int i = 0; i < script->n_commands; i++) { struct vr_script_command *command = script->commands + i; if (command->op == VR_SCRIPT_OP_SET_BUFFER_SUBDATA) vr_free(command->set_buffer_subdata.data); else if (command->op == VR_SCRIPT_OP_SET_PUSH_CONSTANT) vr_free(command->set_push_constant.data); else if (command->op == VR_SCRIPT_OP_PROBE_SSBO) vr_free(command->probe_ssbo.value); } for (stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) { vr_list_for_each_safe(shader, tmp, &script->stages[stage], link) { vr_free(shader); } } if (script->vertex_data) vr_vbo_free(script->vertex_data); vr_free(script->indices); vr_free(script->filename); vr_free(script->commands); for (int i = 0; i < script->n_pipeline_keys; i++) vr_pipeline_key_destroy(script->pipeline_keys + i); vr_free(script->pipeline_keys); vr_free(script->buffers); vr_requirements_free(script->requirements); vr_free(script); } int vr_script_get_shaders(const struct vr_script *script, const struct vr_source *source, struct vr_script_shader_code *shaders) { int shaders_number = 0; int stage; struct vr_script_shader *shader, *tmp; for (stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) { vr_list_for_each_safe(shader, tmp, &script->stages[stage], link) { shaders[shaders_number].source_type = shader->source_type; shaders[shaders_number].source_length = shader->length; shaders[shaders_number].stage = stage; shaders[shaders_number].source = malloc(shader->length + 1); memcpy(shaders[shaders_number].source, shader->source, shader->length); shaders[shaders_number].source[shader->length] = '\0'; shaders_number++; } } return shaders_number; } int vr_script_get_num_shaders(const struct vr_script* script) { int stage, num_shaders = 0; for (stage = 0; stage < VR_SHADER_STAGE_N_STAGES; stage++) { num_shaders += vr_list_length(&script->stages[stage]); } return num_shaders; } void vr_script_replace_shaders_stage_binary(struct vr_script *script, enum vr_shader_stage stage, size_t source_length, const uint32_t *source) { struct vr_script_shader *shader, *tmp; /* Remove all the shaders of the stage */ vr_list_for_each_safe(shader, tmp, &script->stages[stage], link) { vr_list_remove(&shader->link); vr_free(shader); } /* Add the new shader for the stage */ add_shader(script, stage, VR_SCRIPT_SOURCE_TYPE_BINARY, source_length, (const char *) source); }
31.495971
80
0.476286
[ "geometry" ]
4c8b5ac166112591c256f862299b6ee44974a7fc
1,764
h
C
src/engine_config.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
src/engine_config.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
src/engine_config.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
/* File: EngineConfig.h Author: Lars Vidar Magnusson */ #pragma once namespace game { #define DEFAULT_LOG_FILENAME "engine.log" #define DEFAULT_ENGINECONFIG_FILENAME "default.engine_config" #define EXTENSION_ENGINECONFIG ".engine_config" #define XMLNAME_ENGINECONFIG "EngineConfig" #define XMLNAME_ENGINECONFIG_LOGFILENAME "LogFilename" #define XMLNAME_ENGINECONFIG_PLATFORMCONFIG XMLNAME_PLATFORMCONFIG #define XMLNAME_ENGINECONFIG_ADDIN XMLNAME_ADDINHEADER /** * EngineConfig provides the setup details for the engine_. */ class GAME_API EngineConfig : public content::XmlContent { private: std::unique_ptr<std::string> log_filename_; std::vector<std::string> addin_filenames_; std::unique_ptr<platform::PlatformConfig> platform_config_; protected: EngineConfig(const std::string& filename); public: virtual ~EngineConfig(); const std::string& GetLogFilename() const; void SetLogFilename(const std::string& log_filename); void AddAddinFilename(const std::string& addin_filename); const std::vector<std::reference_wrapper<const std::string>> GetAddinFilenames(); platform::PlatformConfig* GetPlatformConfig() const; void SetPlatformConfig(platform::PlatformConfig* config); using content::XmlContent::Load; using content::XmlContent::Save; bool Load(content::xml::XmlNode root_node) override; bool Save(content::xml::XmlNode root_node) override; private: class Loader : public ILoader { private: static Loader singleton; Loader(); public: content::Content* Load(const std::string& filename) override; }; }; }
23.837838
89
0.694444
[ "vector" ]
4c969e17a69e742bb4126bc3a6d92195073d287a
13,579
h
C
yarnc/include/llvm/Yarn/YarnLoopInfo.h
RAttab/yarn
3caa9d589aa298a7d2bf1091d056410206384454
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
yarnc/include/llvm/Yarn/YarnLoopInfo.h
RAttab/yarn
3caa9d589aa298a7d2bf1091d056410206384454
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
yarnc/include/llvm/Yarn/YarnLoopInfo.h
RAttab/yarn
3caa9d589aa298a7d2bf1091d056410206384454
[ "BSD-2-Clause-FreeBSD" ]
1
2020-04-15T23:37:10.000Z
2020-04-15T23:37:10.000Z
//===- YarnLoop.h - Example code from "Writing an LLVM Pass" --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the FreeBSD License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Yarnc loop analysis pass. // //===----------------------------------------------------------------------===// #ifndef YARN_LOOP_INFO_H #define YARN_LOOP_INFO_H #include "YarnCommon.h" #include <llvm/Pass.h> #include <llvm/Function.h> #include <llvm/Module.h> #include <llvm/BasicBlock.h> #include <llvm/Instructions.h> #include <llvm/Support/Casting.h> #include <vector> #include <map> #include <set> // Forward declarations. namespace llvm { class Loop; class LoopInfo; class AliasAnalysis; class PostDominatorTree; class DominatorTree; } namespace yarn { class YarnLoop; //===----------------------------------------------------------------------===// /// Describes a pointer used in the loop. /// class LoopPointer : public Noncopyable { public: typedef std::vector<llvm::Value*> AliasList; private: AliasList Aliases; public: LoopPointer () : Aliases() {} /// Returns the list of pointers that are known to always be aliases. inline AliasList& getAliasList () { return Aliases; } /// Debug. void print (llvm::raw_ostream &OS) const; private: // It's a friend because it needs to manipulate the IsRead/Write members. friend class YarnLoop; }; //===----------------------------------------------------------------------===// /// Contains the dependency defined by the loops' phi nodes. /// class LoopValue : public Noncopyable { public: typedef std::vector<llvm::Value*> ValueList; private: // Node that defines the Entry and Exiting Value llvm::PHINode* HeaderNode; //Node that uses the Exiting Value to define the Exit value. llvm::PHINode* FooterNode; // Value of the dependency before the loop. llvm::Value* EntryValue; ValueList ExitingValues; // Value used for each iteration. // Not necessarily an exiting value (eg. an induction variable not used outside). llvm::Value* IterationValue; public: LoopValue () : HeaderNode(NULL), FooterNode(NULL), EntryValue(NULL), ExitingValues(), IterationValue(NULL) {} /// The phi node in the loop header used to determine what the /// entry and exiting values are. inline llvm::PHINode* getHeaderNode () const { return HeaderNode; } /// The phi node in the loop footer used to determine what the /// exit value is. inline llvm::PHINode* getFooterNode () const { return FooterNode; } /// Value that existed before the loop that is used within the loop. /// Null if the value isn't used before the loop. inline llvm::Value* getEntryValue () const { return EntryValue; } /// Value that is used within the loop and that continues to exist after the loop. /// Null if the value isn't used after the loop. inline llvm::Value* getExitValue () const { return FooterNode; } inline const ValueList& getExitingValues () const { return ExitingValues; } inline llvm::Value* getExitingValue () const { assert(ExitingValues.size() == 1); return ExitingValues[0]; } inline llvm::Value* getStartIterationValue () const {return HeaderNode; } inline llvm::Value* getEndIterationValue () const {return IterationValue; } inline bool isExitOnly() const { return EntryValue == NULL; } /// Debug. void print (llvm::raw_ostream &OS) const; private : /// Friend because it needs to manipulate the Entry/ExitValue. friend class YarnLoop; }; //===----------------------------------------------------------------------===// /// Represents that type of instrumentation that needs to take place. enum InstrType { InstrLoad = 1, InstrStore = 2 }; //===----------------------------------------------------------------------===// /// Holds the pointer instruction that needs to be instrumented. class PointerInstr : public Noncopyable { InstrType Type; llvm::Instruction* I; public : PointerInstr (InstrType t, llvm::Instruction* i) : Type(t), I(i) {} inline InstrType getType () const { return Type; } /// Returns the instruction to instrument. inline llvm::Instruction* getInstruction () const { return I; } /// Debug. void print (llvm::raw_ostream &OS) const; }; //===----------------------------------------------------------------------===// /// Indicates where the load/store instrumentation for a value should placed. class ValueInstr : public Noncopyable { InstrType Type; llvm::Value* V; llvm::Value* Pos; unsigned Index; public : ValueInstr (InstrType t, llvm::Value* v, llvm::Value* p, unsigned i) : Type(t), V(v), Pos(p), Index(i) {} inline InstrType getType () const { return Type; } /// Returns the value to load/store. inline llvm::Value* getValue () const { return V; } /// Indicates that the instrumentation should take place on the /// specified instruction (before if type == InstrLoad and after /// if type == InstrStore). If it returns NULL then use getBBPos() /// instead. inline llvm::Instruction* getInstPos () const { return llvm::dyn_cast<llvm::Instruction>(Pos); } /// Indicates that the instrumentation should take place on the /// specified BB (at the beginning if type == InstrLoad and at the /// end if type == InstrStore). If it returns NULL then use /// getInstPos() instead. inline llvm::BasicBlock* getBBPos () const { return llvm::dyn_cast<llvm::BasicBlock>(Pos); } /// Index for calls to yarn_dep_xxx_fast inline unsigned getIndex () const { return Index; } /// Debug. void print (llvm::raw_ostream &OS) const; }; //===----------------------------------------------------------------------===// /// Contains info about a loop that needs to be instrumented. class ArrayEntry : public Noncopyable { llvm::Value* EntryValue; llvm::PHINode* ExitNode; bool IsInvariant; llvm::Value* Pointer; llvm::Value* NewValue; public : ArrayEntry(llvm::Value* EV, llvm::PHINode* EN, bool I): EntryValue(EV), ExitNode(EN), IsInvariant(I), Pointer(NULL), NewValue(NULL) {} inline llvm::Value* getEntryValue() const { return EntryValue; } inline llvm::PHINode* getExitNode() const { return ExitNode; } inline bool getIsInvariant() const { return IsInvariant; } inline void setPointer (llvm::Value* P) { Pointer = P; } inline llvm::Value* getPointer() const { return Pointer; } inline void setNewValue (llvm::Value* NV) { NewValue = NV; } inline llvm::Value* getNewValue() const { return NewValue; } /*! \todo Needs to be improved. Doesn't work for induction variable because it's entry value is a constant (0). In this case, we should use the name of the PHINode. This means that we have have to get the name during the analysis phase and not the instrumentation phase. */ inline std::string getName () const { if (EntryValue != NULL) { return EntryValue->getName(); } else if (ExitNode != NULL) { return ExitNode->getName(); } else { return ""; } } /// Debug. void print (llvm::raw_ostream &OS) const; }; //===----------------------------------------------------------------------===// /// Contains info about a loop that needs to be instrumented. class YarnLoop : public Noncopyable { public: typedef std::vector<LoopValue*> ValueList; typedef std::vector<LoopPointer*> PointerList; typedef std::set<llvm::Value*> InvariantList; typedef std::vector<PointerInstr*> PointerInstrList; typedef std::vector<ValueInstr*> ValueInstrList; typedef std::vector<ArrayEntry*> ArrayEntryList; private: llvm::LoopInfo* LI; llvm::AliasAnalysis* AA; llvm::DominatorTree* DT; llvm::PostDominatorTree* PDT; /// The function that the loop belongs too. llvm::Function* F; /// The loop being analyzed. llvm::Loop* L; /// Represents a list of values that are used within and before/after the loop. ValueList Dependencies; /// Represents pointers who are known to treat with aliased memory. PointerList Pointers; /// Represents values that are used outside the loop but only read within the loop. /// May be a pointer or a regular value. InvariantList Invariants; /// List locations where isntrumentation should be added. PointerInstrList PointerInstrs; ValueInstrList ValueInstrs; /// List of all the values that need to be passed to the speculative function. ArrayEntryList ArrayEntries; public: YarnLoop(llvm::Function* f, llvm::Loop* l, llvm::LoopInfo* li, llvm::AliasAnalysis* aa, llvm::DominatorTree* dt, llvm::PostDominatorTree* pdt); ~YarnLoop(); /// Returns the llvm::Loop object that represents our loop. inline llvm::Loop* getLoop () { return L; } /// List of all the values that need to be instrumented. inline const ValueList& getDependencies () const { return Dependencies; } /// Returns the LoopValue for a given entry or exit value. LoopValue* getDependencyForValue (llvm::Value* v); /// List of all the pointers that need to be instrumented. inline const PointerList& getPointers () const { return Pointers; } /// List of all the loop invariants that are needed but should not be instrumented. /// There's no overlap between tthe getDependencies and the getPointers list. inline const InvariantList& getInvariants () const { return Invariants; } /// Instrumentation points for the pointer dependencies. inline const PointerInstrList& getPointerInstrs () const { return PointerInstrs; } /// Instrumentation points for the value dependencies. inline const ValueInstrList& getValueInstrs () const { return ValueInstrs; } /// List of all the values that need to be passed to the speculative function. /// If the tuple contains a true value then it should be loaded in the header. inline ArrayEntryList& getArrayEntries () { return ArrayEntries; } inline ArrayEntry* getArrayEntry(unsigned I) { return ArrayEntries[I]; } /// Debug. void print (llvm::raw_ostream &OS) const; /* */ private: typedef std::map<llvm::Value*, LoopValue*> ValueMap; typedef std::set<llvm::Value*> PointerInstSet; // Loops over the instructions and dispatches to functions below. void processLoop (); // Called for PHINode in the loop header and fills in Dependencies. void processHeaderPHINode (llvm::PHINode* N, ValueMap& ExitingValueMap); // Called for PHINode in the loop footer and fills in Dependencies. void processFooterPHINode (llvm::PHINode* N, ValueMap& ExitingValueMap); // Called for a store/load instruction and fills in Pointers. void processPointers (PointerInstSet& loadSet, PointerInstSet& storeSet); // Called for anything else that has operands and fills in Invariants. void processInvariants (llvm::Instruction* I); void processArrayEntries (); /// Finds the instrumentation points for all the pointer dependencies. void processPointerInstrs (LoopPointer* LP); /// Finds the instrumentation points for all the value dependencies. void processValueInstrs (LoopValue* LV, unsigned Index); typedef llvm::Value* BBPos; typedef std::vector<BBPos> BBPosList; /// Finds the earliest point where a yarn_load can occur that will /// dominate all the possible reads. /// Only supports LoopValues for now. BBPosList findLoadPos (llvm::Value* V) const; /// Finds the latest point where a yarn_store can occur that will be dominated /// by all the possible writes. /// Only supports LoopValues for now. /// \todo Could also do LoopPointer if we know that they're aliases. BBPosList findStorePos (llvm::Value* value) const; }; //===----------------------------------------------------------------------===// /// Function pass that finds and analyzes loops that needs to be instrumented. class YarnLoopInfo : public llvm::FunctionPass, public Noncopyable { public: typedef std::vector<YarnLoop*> LoopList; typedef LoopList::iterator iterator; private: llvm::LoopInfo* LI; llvm::AliasAnalysis* AA; LoopList Loops; public: static char ID; // Pass identification, replacement for typeid. YarnLoopInfo() : FunctionPass(ID) {} inline iterator begin () { return Loops.begin(); } inline iterator end () { return Loops.end(); } bool empty () const { return Loops.empty(); } virtual void getAnalysisUsage (llvm::AnalysisUsage &AU) const; virtual bool runOnFunction (llvm::Function& F); virtual void releaseMemory (); virtual void print (llvm::raw_ostream &O, const llvm::Module *M) const; private: /// Checks the loop to make sure it doesn't contain any unsupported features. bool checkLoop (llvm::Loop* L, llvm::DominatorTree* dt); /// Determines whether the loop is worth instrumenting or not. bool keepLoop (YarnLoop* YL); }; } // namespace yarn. #endif // YARN_LOOP_INFO_H
30.108647
87
0.632889
[ "object", "vector" ]
4c985c8f14c617a0f363864b696b400a8084a22a
374
h
C
include/vapor/DataMgrFactory.h
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
120
2017-07-31T08:40:34.000Z
2022-03-24T03:57:35.000Z
include/vapor/DataMgrFactory.h
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
2,215
2017-06-21T20:47:30.000Z
2022-03-31T22:41:38.000Z
include/vapor/DataMgrFactory.h
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
48
2017-08-02T22:56:40.000Z
2022-02-12T13:44:51.000Z
// // $Id$ // #ifndef _DataMgrFactory_h_ #define _DataMgrFactory_h_ #include <vector> #include <string> #include <vapor/DataMgr.h> namespace VAPoR { class VDF_API DataMgrFactory : public Wasp::MyBase { public: static DataMgr *New(const vector<string> &files, size_t mem_size, string ftype = "vdf"); }; }; // namespace VAPoR #endif // _DataMgrFactory_h_
17
92
0.697861
[ "vector" ]
4ca7fce8bea79612a71b054aa3c3458b598932e9
3,854
h
C
engine/kotek.core/include/kotek_component_allocator.h
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
engine/kotek.core/include/kotek_component_allocator.h
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
engine/kotek.core/include/kotek_component_allocator.h
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "kotek_std.h" namespace Kotek { namespace Core { class ktkMainManager; } } // namespace Kotek namespace Kotek { namespace Core { class ktkIComponentAllocator { public: virtual ~ktkIComponentAllocator() {} virtual bool Create(ktk::entity_t id) noexcept = 0; virtual void* Get(ktk::entity_t id) noexcept = 0; virtual bool Remove(ktk::entity_t id) noexcept = 0; virtual ktk::string GetDebugName(void) const noexcept = 0; virtual ktk::string GetComponentName(void) const noexcept = 0; virtual void DrawImGui(Kotek::Core::ktkMainManager& main_manager, Kotek::ktk::entity_t entity_id) noexcept = 0; }; template <typename ComponentType, std::size_t array_size> class ktkComponentAllocator : public ktkIComponentAllocator { public: ktkComponentAllocator(void) : m_hashed_type(typeid(ComponentType).hash_code()), m_current_index{} { KOTEK_ASSERT(array_size > 0, "you must create allocator with array_size > 0! {}", this->GetDebugName().get_as_is()); // TODO: Use deffered initialization for that case this->m_storage.resize(array_size); this->m_storage_entity_indicies.reserve(array_size); } ~ktkComponentAllocator(void) {} // TODO: it's better to remove because you have GetComponentName ktk::string GetDebugName(void) const noexcept override { return ktk::cast::to_string(typeid(ComponentType).name()); } bool Create(ktk::entity_t id) noexcept override { if (this->m_storage_entity_indicies.find(id) != this->m_storage_entity_indicies.end()) { KOTEK_ASSERT(false, "you have already existed component in storage: {}", id); return false; } if (this->m_current_index + 1 > array_size) { KOTEK_ASSERT(this->m_current_index == array_size, "Overflow! You need to set size bigger than: {}, [{}]", array_size, this->GetDebugName().get_as_is()); return false; } this->m_storage_entity_indicies[id] = this->m_current_index; ++this->m_current_index; return true; } bool Remove(ktk::entity_t id) noexcept override { if (this->m_storage_entity_indicies.find(id) == this->m_storage_entity_indicies.end()) { return false; } auto index = this->m_storage_entity_indicies.at(id); this->m_storage.at(index).Clear(); this->m_storage_entity_indicies.erase(id); --this->m_current_index; return true; } void* Get(ktk::entity_t id) noexcept override { if (this->m_storage_entity_indicies.find(id) == this->m_storage_entity_indicies.end()) { return nullptr; } auto index = this->m_storage_entity_indicies.at(id); KOTEK_ASSERT(index < this->m_storage.size(), "Overflow or index is invalid, debug your code"); return static_cast<void*>(&this->m_storage.at(index)); } ktk::size_t GetHashedValueOfComponentType(void) const noexcept { return this->m_hashed_type; } ktk::string GetComponentName(void) const noexcept override { return ComponentType::GetComponentName(); } void DrawImGui(Kotek::Core::ktkMainManager& main_manager, Kotek::ktk::entity_t entity_id) noexcept override { ComponentType* p_component = static_cast<ComponentType*>(this->Get(entity_id)); if (p_component) { p_component->DrawImGui(main_manager); } } ktk::size_t GetCurrentSize(void) const noexcept { return this->m_current_index; } const ktk::vector<ComponentType>& GetComponents(void) const noexcept { return this->m_storage; } private: ktk::size_t m_hashed_type; ktk::size_t m_current_index; ktk::vector<ComponentType> m_storage; ktk::unordered_map<ktk::entity_t, ktk::size_t> m_storage_entity_indicies; }; } // namespace Core } // namespace Kotek
24.0875
71
0.684224
[ "vector" ]
7304d02e12837acaf977a5adfa9a97eac68bab5a
3,553
h
C
TriangleCodec/TriangleCodecFloat3SOA8.h
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
7
2020-05-26T15:23:25.000Z
2022-02-25T19:36:25.000Z
TriangleCodec/TriangleCodecFloat3SOA8.h
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
null
null
null
TriangleCodec/TriangleCodecFloat3SOA8.h
jrouwe/RayCastTest
6f16eef819bd13f7f7bf063b076dab7091b1886a
[ "MIT" ]
2
2022-03-02T16:30:50.000Z
2022-03-06T14:45:33.000Z
#pragma once #include <Geometry/RayTriangle8.h> // Uncompressed triangle codec, vertices are stored as structure of array, padded to a multiple of 8 and tested 8 at a time template <int Alignment> class TriangleCodecFloat3SOA8 { public: class TriangleHeader { }; enum { TriangleHeaderSize = 0 }; enum { ChangesOffsetOnPack = (Alignment != 1) }; // If this codec could return a different offset than the current buffer size when calling Pack() class EncodingContext { public: uint GetPessimisticMemoryEstimate(uint inTriangleCount) const { return inTriangleCount * (8 * 3 * sizeof(Float3) + Alignment - 1); // Worst case every triangle goes into a group of 8 triangles } uint Pack(const VertexList &inVertices, const IndexedTriangleList &inTriangles, const Vec3 &inBoundsMin, const Vec3 &inBoundsMax, ByteBuffer &ioBuffer) { // Align buffer ioBuffer.Align(Alignment); // Determine position of triangles start uint offset = (uint)ioBuffer.size(); // Pack vertices uint triangle_count = (uint)inTriangles.size(); uint padded_triangle_count = AlignUp(triangle_count, 8); float *vertex = ioBuffer.Allocate<float>(padded_triangle_count * 3 * 3); for (uint b = 0; b < padded_triangle_count; b += 8) for (int v = 0; v < 3; ++v) for (int c = 0; c < 3; ++c) for (uint t = 0; t < 8; ++t) *vertex++ = inVertices[b + t < triangle_count? inTriangles[b + t].mIdx[v] : inTriangles[triangle_count - 1].mIdx[0]][c]; // Pad with degenerate triangles return offset; } void Finalize(TriangleHeader *ioHeader, ByteBuffer &ioBuffer) const { } void GetStats(string &outTriangleCodecName, float &outVerticesPerTriangle) { // Store stats outTriangleCodecName = "Float3SOA8Align" + ConvertToString(Alignment); outVerticesPerTriangle = 3; } }; class DecodingContext { public: f_inline DecodingContext(const TriangleHeader *inHeader, const ByteBuffer &inBuffer) { } f_inline void TestRay(const Vec3 &inRayOrigin, const Vec3 &inRayDirection, const Vec3 &inBoundsMin, const Vec3 &inBoundsMax, const void *inTriangleStart, uint32 inNumTriangles, float &ioClosest) const { Vec8 closest = Vec8::sReplicate(ioClosest); const float *vertex = reinterpret_cast<const float *>(inTriangleStart); assert(IsAligned(vertex, Alignment)); for (uint b = 0; b < inNumTriangles; b += 8) { Vec8 v0x = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v0y = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v0z = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v1x = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v1y = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v1z = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v2x = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v2y = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 v2z = Vec8LoadFloat8ConditionallyAligned<Alignment % 32 == 0>(vertex); vertex += 8; Vec8 distance = RayTriangle8(inRayOrigin, inRayDirection, v0x, v0y, v0z, v1x, v1y, v1z, v2x, v2y, v2z); closest = Vec8::sMin(distance, closest); } ioClosest = closest.ReduceMin(); } }; };
37.797872
206
0.681677
[ "geometry" ]
73180c34aa873ba15c2f018a7c10d266a1a557f7
769
h
C
include/ResourceManager.h
flyingjam/cppac
792dcdf437e6ab721dd7d24f53a6615bb0d5e11e
[ "MIT" ]
null
null
null
include/ResourceManager.h
flyingjam/cppac
792dcdf437e6ab721dd7d24f53a6615bb0d5e11e
[ "MIT" ]
null
null
null
include/ResourceManager.h
flyingjam/cppac
792dcdf437e6ab721dd7d24f53a6615bb0d5e11e
[ "MIT" ]
null
null
null
#ifndef RESOURCE_MANAGER_H #define RESOURCE_MANAGER_H #include "Texture.h" #include "ShaderProgram.h" #include <vector> #include <map> #include <string> #include <unordered_map> class ResourceManager{ public: static std::unordered_map<std::string, ShaderProgram> shaders; static std::unordered_map<std::string, Texture> textures; static ShaderProgram load_shader(const std::string& vertex, const std::string& fragment, std::string name); static ShaderProgram get_shader( std::string name); static Texture load_texture(const std::string& path, std::string name); static Texture get_texture( std::string name); static void clear(); private: ResourceManager() {} }; #endif
24.03125
80
0.682705
[ "vector" ]
731c1c830339e1e02f4e497ee056047064dc0ffd
10,526
c
C
vm/src/lib/string.c
e-wiki/jsos
a84c42b37974034891563351f5d0bb92d21f4b7a
[ "NCSA", "BSD-2-Clause", "Unlicense" ]
834
2015-01-02T14:28:21.000Z
2021-02-22T16:46:00.000Z
vm/src/lib/string.c
e-wiki/jsos
a84c42b37974034891563351f5d0bb92d21f4b7a
[ "NCSA", "BSD-2-Clause", "Unlicense" ]
12
2015-04-17T12:00:54.000Z
2018-08-08T08:12:04.000Z
vm/src/lib/string.c
e-wiki/jsos
a84c42b37974034891563351f5d0bb92d21f4b7a
[ "NCSA", "BSD-2-Clause", "Unlicense" ]
177
2015-01-05T00:42:10.000Z
2021-03-24T15:41:36.000Z
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #include "string.h" #include "lib.h" #include "object.h" #include "gc.h" #include "exception.h" typedef struct { js_value_t base; js_string_t string; } js_string_object_t; static bool statically_initialized; static js_object_internal_methods_t string_vtable; static VAL String_call(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(argc == 0) { return js_value_make_cstring(""); } else { return js_to_string(argv[0]); } } static VAL String_construct(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(argc == 0) { return js_make_string_object(vm, js_cstring("")); } else { js_value_t* val = js_value_get_pointer(js_to_string(argv[1])); return js_make_string_object(vm, &val->string); } } VAL js_make_string_object(js_vm_t* vm, js_string_t* string) { js_string_object_t* str = js_alloc(sizeof(js_string_object_t)); str->base.type = JS_T_STRING_OBJECT; str->base.object.vtable = &string_vtable; str->base.object.prototype = vm->lib.String_prototype; str->base.object.class = vm->lib.String; str->base.object.properties = js_st_table_new(); str->string.buff = string->buff; str->string.length = string->length; VAL v = js_value_make_pointer((js_value_t*)str); js_object_put(v, js_cstring("length"), js_value_make_double(str->string.length)); return v; } static bool is_string_integer(js_string_t* str) { uint32_t i; for(i = 0; i < str->length; i++) { if(str->buff[i] < '0' || str->buff[i] > '9') { // not an integer return false; } } return true; } static VAL string_vtable_get(js_value_t* obj, js_string_t* prop) { js_string_object_t* str = (js_string_object_t*)obj; if(is_string_integer(prop)) { uint32_t idx = atoi(prop->buff); if(idx < str->string.length) { char x = str->string.buff[idx]; return js_value_make_string(&x, 1); } } return js_object_base_vtable()->get(obj, prop); } static VAL String_fromCharCode(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { js_value_t* val = js_alloc(sizeof(js_value_t)); val->type = JS_T_STRING; val->string.length = argc; val->string.buff = js_alloc_no_pointer(val->string.length + 1); uint32_t i; for(i = 0; i < argc; i++) { val->string.buff[i] = (uint8_t)js_value_get_double(js_to_number(argv[i])); } val->string.buff[i] = 0; return js_value_make_pointer(val); } static VAL String_prototype_toString(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { js_throw_error(vm->lib.TypeError, "String.prototype.toString() is not generic"); } js_string_object_t* strobj = ((js_string_object_t*)js_value_get_pointer(this)); return js_value_wrap_string(&strobj->string); } static VAL String_prototype_valueOf(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { js_throw_error(vm->lib.TypeError, "String.prototype.valueOf() is not generic"); } js_string_object_t* strobj = ((js_string_object_t*)js_value_get_pointer(this)); return js_value_wrap_string(&strobj->string); } static VAL String_prototype_substr(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { js_throw_error(vm->lib.TypeError, "String.prototype.substr() is not generic"); } js_string_object_t* str = (js_string_object_t*)js_value_get_pointer(this); if(argc == 0) { return this; } if(argc == 1) { uint32_t index = js_to_uint32(argv[0]); if(index >= str->string.length) { return js_value_make_cstring(""); } return js_value_make_string(str->string.buff + index, str->string.length - index); } uint32_t index = js_to_uint32(argv[0]); uint32_t length = js_to_uint32(argv[1]); if(index >= str->string.length) { return js_value_make_cstring(""); } if(index + length >= str->string.length) { length = str->string.length - index; } return js_value_make_string(str->string.buff + index, length); } static VAL String_prototype_trimRight(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { js_throw_error(vm->lib.TypeError, "String.prototype.trimRight() is not generic"); } js_string_object_t* str = (js_string_object_t*)js_value_get_pointer(this); uint32_t new_len = str->string.length; while(str->string.buff[new_len - 1] == ' ') { if(--new_len == 0) { return js_value_make_cstring(""); } } return js_value_make_string(str->string.buff, new_len); } static VAL String_prototype_indexOf(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { // @TODO throw exception js_panic("String.prototype.substr() is not generic"); } if(argc > 0) { uint32_t index = 0; js_string_t* needle = js_to_js_string_t(argv[0]); js_string_t* haystack = js_to_js_string_t(this); if(js_string_index_of(haystack, needle, &index)) { return js_value_make_double(index); } } return js_value_make_double(-1); } static VAL String_prototype_split(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { // @TODO throw exception js_panic("String.prototype.substr() is not generic"); } if(argc == 0) { return js_make_array(vm, 1, &this); } js_string_t* delimiter = js_to_js_string_t(argv[0]); uint32_t capacity = 4; uint32_t count = 0; VAL* items = js_alloc(sizeof(VAL) * 4); js_string_t remaining = ((js_string_object_t*)js_value_get_pointer(this))->string; uint32_t index; while(js_string_index_of(&remaining, delimiter, &index)) { if(count + 1 == capacity) { capacity *= 2; items = js_realloc(items, sizeof(VAL) * capacity); } items[count++] = js_value_make_string(remaining.buff, index); index += delimiter->length; remaining.buff += index; remaining.length -= index; } items[count++] = js_value_make_string(remaining.buff, remaining.length); return js_make_array(vm, count, items); } static VAL String_prototype_toLowerCase(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { // @TODO throw exception js_panic("String.prototype.substr() is not generic"); } js_string_object_t* str = (js_string_object_t*)js_value_get_pointer(this); js_value_t* new_str = (js_value_t*)js_alloc(sizeof(js_value_t)); new_str->type = JS_T_STRING; new_str->string.buff = js_alloc_no_pointer(str->string.length + 1); new_str->string.length = str->string.length; memcpy(new_str->string.buff, str->string.buff, str->string.length); uint32_t i; for(i = 0; i < str->string.length; i++) { if(new_str->string.buff[i] >= 'A' && new_str->string.buff[i] <= 'Z') { new_str->string.buff[i] += 'a' - 'A'; } } return js_value_make_pointer(new_str); } static VAL String_prototype_trim(js_vm_t* vm, void* state, VAL this, uint32_t argc, VAL* argv) { if(js_value_get_type(this) != JS_T_STRING_OBJECT) { // @TODO throw exception js_panic("String.prototype.trim() is not generic"); } js_string_object_t* str = (js_string_object_t*)js_value_get_pointer(this); uint32_t trimBegin = 0; uint32_t trimEnd = str->string.length; for(; trimBegin < str->string.length; trimBegin++) { char c = str->string.buff[trimBegin]; if(c != ' ' && c != '\n' && c != '\t') { break; } } for(; trimEnd > trimBegin; trimEnd--) { char c = str->string.buff[trimEnd - 1]; if(c != ' ' && c != '\n' && c != '\t') { break; } } return js_value_make_string(str->string.buff + trimBegin, trimEnd - trimBegin); } void js_lib_string_initialize(js_vm_t* vm) { if(!statically_initialized) { statically_initialized = true; memcpy(&string_vtable, js_object_base_vtable(), sizeof(js_object_internal_methods_t)); string_vtable.get = string_vtable_get; } vm->lib.String = js_value_make_native_function(vm, NULL, js_cstring("String"), String_call, String_construct); js_object_put(vm->global_scope->global_object, js_cstring("String"), vm->lib.String); vm->lib.String_prototype = js_value_make_object(vm->lib.Object_prototype, vm->lib.String); js_object_put(vm->lib.String, js_cstring("prototype"), vm->lib.String_prototype); js_object_put(vm->lib.String, js_cstring("fromCharCode"), js_value_make_native_function(vm, NULL, js_cstring("fromCharCode"), String_fromCharCode, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("toString"), js_value_make_native_function(vm, NULL, js_cstring("toString"), String_prototype_toString, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("valueOf"), js_value_make_native_function(vm, NULL, js_cstring("valueOf"), String_prototype_valueOf, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("substr"), js_value_make_native_function(vm, NULL, js_cstring("substr"), String_prototype_substr, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("trimRight"), js_value_make_native_function(vm, NULL, js_cstring("trimRight"), String_prototype_trimRight, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("indexOf"), js_value_make_native_function(vm, NULL, js_cstring("indexOf"), String_prototype_indexOf, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("split"), js_value_make_native_function(vm, NULL, js_cstring("split"), String_prototype_split, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("toLowerCase"), js_value_make_native_function(vm, NULL, js_cstring("toLowerCase"), String_prototype_toLowerCase, NULL)); js_object_put(vm->lib.String_prototype, js_cstring("trim"), js_value_make_native_function(vm, NULL, js_cstring("trim"), String_prototype_trim, NULL)); }
39.423221
175
0.67414
[ "object" ]
73244c759ed1ecd391ffe0a02b71a1851a78c1f8
866
h
C
inex/extensions.h
PhysShell/inexplicable_engine
a91d2f30fc4c64abd5a78fd71f21b13052c86c9d
[ "WTFPL" ]
null
null
null
inex/extensions.h
PhysShell/inexplicable_engine
a91d2f30fc4c64abd5a78fd71f21b13052c86c9d
[ "WTFPL" ]
null
null
null
inex/extensions.h
PhysShell/inexplicable_engine
a91d2f30fc4c64abd5a78fd71f21b13052c86c9d
[ "WTFPL" ]
null
null
null
#ifndef EXTENSIONS_H_INCLUDED # define EXTENSIONS_H_INCLUDED # include <stdarg.h> # include <cstring> # include <iostream> # include <cstdint> // os_extensions // # include <inex/macro_extensions.h> # include <inex/core/api.h> //# include <inex/render/api.h> //# include <inex/sound/api.h> //# include <inex/ui/api.h> # include <inex/types.h> # include <inex/core/sources/ie_debug.h> # include <inex/core/sources/logger.h> # include <inex/os_extensions.h> # include <inex/memory_extensions.h> //# include <inex/stl_extensions_vector.h> # include <inex/core/sources/ie_syncronize.h> //#include ie_memory.h # include <inex/math_functions.h> # include <inex/math_float3.h> # include <inex/math_float4x4.h> # include <inex/core/sources/fs_file_system.h> //# include <inex/core/sources/fs_manager.h> #endif // #ifdef EXTENSIONS_H_INCLUDED
24.742857
48
0.71709
[ "render" ]
7327a767bbf55f9ce66f40dafaba2a535bfc0c55
48,405
h
C
src/simple_matrix.h
ETCHKILI/cs205-project-simple-matrix
076cff23987758e55f60ea590d78bb17be7406ef
[ "MIT" ]
2
2021-05-19T18:49:35.000Z
2021-06-09T10:06:25.000Z
src/simple_matrix.h
ETCHKILI/cs205-project-simple-matrix
076cff23987758e55f60ea590d78bb17be7406ef
[ "MIT" ]
null
null
null
src/simple_matrix.h
ETCHKILI/cs205-project-simple-matrix
076cff23987758e55f60ea590d78bb17be7406ef
[ "MIT" ]
1
2021-06-09T16:44:41.000Z
2021-06-09T16:44:41.000Z
/* MIT License Copyright (c) 2021 ETCHKILI 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. */ /** * @file simple_matrix.cpp * @author Guo Yubin, Shen Zhilong, Fan Leilong * @date 2021-06-11 * @Github https://github.com/ETCHKILI/cs205-project-simple-matrix * @Organization SUSTech * @version 0.1.0 * @attention Should specify the OpenCV(compiled by mingw) path and Eigen path * in the CMakeLists.txt. For detail please see CmakeLists.txt */ #ifndef CS205_PROJECT_SIMPLE_MATRIX_SIMPLE_MATRIX_H #define CS205_PROJECT_SIMPLE_MATRIX_SIMPLE_MATRIX_H #include "simple_matrix_exception.h" #include <cstdint> #include <iterator> #include <vector> #include <opencv2/opencv.hpp> #include <Eigen/Dense> #include <opencv2/core/mat.hpp> #include <opencv2/core/eigen.hpp> #include <iostream> #include <functional> #include <cmath> #include <typeinfo> /** * @brief The namespace of the simple_matrix project, including one * matrix class and three exception class */ namespace simple_matrix { static const constexpr int64_t kDefaultRowSize = 10; static const constexpr int64_t kDefaultColumnSize = 10; static const constexpr int64_t kDefaultSideLength = 10; static const uint64_t kMaxAllocateSize = UINT64_MAX; static const int64_t kOSBits = sizeof (void *) * 8; static const double eps = 1e-3; /** * @brief Enum class that specify the direction of the vector(s): * Row vector, Column vector or a Sub-matrix */ enum class SelectAs { SUB_MATRIX, ROW, COLUMN }; /** * @class Matrix * @brief Base class in simple_matrix * @tparam T * @details Use one-dimension array to simulate a matrix * store the data in continuous heap memory which make it efficient */ template<typename T> class Matrix { private: protected: /** * @brief the pointer to the data array */ T *data_; uint64_t row_size_; ///< the row size uint64_t column_size_; ///< the column size explicit Matrix(); public: T *operator[](int row) const; explicit Matrix(uint64_t row_size, uint64_t column_size); explicit Matrix(uint64_t row_size, uint64_t column_size, const T &initial_value); explicit Matrix(const std::vector<T> &v, SelectAs selectAs); explicit operator cv::Mat_<T>(); Matrix(const Matrix<T> &that); Matrix(Matrix<T> &&that) noexcept; Matrix<T> &operator=(const Matrix<T> &that); Matrix<T> &operator=(Matrix<T> &&that) noexcept; virtual ~Matrix(); virtual T &Access(uint64_t row, uint64_t column); virtual void SetValue(T val); [[nodiscard]] uint64_t getRowSize() const; [[nodiscard]] uint64_t getColumnSize() const; static bool CheckSizeValid(uint64_t row_size, uint64_t column_size); [[nodiscard]] Matrix<T> operator+(const Matrix<T> &that); [[nodiscard]] Matrix<T> operator+(const T &k); Matrix<T> &operator+=(const Matrix<T> &that); Matrix<T> &operator+=(const T &k); [[nodiscard]] Matrix<T> operator-(const Matrix<T> &that); [[nodiscard]] Matrix<T> operator-(const T &k); Matrix<T> &operator-=(const Matrix<T> &that); Matrix<T> &operator-=(const T &k); [[nodiscard]] Matrix<T> operator*(const Matrix<T> &that); [[nodiscard]] Matrix<T> operator*(const T &k); Matrix<T> &operator*=(const Matrix<T> &that); Matrix<T> &operator*=(const T &k); [[nodiscard]] Matrix<T> operator/(const Matrix<T> &that); [[nodiscard]] Matrix<T> operator/(const T &k); Matrix<T> &operator/=(const Matrix<T> &that); Matrix<T> &operator/=(const T &k); T FindMin(std::vector<int32_t> index = std::vector<int32_t>(), SelectAs selectAs = SelectAs::SUB_MATRIX, std::function<bool(const T &, const T &)> compare = [](const T &a, const T &b) { return a < b; }); T FindMax(std::vector<int32_t> index = std::vector<int32_t>(), SelectAs selectAs = SelectAs::SUB_MATRIX, std::function<bool(const T &, const T &)> compare = [](const T &a, const T &b) { return a > b; }); T Sum(std::vector<int32_t> index = std::vector<int32_t>(), SelectAs selectAs = SelectAs::SUB_MATRIX); T Average(std::vector<int32_t> index = std::vector<int32_t>(), SelectAs selectAs = SelectAs::SUB_MATRIX); Matrix<T> getRotate180(); Matrix<T> subMatrix(uint64_t row_lo, uint64_t col_lo, uint64_t row_hi, uint64_t col_hi); Matrix<T> convolution(Matrix<T> &that); [[nodiscard]] Matrix<T> transpose(); static Matrix<T> identity(uint64_t s, T t); [[nodiscard]] Matrix<double> Householder(uint64_t col, uint64_t ele); [[nodiscard]] Matrix<double> Hessenberg(); [[nodiscard]] Matrix<double> Givens(uint64_t col, uint64_t begin, uint64_t end); [[nodiscard]] Matrix<double> QR_iteration(); [[nodiscard]] std::vector<double> eigenvalue(); [[nodiscard]] Matrix<T> inverse(); std::vector<std::pair<T, std::vector<T>>> eigen(); [[nodiscard]] T trace(); [[nodiscard]] T determinant(); [[nodiscard]] Matrix<T> reshape(int32_t row, int32_t col); [[nodiscard]] Matrix<T> slice(int32_t row1, int32_t row2, int32_t col1, int32_t col2); [[nodiscard]] Matrix<T> Conjugate(std::function<T(const T &)> conjugate); }; /** * @protected because it is not meaningful to create a 1-row-1-column * matrix. If it is needed, you can specify the size. * @tparam T */ template<typename T> Matrix<T>::Matrix() { Matrix(1, 1); } /** * @brief Constructor that initialize the element with default constructor * @tparam T * @param row_size * @param column_size */ template<typename T> Matrix<T>::Matrix(uint64_t row_size, uint64_t column_size) { if (!CheckSizeValid(row_size, column_size)) { throw simple_matrix::BadSizeException("Size invalid!"); } data_ = new T[row_size * column_size](); column_size_ = column_size; row_size_ = row_size; } /*! * @brief Constructor that initialize the data * @tparam T * @param row_size * @param column_size * @param initial_value */ template<typename T> Matrix<T>::Matrix(uint64_t row_size, uint64_t column_size, const T &initial_value) { if (!CheckSizeValid(row_size, column_size)) { throw simple_matrix::BadSizeException("Size too large!"); } data_ = new T[row_size * column_size](); column_size_ = column_size; row_size_ = row_size; for (int i = 0; i < row_size_; ++i) { for (int j = 0; j < column_size_; ++j) { data_[i * column_size_ + j] = initial_value; } } } /** * @brief Constructor by a vector * @tparam T * @param v * @param selectAs */ template<typename T> Matrix<T>::Matrix(const std::vector<T> &v, SelectAs selectAs) { if (v.empty()) { throw BadSizeException("Size zero error"); } data_ = new T[v.size()]; if (selectAs == SelectAs::COLUMN) { column_size_ = v.size(); row_size_ = 1; } else { column_size_ = 1; row_size_ = v.size(); } } /** * @brief Copy constructor * @tparam T * @param that */ template<typename T> Matrix<T>::Matrix(const Matrix<T> &that) { data_ = new T[that.row_size_ * that.column_size_]; row_size_ = that.row_size_; column_size_ = that.column_size_; int n = row_size_ * column_size_; for (int i = 0; i < n; ++i) { data_[i] = that.data_[i]; } } /** * @brief Move constructor * @tparam T * @param that */ template<typename T> Matrix<T>::Matrix(Matrix<T> &&that) noexcept { data_ = that.data_; row_size_ = that.row_size_; column_size_ = that.column_size_; that.data_ = nullptr; } /** * @brief Destructor : delete []data * @tparam T * @param row_size * @param column_size * @param initial_value */ template<typename T> Matrix<T>::~Matrix() { if (data_ != nullptr) { delete[]data_; } } /** * @brief Copy assignment * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator=(const Matrix<T> &that) { if (this != &that) { data_ = new T[that.row_size_ * that.column_size_]; row_size_ = that.row_size_; column_size_ = that.column_size_; int n = row_size_ * column_size_; for (int i = 0; i < n; ++i) { data_[i] = that.data_[i]; } } return *this; } /** * @brief Move assignment * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator=(Matrix<T> &&that) noexcept { if (this != &that) { data_ = that.data_; row_size_ = that.row_size_; column_size_ = that.column_size_; that.data_ = nullptr; } return *this; } /** * @brief The operator[] which can access the data * @detail return a pointer equal to (data_ + row * column_size_) * @example use like this: {@code matrix[i][j]} to access the data in row i and column j * @tparam T * @param row * @return */ template<typename T> T *Matrix<T>::operator[](int row) const { return data_ + row * column_size_; } /** * @brief Check if the size is valid for constructing a matrix * @tparam T * @param row_size * @param column_size * @return True if the size is valid for constructing a matrix. False if not */ template<typename T> bool Matrix<T>::CheckSizeValid(uint64_t row_size, uint64_t column_size) { return ((row_size <= kMaxAllocateSize / column_size) || (column_size <= kMaxAllocateSize / row_size)) && std::max(row_size, column_size) > 0; } /** * @brief Set the value for the whole matrix * @tparam T * @param val */ template<typename T> void Matrix<T>::SetValue(T val) { if (data_ == nullptr) { throw BadAccessException("Matrix is not initialized or index out of range"); } for (int i = 0; i < row_size_; ++i) { for (int j = 0; j < column_size_; ++j) { data_[i * column_size_ + j] = val; } } } /** * @brief The way that can be overloaded by derived class to access the data (get or change the value) * @tparam T * @param row * @param column * @return */ template<typename T> T &Matrix<T>::Access(uint64_t row, uint64_t column) { if (row > row_size_ - 1 || column > column_size_ - 1) { throw BadAccessException("Index out of bounds"); } return (*this)[row][column]; } /** * @brief the public way to get the row_size of the matrix * @tparam T * @return */ template<typename T> uint64_t Matrix<T>::getRowSize() const { return row_size_; } /** * @brief the public way to get the column_size of the matrix * @tparam T * @return */ template<typename T> uint64_t Matrix<T>::getColumnSize() const { return column_size_; } /** * @brief operator overload * @tparam T * @param that: another matrix * @return */ template<typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T> &that) { if (this->column_size_ != that.column_size_ || this->row_size_ != that.row_size_) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] + that.data_[i]; } return result; } /** * @brief operator overload, every element of the matrix should be operate with the value * @tparam T * @param k: a value * @return */ template<typename T> Matrix<T> Matrix<T>::operator+(const T &k) { Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] + k; } return result; } /** * @brief operator overload * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &that) { if (this->column_size_ != that.column_size_ || this->row_size_ != that.row_size_) { throw ArgumentNotMatchException("Matrix size not match"); } uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] + that.data_[i]; } return (*this); } /** * @brief operator overload * @tparam T * @param k * @return */ template<typename T> Matrix<T> &Matrix<T>::operator+=(const T &k) { uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] + k; } return (*this); } /** * @brief operator overload * @tparam T * @param that: another matrix * @return */ template<typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T> &that) { if (this->column_size_ != that.column_size_ || this->row_size_ != that.row_size_) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] - that.data_[i]; } return result; } /** * @brief operator overload, every element of the matrix should be operate with the value * @tparam T * @param k: a value * @return */ template<typename T> Matrix<T> Matrix<T>::operator-(const T &k) { Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] - k; } return result; } /** * @brief operator overload * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator-=(const Matrix<T> &that) { if (this->column_size_ != that.column_size_ || this->row_size_ != that.row_size_) { throw ArgumentNotMatchException("Matrix size not match"); } uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] - that.data_[i]; } return (*this); } /** * @brief operator overload * @tparam T * @param k * @return */ template<typename T> Matrix<T> &Matrix<T>::operator-=(const T &k) { uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] - k; } return (*this); } /** * @brief operator overload * @tparam T * @param that: another matrix * @detail use continuous memory access to speed up the cross multiplication * @return the result of cross product of two matrix */ template<typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T> &that) { if (this->column_size_ != that.row_size_ || this->row_size_ != that.column_size_) { throw ArgumentNotMatchException("Matrix size not match"); } int n = this->row_size_; Matrix<T> result(n, n); for (int i = 0; i < n; ++i) { for (int k = 0; k < this->column_size_; ++k) { T temp = (*this)[i][k]; for (int j = 0; j < n; ++j) { result[i][j] = result[i][j] + temp * that[k][j]; } } } return result; } /** * @brief operator overload * @tparam T * @param k * @return */ template<typename T> Matrix<T> Matrix<T>::operator*(const T &k) { Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] * k; } return result; } /** * @brief operator overload * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator*=(const Matrix<T> &that) { (*this) = (*this) * that; return (*this); } /** * @brief operator overload * @tparam T * @param k * @return */ template<typename T> Matrix<T> &Matrix<T>::operator*=(const T &k) { uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] * k; } return (*this); } /** * @brief Division between matrix, A / B is calculated as A * B.inverse * @tparam T * @param that * @return */ template<typename T> Matrix<T> Matrix<T>::operator/(const Matrix<T> &that) { return (*this) * that.inverse(); } /** * @brief operator overload * @tparam T * @param k * @return */ template<typename T> Matrix<T> Matrix<T>::operator/(const T &k) { Matrix<T> result(this->row_size_, this->column_size_); uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = this->data_[i] / k; } return result; } /** * @brief operator overload * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator/=(const Matrix<T> &that) { (*this) = (*this) / that; return (*this); } /** * @brief operator overload * @tparam T * @param that * @return */ template<typename T> Matrix<T> &Matrix<T>::operator/=(const T &k) { uint64_t n = this->row_size_ * this->column_size_; for (int i = 0; i < n; ++i) { this->data_[i] = this->data_[i] / k; } return (*this); } /** * @brief Implement the convolution of the matrix, supported by the operator overloads * @tparam T * @param that * @return the result matrix */ template<typename T> Matrix<T> Matrix<T>::convolution(Matrix<T> &that) { uint64_t new_row_size = this->row_size_ + that.row_size_ - 1; uint64_t new_col_size = this->column_size_ + that.column_size_ - 1; Matrix<T> res(new_row_size, new_col_size); Matrix<T> thatRotated = that.getRotate180(); uint64_t ROW_lo, ROW_hi, COL_lo, COL_hi; for (uint64_t ROW = 0; ROW < new_row_size; ++ROW) { for (uint64_t COL = 0; COL < new_col_size; ++COL) { ROW_lo = (that.row_size_ - 1 > ROW) ? that.row_size_ - 1 : ROW; COL_lo = (that.column_size_ - 1 > COL) ? that.column_size_ - 1 : COL; ROW_hi = (that.row_size_ + this->row_size_ - 2 < ROW + that.row_size_ - 1) ? that.row_size_ + this->row_size_ - 2 : ROW + that.row_size_ - 1; COL_hi = (that.column_size_ + this->column_size_ - 2 < COL + that.column_size_ - 1) ? that.column_size_ + this->column_size_ - 2 : COL + that.column_size_ - 1; auto a = this->subMatrix(ROW_lo - that.row_size_ + 1, COL_lo - that.column_size_ + 1, ROW_hi - that.row_size_ + 1, COL_hi - that.column_size_ + 1); auto b = thatRotated.subMatrix(ROW_lo - ROW, COL_lo - COL, ROW_hi - ROW, COL_hi - COL); res[ROW][COL] = InnerProduct(a, b); } } return res; } /** * @brief Implement the innerProduct of the matrix * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto InnerProduct(Matrix<T1> a, Matrix<T2> b) { using T3 = decltype(std::declval<T1>() * std::declval<T2>()); auto na = a.getRowSize(); auto ma = a.getColumnSize(); auto nb = b.getRowSize(); auto mb = b.getColumnSize(); if (na != nb || ma != mb) { throw ArgumentNotMatchException("Matrix size not match"); } T3 innerProduct = a.Access(0, 0) * b.Access(0, 0); for (int i = 1; i < na * ma; ++i) { innerProduct += a.Access(i / ma, i % ma) * b.Access(i / mb, i % mb); } return innerProduct; } /** * @brief the sub-matrix specified by the index * @tparam T * @param row_lo * @param col_lo * @param row_hi * @param col_hi * @return */ template<typename T> Matrix<T> Matrix<T>::subMatrix(uint64_t row_lo, uint64_t col_lo, uint64_t row_hi, uint64_t col_hi) { uint64_t new_row_size = row_hi - row_lo + 1; uint64_t new_col_size = col_hi - col_lo + 1; Matrix<T> res(new_row_size, new_col_size); for (int i = 0; i < new_row_size; ++i) { for (int j = 0; j < new_col_size; ++j) { res.Access(i, j) = Access(row_lo + i, col_lo + j); } } return res; } /** * @brief Get a matrix which is the result of 180-rotation of this matrix * @tparam T * @return */ template<typename T> Matrix<T> Matrix<T>::getRotate180() { Matrix<T> res(row_size_, column_size_); for (int i = 0; i < row_size_ * column_size_; ++i) { res.Access(i / column_size_, i % column_size_) = Access(row_size_ - 1 - (int) (i / column_size_), column_size_ - 1 - i % column_size_); } return res; } /** * @brief Find the min element, in the matrix (or rows or columns or sub-matrix, you * can specify the index by a vector) * @tparam T * @param index : the vector that specify the index * @param selectAs * @param compare * @return */ template<typename T> T Matrix<T>::FindMin(std::vector<int32_t> index, SelectAs selectAs, std::function<bool(const T &, const T &)> compare) { T res; if (selectAs == SelectAs::COLUMN) { res = data_[index[0]]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < row_size_; ++j) { if (compare(data_[j * column_size_ + index[i]], res)) { res = data_[j * column_size_ + index[i]]; } } } } else if (selectAs == SelectAs::ROW) { res = data_[index[0] * column_size_]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < column_size_; ++j) { if (compare(data_[index[i] * column_size_ + j], res)) { res = data_[index[i] * column_size_ + j]; } } } } else { if (index.empty()) { index = std::vector<int32_t>(); index.push_back(0); index.push_back(0); index.push_back(row_size_); index.push_back(column_size_); } res = data_[index[0] * column_size_ + index[1]]; for (int i = index[0]; i < index[2]; ++i) { for (int j = index[1]; j < index[3]; ++j) { if (compare(data_[i * column_size_ + j], res)) { res = data_[i * column_size_ + j]; } } } } return res; } /** * @brief Find the max element, in the matrix (or rows or columns or sub-matrix, you * can specify the index by a vector) * @tparam T * @param index : the vector that specify the index * @param selectAs * @param compare * @return */ template<typename T> T Matrix<T>::FindMax(std::vector<int32_t> index, SelectAs selectAs, std::function<bool(const T &, const T &)> compare) { T res; if (selectAs == SelectAs::COLUMN) { res = data_[index[0]]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < row_size_; ++j) { if (compare(data_[j * column_size_ + index[i]], res)) { res = data_[j * column_size_ + index[i]]; } } } } else if (selectAs == SelectAs::ROW) { res = data_[index[0] * column_size_]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < column_size_; ++j) { if (compare(data_[index[i] * column_size_ + j], res)) { res = data_[index[i] * column_size_ + j]; } } } } else { if (index.empty()) { index = std::vector<int32_t>(); index.push_back(0); index.push_back(0); index.push_back(row_size_); index.push_back(column_size_); } res = data_[index[0] * column_size_ + index[1]]; for (int i = index[0]; i < index[2]; ++i) { for (int j = index[1]; j < index[3]; ++j) { if (compare(data_[i * column_size_ + j], res)) { res = data_[i * column_size_ + j]; } } } } return res; } /** * @brief Sum the min element, in the matrix (or rows or columns or sub-matrix, you * can specify the index by a vector) * @tparam T * @param index : the vector that specify the index * @param selectAs * @param compare * @return */ template<typename T> T Matrix<T>::Sum(std::vector<int32_t> index, SelectAs selectAs) { T res; if (selectAs == SelectAs::COLUMN) { res = data_[index[0]]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < row_size_; ++j) { if (i != 0 || j != 0) { res = res + data_[j * column_size_ + index[i]]; } } } } else if (selectAs == SelectAs::ROW) { res = data_[index[0] * column_size_]; for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < column_size_; ++j) { if (i != 0 || j != 0) { res = res + data_[index[i] * column_size_ + j]; } } } } else { if (index.empty()) { index = std::vector<int32_t>(); index.push_back(0); index.push_back(0); index.push_back(row_size_); index.push_back(column_size_); } res = data_[index[0] * column_size_ + index[1]]; for (int i = index[0]; i < index[2]; ++i) { for (int j = index[1]; j < index[3]; ++j) { if (i != index[0] || j != index[1]) { res = res + data_[i * column_size_ + j]; } } } } return res; } /** * @brief Find the average, in the matrix (or rows or columns or sub-matrix, you * can specify the index by a vector) * @tparam T * @param index : the vector that specify the index * @param selectAs * @param compare * @return */ template<typename T> T Matrix<T>::Average(std::vector<int32_t> index, SelectAs selectAs) { return (Sum(index, selectAs) / (row_size_ * column_size_)); } /** * @brief operator overload, extra support added if two types can be operated. * For example, if T1 + T2 is valid, then Matrix<T1> + Matrix<T2> is valid * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto operator+(Matrix<T1> &a, Matrix<T2> &b) { using T3 = decltype(std::declval<T1>() + std::declval<T2>()); auto na = a.getRowSize(); auto ma = a.getColumnSize(); auto nb = b.getRowSize(); auto mb = b.getColumnSize(); if (na != nb || ma != mb) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T3> c(na, ma); for (int i = 0; i < na; ++i) { for (int j = 0; j < ma; ++j) { c.Access(i, j) = a.Access(i, j) + b.Access(i, j); } } return c; } /** * @brief operator overload, extra support added if two types can be operated. * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto operator-(Matrix<T1> &a, Matrix<T2> &b) { using T3 = decltype(std::declval<T1>() - std::declval<T2>()); auto na = a.getRowSize(); auto ma = a.getColumnSize(); auto nb = b.getRowSize(); auto mb = b.getColumnSize(); if (na != nb || ma != mb) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T3> c(na, ma); for (int i = 0; i < na; ++i) { for (int j = 0; j < ma; ++j) { c.Access(i, j) = a.Access(i, j) - b.Access(i, j); } } return c; } /** * @brief operator overload, extra support added if two types can be operated. * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto operator*(Matrix<T1> &a, Matrix<T2> &b) { using T3 = decltype(std::declval<T1>() * std::declval<T2>()); auto na = a.getRowSize(); auto ma = a.getColumnSize(); auto nb = b.getRowSize(); auto mb = b.getColumnSize(); if (na != mb || ma != nb) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T3> c(na, na); for (int i = 0; i < na; ++i) { for (int k = 0; k < ma; ++k) { T1 temp = a.Access(i, k); for (int j = 0; j < na; ++j) { c.Access(i, j) = c.Access(i, j) + temp * b.Access(k, j); } } } return c; } /** * @brief Implement the dot multiplication * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto DotMultiply(Matrix<T1> &a, Matrix<T2> &b) { using T3 = decltype(std::declval<T1>() * std::declval<T2>()); auto na = a.getRowSize(); auto ma = a.getColumnSize(); auto nb = b.getRowSize(); auto mb = b.getColumnSize(); if (na != nb || ma != mb) { throw ArgumentNotMatchException("Matrix size not match"); } Matrix<T3> c(na, ma); for (int i = 0; i < na; ++i) { for (int j = 0; j < ma; ++j) { c.Access(i, j) = a.Access(i, j) * b.Access(i, j); } } return c; } /** * @brief operator overload, extra support added if two types can be operated. * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto operator*(Matrix<T1> &a, std::vector<T2> &b) { using T3 = decltype(std::declval<T1>() * std::declval<T2>()); if (a.getColumnSize() != b.size()) { throw ArgumentNotMatchException("Matrix and Vector size not match"); } Matrix<T3> c(a.getRowSize(), 1); for (int i = 0; i < a.getRowSize(); ++i) { for (int j = 0; j < a.getColumnSize(); ++j) { c.Access(i, 1) = c.Access(i, 1) + a.Access(i, j) * b[j]; } } return c; } /** * @brief operator overload, extra support added if two types can be operated. * @tparam T1 * @tparam T2 * @param a * @param b * @return */ template<typename T1, typename T2> [[nodiscard]] auto operator/(Matrix<T1> &a, const T2 &b) { using T3 = decltype(std::declval<T1>() * std::declval<T2>()); uint64_t n = a.getRowSize(); uint64_t m = a.getColumnSize(); Matrix<T3> c(n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { c[i][j] = a.Access(i, j) / b; } } } /** * @warning It is very slow to print the matrix to the output * @tparam T * @param ostream * @param matrix * @return the reference of ostream itself */ template<typename T> auto &operator<<(std::ostream &ostream, const Matrix<T> &matrix) { for (int i = 0; i < matrix.getRowSize(); ++i) { for (int j = 0; j < matrix.getColumnSize(); ++j) { ostream << matrix[i][j] << ' '; } ostream << '\n'; } return ostream; } /** * Implement the transpose of a Matrix * @tparam T * @return */ template<typename T> Matrix<T> Matrix<T>::transpose() { Matrix<T> res(this->column_size_, this->row_size_); for (uint64_t i = 0; i < this->row_size_; ++i) { for (uint64_t j = 0; j < this->column_size_; ++j) { res.Access(j, i) = this->Access(i, j); } } return res; } /** * @static get a identity Matrix of given size * @tparam T * @param s * @param t * @return */ template<typename T> Matrix<T> Matrix<T>::identity(uint64_t s, T t) { Matrix<T> res(s, s); for (uint64_t i = 0; i < s; ++i) { res.Access(i, i) = t; } return res; } /** * @brief * @tparam T * @param col * @param ele * @return */ template<typename T> Matrix<double> Matrix<T>::Householder(uint64_t col, uint64_t ele) { double square = 0; for (uint64_t i = ele - 1; i < row_size_ * column_size_; ++i) { square += pow(this->Access(i, col - 1), 2); } double mod = this->Access(ele - 1, col - 1) > 0 ? pow(square, 0.5) : -pow(square, 0.5); double modulus = mod * (mod + this->Access(ele - 1, col - 1)); Matrix<double> U(this->row_size_, 1); for (int j = 0; j < this->row_size_; ++j) { if (j > ele - 1) { U.Access(j, 0) = this->Access(j, col - 1); } else { U.Access(j, 0) = 0; } } U.Access(ele - 1, 0) = this->Access(ele - 1, col - 1) + mod; return Matrix<double>::identity(this->row_size_, 1) - U * U.transpose() / modulus; } /** * @brief * @tparam T * @param col * @param ele * @return */ template<typename T> Matrix<double> Matrix<T>::Hessenberg() { if (this->column_size_ != this->row_size_) { throw std::invalid_argument("The matrix needs to be square"); } Matrix<double> left_H = Matrix<double>::identity(this->row_size_, 1); Matrix<double> right_H = Matrix<double>::identity(this->row_size_, 1); Matrix<double> H = left_H * (*this) * right_H; for (int i = 1; i < this->row_size_ - 1; ++i) { if (abs(H.Access(i + 1, i - 1)) > eps) { left_H = left_H * H.Householder(i, i + 1); right_H = H.Householder(i, i + 1) * right_H; H = left_H * (*this) * right_H; } } return H; } /** * * @tparam T * @param col * @param begin * @param end * @return */ template<typename T> Matrix<double> Matrix<T>::Givens(uint64_t col, uint64_t begin, uint64_t end) { Matrix<double> R = Matrix<double>::identity(this->row_size_, 1); double r = pow(pow(this->Access(begin - 1, col - 1), 2) + pow(this->Access(end - 1, col - 1), 2), 0.5); double c = 1; double s = 0; if (abs(r) > eps) { c = this->Access(begin - 1, col - 1) / r; s = this->Access(end - 1, col - 1) / r; } R.Access(begin - 1, begin - 1) = c; R.Access(begin - 1, end - 1) = s; R.Access(end - 1, begin - 1) = -s; R.Access(end - 1, end - 1) = c; return R; } /** * @brief QR iteration implemented * @tparam T * @return */ template<typename T> Matrix<double> Matrix<T>::QR_iteration() { Matrix<double> R = this->Hessenberg(); Matrix<double> Q = Matrix<double>::identity(this->row_size_, 1); for (uint64_t i = 1; i < this->row_size_; ++i) { Matrix<double> temp_R = R.Givens(i, i, i + 1); R = temp_R * R; Q = Q * temp_R.transpose(); } return R * Q; } /** * @brief get eigen value implemented * @tparam T * @return */ template<typename T> std::vector<double> Matrix<T>::eigenvalue() { if (this->column_size_ != this->row_size_) { throw std::invalid_argument("The matrix needs to be square"); } std::vector<double> eigenvalues(this->row_size_); static constexpr int32_t iter_times = 150; Matrix<double> H = this->QR_iteration(); for (int i = 0; i < iter_times; ++i) { H = H.QR_iteration(); } for (int j = 0; j < this->row_size_; ++j) { eigenvalues[j] = H.Access(j, j); } return eigenvalues; } /** * @brief Inverse of Matrix * @tparam T * @return */ template<typename T> Matrix<T> Matrix<T>::inverse() { if ((this->column_size_ != this->row_size_) && this->determinant() == 0) { throw std::invalid_argument("The matrix does not meet the invertible condition (square matrix and the determinant is not 0)"); } Matrix<T> res(this->row_size_, this->column_size_, static_cast<T>(0)); for (int32_t i = 0; i < this->row_size_; i++) { for (int32_t j = 0; j < this->column_size_; j++) { std::vector< std::vector <T>> submatrix(this->row_size_,std::vector<T>(this->column_size_, static_cast<T>(0))); for(int r=0;r<this->row_size_;r++){ for(int c=0;c<this->column_size_;c++){ submatrix[r][c]=this->Access(r,c); } } submatrix.erase(submatrix.begin() + i); for (int m = 0; m < this->row_size_ - 1; ++m) { submatrix[m].erase(submatrix[m].begin() + j); } Matrix<T> sub(submatrix.size(),submatrix[0].size()); for(int r=0;r<submatrix.size();r++){ for(int c=0;c<submatrix[0].size();c++){ sub.Access(r,c)=submatrix[r][c]; } } res[j][i] = (((i + j) % 2) ? -1 : 1) * sub.determinant(); } } Matrix<T> ans = Matrix<T>{res}; ans = ans / this->determinant(); return ans; } /** * @brief trace of Matrix * @tparam T * @return */ template<typename T> T Matrix<T>::trace() { T ans{0}; if (this->column_size_ != this->row_size_) { throw std::invalid_argument("The matrix needs to be square"); } for (int32_t i = 0; i < this->row_size_; ++i) { ans += this->Access(i, i); } return ans; } /** * @brief determinant of Matrix * @tparam T * @return */ template<typename T> T Matrix<T>::determinant() { if (this->column_size_ != this->row_size_) { throw std::invalid_argument("The matrix needs to be square"); } uint64_t size_m = this->row_size_; if (size_m == 1) { return this->Access(0, 0); } Matrix<T> submatrix(size_m - 1, size_m - 1, 0); T ans(0); for (uint32_t i = 0; i < size_m; ++i) { for (uint32_t j = 0; j < size_m - 1; ++j) { for (uint32_t k = 0; k < size_m - 1; ++k) { submatrix.Access(j, k) = this->Access((((i > j) ? 0 : 1) + j), k + 1); } } ans += ((i % 2) ? -1 : 1) * this->Access(i, 0) * submatrix.determinant(); } return ans; } /** * @brief reshape the Matrix of the given size * @tparam T * @param row * @param col * @return */ template<typename T> Matrix<T> Matrix<T>::reshape(int32_t row, int32_t col) { int32_t col_num = this->column_size_; int32_t num = this->row_size_ * col_num; if (row * col != num || num <= 0) { throw std::invalid_argument("The matrix needs to be square"); return *this; } Matrix<T> res(row, col); for (int i = 0; i < num; i++) { res.Access(i / col, i % col) = this->Access(i / col_num, i % col_num); } return Matrix<T>(std::move(res)); } /** * @brief slice the Matrix into a smaller one * @tparam T * @param row1 * @param row2 * @param col1 * @param col2 * @return */ template<typename T> Matrix<T> Matrix<T>::slice(int32_t row1, int32_t row2, int32_t col1, int32_t col2) { if (row1 < 0 || row2 >= this->row_size_ || col1 < 0 || col2 >= this->column_size_ || row1 > row2 || col1 > col2) { return *this; } Matrix<T> res(row2 - row1, col2 - col1); for (int32_t i = row1; i < row2; i++) { for (int32_t j = col1; j < col2; j++) { res.Access(i - row1, j - col1) = this->Access(i, j); } } return Matrix<T>(std::move(res)); } /** * @brief get the conjugate of Matrix * @tparam T * @param conjugate * @return */ template<typename T> Matrix<T> Matrix<T>::Conjugate(std::function<T(const T &)> conjugate) { auto result = Matrix<T>(row_size_, column_size_); int n = row_size_ * column_size_; for (int i = 0; i < n; ++i) { result.data_[i] = conjugate(data_[i]); } return result; } /** * @brief Convert cv::Mat to Matrix * @param mat * @return */ Matrix<double> CvMatToMatrix(const cv::Mat &mat) { int32_t type = mat.type(); if (mat.channels() > 1) { throw ArgumentNotMatchException("Channel not supported!"); } if (mat.rows == 0 || mat.cols == 0) { throw BadSizeException("Size exception"); } Matrix<double> result(mat.rows, mat.cols); for (int i = 0; i < mat.rows; ++i) { for (int j = 0; j < mat.cols; ++j) { result[i][j] = mat.at<int>(i, j); } } return result; } /** * @brief Convert Matrix to cv::Mat * @tparam T * @param matrix * @return */ template<typename T> cv::Mat MatrixToCvMat(const Matrix<T> &matrix) { using std::is_same_v; int type = 7; if (is_same_v<T, uint8_t>()) { type = 0; } else if (is_same_v<T, int8_t>()) { type = 1; } else if (is_same_v<T, uint16_t>()) { type = 2; } else if (is_same_v<T, int16_t>()) { type = 3; } else if (is_same_v<T, int32_t>()) { type = 4; } else if (is_same_v<T, float>()) { type = 5; } else if (is_same_v<T, double>()) { type = 6; } if (type == 7) { throw ArgumentNotMatchException("Type not supported"); } if (type < 5) { cv::Mat mat(matrix.getRowSize(), matrix.getColumnSize(), CV_32S); for (int i = 0; i < matrix.getRowSize(); ++i) { for (int j = 0; j < matrix.getColumnSize(); ++j) { mat.at<T>(i, j) = matrix[i][j]; } } return mat; } else { cv::Mat mat(matrix.getRowSize(), matrix.getColumnSize(), CV_64F); for (int i = 0; i < matrix.getRowSize(); ++i) { for (int j = 0; j < matrix.getColumnSize(); ++j) { mat.at<T>(i, j) = matrix[i][j]; } } return mat; } } /** * @brief Implement the eigen vector by using the eigen library * @tparam T * @return */ template<typename T> std::vector<std::pair<T, std::vector<T>>> Matrix<T>::eigen() { auto mat = (cv::Mat_<T>)(*this); cv::Mat_<T> valuesMat; cv::Mat_<T> vectorsMat; cv::eigen(mat, valuesMat, vectorsMat); std::vector<std::pair<T, std::vector<T>>> result; for (int i = 0; i < valuesMat.rows; ++i) { std::vector<T> vec; for (int j = 0; j < vectorsMat.cols; ++j) { vec.push_back(vectorsMat[i][0]); } result.push_back(std::make_pair(valuesMat[i][0], vec)); } return result; } /** * Cast operator overload (from Matrix to cv::Mat_ ) * @tparam T * @return */ template<typename T> Matrix<T>::operator cv::Mat_<T>() { cv::Mat_<T> mat(row_size_, column_size_); #pragma omp parallel for collapse(2) for (int row = 0; row < row_size_; ++row) { for (int col = 0; col < column_size_; ++col) { mat(row, col) = data_[row * column_size_ + col]; } } return mat; } } #endif //CS205_PROJECT_SIMPLE_MATRIX_SIMPLE_MATRIX_H
31.350389
138
0.51096
[ "vector" ]