hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
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
270
max_issues_repo_name
stringlengths
5
116
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
270
max_forks_repo_name
stringlengths
5
116
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
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
1f8d17e4d0ab29d6e3be8ae02d240f13bf607b7c
40,097
cpp
C++
src/mame/machine/nl_breakout.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/machine/nl_breakout.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/machine/nl_breakout.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:GPL-2.0+ // copyright-holders:DICE Team,Couriersud /* * Changelog: * * - Drop dice syntax (Couriersud) * - Fix brick display (Couriersud) * - Added led and lamp components (Couriersud) * - Start2 works (Couriersud) * - Added discrete paddle potentiometers (Couriersud) * - Changes made to run in MAME (Couriersud) * - Added bonus game dip switch (Couriersud) * - Added discrete startup latch * - Original version imported from DICE * * TODO: * - lamp triacs? * * The MAME team has asked for and received written confirmation from the * author of DICE to use, modify and redistribute code under: * * - GPL (GNU General Public License) * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * - DICE itself is licensed under version 3 of the GNU General Public License. * Under no circumstances the exemptions listed above shall apply to any * other code of DICE not contained in this file. * * The following is an extract from the DICE readme. * * ---------------------------------------------------------------------------- * * DICE is a Discrete Integrated Circuit Emulator. It emulates computer systems * that lack any type of CPU, consisting only of discrete logic components. * * Project Page: http://sourceforge.net/projects/dice/ * Email: dice.emulator@gmail.com * * License * * Copyright (C) 2008-2013 DICE Team * * 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 3 of the License, or * (at your option) any later version. * */ /* * Notes * FIXME: breakout generates some spurious hsync in the middle of line 27 * */ #include "netlist/devices/net_lib.h" #define SLOW_BUT_ACCURATE (0) NETLIST_START(breakout) #if (SLOW_BUT_ACCURATE) SOLVER(Solver, 16000) PARAM(Solver.RELTOL, 5e-4) // less accuracy and diode will not work PARAM(Solver.DYNAMIC_TS, 1) PARAM(Solver.DYNAMIC_LTE, 1e0) PARAM(Solver.DYNAMIC_MIN_TIMESTEP, 1e-7) PARAM(Solver.METHOD, "MAT_CR") #else SOLVER(Solver, 16000) PARAM(Solver.ACCURACY, 1e-4) PARAM(Solver.DYNAMIC_TS, 1) PARAM(Solver.DYNAMIC_LTE, 1e-2) PARAM(Solver.DYNAMIC_MIN_TIMESTEP, 1e-8) PARAM(Solver.METHOD, "MAT_CR") #endif PARAM(NETLIST.USE_DEACTIVATE, 1) //---------------------------------------------------------------- // Dip-Switch - Free game //---------------------------------------------------------------- SWITCH(S1_1) SWITCH(S1_2) SWITCH(S1_3) SWITCH(S1_4) SWITCH2(COIN1) // Coin 1 SWITCH2(COIN2) // Coin 2 SWITCH(START1) // Start 1 SWITCH(START2) // Start 2 SWITCH(SERVE) // Start 2 SWITCH(S2) // Cocktail SWITCH(S3) // 2 Plays / 25c SWITCH2(S4) // Three Balls / 5 Balls ANALOG_INPUT(V5, 5) ALIAS(VCC, V5) ALIAS(GNDD ,GND.Q) ALIAS(P ,V5.Q) TTL_INPUT(ttlhigh, 1) TTL_INPUT(ttllow, 0) TTL_INPUT(antenna, 0) NET_C(VCC, ttlhigh.VCC, ttllow.VCC, antenna.VCC) NET_C(GND, ttlhigh.GND, ttllow.GND, antenna.GND) //---------------------------------------------------------------- // Clock circuit //---------------------------------------------------------------- #if (SLOW_BUT_ACCURATE) MAINCLOCK(Y1, 14318000.0) TTL_9316_DIP(F1) NET_C(Y1.Q, F1.2) NET_C(F1.14, H1.13) NET_C(F1.13, H1.12) NET_C(F1.15, E1.5) NET_C(P, F1.1) NET_C(P, F1.7) NET_C(P, F1.10) NET_C(GNDD, F1.3) NET_C(P, F1.4) NET_C(GNDD, F1.5) NET_C(GNDD, F1.6) NET_C(E1.6, F1.9) ALIAS(CKBH, F1.13) ALIAS(CLOCK, H1.11) #else /* * 9316 2 3 4 5 6 7 8 9 10 11 12 13 14 15 2 3 4 5 6 * A 0 1 0 1 0 1 0 1 0 1 0 1 0 1 * B 1 1 0 0 1 1 0 0 1 1 0 0 1 1 * CKBH 1 1 0 0 1 1 0 0 1 1 0 0 1 1 * ^--- Pattern Start * CLOCK 1 0 1 1 1 0 1 1 1 0 1 1 1 0 * ^--- Pattern Start * <------> 2 Clocks Offset */ //EXTCLOCK(Y2, 14318000.0, "2,6,2,6,2,2,2,6") EXTCLOCK(Y2, 14318000.0, "6,2,6,2,2,2,6,2") EXTCLOCK(Y1, 14318000.0, "4,4,4,4,8,4") PARAM(Y2.OFFSET, 1.047632350887E-07) // 1.5 clocks / 14318000.0 ALIAS(CKBH, Y1.Q) ALIAS(CLOCK, Y2.Q) NET_C(ttlhigh, H1.13) NET_C(ttlhigh, H1.12) NET_C(ttlhigh, E1.5) #endif //---------------------------------------------------------------- // Startup / Antenna latch //---------------------------------------------------------------- DIODE(CR3, "1N914") DIODE(CR4, "1N914") DIODE(CR5, "1N914") DIODE(CR7, "1N914") // No need to model capacitance QBJT_EB(Q1, "2N3644(CJC=0 CJE=0)") QBJT_EB(Q2, "2N3643(CJC=0 CJE=0)") QBJT_EB(Q3, "2N3643(CJC=0 CJE=0)") CAP(C19, CAP_U(0.1)) CAP(C16, CAP_U(0.1)) RES(R25, 100) RES(R26, 330) RES(R27, 100) RES(R31, 220) RES(R32, 100) NET_C(GND, CR5.A, Q2.E, C16.2, R25.2, Q3.E) NET_C(CR5.K, Q2.B, antenna) NET_C(Q2.C, C16.1, R25.1, Q3.B, R27.2) NET_C(R27.1, CR7.A, R31.2) //CR7.K == IN NET_C(R31.1, Q1.C) NET_C(Q3.C, R26.2, CR3.A, CR4.A, E9.5) // E9.6 = Q Q3.C=QQ CR3.K = COIN*1 CR4.K = COIN*2 NET_C(R26.1, Q1.B, C19.2, R32.2) NET_C(Q1.E, C19.1, R32.1, V5) ALIAS(LAT_Q ,E9.6) ALIAS(Q_n ,Q3.C) ALIAS(COIN1_n ,F8.5) ALIAS(COIN2_n ,H9.5) NET_C(CR7.K, D8.11) //set NET_C(CR3.K, COIN1_n) //reset NET_C(CR4.K, COIN2_n) //reset //static CapacitorDesc c32_desc(CAP_U(0.1)); //NETDEV_DELAY(C32) NETDEV_PARAMI(C32, L_TO_H, CAPACITOR_tc_lh((&c32_desc)->c, (&c32_desc)->r)) NETDEV_PARAMI(C32, H_TO_L, CAPACITOR_tc_hl((&c32_desc)->c, (&c32_desc)->r)) CAP(C32, CAP_U(0.1)) NET_C(GND, C32.2) #if (SLOW_BUT_ACCURATE) CAP(C36, CAP_N(1.0)) //0.001uF = 1nF - determines horizontal gap between bricks NET_C(GND, C36.2) #else NETDEV_DELAY(C36) PARAM(C36.L_TO_H, 93) PARAM(C36.H_TO_L, 2) #endif CAP(C37, CAP_P(330)) NET_C(GND, C37.2) TTL_7474_DIP(A3) TTL_7408_DIP(A4) TTL_7400_DIP(A5) TTL_7474_DIP(A6) TTL_9602_DIP(A7) NET_C(VCC, A7.16) NET_C(GND, A7.8) RES(R45, RES_K(68)) CAP(CC24, CAP_U(1)) RES(R46, RES_K(22)) NET_C(A7.1, CC24.1) NET_C(A7.2, CC24.2) NET_C(A7.2, R45.2) NET_C(VCC, R45.1) CAP(CC25, CAP_U(10)) NET_C(A7.15, CC25.1) NET_C(A7.14, CC25.2) NET_C(A7.14, R46.2) NET_C(VCC, R46.1) TTL_9602_DIP(A8) NET_C(VCC, A8.16) NET_C(GND, A8.8) RES(R47, RES_K(27)) CAP(CC26, CAP_U(1)) RES(R48, RES_K(27)) NET_C(A8.1, CC26.1) NET_C(A8.2, CC26.2) NET_C(A8.2, R47.2) NET_C(VCC, R47.1) CAP(CC27, CAP_U(1)) NET_C(A8.15, CC27.1) NET_C(A8.14, CC27.2) NET_C(A8.14, R48.2) NET_C(VCC, R48.1) NE555_DIP(B2) RES(R55, 560) RES(R54, RES_M(1.8)) CAP(C34, CAP_U(0.1)) NET_C(B2.7, R55.1) NET_C(B2.7, R54.1) NET_C(B2.6, R54.2) NET_C(B2.6, C34.1) NET_C(B2.2, C34.1) NET_C(R55.2, V5) NET_C(C34.2, GND) NET_C(B2.8, V5) NET_C(B2.1, GND) TTL_7402_DIP(B3) TTL_9316_DIP(B4) TTL_74193_DIP(B5) TTL_7400_DIP(B6) TTL_9316_DIP(B7) TTL_9316_DIP(B8) TTL_7408_DIP(B9) TTL_7400_DIP(C2) TTL_7400_DIP(C3) TTL_7486_DIP(C4) TTL_7404_DIP(C5) TTL_7486_DIP(C6) TTL_9316_DIP(C7) TTL_9316_DIP(C8) NE555_DIP(C9) TTL_7432_DIP(D2) TTL_7474_DIP(D3) TTL_9316_DIP(D4) TTL_7474_DIP(D5) TTL_7408_DIP(D6) TTL_7411_DIP(D7) TTL_7400_DIP(D8) // CHIP("D9", 4016) //quad bilateral switch TTL_7404_DIP(E1) TTL_7486_DIP(E2) TTL_7402_DIP(E3) TTL_7432_DIP(E4) TTL_7408_DIP(E5) TTL_7474_DIP(E6) TTL_7402_DIP(E7) TTL_7474_DIP(E8) TTL_7404_DIP(E9) TTL_7411_DIP(F2) TTL_9602_DIP(F3) NET_C(VCC, F3.16) NET_C(GND, F3.8) RES(R22, RES_K(47)) CAP(CC14, CAP_U(1)) RES(R23, RES_K(47)) NET_C(F3.1, CC14.1) NET_C(F3.2, CC14.2) NET_C(F3.2, R22.2) NET_C(VCC, R22.1) CAP(CC15, CAP_U(1)) NET_C(F3.15, CC15.1) NET_C(F3.14, CC15.2) NET_C(F3.14, R23.2) NET_C(VCC, R23.1) TTL_7474_DIP(F4) TTL_7474_DIP(F5) TTL_74193_DIP(F6) TTL_74279_DIP(F7) TTL_7474_DIP(F8) TTL_7404_DIP(F9) TTL_7437_DIP(H1) TTL_7408_DIP(H2) TTL_7427_DIP(H3) TTL_7400_DIP(H4) TTL_9312_DIP(H5) TTL_9310_DIP(H6) TTL_7408_DIP(H7) TTL_7474_DIP(H8) TTL_7474_DIP(H9) TTL_74175_DIP(J1) TTL_7404_DIP(J2) TTL_7402_DIP(J3) TTL_9312_DIP(J4) TTL_7448_DIP(J5) TTL_9310_DIP(J6) TTL_7420_DIP(J7) TTL_74279_DIP(J8) TTL_7410_DIP(J9) TTL_9316_DIP(K1) TTL_7486_DIP(K2) TTL_7430_DIP(K3) TTL_7408_DIP(K4) TTL_9312_DIP(K5) TTL_9310_DIP(K6) TTL_7486_DIP(K7) TTL_7474_DIP(K8) TTL_74107_DIP(K9) TTL_9316_DIP(L1) TTL_7486_DIP(L2) TTL_82S16_DIP(L3) // Ram chip TTL_7411_DIP(L4) TTL_9312_DIP(L5) TTL_9310_DIP(L6) TTL_7486_DIP(L7) TTL_74193_DIP(L8) TTL_7400_DIP(L9) TTL_9316_DIP(M1) TTL_7483_DIP(M2) TTL_7486_DIP(M3) TTL_7410_DIP(M4) TTL_9312_DIP(M5) TTL_9310_DIP(M6) TTL_7427_DIP(M8) TTL_7404_DIP(M9) TTL_9316_DIP(N1) TTL_7483_DIP(N2) TTL_7486_DIP(N3) TTL_7411_DIP(N4) TTL_9312_DIP(N5) TTL_9310_DIP(N6) TTL_7408_DIP(N7) TTL_9602_DIP(N8) NET_C(VCC, N8.16) NET_C(GND, N8.8) RES(R2, RES_K(33)) CAP(CC2, CAP_U(100)) RES(R3, RES_K(5.6)) NET_C(N8.1, CC2.1) NET_C(N8.2, CC2.2) NET_C(N8.2, R2.2) NET_C(VCC, R2.1) NET_C(N8.14, R3.2) NET_C(VCC, R3.1) TTL_74192_DIP(N9) //LM380 //speaker amplifier - not emulated //LM323 //regulator - not emulated //---------------------------------------------------------------- // HSYNC and VSYNC //---------------------------------------------------------------- ALIAS(H1_d ,L1.14) ALIAS(H2_d ,L1.13) ALIAS(H4_d ,L1.12) ALIAS(H8_d ,L1.11) ALIAS(H8_n ,J2.2) ALIAS(H16_d ,K1.14) ALIAS(H16_n ,J2.6) ALIAS(H32_d ,K1.13) ALIAS(H32_n ,J2.4) ALIAS(H64_d ,K1.12) ALIAS(H128_d ,K1.11) ALIAS(V1_d ,M1.14) ALIAS(V2_d ,M1.13) ALIAS(V4_d ,M1.12) ALIAS(V8_d ,M1.11) ALIAS(V16_d ,N1.14) ALIAS(V16_n ,J2.10) ALIAS(V32_d ,N1.13) ALIAS(V64_d ,N1.12) ALIAS(V64I ,H7.11) ALIAS(V64_n ,M9.10) ALIAS(V128_d ,N1.11) ALIAS(H1 ,L2.8) ALIAS(H2 ,L2.11) ALIAS(H4 ,L2.3) ALIAS(H8 ,L2.6) ALIAS(H16 ,K2.8) ALIAS(H32 ,K2.11) ALIAS(H64 ,K2.3) ALIAS(H128 ,K2.6) ALIAS(V2 ,M3.3) ALIAS(V4 ,M3.6) ALIAS(V8 ,M3.11) ALIAS(V16 ,N3.8) ALIAS(V32 ,N3.3) ALIAS(V64 ,N3.6) ALIAS(V128 ,N3.11) ALIAS(HSYNC ,J1.2) ALIAS(HSYNC_n ,J1.3) ALIAS(VSYNC ,J1.7) ALIAS(VSYNC_n ,J1.6) ALIAS(PSYNC ,J1.11) ALIAS(PSYNC_n ,J1.10) ALIAS(BSYNC ,J1.15) ALIAS(BSYNC_n ,J1.14) ALIAS(BALL ,D7.6) ALIAS(BALL_DISPLAY ,A4.6) ALIAS(PLAYFIELD ,H4.3) ALIAS(SCORE ,D3.5) ALIAS(VERT_TRIG_n ,H1.8) ALIAS(SCLOCK ,K1.15) ALIAS(PAD_n ,K3.8) ALIAS(PAD_EN_n ,C2.8) ALIAS(COIN ,L9.6) ALIAS(CREDIT_1_OR_2 ,L9.3) ALIAS(CREDIT_1_OR_2_n ,F9.8) ALIAS(CREDIT2 ,F9.6) ALIAS(CREDIT2_n ,M8.8) ALIAS(CR_START1 ,E8.5) ALIAS(CR_START1_n ,E8.6) //Schematic shows E8.6 as positive CR_START1, but this can't be right? ALIAS(CR_START2 ,E8.9) ALIAS(CR_START2_n ,E8.8) ALIAS(CSW1 ,F9.12) ALIAS(CSW2 ,F9.2) ALIAS(P2_CONDITIONAL ,H1.3) ALIAS(P2_CONDITIONAL_dash ,H7.8) ALIAS(PLAYER_2 ,B4.14) ALIAS(PLAYER_2_n ,M9.8) ALIAS(START_GAME ,D8.6) ALIAS(START_GAME1_n ,M9.4) ALIAS(START_GAME_n ,M9.6) ALIAS(BG1_n ,K8.9) ALIAS(BG1 ,K8.8) ALIAS(BG2_n ,K8.5) ALIAS(BG2 ,K8.6) ALIAS(FREE_GAME_TONE ,N7.3) ALIAS(BONUS_COIN ,L9.11) ALIAS(SBD_n ,D2.11) ALIAS(PLAY_CP ,D2.8) ALIAS(PLGM2_n ,F7.7) ALIAS(VB_HIT_n ,A5.6) ALIAS(SERVE_n ,SERVE.1) ALIAS(SERVE_WAIT ,A3.9) ALIAS(SERVE_WAIT_n ,A3.8) ALIAS(BRICK_DISPLAY ,E3.1) ALIAS(BRICK_HIT ,E6.5) ALIAS(BRICK_HIT_n ,E6.6) //ALIAS(EGL ,A4.3) ALIAS(EGL ,C37.1) ALIAS(EGL_n ,C5.2) ALIAS(RAM_PLAYER1 ,E7.4) ALIAS(A1 ,H6.14) ALIAS(B1 ,H6.13) ALIAS(C1 ,H6.12) ALIAS(D1 ,H6.11) ALIAS(E1 ,J6.14) ALIAS(F1 ,J6.13) ALIAS(G1 ,J6.12) ALIAS(H01 ,J6.11) ALIAS(I1 ,K6.14) ALIAS(J1 ,K6.13) ALIAS(K1 ,K6.12) ALIAS(L1 ,K6.11) ALIAS(A2 ,N6.14) ALIAS(B2 ,N6.13) ALIAS(C2 ,N6.12) ALIAS(D2 ,N6.11) ALIAS(E2s ,M6.14) ALIAS(F2 ,M6.13) ALIAS(G2 ,M6.12) ALIAS(H02 ,M6.11) ALIAS(I2 ,L6.14) ALIAS(J2 ,L6.13) ALIAS(K2 ,L6.12) ALIAS(L2 ,L6.11) ALIAS(CX0 ,C6.11) ALIAS(CX1 ,C6.6) ALIAS(X0 ,C5.10) ALIAS(X1 ,B6.3) ALIAS(X2 ,C6.3) ALIAS(Y0 ,B6.11) ALIAS(Y1 ,B6.6) ALIAS(Y2 ,A6.6) ALIAS(DN ,C4.3) ALIAS(PC ,D4.12) ALIAS(PD ,D4.11) ALIAS(SU_n ,D5.8) ALIAS(V_SLOW ,C5.8) ALIAS(PLNR ,E3.4) ALIAS(SCI_n ,H4.6) ALIAS(SFL_n ,E9.12) // Score Flash ALIAS(TOP_n ,E9.2) ALIAS(BP_HIT_n ,A5.8) ALIAS(BTB_HIT_n ,C3.3) ALIAS(SET_BRICKS ,D3.9) ALIAS(SET_BRICKS_n ,D3.8) ALIAS(BALL_A ,B4.13) ALIAS(BALL_B ,B4.12) ALIAS(BALL_C ,B4.11) ALIAS(FPD1 ,F3.10) ALIAS(FPD1_n ,F3.9) ALIAS(FPD2 ,F3.6) ALIAS(FPD2_n ,F3.7) ALIAS(COUNT ,N7.11) ALIAS(COUNT_1 ,N7.8) ALIAS(COUNT_2 ,N7.6) ALIAS(ATTRACT ,E6.8) ALIAS(ATTRACT_n ,E6.9) ALIAS(BRICK_SOUND ,B8.14) ALIAS(P_HIT_SOUND ,B7.12) ALIAS(VB_HIT_SOUND ,B7.11) ALIAS(LH_SIDE ,J3.13) ALIAS(RH_SIDE ,H2.3) ALIAS(TOP_BOUND ,K4.6) //---------------------------------------------------------------- // Audio circuit //---------------------------------------------------------------- NET_C(M9.2, F6.5) NET_C(M9.2, F7.15) NET_C(F6.13, F7.14) NET_C(START_GAME_n, F6.11) NET_C(P, F6.15) NET_C(P, F6.1) NET_C(P, F6.10) NET_C(P, F6.9) NET_C(GNDD, F6.14) NET_C(F7.13, J9.2) NET_C(VSYNC, J9.1) NET_C(A7.9, J9.13) NET_C(J9.12, F6.4) NET_C(J9.12, A7.11) NET_C(GNDD, A7.12) NET_C(ATTRACT_n, A7.13) NET_C(J9.12, A8.11) NET_C(GNDD, A8.12) NET_C(ATTRACT_n, A8.13) NET_C(VB_HIT_n, A7.5) NET_C(GNDD, A7.4) NET_C(ATTRACT_n, A7.3) NET_C(BP_HIT_n, A8.5) NET_C(GNDD, A8.4) NET_C(ATTRACT_n, A8.3) NET_C(A8.6, B9.13) NET_C(P_HIT_SOUND, B9.12) NET_C(A8.10, B9.10) NET_C(BRICK_SOUND, B9.9) NET_C(A7.6, B9.4) NET_C(VB_HIT_SOUND, B9.5) NET_C(S1_1.1, GND) NET_C(S1_2.1, GND) NET_C(S1_3.1, GND) NET_C(S1_4.1, GND) RES(R7, RES_K(2.7)) RES(R8, RES_K(2.7)) RES(R9, RES_K(2.7)) RES(R10, RES_K(2.7)) NET_C(R7.1, V5) NET_C(R8.1, V5) NET_C(R9.1, V5) NET_C(R10.1, V5) NET_C(S1_1.2, R7.2) NET_C(S1_2.2, R8.2) NET_C(S1_3.2, R9.2) NET_C(S1_4.2, R10.2) //---------------------------------------------------------------- // Free Game //---------------------------------------------------------------- NET_C(I1, K7.2) NET_C(S1_1.2, K7.1) NET_C(J1, K7.12) NET_C(S1_2.2, K7.13) NET_C(K1, K7.5) NET_C(S1_3.2, K7.4) NET_C(L1, K7.9) NET_C(S1_4.2, K7.10) NET_C(I2, L7.2) NET_C(S1_1.2, L7.1) NET_C(J2, L7.12) NET_C(S1_2.2, L7.13) NET_C(K2, L7.5) NET_C(S1_3.2, L7.4) NET_C(L2, L7.9) NET_C(S1_4.2, L7.10) NET_C(K7.3, J7.13) NET_C(K7.11, J7.12) NET_C(K7.6, J7.10) NET_C(K7.8, J7.9) NET_C(L7.3, J7.1) NET_C(L7.11, J7.2) NET_C(L7.6, J7.4) NET_C(L7.8, J7.5) NET_C(START_GAME1_n, J8.12) NET_C(BG1_n, J8.11) NET_C(J7.8, J8.10) NET_C(START_GAME1_n, J8.2) NET_C(BG2_n, J8.3) NET_C(J7.6, J8.1) NET_C(J8.9, K8.12) NET_C(EGL, K8.11) NET_C(P, K8.13) NET_C(LAT_Q, K8.10) NET_C(J8.4, K8.2) NET_C(EGL, K8.3) NET_C(P, K8.1) NET_C(LAT_Q, K8.4) NET_C(P, K9.8) NET_C(J8.9, K9.9) NET_C(GNDD, K9.11) NET_C(HSYNC_n, K9.10) NET_C(P, K9.1) NET_C(J8.4, K9.12) NET_C(GNDD, K9.4) NET_C(HSYNC_n, K9.13) NET_C(K9.6, L9.12) NET_C(K9.2, L9.13) NET_C(P, N8.5) NET_C(BONUS_COIN, N8.4) NET_C(ATTRACT_n, N8.3) NET_C(V4_d, N7.2) NET_C(N8.6, N7.1) NET_C(GNDD, M2.13) NET_C(V1_d, M2.10) NET_C(V2_d, M2.8) NET_C(V4_d, M2.3) NET_C(V8_d, M2.1) NET_C(GNDD, M2.11) NET_C(P2_CONDITIONAL, M2.7) NET_C(GNDD, M2.4) NET_C(GNDD, M2.16) NET_C(M2.14, N2.13) NET_C(V16_d, N2.10) NET_C(V32_d, N2.8) NET_C(V64_d, N2.3) NET_C(V128_d, N2.1) NET_C(GNDD, N2.11) NET_C(P2_CONDITIONAL, N2.7) NET_C(GNDD, N2.4) NET_C(GNDD, N2.16) NET_C(M2.6, M3.2) NET_C(P2_CONDITIONAL, M3.1) NET_C(M2.2, M3.5) NET_C(P2_CONDITIONAL, M3.4) NET_C(M2.15, M3.12) NET_C(P2_CONDITIONAL, M3.13) NET_C(P2_CONDITIONAL, N3.10) NET_C(N2.9, N3.9) NET_C(P2_CONDITIONAL, N3.1) NET_C(N2.6, N3.2) NET_C(P2_CONDITIONAL, N3.4) NET_C(N2.2, N3.5) NET_C(P2_CONDITIONAL, N3.13) NET_C(N2.15, N3.12) NET_C(H1_d, L2.9) NET_C(P2_CONDITIONAL, L2.10) NET_C(H2_d, L2.12) NET_C(P2_CONDITIONAL, L2.13) NET_C(H4_d, L2.2) NET_C(P2_CONDITIONAL, L2.1) NET_C(H8_d, L2.5) NET_C(P2_CONDITIONAL, L2.4) NET_C(P2_CONDITIONAL, K2.10) NET_C(H16_d, K2.9) NET_C(P2_CONDITIONAL, K2.13) NET_C(H32_d, K2.12) NET_C(P2_CONDITIONAL, K2.1) NET_C(H64_d, K2.2) NET_C(P2_CONDITIONAL, K2.4) NET_C(H128_d, K2.5) NET_C(V64, M9.11) NET_C(H16, J2.5) NET_C(H32, J2.3) NET_C(V16, J2.11) NET_C(H8, J2.1) NET_C(CLOCK, J1.9) NET_C(SCLOCK, J1.4) NET_C(N4.6, J1.5) NET_C(PAD_n, J1.12) NET_C(BALL_DISPLAY, J1.13) NET_C(P, J1.1) NET_C(P, K1.1) NET_C(P, K1.3) NET_C(P, K1.4) NET_C(P, K1.5) NET_C(P, K1.6) NET_C(P, K1.9) NET_C(P, K1.10) NET_C(CLOCK, K1.2) NET_C(L1.15, K1.7) NET_C(P, L1.1) NET_C(P, L1.3) NET_C(GNDD, L1.4) NET_C(P, L1.5) NET_C(GNDD, L1.6) NET_C(VERT_TRIG_n, L1.9) NET_C(P, L1.10) NET_C(CLOCK, L1.2) NET_C(P, L1.7) NET_C(P, N1.1) NET_C(P, N1.10) NET_C(P, N1.3) NET_C(P, N1.4) NET_C(P, N1.5) NET_C(P, N1.6) NET_C(P, N1.9) NET_C(CLOCK, N1.2) NET_C(H2.6, N1.7) NET_C(M1.15, H2.5) NET_C(L1.15, H2.4) NET_C(V128_d, N4.5) NET_C(V64_d, N4.3) NET_C(V32_d, N4.4) NET_C(N4.6, H1.10) NET_C(VSYNC_n, H1.9) NET_C(P, M1.1) NET_C(GNDD, M1.3) NET_C(GNDD, M1.4) NET_C(P, M1.5) NET_C(GNDD, M1.6) NET_C(VERT_TRIG_n, M1.9) NET_C(CLOCK, M1.2) NET_C(L1.15, M1.7) NET_C(K1.15, M1.10) NET_C(PLAYER_2, M9.9) NET_C(BALL_A, C5.5) NET_C(BALL_A, C4.13) NET_C(BALL_B, C4.12) NET_C(BALL_A, A4.13) NET_C(BALL_B, A4.12) NET_C(BALL_C, C4.10) NET_C(A4.11, C4.9) NET_C(A2, N5.1) NET_C(E2s, N5.2) NET_C(I2, N5.3) NET_C(C5.6, N5.4) NET_C(A1, N5.5) NET_C(E1, N5.6) NET_C(I1, N5.7) NET_C(PLAYER_2_n, N5.9) NET_C(H32_n, N5.10) NET_C(V16, N5.11) NET_C(V64, N5.12) NET_C(V128, N5.13) NET_C(B2, M5.1) NET_C(F2, M5.2) NET_C(J2, M5.3) NET_C(C4.11, M5.4) NET_C(B1, M5.5) NET_C(F1, M5.6) NET_C(J1, M5.7) NET_C(PLAYER_2, M5.9) NET_C(H32_n, M5.10) NET_C(V16, M5.11) NET_C(V64, M5.12) NET_C(V128, M5.13) NET_C(C2, L5.1) NET_C(G2, L5.2) NET_C(K2, L5.3) NET_C(C4.8, L5.4) NET_C(C1, L5.5) NET_C(G1, L5.6) NET_C(K1, L5.7) NET_C(GNDD, L5.9) NET_C(H32_n, L5.10) NET_C(V16, L5.11) NET_C(V64, L5.12) NET_C(V128, L5.13) NET_C(D2, K5.1) NET_C(H02, K5.2) NET_C(L2, K5.3) NET_C(GNDD, K5.4) NET_C(D1, K5.5) NET_C(H01, K5.6) NET_C(L1, K5.7) NET_C(GNDD, K5.9) NET_C(H32_n, K5.10) NET_C(V16, K5.11) NET_C(V64, K5.12) NET_C(V128, K5.13) NET_C(P, J5.4) NET_C(P, J5.3) NET_C(N5.15, J5.7) NET_C(M5.15, J5.1) NET_C(L5.15, J5.2) NET_C(K5.15, J5.6) NET_C(H32, J5.5) NET_C(J5.13, H5.1) NET_C(GNDD, H5.2) NET_C(GNDD, H5.3) NET_C(J5.14, H5.4) NET_C(GNDD, H5.5) NET_C(GNDD, H5.6) NET_C(J5.10, H5.7) NET_C(GNDD, H5.9) NET_C(V4, K4.12) NET_C(V8, K4.13) NET_C(K4.11, H5.10) NET_C(H2, H5.11) NET_C(H4, H5.12) NET_C(H8, H5.13) NET_C(H2, L4.3) NET_C(H4, L4.5) NET_C(H8, L4.4) NET_C(J5.12 , J4.1) NET_C(J5.11, J4.2) NET_C(GNDD, J4.3) NET_C(GNDD, J4.4) NET_C(J5.15, J4.5) NET_C(J5.9, J4.6) NET_C(GNDD, J4.7) NET_C(GNDD, J4.9) NET_C(L4.6, J4.10) NET_C(H8, J4.11) NET_C(V4, J4.12) NET_C(V8, J4.13) NET_C(H5.14, H4.13) NET_C(J4.14, H4.12) //---------------------------------------------------------------- // Paddles //--------------------------------------------------------------- NET_C(ATTRACT_n, B2.4) NET_C(B2.3, E9.13) NET_C(PLAYER_2_n, M3.9) NET_C(V128, M3.10) NET_C(H64, J3.8) NET_C(H128, J3.9) NET_C(V32, E3.5) NET_C(V16_n, E3.6) NET_C(SFL_n, M8.1) NET_C(M3.8, M8.2) NET_C(PLNR, M8.13) NET_C(J3.10, E9.1) NET_C(V64, E2.5) NET_C(V32, E2.4) NET_C(PLNR, E2.10) NET_C(H16, E2.9) NET_C(M8.12, M8.3) NET_C(TOP_n, M8.4) NET_C(TOP_n, M8.5) NET_C(H4.11, F2.11) NET_C(E2.6, F2.10) NET_C(E2.8, F2.9) NET_C(M8.6, H4.5) NET_C(F2.8, H4.4) // NOTE: Stabilizing CAP C20 not modelled. NET_C(PAD_EN_n, C9.4) NET_C(PAD_EN_n, C9.2) NET_C(C9.8, V5) NET_C(C9.1, GND) RES(R53, RES_K(12)) // 12k CAP(C21, CAP_U(1)) NET_C(GND, C21.2, R53.2) NET_C(C21.1, R53.1, C9.6, C9.7) NET_C(BTB_HIT_n, C5.3) NET_C(P, F5.10) NET_C(P, F5.12) NET_C(C5.4, F5.11) NET_C(SERVE_WAIT_n, F5.13) NET_C(H64, E5.13) NET_C(F5.9, E5.12) NET_C(H128, E5.10) NET_C(F5.8, E5.9) NET_C(E5.11, E4.12) NET_C(E5.8, E4.13) NET_C(E4.11, D4.2) NET_C(P, D4.3) NET_C(P, D4.4) NET_C(P, D4.5) NET_C(P, D4.6) NET_C(P, D4.9) NET_C(P, D4.10) NET_C(C3.11, D4.7) NET_C(VSYNC_n, D4.1) NET_C(D4.15, E4.10) NET_C(H7.6, E4.9) NET_C(C9.3, H7.5) NET_C(PAD_EN_n, H7.4) NET_C(E4.8, C3.12) NET_C(ATTRACT_n, C3.13) NET_C(H8, J3.2) NET_C(H32, J3.3) NET_C(C3.11, K3.12) NET_C(H128, K3.5) NET_C(H64, K3.6) NET_C(H16, K3.11) NET_C(H4, K3.4) NET_C(J3.1, K3.1) NET_C(P, K3.3) NET_C(P, K3.2) NET_C(V16_d, D7.1) NET_C(V64_d, D7.13) NET_C(V128_d, D7.2) NET_C(D7.12, H1.4) NET_C(V8_d, H1.5) NET_C(H1.6, C2.4) NET_C(H1.6, C2.5) NET_C(V32_d, J2.9) NET_C(J2.8, C2.10) NET_C(C2.6, C2.9) //---------------------------------------------------------------- // Score circuit //--------------------------------------------------------------- NET_C(SCI_n, D3.4) NET_C(GNDD, D3.2) NET_C(GNDD, D3.3) NET_C(GNDD, D3.1) //---------------------------------------------------------------- // Player 2 //--------------------------------------------------------------- NET_C(PLAYER_2, H7.10) NET_C(S2.2, GND) NET_C(S2.1, H7.9) RES(R18, RES_K(1)) NET_C(R18.2, V5) NET_C(R18.1, S2.1) //A-L 1 and 2 NET_C(SET_BRICKS_n, B3.2) NET_C(H2, B3.3) NET_C(B3.1, E7.6) NET_C(PLAYER_2, E7.5) NET_C(P, N6.9) NET_C(P, M6.9) NET_C(P, L6.9) NET_C(P, H6.9) NET_C(P, J6.9) NET_C(P, K6.9) NET_C(P, N6.10) NET_C(PLAYER_2, N6.7) NET_C(COUNT_2, N6.2) NET_C(START_GAME_n, N6.1) NET_C(N6.15, M6.10) NET_C(PLAYER_2, M6.7) NET_C(COUNT_2, M6.2) NET_C(START_GAME_n, M6.1) NET_C(M6.15, L6.10) NET_C(PLAYER_2, L6.7) NET_C(COUNT_2, L6.2) NET_C(START_GAME_n, L6.1) NET_C(P, H6.10) NET_C(RAM_PLAYER1, H6.7) NET_C(COUNT_1, H6.2) NET_C(START_GAME_n, H6.1) NET_C(H6.15, J6.10) NET_C(RAM_PLAYER1, J6.7) NET_C(COUNT_1, J6.2) NET_C(START_GAME_n, J6.1) NET_C(J6.15, K6.10) NET_C(RAM_PLAYER1, K6.7) NET_C(COUNT_1, K6.2) NET_C(START_GAME_n, K6.1) //CX0 and CX1 NET_C(BRICK_HIT, H2.9) NET_C(H16_n, H2.10) NET_C(P, D5.10) NET_C(P, D5.12) NET_C(H2.8, D5.11) NET_C(SERVE_WAIT_n, D5.13) NET_C(X0, C6.13) NET_C(D5.9, C6.12) NET_C(D5.9, D6.12) NET_C(DN, D6.13) NET_C(D6.11, C6.4) NET_C(X1, C6.5) //---------------------------------------------------------------- // COUNT1 and COUNT2 //--------------------------------------------------------------- NET_C(P, N8.11) NET_C(BRICK_HIT, N8.12) NET_C(ATTRACT_n, N8.13) NET_C(N8.9, N9.11) NET_C(P, N9.15) NET_C(P, N9.5) NET_C(COUNT, N9.4) NET_C(START_GAME, N9.14) NET_C(H8_n, N9.1) NET_C(H16_n, N9.10) NET_C(GNDD, N9.9) NET_C(N9.13, N7.13) NET_C(SCLOCK, N7.12) NET_C(PLAYER_2, N7.5) NET_C(COUNT, N7.4) NET_C(COUNT, M9.1) NET_C(COUNT, N7.10) NET_C(RAM_PLAYER1, N7.9) //---------------------------------------------------------------- // DSW - Free Game and Ball Logic //--------------------------------------------------------------- NET_C(P, C7.1) NET_C(P, C7.10) NET_C(P, C7.7) NET_C(CX0, C7.3) NET_C(CX1, C7.4) NET_C(X2, C7.5) NET_C(GNDD, C7.6) NET_C(D8.8, C7.9) NET_C(C7.15, C8.7) NET_C(C7.11, C8.10) NET_C(C7.12, D7.10) NET_C(C7.13, D7.11) NET_C(CLOCK, C7.2) NET_C(P, C8.1) NET_C(P, C8.3) NET_C(P, C8.4) NET_C(P, C8.5) NET_C(P, C8.6) NET_C(P, C8.9) NET_C(CLOCK, C8.2) NET_C(C8.15, B7.7) NET_C(C7.15, B7.10) NET_C(P, B7.1) NET_C(Y0, B7.3) NET_C(Y1, B7.4) NET_C(Y2, B7.5) NET_C(GNDD, B7.6) NET_C(D8.8, B7.9) NET_C(CLOCK, B7.2) NET_C(B7.15, B8.7) NET_C(VB_HIT_SOUND, D7.9) NET_C(P, B8.1) NET_C(P, B8.3) NET_C(P, B8.4) NET_C(P, B8.5) NET_C(P, B8.6) NET_C(P, B8.9) NET_C(C8.15, B8.10) NET_C(CLOCK, B8.2) NET_C(B8.15, D8.10) NET_C(B7.15, D8.9) NET_C(D7.8, D7.5) NET_C(P_HIT_SOUND, D7.4) NET_C(B8.15, D7.3) //---------------------------------------------------------------- // RH and LH Sides //--------------------------------------------------------------- NET_C(V128, N4.1) NET_C(V64, N4.2) NET_C(V16, N4.13) NET_C(N4.12, N4.11) NET_C(V8, N4.10) NET_C(V4, N4.9) NET_C(N4.8, H2.2) NET_C(V32, H2.1) NET_C(N4.8, J2.13) NET_C(J2.12, J3.11) NET_C(V32, J3.12) //---------------------------------------------------------------- // Top Bound //--------------------------------------------------------------- NET_C(H128, H3.4) NET_C(H64, H3.5) NET_C(H32, H3.3) NET_C(H3.6, L4.9) NET_C(H16, L4.10) NET_C(H8, L4.11) NET_C(L4.8, K4.5) NET_C(VSYNC_n, K4.4) //---------------------------------------------------------------- // Cabinet type // // FIXME: missing? //--------------------------------------------------------------- //---------------------------------------------------------------- // Coin Circuit //--------------------------------------------------------------- NET_C(COIN1.2, F9.13) NET_C(COIN1.1, F9.11) NET_C(COIN1.Q, GND) NET_C(CSW1, COIN1.1) NET_C(F9.10, COIN1.2) NET_C(V64, H7.12) NET_C(V64, H7.13) NET_C(CSW1, F8.10) NET_C(F9.10, F8.12) NET_C(V64I, F8.11) NET_C(P, F8.13) NET_C(P, F8.1) NET_C(V64I, F8.3) NET_C(F8.9, F8.2) NET_C(CSW1, F8.4) NET_C(F8.6, H8.12) NET_C(P, H8.10) NET_C(V16_d, H8.11) NET_C(P, H8.13) NET_C(H8.9, J8.15) NET_C(H8.9, J9.9) NET_C(V16_d, J8.14) NET_C(J8.13, J9.10) NET_C(V4_d, S3.1) NET_C(S3.2, J9.11) RES(R15, RES_K(1)) NET_C(R15.1, V5) NET_C(R15.2, S3.2) NET_C(J9.8, L9.5) NET_C(J9.6, L9.4) NET_C(COIN2.2, F9.1) NET_C(COIN2.1, F9.3) NET_C(COIN2.Q, GND) NET_C(CSW2, COIN2.1) NET_C(CSW2, H9.10) NET_C(F9.4, H9.12) NET_C(F9.4, COIN2.2) NET_C(V64_n, H9.11) NET_C(V64_n, H9.3) NET_C(P, H9.13) NET_C(H9.9, H9.2) NET_C(CSW2, H9.4) NET_C(P, H9.1) NET_C(P, H8.4) NET_C(H9.6, H8.2) NET_C(V16_d, H8.3) NET_C(P, H8.1) NET_C(H8.5, J8.6) NET_C(V16_d, J8.5) NET_C(P, J9.3) NET_C(H8.5, J9.5) NET_C(J8.7, J9.4) NET_C(P2_CONDITIONAL_dash, E9.9) NET_C(E9.8, H1.1) NET_C(E9.8, H1.2) //---------------------------------------------------------------- // Start 1 & 2 logic //--------------------------------------------------------------- RES(R58, RES_K(1)) NET_C(START2.2, GND) NET_C(R58.1, V5) NET_C(START2.1, R58.2, E9.11) NET_C(E9.10, E8.12) NET_C(P, E8.10) NET_C(V64I, E8.11) NET_C(V128_d, F7.2) NET_C(V128_d, F7.3) NET_C(CREDIT2_n, F7.1) NET_C(ATTRACT_n, E7.12) NET_C(F7.4, E7.11) NET_C(E7.13, E8.13) //Start1 Input RES(R57, RES_K(1)) NET_C(START1.2, GND) NET_C(R57.1, V5) NET_C(START1.1, R57.2, E9.3) NET_C(E9.4, E8.2) NET_C(P, E8.4) NET_C(V64_d, E8.3) NET_C(CREDIT_1_OR_2_n, E7.2) NET_C(ATTRACT_n, E7.3) NET_C(E7.1, E8.1) NET_C(CR_START1_n, D8.4) NET_C(CR_START2_n, D8.5) NET_C(START_GAME, M9.3) NET_C(START_GAME, M9.5) NET_C(V32, D6.4) NET_C(ATTRACT, D6.5) NET_C(P, E6.10) NET_C(START_GAME, E6.12) NET_C(D6.6, E6.11) NET_C(D6.3, E6.13) NET_C(CREDIT_1_OR_2_n, D8.13) NET_C(EGL, D8.12) NET_C(LAT_Q, D6.1) NET_C(EGL_n, D6.2) //---------------------------------------------------------------- // Serve logic //--------------------------------------------------------------- RES(R30, RES_K(1)) NET_C(SERVE.2, GND) NET_C(SERVE.1, R30.2) NET_C(R30.1, V5) NET_C(H64, J3.6) NET_C(H32, J3.5) NET_C(J3.4, L4.13) NET_C(H128, L4.2) NET_C(H16, L4.1) NET_C(BALL_DISPLAY, H2.13) NET_C(H128, H2.12) NET_C(H2.11, C3.9) NET_C(HSYNC, C3.10) NET_C(C3.8, B3.5) NET_C(H8_d, B3.6) NET_C(B3.4, C3.4) NET_C(H4, C3.5) NET_C(C3.6, A4.9) NET_C(START_GAME1_n, A4.10) NET_C(SERVE_WAIT_n, D2.13) NET_C(SERVE_n, D2.12) NET_C(SERVE_n, A3.4) NET_C(P, A3.2) NET_C(ATTRACT, A3.3) NET_C(SERVE_WAIT, A3.1) NET_C(BALL, E1.13) NET_C(E1.12, B3.8) NET_C(A3.6, B3.9) NET_C(B3.10, B3.11) NET_C(SERVE_WAIT_n, B3.12) NET_C(B3.13, A3.12) NET_C(A4.8, A3.10) NET_C(L4.12, A3.11) NET_C(P, A3.13) //---------------------------------------------------------------- // Bricks logic //--------------------------------------------------------------- NET_C(P, D3.10) NET_C(P, D3.12) NET_C(START_GAME, D3.11) NET_C(SERVE_n, D3.13) //---------------------------------------------------------------- // Playfield logic //--------------------------------------------------------------- NET_C(LH_SIDE, H3.1) NET_C(TOP_BOUND, H3.13) NET_C(RH_SIDE, H3.2) NET_C(H3.12, H4.2) NET_C(E1.2, C36.1) #if (SLOW_BUT_ACCURATE) NET_C(C36.1, H4.1) #else NET_C(C36.2, H4.1) #endif NET_C(BALL_DISPLAY, A5.10) NET_C(PSYNC, A5.9) NET_C(BSYNC, C3.2) NET_C(TOP_BOUND, C3.1) NET_C(PC, C4.4) NET_C(PD, C4.5) NET_C(BP_HIT_n, C5.13) NET_C(PD, A5.1) NET_C(C5.12, A5.2) NET_C(BSYNC, A5.5) NET_C(VSYNC, A5.4) NET_C(C5.12, A5.13) NET_C(A5.3, A5.12) NET_C(BRICK_HIT, D5.3) NET_C(E5.3, D5.1) NET_C(D5.6, D5.2) NET_C(BP_HIT_n, D5.4) NET_C(P, A6.10) NET_C(C4.6, A6.12) NET_C(BP_HIT_n, A6.11) NET_C(P, A6.13) NET_C(A5.3, A6.4) NET_C(V16_d, A6.2) NET_C(VB_HIT_n, A6.3) NET_C(A5.11, A6.1) NET_C(P2_CONDITIONAL, C6.1) NET_C(D5.5, C6.2) NET_C(D5.6, C4.2) NET_C(P2_CONDITIONAL, C4.1) NET_C(V_SLOW, B6.12) NET_C(A6.8, B6.13) NET_C(V_SLOW, C6.10) NET_C(A6.5, C6.9) NET_C(Y0, B6.4) NET_C(C6.8, B6.5) NET_C(X2, D6.10) NET_C(B6.8, D6.9) NET_C(B5.7, B6.9) NET_C(B5.6, B6.10) NET_C(X0, B6.1) NET_C(X2, B6.2) NET_C(B5.6, C5.11) NET_C(B5.7, C5.9) NET_C(SU_n, B5.11) NET_C(P, B5.15) NET_C(P, B5.1) NET_C(P, B5.10) NET_C(P, B5.9) NET_C(P, B5.4) NET_C(D6.8, B5.5) NET_C(SERVE_WAIT, B5.14) NET_C(BTB_HIT_n, E5.1) NET_C(SBD_n, E5.2) NET_C(BP_HIT_n, E5.4) NET_C(BTB_HIT_n, E5.5) NET_C(E5.6, F7.11) NET_C(E5.6, F7.12) NET_C(BRICK_HIT_n, F7.10) NET_C(F7.9, C2.2) NET_C(BALL_DISPLAY, C2.1) NET_C(L3.6, E3.11) NET_C(C2.3, E3.12) NET_C(SET_BRICKS_n, E6.4) NET_C(E3.13, E6.2) NET_C(CKBH, E6.3) NET_C(E3.13, D2.2) NET_C(SET_BRICKS, D2.1) NET_C(D2.3, E6.1) NET_C(BRICK_DISPLAY, E1.1) NET_C(H1, K4.9) NET_C(H2, K4.10) NET_C(K4.8, E3.2) NET_C(L3.6, E3.3) NET_C(ATTRACT_n, C2.13) NET_C(SET_BRICKS_n, C2.12) NET_C(C2.11, H3.10) NET_C(FPD1, H3.9) NET_C(FPD2, H3.11) NET_C(H3.8, E1.3) NET_C(E1.4, C32.1) NET_C(C32.1, L3.13) NET_C(H4, L3.2) NET_C(H8, L3.1) NET_C(H16, L3.15) NET_C(V32, L3.14) NET_C(V64, L3.7) NET_C(V128, L3.9) NET_C(V16, L3.10) NET_C(RAM_PLAYER1, L3.11) NET_C(H32, L3.3) NET_C(H128, L3.4) NET_C(H4.8, L3.5) NET_C(V2, M4.5) NET_C(V4, M4.4) NET_C(V8, M4.3) NET_C(M4.6, H4.9) NET_C(VSYNC_n, K4.2) NET_C(H64, K4.1) NET_C(K4.3, H4.10) NET_C(FPD1_n, F2.13) NET_C(BRICK_HIT_n, F2.2) NET_C(FPD2_n, F2.1) NET_C(F2.12, L3.12) //---------------------------------------------------------------- // Hit circuits and start logic //--------------------------------------------------------------- NET_C(K2, M4.2) NET_C(G2, M4.13) NET_C(D2, M4.1) NET_C(K1, M4.9) NET_C(G1, M4.10) NET_C(D1, M4.11) NET_C(BP_HIT_n, E4.2) NET_C(M4.12, E4.1) NET_C(BP_HIT_n, E4.4) NET_C(M4.8, E4.5) NET_C(P, F4.4) NET_C(P, F4.2) NET_C(E4.3, F4.3) NET_C(START_GAME1_n, F4.1) NET_C(P, F4.10) NET_C(P, F4.12) NET_C(E4.6, F4.11) NET_C(START_GAME1_n, F4.13) NET_C(F4.6, F3.5) NET_C(GNDD, F3.4) NET_C(F4.8, F3.11) NET_C(GNDD, F3.12) NET_C(P, F3.3) NET_C(P, F3.13) //---------------------------------------------------------------- // Credit counter logic //--------------------------------------------------------------- NET_C(BONUS_COIN, E7.8) NET_C(COIN, E7.9) NET_C(CR_START1_n, H7.2) NET_C(V8, D8.1) NET_C(CR_START2, D8.2) NET_C(D8.3, H7.1) NET_C(L8.12, L8.11) // FIXME: not on schematic, on rollover load 16, keeps you from losing all credits NET_C(P, L8.15) NET_C(P, L8.1) NET_C(P, L8.10) NET_C(P, L8.9) NET_C(E7.10, L8.5) NET_C(H7.3, L8.4) NET_C(LAT_Q, L9.10) NET_C(L8.13, L9.9) NET_C(L9.8, L8.14) NET_C(L8.7, M8.9) NET_C(L8.6, M8.10) NET_C(L8.2, M8.11) NET_C(L8.3, M9.13) NET_C(CREDIT2_n, F9.5) NET_C(CREDIT2_n, L9.2) NET_C(M9.12, L9.1) NET_C(CREDIT_1_OR_2, F9.9) NET_C(CR_START1_n, F7.6) NET_C(CR_START2_n, F7.5) NET_C(PLGM2_n, F2.5) NET_C(PLAYER_2, F2.4) NET_C(H1, F2.3) NET_C(P, F5.4) NET_C(P, F5.2) NET_C(SERVE_WAIT, F5.3) NET_C(H128, F5.1) NET_C(F2.6, D2.9) NET_C(F5.5, D2.10) NET_C(P, B4.10) NET_C(P, B4.7) NET_C(P, B4.9) NET_C(PLAY_CP, B4.2) NET_C(EGL, C5.1) //---------------------------------------------------------------- // Ball logic //--------------------------------------------------------------- NET_C(START_GAME1_n, B4.1) NET_C(BALL_A, A4.2) NET_C(BALL_B, S4.1) // Three balls NET_C(BALL_C, S4.2) // Five balls NET_C(S4.Q, A4.1) NET_C(A4.3, C37.1) NET_C(SERVE_WAIT_n, A4.5) NET_C(BALL, A4.4) //---------------------------------------------------------------- // Video output logic //--------------------------------------------------------------- NET_C(V16_d, D2.4) NET_C(V8_d, D2.5) NET_C(D2.6, E3.8) NET_C(VSYNC_n, E3.9) NET_C(HSYNC_n, E2.12) NET_C(E3.10, E2.13) NET_C(PSYNC, B9.1) NET_C(VSYNC_n, B9.2) RES(R41, RES_K(3.9)) RES(R42, RES_K(3.9)) RES(R43, RES_K(3.9)) RES(R51, RES_K(3.9)) RES(R52, RES_K(3.9)) #if (SLOW_BUT_ACCURATE) DIODE(CR6, "1N914") NET_C(E2.11, CR6.K) NET_C(CR6.A, R41.1, R42.1, R43.1, R51.1, R52.1) #else SYS_DSW(CR6, E2.11, R41.1, GND) PARAM(CR6.RON, 1e20) PARAM(CR6.ROFF, 1) NET_C(R41.1, R42.1, R43.1, R51.1, R52.1) #endif NET_C(R51.2, PLAYFIELD) NET_C(R43.2, BSYNC) NET_C(R52.2, SCORE) NET_C(R41.2, B9.3) NET_C(R42.2, V5) ALIAS(videomix, R41.1) //---------------------------------------------------------------- // Audio logic //--------------------------------------------------------------- RES(R36, RES_K(47)) RES(R37, RES_K(47)) RES(R38, RES_K(47)) RES(R39, RES_K(47)) NET_C(R36.2, B9.11) NET_C(R38.2, B9.8) NET_C(R39.2, FREE_GAME_TONE) NET_C(R37.2, B9.6) NET_C(R36.1, R37.1, R38.1, R39.1) ALIAS(sound, R36.1) //---------------------------------------------------------------- // Potentiometer logic //--------------------------------------------------------------- POT2(POTP1, RES_K(5)) // 5k PARAM(POTP1.DIALLOG, 1) // Log Dial ... PARAM(POTP1.REVERSE, 1) // Log Dial ... NET_C(POTP1.1, V5) POT2(POTP2, RES_K(5)) // 5k PARAM(POTP2.DIALLOG, 1) // Log Dial ... PARAM(POTP2.REVERSE, 1) // Log Dial ... NET_C(POTP2.1, V5) RES(R33, 47) CD4016_DIP(D9) NET_C(D9.7, GND) NET_C(D9.14, V5) NET_C(P2_CONDITIONAL_dash, D9.6) NET_C(D9.12, E9.8) NET_C(D9.8, POTP2.2) // Connect P2 dial here NET_C(D9.11, POTP1.2) NET_C(D9.9, D9.10, R33.1) NET_C(R33.2, C9.6) //---------------------------------------------------------------- // Serve Leds //---------------------------------------------------------------- RES(R40, 150) RES(R21, 150) DIODE(LED1, "LedRed") /* Below is the upright cabinet configuration * cocktail has two leds connected to R40.1 */ NET_C(SERVE_WAIT_n, R21.2) NET_C(R21.1, R40.2) NET_C(LED1.K, R40.1) NET_C(LED1.A, V5) ALIAS(CON_P, R40.1) //---------------------------------------------------------------- // Credit lamps //---------------------------------------------------------------- /* The credit lamp circuit uses thyristors and 6VAC. This is * currently not modeled and instead the CREDIT_1_OR_2 and CREDIT2 * signals are used. */ ALIAS(CON_CREDIT1, L9.3) // CREDIT_1_OR_2 ALIAS(CON_CREDIT2, F9.6) // CREDIT2 //---------------------------------------------------------------- // Coin Counter //---------------------------------------------------------------- NET_C(CSW1, E2.1) NET_C(CSW2, E2.2) RES(R14, 150) QBJT_SW(Q6, "2N5190") DIODE(CR8, "1N4001") NET_C(E2.3, R14.1) NET_C(R14.2, Q6.B) NET_C(GND, Q6.E) NET_C(Q6.C, CR8.A) NET_C(CR8.K, V5) ALIAS(CON_T, Q6.C) // Not on PCB: Coincounter RES(CC_R, 20) // this is connected NET_C(CC_R.1, CON_T) NET_C(CC_R.2, V5) //---------------------------------------------------------------- // Not connected pins //---------------------------------------------------------------- NET_C(ttlhigh, B4.3, B4.4, B4.5, B4.6) NET_C(ttlhigh, N6.3, N6.4, N6.5, N6.6) NET_C(ttlhigh, M6.3, M6.4, M6.5, M6.6) NET_C(ttlhigh, L6.3, L6.4, L6.5, L6.6) NET_C(ttlhigh, H6.3, H6.4, H6.5, H6.6) NET_C(ttlhigh, K6.3, K6.4, K6.5, K6.6) NET_C(ttlhigh, J6.3, J6.4, J6.5, J6.6) NET_C(ttlhigh, E1.9, E1.11) NET_C(GND, D9.1, D9.2, D9.13, D9.3, D9.4, D9.5) //---------------------------------------------------------------- // Power Pins //---------------------------------------------------------------- NET_C(V5, A3.14, A4.14, A5.14, A6.14, B3.14, B4.16, B5.16, B6.14, B7.16, B8.16, B9.14, C2.14, C3.14, C4.14, C5.14, C6.14, C7.16, C8.16, D2.14, D3.14, D4.16, D5.14, D6.14, D7.14, D8.14, E1.14, E2.14, E3.14, E4.14, E5.14, E6.14, E7.14, E8.14, E9.14, F2.14, F4.14, F5.14, F6.16, F7.16, F8.14, F9.14, H1.14, H2.14, H3.14, H4.14, H5.16, H6.16, H7.14, H8.14, H9.14, J1.16, J2.14, J3.14, J4.16, J5.16, J6.16, J7.14, J8.16, J9.14, K1.16, K2.14, K3.14, K4.14, K5.16, K6.16, K7.14, K8.14, K9.14, L1.16, L2.14, L3.16, L4.14, L5.16, L6.16, L7.14, L8.16, L9.14, M1.16, M2.5, M3.14, M4.14, M5.16, M6.16, M8.14, M9.14, N1.16, N2.5, N3.14, N4.14, N5.16, N6.16, N7.14, N9.16) NET_C(GND, A3.7, A4.7, A5.7, A6.7, B3.7, B4.8, B5.8, B6.7, B7.8, B8.8, B9.7, C2.7, C3.7, C4.7, C5.7, C6.7, C7.8, C8.8, D2.7, D3.7, D4.8, D5.7, D6.7, D7.7, D8.7, E1.7, E2.7, E3.7, E4.7, E5.7, E6.7, E7.7, E8.7, E9.7, F2.7, F4.7, F5.7, F6.8, F7.8, F8.7, F9.7, H1.7, H2.7, H3.7, H4.7, H5.8, H6.8, H7.7, H8.7, H9.7, J1.8, J2.7, J3.7, J4.8, J5.8, J6.8, J7.7, J8.8, J9.7, K1.8, K2.7, K3.7, K4.7, K5.8, K6.8, K7.7, K8.7, K9.7, L1.8, L2.7, L3.8, L4.7, L5.8, L6.8, L7.7, L8.8, L9.7, M1.8, M2.12, M3.7, M4.7, M5.8, M6.8, M8.7, M9.7, N1.8, N2.12, N3.7, N4.7, N5.8, N6.8, N7.7, N9.8 ) #if (SLOW_BUT_ACCURATE) NET_C(VCC, F1.16) NET_C(GND, F1.8) #endif // 163% -- manually optimized HINT(B6.C, NO_DEACTIVATE) HINT(C4.C, NO_DEACTIVATE) HINT(C4.D, NO_DEACTIVATE) HINT(C5.C, NO_DEACTIVATE) HINT(C5.D, NO_DEACTIVATE) HINT(E2.B, NO_DEACTIVATE) HINT(E3.B, NO_DEACTIVATE) HINT(E5.D, NO_DEACTIVATE) HINT(E9.F, NO_DEACTIVATE) HINT(H2.A, NO_DEACTIVATE) HINT(H3.A, NO_DEACTIVATE) HINT(J3.D, NO_DEACTIVATE) HINT(J5, NO_DEACTIVATE) // 7448 needs to be disabled in all cases HINT(J6, NO_DEACTIVATE) HINT(J8.A, NO_DEACTIVATE) HINT(J8.C, NO_DEACTIVATE) HINT(K4.D, NO_DEACTIVATE) HINT(M3.B, NO_DEACTIVATE) HINT(M3.D, NO_DEACTIVATE) HINT(M4.B, NO_DEACTIVATE) HINT(M6, NO_DEACTIVATE) HINT(M8.A, NO_DEACTIVATE) HINT(N7.C, NO_DEACTIVATE) NETLIST_END() /* * MCR106-2 model from http://www.duncanamps.com/ * MCR106-1 are used to drive lamps for player 1 and player 2 * These have a BV of 30 ("-2" has 60, see comments below * Not yet modeled. * * MCR106-2 SCR A G K MCE 7-17-95 *MCE MCR106-2 60V 4A pkg:TO-225AA .SUBCKT XMCR1062 1 2 3 QP 6 4 1 POUT OFF QN 4 6 5 NOUT OFF RF 6 4 15MEG RR 1 4 10MEG RGK 6 5 6.25K RG 2 6 46.2 RK 3 5 16.2M DF 6 4 ZF DR 1 4 ZR DGK 6 5 ZGK .MODEL ZF D (IS=1.6F IBV=800N BV=60 RS=2.25MEG) // BV=30 .MODEL ZR D (IS=1.6F IBV=800N BV=80) // BV=80/60*30 .MODEL ZGK D (IS=1.6F IBV=800N BV=6) .MODEL POUT PNP (IS=1.6P BF=1 CJE=60.3P) .MODEL NOUT NPN (IS=1.6P BF=100 RC=65M + CJE=60.3P CJC=12P TF=126N TR=18U) .ENDS XMCR1062 */
21.181722
172
0.57114
[ "model" ]
1f90e34b0271dc6a460a6f4aff2641b69df19a1b
2,838
cc
C++
jarvis/src/model/ModifyAccessWhiteListAutoShareRequest.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
jarvis/src/model/ModifyAccessWhiteListAutoShareRequest.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
jarvis/src/model/ModifyAccessWhiteListAutoShareRequest.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/jarvis/model/ModifyAccessWhiteListAutoShareRequest.h> using AlibabaCloud::Jarvis::Model::ModifyAccessWhiteListAutoShareRequest; ModifyAccessWhiteListAutoShareRequest::ModifyAccessWhiteListAutoShareRequest() : RpcServiceRequest("jarvis", "2018-02-06", "ModifyAccessWhiteListAutoShare") {} ModifyAccessWhiteListAutoShareRequest::~ModifyAccessWhiteListAutoShareRequest() {} std::string ModifyAccessWhiteListAutoShareRequest::getSrcIP()const { return srcIP_; } void ModifyAccessWhiteListAutoShareRequest::setSrcIP(const std::string& srcIP) { srcIP_ = srcIP; setParameter("SrcIP", srcIP); } std::string ModifyAccessWhiteListAutoShareRequest::getSourceIp()const { return sourceIp_; } void ModifyAccessWhiteListAutoShareRequest::setSourceIp(const std::string& sourceIp) { sourceIp_ = sourceIp; setParameter("SourceIp", sourceIp); } int ModifyAccessWhiteListAutoShareRequest::getAutoConfig()const { return autoConfig_; } void ModifyAccessWhiteListAutoShareRequest::setAutoConfig(int autoConfig) { autoConfig_ = autoConfig; setParameter("AutoConfig", std::to_string(autoConfig)); } std::string ModifyAccessWhiteListAutoShareRequest::getProductName()const { return productName_; } void ModifyAccessWhiteListAutoShareRequest::setProductName(const std::string& productName) { productName_ = productName; setParameter("ProductName", productName); } int ModifyAccessWhiteListAutoShareRequest::getWhiteListType()const { return whiteListType_; } void ModifyAccessWhiteListAutoShareRequest::setWhiteListType(int whiteListType) { whiteListType_ = whiteListType; setParameter("WhiteListType", std::to_string(whiteListType)); } std::string ModifyAccessWhiteListAutoShareRequest::getLang()const { return lang_; } void ModifyAccessWhiteListAutoShareRequest::setLang(const std::string& lang) { lang_ = lang; setParameter("Lang", lang); } std::string ModifyAccessWhiteListAutoShareRequest::getSourceCode()const { return sourceCode_; } void ModifyAccessWhiteListAutoShareRequest::setSourceCode(const std::string& sourceCode) { sourceCode_ = sourceCode; setParameter("SourceCode", sourceCode); }
27.028571
91
0.777308
[ "model" ]
1f94bfbfb244e8c3022c05c4d96f61f0ed60f30f
6,748
cpp
C++
src/utils/system/gpu_comm.cpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
null
null
null
src/utils/system/gpu_comm.cpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
null
null
null
src/utils/system/gpu_comm.cpp
rigarash/monolish-debian-package
70b4917370184bcf07378e1907c5239a1ad9579b
[ "Apache-2.0" ]
1
2021-04-06T07:12:11.000Z
2021-04-06T07:12:11.000Z
#include "../../../include/monolish_blas.hpp" #include "../../internal/monolish_internal.hpp" namespace monolish { // vec /////////////////////////////////////// // send template <typename T> void vector<T>::send() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU const T *d = val.data(); const size_t N = val.size(); if (gpu_status == true) { #pragma omp target update to(d [0:N]) } else { #pragma omp target enter data map(to : d [0:N]) gpu_status = true; } #endif logger.util_out(); } // recv template <typename T> void vector<T>::recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *d = val.data(); const size_t N = val.size(); #pragma omp target exit data map(from : d [0:N]) gpu_status = false; } #endif logger.util_out(); } // nonfree_recv template <typename T> void vector<T>::nonfree_recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *d = val.data(); const size_t N = val.size(); #pragma omp target update from(d [0:N]) } #endif logger.util_out(); } // device_free template <typename T> void vector<T>::device_free() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { const T *d = val.data(); const size_t N = val.size(); #pragma omp target exit data map(release : d [0:N]) gpu_status = false; } #endif logger.util_out(); } template void vector<float>::send() const; template void vector<double>::send() const; template void vector<float>::recv(); template void vector<double>::recv(); template void vector<float>::nonfree_recv(); template void vector<double>::nonfree_recv(); template void vector<float>::device_free() const; template void vector<double>::device_free() const; // CRS /////////////////////////////////// // send template <typename T> void matrix::CRS<T>::send() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU const T *vald = val.data(); const int *cold = col_ind.data(); const int *rowd = row_ptr.data(); const size_t N = get_row(); const size_t nnz = get_nnz(); if (gpu_status == true) { #pragma omp target update to(vald [0:nnz], cold [0:nnz], rowd [0:N + 1]) } else { #pragma omp target enter data map(to \ : \ vald [0:nnz], cold [0:nnz], rowd [0:N + 1]) gpu_status = true; } #endif logger.util_out(); } // recv template <typename T> void matrix::CRS<T>::recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *vald = val.data(); int *cold = col_ind.data(); int *rowd = row_ptr.data(); size_t N = get_row(); size_t nnz = get_nnz(); #pragma omp target exit data map(from \ : vald [0:nnz], cold [0:nnz], rowd [0:N + 1]) gpu_status = false; } #endif logger.util_out(); } // nonfree_recv template <typename T> void matrix::CRS<T>::nonfree_recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *vald = val.data(); int *cold = col_ind.data(); int *rowd = row_ptr.data(); size_t N = get_row(); size_t nnz = get_nnz(); #pragma omp target update from(vald [0:nnz], cold [0:nnz], rowd [0:N + 1]) } #endif logger.util_out(); } // device_free template <typename T> void matrix::CRS<T>::device_free() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { const T *vald = val.data(); const int *cold = col_ind.data(); const int *rowd = row_ptr.data(); const size_t N = get_row(); const size_t nnz = get_nnz(); #pragma omp target exit data map(release \ : vald [0:nnz], cold [0:nnz], rowd [0:N + 1]) gpu_status = false; } #endif logger.util_out(); } template void matrix::CRS<float>::send() const; template void matrix::CRS<double>::send() const; template void matrix::CRS<float>::recv(); template void matrix::CRS<double>::recv(); template void matrix::CRS<float>::nonfree_recv(); template void matrix::CRS<double>::nonfree_recv(); template void matrix::CRS<float>::device_free() const; template void matrix::CRS<double>::device_free() const; // Dense /////////////////////////////////// // send template <typename T> void matrix::Dense<T>::send() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU const T *vald = val.data(); const size_t nnz = get_nnz(); if (gpu_status == true) { #pragma omp target update to(vald [0:nnz]) } else { #pragma omp target enter data map(to : vald [0:nnz]) gpu_status = true; } #endif logger.util_out(); } // recv template <typename T> void matrix::Dense<T>::recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *vald = val.data(); size_t nnz = get_nnz(); #pragma omp target exit data map(from : vald [0:nnz]) gpu_status = false; } #endif logger.util_out(); } // nonfree_recv template <typename T> void matrix::Dense<T>::nonfree_recv() { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { T *vald = val.data(); size_t nnz = get_nnz(); #pragma omp target update from(vald [0:nnz]) } #endif logger.util_out(); } // device_free template <typename T> void matrix::Dense<T>::device_free() const { Logger &logger = Logger::get_instance(); logger.util_in(monolish_func); #if MONOLISH_USE_GPU if (gpu_status == true) { const T *vald = val.data(); const size_t nnz = get_nnz(); #pragma omp target exit data map(release : vald [0:nnz]) gpu_status = false; } #endif logger.util_out(); } template void matrix::Dense<float>::send() const; template void matrix::Dense<double>::send() const; template void matrix::Dense<float>::recv(); template void matrix::Dense<double>::recv(); template void matrix::Dense<float>::nonfree_recv(); template void matrix::Dense<double>::nonfree_recv(); template void matrix::Dense<float>::device_free() const; template void matrix::Dense<double>::device_free() const; } // namespace monolish
25.368421
80
0.62626
[ "vector" ]
1f9597a79ff8756bf05012823da1e7742e35c859
9,729
cxx
C++
Logic/igtlioLogic.cxx
adamrankin/OpenIGTLinkIO
9d0b1010be7b92947dbd461dc5298c320dfc00e4
[ "Apache-2.0" ]
7
2016-02-02T19:03:33.000Z
2021-07-31T19:12:03.000Z
Logic/igtlioLogic.cxx
adamrankin/OpenIGTLinkIO
9d0b1010be7b92947dbd461dc5298c320dfc00e4
[ "Apache-2.0" ]
61
2016-02-01T21:47:49.000Z
2022-03-15T16:12:31.000Z
Logic/igtlioLogic.cxx
adamrankin/OpenIGTLinkIO
9d0b1010be7b92947dbd461dc5298c320dfc00e4
[ "Apache-2.0" ]
20
2016-02-01T22:24:52.000Z
2021-07-31T19:12:04.000Z
/*========================================================================== Portions (c) Copyright 2008-2009 Brigham and Women's Hospital (BWH) All Rights Reserved. See Doc/copyright/copyright.txt or http://www.slicer.org/copyright/copyright.txt for details. Program: 3D Slicer Module: $HeadURL: http://svn.slicer.org/Slicer4/trunk/Modules/OpenIGTLinkIF/vtkSlicerOpenIGTLinkIFLogic.cxx $ Date: $Date: 2011-06-12 14:55:20 -0400 (Sun, 12 Jun 2011) $ Version: $Revision: 16985 $ ==========================================================================*/ #include <algorithm> // IGTLIO includes #include "igtlioLogic.h" #include "igtlioConnector.h" #include "igtlioSession.h" #include <vtkObjectFactory.h> // OpenIGTLinkIF Logic includes #include <vtkNew.h> #include <vtkCallbackCommand.h> #include <vtkImageData.h> #include <vtkTransform.h> //--------------------------------------------------------------------------- void onNewDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata) { igtlioLogic* logic = reinterpret_cast<igtlioLogic*>(clientdata); logic->InvokeEvent(igtlioLogic::NewDeviceEvent, calldata); } //--------------------------------------------------------------------------- void onRemovedDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata) { igtlioLogic* logic = reinterpret_cast<igtlioLogic*>(clientdata); logic->InvokeEvent(igtlioLogic::RemovedDeviceEvent, calldata); igtlioDevice* device = reinterpret_cast<igtlioDevice*>(calldata); device->RemoveObserver(logic->DeviceEventCallback); } //--------------------------------------------------------------------------- void onDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata) { igtlioLogic* logic = reinterpret_cast<igtlioLogic*>(clientdata); if (eid==igtlioConnector::DeviceContentModifiedEvent) { logic->InvokeEvent(eid, calldata); } } //--------------------------------------------------------------------------- void onCommandEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata) { igtlioLogic* logic = reinterpret_cast<igtlioLogic*>(clientdata); if ((eid == igtlioCommand::CommandResponseEvent) || (eid == igtlioCommand::CommandExpiredEvent) || (eid == igtlioCommand::CommandReceivedEvent) || (eid == igtlioCommand::CommandCancelledEvent) || (eid == igtlioCommand::CommandCompletedEvent)) { logic->InvokeEvent(eid, calldata); } } //--------------------------------------------------------------------------- vtkStandardNewMacro(igtlioLogic); //--------------------------------------------------------------------------- igtlioLogic::igtlioLogic() : vtkObject() , NewDeviceCallback(vtkSmartPointer<vtkCallbackCommand>::New()) , RemovedDeviceCallback(vtkSmartPointer<vtkCallbackCommand>::New()) , DeviceEventCallback(vtkSmartPointer<vtkCallbackCommand>::New()) , CommandEventCallback(vtkSmartPointer<vtkCallbackCommand>::New()) { this->NewDeviceCallback->SetCallback(onNewDeviceEventFunc); this->NewDeviceCallback->SetClientData(this); this->RemovedDeviceCallback->SetCallback(onRemovedDeviceEventFunc); this->RemovedDeviceCallback->SetClientData(this); this->DeviceEventCallback->SetCallback(onDeviceEventFunc); this->DeviceEventCallback->SetClientData(this); this->CommandEventCallback->SetCallback(onCommandEventFunc); this->CommandEventCallback->SetClientData(this); } //--------------------------------------------------------------------------- igtlioLogic::~igtlioLogic() { } //--------------------------------------------------------------------------- void igtlioLogic::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "vtkIGTLIOLogic: " << this->GetClassName() << "\n"; } //--------------------------------------------------------------------------- igtlioConnectorPointer igtlioLogic::CreateConnector() { igtlioConnectorPointer connector = igtlioConnectorPointer::New(); connector->SetUID(this->CreateUniqueConnectorID()); std::stringstream ss; ss << "IGTLConnector_" << connector->GetUID(); connector->SetName(ss.str()); Connectors.push_back(connector); connector->AddObserver(igtlioConnector::NewDeviceEvent, NewDeviceCallback); connector->AddObserver(igtlioConnector::DeviceContentModifiedEvent, DeviceEventCallback); connector->AddObserver(igtlioConnector::RemovedDeviceEvent, RemovedDeviceCallback); connector->AddObserver(igtlioCommand::CommandResponseEvent, CommandEventCallback); connector->AddObserver(igtlioCommand::CommandExpiredEvent, CommandEventCallback); connector->AddObserver(igtlioCommand::CommandReceivedEvent, CommandEventCallback); connector->AddObserver(igtlioCommand::CommandCancelledEvent, CommandEventCallback); connector->AddObserver(igtlioCommand::CommandCompletedEvent, CommandEventCallback); this->InvokeEvent(ConnectionAddedEvent, connector.GetPointer()); return connector; } //--------------------------------------------------------------------------- int igtlioLogic::CreateUniqueConnectorID() const { int retval=0; for (unsigned int i=0; i<Connectors.size(); ++i) { retval = std::max<int>(retval, Connectors[i]->GetUID()+1); } return retval; } //--------------------------------------------------------------------------- int igtlioLogic::RemoveConnector(unsigned int index) { std::vector<igtlioConnectorPointer>::iterator toRemove = Connectors.begin()+index; return this->RemoveConnector(toRemove); } //--------------------------------------------------------------------------- int igtlioLogic::RemoveConnector(igtlioConnectorPointer connector) { std::vector<igtlioConnectorPointer>::iterator toRemove = Connectors.begin(); for(; toRemove != Connectors.end(); ++toRemove) { if(connector == (*toRemove)) break; } return this->RemoveConnector(toRemove); } //--------------------------------------------------------------------------- int igtlioLogic::RemoveConnector(std::vector<igtlioConnectorPointer>::iterator toRemove) { if(toRemove == Connectors.end()) return 0; toRemove->GetPointer()->RemoveObserver(NewDeviceCallback); toRemove->GetPointer()->RemoveObserver(RemovedDeviceCallback); toRemove->GetPointer()->RemoveObserver(DeviceEventCallback); toRemove->GetPointer()->RemoveObserver(CommandEventCallback); this->InvokeEvent(ConnectionAboutToBeRemovedEvent, toRemove->GetPointer()); Connectors.erase(toRemove); return 1; } //--------------------------------------------------------------------------- int igtlioLogic::GetNumberOfConnectors() const { return Connectors.size(); } //--------------------------------------------------------------------------- igtlioConnectorPointer igtlioLogic::GetConnector(unsigned int index) { if (index<Connectors.size()) return Connectors[index]; vtkErrorMacro("index " << index << " out of bounds."); return NULL; } igtlioSessionPointer igtlioLogic::StartServer(int serverPort, IGTLIO_SYNCHRONIZATION_TYPE sync, double timeout_s) { igtlioSessionPointer session = igtlioSessionPointer::New(); session->SetConnector(this->CreateConnector()); session->StartServer(serverPort, sync, timeout_s); return session; } igtlioSessionPointer igtlioLogic::ConnectToServer(std::string serverHost, int serverPort, IGTLIO_SYNCHRONIZATION_TYPE sync, double timeout_s) { igtlioSessionPointer session = igtlioSessionPointer::New(); session->SetConnector(this->CreateConnector()); session->ConnectToServer(serverHost, serverPort, sync, timeout_s); return session; } //--------------------------------------------------------------------------- void igtlioLogic::PeriodicProcess() { for (unsigned i=0; i<Connectors.size(); ++i) { Connectors[i]->PeriodicProcess(); } } //--------------------------------------------------------------------------- unsigned int igtlioLogic::GetNumberOfDevices() const { std::vector<igtlioDevicePointer> all = this->CreateDeviceList(); return all.size(); } //--------------------------------------------------------------------------- void igtlioLogic::RemoveDevice(unsigned int index) { igtlioDevicePointer device = this->GetDevice(index); for (unsigned i=0; i<Connectors.size(); ++i) { for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j) { igtlioDevicePointer local = Connectors[i]->GetDevice(j); if (device==local) Connectors[i]->RemoveDevice(j); } } } //--------------------------------------------------------------------------- igtlioDevicePointer igtlioLogic::GetDevice(unsigned int index) { // TODO: optimize by caching the vector if necessary std::vector<igtlioDevicePointer> all = this->CreateDeviceList(); if (index<all.size()) return all[index]; vtkErrorMacro("index " << index << " out of bounds."); return NULL; } //--------------------------------------------------------------------------- int igtlioLogic::ConnectorIndexFromDevice( igtlioDevicePointer d ) { for( std::vector<igtlioConnectorPointer>::size_type i = 0; i < Connectors.size(); ++i ) if( Connectors[i]->HasDevice(d) ) return i; return -1; } //--------------------------------------------------------------------------- std::vector<igtlioDevicePointer> igtlioLogic::CreateDeviceList() const { std::set<igtlioDevicePointer> all; for (unsigned i=0; i<Connectors.size(); ++i) { for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j) { all.insert(Connectors[i]->GetDevice(j)); } } return std::vector<igtlioDevicePointer>(all.begin(), all.end()); }
34.5
141
0.605201
[ "vector", "3d" ]
1faf14bc1d16aabace84b98552c20332bd6ec4b2
21,773
cpp
C++
projects-lib/mini-gl-engine/util/Animation.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
15
2019-01-13T16:07:27.000Z
2021-09-27T15:18:58.000Z
projects-lib/mini-gl-engine/util/Animation.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
1
2019-03-14T00:36:35.000Z
2020-12-29T11:48:09.000Z
projects-lib/mini-gl-engine/util/Animation.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
3
2020-03-02T21:28:56.000Z
2021-09-27T15:18:50.000Z
#include "Animation.h" namespace GLEngine { bool AnimationClip::findRootNode(Transform *t, const void* userData) { if (root_node != NULL) return false; const model::Animation &animation = *(const model::Animation*)userData; for (int i = 0; i < animation.channels.size(); i++) { const model::NodeAnimation &node_anim = animation.channels[i]; if (node_anim.nodeName.compare(t->Name) == 0) { root_node = t; return false; } } return true; } AnimationClip::AnimationClip(const std::string &clip_name, Transform *root, const model::Animation &animation ) { base_model = root; root_node = NULL; root->traversePreOrder_DepthFirst( TransformTraverseMethod_const(this, &AnimationClip::findRootNode), &animation); loop = true; wait_end_to_transition = false; last_sampled_time = -1.0f; current_time = 0.0f; //name = animation.name; name = clip_name; duration = animation.durationTicks / animation.ticksPerSecond; printf("AnimationClip(%s)\n",name.c_str()); int root_node_animation_index = -1; for (int i=0;i<animation.channels.size();i++){ const model::NodeAnimation &node_anim = animation.channels[i]; Transform *t_node = root->findTransformByName(node_anim.nodeName); if (t_node != NULL){ printf(" --channel %i (node: %s)\n",i, node_anim.nodeName.c_str()); printf(" positions: %lu\n",node_anim.positionKeys.size()); printf(" scales: %lu\n",node_anim.scalingKeys.size()); printf(" rotations: %lu\n",node_anim.rotationKeys.size()); NodeAnimation result; if (node_anim.positionKeys.size() > 0) for (int j=0;j<node_anim.positionKeys.size();j++){ const model::Vec3Key &key = node_anim.positionKeys[j]; result.position.addKey( Key<aRibeiro::vec3>(key.time / animation.ticksPerSecond, key.value) ); } if (node_anim.scalingKeys.size() > 0) for (int j=0;j<node_anim.scalingKeys.size();j++){ const model::Vec3Key &key = node_anim.scalingKeys[j]; result.scale.addKey( Key<aRibeiro::vec3>(key.time / animation.ticksPerSecond, key.value) ); } if (node_anim.rotationKeys.size() > 0) for (int j=0;j<node_anim.rotationKeys.size();j++){ const model::QuatKey &key = node_anim.rotationKeys[j]; result.rotation.addKey( Key<aRibeiro::quat>(key.time / animation.ticksPerSecond, key.value) ); } //result.node = t_node; result.setTransform(t_node, t_node == root_node); if (result.isRootNode) root_node_animation_index = channels.size(); channels.push_back(result); } else { printf("[AnimationClip] Animation without a scene node...\n"); } } ARIBEIRO_ABORT(root_node_animation_index == -1, "No bone root animation found..."); root_node_animation = &channels[root_node_animation_index]; printf("[AnimationClip] Bone root: %s\n", root_node_animation->node->getName().c_str()); root_node_animation->clampDuration(0, duration); } void AnimationClip::update(float elapsed_secs) { current_time += elapsed_secs; if (!loop){ if (current_time > duration) current_time = duration; } else { current_time = fmod( current_time, duration); } //doSample(); } void AnimationClip::reset() { last_sampled_time = -1; current_time = 0; root_node_animation->resetInterframeInformation(); //printf("reset %s \n", name.c_str()); //doSample(); } void AnimationClip::forceResample(){ last_sampled_time = -1; } void AnimationClip::doSample(float amount, RootMotionAnalyser *rootMotionAnalyser) { if (last_sampled_time != current_time) { rootMotionAnalyser->data.clip_count = 1; rootMotionAnalyser->data.clip_to_process = 0; rootMotionAnalyser->data.clipInfo[0].clip = this; rootMotionAnalyser->data.clipInfo[0].weight = 1.0f;//force weight to be 1.0... for (int i=0;i<channels.size();i++) channels[i].sampleTime(current_time, amount, rootMotionAnalyser); last_sampled_time = current_time; } } bool AnimationClip::canDoSample() { return last_sampled_time != current_time; } void AnimationClip::didExternalSample() { last_sampled_time = current_time; } AnimationTransitionChannelInformation& AnimationMixer::getTransition(uint32_t x, uint32_t y){ return transitions[x+y*clips_array.size()]; } AnimationMixer::AnimationMixer() { current_clip = NULL; current_index = 0; } AnimationMixer::~AnimationMixer() { for (int i=0;i<clips_array.size();i++){ delete clips_array[i]; } clips_index.clear(); clips_array.clear(); transitions.clear(); current_clip = NULL; } void AnimationMixer::addClip(AnimationClip* clip) { ARIBEIRO_ABORT(transitions.size() > 0,"trying to add clip after the animation transition computation.\n"); clips_index[clip->name] = clips_array.size(); clips_array.push_back(clip); } void AnimationMixer::computeTransitions() { ARIBEIRO_ABORT(transitions.size() > 0,"trying to initialize the animation twice.\n"); //normalize the scale of all clips Transform *model_from_file = clips_array[0]->base_model->getChildAt(0); aRibeiro::vec3 scale = model_from_file->getScale(); printf("[AnimationMixer] Model scale: %f %f %f.\n", scale.x, scale.y, scale.z); if (current_clip == NULL) { current_clip = clips_array[0]; current_clip->doSample(1.0f, &rootMotionAnalyser); if (rootMotionAnalyser.method != NULL && rootMotionAnalyser.data.dirty) { rootMotionAnalyser.data.dirty = false; rootMotionAnalyser.method(&rootMotionAnalyser.data); } } //check the clips root node for (int i = 1; i < clips_array.size(); i++) { ARIBEIRO_ABORT(clips_array[i]->root_node != current_clip->root_node, "All animations need to share the root node with an animation attached to it.\n"); } transitions.resize(clips_array.size()*clips_array.size()); for(int index_a=0;index_a<clips_array.size();index_a++){ for(int index_b=0;index_b<clips_array.size();index_b++){ if (index_a>=index_b) continue; AnimationClip* clip_a = clips_array[index_a]; AnimationClip* clip_b = clips_array[index_b]; AnimationTransitionChannelInformation &transition = getTransition(index_a, index_b); for(int i=0;i<clip_a->channels.size();i++){ Transform *aNode = clip_a->channels[i].node; NodeAnimation *channel_b = NULL; bool found = false; for(int j=0;j<clip_b->channels.size();j++){ Transform *bNode = clip_b->channels[j].node; if (aNode == bNode) { found = true; channel_b = &clip_b->channels[j]; break; } } if (!found){ transition.no_matching_a_elements.push_back(&clip_a->channels[i]); } else { transition.matching_a_elements.push_back(&clip_a->channels[i]); //transition.matching_b_elements.push_back(&clip_b->channels[i]); transition.matching_b_elements.push_back(channel_b); } } for(int i=0;i<clip_b->channels.size();i++){ Transform *bNode = clip_b->channels[i].node; bool found = false; for(int j=0;j<clip_a->channels.size();j++){ Transform *aNode = clip_a->channels[j].node; if (aNode == bNode) { found = true; break; } } if (!found){ transition.no_matching_b_elements.push_back(&clip_b->channels[i]); } else { //transition.matching_b_elements.push_back(&clip_b->channels[i]); } } ARIBEIRO_ABORT( transition.matching_a_elements.size() != transition.matching_b_elements.size(), "Error on compute animation transition matrix.\n" ); } } } void AnimationMixer::update(float elapsed_secs) { if (request_queue.size() == 0) { current_clip->update(elapsed_secs); current_clip->doSample(1.0f, &rootMotionAnalyser); if (rootMotionAnalyser.method != NULL && rootMotionAnalyser.data.dirty) { rootMotionAnalyser.data.dirty = false; rootMotionAnalyser.method(&rootMotionAnalyser.data); } } else { AnimationMixerLerpTarget *anim_target = &request_queue[0]; anim_target->incrementTransitionTime(elapsed_secs); if (anim_target->reachedEnd()) { //set new current clip and index... and remove the first element from queue current_clip = anim_target->clip; current_index = anim_target->index; request_queue.erase(request_queue.begin()); current_clip->update(elapsed_secs); current_clip->doSample(1.0f, &rootMotionAnalyser); if (rootMotionAnalyser.method != NULL && rootMotionAnalyser.data.dirty) { rootMotionAnalyser.data.dirty = false; rootMotionAnalyser.method(&rootMotionAnalyser.data); } } else { //custom sample clips acording the weight (lerp) float lrp = anim_target->computeLerp(); float one_minus_lrp = 1.0f - lrp; current_clip->update(elapsed_secs); anim_target->clip->update(elapsed_secs); bool current_clip_can_do_sample = current_clip->canDoSample(); bool blend_clip_can_do_sample = anim_target->clip->canDoSample(); //query transition Node animation information uint32_t index_a = current_index; uint32_t index_b = anim_target->index; bool swap_index = false; if (index_a > index_b) swap_index = true; std::vector<NodeAnimation*> *no_matching_a_elements; std::vector<NodeAnimation*> *no_matching_b_elements; std::vector<NodeAnimation*> *matching_a_elements; std::vector<NodeAnimation*> *matching_b_elements; if (swap_index) { AnimationTransitionChannelInformation &transition = getTransition(index_b, index_a); no_matching_a_elements = &transition.no_matching_b_elements; no_matching_b_elements = &transition.no_matching_a_elements; matching_a_elements = &transition.matching_b_elements; matching_b_elements = &transition.matching_a_elements; } else { AnimationTransitionChannelInformation &transition = getTransition(index_a, index_b); no_matching_a_elements = &transition.no_matching_a_elements; no_matching_b_elements = &transition.no_matching_b_elements; matching_a_elements = &transition.matching_a_elements; matching_b_elements = &transition.matching_b_elements; } ARIBEIRO_ABORT(matching_a_elements->size() != matching_b_elements->size(), "Matching elements different sizes.\n"); float anim_time_a = current_clip->current_time, anim_time_b = anim_target->clip->current_time; rootMotionAnalyser.data.clip_count = 2; rootMotionAnalyser.data.clipInfo[0].clip = current_clip; rootMotionAnalyser.data.clipInfo[1].clip = anim_target->clip; // // Independent transforms update // rootMotionAnalyser.data.clip_to_process = 0; if (current_clip_can_do_sample) { for (int i = 0; i < no_matching_a_elements->size(); i++) no_matching_a_elements->at(i)->sampleTime(anim_time_a, one_minus_lrp, &rootMotionAnalyser); current_clip->didExternalSample(); } rootMotionAnalyser.data.clip_to_process = 1; if (blend_clip_can_do_sample) { for (int i = 0; i < no_matching_b_elements->size(); i++) no_matching_b_elements->at(i)->sampleTime(anim_time_b, lrp, &rootMotionAnalyser); anim_target->clip->didExternalSample(); } // // shared transforms update // for (int i = 0; i < matching_a_elements->size(); i++) { NodeAnimation* node_a = matching_a_elements->at(i); NodeAnimation* node_b = matching_b_elements->at(i); ARIBEIRO_ABORT(node_a->node != node_b->node, "Node A transform different from node B transform.\n"); node_a->Sample_Lerp_to_Another_Node(anim_time_a, node_b, anim_time_b, lrp, &rootMotionAnalyser); } //all blend frames could generate a dirty flag if (rootMotionAnalyser.method != NULL && rootMotionAnalyser.data.dirty) { rootMotionAnalyser.data.dirty = false; rootMotionAnalyser.method(&rootMotionAnalyser.data); } } } } void AnimationMixer::play(const std::string &clipname, float blend_time) { if (clips_index.find(clipname) == clips_index.end()) return; uint32_t index = clips_index[clipname]; if (request_queue.size() == 0) { if (current_index == index) return; } else { if (request_queue[request_queue.size() - 1].index == index) return; } while (request_queue.size() > 1) request_queue.pop_back(); if (request_queue.size() == 0 || request_queue[0].index != index) request_queue.push_back(AnimationMixerLerpTarget(clips_array[index], index, blend_time)); } Transform * AnimationMixer::rootNode() { return current_clip->root_node; } RootMotionAnalyserData::RootMotionAnalyserData(){ clipInfo[0].clip = NULL; clipInfo[0].weight = 0.0f; clipInfo[1].clip = NULL; clipInfo[1].weight = 0.0f; clip_count = 0; clip_to_process = 0; dirty = true; } void RootMotionAnalyserData::setFromCurrentState() { if (!isClipsBlending()) { for (int i = 0; i < clip_count; i++) { clip_to_process = i; setFromNodeAnimation(clipInfo[i].clip->root_node_animation, clipInfo[i].clip->current_time , clipInfo[i].weight); } } else { setFromNodeAnimationBlend( clipInfo[0].clip->root_node_animation, clipInfo[0].clip->current_time, clipInfo[1].clip->root_node_animation, clipInfo[1].clip->current_time, clipInfo[1].weight); } } void RootMotionAnalyserData::setFromNodeAnimation( NodeAnimation *node_animation, float time, float weight ){ dirty = true; Transform *node = node_animation->node; ClipInfo *_clipInfo = &clipInfo[clip_to_process]; aRibeiro::vec3 target_local_position = node_animation->samplePos(time, &_clipInfo->position_delta_interframe); //make global node->setLocalPosition(_clipInfo->position_delta_interframe); _clipInfo->position_delta_interframe = node->getPosition(); node->setLocalPosition(target_local_position); _clipInfo->position = node->getPosition(); node->setLocalPosition(node_animation->start_position); _clipInfo->start = node->getPosition(); _clipInfo->local_position = target_local_position; _clipInfo->local_start = node_animation->start_position; //compute deltas _clipInfo->position_delta = _clipInfo->position - _clipInfo->start; _clipInfo->local_position_delta = _clipInfo->local_position - _clipInfo->local_start; _clipInfo->weight = weight; } void RootMotionAnalyserData::setFromNodeAnimationBlend( NodeAnimation *node_animation_a, float time_a, NodeAnimation *node_animation_b, float time_b, float lrp ) { dirty = true; ClipInfo *clipInfo_a = &clipInfo[0]; ClipInfo *clipInfo_b = &clipInfo[1]; Transform *node = node_animation_a->node; aRibeiro::vec3 target_local_position_a = node_animation_a->samplePos(time_a, &clipInfo_a->position_delta_interframe); aRibeiro::vec3 target_local_position_b = node_animation_b->samplePos(time_b, &clipInfo_b->position_delta_interframe); //make global node->setLocalPosition(clipInfo_a->position_delta_interframe); clipInfo_a->position_delta_interframe = node->getPosition(); node->setLocalPosition(target_local_position_a); clipInfo_a->position = node->getPosition(); node->setLocalPosition(node_animation_a->start_position); clipInfo_a->start = node->getPosition(); clipInfo_a->weight = 1.0f - lrp; clipInfo_a->local_position = target_local_position_a; clipInfo_a->local_start = node_animation_a->start_position; clipInfo_a->position_delta = clipInfo_a->position - clipInfo_a->start; clipInfo_a->local_position_delta = clipInfo_a->local_position - clipInfo_a->local_start; //make global node->setLocalPosition(clipInfo_b->position_delta_interframe); clipInfo_b->position_delta_interframe = node->getPosition(); node->setLocalPosition(target_local_position_b); clipInfo_b->position = node->getPosition(); node->setLocalPosition(node_animation_b->start_position); clipInfo_b->start = node->getPosition(); clipInfo_b->weight = lrp; clipInfo_b->local_position = target_local_position_b; clipInfo_b->local_start = node_animation_b->start_position; clipInfo_b->position_delta = clipInfo_b->position - clipInfo_b->start; clipInfo_b->local_position_delta = clipInfo_b->local_position - clipInfo_b->local_start; node->setLocalPosition(aRibeiro::lerp(clipInfo_a->local_start, clipInfo_b->local_start, lrp)); } bool RootMotionAnalyserData::isClipsBlending() const { return clip_count == 2 && clipInfo[0].clip->root_node_animation->node == clipInfo[1].clip->root_node_animation->node; } void RootMotionAnalyserData::applyMotionLocalExample() { if (!isClipsBlending()) { for (int i = 0; i < clip_count; i++) { ClipInfo &_clipInfo = clipInfo[i]; _clipInfo.clip->root_node->setLocalPosition(aRibeiro::lerp( _clipInfo.local_start, _clipInfo.local_position, _clipInfo.weight )); } } else { // 2 clips, and they have the same node ClipInfo &clipInfo_a = clipInfo[0]; ClipInfo &clipInfo_b = clipInfo[1]; Transform *node = clipInfo_a.clip->root_node; node->setLocalPosition(aRibeiro::lerp( clipInfo_a.local_position, clipInfo_b.local_position, clipInfo_b.weight )); } } void RootMotionAnalyserData::applyMotionGlobalExample() { if (!isClipsBlending()) { for (int i = 0; i < clip_count; i++) { ClipInfo &_clipInfo = clipInfo[i]; _clipInfo.clip->root_node->setPosition(aRibeiro::lerp( _clipInfo.start, _clipInfo.position, _clipInfo.weight )); } } else { // 2 clips, and they have the same node ClipInfo &clipInfo_a = clipInfo[0]; ClipInfo &clipInfo_b = clipInfo[1]; Transform *node = clipInfo_a.clip->root_node; node->setPosition(aRibeiro::lerp( clipInfo_a.position, clipInfo_b.position, clipInfo_b.weight )); } } }
36.966044
164
0.574703
[ "vector", "model", "transform" ]
1fbd3cdea733b26cbca2f2018c7b5d1ceb8904f7
747
hpp
C++
sensact_firmware_stm32/lib/core/cModel.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2021-02-09T16:17:43.000Z
2021-08-09T04:02:44.000Z
sensact_firmware_stm32/lib/core/cModel.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2016-05-17T20:45:10.000Z
2020-03-10T07:03:39.000Z
sensact_firmware_stm32/lib/core/cModel.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
1
2020-05-24T13:37:55.000Z
2020-05-24T13:37:55.000Z
#pragma once #include "common.hpp" #ifdef SENSACTUP #include <cWs281x.h> #endif #include "cApplication.hpp" //#include <cWeeklySchedule.h> namespace sensactcore { class MODEL { public: //Index is source appId static cApplication *const Glo2locEvt[]; //Index is destination appId static cApplication *const Glo2locCmd[]; static const eNodeID NodeID; static const char NodeDescription[]; static const eApplicationID NodeMasterApplication; static const char *const ApplicationNames[]; static const uint8_t wellKnownRGBWColors[][4]; static const uint8_t wellKnownRGBWColorsCnt; //static cWeeklySchedule volumeSchedule; #ifdef MASTERNODE static uint8_t applicationStatus[][8]; #endif }; } // namespace sensactcore
21.342857
52
0.760375
[ "model" ]
1fbf474faf03014748cb283b4cea7bb6dab50196
7,640
hpp
C++
src/dude/clong/Repository.hpp
fabic/cxx-playground
61f6bdd91bb886c172df7686971511e2c348b1ef
[ "MIT" ]
null
null
null
src/dude/clong/Repository.hpp
fabic/cxx-playground
61f6bdd91bb886c172df7686971511e2c348b1ef
[ "MIT" ]
null
null
null
src/dude/clong/Repository.hpp
fabic/cxx-playground
61f6bdd91bb886c172df7686971511e2c348b1ef
[ "MIT" ]
null
null
null
#ifndef _PIMPL_PLUGIN_Repository_HPP #define _PIMPL_PLUGIN_Repository_HPP #include <functional> #include <memory> #include <clang/AST/Type.h> // for Qualifiers. // #include <llvm/ADT/MapVector.h> // ^ TEMP. imported : #include "dude/llvm/MapVector.hpp" #include "types.hpp" #include "exceptions.hpp" namespace clang { class DeclContext; class Decl; class TranslationUnitDecl; class NamedDecl; class NamespaceDecl; class Type; class TypeLoc; } namespace clong { namespace plugin { using namespace clang; // FIXME: Clang 5.0.1 -> 6.x : strange llvm::Type name conflict. using Type = clang::Type; // Fwd decl. class Repository ; // Fwd Decl. class Clong ; /** * A "code artifact" : used to represent either a `Decl *` or a `Type *`. * * TODO: Copy ctor/assign & Move -abilities (?) maybe prevent copying? */ class Artifact { // Repository is friend so that it can access private // methods `SetIndex()` and `GetIndex0()`. friend class Repository ; private: /// The Clang `Decl` this artifact is bound to. const Decl* Decl_ ; const Type* Type_ ; /// TODO: impl. const Qualifiers Quals_ ; /// The database identifier, 0 meaning "not defined". DBIdentifier_t ID_ ; /// Unique 1-based index of this artifact within the /// `Repository::Map_t` vector. size_t Index_ ; private: /// [private] Used by Repository::Add() for setting this artifact's index /// which is known once it has been inserted into the Repository artifacts /// map. Artifact& SetIndex(size_t I) { Index_ = I ; return *this; } /// Return the 0-based index of this artifact inside the Repository /// MapVector of Decl/s. This was made private, with the Repository /// as a friend class. size_t GetIndex0() const { return Index_ ; } public: /// Ctor. explicit Artifact(const Decl* D, DBIdentifier_t ID = 0) : Decl_(D) , ID_(ID) , Index_(0) { assert(Decl_ != nullptr); } /// Ctor. explicit Artifact(const Type* T, Qualifiers Q, DBIdentifier_t ID = 0) : Decl_(nullptr) , Type_(T), Quals_(Q) , ID_(ID), Index_(0) { assert(Type_ != nullptr); } private: /// Ctor : Nil artifact. Artifact() : Decl_(nullptr), Type_(nullptr), Quals_(), ID_(0), Index_(0) { /* noop */ } /// Ctor explicit Artifact(DBIdentifier_t ID) : Decl_(nullptr), Type_(nullptr), Quals_(), ID_(ID), Index_(0) { /* noop */ } public: /// Returns _this_ 1-based artifact number (which is set by the Repository /// upon insertion in its map of artifacts). Note: it happens that this /// number is _the index within the artifacts vector container, +1_. size_t GetNumber() const { assert(Index_ > 0 && "Artifact index wasn't initialized ?"); return Index_ + 1 ; } /// Shall not return nullptr. const Decl* GetDecl() const { return Decl_ ; } /// Helper for casting the Decl* to one of its subtypes. template<typename DeclSubType> const DeclSubType * GetDeclAs() const { return cast< DeclSubType >( Decl_ ) ; } /// Helper that returns a DeclContext if Decl is one, else throws! const DeclContext* GetAsDeclContext() const; /// True if `Decl_` is-a `DeclContext`. bool isDeclContext() const; bool hasDatabaseIdentifier() const { return ID_ > 0 ; } /// May return 0, is it ok ? DBIdentifier_t getDatabaseID() const { return ID_ ; } Artifact& setDatabaseID(DBIdentifier_t ID) { assert( ID > 0 ); // we do not allow setting it back to 0. ID_ = ID; return *this; } }; /** * Repository that indexes Decl/s and Type/s wrapped as `Artifact`/s * into a map. * * * TODO: have a Clong& ref. so that we may query the DB for stuff, specif. * for querying Artifacts for builtin types. */ class Repository { public: /// Key type may be a `const Decl*` or `const Type*` (?) using Key_t = size_t; using Map_t = MapVector< Key_t, Artifact > ; using DeclContextStack_t = llvm::SmallVector< size_t, /* nElt= */ 32 > ; public: /// Comes up with a key for this `Decl*` for insertion in the artifacts map. /// Note: we're using the `Decl*` memory address. static Key_t KeyOf(const Decl *D) { return reinterpret_cast< size_t >( D ); } /// Likewise for Type/s. static Key_t KeyOf(const Type *T) { return reinterpret_cast< size_t >( T ); } private: /// Reference to the owning Clong. Clong& Clong_; /// The artifacts map. Note that it is a `_llvm::MapVector<>` which is a /// `llvm::DenseMap<>` along with a `std::vector` that preserve information /// about the insertion order. Map_t Artifacts_ ; /// A stack of integers that are indexes into the `Artifacts_` map, for /// DeclContext artifacts. DeclContextStack_t DCStack_ ; private: /// For the impl. of Add() where we need to `Artifact::SetIndex()`. size_t GetIndexOfLastArtifact() const { // See ctor: we ensure there's at least one "NIL" artifact. // if (Artifacts_.empty()) // throw clong_error("GetIndexOfLastArtifact(): we have no artifacts (empty map)."); return Artifacts_.GetVector().size() - 1 ; } public: /// Ctor explicit Repository(Clong& CL); void Init(); /// Return the `MapVector(&)` that stores the collected code artifacts. Map_t& getArtifactsMap() { return Artifacts_ ; } /// Add a Clang `Decl*` to the artifacts map. Artifact& Add(const Decl* D, DBIdentifier_t ID = 0); Artifact& Add(const Type* T, DBIdentifier_t ID = 0); // TODO: impl. void Add(const TypeLoc* T); /// True if we have an artifact for this `Decl*`. bool Has(const Decl* D) const; /// Fetch the artifact that corresponds to this `Decl*`. /// Probably O(log2(n)). Artifact& Get(const Decl* D); /// Fetch an artifact by its integral `size_t` key. Artifact& Get(Key_t K); /// Return the NIL artifact. Artifact& GetNilArtifact(); /// Convenience helper that invokes `Has()`. /// fixme: rename as isKnownDeclContext ? /// fixme: ^ we're checking the if it's in the MapVector here, /// fixme: ^ not if it is in the DeclStack. bool HasDeclContext(const DeclContext* DC); /// Convenience helper that invokes `Get()`, so that we do not have to /// dyn_cast<>() here'n'there. Artifact& GetDeclContext(const DeclContext* DC); ///{ Convenience helpers around the DeclContext stack. /// Get the current "top-most" DeclContext artifact that is on the stack. Artifact& CurrentDeclContext(); const Artifact& CurrentDeclContext() const; Artifact& PreviousDeclContext(unsigned int distance = 1); /// Tells whether DC is the current DeclContext at the top of the stack. bool isCurrentDeclContext(const DeclContext* DC) const; /// Push a DC onto the top of the stack. DC is added to the repository /// if it is unknown. /// FIXME: this shall not take an ID arg. / this meth. shall just push /// FIXME: not do some fancy other stuff. Artifact& PushDeclContext(const DeclContext* DC, DBIdentifier_t ID = 0); /// Pop the DC at stack top. Artifact& PopDeclContext(); /// Return the current depth of the DeclContex stack, i.e. the current /// nesting level. size_t GetDeclContextStackDepth() const { return DCStack_.size(); } ///} }; } // plugin ns } // clong ns #endif // _PIMPL_PLUGIN_Repository_HPP
28.088235
92
0.635209
[ "vector" ]
1fc3424b9ef073c26d76030886cea4d060b8fca6
2,515
cpp
C++
libvast/src/system/version_command.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/src/system/version_command.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
libvast/src/system/version_command.cpp
frerich/vast
decac739ea4782ab91a1cee791ecd754b066419f
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/version_command.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/json.hpp" #include "vast/config.hpp" #include "vast/json.hpp" #include "vast/logger.hpp" #if VAST_HAVE_ARROW # include <arrow/util/config.h> #endif #if VAST_HAVE_PCAP # include <pcap/pcap.h> #endif #if VAST_USE_JEMALLOC # include <jemalloc/jemalloc.h> #endif #include <iostream> #include <sstream> namespace vast::system { namespace { json::object retrieve_versions() { json::object result; result["VAST"] = VAST_VERSION; std::ostringstream caf_v; caf_v << CAF_MAJOR_VERSION << '.' << CAF_MINOR_VERSION << '.' << CAF_PATCH_VERSION; result["CAF"] = caf_v.str(); #if VAST_HAVE_ARROW std::ostringstream arrow_v; arrow_v << ARROW_VERSION_MAJOR << '.' << ARROW_VERSION_MINOR << '.' << ARROW_VERSION_PATCH; result["Apache Arrow"] = arrow_v.str(); #else result["Apache Arrow"] = json{}; #endif #if VAST_HAVE_PCAP result["PCAP"] = pcap_lib_version(); #else result["PCAP"] = json{}; #endif #if VAST_USE_JEMALLOC result["jemalloc"] = JEMALLOC_VERSION; #else result["jemalloc"] = json{}; #endif return result; } } // namespace void print_version(const json::object& extra_content) { auto version = retrieve_versions(); std::cout << to_string(combine(extra_content, version)) << std::endl; } caf::message version_command([[maybe_unused]] const invocation& inv, caf::actor_system&) { VAST_TRACE(inv); print_version(); return caf::none; } } // namespace vast::system
29.940476
80
0.55825
[ "object" ]
1fc59e758c05d340e0e1ab5cf7f999fb0e161b95
40,168
cpp
C++
RIT_Library/src/src/utils/IOUtils.cpp
PWrGitHub194238/RIT
74ae41ce8cfdca3f14fc1e9a36840c68dff42b23
[ "Apache-2.0" ]
null
null
null
RIT_Library/src/src/utils/IOUtils.cpp
PWrGitHub194238/RIT
74ae41ce8cfdca3f14fc1e9a36840c68dff42b23
[ "Apache-2.0" ]
1
2016-02-14T18:27:05.000Z
2016-03-15T17:32:11.000Z
BinaryIMST_Library/src/src/utils/IOUtils.cpp
PWrGitHub194238/BinaryIMST
53490c10580fd4ad61c9234b82b3140c5cce5de0
[ "Apache-2.0" ]
null
null
null
/* * IOUtils.cpp * * Created on: 26 lut 2016 * Author: tomasz */ #include "../../include/utils/IOUtils.hpp" #include <boost/interprocess/detail/os_file_functions.hpp> #include <boost/interprocess/exceptions.hpp> #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/streams/bufferstream.hpp> #include <log4cxx/helpers/messagebuffer.h> #include <log4cxx/logger.h> #include <rapidjson/document.h> #include <rapidjson/filereadstream.h> #include <rapidjson/filewritestream.h> #include <rapidjson/rapidjson.h> #include <rapidjson/writer.h> #include <cstddef> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <limits> #include <memory> #include <sstream> #include <string> #include <utility> #include <vector> #include "../../include/bundle/Bundle.hpp" #include "../../include/enums/GraphConstructMode.hpp" #include "../../include/exp/IOExceptions.hpp" #include "../../include/log/bundle/Bundle.hpp" #include "../../include/log/utils/LogStringUtils.hpp" #include "../../include/log/utils/LogUtils.hpp" #include "../../include/structures/EdgeIF.hpp" #include "../../include/structures/GraphEdgeCostsInclude.hpp" #include "../../include/structures/GraphInclude.hpp" #include "../../include/structures/VertexInclude.hpp" #include "../../include/typedefs/primitive.hpp" #include "../../include/utils/BundleUtils.hpp" #include "../../include/utils/enums/GraphVizEngine.hpp" #include "../../include/utils/enums/InputFormat.hpp" #include "../../include/utils/enums/InputMode.hpp" #include "../../include/utils/enums/OutputFormat.hpp" #include "../../include/utils/GraphVizUtils.hpp" #include "../../include/utils/StringUtils.hpp" #include "../../include/exp/IOExceptions.hpp" class EdgeSetIF; class VertexSetIF; const static log4cxx::LoggerPtr logger( log4cxx::Logger::getLogger("utils.IOUtils")); const unsigned short IOUtils::impl::MAX_CHARS_IN_LINE { 2 * (std::numeric_limits<EdgeIdx>::digits10 + 1) + (std::numeric_limits<EdgeCost>::digits10 + 1) + 3 }; const long IOUtils::impl::MAX_STREAM_SIZE { std::numeric_limits<std::streamsize>::max() }; const short IOUtils::impl::BUFFER_SIZE { 4096 }; const char IOUtils::impl::GR::COMMENT_LINE { 'c' }; constexpr unsigned short IOUtils::impl::GR::COMMENT_LINE_NUMERIC { IOUtils::impl::GR::COMMENT_LINE }; const char* IOUtils::impl::GR::COMMENT_LINE_PATTERN { "%*[^\n]\n" }; const unsigned short IOUtils::impl::GR::COMMENT_LINE_PATTERN_ARGS { 0 }; extern const char IOUtils::impl::GR::PROBLEM_DEF_LINE { 'p' }; extern const unsigned short IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC { IOUtils::impl::GR::PROBLEM_DEF_LINE }; extern const std::unique_ptr<char[]> IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN { StringUtils::parseStringFormatSpecifiers( " mst %VertexCount% %EdgeCount%") }; extern const unsigned short IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN_ARGS { 2 }; extern const char IOUtils::impl::GR::ARC_DEF_LINE { 'a' }; extern const unsigned short IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC { IOUtils::impl::GR::ARC_DEF_LINE }; extern const std::unique_ptr<char[]> IOUtils::impl::GR::ARC_DEF_LINE_PATTERN { StringUtils::parseStringFormatSpecifiers( " %VertexIdx% %VertexIdx% %IOEdgeCost%") }; const unsigned short IOUtils::impl::GR::ARC_DEF_LINE_PATTERN_ARGS { 3 }; const char* IOUtils::impl::VA::VERTEX_LIST_KEY { "vl" }; const char* IOUtils::impl::VA::EDGE_LIST_KEY { "el" }; const char* IOUtils::impl::VA::EDGE_VERTEX_A_KEY { "vertexA" }; const char* IOUtils::impl::VA::EDGE_VERTEX_B_KEY { "vertexB" }; const char* IOUtils::impl::VA::EDGE_COST_KEY { "weight" }; const char* IOUtils::impl::DOT::GRAPH_DEF { "graph" }; const char* IOUtils::impl::DOT::DIR { "rankdir" }; const char* IOUtils::impl::DOT::LABEL { "label" }; const char* IOUtils::impl::DOT::WEIGHT { "weight" }; const char* IOUtils::impl::DOT::LEN { "len" }; const char* IOUtils::impl::DOT::EDGE_UNDIR { "--" }; const char* IOUtils::impl::DOT::ENDLN { ";" }; GraphIF * InputUtils::readGraph(char const * filename, InputFormat inputFormat, InputMode inputMode) throw (IOExceptions::FileNotFountException) { switch (inputMode) { case InputMode::RAM: return InputUtils::impl::RAM::readGraph(filename, inputFormat); default: return InputUtils::impl::HDD::readGraph(filename, inputFormat); } return nullptr; } GraphEdgeCostsIF * InputUtils::readCosts(char const * filename, InputFormat inputFormat, InputMode inputMode, std::string scenarioName) throw (IOExceptions::FileNotFountException) { switch (inputMode) { case InputMode::RAM: return InputUtils::impl::RAM::readCosts(filename, inputFormat, scenarioName); default: return InputUtils::impl::HDD::readCosts(filename, inputFormat, scenarioName); } return nullptr; } GraphEdgeCostsIF * InputUtils::readCosts(char const * filename, InputFormat inputFormat, InputMode inputMode) throw (IOExceptions::FileNotFountException) { return InputUtils::readCosts(filename, inputFormat, inputMode, BundleUtils::getString(AppBundleKey::DEFAULT_SCENARIO_NAME)); } VertexIdx InputUtils::impl::VA::getVertexIdxFromValue( const rapidjson::Value& vertexIdx) { if (vertexIdx.IsString()) { return (VertexIdx) std::atoll(vertexIdx.GetString()); } else { return vertexIdx.GetDouble(); } } EdgeCost InputUtils::impl::VA::getEdgeCostFromValue( const rapidjson::Value& edgeCost) { if (edgeCost.IsString()) { return std::atoll(edgeCost.GetString()); } else { return edgeCost.GetDouble(); } } GraphIF * InputUtils::impl::RAM::readGraph(char const * const filename, InputFormat inputFormat) throw (IOExceptions::FileNotFountException) { switch (inputFormat) { case InputFormat::VA: return InputUtils::impl::RAM::VA::readGraph(filename); default: return InputUtils::impl::RAM::GR::readGraph(filename); } } GraphEdgeCostsIF * InputUtils::impl::RAM::readCosts(char const * const filename, InputFormat inputFormat, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { switch (inputFormat) { case InputFormat::VA: return InputUtils::impl::RAM::VA::readCosts(filename, scenarioName); default: return InputUtils::impl::RAM::GR::readCosts(filename, scenarioName); } } GraphIF * InputUtils::impl::RAM::GR::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { }; std::size_t fileSize { }; char buffer[IOUtils::impl::BUFFER_SIZE] { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); while (!input_stream.eof()) { switch (input_stream.get()) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; input_stream.ignore(IOUtils::impl::MAX_STREAM_SIZE, '\n'); break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); graph = InputUtils::impl::RAM::GR::createGraph(buffer); idxEdgeCounter = 0; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); InputUtils::impl::RAM::GR::addEdge(idxEdgeCounter, buffer, graph); idxEdgeCounter += 1; break; default: WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING) ; break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); return graph; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } } GraphEdgeCostsIF * InputUtils::impl::RAM::GR::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; EdgeCount numberOfEdgeCosts { }; std::size_t fileSize { }; char buffer[IOUtils::impl::BUFFER_SIZE] { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); while (!input_stream.eof()) { switch (input_stream.get()) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; input_stream.ignore(IOUtils::impl::MAX_STREAM_SIZE, '\n'); break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); numberOfEdgeCosts = InputUtils::impl::RAM::GR::getNumberOfEdgeCosts(buffer); graphCosts = new GraphEdgeCostsImpl { numberOfEdgeCosts, scenarioName, false }; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); graphCosts->push_back( InputUtils::impl::RAM::GR::getCost(buffer)); break; default: WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING) ; break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); return graphCosts; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } } GraphIF * InputUtils::impl::RAM::GR::createGraph(char * const buffer) throw (IOExceptions::InvalidProblemRead) { VertexCount vCount { }; EdgeCount eCount { }; if (sscanf(buffer, IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN.get(), &vCount, &eCount) != IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_PROBLEM_LINE_READ); throw IOExceptions::InvalidProblemRead(); } INFO(logger, LogBundleKey::IOU_MST_PROBLEM_READ, vCount, eCount); return new GraphImpl { vCount, eCount, GraphConstructMode::AUTO_CONSTRUCT_VERTEX }; } EdgeCount InputUtils::impl::RAM::GR::getNumberOfEdgeCosts(char * const buffer) throw (IOExceptions::InvalidProblemRead) { VertexCount vCount { }; EdgeCount eCount { }; if (sscanf(buffer, IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN.get(), &vCount, &eCount) != IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_PROBLEM_LINE_READ); throw IOExceptions::InvalidProblemRead(); } INFO(logger, LogBundleKey::IOU_MST_PROBLEM_READ_GET_EDGES, vCount, eCount); return eCount; } void InputUtils::impl::RAM::GR::addEdge(EdgeIdx const edgeIdx, char * const buffer, GraphIF * const graph) throw (IOExceptions::InvalidArcRead) { VertexIdx vertexU { }; VertexIdx vertexV { }; EdgeCost eCost { }; if (sscanf(buffer, IOUtils::impl::GR::ARC_DEF_LINE_PATTERN.get(), &vertexU, &vertexV, &eCost) != IOUtils::impl::GR::ARC_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_ARC_LINE_READ); throw IOExceptions::InvalidArcRead(); } INFO(logger, LogBundleKey::IOU_ARC_DEF_READ, eCost, vertexU, vertexV); graph->addEdge(edgeIdx, vertexU, vertexV, eCost); } EdgeCost InputUtils::impl::RAM::GR::getCost(char * const buffer) throw (IOExceptions::InvalidArcRead) { VertexIdx vertexU { }; VertexIdx vertexV { }; EdgeCost eCost { }; if (sscanf(buffer, IOUtils::impl::GR::ARC_DEF_LINE_PATTERN.get(), &vertexU, &vertexV, &eCost) != IOUtils::impl::GR::ARC_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_ARC_LINE_READ); throw IOExceptions::InvalidArcRead(); } INFO(logger, LogBundleKey::IOU_ARC_COST_READ, vertexU, vertexV, eCost); return eCost; } GraphIF * InputUtils::impl::RAM::VA::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { }; std::size_t fileSize { }; char* buffer { }; rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator vertexList { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); jsonDoc.Parse(input_stream.buffer().first); endValue = jsonDoc.MemberEnd(); vertexList = jsonDoc.FindMember(IOUtils::impl::VA::VERTEX_LIST_KEY); if (vertexList != endValue) { edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graph = InputUtils::impl::RAM::VA::createGraph( vertexList->value, edgeList->value.MemberCount()); idxEdgeCounter = 0; it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { InputUtils::impl::RAM::VA::addEdge(idxEdgeCounter, itBegin, graph); idxEdgeCounter += 1; } } } INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); return graph; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } } GraphEdgeCostsIF * InputUtils::impl::RAM::VA::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; std::size_t fileSize { }; char* buffer { }; rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); jsonDoc.Parse(input_stream.buffer().first); edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graphCosts = new GraphEdgeCostsImpl { (EdgeCount) edgeList->value.MemberCount(), scenarioName, false }; it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { graphCosts->push_back( InputUtils::impl::RAM::VA::getCost(itBegin)); } } INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); return graphCosts; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } } GraphIF * InputUtils::impl::RAM::VA::createGraph(rapidjson::Value & vertexList, rapidjson::SizeType const numberOfEdges) throw (IOExceptions::InvalidProblemRead) { return InputUtils::impl::HDD::VA::createGraph(vertexList, numberOfEdges); } void InputUtils::impl::RAM::VA::addEdge(EdgeIdx const edgeIdx, rapidjson::Value::ConstMemberIterator& edge, GraphIF * const graph) throw (IOExceptions::InvalidArcRead) { return InputUtils::impl::HDD::VA::addEdge(edgeIdx, edge, graph); } EdgeCost InputUtils::impl::RAM::VA::getCost( rapidjson::Value::ConstMemberIterator& edge) throw (IOExceptions::InvalidArcRead) { return InputUtils::impl::HDD::VA::getCost(edge); } GraphIF * InputUtils::impl::HDD::readGraph(char const * const filename, InputFormat inputFormat) throw (IOExceptions::FileNotFountException) { switch (inputFormat) { case InputFormat::VA: return InputUtils::impl::HDD::VA::readGraph(filename); default: return InputUtils::impl::HDD::GR::readGraph(filename); } } GraphEdgeCostsIF * InputUtils::impl::HDD::readCosts(char const * const filename, InputFormat inputFormat, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { switch (inputFormat) { case InputFormat::VA: return InputUtils::impl::HDD::VA::readCosts(filename, scenarioName); default: return InputUtils::impl::HDD::GR::readCosts(filename, scenarioName); } } GraphIF * InputUtils::impl::HDD::VA::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { 0 }; FILE * dataFile = std::fopen(filename, "r"); rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator vertexList { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; char readBuffer[IOUtils::impl::BUFFER_SIZE] { }; if (dataFile == NULL) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, filename); throw IOExceptions::FileNotFountException(filename); } else { TRACE(logger, LogBundleKey::IOU_START_READ_FILE_DATA, filename); rapidjson::FileReadStream is(dataFile, readBuffer, sizeof(readBuffer)); jsonDoc.ParseStream(is); endValue = jsonDoc.MemberEnd(); vertexList = jsonDoc.FindMember(IOUtils::impl::VA::VERTEX_LIST_KEY); if (vertexList != endValue) { edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graph = InputUtils::impl::HDD::VA::createGraph( vertexList->value, edgeList->value.MemberCount()); it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { InputUtils::impl::HDD::VA::addEdge(idxEdgeCounter, itBegin, graph); idxEdgeCounter += 1; } } } fclose(dataFile); INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); } return graph; } GraphEdgeCostsIF * InputUtils::impl::HDD::VA::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; FILE * dataFile = std::fopen(filename, "r"); rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator vertexList { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; char readBuffer[IOUtils::impl::BUFFER_SIZE] { }; if (dataFile == NULL) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, filename); throw IOExceptions::FileNotFountException(filename); } else { TRACE(logger, LogBundleKey::IOU_START_READ_FILE_DATA, filename); rapidjson::FileReadStream is(dataFile, readBuffer, sizeof(readBuffer)); jsonDoc.ParseStream(is); endValue = jsonDoc.MemberEnd(); edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graphCosts = new GraphEdgeCostsImpl { (EdgeCount) edgeList->value.MemberCount(), scenarioName, false }; it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { graphCosts->push_back( InputUtils::impl::HDD::VA::getCost(itBegin)); } } fclose(dataFile); INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); } return graphCosts; } GraphIF * InputUtils::impl::HDD::VA::createGraph(rapidjson::Value & vertexList, rapidjson::SizeType const numberOfEdges) throw (IOExceptions::InvalidProblemRead) { GraphIF* graph = new GraphImpl { vertexList.MemberCount(), numberOfEdges, GraphConstructMode::RESERVE_SPACE_ONLY }; rapidjson::Value::ConstMemberIterator itEnd = vertexList.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = vertexList.MemberBegin(); itBegin != itEnd; ++itBegin) { graph->addVertex( new VertexImpl { (VertexIdx) std::atoll( itBegin->name.GetString()) }); } return graph; } void InputUtils::impl::HDD::VA::addEdge(EdgeIdx const edgeIdx, rapidjson::Value::ConstMemberIterator& edge, GraphIF * const graph) throw (IOExceptions::InvalidArcRead) { const rapidjson::Value& endValue = edge->value.MemberEnd()->value; const rapidjson::Value& vertexU = edge->value.FindMember( IOUtils::impl::VA::EDGE_VERTEX_A_KEY)->value; const rapidjson::Value& vertexV = edge->value.FindMember( IOUtils::impl::VA::EDGE_VERTEX_B_KEY)->value; const rapidjson::Value& edgeCost = edge->value.FindMember( IOUtils::impl::VA::EDGE_COST_KEY)->value; if (vertexU == endValue || vertexV == endValue || edgeCost == endValue) { throw IOExceptions::InvalidArcRead(); } else { INFO(logger, LogBundleKey::IOU_ARC_DEF_READ, InputUtils::impl::VA::getVertexIdxFromValue(vertexU), InputUtils::impl::VA::getVertexIdxFromValue(vertexV), InputUtils::impl::VA::getEdgeCostFromValue(edgeCost)); graph->addEdge(edgeIdx, InputUtils::impl::VA::getVertexIdxFromValue(vertexU), InputUtils::impl::VA::getVertexIdxFromValue(vertexV), InputUtils::impl::VA::getEdgeCostFromValue(edgeCost)); } } EdgeCost InputUtils::impl::HDD::VA::getCost( rapidjson::Value::ConstMemberIterator& edge) throw (IOExceptions::InvalidArcRead) { const rapidjson::Value& endValue = edge->value.MemberEnd()->value; const rapidjson::Value& vertexU = edge->value.FindMember( IOUtils::impl::VA::EDGE_VERTEX_A_KEY)->value; const rapidjson::Value& vertexV = edge->value.FindMember( IOUtils::impl::VA::EDGE_VERTEX_B_KEY)->value; const rapidjson::Value& edgeCost = edge->value.FindMember( IOUtils::impl::VA::EDGE_COST_KEY)->value; if (vertexU == endValue || vertexV == endValue || edgeCost == endValue) { throw IOExceptions::InvalidArcRead(); } else { INFO(logger, LogBundleKey::IOU_ARC_COST_READ, InputUtils::impl::VA::getEdgeCostFromValue(edgeCost), InputUtils::impl::VA::getVertexIdxFromValue(vertexU), InputUtils::impl::VA::getVertexIdxFromValue(vertexV)); } return InputUtils::impl::VA::getEdgeCostFromValue(edgeCost); } GraphIF * InputUtils::impl::HDD::GR::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { }; FILE * dataFile = std::fopen(filename, "r"); if (dataFile == NULL) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, filename); throw IOExceptions::FileNotFountException(filename); } else { TRACE(logger, LogBundleKey::IOU_START_READ_FILE_DATA, filename); while (!feof(dataFile)) { switch (fgetc(dataFile)) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; if (fscanf(dataFile, IOUtils::impl::GR::COMMENT_LINE_PATTERN) != IOUtils::impl::GR::COMMENT_LINE_PATTERN_ARGS) { WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING); } break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: graph = InputUtils::impl::HDD::GR::createGraph(dataFile); idxEdgeCounter = 0; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: InputUtils::impl::HDD::GR::addEdge(idxEdgeCounter, dataFile, graph); idxEdgeCounter += 1; break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); fclose(dataFile); } return graph; } GraphEdgeCostsIF * InputUtils::impl::HDD::GR::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; EdgeCount numberOfEdgeCosts { }; FILE * dataFile = std::fopen(filename, "r"); if (dataFile == NULL) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, filename); throw IOExceptions::FileNotFountException(filename); } else { TRACE(logger, LogBundleKey::IOU_START_READ_FILE_DATA, filename); while (!feof(dataFile)) { switch (fgetc(dataFile)) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; if (fscanf(dataFile, IOUtils::impl::GR::COMMENT_LINE_PATTERN) != IOUtils::impl::GR::COMMENT_LINE_PATTERN_ARGS) { WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING); } break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: numberOfEdgeCosts = InputUtils::impl::HDD::GR::getNumberOfEdgeCosts( dataFile); graphCosts = new GraphEdgeCostsImpl { numberOfEdgeCosts, scenarioName, false }; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: graphCosts->push_back( InputUtils::impl::HDD::GR::getCost(dataFile)); break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); fclose(dataFile); } return graphCosts; } GraphIF * InputUtils::impl::HDD::GR::createGraph(FILE * const dataFile) throw (IOExceptions::InvalidProblemRead) { VertexCount vCount { }; EdgeCount eCount { }; if (fscanf(dataFile, IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN.get(), &vCount, &eCount) != IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_PROBLEM_LINE_READ); throw IOExceptions::InvalidProblemRead(); } INFO(logger, LogBundleKey::IOU_MST_PROBLEM_READ, vCount, eCount); return new GraphImpl { vCount, eCount, GraphConstructMode::AUTO_CONSTRUCT_VERTEX }; } EdgeCount InputUtils::impl::HDD::GR::getNumberOfEdgeCosts(FILE * const dataFile) throw (IOExceptions::InvalidProblemRead) { VertexCount vCount { }; EdgeCount eCount { }; if (fscanf(dataFile, IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN.get(), &vCount, &eCount) != IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_PROBLEM_LINE_READ); throw IOExceptions::InvalidProblemRead(); } INFO(logger, LogBundleKey::IOU_MST_PROBLEM_READ_GET_EDGES, vCount, eCount); return eCount; } void InputUtils::impl::HDD::GR::addEdge(EdgeIdx const edgeIdx, FILE * const dataFile, GraphIF * const graph) throw (IOExceptions::InvalidArcRead) { VertexIdx vertexU { }; VertexIdx vertexV { }; EdgeCost eCost { }; if (fscanf(dataFile, IOUtils::impl::GR::ARC_DEF_LINE_PATTERN.get(), &vertexU, &vertexV, &eCost) != IOUtils::impl::GR::ARC_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_ARC_LINE_READ); throw IOExceptions::InvalidArcRead(); } INFO(logger, LogBundleKey::IOU_ARC_DEF_READ, vertexU, vertexV, eCost); graph->addEdge(edgeIdx, vertexU, vertexV, eCost); } EdgeCost InputUtils::impl::HDD::GR::getCost(FILE * const dataFile) throw (IOExceptions::InvalidArcRead) { VertexIdx vertexU { }; VertexIdx vertexV { }; EdgeCost eCost { }; if (fscanf(dataFile, IOUtils::impl::GR::ARC_DEF_LINE_PATTERN.get(), &vertexU, &vertexV, &eCost) != IOUtils::impl::GR::ARC_DEF_LINE_PATTERN_ARGS) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_ARC_LINE_READ); throw IOExceptions::InvalidArcRead(); } INFO(logger, LogBundleKey::IOU_ARC_COST_READ, eCost, vertexU, vertexV); return eCost; } void OutputUtils::exportGraph(GraphIF* const graph, char const * exportPath, OutputFormat const outputFormat, GraphVizEngine const layoutEngine, GraphVizUtils::GraphDimmention graphMaxWidth, GraphVizUtils::GraphDimmention graphMaxHeight) throw (IOExceptions::InvalidProblemWrite, IOExceptions::InvalidArcWrite) { switch (outputFormat) { case OutputFormat::GR: //TODO break; case OutputFormat::VA: OutputUtils::impl::VA::exportGraph(graph, exportPath, layoutEngine, graphMaxWidth, graphMaxHeight); break; case OutputFormat::DOT: // TODO break; default: break; } } void OutputUtils::exportGraph(GraphIF* const graph, char const * exportPath, OutputFormat const outputFormat) throw (IOExceptions::InvalidProblemWrite, IOExceptions::InvalidArcWrite) { switch (outputFormat) { case OutputFormat::GR: OutputUtils::impl::GR::exportGraph(graph, exportPath); break; case OutputFormat::VA: OutputUtils::impl::VA::exportGraph(graph, exportPath); break; case OutputFormat::DOT: OutputUtils::impl::DOT::exportGraph(graph, exportPath); break; default: break; } } void OutputUtils::impl::GR::exportGraph(GraphIF* const graph, char const * exportPath) throw (IOExceptions::InvalidProblemWrite, IOExceptions::InvalidArcWrite) { std::ofstream exportFile { }; char buffer[IOUtils::impl::MAX_CHARS_IN_LINE] { }; VertexCount vCount { }; EdgeCount eCount { }; EdgeIF * edge { }; exportFile.open(exportPath); if (!exportFile.is_open()) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, exportPath); } else { TRACE(logger, LogBundleKey::IOU_START_WRITE_FILE_DATA, exportPath); exportFile << IOUtils::impl::GR::COMMENT_LINE << " " << "9th DIMACS Implementation Challenge: Minimum Spanning Tree" << std::endl; exportFile << IOUtils::impl::GR::COMMENT_LINE << " " << "http://www.dis.uniroma1.it/~challenge9" << std::endl; exportFile << IOUtils::impl::GR::COMMENT_LINE << " " << exportPath << std::endl; exportFile << IOUtils::impl::GR::COMMENT_LINE << std::endl; vCount = graph->getNumberOfVertices(); eCount = graph->getNumberOfEdges(); if (sprintf(buffer, IOUtils::impl::GR::PROBLEM_DEF_LINE_PATTERN.get(), vCount, eCount) < 0) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_PROBLEM_LINE_WRITE); throw IOExceptions::InvalidProblemWrite(); } exportFile << IOUtils::impl::GR::PROBLEM_DEF_LINE << buffer << std::endl; INFO(logger, LogBundleKey::IOU_MST_PROBLEM_WRITE, vCount, eCount, exportPath); exportFile << IOUtils::impl::GR::COMMENT_LINE << " " << "graph contains " << vCount << " nodes and " << eCount << " arcs" << std::endl; exportFile << IOUtils::impl::GR::COMMENT_LINE << std::endl; graph->beginEdge(); while (graph->hasNextEdge()) { edge = graph->nextEdge(); if (sprintf(buffer, IOUtils::impl::GR::ARC_DEF_LINE_PATTERN.get(), edge->getSourceVertex()->getVertexIdx(), edge->getTargetVertex()->getVertexIdx(), edge->getEdgeCost()) < 0) { FATAL_NOARG(logger, LogBundleKey::IOU_INVALID_ARC_LINE_WRITE); throw IOExceptions::InvalidArcRead(); } exportFile << IOUtils::impl::GR::ARC_DEF_LINE << buffer << std::endl; INFO(logger, LogBundleKey::IOU_ARC_DEF_WRITE, LogStringUtils::edgeVisualization(edge, "\t").c_str()); } exportFile.close(); INFO(logger, LogBundleKey::IOU_END_OF_WRITE, exportPath, LogStringUtils::graphDescription(graph, "\t").c_str()); } } void OutputUtils::impl::VA::exportGraph(GraphIF* const graph, char const * exportPath, GraphVizEngine const layoutEngine, GraphVizUtils::GraphDimmention graphMaxWidth, GraphVizUtils::GraphDimmention graphMaxHeight) { FILE* exportFile = fopen(exportPath, "w"); char buffer[IOUtils::impl::MAX_CHARS_IN_LINE] { }; rapidjson::Document jsonDoc { }; rapidjson::Document vertexJsonDoc { }; rapidjson::Document edgeJsonDoc { }; rapidjson::Document::AllocatorType& allocator = jsonDoc.GetAllocator(); EdgeIF* edge { }; EdgeCount edgeCounter { 0 }; VertexIF* vertex { }; if (exportFile == nullptr) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, exportPath); } else { rapidjson::FileWriteStream os(exportFile, buffer, sizeof(buffer)); rapidjson::Writer<rapidjson::FileWriteStream> writer(os); jsonDoc.SetObject(); TRACE(logger, LogBundleKey::IOU_START_WRITE_FILE_DATA, exportPath); jsonDoc.AddMember("vl", OutputUtils::impl::VA::getVertexSetJson(allocator, graph, GraphVizUtils::getVerticesCoordinates(graph, layoutEngine, graphMaxWidth, graphMaxHeight)), allocator); jsonDoc.AddMember("el", OutputUtils::impl::VA::getEdgeSetJson(allocator, graph), allocator); INFO(logger, LogBundleKey::IOU_END_OF_WRITE, exportPath, LogStringUtils::graphDescription(graph, "\t").c_str()); jsonDoc.Accept(writer); fclose(exportFile); } } rapidjson::Document OutputUtils::impl::VA::getVertexSetJson( rapidjson::Document::AllocatorType& allocator, GraphIF * const graph, GraphVizUtils::VerticesCoordinates verticesCoordinates) { rapidjson::Document vertexJsonDoc { }; VertexIF * vertex { }; vertexJsonDoc.SetObject(); graph->beginVertex(); vertexJsonDoc.SetObject(); while (graph->hasNextVertex()) { vertex = graph->nextVertex(); rapidjson::Value key(std::to_string(vertex->getVertexIdx()).c_str(), allocator); vertexJsonDoc.AddMember(key, OutputUtils::impl::VA::getVertexJson(vertexJsonDoc, allocator, vertex, verticesCoordinates.at(vertex->getVertexIdx())), allocator); INFO(logger, LogBundleKey::IOU_VERTEX_DEF_WRITE, LogStringUtils::vertexVisualization(vertex, "\t").c_str()); } return vertexJsonDoc; } rapidjson::Document OutputUtils::impl::VA::getVertexJson( rapidjson::Document& vertexJsonDoc, rapidjson::Document::AllocatorType& allocator, VertexIF * const vertex, GraphVizUtils::VertexCoordinates vertexCoordinates) { rapidjson::Document jsonDoc { }; rapidjson::Value text(std::to_string(vertex->getVertexIdx()).c_str(), allocator); jsonDoc.SetObject(); jsonDoc.AddMember("cx", vertexCoordinates.first, allocator); jsonDoc.AddMember("cy", vertexCoordinates.second, allocator); jsonDoc.AddMember("text", text, allocator); jsonDoc.AddMember("state", "default", allocator); return jsonDoc; } void OutputUtils::impl::VA::exportGraph(GraphIF* const graph, char const * exportPath) { FILE* exportFile = fopen(exportPath, "w"); char buffer[IOUtils::impl::MAX_CHARS_IN_LINE] { }; rapidjson::Document jsonDoc { }; rapidjson::Document vertexJsonDoc { }; rapidjson::Document edgeJsonDoc { }; rapidjson::Document::AllocatorType& allocator = jsonDoc.GetAllocator(); EdgeIF* edge { }; EdgeCount edgeCounter { 0 }; VertexIF* vertex { }; if (exportFile == nullptr) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, exportPath); } else { rapidjson::FileWriteStream os(exportFile, buffer, sizeof(buffer)); rapidjson::Writer<rapidjson::FileWriteStream> writer(os); jsonDoc.SetObject(); TRACE(logger, LogBundleKey::IOU_START_WRITE_FILE_DATA, exportPath); jsonDoc.AddMember("vl", OutputUtils::impl::VA::getVertexSetJson(allocator, graph), allocator); jsonDoc.AddMember("el", OutputUtils::impl::VA::getEdgeSetJson(allocator, graph), allocator); INFO(logger, LogBundleKey::IOU_END_OF_WRITE, exportPath, LogStringUtils::graphDescription(graph, "\t").c_str()); jsonDoc.Accept(writer); fclose(exportFile); } } rapidjson::Document OutputUtils::impl::VA::getVertexSetJson( rapidjson::Document::AllocatorType& allocator, GraphIF * const graph) { rapidjson::Document vertexJsonDoc { }; VertexIF * vertex { }; vertexJsonDoc.SetObject(); graph->beginVertex(); vertexJsonDoc.SetObject(); while (graph->hasNextVertex()) { vertex = graph->nextVertex(); rapidjson::Value key(std::to_string(vertex->getVertexIdx()).c_str(), allocator); vertexJsonDoc.AddMember(key, OutputUtils::impl::VA::getVertexJson(vertexJsonDoc, allocator, vertex), allocator); INFO(logger, LogBundleKey::IOU_VERTEX_DEF_WRITE, LogStringUtils::vertexVisualization(vertex, "\t").c_str()); } return vertexJsonDoc; } rapidjson::Document OutputUtils::impl::VA::getEdgeSetJson( rapidjson::Document::AllocatorType& allocator, GraphIF * const graph) { rapidjson::Document edgeJsonDoc { }; EdgeIF * edge { }; EdgeCount edgeCounter { 0 }; edgeJsonDoc.SetObject(); graph->beginEdge(); edgeJsonDoc.SetObject(); while (graph->hasNextEdge()) { edge = graph->nextEdge(); rapidjson::Value key(std::to_string(edgeCounter++).c_str(), allocator); edgeJsonDoc.AddMember(key, OutputUtils::impl::VA::getEdgeJson(edgeJsonDoc, allocator, edge), allocator); INFO(logger, LogBundleKey::IOU_ARC_DEF_WRITE, LogStringUtils::edgeVisualization(edge, "\t").c_str()); } return edgeJsonDoc; } rapidjson::Document OutputUtils::impl::VA::getVertexJson( rapidjson::Document& vertexJsonDoc, rapidjson::Document::AllocatorType& allocator, VertexIF * const vertex) { rapidjson::Document jsonDoc { }; rapidjson::Value text(std::to_string(vertex->getVertexIdx()).c_str(), allocator); jsonDoc.SetObject(); jsonDoc.AddMember("cx", 0, allocator); jsonDoc.AddMember("cy", 0, allocator); jsonDoc.AddMember("text", text, allocator); jsonDoc.AddMember("state", "default", allocator); return jsonDoc; } rapidjson::Document OutputUtils::impl::VA::getEdgeJson( rapidjson::Document& vertexJsonDoc, rapidjson::Document::AllocatorType& allocator, EdgeIF * const edge) { rapidjson::Document jsonDoc { }; jsonDoc.SetObject(); jsonDoc.AddMember("vertexA", edge->getSourceVertex()->getVertexIdx(), allocator); jsonDoc.AddMember("vertexB", edge->getTargetVertex()->getVertexIdx(), allocator); jsonDoc.AddMember("type", 0, allocator); jsonDoc.AddMember("weight", edge->getEdgeCost(), allocator); jsonDoc.AddMember("state", "default", allocator); jsonDoc.AddMember("displayWeight", true, allocator); jsonDoc.AddMember("animateHighlighed", false, allocator); return jsonDoc; } void OutputUtils::impl::DOT::exportGraph(GraphIF* const graph, char const * exportPath) { std::ofstream exportFile { }; exportFile.open(exportPath); if (!exportFile.is_open()) { ERROR(logger, LogBundleKey::IOU_CANNOT_OPEN_FILE, exportPath); } else { TRACE(logger, LogBundleKey::IOU_START_WRITE_FILE_DATA, exportPath); OutputUtils::impl::DOT::exportGraphToStream(graph, exportFile); exportFile.close(); INFO(logger, LogBundleKey::IOU_END_OF_WRITE, exportPath, LogStringUtils::graphDescription(graph, "\t").c_str()); } } std::string OutputUtils::impl::DOT::exportGraph(GraphIF* const graph) { std::ostringstream oss { }; TRACE_NOARG(logger, LogBundleKey::IOU_START_STREAM_WRITE_DATA); OutputUtils::impl::DOT::exportGraphToStream(graph, oss); TRACE_NOARG(logger, LogBundleKey::IOU_END_STREAM_WRITE); return oss.str(); } void OutputUtils::impl::DOT::exportGraphToStream(GraphIF* const graph, std::ostream& stream) { VertexIF * vertex { }; EdgeIF * edge { }; EdgeCost edgeCost { }; EdgeCost totalCost { graph->getTotalEdgeCost() }; stream << IOUtils::impl::DOT::GRAPH_DEF << " G {" << std::endl; stream << "\t" << IOUtils::impl::DOT::DIR << "\t=\t" << "LR" << IOUtils::impl::DOT::ENDLN << std::endl; graph->beginVertex(); while (graph->hasNextVertex()) { vertex = graph->nextVertex(); stream << "\t" << vertex->getVertexIdx() << "\t[" << IOUtils::impl::DOT::LABEL << "=\"" << vertex->getVertexIdx() << "\"]" << IOUtils::impl::DOT::ENDLN << std::endl; INFO(logger, LogBundleKey::IOU_VERTEX_DEF_WRITE, LogStringUtils::vertexVisualization(vertex, "\t").c_str()); } graph->beginEdge(); while (graph->hasNextEdge()) { edge = graph->nextEdge(); edgeCost = edge->getEdgeCost(); stream << "\t" << edge->getSourceVertex()->getVertexIdx() << "\t" << IOUtils::impl::DOT::EDGE_UNDIR << "\t" << edge->getTargetVertex()->getVertexIdx() << "\t[" << IOUtils::impl::DOT::LABEL << "=\"" << edgeCost << "\",\t" << IOUtils::impl::DOT::WEIGHT << "=" << 1 - (double) edgeCost / totalCost << ",\t" << IOUtils::impl::DOT::LEN << "=" << edgeCost << "]" << IOUtils::impl::DOT::ENDLN << std::endl; INFO(logger, LogBundleKey::IOU_ARC_DEF_WRITE, LogStringUtils::edgeVisualization(edge, "\t").c_str()); } stream << "}" << std::flush; }
34.657463
83
0.724856
[ "vector" ]
1fc5bd0568b7e60b1d5dc8e3be61dca706d522fc
9,285
cxx
C++
smtk/bridge/discrete/legacycmb/SimBuilderMesh/vtkCMBMeshServer.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/bridge/discrete/legacycmb/SimBuilderMesh/vtkCMBMeshServer.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/bridge/discrete/legacycmb/SimBuilderMesh/vtkCMBMeshServer.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "vtkCMBMeshServer.h" #include <vtkCallbackCommand.h> #include <vtkDiscreteModel.h> #include "vtkCMBModelEdgeMeshServer.h" #include "vtkCMBModelFaceMeshServer.h" #include <vtkDiscreteModelGeometricEntity.h> #include "vtkCMBModelVertexMesh.h" #include <vtkIdList.h> #include <vtkMath.h> #include <vtkMergeEventData.h> #include <vtkModel.h> #include <vtkModelEdge.h> #include <vtkModelEntity.h> #include <vtkModelFace.h> #include <vtkModelGeometricEntity.h> #include <vtkModelItemIterator.h> #include <vtkModelVertex.h> #include <vtkObjectFactory.h> #include <vtkPolyData.h> #include <vtkSmartPointer.h> #include <vtkSplitEventData.h> #include <map> vtkStandardNewMacro(vtkCMBMeshServer); class vtkCMBMeshServerInternals { public: std::map<vtkModelEdge*, vtkSmartPointer<vtkCMBModelEdgeMeshServer> > ModelEdges; std::map<vtkModelFace*, vtkSmartPointer<vtkCMBModelFaceMeshServer> > ModelFaces; }; //---------------------------------------------------------------------------- vtkCMBMeshServer::vtkCMBMeshServer() { this->Internal = new vtkCMBMeshServerInternals; } //---------------------------------------------------------------------------- vtkCMBMeshServer::~vtkCMBMeshServer() { if(this->CallbackCommand) { if(this->Model) { this->Model->RemoveObserver(this->CallbackCommand); } this->CallbackCommand = NULL; } if(this->Internal) { delete this->Internal; this->Internal = NULL; } } //---------------------------------------------------------------------------- void vtkCMBMeshServer::Initialize(vtkModel* model) { if(model == NULL) { vtkErrorMacro("Passed in NULL model."); return; } if(model->GetModelDimension() != 2) { // do nothing if it's not a 2d model return; } if(this->Model != model) { this->Reset(); this->Model = model; } // register model modification events that we want // this may not be correct yet this->CallbackCommand = vtkSmartPointer<vtkCallbackCommand>::New(); this->CallbackCommand->SetCallback(vtkCMBMeshServer::ModelGeometricEntityChanged); this->CallbackCommand->SetClientData(static_cast<void*>(this)); model->AddObserver(ModelGeometricEntityBoundaryModified, this->CallbackCommand); model->AddObserver(ModelGeometricEntitiesAboutToMerge, this->CallbackCommand); model->AddObserver(ModelGeometricEntitySplit, this->CallbackCommand); // edges vtkModelItemIterator* iter = model->NewIterator(vtkModelEdgeType); for(iter->Begin();!iter->IsAtEnd();iter->Next()) { vtkModelEdge* edge = vtkModelEdge::SafeDownCast(iter->GetCurrentItem()); vtkSmartPointer<vtkCMBModelEdgeMeshServer> meshRepresentation = vtkSmartPointer<vtkCMBModelEdgeMeshServer>::New(); meshRepresentation->Initialize(this, edge); this->Internal->ModelEdges[edge] = meshRepresentation; } iter->Delete(); // faces iter = model->NewIterator(vtkModelFaceType); for(iter->Begin();!iter->IsAtEnd();iter->Next()) { vtkModelFace* face = vtkModelFace::SafeDownCast(iter->GetCurrentItem()); vtkSmartPointer<vtkCMBModelFaceMeshServer> meshRepresentation = vtkSmartPointer<vtkCMBModelFaceMeshServer>::New(); meshRepresentation->Initialize(this, face); this->Internal->ModelFaces[face] = meshRepresentation; } iter->Delete(); this->Modified(); } //---------------------------------------------------------------------------- bool vtkCMBMeshServer::SetGlobalLength(double globalLength) { if(this->GlobalLength == globalLength) { return false; } if(globalLength <= 0) { this->GlobalLength = 0.; return false; } this->GlobalLength = globalLength > 0. ? globalLength : 0.; this->Modified(); return true; } //---------------------------------------------------------------------------- bool vtkCMBMeshServer::SetGlobalMinimumAngle(double minAngle) { if(this->GlobalMinimumAngle == minAngle) { return false; } if(minAngle < 0.) { this->GlobalMinimumAngle = 0; } else if(minAngle > 33.) { this->GlobalMinimumAngle = 33.; } else { this->GlobalMinimumAngle = minAngle; } this->Modified(); return true; } //---------------------------------------------------------------------------- void vtkCMBMeshServer::Reset() { this->Internal->ModelEdges.clear(); this->Internal->ModelFaces.clear(); if(this->CallbackCommand) { if(this->Model) { this->Model->RemoveObserver(this->CallbackCommand); } this->CallbackCommand = NULL; } this->Superclass::Reset(); this->Modified(); } //---------------------------------------------------------------------------- vtkCMBModelEntityMesh* vtkCMBMeshServer::GetModelEntityMesh( vtkModelGeometricEntity* entity) { if(vtkModelEdge* modelEdge = vtkModelEdge::SafeDownCast(entity)) { std::map<vtkModelEdge*,vtkSmartPointer<vtkCMBModelEdgeMeshServer> >::iterator it= this->Internal->ModelEdges.find(modelEdge); if(it == this->Internal->ModelEdges.end()) { return NULL; } return it->second; } if(vtkModelFace* modelFace = vtkModelFace::SafeDownCast(entity)) { std::map<vtkModelFace*, vtkSmartPointer<vtkCMBModelFaceMeshServer> >::iterator it= this->Internal->ModelFaces.find(modelFace); if(it == this->Internal->ModelFaces.end()) { return NULL; } return it->second; } vtkErrorMacro("Incorrect type."); return NULL; } //---------------------------------------------------------------------------- void vtkCMBMeshServer::ModelEdgeSplit(vtkSplitEventData* splitEventData) { vtkModelEdge* sourceEdge = vtkModelEdge::SafeDownCast( splitEventData->GetSourceEntity()->GetThisModelEntity()); if(splitEventData->GetCreatedModelEntityIds()->GetNumberOfIds() != 2) { vtkGenericWarningMacro("Problem with split event."); return; } vtkModelEdge* createdEdge = vtkModelEdge::SafeDownCast( this->Model->GetModelEntity( vtkModelEdgeType, splitEventData->GetCreatedModelEntityIds()->GetId(0))); if(createdEdge == NULL) { createdEdge = vtkModelEdge::SafeDownCast( this->Model->GetModelEntity( vtkModelEdgeType, splitEventData->GetCreatedModelEntityIds()->GetId(1))); } vtkCMBModelEdgeMesh* sourceMesh = vtkCMBModelEdgeMesh::SafeDownCast( this->GetModelEntityMesh(sourceEdge)); sourceMesh->BuildModelEntityMesh(false); vtkSmartPointer<vtkCMBModelEdgeMeshServer> createdMesh = vtkSmartPointer<vtkCMBModelEdgeMeshServer>::New(); createdMesh->SetLength(sourceMesh->GetLength()); createdMesh->Initialize(this, createdEdge); this->Internal->ModelEdges[createdEdge] = createdMesh; createdMesh->BuildModelEntityMesh(true); this->Modified(); } //---------------------------------------------------------------------------- void vtkCMBMeshServer::ModelEdgeMerge(vtkMergeEventData* mergeEventData) { vtkModelEdge* sourceEdge = vtkModelEdge::SafeDownCast( mergeEventData->GetSourceEntity()->GetThisModelEntity()); vtkModelEdge* targetEdge = vtkModelEdge::SafeDownCast( mergeEventData->GetTargetEntity()->GetThisModelEntity()); vtkCMBModelEdgeMesh* sourceMesh = vtkCMBModelEdgeMesh::SafeDownCast( this->GetModelEntityMesh(sourceEdge)); double sourceLength = sourceMesh->GetLength(); this->Internal->ModelEdges.erase(sourceEdge); vtkCMBModelEdgeMesh* targetEdgeMesh = vtkCMBModelEdgeMesh::SafeDownCast( this->GetModelEntityMesh(targetEdge)); if( (targetEdgeMesh->GetLength() > sourceLength && sourceLength > 0.) || targetEdgeMesh->GetLength() <= 0.) { targetEdgeMesh->SetLength(sourceLength); } this->Modified(); } //---------------------------------------------------------------------------- void vtkCMBMeshServer::ModelEntityBoundaryModified(vtkModelGeometricEntity* entity) { if(entity->IsA("vtkModelEdge") != 0) { if(vtkCMBModelEntityMesh* entityMesh = this->GetModelEntityMesh(entity)) { entityMesh->BuildModelEntityMesh(false); } } else if(vtkModelFace* face = vtkModelFace::SafeDownCast(entity)) { vtkModelItemIterator* edges = face->NewAdjacentModelEdgeIterator(); for(edges->Begin();!edges->IsAtEnd();edges->Next()) { if(vtkCMBModelEntityMesh* entityMesh = this->GetModelEntityMesh(vtkModelEdge::SafeDownCast(edges->GetCurrentItem()))) { entityMesh->BuildModelEntityMesh(false); } } edges->Delete(); if(vtkCMBModelEntityMesh* faceMesh = this->GetModelEntityMesh(face)) { faceMesh->BuildModelEntityMesh(false); } } } //---------------------------------------------------------------------------- void vtkCMBMeshServer::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
31.157718
87
0.63371
[ "model" ]
1fca36d9e7e66af3421b88d6302ba867eb7a7e52
56,308
cpp
C++
ext/gdiplus/gdip_graphicspath.cpp
yagisumi/ruby-gdiplus
8c8aed4942a61e61f554394705140971db8debb6
[ "MIT" ]
1
2017-05-04T05:48:19.000Z
2017-05-04T05:48:19.000Z
ext/gdiplus/gdip_graphicspath.cpp
yagisumi/ruby-gdiplus
8c8aed4942a61e61f554394705140971db8debb6
[ "MIT" ]
null
null
null
ext/gdiplus/gdip_graphicspath.cpp
yagisumi/ruby-gdiplus
8c8aed4942a61e61f554394705140971db8debb6
[ "MIT" ]
null
null
null
/* * gdip_graphicspath.cpp * Copyright (c) 2017 Yagi Sumiya * Released under the MIT License. */ #include "ruby_gdiplus.h" const rb_data_type_t tGraphicsPath = _MAKE_DATA_TYPE( "GraphicsPath", 0, GDIP_OBJ_FREE(GraphicsPath *), NULL, NULL, &cGraphicsPath); struct gdipPathData { public: int count; VALUE v_points; VALUE v_types; }; static void gdip_pathdata_mark(gdipPathData *pathdata) { if (pathdata != NULL) { rb_gc_mark(pathdata->v_points); rb_gc_mark(pathdata->v_types); } } static VALUE cPathData; const rb_data_type_t tPathData = _MAKE_DATA_TYPE( "PathData", RUBY_DATA_FUNC(gdip_pathdata_mark), GDIP_DEFAULT_FREE(gdipPathData), NULL, NULL, &cPathData); static VALUE gdip_pathdata_create(PathData *pathdata) { VALUE r = typeddata_alloc<gdipPathData, &tPathData>(cPathData); gdipPathData *p = Data_Ptr<gdipPathData *>(r); int count = pathdata->Count; p->count = count; if (count <= 0) { p->v_points = rb_ary_new(); p->v_types = rb_ary_new(); RB_OBJ_FREEZE(p->v_points); RB_OBJ_FREEZE(p->v_types); } else { VALUE points = rb_ary_new_capa(count); VALUE types = rb_ary_new_capa(count); for (int i = 0; i < count; ++i) { rb_ary_push(points, gdip_pointf_create(pathdata->Points[i].X, pathdata->Points[i].Y)); rb_ary_push(types, gdip_enumint_create(cPathPointType, pathdata->Types[i])); } RB_OBJ_FREEZE(points); RB_OBJ_FREEZE(types); p->v_points = points; p->v_types = types; } return r; } static VALUE gdip_pathdata_get_points(VALUE self) { gdipPathData *pathdata = Data_Ptr<gdipPathData *>(self); Check_NULL(pathdata, "This PathData object does not exist."); return pathdata->v_points; } static VALUE gdip_pathdata_get_types(VALUE self) { gdipPathData *pathdata = Data_Ptr<gdipPathData *>(self); Check_NULL(pathdata, "This PathData object does not exist."); return pathdata->v_types; } static VALUE gdip_pathdata_get_count(VALUE self) { gdipPathData *pathdata = Data_Ptr<gdipPathData *>(self); Check_NULL(pathdata, "This PathData object does not exist."); return RB_INT2NUM(pathdata->count); } static BYTE * alloc_array_of_pptype(VALUE ary, int& count) { count = 0; for (long i = 0; i < RARRAY_LEN(ary); ++i) { VALUE elem = rb_ary_entry(ary, i); int enumint; if (gdip_arg_to_enumint(cPathPointType, elem, &enumint)) { count += 1; } } if (count == 0) return NULL; int idx = 0; BYTE *tary = static_cast<BYTE *>(ruby_xcalloc(count, sizeof(BYTE))); for (long i = 0; i < RARRAY_LEN(ary); ++i) { VALUE elem = rb_ary_entry(ary, i); int enumint; if (gdip_arg_to_enumint(cPathPointType, elem, &enumint)) { tary[idx] = static_cast<BYTE>(enumint); idx += 1; } } return tary; } /** * @overload initialize(fill_mode=FillMode.Alternate) * @param fill_mode [FillMode] * @overload initialize(points, types, fill_mode=FillMode.Alternate) * @param points [Array<Point or PointF>] * @param types [PathPointType] * @param fill_mode [FillMode] */ static VALUE gdip_gpath_init(int argc, VALUE *argv, VALUE self) { if (argc > 3) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 0..3)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); if (gp != NULL) { _VERBOSE("This GraphicsPath object is already initialized."); return self; } if (argc == 0 || argc == 1) { VALUE v_fill_mode = Qnil; rb_scan_args(argc, argv, "01", &v_fill_mode); int enumint = 0; if (!RB_NIL_P(v_fill_mode)) { gdip_arg_to_enumint(cFillMode, v_fill_mode, &enumint, "The argument should be FillMode."); } _DATA_PTR(self) = gdip_obj_create(new GraphicsPath(static_cast<FillMode>(enumint))); } else if (argc == 2 || argc == 3) { VALUE v_points; VALUE v_types; VALUE v_fill_mode = Qnil; rb_scan_args(argc, argv, "21", &v_points, &v_types, &v_fill_mode); int enumint = 0; if (!RB_NIL_P(v_fill_mode)) { gdip_arg_to_enumint(cFillMode, v_fill_mode, &enumint, "The argument should be FillMode."); } if (_RB_ARRAY_P(v_points) && _RB_ARRAY_P(v_types)) { if (RARRAY_LEN(v_points) <= 0) { rb_raise(rb_eTypeError, "The first arguments should be Array of Point or PointF."); } VALUE first = rb_ary_entry(v_points, 0); if (_KIND_OF(first, &tPoint)) { int cnt_points = 0; int cnt_types = 0; Point *points = alloc_array_of<Point, &tPoint>(v_points, cnt_points); BYTE *types = alloc_array_of_pptype(v_types, cnt_types); if (cnt_points == cnt_types) { GraphicsPath *new_gp = new GraphicsPath(points, types, cnt_points, static_cast<FillMode>(enumint)); ruby_xfree(points); ruby_xfree(types); _DATA_PTR(self) = gdip_obj_create(new_gp); } else { ruby_xfree(points); ruby_xfree(types); rb_raise(rb_eArgError, "The number of elements in two arrays is different. (Point: %d, PathPointType: %d)", cnt_points, cnt_types); } } else if (_KIND_OF(first, &tPointF)) { int cnt_points = 0; int cnt_types = 0; PointF *points = alloc_array_of<PointF, &tPointF>(v_points, cnt_points); BYTE *types = alloc_array_of_pptype(v_types, cnt_types); if (cnt_points == cnt_types) { GraphicsPath *new_gp = new GraphicsPath(points, types, cnt_points, static_cast<FillMode>(enumint)); ruby_xfree(points); ruby_xfree(types); _DATA_PTR(self) = gdip_obj_create(new_gp); } else { ruby_xfree(points); ruby_xfree(types); rb_raise(rb_eArgError, "The number of elements in two arrays is different. (Point: %d, PathPointType: %d)", cnt_points, cnt_types); } } else { rb_raise(rb_eTypeError, "The first arguments should be Array of Point or PointF."); } } else { rb_raise(rb_eTypeError, "The first and second arguments should be Array."); } } return self; } /** * Gets or sets a FillMode. * @return [FillMode] */ static VALUE gdip_gpath_get_fill_mode(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); return gdip_enumint_create(cFillMode, gp->GetFillMode()); } static VALUE gdip_gpath_set_fill_mode(VALUE self, VALUE arg) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); int enumint = 0; gdip_arg_to_enumint(cFillMode, arg, &enumint, "The argument should be FillMode."); Status status = gp->SetFillMode(static_cast<FillMode>(enumint)); Check_Status(status); return self; } static VALUE gdip_gpath_get_point_count(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); return RB_INT2NUM(gp->GetPointCount()); } static VALUE gdip_gpath_get_path_types(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); int count = gp->GetPointCount(); if (count < 1) { return rb_ary_new(); } BYTE *types = static_cast<BYTE *>(RB_ZALLOC_N(BYTE, count)); Status status = gp->GetPathTypes(types, count); VALUE r = rb_ary_new_capa(count); for (int i = 0; i < count; ++i) { rb_ary_push(r, gdip_enumint_create(cPathPointType, types[i])); } ruby_xfree(types); Check_Status(status); return r; } static VALUE gdip_gpath_get_path_points(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); int count = gp->GetPointCount(); if (count < 1) { return rb_ary_new(); } PointF *points = static_cast<PointF *>(RB_ZALLOC_N(PointF, count)); Status status = gp->GetPathPoints(points, count); VALUE r = rb_ary_new_capa(count); for (int i = 0; i < count; ++i) { rb_ary_push(r, gdip_pointf_create(points[i].X, points[i].Y)); } ruby_xfree(points); Check_Status(status); return r; } static VALUE gdip_gpath_get_path_data(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); PathData *pathdata = new PathData(); Status status = Ok; if (gp->GetPointCount()) { status = gp->GetPathData(pathdata); } VALUE v_pathdata = gdip_pathdata_create(pathdata); delete pathdata; Check_Status(status); return v_pathdata; } /** * @overload AddArc(rect, start_angle, sweep_angle) * @param rect [Rectangle or RectangleF] * @param start_angle [Integer or Float] * @param sweep_angle [Integer or Float] * @overload AddArc(x, y, width, height, start_angle, sweep_angle) * @param x [Integer or Float] * @param y [Integer or Float] * @param width [Integer or Float] * @param height [Integer or Float] * @param start_angle [Integer or Float] * @param sweep_angle [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_arc(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 3 && argc != 6) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 3 or 6)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); float start_angle; float sweep_angle; if (argc == 3 && !gdip_arg_to_single(argv[1], &start_angle)) { rb_raise(rb_eTypeError, "The argument of the start angle should be Integer or Float."); } if (argc == 3 && !gdip_arg_to_single(argv[2], &sweep_angle)) { rb_raise(rb_eTypeError, "The argument of the sweep angle should be Integer or Float."); } if (argc == 6 && !gdip_arg_to_single(argv[4], &start_angle)) { rb_raise(rb_eTypeError, "The argument of the start angle should be Integer or Float."); } if (argc == 6 && !gdip_arg_to_single(argv[5], &sweep_angle)) { rb_raise(rb_eTypeError, "The argument of the sweep angle should be Integer or Float."); } Status status = Ok; if (argc == 3) { if (_KIND_OF(argv[0], &tRectangle)) { Rect *rect = Data_Ptr<Rect *>(argv[0]); status = gp->AddArc(*rect, start_angle, sweep_angle); } else if (_KIND_OF(argv[0], &tRectangleF)) { RectF *rect = Data_Ptr<RectF *>(argv[0]); status = gp->AddArc(*rect, start_angle, sweep_angle); } else { rb_raise(rb_eTypeError, "The second argument should be Rectangle or RectangleF"); } } else if (argc == 6) { if (Integer_p(argv[0], argv[1], argv[2], argv[3])) { status = gp->AddArc(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3]), start_angle, sweep_angle); } else if (Float_p(argv[0], argv[1], argv[2], argv[3])) { status = gp->AddArc(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3]), start_angle, sweep_angle); } else { rb_raise(rb_eTypeError, "The arguments representing the position and size of the rectangle should be Integer or Float."); } } Check_Status(status); return self; } /** * @overload AddBezier(point1, point2, point3, point4) * @param point1 [Point or PointF] * @param point2 [Point or PointF] * @param point3 [Point or PointF] * @param point4 [Point or PointF] * @overload AddBezier(x1, y1, x2, y2, x3, y3, x4, y4) * @param x1 [Integer or Float] * @param y1 [Integer or Float] * @param x2 [Integer or Float] * @param y2 [Integer or Float] * @param x3 [Integer or Float] * @param y3 [Integer or Float] * @param x4 [Integer or Float] * @param y4 [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_bezier(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 4 && argc != 8) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 4 or 8)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); Status status = Ok; if (argc == 4) { if (Typeddata_p(3, &argv[0], &tPoint)) { Point *po1 = Data_Ptr<Point *>(argv[0]); Point *po2 = Data_Ptr<Point *>(argv[1]); Point *po3 = Data_Ptr<Point *>(argv[2]); Point *po4 = Data_Ptr<Point *>(argv[3]); status = gp->AddBezier(*po1, *po2, *po3, *po4); } else if (Typeddata_p(3, &argv[0], &tPointF)) { PointF *po1 = Data_Ptr<PointF *>(argv[0]); PointF *po2 = Data_Ptr<PointF *>(argv[1]); PointF *po3 = Data_Ptr<PointF *>(argv[2]); PointF *po4 = Data_Ptr<PointF *>(argv[3]); status = gp->AddBezier(*po1, *po2, *po3, *po4); } else { rb_raise(rb_eTypeError, "The argument representing points should be Point or PointF."); } } else if (argc == 8) { if (Integer_p(8, argv)) { status = gp->AddBezier( RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3]), RB_NUM2INT(argv[4]), RB_NUM2INT(argv[5]), RB_NUM2INT(argv[6]), RB_NUM2INT(argv[7])); } else if (Float_p(8, argv)) { status = gp->AddBezier( NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3]), NUM2SINGLE(argv[4]), NUM2SINGLE(argv[5]), NUM2SINGLE(argv[6]), NUM2SINGLE(argv[7])); } else { rb_raise(rb_eTypeError, "The argument representing the coordinates of points should be Integer or Float."); } } Check_Status(status); return self; } /** * @overload AddBeziers(points) * @param points [Array<Point or PointF>] The number of points should be 1 + 3n (n >= 1: 4, 7, 10, 13, ...). * @return [self] */ static VALUE gdip_gpath_add_beziers(VALUE self, VALUE ary) { Check_Frozen(self); if (!_RB_ARRAY_P(ary) || RARRAY_LEN(ary) == 0) { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); VALUE first = rb_ary_entry(ary, 0); if (_KIND_OF(first, &tPoint)) { int count; Point *points = alloc_array_of<Point, &tPoint>(ary, count); if ((count - 1) % 3 == 0) { Status status = gp->AddBeziers(points, count); ruby_xfree(points); Check_Status(status); } else { ruby_xfree(points); rb_raise(rb_eArgError, "wrong number of elements of the array (%d for 4, 7, 10, 13, ...)", count); } } else if (_KIND_OF(first, &tPointF)) { int count; PointF *points = alloc_array_of<PointF, &tPointF>(ary, count); if ((count - 1) % 3 == 0) { Status status = gp->AddBeziers(points, count); ruby_xfree(points); Check_Status(status); } else { ruby_xfree(points); rb_raise(rb_eArgError, "wrong number of elements of the array (%d for 4, 7, 10, 13, ...)", count); } } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } return self; } /** * @overload AddClosedCurve(points, tension=0.5) * @param points [Array<Point or PointF>] * @param tension [Float] 0.0-1.0 * @return [self] */ static VALUE gdip_gpath_add_closed_curve(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); VALUE v_ary; VALUE v_tension = Qnil; rb_scan_args(argc, argv, "11", &v_ary, &v_tension); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); float tension = 0.5f; if (!RB_NIL_P(v_tension)) { if (Float_p(v_tension)) { tension = clamp(NUM2SINGLE(v_tension), 0.0f, 1.0f); } else { rb_raise(rb_eTypeError, "The third argument should be Float."); } } if (_RB_ARRAY_P(v_ary) && RARRAY_LEN(v_ary) > 0) { VALUE first = rb_ary_entry(v_ary, 0); if (_KIND_OF(first, &tPoint)) { int count; Point *points = alloc_array_of<Point, &tPoint>(v_ary, count); Status status = gp->AddClosedCurve(points, count, tension); ruby_xfree(points); Check_Status(status); } else if (_KIND_OF(first, &tPointF)) { int count; PointF *points = alloc_array_of<PointF, &tPointF>(v_ary, count); Status status = gp->AddClosedCurve(points, count, tension); ruby_xfree(points); Check_Status(status); } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } return self; } /** * @overload AddCurve(points, tension=0.5) * @param points [Array<Point or PointF>] * @param tension [Float] 0.0-1.0 * @overload AddCurve(points, offset, num, tension=0.5) * @param points [Array<Point or PointF>] * @param offset [Integer] start index of points * @param num [Integer] number of segments * @param tension [Float] 0.0-1.0 * @return [self] */ static VALUE gdip_gpath_add_curve(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc < 1 || 4 < argc) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1..4)", argc); } if (!_RB_ARRAY_P(argv[0]) || RARRAY_LEN(argv[0]) == 0) { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } if (argc == 2 && !Float_p(argv[1])) { rb_raise(rb_eTypeError, "The last argument should be Float."); } else if (argc == 3 && !Integer_p(argv[1], argv[2])) { rb_raise(rb_eTypeError, "The arguments should be Integer."); } else if (argc == 4) { if (!Float_p(argv[3])) { rb_raise(rb_eTypeError, "The last argument should be Float."); } else if (!Integer_p(argv[1], argv[2])) { rb_raise(rb_eTypeError, "The arguments should be Integer."); } } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); VALUE first = rb_ary_entry(argv[0], 0); int offset = 0; int num = 0; if (argc > 2) { offset = RB_NUM2INT(argv[1]); num = RB_NUM2INT(argv[2]); } float tension = 0.5f; if (argc == 2) { tension = clamp(NUM2SINGLE(argv[1]), 0.0f, 1.0f); } if (argc == 4) { tension = clamp(NUM2SINGLE(argv[3]), 0.0f, 1.0f); } if (_KIND_OF(first, &tPoint)) { int count; Point *points = alloc_array_of<Point, &tPoint>(argv[0], count); Status status; if (argc > 2) { status = gp->AddCurve(points, count, offset, num, tension); } else { status = gp->AddCurve(points, count, tension); } ruby_xfree(points); Check_Status(status); } else if (_KIND_OF(first, &tPointF)) { int count; PointF *points = alloc_array_of<PointF, &tPointF>(argv[0], count); Status status; if (argc > 2) { status = gp->AddCurve(points, count, offset, num, tension); } else { status = gp->AddCurve(points, count, tension); } ruby_xfree(points); Check_Status(status); } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } return self; } /** * @overload AddEllipse(rectangle) * @param rectangle [Rectangle or RectangleF] * @overload AddEllipse(x, y, width, height) * @param x [Integer or Float] * @param y [Integer or Float] * @param width [Integer or Float] * @param height [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_ellipse(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 1 && argc != 4) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 4)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); if (argc == 1) { if (_KIND_OF(argv[0], &tRectangle)) { Rect *rect = Data_Ptr<Rect *>(argv[0]); gp->AddEllipse(*rect); } else if (_KIND_OF(argv[0], &tRectangleF)) { RectF *rect = Data_Ptr<RectF *>(argv[0]); gp->AddEllipse(*rect); } else { rb_raise(rb_eTypeError, "The argument should be Rectangle or RectangleF."); } } else if (argc == 4) { if (Integer_p(argv[0], argv[1], argv[2], argv[3])) { gp->AddEllipse(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3])); } else if (Float_p(argv[0], argv[1], argv[2], argv[3])) { gp->AddEllipse(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3])); } else { rb_raise(rb_eTypeError, "The arguments should be Integer or Float."); } } return self; } /** * @overload AddLine(point1, point2) * @param point1 [Point or PointF] * @param point2 [Point or PointF] * @overload AddLine(x1, y1, x2, y2) * @param x1 [Integer or Float] * @param y1 [Integer or Float] * @param x2 [Integer or Float] * @param y2 [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_line(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 2 && argc != 4) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 4)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); if (argc == 2) { if (_KIND_OF(argv[0], &tPoint) && _KIND_OF(argv[1], &tPoint)) { Point *po1 = Data_Ptr<Point *>(argv[0]); Point *po2 = Data_Ptr<Point *>(argv[1]); gp->AddLine(po1->X, po1->Y, po2->X, po2->Y); } else if (_KIND_OF(argv[0], &tPointF) && _KIND_OF(argv[1], &tPointF)) { PointF *po1 = Data_Ptr<PointF *>(argv[0]); PointF *po2 = Data_Ptr<PointF *>(argv[1]); gp->AddLine(po1->X, po1->Y, po2->X, po2->Y); } else { rb_raise(rb_eTypeError, "The arguments should be Point or PointF."); } } else if (argc == 4) { if (Integer_p(argv[0], argv[1], argv[2], argv[3])) { gp->AddLine(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3])); } else if (Float_p(argv[0], argv[1], argv[2], argv[3])) { gp->AddLine(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3])); } else { rb_raise(rb_eTypeError, "The arguments should be Integer or Float."); } } return self; } /** * @overload AddLines(points) * @param points [Array<Point or PointF>] * @return [self] */ static VALUE gdip_gpath_add_lines(VALUE self, VALUE ary) { Check_Frozen(self); if (!_RB_ARRAY_P(ary) && RARRAY_LEN(ary) == 0) { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); VALUE first = rb_ary_entry(ary, 0); if (_KIND_OF(first, &tPoint)) { int count; Point *points = alloc_array_of<Point, &tPoint>(ary, count); Status status = gp->AddLines(points, count); ruby_xfree(points); Check_Status(status); } else if (_KIND_OF(first, &tPointF)) { int count; PointF *points = alloc_array_of<PointF, &tPointF>(ary, count); Status status = gp->AddLines(points, count); ruby_xfree(points); Check_Status(status); } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } return self; } /** * @overload AddPie(rect, start_angle, sweep_angle) * @param rect [Rectangle or RectangleF] * @param start_angle [Integer or Float] * @param sweep_angle [Integer or Float] * @overload AddPie(x, y, width, height, start_angle, sweep_angle) * @param x [Integer or Float] * @param y [Integer or Float] * @param width [Integer or Float] * @param height [Integer or Float] * @param start_angle [Integer or Float] * @param sweep_angle [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_pie(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 3 && argc != 6) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 3 or 6)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); float start_angle; float sweep_angle; if (argc == 3 && !gdip_arg_to_single(argv[1], &start_angle)) { rb_raise(rb_eTypeError, "The argument of the start angle should be Integer or Float."); } if (argc == 3 && !gdip_arg_to_single(argv[2], &sweep_angle)) { rb_raise(rb_eTypeError, "The argument of the sweep angle should be Integer or Float."); } if (argc == 6 && !gdip_arg_to_single(argv[4], &start_angle)) { rb_raise(rb_eTypeError, "The argument of the start angle should be Integer or Float."); } if (argc == 6 && !gdip_arg_to_single(argv[5], &sweep_angle)) { rb_raise(rb_eTypeError, "The argument of the sweep angle should be Integer or Float."); } Status status = Ok; if (argc == 3) { if (_KIND_OF(argv[0], &tRectangle)) { Rect *rect = Data_Ptr<Rect *>(argv[0]); status = gp->AddPie(*rect, start_angle, sweep_angle); } else if (_KIND_OF(argv[0], &tRectangleF)) { RectF *rect = Data_Ptr<RectF *>(argv[0]); status = gp->AddPie(*rect, start_angle, sweep_angle); } else { rb_raise(rb_eTypeError, "The second argument should be Rectangle or RectangleF"); } } else if (argc == 6) { if (Integer_p(argv[0], argv[1], argv[2], argv[3])) { status = gp->AddPie(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3]), start_angle, sweep_angle); } else if (Float_p(argv[0], argv[1], argv[2], argv[3])) { status = gp->AddPie(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3]), start_angle, sweep_angle); } else { rb_raise(rb_eTypeError, "The arguments representing the position and size of the rectangle should be Integer or Float."); } } Check_Status(status); return self; } /** * @overload AddPolygon(points) * @param points [Array<Point or PointF>] * @return [self] */ static VALUE gdip_gpath_add_polygon(VALUE self, VALUE ary) { Check_Frozen(self); if (!_RB_ARRAY_P(ary) && RARRAY_LEN(ary) == 0) { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); VALUE first = rb_ary_entry(ary, 0); if (_KIND_OF(first, &tPoint)) { int count; Point *points = alloc_array_of<Point, &tPoint>(ary, count); Status status = gp->AddPolygon(points, count); ruby_xfree(points); Check_Status(status); } else if (_KIND_OF(first, &tPointF)) { int count; PointF *points = alloc_array_of<PointF, &tPointF>(ary, count); Status status = gp->AddPolygon(points, count); ruby_xfree(points); Check_Status(status); } else { rb_raise(rb_eTypeError, "The second argument should be Array of Point or PointF."); } return self; } /** * @overload AddRectangle(rectangle) * @param rectangle [Rectangle or RectangleF] * @overload AddRectangle(x, y, width, height) * @param x [Integer or Float] * @param y [Integer or Float] * @param width [Integer or Float] * @param height [Integer or Float] * @return [self] */ static VALUE gdip_gpath_add_rectangle(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); if (argc != 1 && argc != 4) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 4)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); if (argc == 1) { if (_KIND_OF(argv[0], &tRectangle)) { Rect *rect = Data_Ptr<Rect *>(argv[0]); gp->AddRectangle(*rect); } else if (_KIND_OF(argv[0], &tRectangleF)) { RectF *rect = Data_Ptr<RectF *>(argv[0]); gp->AddRectangle(*rect); } else { rb_raise(rb_eTypeError, "The argument should be Rectangle or RectangleF."); } } else if (argc == 4) { if (Integer_p(argv[0], argv[1], argv[2], argv[3])) { Rect rect(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), RB_NUM2INT(argv[2]), RB_NUM2INT(argv[3])); gp->AddRectangle(rect); } else if (Float_p(argv[0], argv[1], argv[2], argv[3])) { RectF rect(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), NUM2SINGLE(argv[2]), NUM2SINGLE(argv[3])); gp->AddRectangle(rect); } else { rb_raise(rb_eTypeError, "The arguments should be Integer or Float."); } } return self; } /** * @overload AddRectangles(rectangles) * @param rectangles [Array<Rectangle or RectangleF>] * @return [self] */ static VALUE gdip_gpath_add_rectangles(VALUE self, VALUE ary) { Check_Frozen(self); if (!_RB_ARRAY_P(ary) && RARRAY_LEN(ary) == 0) { rb_raise(rb_eTypeError, "The second argument should be Array of Rectangle or RectangleF."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "The GraphicsPath object does not exist."); VALUE first = rb_ary_entry(ary, 0); if (_KIND_OF(first, &tRectangle)) { int count; Rect *rects = alloc_array_of<Rect, &tRectangle>(ary, count); Status status = gp->AddRectangles(rects, count); ruby_xfree(rects); Check_Status(status); } else if (_KIND_OF(first, &tRectangleF)) { int count; RectF *rects = alloc_array_of<RectF, &tRectangleF>(ary, count); Status status = gp->AddRectangles(rects, count); ruby_xfree(rects); Check_Status(status); } else { rb_raise(rb_eTypeError, "The second argument should be Array of Rectangle or RectangleF."); } return self; } /** * @overload AddString(str, family, style, size, origin, format) * @param str [String] * @param family [FontFamily] * @param style [FontStyle] * @param size [Float or Integer] * @param origin [Point or PointF] * @param format [StringFormat] * @overload AddString(str, family, style, size, rect, format) * @param str [String] * @param family [FontFamily] * @param style [FontStyle] * @param size [Float or Integer] * @param rect [Rectangle or RectangleF] * @param format [StringFormat] * @return [self] */ static VALUE gdip_gpath_add_string(VALUE self, VALUE str, VALUE v_family, VALUE v_style, VALUE v_size, VALUE point_or_rect, VALUE v_format) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); if (!_RB_STRING_P(str)) { rb_raise(rb_eTypeError, "The first argument should be String."); } if (!_KIND_OF(v_family, &tFontFamily)) { rb_raise(rb_eTypeError, "The second argument should be FontFamily."); } int style = 0; gdip_arg_to_enumint(cFontStyle, v_style, &style, "The third argument should be FontStyle."); float size = 12.0f; gdip_arg_to_single(v_size, &size, "The fourth argument should be Float or Integer."); if (!_KIND_OF(v_format, &tStringFormat)) { rb_raise(rb_eTypeError, "The sixth argument should be StringFormat."); } FontFamily *family = Data_Ptr<FontFamily *>(v_family); Check_NULL(family, "This FontFamily object does not exist."); StringFormat *format = Data_Ptr<StringFormat *>(v_format); Check_NULL(format, "This StringFormat object does not exist."); VALUE wstr = util_utf16_str_new(str); Status status = Ok; if (_KIND_OF(point_or_rect, &tPoint)) { Point *point = Data_Ptr<Point *>(point_or_rect); status = gp->AddString(RString_Ptr<WCHAR *>(wstr), -1, family, style, size, *point, format); } else if (_KIND_OF(point_or_rect, &tPointF)) { PointF *point = Data_Ptr<PointF *>(point_or_rect); status = gp->AddString(RString_Ptr<WCHAR *>(wstr), -1, family, style, size, *point, format); } else if (_KIND_OF(point_or_rect, &tRectangle)) { Rect *rect = Data_Ptr<Rect *>(point_or_rect); status = gp->AddString(RString_Ptr<WCHAR *>(wstr), -1, family, style, size, *rect, format); } else if (_KIND_OF(point_or_rect, &tRectangleF)) { RectF *rect = Data_Ptr<RectF *>(point_or_rect); status = gp->AddString(RString_Ptr<WCHAR *>(wstr), -1, family, style, size, *rect, format); } else { rb_raise(rb_eTypeError, "The fifth argument should be Point, PointF, Rectangle or RectangleF."); } Check_Status(status); return self; } /** * @overload AddPath(path, connect=false) * @param path [GraphicsPath] * @param connect [Boolean] * @return [self] */ static VALUE gdip_gpath_add_path(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); VALUE v_path; VALUE v_connect; rb_scan_args(argc, argv, "11", &v_path, &v_connect); if (!_KIND_OF(v_path, &tGraphicsPath)) { rb_raise(rb_eTypeError, "The first argument should be GraphicsPath."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); GraphicsPath *path = Data_Ptr<GraphicsPath *>(argv[0]); Check_NULL(path, "This GraphicsPath object does not exist."); Status status = gp->AddPath(path, RB_TEST(v_connect)); Check_Status(status); return self; } /** * Clears all markers. * @return [self] */ static VALUE gdip_gpath_clear_markers(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->ClearMarkers(); Check_Status(status); return self; } /** * Closes all figures. * @return [self] */ static VALUE gdip_gpath_close_all_figures(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->CloseAllFigures(); Check_Status(status); return self; } /** * Closes the current figure. * @return [self] */ static VALUE gdip_gpath_close_figure(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->CloseFigure(); Check_Status(status); return self; } /** * Resets. * @return [self] */ static VALUE gdip_gpath_reset(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->Reset(); Check_Status(status); return self; } /** * Reverses the order of points. * @return [self] */ static VALUE gdip_gpath_reverse(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->Reverse(); Check_Status(status); return self; } /** * Sets a marker at the current point. * @return [self] */ static VALUE gdip_gpath_set_marker(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->SetMarker(); Check_Status(status); return self; } /** * Starts a new figure without closing the current figure. * @return [self] */ static VALUE gdip_gpath_start_figure(VALUE self) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Status status = gp->StartFigure(); Check_Status(status); return self; } /** * @overload Flatten(matrix=nil, flatness=0.25) * Convert each curve to lines. * @param matrix [Matrix] Transforms before flatten. * @param flatness [Float] Specify the allowable error. Decreasing the value is close to the curve. * @return [self] */ static VALUE gdip_gpath_flatten(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); VALUE v_matrix, v_flatness; rb_scan_args(argc, argv, "02", &v_matrix, &v_flatness); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Matrix* matrix = NULL; float flatness = 0.25f; if (!RB_NIL_P(v_matrix)) { if (_KIND_OF(v_matrix, &tMatrix)) { matrix = Data_Ptr<Matrix *>(v_matrix); } else { rb_raise(rb_eTypeError, "The first argument should be Matrix."); } } if (!RB_NIL_P(v_flatness)) { gdip_arg_to_single(v_flatness, &flatness, "The second argument should be Float."); } Status status = gp->Flatten(matrix, flatness); Check_Status(status); return self; } /** * @overload Transform(matrix) * Transforms with the specified matrix. * @param matrix [Matrix] * @return [self] */ static VALUE gdip_gpath_transform(VALUE self, VALUE v_matrix) { Check_Frozen(self); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); if (_KIND_OF(v_matrix, &tMatrix)) { Matrix *matrix = Data_Ptr<Matrix *>(v_matrix); Status status = gp->Transform(matrix); Check_Status(status); } else { rb_raise(rb_eTypeError, "The first argument should be Matrix."); } return self; } /** * @overload Warp(dest_points, src_rect, matrix=nil, mode=WarpMode.Perspective, flatness=0.25) * @param dest_points [Array<PointF>] * @param src_rect [RectangleF] * @param matrix [Matrix] * @param mode [WarpMode] * @param flatness [Float] see {#flatten} * @return [self] */ static VALUE gdip_gpath_warp(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); VALUE v_points, v_rect, v_matrix, v_mode, v_flatness; rb_scan_args(argc, argv, "23", &v_points, &v_rect, &v_matrix, &v_mode, &v_flatness); if (!_RB_ARRAY_P(v_points) && RARRAY_LEN(v_points) < 1) { rb_raise(rb_eTypeError, "The first argument should be Array of PointF."); } VALUE first = rb_ary_entry(v_points, 0); if (!_KIND_OF(first, &tPointF)) { rb_raise(rb_eTypeError, "The first argument should be Array of PointF."); } if (!_KIND_OF(v_rect, &tRectangleF)) { rb_raise(rb_eTypeError, "The second argument should be RectangleF."); } Matrix *matrix = NULL; WarpMode mode = WarpModePerspective; float flatness = 0.25f; if (!RB_NIL_P(v_matrix)) { if (_KIND_OF(v_matrix, &tMatrix)) { matrix = Data_Ptr<Matrix *>(v_matrix); } else { rb_raise(rb_eTypeError, "The third argument should be Matrix."); } } if (!RB_NIL_P(v_mode)) { gdip_arg_to_enumint(cWarpMode, v_mode, &mode, "The fourth argument should be Float."); } if (!RB_NIL_P(v_flatness)) { gdip_arg_to_single(v_flatness, &flatness, "The fifth argument should be Float."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); int count = 0; PointF *points = alloc_array_of<PointF, &tPointF>(v_points, count); if (count < 3) { ruby_xfree(points); rb_raise(rb_eArgError, "The second argument should be Array with three or four Point."); } RectF *rect = Data_Ptr<RectF *>(v_rect); Status status = gp->Warp(points, count == 3 ? 3 : 4, *rect, matrix, mode, flatness); ruby_xfree(points); Check_Status(status); return self; } /** * @overload Widen(pen, matrix=nil, flatness=0.25) * Widens this path. * @param pen [Pen] * @param matrix [Matrix] * @param flatness [Float] * @return [self] */ static VALUE gdip_gpath_widen(int argc, VALUE *argv, VALUE self) { Check_Frozen(self); VALUE v_pen, v_matrix, v_flatness; rb_scan_args(argc, argv, "12", &v_pen, &v_matrix, &v_flatness); Pen *pen = NULL; if (_KIND_OF(v_pen, &tPen)) { pen = Data_Ptr<Pen *>(v_pen); } else { rb_raise(rb_eTypeError, "The first argument should be Pen."); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Matrix* matrix = NULL; float flatness = 0.25f; if (!RB_NIL_P(v_matrix)) { if (_KIND_OF(v_matrix, &tMatrix)) { matrix = Data_Ptr<Matrix *>(v_matrix); } else { rb_raise(rb_eTypeError, "The second argument should be Matrix."); } } if (!RB_NIL_P(v_flatness)) { gdip_arg_to_single(v_flatness, &flatness, "The third argument should be Float."); } Status status = gp->Widen(pen, matrix, flatness); Check_Status(status); return self; } /** * @overload GetBounds(matrix=nil, pen=nil) * Convert curves to lines. * @param matrix [Matrix] Transforms before flatten. * @param pen [Pen] * @return [RectangleF] */ static VALUE gdip_gpath_get_bounds(int argc, VALUE *argv, VALUE self) { VALUE v_matrix, v_pen; rb_scan_args(argc, argv, "02", &v_matrix, &v_pen); GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); Matrix* matrix = NULL; Pen *pen = NULL; if (!RB_NIL_P(v_matrix)) { if (_KIND_OF(v_matrix, &tMatrix)) { matrix = Data_Ptr<Matrix *>(v_matrix); } else { rb_raise(rb_eTypeError, "The first argument should be Matrix."); } } if (!RB_NIL_P(v_pen)) { if (_KIND_OF(v_pen, &tPen)) { pen = Data_Ptr<Pen *>(v_pen); } else { rb_raise(rb_eTypeError, "The second argument should be Pen."); } } RectF rect; Status status = gp->GetBounds(&rect, matrix, pen); Check_Status(status); return gdip_rectf_create(&rect); } /** * Gets the last point. * @return [PointF] */ static VALUE gdip_gpath_get_last_point(VALUE self) { GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); PointF point; Status status = gp->GetLastPoint(&point); Check_Status(status); return gdip_pointf_create(point.X, point.Y); } /** * Whether the specified point is contained within the outline of this path. * @overload IsOutlineVisible(x, y, pen, graphics=nil) * @param x [Integer or Float] * @param y [Integer or Float] * @param pen [Pen] * @param graphics [Graphics] * @overload IsOutlineVisible(point, pen, graphics=nil) * @param point [Point or PointF] * @param pen [Pen] * @param graphics [Graphics] * @return [Boolean] */ static VALUE gdip_gpath_is_oubline_visible(int argc, VALUE *argv, VALUE self) { if (argc < 2 || 4 < argc) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 2..4)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); BOOL b = false; if (Integer_p(argv[0])) { if (!Integer_p(argv[1])) { rb_raise(rb_eTypeError, "The second argument should be Integer."); } if (argc < 3 || !_KIND_OF(argv[2], &tPen)) { rb_raise(rb_eTypeError, "The third argument should be Pen."); } if (argc == 4 && !_KIND_OF(argv[3], &tGraphics)) { rb_raise(rb_eTypeError, "The fourth argument should be Graphics."); } Pen *pen = Data_Ptr<Pen *>(argv[2]); Graphics *g = (argc == 4) ? Data_Ptr<Graphics *>(argv[3]) : NULL; b = gp->IsOutlineVisible(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), pen, g); } else if (Float_p(argv[0])) { if (!Float_p(argv[1])) { rb_raise(rb_eTypeError, "The second argument should be Float."); } if (argc < 3 || !_KIND_OF(argv[2], &tPen)) { rb_raise(rb_eTypeError, "The third argument should be Pen."); } if (argc == 4 && !_KIND_OF(argv[3], &tGraphics)) { rb_raise(rb_eTypeError, "The fourth argument should be Graphics."); } Pen *pen = Data_Ptr<Pen *>(argv[2]); Graphics *g = (argc == 4) ? Data_Ptr<Graphics *>(argv[3]) : NULL; b = gp->IsOutlineVisible(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), pen, g); } else if (_KIND_OF(argv[0], &tPoint)) { if (argc == 4) { rb_raise(rb_eArgError, "wrong number of argument"); } if (!_KIND_OF(argv[1], &tPen)) { rb_raise(rb_eTypeError, "The second argument should be Pen."); } if (argc == 3 && !_KIND_OF(argv[2], &tGraphics)) { rb_raise(rb_eTypeError, "The third argument should be Graphics."); } Point *point = Data_Ptr<Point *>(argv[0]); Pen *pen = Data_Ptr<Pen *>(argv[1]); Graphics *g = (argc == 3) ? Data_Ptr<Graphics *>(argv[2]) : NULL; b = gp->IsOutlineVisible(*point, pen, g); } else if (_KIND_OF(argv[0], &tPointF)) { if (argc == 4) { rb_raise(rb_eArgError, "wrong number of argument"); } if (!_KIND_OF(argv[1], &tPen)) { rb_raise(rb_eTypeError, "The second argument should be Pen."); } if (argc == 3 && !_KIND_OF(argv[2], &tGraphics)) { rb_raise(rb_eTypeError, "The third argument should be Graphics."); } PointF *point = Data_Ptr<PointF *>(argv[0]); Pen *pen = Data_Ptr<Pen *>(argv[1]); Graphics *g = (argc == 3) ? Data_Ptr<Graphics *>(argv[2]) : NULL; b = gp->IsOutlineVisible(*point, pen, g); } else { rb_raise(rb_eTypeError, "The first argument should be Point, PointF, Integer or Float."); } Check_LastStatus(gp); return b ? Qtrue : Qfalse; } /** * Whether the specified point is contained within this path. * @overload IsVisible(x, y, graphics=nil) * @param x [Integer or Float] * @param y [Integer or Float] * @param graphics [Graphics] * @overload IsVisible(point, graphics=nil) * @param point [Point or PointF] * @param graphics [Graphics] * @return [Boolean] */ static VALUE gdip_gpath_is_visible(int argc, VALUE *argv, VALUE self) { if (argc < 1 || 3 < argc) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1..3)", argc); } GraphicsPath *gp = Data_Ptr<GraphicsPath *>(self); Check_NULL(gp, "This GraphicsPath object does not exist."); BOOL b = false; if (Integer_p(argv[0])) { if (argc == 1 || !Integer_p(argv[1])) { rb_raise(rb_eTypeError, "The second argument should be Integer."); } if (argc == 3 && !_KIND_OF(argv[2], &tGraphics)) { rb_raise(rb_eTypeError, "The third argument should be Graphics."); } Graphics *g = (argc == 3) ? Data_Ptr<Graphics *>(argv[2]) : NULL; b = gp->IsVisible(RB_NUM2INT(argv[0]), RB_NUM2INT(argv[1]), g); } else if (Float_p(argv[0])) { if (argc == 1 || !Float_p(argv[1])) { rb_raise(rb_eTypeError, "The second argument should be Float."); } if (argc == 3 && !_KIND_OF(argv[2], &tGraphics)) { rb_raise(rb_eTypeError, "The third argument should be Graphics."); } Graphics *g = (argc == 3) ? Data_Ptr<Graphics *>(argv[2]) : NULL; b = gp->IsVisible(NUM2SINGLE(argv[0]), NUM2SINGLE(argv[1]), g); } else if (_KIND_OF(argv[0], &tPoint)) { if (argc == 3) { rb_raise(rb_eArgError, "wrong number of argument"); } if (argc == 2 && !_KIND_OF(argv[1], &tGraphics)) { rb_raise(rb_eTypeError, "The second argument should be Graphics."); } Point *point = Data_Ptr<Point *>(argv[0]); Graphics *g = (argc == 2) ? Data_Ptr<Graphics *>(argv[1]) : NULL; b = gp->IsVisible(*point, g); } else if (_KIND_OF(argv[0], &tPointF)) { if (argc == 3) { rb_raise(rb_eArgError, "wrong number of argument"); } if (argc == 2 && !_KIND_OF(argv[1], &tGraphics)) { rb_raise(rb_eTypeError, "The second argument should be Graphics."); } PointF *point = Data_Ptr<PointF *>(argv[0]); Graphics *g = (argc == 2) ? Data_Ptr<Graphics *>(argv[1]) : NULL; b = gp->IsVisible(*point, g); } else { rb_raise(rb_eTypeError, "The first argument should be Point, PointF, Integer or Float."); } Check_LastStatus(gp); return b ? Qtrue : Qfalse; } void Init_graphicspath() { cPathData = rb_define_class_under(mGdiplus, "PathData", cGpObject); rb_undef_alloc_func(cPathData); ATTR_R(cPathData, Points, points, pathdata); ATTR_R(cPathData, Types, types, pathdata); ATTR_R(cPathData, Count, count, pathdata); cGraphicsPath = rb_define_class_under(mGdiplus, "GraphicsPath", cGpObject); rb_define_alloc_func(cGraphicsPath, &typeddata_alloc_null<&tGraphicsPath>); rb_define_method(cGraphicsPath, "initialize", RUBY_METHOD_FUNC(gdip_gpath_init), -1); ATTR_RW(cGraphicsPath, FillMode, fill_mode, gpath); ATTR_R(cGraphicsPath, PointCount, point_count, gpath); ATTR_R(cGraphicsPath, PathTypes, path_types, gpath); ATTR_R(cGraphicsPath, PathPoints, path_points, gpath); ATTR_R(cGraphicsPath, PathData, path_data, gpath); rb_define_method(cGraphicsPath, "AddArc", RUBY_METHOD_FUNC(gdip_gpath_add_arc), -1); rb_define_alias(cGraphicsPath, "add_arc", "AddArc"); rb_define_method(cGraphicsPath, "AddBezier", RUBY_METHOD_FUNC(gdip_gpath_add_bezier), -1); rb_define_alias(cGraphicsPath, "add_bezier", "AddBezier"); rb_define_method(cGraphicsPath, "AddBeziers", RUBY_METHOD_FUNC(gdip_gpath_add_beziers), 1); rb_define_alias(cGraphicsPath, "add_beziers", "AddBeziers"); rb_define_method(cGraphicsPath, "AddClosedCurve", RUBY_METHOD_FUNC(gdip_gpath_add_closed_curve), -1); rb_define_alias(cGraphicsPath, "add_closed_curve", "AddClosedCurve"); rb_define_method(cGraphicsPath, "AddCurve", RUBY_METHOD_FUNC(gdip_gpath_add_curve), -1); rb_define_alias(cGraphicsPath, "add_curve", "AddCurve"); rb_define_method(cGraphicsPath, "AddEllipse", RUBY_METHOD_FUNC(gdip_gpath_add_ellipse), -1); rb_define_alias(cGraphicsPath, "add_ellipse", "AddEllipse"); rb_define_method(cGraphicsPath, "AddLine", RUBY_METHOD_FUNC(gdip_gpath_add_line), -1); rb_define_alias(cGraphicsPath, "add_line", "AddLine"); rb_define_method(cGraphicsPath, "AddLines", RUBY_METHOD_FUNC(gdip_gpath_add_lines), 1); rb_define_alias(cGraphicsPath, "add_lines", "AddLines"); rb_define_method(cGraphicsPath, "AddPie", RUBY_METHOD_FUNC(gdip_gpath_add_pie), -1); rb_define_alias(cGraphicsPath, "add_pie", "AddPie"); rb_define_method(cGraphicsPath, "AddPolygon", RUBY_METHOD_FUNC(gdip_gpath_add_polygon), 1); rb_define_alias(cGraphicsPath, "add_polygon", "AddPolygon"); rb_define_method(cGraphicsPath, "AddRectangle", RUBY_METHOD_FUNC(gdip_gpath_add_rectangle), -1); rb_define_alias(cGraphicsPath, "add_rectangle", "AddRectangle"); rb_define_method(cGraphicsPath, "AddRectangles", RUBY_METHOD_FUNC(gdip_gpath_add_rectangles), 1); rb_define_alias(cGraphicsPath, "add_rectangles", "AddRectangles"); rb_define_method(cGraphicsPath, "AddString", RUBY_METHOD_FUNC(gdip_gpath_add_string), 6); rb_define_alias(cGraphicsPath, "add_string", "AddString"); rb_define_method(cGraphicsPath, "AddPath", RUBY_METHOD_FUNC(gdip_gpath_add_path), -1); rb_define_alias(cGraphicsPath, "add_path", "AddPath"); rb_define_method(cGraphicsPath, "ClearMarkers", RUBY_METHOD_FUNC(gdip_gpath_clear_markers), 0); rb_define_alias(cGraphicsPath, "clear_markers", "ClearMarkers"); rb_define_method(cGraphicsPath, "CloseAllFigures", RUBY_METHOD_FUNC(gdip_gpath_close_all_figures), 0); rb_define_alias(cGraphicsPath, "close_all_figures", "CloseAllFigures"); rb_define_method(cGraphicsPath, "CloseFigure", RUBY_METHOD_FUNC(gdip_gpath_close_figure), 0); rb_define_alias(cGraphicsPath, "close_figure", "CloseFigure"); rb_define_method(cGraphicsPath, "Reset", RUBY_METHOD_FUNC(gdip_gpath_reset), 0); rb_define_alias(cGraphicsPath, "reset", "Reset"); rb_define_method(cGraphicsPath, "Reverse", RUBY_METHOD_FUNC(gdip_gpath_reverse), 0); rb_define_alias(cGraphicsPath, "reverse", "Reverse"); rb_define_method(cGraphicsPath, "SetMarker", RUBY_METHOD_FUNC(gdip_gpath_set_marker), 0); rb_define_alias(cGraphicsPath, "set_marker", "SetMarker"); rb_define_alias(cGraphicsPath, "SetMarkers", "SetMarker"); rb_define_alias(cGraphicsPath, "set_markers", "SetMarker"); rb_define_method(cGraphicsPath, "StartFigure", RUBY_METHOD_FUNC(gdip_gpath_start_figure), 0); rb_define_alias(cGraphicsPath, "start_figure", "StartFigure"); rb_define_method(cGraphicsPath, "Flatten", RUBY_METHOD_FUNC(gdip_gpath_flatten), -1); rb_define_alias(cGraphicsPath, "flatten", "Flatten"); rb_define_method(cGraphicsPath, "Transform", RUBY_METHOD_FUNC(gdip_gpath_transform), 1); rb_define_alias(cGraphicsPath, "transform", "Transform"); rb_define_method(cGraphicsPath, "Warp", RUBY_METHOD_FUNC(gdip_gpath_warp), -1); rb_define_alias(cGraphicsPath, "warp", "Warp"); rb_define_method(cGraphicsPath, "Widen", RUBY_METHOD_FUNC(gdip_gpath_widen), -1); rb_define_alias(cGraphicsPath, "widen", "Widen"); rb_define_method(cGraphicsPath, "GetBounds", RUBY_METHOD_FUNC(gdip_gpath_get_bounds), -1); rb_define_alias(cGraphicsPath, "get_bounds", "GetBounds"); rb_define_method(cGraphicsPath, "GetLastPoint", RUBY_METHOD_FUNC(gdip_gpath_get_last_point), 0); rb_define_alias(cGraphicsPath, "get_last_point", "GetLastPoint"); rb_define_method(cGraphicsPath, "IsOutlineVisible", RUBY_METHOD_FUNC(gdip_gpath_is_oubline_visible), -1); rb_define_alias(cGraphicsPath, "is_outline_visible?", "IsOutlineVisible"); rb_define_method(cGraphicsPath, "IsVisible", RUBY_METHOD_FUNC(gdip_gpath_is_visible), -1); rb_define_alias(cGraphicsPath, "is_visible?", "IsVisible"); }
33.516667
151
0.623375
[ "object", "transform" ]
1fcb023ef8cf0c2a632513cf0966a58e9a72b368
14,594
cpp
C++
src/handle.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
src/handle.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
src/handle.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
#define ICI_CORE #include "priv.h" namespace ici { static DataHandle ici_handle_proto; DataHandle* createDataHandle(void* ptr, String* name, SuperObject* super, void (*prefree)(DataHandle*)) { DataHandle* h; Object** po; ici_handle_proto.h_ptr = ptr; ici_handle_proto.h_name = name; ici_handle_proto.o_super = super; if(auto x = atom_probe2(&ici_handle_proto, &po)) { h = x->toDataHandle(); h->incref(); return h; } supress_collect++; if((h = allocateType<DataHandle>()) == nullptr) return nullptr; h->setHeaderFields(TC_HANDLE, (super != nullptr ? Object::O_SUPER : 0) | Object::O_ATOM, 1, 0); h->h_ptr = ptr; h->h_name = name; h->o_super = super; h->h_pre_free = prefree; h->h_member_map = nullptr; h->h_member_intf = nullptr; h->h_general_intf = nullptr; registerForGC(h); supress_collect--; store_atom_and_count(po, h); return h; } /* * If it exists, return a pointer to the DataHandle corresponding to the C data * structure 'ptr' with the ICI type 'name'. If it doesn't exist, return * nullptr. The DataHandle (if returned) will have been increfed. * * This function can be used to probe to see if there is an ICI DataHandle * associated with your C data structure in existence, but avoids allocating * it if does not exist already (as 'createDataHandle()' would do). This can be * useful if you want to free your C data structure, and need to mark any ICI * reference to the data by setting DataHandle::CLOSED in the DataHandle's Object header. */ DataHandle* handle_probe(void* ptr, String* name) { DataHandle* h; ici_handle_proto.h_ptr = ptr; ici_handle_proto.h_name = name; if((h = atom_probe(&ici_handle_proto)->toDataHandle()) != nullptr) h->incref(); return h; } /* * Verify that a method on a DataHandle has been invoked correctly. In * particular, that 'inst' is not nullptr and is a DataHandle with the given 'name'. * If OK and 'h' is non-nullptr, the DataHandle is stored through it. If 'p' is * non-nullptr, the associted pointer ('h_ptr') is stored through it. Return 1 * on error and sets error, else 0. * * For example, a typical method where the instance should be a DataHandle * of type 'XML_Parse' might look like this: * * static int * ici_xml_SetBase(Object *inst) * { * char *s; * XML_Parser p; * * if (handle_method_check(inst, ICIS(XML_Parser), nullptr, &p)) * return 1; * if (typecheck("s", &s)) * return 1; * if (!XML_SetBase(p, s)) * return ici_xml_error(p); * return setReturnNull(); * } */ int handle_method_check(Object* inst, String* name, DataHandle** h, void** p) { char n1[objnamez]; char n2[objnamez]; if(method_check(inst, TC_HANDLE)) return 1; if(inst->toDataHandle()->h_name != name) { setError("attempt to apply method %s to %s", objname(n1, g_opstack.a_top[-1]), objname(n2, inst)); return 1; } if(h != nullptr) *h = inst->toDataHandle(); if(p != nullptr) *p = inst->toDataHandle()->h_ptr; return 0; } /* * The function used to field method calls that go through the member map * mechanism. Checks conditions and transfers to the h_memeber_intf function * of the DataHandle. */ static int ici_handle_method(Object* inst) { Object* r; char n1[objnamez]; char n2[objnamez]; long id; if(method_check(inst, TC_HANDLE)) return 1; if(inst->hasFlag(DataHandle::CLOSED)) { setError("attempt to apply method %s to %s which is dead", objname(n1, g_opstack.a_top[-1]), objname(n2, inst)); return 1; } r = nullptr; id = (long)g_opstack.a_top[-1]->toNativeFunc()->cf_arg1; if((*inst->toDataHandle()->h_member_intf)(inst->toDataHandle()->h_ptr, id, nullptr, &r)) return 1; if(r == nullptr) { setError("attempt to apply method %s to %s", objname(n1, g_opstack.a_top[-1]), objname(n2, inst)); return 1; } setReturnUnref(r); return 0; } Object* make_handle_member_map(NameID* ni) { Object* m; String* n; Object* id; if((m = createMap()) == nullptr) return nullptr; for(; ni->ni_name != nullptr; ni++) { id = nullptr; if((n = String::create(ni->ni_name)) == nullptr) goto fail; if(ni->ni_id & DataHandle::METHOD) { id = createNativeFunc(n, (int (*)(...))(ici_handle_method), (void*)(ni->ni_id & ~DataHandle::METHOD), nullptr); if(id == nullptr) goto fail; } else { if((id = createIntNum(ni->ni_id)) == nullptr) goto fail; } if(m->assign(n, id)) goto fail; n->decref(); id->decref(); } return m; fail: if(n != nullptr) n->decref(); if(id != nullptr) id->decref(); m->decref(); return nullptr; } void DataHandle::TypeInfo::objname(Object* o, char p[objnamez]) { if(o->toDataHandle()->h_name == nullptr) strcpy(p, "handle"); else { if(o->toDataHandle()->h_name->length() > objnamez - 1) sprintf(p, "%.*s...", objnamez - 4, o->toDataHandle()->h_name->cstr()); else sprintf(p, "%s", o->toDataHandle()->h_name->cstr()); } } size_t DataHandle::TypeInfo::mark(Object* o) { auto mem = TypeData::mark(o); if(o->toSuperObject()->o_super != nullptr) mem += o->toSuperObject()->o_super->mark(); if(o->toDataHandle()->h_name != nullptr) mem += o->toDataHandle()->h_name->mark(); return mem; } int DataHandle::TypeInfo::compare(Object* o1, Object* o2) { return ( (o1->toDataHandle()->h_ptr != o2->toDataHandle()->h_ptr) || (o1->toDataHandle()->h_name != o2->toDataHandle()->h_name) ); } unsigned long DataHandle::TypeInfo::hash(Object* o) { return ICI_PTR_HASH(o->toDataHandle()->h_ptr) ^ ICI_PTR_HASH(o->toDataHandle()->h_name); } Object* DataHandle::TypeInfo::fetch(Object* o, Object* k) { DataHandle* h; Object* r; h = o->toDataHandle(); if(h->h_member_map != nullptr && !o->hasFlag(DataHandle::CLOSED)) { Object* id; if((id = h->h_member_map->fetch(k)) == nullptr) return nullptr; if(id->isNativeFunc()) return id; if(id->isIntNum()) { r = nullptr; if((*h->h_member_intf)(h->h_ptr, id->toIntNum()->i_value, nullptr, &r)) return nullptr; if(r != nullptr) return r; } } if(h->h_general_intf != nullptr) { r = nullptr; if((*h->h_general_intf)(h, k, nullptr, &r)) return nullptr; if(r != nullptr) return r; } if(!o->hasSuper() || o->toDataHandle()->o_super == nullptr) return fetch_fail(o, k); return o->toDataHandle()->o_super->fetch(k); } /* * Do a fetch where we are the super of some other Object that is * trying to satisfy a fetch. Don't regard the item k as being present * unless it really is. Return -1 on error, 0 if it was not found, * and 1 if was found. If found, the value is stored in *v. * * If not nullptr, b is a struct that was the base element of this * assignment. This is used to mantain the lookup lookaside mechanism. */ int DataHandle::TypeInfo::fetchSuper(Object* o, Object* k, Object** v, Map* b) { if(!o->hasSuper()) { fetch_fail(o, k); return 1; } if(o->toDataHandle()->o_super == nullptr) return 0; return o->toDataHandle()->o_super->fetchSuper(k, v, b); } Object* DataHandle::TypeInfo::fetchBase(Object* o, Object* k) { DataHandle* h; Object* r; h = o->toDataHandle(); if(h->h_member_map != nullptr && !o->hasFlag(DataHandle::CLOSED)) { Object* id; if((id = h->h_member_map->fetch(k)) == nullptr) return nullptr; if(id->isNativeFunc()) return id; if(id->isIntNum()) { r = nullptr; if((*h->h_member_intf)(h->h_ptr, id->toIntNum()->i_value, nullptr, &r)) return nullptr; if(r != nullptr) return r; } } if(h->h_general_intf != nullptr) { r = nullptr; if((*h->h_general_intf)(h, k, nullptr, &r)) return nullptr; if(r != nullptr) return r; } if(!o->hasSuper()) return fetch_fail(o, k); if(!o->hasFlag(DataHandle::HAS_PRIV_MAP)) return null; return h->o_super->fetchBase(k); } /* * Assign a value into a key of Object o, but ignore the super chain. * That is, always assign into the lowest level. Usual error coventions. */ int DataHandle::TypeInfo::assignBase(Object* o, Object* k, Object* v) { DataHandle* h; Object* r; h = o->toDataHandle(); if(h->h_member_map != nullptr && !o->hasFlag(DataHandle::CLOSED)) { Object* id; if((id = h->h_member_map->fetch(k)) == nullptr) return 1; if(id->isIntNum()) { r = nullptr; if((*h->h_member_intf)(h->h_ptr, id->toIntNum()->i_value, v, &r)) return 1; if(r != nullptr) return 0; } } if(h->h_general_intf != nullptr) { r = nullptr; if((*h->h_general_intf)(h, k, v, &r)) return 1; if(r != nullptr) return 0; } if(!o->hasSuper()) return assign_fail(o, k, v); if(!o->hasFlag(DataHandle::HAS_PRIV_MAP)) { SuperObject* s; /* * We don't yet have a private struct to hold our values. * Give ourselves one. * * This operation disturbs the struct-lookup lookaside mechanism. * We invalidate all existing entries by incrementing g_generationversion. */ if((s = createMap()->toSuperObject()) == nullptr) return 1; s->o_super = o->toSuperObject()->o_super; o->toSuperObject()->o_super = s; g_generationversion++; o->setFlag(DataHandle::HAS_PRIV_MAP); } return o->toSuperObject()->o_super->assignBase(k, v); } /* * Assign to key k of the Object o the value v. Return 1 on error, else 0. * See the comment on t_assign() in Object.h. */ int DataHandle::TypeInfo::assign(Object* o, Object* k, Object* v) { DataHandle* h; Object* r; h = o->toDataHandle(); r = nullptr; if(h->h_member_map != nullptr && !o->hasFlag(DataHandle::CLOSED)) { Object* id; if((id = h->h_member_map->fetch(k)) == nullptr) return 1; if(id->isIntNum()) { if((*h->h_member_intf)(h->h_ptr, id->toIntNum()->i_value, v, &r)) return 1; if(r != nullptr) return 0; } } if(h->h_general_intf != nullptr) { r = nullptr; if((*h->h_general_intf)(h, k, v, &r)) return 1; if(r != nullptr) return 0; } if(!o->hasSuper()) return assign_fail(o, k, v); if(o->hasFlag(DataHandle::HAS_PRIV_MAP)) return h->o_super->assign(k, v); /* * We don't have a base struct of our own yet. Try the super. */ if(o->toDataHandle()->o_super != nullptr) { switch(h->o_super->assignSuper(k, v, nullptr)) { case -1: return 1; case 1: return 0; } } /* * We failed to assign the value to a super, and we haven't yet got * a private struct. Assign it to the base. This will create our * private struct. */ return assignBase(o, k, v); } /* * Do an assignment where we are the super of some other Object that * is trying to satisfy an assign. Don't regard the item k as being * present unless it really is. Return -1 on error, 0 if not found * and 1 if the assignment was completed. * * If 0 is returned, nothing has been modified during the * operation of this function. * * If not nullptr, b is a struct that was the base element of this * assignment. This is used to mantain the lookup lookaside mechanism. */ int DataHandle::TypeInfo::assignSuper(Object* o, Object* k, Object* v, Map* b) { if(!o->hasSuper()) return assign_fail(o, k, v); if(o->toDataHandle()->o_super == nullptr) return 0; return o->toDataHandle()->o_super->assignSuper(k, v, b); } /* * Free this Object and associated memory (but not other objects). * See the comments on t_free() in Object.h. */ void DataHandle::TypeInfo::free(Object* o) { if(o->toDataHandle()->h_pre_free != nullptr) (*o->toDataHandle()->h_pre_free)(o->toDataHandle()); freeType(o); } }// namespace ici
31.864629
127
0.509799
[ "object" ]
1fcd311718ccab7c2223b0e7aa780a91f008d8ad
1,759
cpp
C++
code_blocks/checking_least_square_method/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
12
2020-01-20T14:22:18.000Z
2022-01-26T04:41:36.000Z
code_blocks/checking_least_square_method/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
1
2020-05-23T07:35:03.000Z
2020-05-23T07:35:03.000Z
code_blocks/checking_least_square_method/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
9
2019-11-02T19:01:55.000Z
2021-07-08T21:51:44.000Z
#include <iostream> #include "xtechnical_regression_analysis.hpp" #include <array> #include <vector> int main() { std::cout << "Hello world!" << std::endl; double coeff[3]; double test_data[6][2] = { {1,2}, {2,3}, {3,4}, {4,5}, {5,6}, {6,7}, }; std::array<double[2],6> test_data2 = { 1,2,3,4,5,6, 2,3,4,5,6,7 }; std::vector<std::array<double,2>> test_data3; test_data3.resize(6); test_data3[0][0] = 1; test_data3[0][1] = 2; test_data3[1][0] = 2; test_data3[1][1] = 3; test_data3[2][0] = 3; test_data3[2][1] = 4; test_data3[3][0] = 4; test_data3[3][1] = 5; test_data3[4][0] = 5; test_data3[4][1] = 6; test_data3[5][0] = 6; test_data3[5][1] = 7; xtechnical_regression_analysis::calc_least_squares_method(coeff, test_data, 6, xtechnical_regression_analysis::LSM_PARABOLA); double in_data = 7; double out_data = xtechnical_regression_analysis::calc_line(coeff, in_data, xtechnical_regression_analysis::LSM_PARABOLA); std::cout << "out_data " << out_data << std::endl; xtechnical_regression_analysis::calc_least_squares_method(coeff, test_data2, 6, xtechnical_regression_analysis::LSM_PARABOLA); out_data = xtechnical_regression_analysis::calc_line(coeff, in_data, xtechnical_regression_analysis::LSM_PARABOLA); std::cout << "out_data " << out_data << std::endl; xtechnical_regression_analysis::calc_least_squares_method(coeff, test_data3, 6, xtechnical_regression_analysis::LSM_PARABOLA); out_data = xtechnical_regression_analysis::calc_line(coeff, in_data, xtechnical_regression_analysis::LSM_PARABOLA); std::cout << "out_data " << out_data << std::endl; return 0; }
33.188679
130
0.656623
[ "vector" ]
1fd525e5fd17f95bdf7a513eec21edb5ad95b2f4
10,913
cpp
C++
src/save_file.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
null
null
null
src/save_file.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
null
null
null
src/save_file.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
null
null
null
#include "../include/save_file.hpp" #include "../include/configurations.hpp" #include <iostream> #include <cstdio> #include <string> #include <stdexcept> #include <cmath> #include <limits> namespace detail { enum class type_tag : int { boolean = 1, double_number = 3, string = 4, table = 5, byte_number = 20, short_number = 21, long_number = 23, long_long_number = 24, float_number = 30, small_string = 31, unknown = 127, end_of_table = -1, }; type_tag get_numeric_type_tag(double value, bool compact) { if (!compact) return type_tag::double_number; auto can_be_int = !std::isnan(value) && !std::isinf(value) && std::trunc(value) == value; if (can_be_int) { if (value <= std::numeric_limits<signed char>().max()) return type_tag::byte_number; else if (value <= std::numeric_limits<short>().max()) return type_tag::short_number; else if (value <= std::numeric_limits<long>().max()) return type_tag::long_number; else if (value <= std::numeric_limits<long long>().max()) return type_tag::long_long_number; } return value <= std::numeric_limits<float>().max() ? type_tag::float_number : type_tag::double_number; } type_tag get_string_type_tag(const std::string& value, bool compact) { if (!compact) return type_tag::string; constexpr auto small_size = std::numeric_limits<unsigned char>().max(); return value.length() <= small_size ? type_tag::small_string : type_tag::string; } type_tag sol_type_to_type_tag(sol::type sol_type, const sol::object& value, bool compact) { switch (sol_type) { case sol::type::boolean: return type_tag::boolean; case sol::type::number: return get_numeric_type_tag(value.as<double>(), compact); case sol::type::string: return get_string_type_tag(value.as<std::string>(), compact); case sol::type::table: return type_tag::table; default: return type_tag::unknown; } } template<typename T> void write(std::ostream& stream, const T& value) { stream.write(reinterpret_cast<const char*>(&value), sizeof(T)); } void write(std::ostream& stream, const std::string& value, type_tag tag) { auto length = value.length(); if (tag == type_tag::small_string) write(stream, static_cast<unsigned char>(length)); else write(stream, length); stream.write(value.c_str(), length); } void write_type_tag(std::ostream& stream, type_tag tag, bool compact) { if (compact) write(stream, static_cast<signed char>(tag)); else write(stream, tag); } template <typename T> T object_to_number(const sol::object& value) { auto double_value = value.as<double>(); return static_cast<T>(double_value); } void write_value(std::ostream& stream, type_tag tag, const sol::object& value) { switch (tag) { case type_tag::boolean: write(stream, value.as<bool>()); break; case type_tag::string: case type_tag::small_string: write(stream, value.as<std::string>(), tag); break; case type_tag::byte_number: write(stream, object_to_number<signed char>(value)); break; case type_tag::short_number: write(stream, object_to_number<short>(value)); break; case type_tag::long_number: write(stream, object_to_number<long>(value)); break; case type_tag::long_long_number: write(stream, object_to_number<long long>(value)); break; case type_tag::float_number: write(stream, object_to_number<float>(value)); break; case type_tag::double_number: write(stream, value.as<double>()); break; } } template<typename T> void read(std::istream& stream, T& value){ stream.read(reinterpret_cast<char*>(&value), sizeof(T)); } void read(std::istream& stream, std::string& value, type_tag tag) { std::string::size_type length; if (tag == type_tag::small_string) { unsigned char uc_length; read(stream, uc_length); length = static_cast<std::string::size_type>(uc_length); } else { read(stream, length); } value = std::string(length, ' '); stream.read(&value[0], length); } void read_type_tag(std::istream& stream, type_tag& tag, bool compact) { if (compact) { signed char type; read(stream, type); tag = static_cast<type_tag>(type); } else { read(stream, tag); } } template <typename T> sol::object read_numeric_value(std::istream& stream, const sol::state& state) { T temp{}; read(stream, temp); return sol::make_object(state, static_cast<double>(temp)); } sol::object read_value(std::istream& stream, const sol::state& state, type_tag tag) { std::string temp_str; bool temp_bool; switch (tag) { case type_tag::boolean: read(stream, temp_bool); return sol::make_object(state, temp_bool); case type_tag::byte_number: return read_numeric_value<signed char>(stream, state); case type_tag::short_number: return read_numeric_value<short>(stream, state); case type_tag::long_number: return read_numeric_value<long>(stream, state); case type_tag::long_long_number: return read_numeric_value<long long>(stream, state); case type_tag::float_number: return read_numeric_value<float>(stream, state); case type_tag::double_number: return read_numeric_value<double>(stream, state); case type_tag::string: case type_tag::small_string: read(stream, temp_str, tag); return sol::make_object(state, temp_str); default: throw std::runtime_error("Unexpected value type"); } } bool valid_key_type(sol::type type) { return type == sol::type::number || type == sol::type::string; } bool valid_value_type(sol::type type) { return type == sol::type::number || type == sol::type::string || type == sol::type::boolean || type == sol::type::table; } void write_object(std::ostream& stream, sol::table obj, bool compact) { for (auto& kv : obj) { const auto& key = kv.first; const auto& val = kv.second; auto sol_key_type = key.get_type(); auto sol_val_type = val.get_type(); if (!valid_key_type(sol_key_type)) continue; if (!valid_value_type(sol_val_type)) continue; // Write the key auto key_type = sol_type_to_type_tag(sol_key_type, key, compact); write_type_tag(stream, key_type, compact); write_value(stream, key_type, key); // Write the value auto val_type = sol_type_to_type_tag(sol_val_type, val, compact); write_type_tag(stream, val_type, compact); switch(sol_val_type) { case sol::type::boolean: case sol::type::number: case sol::type::string: write_value(stream, val_type, val); break; case sol::type::table: write_object(stream, val, compact); break; default: throw std::runtime_error("Invalid object key"); } } // Write end of table marker if (compact) write(stream, static_cast<signed char>(type_tag::end_of_table)); else write(stream, type_tag::end_of_table); } sol::table read_object(std::istream& stream, const sol::state& state, bool compact); sol::table read_object(std::istream& stream, const sol::state& state, bool compact) { sol::table obj(state, sol::create); type_tag tag; while (stream) { // Read the key read_type_tag(stream, tag, compact); if (tag == type_tag::end_of_table) return obj; auto key = read_value(stream, state, tag); if (!key.valid()) throw std::runtime_error("Invalid object key"); // Read the value read_type_tag(stream, tag, compact); auto val = tag == type_tag::table ? read_object(stream, state, compact) : read_value(stream, state, tag); // Set key and value obj[key] = val; } return obj; } } Save_File::Save_File(sol::state& state, bool header_only, bool compact) : state(state), data(state, sol::create), header(state, sol::create), header_only(header_only), compact(compact), valid(false) {} Save_File::Save_File(sol::state& state, const sol::table& data, std::optional<sol::table> header, bool compact) : state(state), data(data), header(header.value_or(sol::table(state, sol::create))), header_only(false), compact(compact), valid(true) {} std::ostream& operator<<(std::ostream& stream, Save_File& save_file) { save_file.valid = false; detail::write(stream, Configurations::get<unsigned int>("debug.save-signature")); detail::write_object(stream, save_file.header, save_file.compact); detail::write_object(stream, save_file.data, save_file.compact); save_file.valid = true; return stream; } std::istream& operator>>(std::istream& stream, Save_File& save_file) { save_file.valid = false; unsigned int signature; detail::read(stream, signature); if (signature != Configurations::get<unsigned int>("debug.save-signature")) { throw std::runtime_error("Invalid file signature"); } auto first_table = detail::read_object(stream, save_file.state, save_file.compact); if (save_file.header_only) { save_file.header = first_table; save_file.valid = true; return stream; } if (stream.peek() != EOF) { // Headers are optional since they were introduced later save_file.header = first_table; save_file.data = detail::read_object(stream, save_file.state, save_file.compact); } else { save_file.data = first_table; } save_file.valid = true; return stream; }
32.576119
113
0.582333
[ "object" ]
1fe26be297467c1acd2820157def00ea880c459e
2,814
cpp
C++
Competitive Programming/System Design/Kth Ancestor of a Tree Node.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
Competitive Programming/System Design/Kth Ancestor of a Tree Node.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
Competitive Programming/System Design/Kth Ancestor of a Tree Node.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
/* https://leetcode.com/problems/kth-ancestor-of-a-tree-node/ 1483. Kth Ancestor of a Tree Node Hard 761 73 Add to List Share You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node. The kth ancestor of a tree node is the kth node in the path from that node to the root node. Implement the TreeAncestor class: TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array. int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1. Example 1: Input ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] Output [null, 1, 0, -1] Explanation TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor Constraints: 1 <= k <= n <= 5 * 104 parent.length == n parent[0] == -1 0 <= parent[i] < n for all 0 < i < n 0 <= node < n There will be at most 5 * 104 queries. */ // Time: ctor: O(n * logh) // get: O(logh) // Space: O(n * logh) // binary jump solution (frequently used in competitive programming) class TreeAncestor { public: TreeAncestor(int n, vector<int> &parent) { vector<int> q; for (const auto &p : parent) { parent_.emplace_back(vector<int>(p != -1, p)); if (p != -1) { q.emplace_back(parent_.size() - 1); } } for (int i = 0; !q.empty(); ++i) { vector<int> new_q; for (const auto &curr : q) { if (!(i < parent_[parent_[curr][i]].size())) { continue; } parent_[curr].emplace_back(parent_[parent_[curr][i]][i]); new_q.emplace_back(curr); } q = move(new_q); } } int getKthAncestor(int node, int k) { for (; k; k -= k & ~(k - 1)) { int i = __builtin_ctz(k & ~(k - 1)); if (!(i < parent_[node].size())) { return -1; } node = parent_[node][i]; } return node; } private: vector<vector<int> > parent_; }; /** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor* obj = new TreeAncestor(n, parent); * int param_1 = obj->getKthAncestor(node,k); */
26.8
209
0.571073
[ "object", "vector" ]
9501c9a085fd07f29d99d6409b23c56203af179a
2,826
cc
C++
Code/Components/Services/correlatorsim/current/simplayback/BaselineMap.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Services/correlatorsim/current/simplayback/BaselineMap.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/correlatorsim/current/simplayback/BaselineMap.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file BaselineMap.cc /// /// @copyright (c) 2012 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Ben Humphreys <ben.humphreys@csiro.au> // Include own header file first #include "BaselineMap.h" // Include package level header file #include "askap_correlatorsim.h" // System includes #include <map> #include <stdint.h> // ASKAPsoft includes #include "askap/AskapError.h" #include "askap/AskapUtil.h" #include "Common/ParameterSet.h" #include "casacore/measures/Measures/Stokes.h" // Using using namespace askap; using namespace askap::utility; using namespace askap::cp; using namespace casa; BaselineMap::BaselineMap(const LOFAR::ParameterSet& parset) { const vector<uint32_t> ids = parset.getUint32Vector("baselineids", true); for (vector<uint32_t>::const_iterator it = ids.begin(); it != ids.end(); ++it) { const uint32_t id = *it; if (!parset.isDefined(toString(id))) { ASKAPTHROW(AskapError, "Baseline mapping for id " << id << " not present"); } const vector<string> tuple = parset.getStringVector(toString(id)); if (tuple.size() != 3) { ASKAPTHROW(AskapError, "Baseline mapping for id " << id << " is malformed"); } BaselineMapKey bkey; bkey.antenna1 = fromString<uint32_t>(tuple[0]); bkey.antenna2 = fromString<uint32_t>(tuple[1]); bkey.stokes = Stokes::type(tuple[2]); itsMap[bkey] = id; } } int32_t BaselineMap::operator()(int32_t antenna1, int32_t antenna2, const casa::Stokes::StokesTypes& stokes) const { BaselineMapKey key; key.antenna1 = antenna1; key.antenna2 = antenna2; key.stokes = stokes; std::map<BaselineMapKey, int32_t>::const_iterator it = itsMap.find(key); if (it == itsMap.end()) { return -1; } else { return it->second; } }
32.113636
114
0.682944
[ "vector" ]
950dc764aaf458c2996975894378991d6a2b36f9
11,309
cpp
C++
code/client/build-Client-Desktop_Qt_5_11_1_GCC_64bit-Release/moc_inbox.cpp
LLFKirito/FengFeng-Mail-System
9ff6f0fe0190c720b637b92793dda306337b0c13
[ "MIT" ]
3
2019-03-08T14:34:54.000Z
2020-09-14T06:48:19.000Z
code/client/build-Client-Desktop_Qt_5_11_1_GCC_64bit-Release/moc_inbox.cpp
LLFKirito/FengFeng-Mail-System
9ff6f0fe0190c720b637b92793dda306337b0c13
[ "MIT" ]
null
null
null
code/client/build-Client-Desktop_Qt_5_11_1_GCC_64bit-Release/moc_inbox.cpp
LLFKirito/FengFeng-Mail-System
9ff6f0fe0190c720b637b92793dda306337b0c13
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'inbox.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../Client/inbox.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'inbox.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Inbox_t { QByteArrayData data[27]; char stringdata0[428]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Inbox_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Inbox_t qt_meta_stringdata_Inbox = { { QT_MOC_LITERAL(0, 0, 5), // "Inbox" QT_MOC_LITERAL(1, 6, 14), // "InboxGoManager" QT_MOC_LITERAL(2, 21, 0), // "" QT_MOC_LITERAL(3, 22, 12), // "InboxGoLogin" QT_MOC_LITERAL(4, 35, 14), // "InboxGoContact" QT_MOC_LITERAL(5, 50, 13), // "InboxGoDrafts" QT_MOC_LITERAL(6, 64, 14), // "InboxGoDustbin" QT_MOC_LITERAL(7, 79, 11), // "InboxGoSend" QT_MOC_LITERAL(8, 91, 11), // "InboxGoEdit" QT_MOC_LITERAL(9, 103, 17), // "on_Logout_clicked" QT_MOC_LITERAL(10, 121, 18), // "on_Logout_released" QT_MOC_LITERAL(11, 140, 16), // "on_Help_released" QT_MOC_LITERAL(12, 157, 15), // "on_Help_clicked" QT_MOC_LITERAL(13, 173, 16), // "on_Write_clicked" QT_MOC_LITERAL(14, 190, 17), // "on_Write_released" QT_MOC_LITERAL(15, 208, 18), // "on_Inbox_2_clicked" QT_MOC_LITERAL(16, 227, 19), // "on_Inbox_2_released" QT_MOC_LITERAL(17, 247, 18), // "on_Contact_clicked" QT_MOC_LITERAL(18, 266, 19), // "on_Contact_released" QT_MOC_LITERAL(19, 286, 15), // "on_Send_clicked" QT_MOC_LITERAL(20, 302, 16), // "on_Send_released" QT_MOC_LITERAL(21, 319, 17), // "on_Drafts_clicked" QT_MOC_LITERAL(22, 337, 18), // "on_Drafts_released" QT_MOC_LITERAL(23, 356, 18), // "on_Dustbin_clicked" QT_MOC_LITERAL(24, 375, 19), // "on_Dustbin_released" QT_MOC_LITERAL(25, 395, 9), // "InboxShow" QT_MOC_LITERAL(26, 405, 22) // "on_btn_refresh_clicked" }, "Inbox\0InboxGoManager\0\0InboxGoLogin\0" "InboxGoContact\0InboxGoDrafts\0" "InboxGoDustbin\0InboxGoSend\0InboxGoEdit\0" "on_Logout_clicked\0on_Logout_released\0" "on_Help_released\0on_Help_clicked\0" "on_Write_clicked\0on_Write_released\0" "on_Inbox_2_clicked\0on_Inbox_2_released\0" "on_Contact_clicked\0on_Contact_released\0" "on_Send_clicked\0on_Send_released\0" "on_Drafts_clicked\0on_Drafts_released\0" "on_Dustbin_clicked\0on_Dustbin_released\0" "InboxShow\0on_btn_refresh_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Inbox[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 25, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 7, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 139, 2, 0x06 /* Public */, 3, 0, 142, 2, 0x06 /* Public */, 4, 1, 143, 2, 0x06 /* Public */, 5, 1, 146, 2, 0x06 /* Public */, 6, 1, 149, 2, 0x06 /* Public */, 7, 1, 152, 2, 0x06 /* Public */, 8, 1, 155, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 9, 0, 158, 2, 0x08 /* Private */, 10, 0, 159, 2, 0x08 /* Private */, 11, 0, 160, 2, 0x08 /* Private */, 12, 0, 161, 2, 0x08 /* Private */, 13, 0, 162, 2, 0x08 /* Private */, 14, 0, 163, 2, 0x08 /* Private */, 15, 0, 164, 2, 0x08 /* Private */, 16, 0, 165, 2, 0x08 /* Private */, 17, 0, 166, 2, 0x08 /* Private */, 18, 0, 167, 2, 0x08 /* Private */, 19, 0, 168, 2, 0x08 /* Private */, 20, 0, 169, 2, 0x08 /* Private */, 21, 0, 170, 2, 0x08 /* Private */, 22, 0, 171, 2, 0x08 /* Private */, 23, 0, 172, 2, 0x08 /* Private */, 24, 0, 173, 2, 0x08 /* Private */, 25, 1, 174, 2, 0x08 /* Private */, 26, 0, 177, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, QMetaType::QString, 2, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, 2, QMetaType::Void, 0 // eod }; void Inbox::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Inbox *_t = static_cast<Inbox *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->InboxGoManager((*reinterpret_cast< QString(*)>(_a[1]))); break; case 1: _t->InboxGoLogin(); break; case 2: _t->InboxGoContact((*reinterpret_cast< QString(*)>(_a[1]))); break; case 3: _t->InboxGoDrafts((*reinterpret_cast< QString(*)>(_a[1]))); break; case 4: _t->InboxGoDustbin((*reinterpret_cast< QString(*)>(_a[1]))); break; case 5: _t->InboxGoSend((*reinterpret_cast< QString(*)>(_a[1]))); break; case 6: _t->InboxGoEdit((*reinterpret_cast< QString(*)>(_a[1]))); break; case 7: _t->on_Logout_clicked(); break; case 8: _t->on_Logout_released(); break; case 9: _t->on_Help_released(); break; case 10: _t->on_Help_clicked(); break; case 11: _t->on_Write_clicked(); break; case 12: _t->on_Write_released(); break; case 13: _t->on_Inbox_2_clicked(); break; case 14: _t->on_Inbox_2_released(); break; case 15: _t->on_Contact_clicked(); break; case 16: _t->on_Contact_released(); break; case 17: _t->on_Send_clicked(); break; case 18: _t->on_Send_released(); break; case 19: _t->on_Drafts_clicked(); break; case 20: _t->on_Drafts_released(); break; case 21: _t->on_Dustbin_clicked(); break; case 22: _t->on_Dustbin_released(); break; case 23: _t->InboxShow((*reinterpret_cast< QString(*)>(_a[1]))); break; case 24: _t->on_btn_refresh_clicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoManager)) { *result = 0; return; } } { using _t = void (Inbox::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoLogin)) { *result = 1; return; } } { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoContact)) { *result = 2; return; } } { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoDrafts)) { *result = 3; return; } } { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoDustbin)) { *result = 4; return; } } { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoSend)) { *result = 5; return; } } { using _t = void (Inbox::*)(QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Inbox::InboxGoEdit)) { *result = 6; return; } } } } QT_INIT_METAOBJECT const QMetaObject Inbox::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Inbox.data, qt_meta_data_Inbox, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Inbox::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Inbox::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Inbox.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int Inbox::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 25) qt_static_metacall(this, _c, _id, _a); _id -= 25; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 25) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 25; } return _id; } // SIGNAL 0 void Inbox::InboxGoManager(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void Inbox::InboxGoLogin() { QMetaObject::activate(this, &staticMetaObject, 1, nullptr); } // SIGNAL 2 void Inbox::InboxGoContact(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void Inbox::InboxGoDrafts(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } // SIGNAL 4 void Inbox::InboxGoDustbin(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 4, _a); } // SIGNAL 5 void Inbox::InboxGoSend(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 5, _a); } // SIGNAL 6 void Inbox::InboxGoEdit(QString _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 6, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
34.904321
96
0.585905
[ "object" ]
95130062d3788fcd6364aeccc7b30d0c6e925ac3
13,441
cpp
C++
libs/application/src/xcb/window.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/application/src/xcb/window.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/application/src/xcb/window.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include "window.h" #include <yttrium/image/image.h> #include "../key_codes.h" #include "../window_callbacks.h" #include <seir_base/int_utils.hpp> #include <algorithm> #include <cstring> #include <string> #include <xcb/xcb_image.h> #define explicit explicit_ // https://gitlab.freedesktop.org/xorg/lib/libxcb/issues/23 #include <xcb/xkb.h> #undef explicit #include <xkbcommon/xkbcommon.h> #include <xkbcommon/xkbcommon-x11.h> namespace { constexpr Yt::Key key_from_button(xcb_button_t button) noexcept { switch (button) { case XCB_BUTTON_INDEX_1: return Yt::Key::Mouse1; case XCB_BUTTON_INDEX_2: return Yt::Key::Mouse2; case XCB_BUTTON_INDEX_3: return Yt::Key::Mouse3; case XCB_BUTTON_INDEX_4: return Yt::Key::Mouse4; case XCB_BUTTON_INDEX_5: return Yt::Key::Mouse5; default: return Yt::Key::None; } } } namespace Yt { class WindowBackend::EmptyCursor { public: EmptyCursor(xcb_connection_t* connection, xcb_window_t window) : _connection{ connection } , _cursor{ ::xcb_generate_id(_connection) } { uint8_t data = 0; const auto pixmap = ::xcb_create_pixmap_from_bitmap_data(_connection, window, &data, 1, 1, 1, 0, 0, nullptr); ::xcb_create_cursor(_connection, _cursor, pixmap, pixmap, 0, 0, 0, 0, 0, 0, 0, 0); ::xcb_free_pixmap(_connection, pixmap); ::xcb_change_window_attributes(_connection, window, XCB_CW_CURSOR, &_cursor); } ~EmptyCursor() noexcept { ::xcb_free_cursor(_connection, _cursor); } private: xcb_connection_t* const _connection; const xcb_cursor_t _cursor; }; class WindowBackend::Keyboard { public: explicit Keyboard(xcb_connection_t* connection) : _connection{ connection } { if (!::xkb_x11_setup_xkb_extension(_connection, XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION, XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS, nullptr, nullptr, &_base_event, nullptr)) throw std::runtime_error{ "Unable to setup XKB" }; constexpr uint16_t selected_events = XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_STATE_NOTIFY; // Mask of all valid map parts. constexpr uint16_t selected_map_parts = XCB_XKB_MAP_PART_KEY_TYPES | XCB_XKB_MAP_PART_KEY_SYMS | XCB_XKB_MAP_PART_MODIFIER_MAP | XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS | XCB_XKB_MAP_PART_KEY_ACTIONS | XCB_XKB_MAP_PART_KEY_BEHAVIORS | XCB_XKB_MAP_PART_VIRTUAL_MODS | XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP; const auto cookie = ::xcb_xkb_select_events_aux_checked(_connection, XCB_XKB_ID_USE_CORE_KBD, selected_events, 0, selected_events, selected_map_parts, selected_map_parts, nullptr); seir::CPtr<xcb_generic_error_t, ::free> error{ ::xcb_request_check(_connection, cookie) }; if (error) throw std::runtime_error{ "Unable to select XKB events" }; _keyboard_id = ::xkb_x11_get_core_keyboard_device_id(_connection); if (_keyboard_id == -1) throw std::runtime_error{ "Unable to get XKB core keyboard device ID" }; _context.reset(::xkb_context_new(XKB_CONTEXT_NO_FLAGS)); if (!_context) throw std::runtime_error{ "Unable to create XKB context" }; reset_keymap(); } std::string_view keycode_to_text(xcb_keycode_t keycode) { const auto size = static_cast<size_t>(::xkb_state_key_get_utf8(_state.get(), keycode, nullptr, 0)); if (!size) return {}; if (size > _keycode_text_buffer.size()) _keycode_text_buffer.resize(size); ::xkb_state_key_get_utf8(_state.get(), keycode, _keycode_text_buffer.data(), size + 1); const auto begin = _keycode_text_buffer.begin(); const auto end = std::remove_if(begin, begin + static_cast<std::string::difference_type>(size), [](char c) { return seir::toUnsigned(c) < 32 || c == 127; }); return { _keycode_text_buffer.data(), static_cast<size_t>(end - begin) }; } bool process_event(int event_type, const xcb_generic_event_t* event) { // There's only one X event for all XKB events (see https://bugs.freedesktop.org/show_bug.cgi?id=51295). if (event_type != _base_event) return false; // xkbcommon doesn't have anything like XkbAnyEvent or XkbEvent. union xcb_xkb_event_t { struct { // cppcheck-suppress unusedStructMember uint8_t response_type; uint8_t xkbType; // cppcheck-suppress unusedStructMember uint16_t sequence; // cppcheck-suppress unusedStructMember xcb_timestamp_t time; uint8_t deviceID; } any; xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify; xcb_xkb_map_notify_event_t map_notify; xcb_xkb_state_notify_event_t state_notify; }; const auto e = reinterpret_cast<const xcb_xkb_event_t*>(event); if (e->any.deviceID == _keyboard_id) { switch (e->any.xkbType) { case XCB_XKB_NEW_KEYBOARD_NOTIFY: case XCB_XKB_MAP_NOTIFY: reset_keymap(); break; case XCB_XKB_STATE_NOTIFY: ::xkb_state_update_mask(_state.get(), e->state_notify.baseMods, e->state_notify.latchedMods, e->state_notify.lockedMods, seir::toUnsigned(e->state_notify.baseGroup), seir::toUnsigned(e->state_notify.latchedGroup), e->state_notify.lockedGroup); break; } } return true; } private: void reset_keymap() { decltype(_keymap) keymap{ ::xkb_x11_keymap_new_from_device(_context.get(), _connection, _keyboard_id, XKB_KEYMAP_COMPILE_NO_FLAGS) }; if (!keymap) throw std::runtime_error{ "Unable to create XKB keymap" }; decltype(_state) state{ ::xkb_x11_state_new_from_device(keymap.get(), _connection, _keyboard_id) }; if (!state) throw std::runtime_error{ "Unable to create XKB state" }; std::swap(_keymap, keymap); std::swap(_state, state); } private: xcb_connection_t* const _connection; uint8_t _base_event = 0; int32_t _keyboard_id = -1; seir::CPtr<xkb_context, ::xkb_context_unref> _context; seir::CPtr<xkb_keymap, ::xkb_keymap_unref> _keymap; seir::CPtr<xkb_state, ::xkb_state_unref> _state; std::string _keycode_text_buffer; }; WindowBackend::WindowBackend(WindowBackendCallbacks& callbacks) : _callbacks{ callbacks } { _keyboard = std::make_unique<Keyboard>(_application.connection()); _window = ::xcb_generate_id(_application.connection()); const uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; const uint32_t list[]{ _application.screen()->black_pixel, XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_FOCUS_CHANGE, }; ::xcb_create_window(_application.connection(), XCB_COPY_FROM_PARENT, _window, _application.screen()->root, 0, 0, _application.screen()->width_in_pixels, _application.screen()->height_in_pixels, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, _application.screen()->root_visual, mask, list); ::xcb_change_property(_application.connection(), XCB_PROP_MODE_REPLACE, _window, _wm_protocols->atom, XCB_ATOM_ATOM, 32, 1, &_wm_delete_window->atom); _empty_cursor = std::make_unique<EmptyCursor>(_application.connection(), _window); { const auto net_wm_state = make_atom("_NET_WM_STATE"); const auto net_wm_state_fullscreen = make_atom("_NET_WM_STATE_FULLSCREEN"); ::xcb_change_property(_application.connection(), XCB_PROP_MODE_REPLACE, _window, net_wm_state->atom, XCB_ATOM_ATOM, 32, 1, &net_wm_state_fullscreen->atom); } ::xcb_flush(_application.connection()); } WindowBackend::~WindowBackend() noexcept { close(); } void WindowBackend::close() noexcept { if (_window == XCB_WINDOW_NONE) return; ::xcb_destroy_window(_application.connection(), _window); ::xcb_flush(_application.connection()); _window = XCB_WINDOW_NONE; } bool WindowBackend::get_cursor(Point& cursor) { if (_window == XCB_WINDOW_NONE) return false; const seir::CPtr<xcb_query_pointer_reply_t, ::free> reply{ ::xcb_query_pointer_reply(_application.connection(), ::xcb_query_pointer(_application.connection(), _window), nullptr) }; if (!reply) return false; cursor = { reply->win_x, reply->win_y }; return true; } bool WindowBackend::process_events() { const auto do_key_event = [this](Key key, bool pressed, bool autorepeat, uint16_t state) { if (key == Key::None) return; Flags<KeyEvent::Modifier> modifiers; if (state & XCB_MOD_MASK_SHIFT) modifiers |= KeyEvent::Modifier::Shift; if (state & XCB_MOD_MASK_CONTROL) modifiers |= KeyEvent::Modifier::Control; if (state & XCB_MOD_MASK_1) modifiers |= KeyEvent::Modifier::Alt; _callbacks.on_key_event(key, pressed, autorepeat, modifiers); }; if (_window == XCB_WINDOW_NONE) return false; _events.clear(); for (bool blocking = !_size;;) { P_Event event{ blocking ? ::xcb_wait_for_event(_application.connection()) : ::xcb_poll_for_event(_application.connection()) }; if (!event) break; event->response_type &= 0x7f; if (blocking && event->response_type == XCB_CONFIGURE_NOTIFY) blocking = false; _events.emplace_back(std::move(event)); } if (::xcb_connection_has_error(_application.connection())) return false; bool pending_autorepeat = false; for (std::size_t i = 0; i < _events.size(); ++i) { const auto* const event = _events[i].get(); switch (event->response_type) { case XCB_KEY_PRESS: { const auto e = reinterpret_cast<const xcb_key_press_event_t*>(event); do_key_event(map_linux_key_code(e->detail), true, std::exchange(pending_autorepeat, false), e->state); const auto text = _keyboard->keycode_to_text(e->detail); if (!text.empty()) _callbacks.on_text_input(text); } break; case XCB_KEY_RELEASE: { const auto e = reinterpret_cast<const xcb_key_release_event_t*>(event); if (i + 1 < _events.size() && _events[i + 1]->response_type == XCB_KEY_PRESS) if (const auto n = reinterpret_cast<const xcb_key_press_event_t*>(_events[i + 1].get()); n->detail == e->detail && n->time == e->time && n->event == e->event && n->state == e->state) { pending_autorepeat = true; break; } do_key_event(map_linux_key_code(e->detail), false, false, e->state); } break; case XCB_BUTTON_PRESS: { const auto e = reinterpret_cast<const xcb_button_press_event_t*>(event); do_key_event(::key_from_button(e->detail), true, false, e->state); } break; case XCB_BUTTON_RELEASE: { const auto e = reinterpret_cast<const xcb_button_release_event_t*>(event); do_key_event(::key_from_button(e->detail), false, false, e->state); } break; case XCB_FOCUS_IN: case XCB_FOCUS_OUT: _callbacks.on_focus_event(event->response_type == XCB_FOCUS_IN); break; case XCB_CONFIGURE_NOTIFY: { const auto e = reinterpret_cast<const xcb_configure_notify_event_t*>(event); _size.emplace(e->width, e->height); } _callbacks.on_resize_event(*_size); break; case XCB_CLIENT_MESSAGE: if (const auto e = reinterpret_cast<const xcb_client_message_event_t*>(event); e->type == _wm_protocols->atom && e->data.data32[0] == _wm_delete_window->atom) { close(); return false; } break; default: _keyboard->process_event(event->response_type, event); } } return true; } bool WindowBackend::set_cursor(const Point& cursor) { if (_window == XCB_WINDOW_NONE) return false; ::xcb_warp_pointer(_application.connection(), XCB_WINDOW_NONE, _window, 0, 0, 0, 0, static_cast<int16_t>(cursor._x), static_cast<int16_t>(cursor._y)); ::xcb_flush(_application.connection()); return true; } void WindowBackend::set_icon(const Image& icon) { if (_window == XCB_WINDOW_NONE) return; const auto property_size = 2 + icon.info().width() * icon.info().height(); const auto property_buffer = std::make_unique<uint32_t[]>(property_size); property_buffer[0] = static_cast<uint32_t>(icon.info().width()); property_buffer[1] = static_cast<uint32_t>(icon.info().height()); if (!Image::transform(icon.info(), icon.data(), { icon.info().width(), icon.info().height(), PixelFormat::Bgra32, ImageOrientation::XRightYDown }, &property_buffer[2])) return; const auto net_wm_icon = make_atom("_NET_WM_ICON"); ::xcb_change_property(_application.connection(), XCB_PROP_MODE_REPLACE, _window, net_wm_icon->atom, XCB_ATOM_CARDINAL, 32, static_cast<uint32_t>(property_size), property_buffer.get()); ::xcb_flush(_application.connection()); } void WindowBackend::set_title(const std::string& title) { if (_window == XCB_WINDOW_NONE) return; const auto net_wm_name = make_atom("_NET_WM_NAME"); const auto utf8_string = make_atom("UTF8_STRING"); ::xcb_change_property(_application.connection(), XCB_PROP_MODE_REPLACE, _window, net_wm_name->atom, utf8_string->atom, 8, static_cast<uint32_t>(title.size()), title.data()); ::xcb_flush(_application.connection()); } void WindowBackend::show() { if (_window == XCB_WINDOW_NONE) return; ::xcb_map_window(_application.connection(), _window); ::xcb_flush(_application.connection()); } void WindowBackend::swap_buffers() { static_assert(!YTTRIUM_RENDERER_OPENGL, "Not implemented"); } WindowBackend::P_Atom WindowBackend::make_atom(std::string_view name) { return P_Atom{ ::xcb_intern_atom_reply(_application.connection(), ::xcb_intern_atom(_application.connection(), 0, static_cast<uint16_t>(name.size()), name.data()), nullptr) }; } }
35.002604
187
0.726955
[ "transform" ]
9514ed40d0f0b5c46ce3ad063a7d2ca619ab33de
11,778
cpp
C++
source/Board.cpp
yotam5/socket_chess_sfml
1bfc54085ab12758f8f524b7b01354f6565d074c
[ "Unlicense" ]
null
null
null
source/Board.cpp
yotam5/socket_chess_sfml
1bfc54085ab12758f8f524b7b01354f6565d074c
[ "Unlicense" ]
null
null
null
source/Board.cpp
yotam5/socket_chess_sfml
1bfc54085ab12758f8f524b7b01354f6565d074c
[ "Unlicense" ]
null
null
null
//board class #pragma once #include "../headers/Board.h" //constructor Board::Board(char color) { this->initVariables(); this->initBoard(); this->initTexture(); this->startGame((color == 'w') ? Color::WHITE : Color::BLACK); this->frontPlayer = (color == 'w') ? Color::WHITE : Color::BLACK; //NOTE bruh.... //pointers to kings if (this->frontPlayer == Color::BLACK) { this->kingsPointers[0] = board[0][4]; this->kingsPointers[1] = board[7][4]; } else { this->kingsPointers[0] = board[0][4]; this->kingsPointers[1] = board[7][4]; } } //check if in chess one of the kings bool Board::isInChess(Color color) const { //kings current positions auto currentKingPointer = this->kingsPointers[(color == WHITE) ? 1 : 0]; auto currentKingPos = currentKingPointer->getPositionOnBoard(); //std::cout << "current king pos " << currentKingPos.first << " " << currentKingPos.second << std::endl; for (int i = 0; i < BOARD_LENGTH; i++) { for (int k = 0; k < BOARD_LENGTH; k++) { auto currentPiece = board[i][k]; if (currentPiece == nullptr || currentPiece->getColor() == color) { continue; } auto piecePoses = currentPiece->getPossiblePositions(board); for (auto pos : piecePoses) { //std::cout << pos.first << " " << pos.second << "\n"; if (currentKingPos == pos) { std::cout << "chess" << std::endl; return true; } } } } return false; } //destructor Board::~Board() { for (int i = 0; i < BOARD_SIZE; i++) { for (int k = 0; k < BOARD_SIZE; k++) { delete this->board[i][k]; } } for (auto &texture : this->texturePointer) { delete texture.second; } } //init variables void Board::initVariables() { this->kingsPointers[0] = nullptr; this->kingsPointers[1] = nullptr; this->chess = false; this->currentPlayer = WHITE; this->saveTo = nullptr; this->moveCounter = 0; } //check if availabe bool Board::isEmpty(int row, int column) const { if (row >= 0 && column >= 0 && row <= this->board.size() && column <= this->board.size()) return this->board[row][column] == nullptr; //cuz array else throw std::invalid_argument("ERROR IsEmpty out of range\n"); } //init texture void Board::initTexture() { for (auto pieceName : this->piecesNames) { this->texturePointer[pieceName] = new sf::Texture; if (!this->texturePointer[pieceName]->loadFromFile(this->assertsFolderName + pieceName + ".png")) { throw std::invalid_argument("ERROR LOADING " + pieceName + ".png\n"); } } } //draw void Board::draw(sf::RenderTarget &target) const { for (int i = 0; i < BOARD_SIZE; i++) { for (int k = 0; k < BOARD_SIZE; k++) { if (this->board[i][k] != nullptr) { this->board[i][k]->render(target); } } } } //init game pieces on board void Board::startGame(Color color) { std::array<char, 16> order = { 'r', 'k', 'b', 'Q', 'K', 'b', 'k', 'r', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}; auto colorMe = color; color = (color == Color::BLACK) ? Color::WHITE : Color::BLACK; std::string prefix = (color == Color::BLACK) ? "Black" : "White"; int row = 0; int column = 0; for (int i = 0; i < 2; i++) { for (int k = 0; k < order.size(); k++) { if (column == 8) { column = 0; row += (color != colorMe) ? 1 : -1; } auto expr = order[k]; switch (expr) { case 'p': board[row][column] = new Pawn(row, column, this->texturePointer[prefix + "Pawn"], color); break; case 'r': board[row][column] = new Rook(row, column, this->texturePointer[prefix + "Rook"], color); break; case 'b': board[row][column] = new Bishop(row, column, this->texturePointer[prefix + "Bishop"], color); break; case 'k': board[row][column] = new Knight(row, column, this->texturePointer[prefix + "Knight"], color); break; case 'K': switch (colorMe) { case WHITE: board[row][column] = new King(row, column, this->texturePointer[prefix + "King"], color); break; case BLACK: board[row][column - 1] = new King(row, column - 1, this->texturePointer[prefix + "King"], color); } break; case 'Q': switch (colorMe) { case WHITE: board[row][column] = new Queen(row, column, this->texturePointer[prefix + "Queen"], color); break; case BLACK: board[row][column + 1] = new Queen(row, column + 1, this->texturePointer[prefix + "Queen"], color); break; } break; } column += 1; } prefix = (color == Color::BLACK) ? "White" : "Black"; color = (color == Color::BLACK) ? Color::WHITE : Color::BLACK; row = 8; } } //click to position on board int Board::clickToPlace(double value) { if (value < 0 || value > 640) { return -1; } int key = (int)value; key /= 10; int loc = 0; for (int i = 8; i < 64 && key >= i; i += 8) { ++loc; } return loc; } //overload subscript const Piece *Board::operator()(int row, int col) const { return this->board[row][col]; } //get color in place Color Board::getColor(int row, int col) const { return this->board[row][col]->getColor(); } //copy from to void Board::moveFromTo(int rf, int cf, int rt, int ct) //FIXME encapsulate { auto copy = this->board[rf][cf]; this->board[rf][cf] = nullptr; delete board[rt][ct]; this->board[rt][ct] = copy; this->board[rt][ct]->setPositionOnBoard(rt, ct); this->board[rt][ct]->setPosition(rt, ct); } //do move on board not yet implement to screen bool Board::doMove(int rowTo, int columnTo, int rowFrom, int columnFrom) { auto moves = this->board[rowFrom][columnFrom]->getPossiblePositions(board); auto p = std::make_pair(rowTo, columnTo); if (this->board[rowTo][columnTo] != nullptr && this->board[rowTo][columnTo]->getName() == "King" || this->board[rowFrom][columnFrom] == nullptr) //cant eat king nor move nullptr piece { return false; } for (auto move : moves) { if (move == p) { //TODO detect check mate! this->saveTo = this->board[rowTo][columnTo]; this->board[rowTo][columnTo] = nullptr; this->board[rowTo][columnTo] = this->board[rowFrom][columnFrom]; this->board[rowTo][columnTo]->setPositionOnBoard(rowTo, columnTo); this->board[rowFrom][columnFrom] = nullptr; return true; } } return false; } //redo last doMove move void Board::redoLastMove(int rowTo, int columnTo, int rowFrom, int columnFrom) { this->board[rowFrom][columnFrom] = this->board[rowTo][columnTo]; this->board[rowFrom][columnFrom]->setPositionOnBoard(rowFrom, columnFrom); this->board[rowTo][columnTo] = this->saveTo; this->saveTo = nullptr; } //implement move void Board::implementLastMove(int rowTo, int columnTo, int rowFrom, int columnFrom) { delete this->saveTo; this->saveTo = nullptr; this->board[rowTo][columnTo]->setPosition(rowTo, columnTo); this->currentPlayer = (this->currentPlayer == WHITE) ? BLACK : WHITE; Debug(1); chess = this->isInChess(this->currentPlayer); Debug(2); } //check for checkmate bool Board::isCheckMate(Color color) { Debug(3); bool chess = this->isInChess(color); Debug(4); if (!chess) { return false; } auto copy = this->saveTo; if (chess) { for (int i = 0; i < BOARD_LENGTH; i++) { for (int k = 0; k < BOARD_LENGTH; k++) { if (this->board[i][k] == nullptr || this->board[i][k]->getColor() != color) { continue; } auto currentPiecePos = this->board[i][k]->getPositionOnBoard(); auto pieceMoves = this->board[i][k]->getPossiblePositions(this->board); for (auto move : pieceMoves) { //if legall~ Debug(45); // //NOTE: fix me SEGMENT FAULTJ, TRY EXEPT? try { if (this->doMove(move.first, move.second, currentPiecePos.first, currentPiecePos.second)) { this->moveCounter++; //NOTE Debug(7); chess = this->isInChess(color); Debug(8); Debug(this->currentPlayer); Debug(25); this->redoLastMove(move.first, move.second, currentPiecePos.first, currentPiecePos.second); if (!chess) { this->saveTo = copy; return false; } Debug(24); } } catch (...) { /* code */ } } } } } this->saveTo = copy; return true; } //move piece one board return boolean if move has been done bool Board::move(int rowTo, int columnTo, int rowFrom, int columnFrom) //the new position need change { if (this->board[rowFrom][columnFrom] == nullptr) { std::cout << "nullptr" << std::endl; } auto moves = this->board[rowFrom][columnFrom]->getPossiblePositions(board); auto p = std::make_pair(rowTo, columnTo); if (this->doMove(rowTo, columnTo, rowFrom, columnFrom)) { Debug(5); if (isInChess(this->currentPlayer)) //FIXME if the move make open to chess, illegal { Debug(6); this->redoLastMove(rowTo, columnTo, rowFrom, columnFrom); return false; } else if (chess && !isInChess(this->currentPlayer) || !chess) //if move stopped chess or legall { std::cout << "implem" << std::endl; this->implementLastMove(rowTo, columnTo, rowFrom, columnFrom); return true; } else { throw std::invalid_argument("ERROR in board nor chess/legall move\n"); } } return false; } //init board void Board::initBoard() { for (int i = 0; i < BOARD_SIZE; i++) { for (int k = 0; k < BOARD_SIZE; k++) { this->board[i][k] = nullptr; } } }
30.2
119
0.48684
[ "render" ]
95186f566f6891f594dbd980f0d15e5f1f3481a4
2,800
cpp
C++
src/Hangman/hangman.cpp
clarablz/POO_S4
6fe29e78c346f74c2e25e2628c44496e7f6ced03
[ "MIT" ]
null
null
null
src/Hangman/hangman.cpp
clarablz/POO_S4
6fe29e78c346f74c2e25e2628c44496e7f6ced03
[ "MIT" ]
2
2022-03-19T23:05:28.000Z
2022-03-23T15:24:37.000Z
src/Hangman/hangman.cpp
clarablz/POO_S4
6fe29e78c346f74c2e25e2628c44496e7f6ced03
[ "MIT" ]
null
null
null
#include "hangman.hpp" #include <array> #include <iostream> #include <string> #include <vector> #include "Commons/get_input_from_user.hpp" #include "Commons/random.hpp" void play_hangman() { std::cout << "-----------HANGMAN-----------" << std::endl; Player player(10); std::vector<int> letter_positions; const std::string mystery_word = pick_a_random_word(); std::string progress_word(mystery_word.size(), '_'); std::string word_in_progress; while (player.is_alive() && !has_won(mystery_word, progress_word)) { player.display_life(); display_progress_word(progress_word); auto input_letter = get_input_from_user<std::string>("Enter a letter : "); if (is_letter_in_word(input_letter, mystery_word, letter_positions)) { add_letter(progress_word, input_letter, letter_positions); letter_positions.clear(); } else { player.decrease_life(); } } show_end_message(mystery_word, progress_word); } const std::string pick_a_random_word() { const std::array<std::string, 4> words = { "code", "crous", "imac", "opengl", }; return words[rand<size_t>(0, words.size() - 1)]; } int Player::get_number_of_lives() const { return _number_of_lives; } bool Player::is_alive() const { if (_number_of_lives == 0) { return false; } return true; } void Player::decrease_life() { if (is_alive()) { _number_of_lives--; } } void Player::display_life() const { std::cout << "You have " << _number_of_lives << " lives left. " << std::endl; } bool is_letter_in_word(std::string letter, std::string mystery_word, std::vector<int>& letter_positions) { bool is_letter_found = false; for (unsigned int i = 0; i < mystery_word.size(); i++) { if (mystery_word[i] == letter[0]) { letter_positions.push_back(i); is_letter_found = true; } } return is_letter_found; } void display_progress_word(std::string word) { for (unsigned int i = 0; i < word.size(); i++) { std::cout << word[i] << " "; } std::cout << std::endl; } void add_letter(std::string& progress_word, std::string input_letter, std::vector<int> letter_positions) { for (auto& i : letter_positions) { progress_word[i] = input_letter[0]; } } bool has_won(std::string word_to_find, std::string progress_word) { return (word_to_find == progress_word); } void show_end_message(std::string mystery_word, std::string progress_word) { if (has_won(mystery_word, progress_word)) { std::cout << "You won! The word was indeed '" << mystery_word << "'." << std::endl; } else { std::cout << "You failed..."; } }
25.454545
104
0.617143
[ "vector" ]
951bb951bed045268b0c215702ae22de483421ee
384
cpp
C++
src/mfast/instructions/enum_instruction.cpp
csghone/mFAST
2763f04ed4d9ea7601739e0e498b022ce7cd9fa8
[ "BSD-3-Clause" ]
3
2021-11-04T13:00:27.000Z
2021-11-24T14:57:23.000Z
src/mfast/instructions/enum_instruction.cpp
csghone/mFAST
2763f04ed4d9ea7601739e0e498b022ce7cd9fa8
[ "BSD-3-Clause" ]
null
null
null
src/mfast/instructions/enum_instruction.cpp
csghone/mFAST
2763f04ed4d9ea7601739e0e498b022ce7cd9fa8
[ "BSD-3-Clause" ]
1
2021-11-04T13:00:33.000Z
2021-11-04T13:00:33.000Z
// Copyright (c) 2016, Huang-Ming Huang, Object Computing, Inc. // All rights reserved. // // This file is part of mFAST. // See the file license.txt for licensing information. #include "enum_instruction.h" namespace mfast { enum_field_instruction * enum_field_instruction::clone(arena_allocator &alloc) const { return new (alloc) enum_field_instruction(*this); } } /* mfast */
24
64
0.739583
[ "object" ]
951ded4e9173cbacbd651248d0404b56adcddc69
6,280
cc
C++
FutMPIBench.cc
jgphpc/jub1
ab98a74077b2ea9774a3b170d325d0b57dc04d21
[ "Unlicense" ]
null
null
null
FutMPIBench.cc
jgphpc/jub1
ab98a74077b2ea9774a3b170d325d0b57dc04d21
[ "Unlicense" ]
null
null
null
FutMPIBench.cc
jgphpc/jub1
ab98a74077b2ea9774a3b170d325d0b57dc04d21
[ "Unlicense" ]
null
null
null
#include <mpi.h> #include <stdint.h> #include <cstdlib> #include <iostream> #include <vector> #include "MicroBench.h" #include "MemEstimator.h" #include "timing/ClockSync.h" #include "timing/elg_pform_defs.h" #include "collectives/CollectivesBench.h" #include "collectives/CommMemBench.h" #include "overheads/OverheadsBench.h" #ifdef USE_SCOREP #include <scorep/SCOREP_User.h> SCOREP_USER_METRIC_LOCAL (bench_memory_metric); #endif int main (int argc, char** argv) { // Get the command arguments/ // The command argument is the message size per process bool is_extra_msg_size_bench = false; unsigned int message_size_per_proc = 0; bool duplicate_world_comm = false; if (argc < 2) { return -1; } //is_extra_msg_size_bench = (std::atoi(argv[1]) == 1); message_size_per_proc = std::atoi(argv[1]); //duplicate_world_comm = (std::atoi(argv[3]) == 1); // General init steps CMSB::elg_pform_init (); CMSB::TimeSyncInfo timeSyncInfo; // Measure initial memory consumption uint64_t initial_proc_mem = CMSB::MemEstimator::getProcMemConsumption (); MPI_Init (&argc, &argv); #ifdef USE_SCOREP SCOREP_USER_METRIC_INIT (bench_memory_metric, "Memory", "bytes", SCOREP_USER_METRIC_TYPE_DOUBLE, SCOREP_USER_METRIC_CONTEXT_GLOBAL); #endif int my_rank, num_procs; MPI_Comm_rank (MPI_COMM_WORLD, &my_rank); MPI_Comm_size (MPI_COMM_WORLD, &num_procs); // Create benchmarks std::vector<CMSB::MicroBench*> benchmarks; if (is_extra_msg_size_bench) { //CMSB::createCollectiveExtraSizeMicroBenches (benchmarks, message_size_per_proc); } else { //CMSB::createCollectiveMicroBenches (benchmarks, message_size_per_proc); CMSB::createCollectiveMicroBenchesMinimalVer (benchmarks, message_size_per_proc); //benchmarks.push_back (new CMSB::CommMemBench ()); } CMSB::createOverheadsMicroBenches (benchmarks); CMSB::sync_init_stage1 (&timeSyncInfo); if (my_rank == 0) { std::cout << "Running benchmarks..." << std::endl; std::cout << "Extra message size bench: " << is_extra_msg_size_bench << std::endl; std::cout << "Max buffer size in: " << MAX_BUFF_SIZE_PER_PROC << " MB" << std::endl; std::cout << "Message size per process in doubles: " << message_size_per_proc << std::endl; std::cout << "Non comm-world communicator: " << duplicate_world_comm << std::endl; std::cout << "Running on " << num_procs << " ranks" << std::endl; std::cout << "Memory consumption before allocating buffers " << CMSB::MemEstimator::getCurrentMemConsumption () << std::endl; } unsigned int num_benchmarks = benchmarks.size (); CMSB::MicroBench::MicroBenchInfo benchInfo; unsigned int buff_size = (MAX_BUFF_SIZE_PER_PROC * 1024 * 1024) / sizeof(double); benchInfo._sBuffLen = benchInfo._rBuffLen = buff_size * sizeof(double); benchInfo._sendBuff = new double[buff_size]; benchInfo._recvBuff = new double[buff_size]; benchInfo._sendCounts = new int[num_procs]; benchInfo._sendDispls = new int[num_procs]; benchInfo._recvCounts = new int[num_procs]; benchInfo._recvDispls = new int[num_procs]; if (my_rank == 0) { std::cout << "Memory consumption after allocating buffers " << CMSB::MemEstimator::getCurrentMemConsumption () << std::endl; } // Init buffers std::fill_n (benchInfo._sendBuff, buff_size, my_rank+1); // +1 so that rank's zero buff contains ones instead of zeros std::fill_n (benchInfo._recvBuff, buff_size, 0.0); std::fill_n (benchInfo._sendCounts, num_procs, 0); std::fill_n (benchInfo._sendDispls, num_procs, 0); std::fill_n (benchInfo._recvCounts, num_procs, 0); std::fill_n (benchInfo._recvDispls, num_procs, 0); // Duplicate comm-world communicator MPI_Comm dup_world_comm = MPI_COMM_WORLD; if (duplicate_world_comm) { MPI_Group comm_world_grp; MPI_Comm_group (MPI_COMM_WORLD, &comm_world_grp); MPI_Comm_create (MPI_COMM_WORLD, comm_world_grp, &dup_world_comm); MPI_Group_free (&comm_world_grp); } // Init & run benchmarks for (int i = 0; i < num_benchmarks; i++) { if (my_rank == 0) { std::cout << "Starting benchmark: " << benchmarks[i]->getMicroBenchName () << std::endl; } // Re-init buffers std::fill_n (benchInfo._sendBuff, buff_size, my_rank+1); // +1 so that rank's zero buff contains ones instead of zeros std::fill_n (benchInfo._recvBuff, buff_size, 0.0); benchmarks[i]->init (dup_world_comm, &benchInfo); benchmarks[i]->runMicroBench (&timeSyncInfo); benchmarks[i]->writeResultToProfile (); if (my_rank == 0) { std::cout << "Benchmark: " << benchmarks[i]->getMicroBenchName () << " finished." << std::endl; } } // Calculate MPI memory consumption uint64_t proc_mem = CMSB::MemEstimator::getProcMemConsumption () - initial_proc_mem; uint64_t mpi_mem = CMSB::MemEstimator::getPeakMemConsumption (); uint64_t overheads = CMSB::MemEstimator::getBenchesMemConsumption (benchmarks); overheads += sizeof(double)*2*buff_size + sizeof(int)*4*num_procs; mpi_mem -= overheads; proc_mem -= overheads; if (my_rank == 0) { // Only one rank should update SCORE-P's metrics double mem_consump = double (mpi_mem) / (1024*1024); // Convert to MB double proc_mem_consump = double (proc_mem) / (1024*1024); // Convert to MB #ifdef USE_SCOREP SCOREP_USER_METRIC_DOUBLE (bench_memory_metric, mem_consump); #endif std::cout << "Finished all benchmarks" << std::endl; std::cout << "Peak memory consumption (MB): " << mem_consump << std::endl; std::cout << "Proc (old approach) memory consumption (MB): " << proc_mem_consump << std::endl; CMSB::MemEstimator::printSmapsFile (); } if (duplicate_world_comm) { MPI_Comm_free (&dup_world_comm); } for (int i = 0; i < num_benchmarks; i++) { delete benchmarks[i]; } delete[] benchInfo._sendBuff; delete[] benchInfo._recvBuff; delete[] benchInfo._sendCounts; delete[] benchInfo._sendDispls; delete[] benchInfo._recvCounts; delete[] benchInfo._recvDispls; MPI_Finalize (); return 0; }
36.091954
122
0.679777
[ "vector" ]
9523ac1711acef51a965f29a6badfea216690cf9
2,682
cpp
C++
src/tokeniser.cpp
LordAro/ury-playd
dad5458bb7ae9b21e939c17c25e11b685848c081
[ "BSL-1.0", "MIT" ]
null
null
null
src/tokeniser.cpp
LordAro/ury-playd
dad5458bb7ae9b21e939c17c25e11b685848c081
[ "BSL-1.0", "MIT" ]
null
null
null
src/tokeniser.cpp
LordAro/ury-playd
dad5458bb7ae9b21e939c17c25e11b685848c081
[ "BSL-1.0", "MIT" ]
null
null
null
// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Definition of the Tokeniser class. * @see tokeniser.hpp */ #include <algorithm> #include <cassert> #include <cctype> #include <cstdint> #include "response.hpp" #include "tokeniser.hpp" Tokeniser::Tokeniser() : escape_next(false), in_word(false), quote_type(Tokeniser::QuoteType::NONE) { } std::vector<std::vector<std::string>> Tokeniser::Feed(const std::string &raw) { // The list of ready lines should be cleared by any previous Feed. assert(this->ready_lines.empty()); for (char c : raw) { if (this->escape_next) { this->Push(c); continue; } switch (this->quote_type) { case QuoteType::SINGLE: if (c == '\'') { this->quote_type = QuoteType::NONE; } else { this->Push(c); } break; case QuoteType::DOUBLE: switch (c) { case '\"': this->quote_type = QuoteType::NONE; break; case '\\': this->escape_next = true; break; default: this->Push(c); break; } break; case QuoteType::NONE: switch (c) { case '\n': this->Emit(); break; case '\'': this->in_word = true; this->quote_type = QuoteType::SINGLE; break; case '\"': this->in_word = true; this->quote_type = QuoteType::DOUBLE; break; case '\\': this->escape_next = true; break; default: isspace(c) ? this->EndWord() : this->Push(c); break; } break; } } auto lines = this->ready_lines; this->ready_lines.clear(); return lines; } void Tokeniser::Push(const char c) { assert(this->escape_next || !(this->quote_type == QuoteType::NONE && isspace(c))); this->in_word = true; this->current_word.push_back(c); this->escape_next = false; assert(!this->current_word.empty()); } void Tokeniser::EndWord() { // Don't add a word unless we're in one. if (!this->in_word) return; this->in_word = false; this->words.push_back(this->current_word); this->current_word.clear(); } void Tokeniser::Emit() { // Since we assume these, we don't need to set them later. assert(this->quote_type == QuoteType::NONE); assert(!this->escape_next); // We might still be in a word, in which case we treat the end of a // line as the end of the word too. this->EndWord(); this->ready_lines.push_back(this->words); this->words.clear(); // The state should now be clean and ready for another command. assert(this->quote_type == QuoteType::NONE); assert(!this->escape_next); assert(this->current_word.empty()); }
19.434783
80
0.606264
[ "vector" ]
952593b0d576fe6c1bcd7ac448820108bcd933b0
7,011
hpp
C++
include/Nazara/Physics2D/PhysWorld2D.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
include/Nazara/Physics2D/PhysWorld2D.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
include/Nazara/Physics2D/PhysWorld2D.hpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Physics2D module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_PHYSICS2D_PHYSWORLD2D_HPP #define NAZARA_PHYSICS2D_PHYSWORLD2D_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Color.hpp> #include <Nazara/Math/Angle.hpp> #include <Nazara/Math/Vector2.hpp> #include <Nazara/Physics2D/Config.hpp> #include <Nazara/Physics2D/RigidBody2D.hpp> #include <Nazara/Utils/Signal.hpp> #include <functional> #include <memory> #include <unordered_map> struct cpCollisionHandler; struct cpSpace; namespace Nz { class Arbiter2D; class NAZARA_PHYSICS2D_API PhysWorld2D { friend RigidBody2D; using ContactEndCallback = std::function<void(PhysWorld2D& world, Arbiter2D& arbiter, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata)>; using ContactPreSolveCallback = std::function<bool(PhysWorld2D& world, Arbiter2D& arbiter, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata)>; using ContactPostSolveCallback = std::function<void(PhysWorld2D& world, Arbiter2D& arbiter, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata)>; using ContactStartCallback = std::function<bool(PhysWorld2D& world, Arbiter2D& arbiter, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata)>; using DebugDrawCircleCallback = std::function<void(const Vector2f& origin, const RadianAnglef& rotation, float radius, Color outlineColor, Color fillColor, void* userdata)>; using DebugDrawDotCallback = std::function<void(const Vector2f& origin, float radius, Color color, void* userdata)>; using DebugDrawPolygonCallback = std::function<void(const Vector2f* vertices, std::size_t vertexCount, float radius, Color outlineColor, Color fillColor, void* userdata)>; using DebugDrawSegmentCallback = std::function<void(const Vector2f& first, const Vector2f& second, Color color, void* userdata)>; using DebugDrawTickSegmentCallback = std::function<void(const Vector2f& first, const Vector2f& second, float thickness, Color outlineColor, Color fillColor, void* userdata)>; using DebugDrawGetColorCallback = std::function<Color(RigidBody2D& body, std::size_t shapeIndex, void* userdata)>; public: struct Callback; struct DebugDrawOptions; struct NearestQueryResult; struct RaycastHit; PhysWorld2D(); PhysWorld2D(const PhysWorld2D&) = delete; PhysWorld2D(PhysWorld2D&&) = delete; ///TODO ~PhysWorld2D(); void DebugDraw(const DebugDrawOptions& options, bool drawShapes = true, bool drawConstraints = true, bool drawCollisions = true); float GetDamping() const; Vector2f GetGravity() const; cpSpace* GetHandle() const; std::size_t GetIterationCount() const; std::size_t GetMaxStepCount() const; float GetStepSize() const; bool NearestBodyQuery(const Vector2f& from, float maxDistance, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, RigidBody2D** nearestBody = nullptr); bool NearestBodyQuery(const Vector2f& from, float maxDistance, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, NearestQueryResult* result); void RaycastQuery(const Nz::Vector2f& from, const Nz::Vector2f& to, float radius, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, const std::function<void(const RaycastHit&)>& callback); bool RaycastQuery(const Nz::Vector2f& from, const Nz::Vector2f& to, float radius, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, std::vector<RaycastHit>* hitInfos); bool RaycastQueryFirst(const Nz::Vector2f& from, const Nz::Vector2f& to, float radius, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, RaycastHit* hitInfo = nullptr); void RegionQuery(const Nz::Rectf& boundingBox, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, const std::function<void(Nz::RigidBody2D*)>& callback); void RegionQuery(const Nz::Rectf& boundingBox, Nz::UInt32 collisionGroup, Nz::UInt32 categoryMask, Nz::UInt32 collisionMask, std::vector<Nz::RigidBody2D*>* bodies); void RegisterCallbacks(unsigned int collisionId, Callback callbacks); void RegisterCallbacks(unsigned int collisionIdA, unsigned int collisionIdB, Callback callbacks); void SetDamping(float dampingValue); void SetGravity(const Vector2f& gravity); void SetIterationCount(std::size_t iterationCount); void SetMaxStepCount(std::size_t maxStepCount); void SetSleepTime(float sleepTime); void SetStepSize(float stepSize); void Step(float timestep); void UseSpatialHash(float cellSize, std::size_t entityCount); PhysWorld2D& operator=(const PhysWorld2D&) = delete; PhysWorld2D& operator=(PhysWorld2D&&) = delete; ///TODO struct Callback { ContactEndCallback endCallback = nullptr; ContactPreSolveCallback preSolveCallback = nullptr; ContactPostSolveCallback postSolveCallback = nullptr; ContactStartCallback startCallback = nullptr; void* userdata = nullptr; }; struct DebugDrawOptions { Color constraintColor; Color collisionPointColor; Color shapeOutlineColor; DebugDrawCircleCallback circleCallback; DebugDrawGetColorCallback colorCallback; DebugDrawDotCallback dotCallback; DebugDrawPolygonCallback polygonCallback; DebugDrawSegmentCallback segmentCallback; DebugDrawTickSegmentCallback thickSegmentCallback; void* userdata; }; struct NearestQueryResult { Nz::RigidBody2D* nearestBody; Nz::Vector2f closestPoint; Nz::Vector2f fraction; float distance; }; struct RaycastHit { Nz::RigidBody2D* nearestBody; Nz::Vector2f hitPos; Nz::Vector2f hitNormal; float fraction; }; NazaraSignal(OnPhysWorld2DPreStep, const PhysWorld2D* /*physWorld*/, float /*invStepCount*/); NazaraSignal(OnPhysWorld2DPostStep, const PhysWorld2D* /*physWorld*/, float /*invStepCount*/); private: void InitCallbacks(cpCollisionHandler* handler, Callback callbacks); using PostStep = std::function<void(Nz::RigidBody2D* body)>; void OnRigidBodyMoved(RigidBody2D* oldPointer, RigidBody2D* newPointer); void OnRigidBodyRelease(RigidBody2D* rigidBody); void RegisterPostStep(RigidBody2D* rigidBody, PostStep&& func); struct PostStepContainer { NazaraSlot(RigidBody2D, OnRigidBody2DMove, onMovedSlot); NazaraSlot(RigidBody2D, OnRigidBody2DRelease, onReleaseSlot); std::vector<PostStep> funcs; }; static_assert(std::is_nothrow_move_constructible<PostStepContainer>::value, "PostStepContainer should be noexcept MoveConstructible"); std::size_t m_maxStepCount; std::unordered_map<cpCollisionHandler*, std::unique_ptr<Callback>> m_callbacks; std::unordered_map<RigidBody2D*, PostStepContainer> m_rigidPostSteps; cpSpace* m_handle; float m_stepSize; float m_timestepAccumulator; }; } #endif // NAZARA_PHYSICS2D_PHYSWORLD2D_HPP
42.490909
219
0.768507
[ "vector" ]
952e3da9dee2f17ab1507a9a0a125898044caf68
1,133
cpp
C++
LeetCode/Problems/Algorithms/#40_CombinationSumII.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#40_CombinationSumII.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#40_CombinationSumII.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: void back(int k, const int& sum, const int& target, const int& last_pos, vector<int>& st, const vector<int>& candidates, vector<vector<int>>& solutions){ if(sum == target){ solutions.push_back({st.begin(), st.begin() + k}); }else{ for(int i = last_pos + 1; i < (int)candidates.size(); ++i){ int elem = candidates[i]; bool unique_condition = (i > last_pos + 1 && st[k] == elem ? 0 : 1); if(unique_condition && sum + elem <= target){ st[k] = elem; back(k + 1, sum + elem, target, i, st, candidates, solutions); } } } } public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); int n = target / candidates[0] + 1; vector<int> st(n); vector<vector<int>> solutions; back(0, 0, target, -1, st, candidates, solutions); return solutions; } };
36.548387
116
0.488967
[ "vector" ]
9539cf38436ad2212e8d5abc8a6651b6804a99c5
2,365
cpp
C++
Main/src/main.cpp
DaOnlyOwner/Materializer
80854737d5e923b99b2b34ac339b5f2904152270
[ "MIT" ]
null
null
null
Main/src/main.cpp
DaOnlyOwner/Materializer
80854737d5e923b99b2b34ac339b5f2904152270
[ "MIT" ]
null
null
null
Main/src/main.cpp
DaOnlyOwner/Materializer
80854737d5e923b99b2b34ac339b5f2904152270
[ "MIT" ]
null
null
null
#if 1 #include "NodeFactory.h" #include "BaseNode.h" #include "InputPort.h" #include "OutputPort.h" #include "Scene.h" #include "glad/glad.h" #include "imgui.h" #include "imgui_impl_opengl3.h" #include "imgui_impl_glfw.h" #include <GLFW/glfw3.h> #include <cstdio> #include "TestOperation.h" void register_operations() { NodeFactory& f = NodeFactory::Instance(); f.Register<TestOperation>(NodeInformation{ "TestOperation", "Debugging purposes", {}, {"out"}, {} } , "Operation: Test"); } GLFWwindow* init_all() { if (!glfwInit()) printf("Couldn't initialize window provider"); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(600, 600, "Materializer", nullptr, nullptr); glfwMakeContextCurrent(window); IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui_ImplOpenGL3_Init(); ImGui_ImplGlfw_InitForOpenGL(window, true); // Setup style ImGui::StyleColorsDark(); return window; } #include "CommandMenu.h" void mainloop() { GLFWwindow* window = init_all(); ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); Scene s; //CommandMenu m; glfwSwapInterval(1); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::PushStyleVar(ImGuiStyleVar_GrabRounding, 0); s.Update(); //ImGui::Begin(".."); //std::string text; //if (m.Show(text)) std::cout << text.c_str() << std::endl; //ImGui::End(); ImGui::PopStyleVar(5); ImGui::Render(); int display_w, display_h; glfwMakeContextCurrent(window); glfwGetFramebufferSize(window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); glfwMakeContextCurrent(window); glfwSwapBuffers(window); } } int main() { register_operations(); mainloop(); return 0; } #endif
24.132653
83
0.73277
[ "render" ]
954ae9b388ce63e633807173d273a5f96a2cb37e
15,745
cpp
C++
src/tests/angle_test/angle_test.cpp
google/motive
8e6e850de1f645a690920eaaaa6e6e57ca934cc4
[ "Apache-2.0" ]
210
2015-04-09T19:26:48.000Z
2022-02-08T12:49:13.000Z
src/tests/angle_test/angle_test.cpp
google/motive
8e6e850de1f645a690920eaaaa6e6e57ca934cc4
[ "Apache-2.0" ]
1
2019-05-11T05:20:51.000Z
2019-05-11T05:20:51.000Z
src/tests/angle_test/angle_test.cpp
google/motive
8e6e850de1f645a690920eaaaa6e6e57ca934cc4
[ "Apache-2.0" ]
53
2015-04-12T01:52:38.000Z
2022-01-17T00:12:15.000Z
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cmath> #define FPL_ANGLE_UNIT_TESTS #include <string> #include "motive/math/angle.h" #include "motive/common.h" #include "gtest/gtest.h" using motive::Angle; using motive::AngleToVectorSystem; using motive::kPi; using motive::kHalfPi; using motive::kQuarterPi; using motive::kMinUniqueAngle; using motive::kMaxUniqueAngle; using mathfu::vec3; using mathfu::mat3; union FloatInt { float f; int i; }; static const float kAnglePrecision = 0.0000005f; static const float kUnitVectorPrecision = 0.0000005f; // When diff is +-1, returns the smallest float value that is different than f. // Note: You can construct examples where this function fails. But it works in // almost all cases, and is good for the values we use in these tests. static float MinutelyDifferentFloat(float f, int diff) { FloatInt u; u.f = f; u.i += diff; return u.f; } class AngleTests : public ::testing::Test { protected: virtual void SetUp() { above_pi_ = MinutelyDifferentFloat(kPi, 1); below_pi_ = MinutelyDifferentFloat(kPi, -1); above_negative_pi_ = MinutelyDifferentFloat(-kPi, -1); below_negative_pi_ = MinutelyDifferentFloat(-kPi, 1); half_pi_ = Angle(kHalfPi); } virtual void TearDown() {} protected: float above_pi_; float below_pi_; float above_negative_pi_; float below_negative_pi_; Angle half_pi_; }; // Ensure the constants are in (or not in) the valid angle range. TEST_F(AngleTests, RangeExtremes) { EXPECT_TRUE(Angle::IsAngleInRange(kPi)); EXPECT_FALSE(Angle::IsAngleInRange(-kPi)); EXPECT_TRUE(Angle::IsAngleInRange(kMinUniqueAngle)); EXPECT_TRUE(Angle::IsAngleInRange(kMaxUniqueAngle)); } // Ensure constant values are what we expect them to be. TEST_F(AngleTests, RangeConstants) { EXPECT_FLOAT_EQ(above_negative_pi_, kMinUniqueAngle); EXPECT_FLOAT_EQ(static_cast<float>(M_PI), kMaxUniqueAngle); } // Ensure the smallest value above pi is false. TEST_F(AngleTests, AbovePi) { EXPECT_FALSE(Angle::IsAngleInRange(above_pi_)); } // Ensure the smallest value above -pi is true. TEST_F(AngleTests, AboveNegativePi) { EXPECT_TRUE(Angle::IsAngleInRange(above_negative_pi_)); } // -pi should be represented as pi. TEST_F(AngleTests, ModFromNegativePi) { EXPECT_FLOAT_EQ(Angle::FromWithinThreePi(-kPi).ToRadians(), kPi); } // pi should be represented as pi. TEST_F(AngleTests, ModFromPositivePi) { EXPECT_FLOAT_EQ(Angle::FromWithinThreePi(kPi).ToRadians(), kPi); } // Slightly below -pi should mod to near pi. TEST_F(AngleTests, ModBelowNegativePi) { const Angle a = Angle::FromWithinThreePi(below_negative_pi_); EXPECT_TRUE(a.IsValid()); } // Slightly above pi should mod to near -pi (but above). TEST_F(AngleTests, ModAbovePi) { const Angle a = Angle::FromWithinThreePi(above_pi_); EXPECT_TRUE(a.IsValid()); } // Addition should use modular arithmetic. TEST_F(AngleTests, Addition) { const Angle sum = half_pi_ + half_pi_ + half_pi_ + half_pi_; EXPECT_NEAR(sum.ToRadians(), 0.0f, kAnglePrecision); } // Subtraction should use modular arithmetic. TEST_F(AngleTests, Subtraction) { const Angle diff = half_pi_ - half_pi_ - half_pi_ - half_pi_; EXPECT_NEAR(diff.ToRadians(), kPi, kAnglePrecision); } // Addition should use modular arithmetic. TEST_F(AngleTests, Multiplication) { const Angle product = half_pi_ * 3.f; EXPECT_NEAR(product.ToRadians(), -half_pi_.ToRadians(), kAnglePrecision); } // Subtraction should use modular arithmetic. TEST_F(AngleTests, Division) { const Angle quotient = Angle::FromWithinThreePi(kPi) / 2.0f; EXPECT_NEAR(quotient.ToRadians(), kHalfPi, kAnglePrecision); } // Unary negate should change the sign. TEST_F(AngleTests, Negate) { const Angle a = Angle(kHalfPi); EXPECT_FLOAT_EQ(-a.ToRadians(), -kHalfPi); } // Unary negate should send pi to pi, because -pi is not in range. TEST_F(AngleTests, NegatePi) { const Angle a = Angle(kPi); const Angle negative_a = -a; EXPECT_FLOAT_EQ(negative_a.ToRadians(), kPi); } // Ensure wrapping produces angles in the range (-pi, pi]. TEST_F(AngleTests, WrapAngleTest) { const float a1 = Angle::WrapAngle( static_cast<float>(-M_PI - M_2_PI - M_2_PI)); EXPECT_TRUE(Angle::IsAngleInRange(a1)); const float a2 = Angle::WrapAngle(static_cast<float>(-M_PI - M_2_PI)); EXPECT_TRUE(Angle::IsAngleInRange(a2)); const float a3 = Angle::WrapAngle(static_cast<float>(-M_PI)); EXPECT_TRUE(Angle::IsAngleInRange(a3)); const float a4 = Angle::WrapAngle(0.f); EXPECT_TRUE(Angle::IsAngleInRange(a4)); const float a5 = Angle::WrapAngle(static_cast<float>(M_PI + M_2_PI)); EXPECT_TRUE(Angle::IsAngleInRange(a5)); const float a6 = Angle::WrapAngle( static_cast<float>(M_PI + M_2_PI + M_2_PI)); EXPECT_TRUE(Angle::IsAngleInRange(a6)); } // Clamping a value that's inside the range should not change the value. TEST_F(AngleTests, ClampInside) { const Angle a(kHalfPi + 0.1f); const Angle center(kHalfPi); const Angle max_diff(0.2f); EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), a.ToRadians()); } // Clamping a value that's above the range should clamp to the top boundary. TEST_F(AngleTests, ClampAbove) { const Angle a(kHalfPi + 0.2f); const Angle center(kHalfPi); const Angle max_diff(0.1f); EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center + max_diff).ToRadians()); } // Clamping a value that's below the range should clamp to the bottom boundary. TEST_F(AngleTests, ClampBelow) { const Angle a(-kHalfPi - 0.2f); const Angle center(-kHalfPi); const Angle max_diff(0.1f); EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center - max_diff).ToRadians()); } // Clamping to a range that strattles pi should wrap to the boundary that's // closest under modular arithmetic. TEST_F(AngleTests, ClampModularAtPositiveCenterPositiveAngle) { const Angle a(kPi - 0.2f); const Angle center(kPi); const Angle max_diff(0.1f); // This tests a positive number clamped to the range. EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center - max_diff).ToRadians()); } // Clamping to a range that strattles pi should wrap to the boundary that's // closest under modular arithmetic. TEST_F(AngleTests, ClampModularAtPositiveCenterNegativeAngle) { const Angle a(-kPi + 1.1f); const Angle center(kPi); const Angle max_diff(0.1f); // This tests a negative number clamped to the range. EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center + max_diff).ToRadians()); } // Clamping to a range that strattles pi should wrap to the boundary that's // closest under modular arithmetic. TEST_F(AngleTests, ClampModularAtNegativeCenterPositiveAngle) { const Angle a(kPi - 0.2f); const Angle center(kMinUniqueAngle); const Angle max_diff(0.1f); // This tests a positive number clamped to a range centered about a negative // number. EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center - max_diff).ToRadians()); } // Clamping to a range that strattles pi should wrap to the boundary that's // closest under modular arithmetic. TEST_F(AngleTests, ClampModularAtNegativeCenterNegativeAngle) { const Angle a(-kPi + 1.1f); const Angle center(kMinUniqueAngle); const Angle max_diff(0.1f); // This tests a negative number clamped to the range. EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), (center + max_diff).ToRadians()); } // Clamping with zero diff should return the center. TEST_F(AngleTests, ClampWithZeroDiff) { const Angle a(-kPi + 1.1f); const Angle center(kPi - 2.1f); const Angle max_diff(0.0f); // This tests a negative number clamped to the range. EXPECT_FLOAT_EQ(a.Clamp(center, max_diff).ToRadians(), center.ToRadians()); } void TestToVectorSystem(const AngleToVectorSystem system, const int zero_axis, const int ninety_axis, const int ignored_axis) { // Angle zero should translate to the zero axis. const vec3 zero = Angle(0.0f).ToVectorSystem(system); EXPECT_NEAR(zero[zero_axis], 1.0f, kUnitVectorPrecision); EXPECT_NEAR(zero[ninety_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(zero[ignored_axis], 0.0f, kUnitVectorPrecision); // Angle 180 should translate to the negative zero axis. const vec3 minus_zero = Angle(kPi).ToVectorSystem(system); EXPECT_NEAR(minus_zero[zero_axis], -1.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_zero[ninety_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_zero[ignored_axis], 0.0f, kUnitVectorPrecision); // Angle 90 should translate to the 90 axis. const vec3 ninety = Angle(kHalfPi).ToVectorSystem(system); EXPECT_NEAR(ninety[zero_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(ninety[ninety_axis], 1.0f, kUnitVectorPrecision); EXPECT_NEAR(ninety[ignored_axis], 0.0f, kUnitVectorPrecision); // Angle -90 should translate to the -90 axis. const vec3 minus_ninety = Angle(-kHalfPi).ToVectorSystem(system); EXPECT_NEAR(minus_ninety[zero_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_ninety[ninety_axis], -1.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_ninety[ignored_axis], 0.0f, kUnitVectorPrecision); // Angle 45 should translate to a unit vector between the 0 and 90 axes. const vec3 forty_five = Angle(kQuarterPi).ToVectorSystem(system); const float one_over_root_two = 1.0f / std::sqrt(2.0f); EXPECT_NEAR(forty_five[zero_axis], one_over_root_two, kUnitVectorPrecision); EXPECT_NEAR(forty_five[ninety_axis], one_over_root_two, kUnitVectorPrecision); EXPECT_NEAR(forty_five[ignored_axis], 0.0f, kUnitVectorPrecision); } // Test conversions from angles to vectors. TEST_F(AngleTests, ToVectorSystem) { TestToVectorSystem(motive::kAngleToVectorXY, 0, 1, 2); TestToVectorSystem(motive::kAngleToVectorXZ, 0, 2, 1); TestToVectorSystem(motive::kAngleToVectorYZ, 1, 2, 0); TestToVectorSystem(motive::kAngleToVectorYX, 1, 0, 2); TestToVectorSystem(motive::kAngleToVectorZX, 2, 0, 1); TestToVectorSystem(motive::kAngleToVectorZY, 2, 1, 0); } static const float kIgnoredAxisValues[] = { 0.0f, 1.0f, -10.0f, 300000.0f }; void TestFromVectorSystem(const AngleToVectorSystem system, const int zero_axis, const int ninety_axis, const int ignored_axis) { for (size_t i = 0; i < MOTIVE_ARRAY_SIZE(kIgnoredAxisValues); ++i) { // No matter what the ignored axis is, the returned value should be the // same. vec3 init_vector = mathfu::kZeros3f; init_vector[ignored_axis] = kIgnoredAxisValues[i]; // Zero axis should convert to zero angle. vec3 zero = init_vector; zero[zero_axis] = 1.0f; const Angle zero_angle = Angle::FromVectorSystem(zero, system); EXPECT_NEAR(zero_angle.ToRadians(), 0.0f, kAnglePrecision); // Ninety axis should convert to ninety angle. vec3 ninety = init_vector; ninety[ninety_axis] = 1.0f; const Angle ninety_angle = Angle::FromVectorSystem(ninety, system); EXPECT_NEAR(ninety_angle.ToRadians(), kHalfPi, kAnglePrecision); // Negative zero axis should convert to 180 angle. vec3 neg_zero = init_vector; neg_zero[zero_axis] = -1.0f; const Angle neg_zero_angle = Angle::FromVectorSystem(neg_zero, system); EXPECT_NEAR(neg_zero_angle.ToRadians(), kPi, kAnglePrecision); // Negative ninety axis should convert to -90 angle. vec3 neg_ninety = init_vector; neg_ninety[ninety_axis] = -1.0f; const Angle neg_ninety_angle = Angle::FromVectorSystem(neg_ninety, system); EXPECT_NEAR(neg_ninety_angle.ToRadians(), -kHalfPi, kAnglePrecision); // Half way between zero and ninety axes should return 45 degree angle. vec3 forty_five = init_vector; const float one_over_root_two = 1.0f / std::sqrt(2.0f); forty_five[zero_axis] = one_over_root_two; forty_five[ninety_axis] = one_over_root_two; const Angle forty_five_angle = Angle::FromVectorSystem(forty_five, system); EXPECT_NEAR(forty_five_angle.ToRadians(), kQuarterPi, kAnglePrecision); } } // Test conversions from angles to vectors. TEST_F(AngleTests, FromVectorSystem) { TestFromVectorSystem(motive::kAngleToVectorXY, 0, 1, 2); TestFromVectorSystem(motive::kAngleToVectorXZ, 0, 2, 1); TestFromVectorSystem(motive::kAngleToVectorYZ, 1, 2, 0); TestFromVectorSystem(motive::kAngleToVectorYX, 1, 0, 2); TestFromVectorSystem(motive::kAngleToVectorZX, 2, 0, 1); TestFromVectorSystem(motive::kAngleToVectorZY, 2, 1, 0); } void TestToRotationMatrix(const AngleToVectorSystem system, const int zero_axis, const int ninety_axis, const int ignored_axis) { vec3 v; v[zero_axis] = 1.0f; v[ninety_axis] = 0.0f; v[ignored_axis] = 3.0f; // Angle zero should translate to the zero axis. const mat3 zero_mat = Angle(0.0f).ToRotationMatrix(system); const vec3 zero = zero_mat * v; EXPECT_NEAR(zero[zero_axis], 1.0f, kUnitVectorPrecision); EXPECT_NEAR(zero[ninety_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(zero[ignored_axis], 3.0f, kUnitVectorPrecision); // Angle 180 should translate to the negative zero axis. const mat3 minus_zero_mat = Angle(kPi).ToRotationMatrix(system); const vec3 minus_zero = minus_zero_mat * v; EXPECT_NEAR(minus_zero[zero_axis], -1.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_zero[ninety_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_zero[ignored_axis], 3.0f, kUnitVectorPrecision); // Angle 90 should translate to the 90 axis. const mat3 ninety_mat = Angle(kHalfPi).ToRotationMatrix(system); const vec3 ninety = ninety_mat * v; EXPECT_NEAR(ninety[zero_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(ninety[ninety_axis], 1.0f, kUnitVectorPrecision); EXPECT_NEAR(ninety[ignored_axis], 3.0f, kUnitVectorPrecision); // Angle -90 should translate to the -90 axis. const mat3 minus_ninety_mat = Angle(-kHalfPi).ToRotationMatrix(system); const vec3 minus_ninety = minus_ninety_mat * v; EXPECT_NEAR(minus_ninety[zero_axis], 0.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_ninety[ninety_axis], -1.0f, kUnitVectorPrecision); EXPECT_NEAR(minus_ninety[ignored_axis], 3.0f, kUnitVectorPrecision); // Angle 45 should translate to a unit vector between the 0 and 90 axes. const mat3 forty_five_mat = Angle(kQuarterPi).ToRotationMatrix(system); const vec3 forty_five = forty_five_mat * v; const float one_over_root_two = 1.0f / std::sqrt(2.0f); EXPECT_NEAR(forty_five[zero_axis], one_over_root_two, kUnitVectorPrecision); EXPECT_NEAR(forty_five[ninety_axis], one_over_root_two, kUnitVectorPrecision); EXPECT_NEAR(forty_five[ignored_axis], 3.0f, kUnitVectorPrecision); } // Test conversions from angles to vectors. TEST_F(AngleTests, ToRotationMatrix) { TestToRotationMatrix(motive::kAngleToVectorXY, 0, 1, 2); TestToRotationMatrix(motive::kAngleToVectorXZ, 0, 2, 1); TestToRotationMatrix(motive::kAngleToVectorYZ, 1, 2, 0); TestToRotationMatrix(motive::kAngleToVectorYX, 1, 0, 2); TestToRotationMatrix(motive::kAngleToVectorZX, 2, 0, 1); TestToRotationMatrix(motive::kAngleToVectorZY, 2, 1, 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
38.216019
80
0.741505
[ "vector" ]
954b664c4f4482097c144b5ba2d80b41608b19c6
1,493
cpp
C++
src/optimization/simple_parameters_processor.cpp
wfoperihnofiksnfvopjdf/k52
2bbbfe018db6d73ec9773f29e571269f898a9bc0
[ "MIT" ]
6
2016-04-14T07:36:17.000Z
2019-04-22T22:03:20.000Z
src/optimization/simple_parameters_processor.cpp
wfoperihnofiksnfvopjdf/k52
2bbbfe018db6d73ec9773f29e571269f898a9bc0
[ "MIT" ]
29
2016-04-05T08:49:05.000Z
2016-10-29T07:09:00.000Z
src/optimization/simple_parameters_processor.cpp
wfoperihnofiksnfvopjdf/k52
2bbbfe018db6d73ec9773f29e571269f898a9bc0
[ "MIT" ]
9
2016-04-16T07:53:04.000Z
2019-02-12T21:31:51.000Z
#include "simple_parameters_processor.h" #include <stdexcept> namespace k52 { namespace optimization { SimpleParametersProcessor::SimpleParametersProcessor() :function_counter_(-1) { } IParameters::shared_ptr SimpleParametersProcessor::ProcessParameters( const IObjectiveFunction &function_to_optimize, const std::vector< IParameters::shared_ptr >& parameters, bool maximize) { if(parameters.size() < 1) { throw std::invalid_argument("parameters should contain at least one element in vector"); } std::vector<const IParameters*> parameters_to_count = ExtractPointers(parameters); std::vector<double> values = function_counter_.CountObjectiveFunctionValues( parameters_to_count, function_to_optimize); size_t index = 0; double value = values[index]; for(size_t i=1; i<values.size(); i++) { bool condition = values[i] > value; condition = maximize ? condition : (!condition); if(condition) { index = i; value = values[i]; } } return parameters[index]; } std::vector<const IParameters*> SimpleParametersProcessor::ExtractPointers( const std::vector< IParameters::shared_ptr >& parameters) { std::vector<const IParameters*> pointers(parameters.size()); for(size_t i=0; i<parameters.size(); i++) { pointers[i] = parameters[i].get(); } return pointers; } }/* namespace optimization */ }/* namespace k52 */
25.741379
96
0.669123
[ "vector" ]
954d7c65857414237dab8db660f90a578cc00428
40,291
cpp
C++
src/libcintw/cintwrapper.cpp
ZimmermanGroup/SlaterGPU
941ba0773d34b7a447081f0329532df7f13d2637
[ "Apache-2.0" ]
1
2022-02-24T13:26:53.000Z
2022-02-24T13:26:53.000Z
src/libcintw/cintwrapper.cpp
ZimmermanGroup/SlaterGPU
941ba0773d34b7a447081f0329532df7f13d2637
[ "Apache-2.0" ]
null
null
null
src/libcintw/cintwrapper.cpp
ZimmermanGroup/SlaterGPU
941ba0773d34b7a447081f0329532df7f13d2637
[ "Apache-2.0" ]
1
2022-02-24T13:26:55.000Z
2022-02-24T13:26:55.000Z
#include "cintwrapper.h" #include "elements.h" #include <fstream> #include <sstream> #include <string> #include <cstdlib> #include <vector> #include <unordered_set> #include <cmath> #include <math.h> #include "omp.h" #if USEMKL #include <mkl_lapacke.h> #include <mkl_cblas.h> #else #include <lapacke.h> #include <cblas.h> #endif using namespace std; //extern "C" void dgetri(int *N, double **A, int *lda, int *IPIV, // double *WORK, int *lwork, int *INFO); //extern "C" void dgetrf(int *M, int *N, double **A, int *lda, int *IPIV, // int *INFO); //extern "C" void dsyev(char *jobz, char *uplo, int *n, double *a, int *lda, // double *w, double * work, int *lwork, int* info); bool BT::DO_CART = true; int binom(int n, int k) { return (tgamma(n+1))/(tgamma(n+1-k)*tgamma(k+1)); } int calc_di(int i, int *bas) { int idx_i = 0; for (int j = 0; j < i; j++) { idx_i += CINTcgto_cart(j, bas); } return idx_i; } void get_overlap(double * overlap, int N, int natm, int nbas, int nenv, int *atm, int* bas, double *env) { int idx_i = 0; int di, dj; int shls[2]; if (BT::DO_CART) { for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_cart(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_cart(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_ovlp_cart(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; overlap[oi * N + oj] = overlap[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; } // for i } // if BT::DO_CART else { for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_ovlp_sph(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; overlap[oi * N + oj] = overlap[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i } // else } void get_overlap_ri(double * overlap, int Naux, int natm, int nbas, int nbas_ri, int nenv, int *atm, int* bas, double *env) { int idx_i = 0; int di, dj; int shls[2]; if (BT::DO_CART) { for (int i = 0; i < nbas_ri; i++) { int idx_j = 0; shls[0] = i + nbas; di = CINTcgto_cart(i + nbas, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_cart(j + nbas, bas); shls[1] = j + nbas; double *buf = new double[di*dj]; cint1e_ovlp_cart(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; overlap[oi * Naux + oj] = overlap[oj * Naux + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i } // if BT::DO_CART else { for (int i = 0; i < nbas_ri; i++) { int idx_j = 0; shls[0] = i + nbas; di = CINTcgto_spheric(i + nbas, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_spheric(j + nbas, bas); shls[1] = j + nbas; double *buf = new double[di*dj]; cint1e_ovlp_sph(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; overlap[oi * Naux + oj] = overlap[oj * Naux + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i } // else } void get_hcore(double *hcore, int N, int natm, int nbas, int nenv, int *atm, int *bas, double *env) { int idx_i = 0; int di, dj; int shls[2]; double *tmp = new double[N * N]; if (BT::DO_CART) { for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_cart(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_cart(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_nuc_cart(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; tmp[oi * N + oj] = tmp[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i for (int i = 0; i < N * N; i++) { hcore[i] = tmp[i]; } idx_i = 0; for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_cart(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_cart(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_kin_cart(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; tmp[oi * N + oj] = tmp[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i } // if BT::DO_CART else { for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_nuc_sph(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; tmp[oi * N + oj] = tmp[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i for (int i = 0; i < N * N; i++) { hcore[i] = tmp[i]; } idx_i = 0; for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j <= i; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf = new double[di*dj]; cint1e_kin_sph(buf,shls,atm,natm,bas,nbas,env); for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; tmp[oi * N + oj] = tmp[oj * N + oi] = buf[j1*di + i1]; } // for i1 } // for j1 delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i } for (int i = 0; i < N * N; i++) { hcore[i] += tmp[i]; } delete [] tmp; } void gen_eri(double **eri, int N, int natm, int nbas, int nenv, int *atm, int *bas, double *env) { int N2 = N*N; int idxi = 0; int idxj = 0; int idxk = 0; int idxl = 0; int di = 0; int dj = 0; int dk = 0; int dl = 0; CINTOpt *no_opt = NULL; if (BT::DO_CART) { for (int i = 0; i < nbas; i++) { di = CINTcgto_cart(i,bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_cart(j,bas); for (int k = 0; k < nbas; k++) { dk = CINTcgto_cart(k,bas); for (int l = 0; l < nbas; l++) { dl = CINTcgto_cart(l,bas); double * buf = new double[di*dj*dk*dl]; int shls[4]; shls[0] = i; shls[1] = j; shls[2] = k; shls[3] = l; cint2e_cart(buf, shls, atm, natm, bas, nbas, env, no_opt); for (int l1 = 0; l1 < dl; l1++) { for (int k1 = 0; k1 < dk; k1++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idxi; int oj = j1 + idxj; int ok = k1 + idxk; int ol = l1 + idxl; int ij = oi * N + oj; int kl = ok * N + ol; int bdx = l1*(dk*dj*di) + k1*(dj*di) + j1*(di) + i1; // printf("oi %2d oj %2d ok %2d ol %2d ij %6d kl %6d\n",oi, oj, ok, ol,ij,kl); eri[ij][kl] = eri[kl][ij] = buf[bdx]; } // for i1 } // for j1 } // for k1 } // for l1 delete [] buf; idxl += dl; } // for l idxl = 0; idxk += dk; } // for k idxk = 0; idxj += dj; } // for j idxj = 0; idxi += di; } // for i } // if BT::DO_CART else { for (int i = 0; i < nbas; i++) { di = CINTcgto_spheric(i,bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j,bas); for (int k = 0; k < nbas; k++) { dk = CINTcgto_spheric(k,bas); for (int l = 0; l < nbas; l++) { dl = CINTcgto_spheric(l,bas); double * buf = new double[di*dj*dk*dl]; int shls[4]; shls[0] = i; shls[1] = j; shls[2] = k; shls[3] = l; cint2e_sph(buf, shls, atm, natm, bas, nbas, env, no_opt); for (int l1 = 0; l1 < dl; l1++) { for (int k1 = 0; k1 < dk; k1++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idxi; int oj = j1 + idxj; int ok = k1 + idxk; int ol = l1 + idxl; int ij = oi * N + oj; int kl = ok * N + ol; int bdx = l1*(dk*dj*di) + k1*(dj*di) + j1*(di) + i1; // printf("oi %2d oj %2d ok %2d ol %2d ij %6d kl %6d\n",oi, oj, ok, ol,ij,kl); eri[ij][kl] = eri[kl][ij] = buf[bdx]; } // for i1 } // for j1 } // for k1 } // for l1 delete [] buf; idxl += dl; } // for l idxl = 0; idxk += dk; } // for k idxk = 0; idxj += dj; } // for j idxj = 0; idxi += di; } // for i } // else } void gen_jMOI_gto(double **eri, int N, int natm, int nbas, int nenv, int *atm, int *bas, double *env) { int N2 = N*N; int idxi = 0; int idxj = 0; int idxk = 0; int idxl = 0; int di = 0; int dj = 0; int dk = 0; int dl = 0; CINTOpt *no_opt = NULL; if (BT::DO_CART) { for (int i = 0; i < nbas; i++) { di = CINTcgto_cart(i,bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_cart(j,bas); for (int k = 0; k < nbas; k++) { dk = CINTcgto_cart(k,bas); for (int l = 0; l < nbas; l++) { dl = CINTcgto_cart(l,bas); double * buf = new double[di*dj*dk*dl]; int shls[4]; shls[0] = i; shls[1] = j; shls[2] = k; shls[3] = l; cint2e_cart(buf, shls, atm, natm, bas, nbas, env, no_opt); for (int l1 = 0; l1 < dl; l1++) { for (int k1 = 0; k1 < dk; k1++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idxi; int oj = j1 + idxj; int ok = k1 + idxk; int ol = l1 + idxl; int i = oi; int jkl = oj * N * N + ok * N + ol; int k = ok; int lij = ol * N * N + oi * N + oj; int bdx = l1*(dk*dj*di) + k1*(dj*di) + j1*(di) + i1; // printf("oi %2d oj %2d ok %2d ol %2d ij %6d kl %6d\n",oi, oj, ok, ol,ij,kl); eri[i][jkl] = eri[k][lij] = buf[bdx]; } // for i1 } // for j1 } // for k1 } // for l1 delete [] buf; idxl += dl; } // for l idxl = 0; idxk += dk; } // for k idxk = 0; idxj += dj; } // for j idxj = 0; idxi += di; } // for i } // if BT::DO_CART else { for (int i = 0; i < nbas; i++) { di = CINTcgto_spheric(i,bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j,bas); for (int k = 0; k < nbas; k++) { dk = CINTcgto_spheric(k,bas); for (int l = 0; l < nbas; l++) { dl = CINTcgto_spheric(l,bas); double * buf = new double[di*dj*dk*dl]; int shls[4]; shls[0] = i; shls[1] = j; shls[2] = k; shls[3] = l; cint2e_sph(buf, shls, atm, natm, bas, nbas, env, no_opt); for (int l1 = 0; l1 < dl; l1++) { for (int k1 = 0; k1 < dk; k1++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idxi; int oj = j1 + idxj; int ok = k1 + idxk; int ol = l1 + idxl; int i = oi; int jkl = oj * N * N + ok * N + ol; int k = ok; int lij = ol * N * N + oi * N + oj; int bdx = l1*(dk*dj*di) + k1*(dj*di) + j1*(di) + i1; // printf("oi %2d oj %2d ok %2d ol %2d ij %6d kl %6d\n",oi, oj, ok, ol,ij,kl); eri[i][jkl] = eri[k][lij] = buf[bdx]; } // for i1 } // for j1 } // for k1 } // for l1 delete [] buf; idxl += dl; } // for l idxl = 0; idxk += dk; } // for k idxk = 0; idxj += dj; } // for j idxj = 0; idxi += di; } // for i } // else } void gen_ri_int(double *jSaux, double *jSinv, double **jCaux, double *jERI3c, double *jERI2c, int Naux, int N, int natm, int nbas, int nenv, int nbas_ri, int *atm, int *bas, double *env, double **eri) { int N2 = N*N; int Naux2 = Naux * Naux; gen_eri_3c(jERI3c, N, Naux, natm, nbas, nenv, nbas_ri, atm, bas, env); gen_eri_2c(jERI2c, Naux, natm, nbas, nenv, nbas_ri, atm, bas, env); double * jV = new double[Naux * Naux]; for (int i = 0; i < Naux; i++) { for (int j = 0; j < Naux; j++) { jV[i*Naux+j] = jERI2c[i*Naux + j]; } } double * eval = new double[Naux]; char v = 'V'; char u = 'U'; double * work = new double[Naux]; int info; // dsyev(&v,&u,&Naux,jV, &Naux, eval, work, &Naux, &info); // for (int i = 0; i < Naux; i++) { // eval[i] = 1/sqrt(eval[i]); // } // LAPACKE_dsyev(LAPACK_ROW_MAJOR, v, u, Naux, jV, Naux, work); int ipiv[Naux]; double *diag = new double[Naux2](); for (int i = 0; i < Naux; i++) { diag[i*Naux+i] = 1/sqrt(work[i]); } double *tmp = new double[Naux2](); // cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, // N,N,N,1.0,jV,N,diag,N,0.,tmp,N); // cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasTrans, // N,N,N,1.0,tmp,N,jV,N,0.,diag,N); for (int i = 0; i < N2; i++) { //can replace with cblas_dgemm later for (int mu = 0; mu < Naux; mu++) { jCaux[i][mu] = 0.; for (int nu = 0; nu < Naux; nu++) { jCaux[i][mu] += diag[nu*Naux+mu]*jERI3c[i*Naux+nu]; } } } delete [] diag; delete [] tmp; delete [] work; delete [] jV; delete [] eval; } void gen_eri_ri(double *jSaux, double *jSinv, double **jCaux, double *jERI3c, double *jERI2c, int Naux, int N, int natm, int nbas, int nenv, int nbas_ri, int *atm, int *bas, double *env, double **eri) { int N2 = N*N; int Naux2 = Naux * Naux; gen_eri_3c(jERI3c, N, Naux, natm, nbas, nenv, nbas_ri, atm, bas, env); gen_eri_2c(jERI2c, Naux, natm, nbas, nenv, nbas_ri, atm, bas, env); double * jV = new double[Naux * Naux]; for (int i = 0; i < Naux; i++) { for (int j = 0; j < Naux; j++) { jV[i*Naux+j] = jERI2c[i*Naux+j]; } } int ipiv[Naux]; // LAPACKE_dgetrf(LAPACK_ROW_MAJOR, Naux, Naux, jV, Naux, ipiv); // LAPACKE_dgetri(LAPACK_ROW_MAJOR, Naux, jV, Naux, ipiv); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { for (int l = 0; l < N; l++) { int ij = i*N+j; int kl = k*N+l; eri[ij][kl] = 0.; for (int mu = 0; mu < Naux; mu++) { for (int nu = 0; nu < Naux; nu++) { eri[ij][kl] += jERI3c[ij*Naux + mu] * jERI3c[kl*Naux + nu] * jV[mu*Naux+nu]; } } } } } } delete [] jV; } void gen_eri_3c(double *eri, int N, int Naux, int natm, int nbas, int nenv, int nbas_ri, int *atm, int *bas, double *env) { int N2 = N*N; int idxi = 0; int idxj = 0; int idxmu = 0; int di = 0; int dj = 0; int dmu = 0; CINTOpt *no_opt = NULL; // printf("bas: %d %d\n", // bas[(nbas+nbas_ri)*BAS_SLOTS+PTR_EXP], // bas[(nbas+nbas_ri)*BAS_SLOTS+PTR_COEFF]); // printf("env: %7.4f %7.4f\n", // env[bas[(nbas+nbas_ri)*BAS_SLOTS+PTR_EXP]], // env[bas[(nbas+nbas_ri)*BAS_SLOTS+PTR_COEFF]]); // printf("dim: %d\n",CINTcgto_cart(nbas+nbas_ri,bas)); if (BT::DO_CART) { for (int mu = 0; mu < nbas_ri; mu++) { dmu = CINTcgto_cart(mu+nbas,bas); for (int i = 0; i < nbas; i++) { di = CINTcgto_cart(i, bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_cart(j, bas); double * buf = new double[dmu * di * dj]; int shls[4]; shls[0] = mu + nbas; shls[1] = nbas + nbas_ri; // last bas has exp 0 shls[2] = i; shls[3] = j; cint2e_cart(buf, shls, atm, natm, bas, nbas + nbas_ri + 1, env, no_opt); for (int mu1 = 0; mu1 < dmu; mu1++) { for (int i1 = 0; i1 < di; i1++) { for (int j1 = 0; j1 < dj; j1++) { int omu = mu1 + idxmu; int oi = i1 + idxi; int oj = j1 + idxj; int ij = oi * N + oj; int ji = oj * N + oi; int bdx = j1 * (di * dmu) + i1 * dmu + mu1; eri[ij*Naux + omu] = eri[ji*Naux + omu]= buf[bdx]; } // for j1 } // for i1 } // for mu1 delete [] buf; idxj += dj; } // for j idxj = 0; idxi += di; } // for i idxi = 0; idxmu += dmu; } // for mu } // if BT::DO_CART else { for (int mu = 0; mu < nbas_ri; mu++) { dmu = CINTcgto_spheric(mu+nbas,bas); for (int i = 0; i < nbas; i++) { di = CINTcgto_spheric(i, bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j, bas); double * buf = new double[dmu * di * dj]; int shls[4]; shls[0] = mu + nbas; shls[1] = nbas + nbas_ri; // last bas has exp 0 shls[2] = i; shls[3] = j; cint2e_sph(buf, shls, atm, natm, bas, nbas + nbas_ri + 1, env, no_opt); for (int mu1 = 0; mu1 < dmu; mu1++) { for (int i1 = 0; i1 < di; i1++) { for (int j1 = 0; j1 < dj; j1++) { int omu = mu1 + idxmu; int oi = i1 + idxi; int oj = j1 + idxj; int ij = oi * N + oj; int ji = oj * N + oi; int bdx = j1 * (di * dmu) + i1 * dmu + mu1; eri[ij*Naux + omu] = eri[ji*Naux + omu]= buf[bdx]; } // for j1 } // for i1 } // for mu1 delete [] buf; idxj += dj; } // for j idxj = 0; idxi += di; } // for i idxi = 0; idxmu += dmu; } // for mu } // else } // gen_eri_3c void gen_eri_2c(double *eri, int Naux, int natm, int nbas, int nenv, int nbas_ri, int *atm, int *bas, double *env) { int Naux2 = Naux * Naux; int idxmu = 0; int idxnu = 0; int dmu = 0; int dnu = 0; CINTOpt *no_opt = NULL; if (BT::DO_CART) { for (int mu = 0; mu < nbas_ri; mu++) { dmu = CINTcgto_cart(mu+nbas,bas); for (int nu = 0; nu <= mu; nu++) { dnu = CINTcgto_cart(nu+nbas,bas); double *buf = new double[dmu * dnu]; int shls[4]; shls[0] = mu + nbas; shls[1] = nbas + nbas_ri; shls[2] = nu + nbas; shls[3] = nbas + nbas_ri; cint2e_cart(buf, shls, atm, natm, bas, nbas + nbas_ri + 1, env, no_opt); for (int mu1 = 0; mu1 < dmu; mu1++) { for (int nu1 = 0; nu1 < dnu; nu1++) { int omu = mu1 + idxmu; int onu = nu1 + idxnu; int bdx = nu1 * dmu + mu1; eri[omu * Naux + onu] = eri[onu * Naux + omu] = buf[bdx]; } // for nu1 } // for mu1 delete [] buf; idxnu += dnu; } // for nu idxnu = 0; idxmu += dmu; } // for mu } // if BT::DO_CART else { for (int mu = 0; mu < nbas_ri; mu++) { dmu = CINTcgto_spheric(mu+nbas,bas); for (int nu = 0; nu <= mu; nu++) { dnu = CINTcgto_spheric(nu+nbas,bas); double *buf = new double[dmu * dnu]; int shls[4]; shls[0] = mu + nbas; shls[1] = nbas + nbas_ri; shls[2] = nu + nbas; shls[3] = nbas + nbas_ri; cint2e_sph(buf, shls, atm, natm, bas, nbas + nbas_ri + 1, env, no_opt); for (int mu1 = 0; mu1 < dmu; mu1++) { for (int nu1 = 0; nu1 < dnu; nu1++) { int omu = mu1 + idxmu; int onu = nu1 + idxnu; int bdx = nu1 * dmu + mu1; eri[omu * Naux + onu] = eri[onu * Naux + omu] = buf[bdx]; } // for nu1 } // for mu1 delete [] buf; idxnu += dnu; } // for nu idxnu = 0; idxmu += dmu; } // for mu } // else } void translate_basis(int nbas, int N, int natm, int* atm, int* bas, double* env, vector< vector< double> > &basis) { vector< vector< double > >().swap(basis); for (int i = 0; i < nbas; i++) { int ang_a = bas[ANG_OF + BAS_SLOTS*i]; int idx_a = bas[ATOM_OF + BAS_SLOTS*i]; int atm_n = atm[idx_a * ATM_SLOTS + 0]; int idx_c = atm[idx_a * ATM_SLOTS + 1]; int dim = binom(3+ang_a-1,ang_a); double x = env[idx_c + 0]; double y = env[idx_c + 1]; double z = env[idx_c + 2]; int start; int stop; if (BT::DO_CART) { start = 0; stop = dim; } else { start = -ang_a; stop = ang_a + 1; } for (int j = start; j < stop; j++) { vector< double > basvec; basvec.reserve(10); basvec.push_back(ang_a+1); basvec.push_back(ang_a); basvec.push_back(j); basvec.push_back(0); basvec.push_back(0); basvec.push_back(x); basvec.push_back(y); basvec.push_back(z); basvec.push_back(atm_n); basvec.push_back(atm_n); basis.push_back(basvec); } } } void compute_g_grad_ri(int natm, int N, int Naux, int nbas, int nbas_ri, double *grad, double *GF, double *Pao, double *gQmunu, double *gRS, int *atm, int *bas, double *env) { double * grad_term = new double[3*natm](); // zeroed in each contraction for (int i = 0; i < 3 * natm; i++) { grad[i] = 0.; } printf("Printing g(S)\n"); contract_dS(natm, N, nbas, grad_term, GF, atm, bas, env); for (int i = 0; i < 3 * natm; i++) { grad_term[i] *= -1.; grad[i] += grad_term[i]; } for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad_term[i*3+j]); } printf("\n"); } printf("\n"); printf("Printing g(T)\n"); contract_dK(natm, N, nbas, grad_term, Pao, atm, bas, env); for (int i = 0; i < 3 * natm; i++) { grad_term[i] *= -1; grad[i] += grad_term[i]; } for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad_term[i*3+j]); } printf("\n"); } printf("\n"); printf("Printing g(Vne)\n"); contract_dVne(natm, N, nbas, grad_term, Pao, atm, bas, env); for (int i = 0; i < 3 * natm; i++) { grad_term[i] *= 1.; grad[i] += grad_term[i]; } for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad_term[i*3+j]); } printf("\n"); } printf("\n"); printf("Printing g(PQ)\n"); contract_d2c2e(natm, N, nbas, Naux, nbas_ri, grad_term, gRS, atm, bas, env); for (int i = 0; i < 3 * natm; i++) { grad_term[i] *= 1.; grad[i] += grad_term[i]; } for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad_term[i*3+j]); } printf("\n"); } printf("\n"); printf("Printing g(gamma3c)\n"); contract_d3c2e(natm, N, nbas, Naux, nbas_ri, grad_term, gQmunu, atm, bas, env); for (int i = 0; i < 3 * natm; i++) { grad_term[i] *= -2.; grad[i] += grad_term[i]; } for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad_term[i*3+j]); } printf("\n"); } printf("\n"); printf("Printing grad\n"); for (int i = 0; i < natm; i++) { for (int j = 0; j < 3; j++) { printf("%12.8f ",grad[i*3+j]); } printf("\n"); } printf("\n"); delete [] grad_term; } void contract_dS(int natm, int N, int nbas, double *grad_term, double *GF, int *atm, int *bas, double *env) { int N2 = N*N; double *jS = new double[3*N2]; int idx_i = 0; int *atm_idx = new int[N]; int di, dj; int shls[2]; for (int i = 0; i < 3*natm; i++) { grad_term[i] = 0.; } for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j < di; j++) { atm_idx[idx_i + j] = bas[ATOM_OF + BAS_SLOTS*i]; } for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf = new double[di*dj*3]; cint1e_ipovlp_sph(buf,shls,atm,natm,bas,nbas,env); for (int x = 0; x < 3; x++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; jS[x*N2 + oi * N + oj] = buf[x * dj * di + j1*di + i1]; } // for i1 } // for j1 } // for x delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i for (int x = 0; x < 3; x++) { for (int i = 0; i < N; i++) { int atm_i = atm_idx[i]; for (int j = 0; j < N; j++) { int atm_j = atm_idx[j]; grad_term[atm_i*3 + x] += GF[i*N+j] * jS[x*N2 + i*N+j]; grad_term[atm_j*3 + x] += GF[i*N+j] * jS[x*N2 + j*N+i]; } // for j } // for i } // for x delete [] atm_idx; delete [] jS; } void contract_dK(int natm, int N, int nbas, double *grad_term, double *Pao, int *atm, int *bas, double *env) { int N2 = N*N; double *jK1 = new double[3*N2]; double *jK2 = new double[3*N2]; int idx_i = 0; int *atm_idx = new int[N]; int di, dj; int shls[2]; for (int i = 0; i < 3*natm; i++) { grad_term[i] = 0.; } for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j < di; j++) { atm_idx[idx_i + j] = bas[ATOM_OF + BAS_SLOTS*i]; } for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf1 = new double[di*dj*3]; double *buf2 = new double[di*dj*3]; cint1e_ipkin_sph(buf1,shls,atm,natm,bas,nbas,env); cint1e_kinip_sph(buf2,shls,atm,natm,bas,nbas,env); for (int x = 0; x < 3; x++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; jK1[x*N2 + oi * N + oj] = buf1[x * dj * di + j1*di + i1]; jK2[x*N2 + oi * N + oj] = buf2[x * dj * di + j1*di + i1]; } // for i1 } // for j1 } // for x delete [] buf1; delete [] buf2; idx_j += dj; } // for j idx_i += di; }// for i for (int x = 0; x < 3; x++) { for (int i = 0; i < N; i++) { int atm_i = atm_idx[i]; for (int j = 0; j < N; j++) { int atm_j = atm_idx[j]; grad_term[atm_i*3 + x] += Pao[i*N+j] * jK1[x*N2 + i*N+j]; grad_term[atm_j*3 + x] += Pao[i*N+j] * jK2[x*N2 + i*N+j]; } // for j } // for i } // for x delete [] atm_idx; delete [] jK1; delete [] jK2; } void contract_dVne(int natm, int N, int nbas, double *grad_term, double *Pao, int *atm, int *bas, double *env) { int N2 = N*N; double *jVdi = new double[3*N2](); double *jVdR = new double[3*N2](); int idx_i = 0; int *atm_idx = new int[N]; int di, dj; int shls[2]; for (int i = 0; i < 3*natm; i++) { grad_term[i] = 0.; } for (int i = 0; i < nbas; i++) { di = CINTcgto_spheric(i, bas); for (int j = 0; j < di; j++) { atm_idx[idx_i + j] = bas[ATOM_OF + BAS_SLOTS*i]; } idx_i += di; }// for i for (int a = 0; a < natm; a++) { int atomic_num = atm[CHARGE_OF + ATM_SLOTS * a]; // PTR_RINV_ORIG = PTR_ENV_START + a * 3; for (int ra = 0; ra < 3; ra++) { env[PTR_RINV_ORIG + ra] = env[atm[a*ATM_SLOTS + PTR_COORD] + ra]; } idx_i = 0; for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *bufr = new double[di*dj*3]; double *bufi = new double[di*dj*3]; cint1e_drinv_sph(bufr,shls,atm,natm,bas,nbas,env); cint1e_iprinv_sph(bufi,shls,atm,natm,bas,nbas,env); for (int x = 0; x < 3; x++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; jVdR[x*N2 + oi*N + oj] = bufr[x*dj*di + j1*di +i1]; jVdi[x*N2 + oi*N + oj] = bufi[x*dj*di + j1*di +i1]; } // for i1 } // for j1 } // for x delete [] bufr; delete [] bufi; idx_j += dj; } // for j idx_i += di; } // for i for (int x = 0; x < 3; x++) { for (int i = 0; i < N; i++) { int atm_i = atm_idx[i]; for (int j = 0; j < N; j++) { int atm_j = atm_idx[j]; grad_term[a*3 + x] -= atomic_num * Pao[i*N+j] * jVdR[x*N2 + j*N+i]; grad_term[atm_i*3 + x] += atomic_num * Pao[i*N+j] * jVdi[x*N2 + i*N+j]; grad_term[atm_j*3 + x] += atomic_num * Pao[i*N+j] * jVdi[x*N2 + j*N+i]; } // for j } // for i } // for x } // for a // printf("Printing dVdR\n"); // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // printf("%8.4f ",jVdR[i*N+j]); // } // printf("\n"); // } // printf("\n"); delete [] atm_idx; delete [] jVdR; delete [] jVdi; } void contract_dVne2(int natm, int N, int nbas, double *grad_term, double *Pao, int *atm, int *bas, double *env) { int N2 = N*N; double *jVne = new double[3*N2]; int idx_i = 0; int *atm_idx = new int[N]; int di, dj; int shls[2]; for (int i = 0; i < 3*natm; i++) { grad_term[i] = 0.; } for (int i = 0; i < nbas; i++) { int idx_j = 0; shls[0] = i; di = CINTcgto_spheric(i, bas); for (int j = 0; j < di; j++) { atm_idx[idx_i + j] = bas[ATOM_OF + BAS_SLOTS*i]; } for (int j = 0; j < nbas; j++) { dj = CINTcgto_spheric(j, bas); shls[1] = j; double *buf = new double[di*dj*3]; cint1e_ipnuc_sph(buf,shls,atm,natm,bas,nbas,env); for (int x = 0; x < 3; x++) { for (int j1 = 0; j1 < dj; j1++) { for (int i1 = 0; i1 < di; i1++) { int oi = i1 + idx_i; int oj = j1 + idx_j; jVne[x*N2 + oi*N + oj] = buf[x*dj*di + j1*di + i1]; } // for i1 } // for j1 } // for x delete [] buf; idx_j += dj; } // for j idx_i += di; }// for i for (int x = 0; x < 3; x++) { for (int i = 0; i < N; i++) { int atm_i = atm_idx[i]; for (int j = 0; j < N; j++) { int atm_j = atm_idx[j]; grad_term[atm_i*3 + x] += Pao[i*N+j] * jVne[x*N2 + i*N+j]; grad_term[atm_j*3 + x] += Pao[i*N+j] * jVne[x*N2 + j*N+i]; } // for j } // for i } // for x // printf("Printing dVne\n"); // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // printf("%8.4f ",jVne[i*N+j]); // } // printf("\n"); // } // printf("\n"); delete [] atm_idx; delete [] jVne; } void contract_d2c2e(int natm, int N, int nbas, int Naux, int nbas_ri, double *grad_term, double *gRS, int *atm, int *bas, double *env) { int Naux2 = Naux * Naux; double *jERI2c = new double[3*Naux2]; int *atm_idx = new int[Naux]; int ds = 0; int dr = 0; int idx_s = 0; int idx_r = 0; int shls[4]; for (int i = 0; i < 3*natm; i++) { grad_term[i] = 0.; } for (int r = 0; r < nbas_ri; r++) { dr = CINTcgto_spheric(r+nbas, bas); shls[0] = r + nbas; shls[1] = nbas + nbas_ri; // shls[1] = nbas + nbas_ri; for (int s = 0; s < dr; s++) { atm_idx[idx_r + s] = bas[ATOM_OF + BAS_SLOTS*(r+nbas)]; } // for s for (int s = 0; s < nbas_ri; s++) { ds = CINTcgto_spheric(s+nbas, bas); shls[2] = s + nbas; shls[3] = nbas + nbas_ri; // shls[3] = nbas + nbas_ri; double *buf = new double[dr * ds * 3]; cint2e_ip1_sph(buf,shls,atm,natm,bas,nbas+nbas_ri+1,env,NULL); for (int x = 0; x < 3; x++) { for (int r1 = 0; r1 < dr; r1++) { for (int s1 = 0; s1 < ds; s1++) { int rr = r1 + idx_r; int os = s1 + idx_s; jERI2c[x*Naux2 + rr*Naux + os] = buf[x*dr*ds + s1*dr + r1]; } // for s1 } // for r1 } // for x delete [] buf; idx_s += ds; } // for s idx_s = 0; idx_r += dr; } // for r for (int x = 0; x < 3; x++) { for (int r = 0; r < Naux; r++) { int atm_r = atm_idx[r]; for (int s = 0; s < Naux; s++) { int atm_s = atm_idx[s]; grad_term[atm_r*3 + x] += gRS[r*Naux+s] * jERI2c[x*Naux2 + r*Naux+s]; grad_term[atm_s*3 + x] += gRS[r*Naux+s] * jERI2c[x*Naux2 + s*Naux+r]; } // for s } // for r } // for x delete [] jERI2c; delete [] atm_idx; } void contract_d3c2e(int natm, int N, int nbas, int Naux, int nbas_ri, double *grad_term, double *gQmunu, int *atm, int *bas, double *env) { int N2 = N*N; int N2a = N2*Naux; int *atm_idx = new int[N]; int *atm_idx_ri = new int[Naux](); double *jERI3c_ip1 = new double[3*N2a]; // ( di j | P ) double *jERI3c_ip2 = new double[3*N2a]; // ( i j | dP ) int dmu = 0; int dnu = 0; int dq = 0; int idx_mu = 0; int idx_nu = 0; int idx_q = 0; int shls[4]; for (int i = 0; i < 3 * natm; i++) { grad_term[i] = 0.; } for (int mu = 0; mu < nbas; mu++) { dmu = CINTcgto_spheric(mu, bas); shls[0] = mu; for (int i = 0; i < dmu; i++) { atm_idx[idx_mu + i] = bas[ATOM_OF + BAS_SLOTS*mu]; } // for i for (int nu = 0; nu < nbas; nu++) { dnu = CINTcgto_spheric(nu, bas); shls[1] = nu; for (int q = 0; q < nbas_ri; q++) { dq = CINTcgto_spheric(q + nbas, bas); shls[2] = nbas + q; shls[3] = nbas + nbas_ri; // shls[3] = nbas + nbas_ri; int dim = dmu * dnu * dq; double *buf_ip1 = new double[dim*3]; double *buf_ip2 = new double[dim*3]; cint2e_ip1_sph(buf_ip1, shls, atm, natm, bas, nbas + nbas_ri + 1, env, NULL); cint2e_ip2_sph(buf_ip2, shls, atm, natm, bas, nbas + nbas_ri + 1, env, NULL); for (int x = 0; x < 3; x++) { for (int mu1 = 0; mu1 < dmu; mu1++) { for (int nu1 = 0; nu1 < dnu; nu1++) { for (int q1 = 0; q1 < dq; q1++) { int omu = mu1 + idx_mu; int onu = nu1 + idx_nu; int oq = q1 + idx_q; int mn = omu * N + onu; int bdx = x*dim + q1 * (dmu * dnu) + nu1 * dmu + mu1; jERI3c_ip1[x * N2a + mn*Naux + oq] = buf_ip1[bdx]; jERI3c_ip2[x * N2a + mn*Naux + oq] = buf_ip2[bdx]; } // for q } // for nu1 } // for mu1 } // for x delete [] buf_ip1; delete [] buf_ip2; idx_q += dq; } // for q idx_q = 0; idx_nu += dnu; } // for nu idx_nu = 0; idx_mu += dmu; } // for mu idx_q = 0; for (int q = 0; q < nbas_ri; q++) { dq = CINTcgto_spheric(q+nbas, bas); shls[0] = q + nbas; for (int s = 0; s < dq; s++) { atm_idx_ri[idx_q + s] = bas[ATOM_OF + BAS_SLOTS*(q+nbas)]; } // for s idx_q += dq; } for (int x = 0; x < 3; x++) { for (int mu = 0; mu < N; mu++) { int atm_mu = atm_idx[mu]; for (int nu = 0; nu < N; nu++) { int atm_nu = atm_idx[nu]; for (int q = 0; q < Naux; q++) { int atm_q = atm_idx_ri[q]; int mn = mu * N + nu; int nm = nu * N + mu; int muatm = atm_mu * 3 + x; int nuatm = atm_nu * 3 + x; grad_term[muatm] += gQmunu[q*N*N + mn] * jERI3c_ip1[x*N2a + mn*Naux + q]; grad_term[nuatm] += gQmunu[q*N*N + mn] * jERI3c_ip1[x*N2a + nm*Naux + q]; } // for q for (int q = 0; q < Naux; q++) { int atm_q = atm_idx_ri[q]; int mn = mu * N + nu; int qatm = atm_q * 3 + x; grad_term[qatm] += gQmunu[q*N*N + mn] * jERI3c_ip2[x*N2a + mn*Naux + q]; } // for q } // for nu } // for mu } // for x delete [] atm_idx; delete [] atm_idx_ri; delete [] jERI3c_ip1; delete [] jERI3c_ip2; }
30.38537
99
0.426274
[ "vector" ]
95639a26bd926c75048539ff7b0526f74b327357
1,344
cpp
C++
union_find/abc120_d.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
union_find/abc120_d.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
union_find/abc120_d.cpp
Takumi1122/data-structure-algorithm
6b9f26e4dbba981f034518a972ecfc698b86d837
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; // クエリを先読みしておいて逆順に処理 // 操作を逆順に見る // 「辺を削除する」というのはめちゃくちゃ扱いづらいので,反対に「辺を追加する」と読み替えた方がいい /* 参考リンク ABC 120 D - Decayed Bridges https://atcoder.jp/contests/abc120/tasks/abc120_d */ struct UnionFind { vector<int> par; UnionFind(int n) : par(n, -1) {} int root(int x) { if (par[x] < 0) return x; else return par[x] = root(par[x]); } bool issame(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) return false; if (par[x] > par[y]) swap(x, y); // merge technique par[x] += par[y]; par[y] = x; return true; } int size(int x) { return -par[root(x)]; } }; int main() { ll n, m; cin >> n >> m; vector<ll> a(m), b(m); rep(i, m) { cin >> a[i] >> b[i]; a[i]--; b[i]--; } UnionFind uf(n); ll now = n * (n - 1) / 2; vector<ll> ans; rep(i, m) { ans.push_back(now); int ai = a[m - 1 - i]; int bi = b[m - 1 - i]; if (uf.issame(ai, bi)) continue; ll sa = uf.size(ai); ll sb = uf.size(bi); now -= sa * sb; uf.merge(ai, bi); } reverse(ans.begin(), ans.end()); rep(i, m) cout << ans[i] << endl; return 0; }
18.410959
58
0.514881
[ "vector" ]
9570a2d20907dbcdedec7646d74abf0022df2ec4
1,638
cpp
C++
apal_cxx/src/origin_singularity_integration.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
apal_cxx/src/origin_singularity_integration.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
15
2019-05-23T07:18:19.000Z
2019-12-17T08:01:10.000Z
apal_cxx/src/origin_singularity_integration.cpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
#include "origin_singularity_integration.hpp" #include <stdexcept> using namespace std; void OriginSingularityIntegration::get_dir1D(std::vector< MMSP::vector<double> > &directions) const{ MMSP::vector<double> vec(3); vec[0] = 1.0; vec[1] = 0.0; vec[2] = 0.0; directions.push_back(vec); vec[0] = -1.0; directions.push_back(vec); } void OriginSingularityIntegration::get_dir2D(std::vector< MMSP::vector<double> > &directions) const{ const double PI = acos(-1.0); for (unsigned int i=0;i<N;i++){ double theta = 2.0*PI*i/N; MMSP::vector<double> vec(3); vec[0] = cos(theta); vec[1] = sin(theta); vec[2] = 0.0; directions.push_back(vec); } } void OriginSingularityIntegration::get_dir3D(std::vector< MMSP::vector<double> > &directions) const{ const double PI = acos(-1.0); for (unsigned int i=0;i<N;i++) for (unsigned int j=0;j<N;j++){ double phi = 2.0*PI*i/N; double theta = PI*i/N; MMSP::vector<double> vec(3); vec[0] = cos(phi)*sin(theta); vec[1] = sin(phi)*sin(theta); vec[2] = cos(theta); directions.push_back(vec); } } void OriginSingularityIntegration::get_integration_directions(unsigned int dim, std::vector< MMSP::vector<double> > &directions) const{ switch(dim){ case 1: get_dir1D(directions); break; case 2: get_dir2D(directions); break; case 3: get_dir3D(directions); break; default: throw invalid_argument("dim has to be 1, 2 or 3!"); } }
28.241379
135
0.58547
[ "vector" ]
9574789893f15ebba5852db987f8e422531687d5
20,219
cpp
C++
TestDLL/CompareQueryTests.cpp
KylinOLAP/odbc-driver
8c4901edd3bc7664dbad729ff99859f235c684eb
[ "Apache-2.0" ]
7
2015-09-11T06:04:38.000Z
2019-07-16T02:57:16.000Z
TestDLL/CompareQueryTests.cpp
KylinOLAP/odbc-driver
8c4901edd3bc7664dbad729ff99859f235c684eb
[ "Apache-2.0" ]
1
2015-05-04T16:16:00.000Z
2015-05-05T02:14:30.000Z
TestDLL/CompareQueryTests.cpp
KylinOLAP/odbc-driver
8c4901edd3bc7664dbad729ff99859f235c684eb
[ "Apache-2.0" ]
9
2015-05-26T17:13:59.000Z
2020-04-23T15:24:01.000Z
#include "Tests.h" #include <vector> #include "ColorPrint.h" #include "fstream" // ----- whether to ask user for DSN and connection parameters OR specify ----- //#define _CONNECT_WITH_PROMPT 1 // ------------- maximum length to be displayed for a column ------------------ #define _DISPLAY_MAX 128 // -------------------- macro to handle error situations ---------------------- #define ODBC_CHK_ERROR(hType,hValue,iStatus,szMsg) \ {\ if ( status != SQL_SUCCESS ) {\ ShowDiagMessages ( hType, hValue, iStatus, szMsg );\ }\ if ( status == SQL_ERROR ) {\ goto Cleanup;\ }\ } // ---------------------------------- structure ------------------------------- typedef struct BindColInfo { SQLSMALLINT iColTitleSize; // size of column title wchar_t* szColTitle; // column title SQLLEN iColDisplaySize; // size to display void* szColData; // display buffer int iType; bool isSigned; SQLLEN indPtr; // size or null indicator BOOL fChar; // character col flag struct BindColInfo* next; // linked list } BIND_COL_INFO; // -------------------------- function prototypes ----------------------------- void ShowDiagMessages ( SQLSMALLINT hType, SQLHANDLE hValue, SQLRETURN iStatus, char* szMsg ); SQLRETURN CheckResults ( HSTMT hStmt , wchar_t* sql ); void FreeBindings ( BIND_COL_INFO* pBindColInfo ); int totalCount; int successCount; int failCount; std::vector<wstring> failedQueries; void validateOneQuery ( wchar_t* sql ) { Sleep ( 1000 ); SQLRETURN status; SQLHANDLE hEnv = 0; SQLHANDLE hConn = 0; SQLHANDLE hStmt = 0; wchar_t szConnStrOut[1024]; SQLSMALLINT x; // show query to be executed wprintf ( L"The query being validated: %ls \n", sql ); // BEFORE U CONNECT // allocate ENVIRONMENT status = SQLAllocHandle ( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv ); // check for error ODBC_CHK_ERROR ( SQL_HANDLE_ENV, hEnv, status, "" ); // set the ODBC version for behaviour expected status = SQLSetEnvAttr ( hEnv, SQL_ATTR_ODBC_VERSION, ( SQLPOINTER ) SQL_OV_ODBC3, 0 ); // check for error ODBC_CHK_ERROR ( SQL_HANDLE_ENV, hEnv, status, "" ); // allocate CONNECTION status = SQLAllocHandle ( SQL_HANDLE_DBC, hEnv, &hConn ); // check for error ODBC_CHK_ERROR ( SQL_HANDLE_ENV, hEnv, status, "" ); #ifdef _WIN64 // ----------- real connection takes place at this point // ----------- option 1: user is prompted for DSN & options status = SQLDriverConnect ( hConn, GetDesktopWindow(), ( unsigned char* ) "", SQL_NTS, szConnStrOut, 1024, &x, SQL_DRIVER_COMPLETE ); #else status = SQLDriverConnectW ( hConn , GetDesktopWindow(), //L"DSN=testDSN;", L"DRIVER={KylinODBCDriver};PROJECT=default;UID=ADMIN;SERVER=http://localhost;PORT=80;", SQL_NTS, szConnStrOut, 1024, &x, SQL_DRIVER_COMPLETE ); #endif // check for error ODBC_CHK_ERROR ( SQL_HANDLE_DBC, hConn, status, "" ); // CONGRATUALTIONS ---- u r connected to a DBMS via an ODBC driver // allocate STATEMENT status = SQLAllocHandle ( SQL_HANDLE_STMT, hConn, &hStmt ); // check for error ODBC_CHK_ERROR ( SQL_HANDLE_DBC, hConn, status, "" ); // execute the statement //status = SQLExecDirect ( hStmt, ( unsigned char* )argv[1], SQL_NTS ); status = SQLExecDirectW ( hStmt, ( SQLWCHAR* ) sql, SQL_NTS ); // check for error ODBC_CHK_ERROR ( SQL_HANDLE_STMT, hConn, status, "" ); // RESULTS READY // show the full results row by row status = CheckResults ( hStmt, sql ); totalCount++; if ( status == SQL_ERROR ) { setPrintColorRED(); fputs ( "[FAIL]\n", stdout ); resetPrintColor(); failCount++; failedQueries.push_back ( sql ); } else if ( status == SQL_SUCCESS ) { setPrintColorGreen(); fputs ( "[SUCCESS]\n", stdout ); resetPrintColor(); successCount++; } // check for error ODBC_CHK_ERROR ( SQL_HANDLE_STMT, hStmt, status, "" ); Cleanup: if ( hStmt ) { SQLFreeHandle ( SQL_HANDLE_STMT, hStmt ); } if ( hConn ) { SQLFreeHandle ( SQL_HANDLE_DBC, hConn ); } if ( hEnv ) { SQLFreeHandle ( SQL_HANDLE_ENV, hEnv ); } return; } void validateQueries ( char* file ) { std::string line; std::ifstream infile ( file ); while ( std::getline ( infile, line ) ) { if ( line.size() < 5 ) { continue; } unique_ptr<wchar_t[]> p ( char2wchar ( line.c_str() ) ); validateOneQuery ( p.get() ); } infile.close(); } bool isValueConsistent ( void* data, wstring& valueJ, int pSrcDataType, bool isSigned ) { fwprintf ( stdout, L"The value from the JDBC is : %s \n", valueJ.c_str() ); switch ( pSrcDataType ) { case SQL_BIT: { wstring tempW; if ( * ( char* ) data == 0 ) { tempW = L"false"; } else if ( * ( char* ) data == 1 ) { tempW = L"true"; } else { return false; } return tempW.compare ( valueJ ) == 0; } case SQL_CHAR: case SQL_VARCHAR: { string temp ( ( char* ) data ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_WCHAR: case SQL_WVARCHAR: { wstring tempW ( ( wchar_t* ) data ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_DECIMAL: { string temp ( ( char* ) data ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_TINYINT: { int v = 0; if ( isSigned ) { v = * ( char* ) data; } else { v = * ( unsigned char* ) data; } char buffer[100]; _itoa ( v, buffer, 10 ); string temp ( buffer ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_SMALLINT: { int v = 0; if ( isSigned ) { v = * ( short* ) data; } else { v = * ( unsigned short* ) data; } char buffer[100]; _itoa ( v, buffer, 10 ); string temp ( buffer ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_INTEGER: { __int64 v = 0; if ( isSigned ) { v = * ( int* ) data; } else { v = * ( unsigned int* ) data; } char buffer[100]; _i64toa ( v, buffer, 10 ); string temp ( buffer ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_BIGINT: { if ( isSigned ) { __int64 v = 0; v = * ( __int64* ) data; char buffer[100]; _i64toa ( v, buffer, 10 ); string temp ( buffer ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } else { unsigned __int64 v = 0; v = * ( unsigned __int64* ) data; char buffer[100]; _ui64toa ( v, buffer, 10 ); string temp ( buffer ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } } case SQL_FLOAT: { float v = 0; v = * ( float* ) data; fwprintf ( stdout, L"The value from the ODBC is (float) : %9.9f \n", v ); double x = ( v - _wtof ( valueJ.c_str() ) ); return ( x > -0.0000001 ) && ( x < 0.0000001 ); // In Kylin float is treated like double, so it might be more accurate } case SQL_DOUBLE: { double v = * ( double* ) data; fwprintf ( stdout, L"The value from the ODBC is (double) : %9.9f\n ", v ); return v == wcstod ( valueJ.c_str(), NULL ); } case SQL_TYPE_DATE: { string temp ( ( char* ) data ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } case SQL_TYPE_TIMESTAMP: { string temp ( ( char* ) data ); wstring tempW = string2wstring ( temp ); fwprintf ( stdout, L"The value from the ODBC is : %s \n", tempW.c_str() ); return tempW.compare ( valueJ ) == 0; } default: return false; } } // ---------------------------------------------------------------------------- // to validate the full results row by row // ---------------------------------------------------------------------------- SQLRETURN CheckResults ( HSTMT hStmt , wchar_t* sql ) { //First directly call REST to get a JDBC version result to compare against std::unique_ptr<SQLResponse> response = restQuery ( sql, "http://localhost", 80, "ADMIN", "KADMIN", "default" ); //Go with hStmt now int i, iCol; BIND_COL_INFO* head; BIND_COL_INFO* last; BIND_COL_INFO* curr; SQLRETURN status; SQLLEN cType; SQLSMALLINT iColCount; // initializations head = NULL; // ALLOCATE SPACE TO FETCH A COMPLETE ROW // get number of cols if ( ( status = SQLNumResultCols ( hStmt, &iColCount ) ) != SQL_SUCCESS ) { return status; } // loop to allocate binding info structure for ( iCol = 1; iCol <= iColCount; iCol ++ ) { // alloc binding structure curr = ( BIND_COL_INFO* ) calloc ( 1, sizeof ( BIND_COL_INFO ) ); if ( curr == NULL ) { fprintf ( stderr, "Out of memory!\n" ); return SQL_ERROR; // its not an ODBC error so no diags r required } memset ( curr, 0, sizeof ( BIND_COL_INFO ) ); // maintain link list if ( iCol == 1 ) { head = curr; } // first col, therefore head of list else { last->next = curr; } // attach last = curr; // tail // get column title size if ( ( status = SQLColAttributeW ( hStmt, iCol, SQL_DESC_NAME, NULL, 0, & ( curr->iColTitleSize ), NULL ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } else { ++ curr->iColTitleSize; // allow space for null char } // allocate buffer for title curr->szColTitle = ( wchar_t* ) calloc ( 1, curr->iColTitleSize * sizeof ( wchar_t ) ); if ( curr->szColTitle == NULL ) { FreeBindings ( head ); fprintf ( stderr, "Out of memory!\n" ); return SQL_ERROR; // its not an ODBC error so no diags r required } // get column title if ( ( status = SQLColAttributeW ( hStmt, iCol, SQL_DESC_NAME, curr->szColTitle, curr->iColTitleSize, & ( curr->iColTitleSize ), NULL ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } //xxx // get col length if ( ( status = SQLColAttributeW ( hStmt, iCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, & ( curr->iColDisplaySize ) ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } // arbitrary limit on display size if ( curr->iColDisplaySize > _DISPLAY_MAX ) { curr->iColDisplaySize = _DISPLAY_MAX; } // allocate buffer for col data + NULL terminator curr->szColData = ( void* ) calloc ( 1, 2 * ( curr->iColDisplaySize + 1 ) * sizeof ( char ) ); if ( curr->szColData == NULL ) { FreeBindings ( head ); fprintf ( stderr, "Out of memory!\n" ); return SQL_ERROR; // its not an ODBC error so no diags r required } //xxx // get col type, not used now but can be checked to print value right aligned etcc if ( ( status = SQLColAttributeW ( hStmt, iCol, SQL_DESC_CONCISE_TYPE, NULL, 0, NULL, &cType ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } curr->iType = cType; fprintf ( stdout, "The type for column %d is %d\n", iCol, cType ); //xxx // get col type, not used now but can be checked to print value right aligned etcc SQLLEN unsignedV = 0; if ( ( status = SQLColAttributeW ( hStmt, iCol, SQL_DESC_UNSIGNED , NULL, 0, NULL, &unsignedV ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } curr->isSigned = ( unsignedV == 1 ) ? false : true; fprintf ( stdout, "The column %d is signed ? %d\n", iCol, curr->isSigned ); // set col type indicator in struct curr->fChar = ( cType == SQL_CHAR || cType == SQL_VARCHAR || cType == SQL_LONGVARCHAR || cType == SQL_WCHAR || cType == SQL_WVARCHAR || cType == SQL_WLONGVARCHAR ); fprintf ( stdout, "char flag is set to %d\n", curr->fChar ); fputs ( "\n", stdout ); //xxx // bind the col buffer so that the driver feeds it with col value on every fetch and use generic char binding for very column if ( ( status = SQLBindCol ( hStmt, iCol, SQL_C_DEFAULT, ( SQLPOINTER ) curr->szColData, 2 * ( curr->iColDisplaySize + 1 ) * sizeof ( char ), & ( curr->indPtr ) ) ) != SQL_SUCCESS ) { FreeBindings ( head ); return status; } } // loop to print all the rows one by one for ( i = 1; TRUE; i ++ ) { // fetch the next row if ( ( status = SQLFetch ( hStmt ) ) == SQL_NO_DATA_FOUND ) { break; } // no more rows so break // check for error else if ( status == SQL_ERROR ) { // fetch failed FreeBindings ( head ); return status; } for ( curr = head, iCol = 0; iCol < iColCount; iCol ++, curr = curr->next ) { fprintf ( stdout, "Row Index: %d, Column Cardinal : %d\n", i - 1, iCol ); if ( !isValueConsistent ( curr->szColData, response->results[i - 1]->contents[iCol], curr->iType, curr->isSigned ) ) { FreeBindings ( head ); return SQL_ERROR; } fputs ( "\n", stdout ); } } // free the allocated bindings FreeBindings ( head ); return SQL_SUCCESS; } // ---------------------------------------------------------------------------- // to free the col info allocated by ShowFullResults // ---------------------------------------------------------------------------- void FreeBindings ( BIND_COL_INFO* pBindColInfo ) { BIND_COL_INFO* next; // precaution if ( pBindColInfo ) { do { // get the next col binding next = pBindColInfo->next; // free any buffer for col title if ( pBindColInfo->szColTitle ) { free ( pBindColInfo->szColTitle ); pBindColInfo->szColTitle = NULL; } // free any col data if ( pBindColInfo->szColData ) { free ( pBindColInfo->szColData ); pBindColInfo->szColData = NULL; } // free the current binding free ( pBindColInfo ); // make next the current pBindColInfo = next; } while ( pBindColInfo ); } } // ---------------------------------------------------------------------------- // to show the ODBC diagnostic messages // ---------------------------------------------------------------------------- void ShowDiagMessages ( SQLSMALLINT hType, SQLHANDLE hValue, SQLRETURN iStatus, char* szMsg ) { SQLSMALLINT iRec = 0; SQLINTEGER iError; SQLTCHAR szMessage[1024]; SQLTCHAR szState[1024]; // header fputs ( "\nDiagnostics:\n" , stdout ); // in case of an invalid handle, no message can be extracted if ( iStatus == SQL_INVALID_HANDLE ) { fprintf ( stderr, "ODBC Error: Invalid handle!\n" ); return; } // loop to get all diag messages from driver/driver manager while ( SQLGetDiagRec ( hType, hValue, ++ iRec, szState, &iError, szMessage, ( SQLSMALLINT ) ( sizeof ( szMessage ) / sizeof ( SQLTCHAR ) ), ( SQLSMALLINT* ) NULL ) == SQL_SUCCESS ) { _ftprintf ( stderr, TEXT ( "[%5.5s] %s (%d)\n" ), szState, szMessage, iError ); } // gap fputs ( "\n" , stdout ); } void crossValidate() { char* queryFile = "testqueries.txt"; //char* queryFile = "c:\\foo.txt"; fprintf ( stdout, "The test queries file location is: %s\n", queryFile ); //validateOneQuery(L"SELECT * FROM classicmodels.new_table;"); validateQueries ( queryFile ); fprintf ( stdout, "The verify process is done.\n", queryFile ); fprintf ( stdout, "Total queries: %d, Successful queries: %d, Failed queries: %d.\n", totalCount, successCount, failCount ); for ( vector<wstring>::iterator iter = failedQueries.begin(); iter != failedQueries.end(); ++iter ) { fprintf ( stdout, wstring2string ( *iter ).c_str() ); fprintf ( stdout, "\n\n" ); } }
38.149057
134
0.476186
[ "vector" ]
957e2221115503279a2484783c37088daea1683b
2,444
cpp
C++
libs/c2ba/src/window_manager/window_manager.cpp
Celeborn2BeAlive/c2ba-graphics-cpp-sdk
752484b37d56eb87ac1f777d630d50e283d192e5
[ "MIT" ]
null
null
null
libs/c2ba/src/window_manager/window_manager.cpp
Celeborn2BeAlive/c2ba-graphics-cpp-sdk
752484b37d56eb87ac1f777d630d50e283d192e5
[ "MIT" ]
null
null
null
libs/c2ba/src/window_manager/window_manager.cpp
Celeborn2BeAlive/c2ba-graphics-cpp-sdk
752484b37d56eb87ac1f777d630d50e283d192e5
[ "MIT" ]
1
2020-09-03T01:30:31.000Z
2020-09-03T01:30:31.000Z
#include <c2ba/glutils/debug_output.hpp> #include <c2ba/window_manager/glfw.hpp> #include <c2ba/window_manager/window_manager.hpp> #include <fmt/format.h> #include <imgui.h> #include <imgui_impl_glfw.h> #include <imgui_impl_opengl3.h> #include <stdexcept> namespace c2ba { WindowManager::WindowManager(uint16_t width, uint16_t height, const char * title) { if (!glfwInit()) { const auto what = "Unable to init GLFW.\n"; fmt::print(stderr, what); throw std::runtime_error(what); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, 4); m_pWindow = glfwCreateWindow(int(width), int(height), title, nullptr, nullptr); if (!m_pWindow) { const auto what = "Unable to open window.\n"; fmt::print(stderr, what); throw std::runtime_error(what); } glfwMakeContextCurrent(m_pWindow); glfwSwapInterval(0); // No VSync if (!gladLoadGL()) { const auto what = "Unable to init OpenGL.\n"; fmt::print(stderr, what); throw std::runtime_error(what); } c2ba::initGLDebugOutput(); // Setup ImGui ImGui::CreateContext(); ImGui_ImplGlfw_InitForOpenGL(m_pWindow, true); const char * glsl_version = "#version 130"; ImGui_ImplOpenGL3_Init(glsl_version); } WindowManager::~WindowManager() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow(m_pWindow); glfwTerminate(); } bool WindowManager::shouldClose() const { return glfwWindowShouldClose(m_pWindow); } glm::ivec2 WindowManager::framebufferSize() const { int displayWidth, displayHeight; glfwGetFramebufferSize(m_pWindow, &displayWidth, &displayHeight); return glm::ivec2(displayWidth, displayHeight); } void WindowManager::swapBuffers() const { glfwSwapBuffers(m_pWindow); } void pollEvents() { glfwPollEvents(); } double getSeconds() { return glfwGetTime(); } void imguiNewFrame() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); } void imguiRenderFrame() { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } } // namespace c2ba
22.841121
83
0.700082
[ "render" ]
9583fb23f02a85a5dbf5e68f8dc134290bf72e43
10,619
cpp
C++
webkit/WebCore/bridge/runtime_object.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/bridge/runtime_object.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/bridge/runtime_object.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2003, 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "runtime_object.h" #include "JSDOMBinding.h" #include "runtime_method.h" #include <runtime/Error.h> #include <runtime/ObjectPrototype.h> using namespace WebCore; namespace JSC { using namespace Bindings; const ClassInfo RuntimeObjectImp::s_info = { "RuntimeObject", 0, 0, 0 }; RuntimeObjectImp::RuntimeObjectImp(ExecState* exec, PassRefPtr<Instance> instance) // FIXME: deprecatedGetDOMStructure uses the prototype off of the wrong global object // We need to pass in the right global object for "i". : JSObject(deprecatedGetDOMStructure<RuntimeObjectImp>(exec)) , m_instance(instance) { } RuntimeObjectImp::RuntimeObjectImp(ExecState*, NonNullPassRefPtr<Structure> structure, PassRefPtr<Instance> instance) : JSObject(structure) , m_instance(instance) { } RuntimeObjectImp::~RuntimeObjectImp() { if (m_instance) m_instance->willDestroyRuntimeObject(); } void RuntimeObjectImp::invalidate() { ASSERT(m_instance); if (m_instance) m_instance->willInvalidateRuntimeObject(); m_instance = 0; } JSValue RuntimeObjectImp::fallbackObjectGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { RuntimeObjectImp* thisObj = static_cast<RuntimeObjectImp*>(asObject(slot.slotBase())); RefPtr<Instance> instance = thisObj->m_instance; if (!instance) return throwInvalidAccessError(exec); instance->begin(); Class *aClass = instance->getClass(); JSValue result = aClass->fallbackObject(exec, instance.get(), propertyName); instance->end(); return result; } JSValue RuntimeObjectImp::fieldGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { RuntimeObjectImp* thisObj = static_cast<RuntimeObjectImp*>(asObject(slot.slotBase())); RefPtr<Instance> instance = thisObj->m_instance; if (!instance) return throwInvalidAccessError(exec); instance->begin(); Class *aClass = instance->getClass(); Field* aField = aClass->fieldNamed(propertyName, instance.get()); JSValue result = aField->valueFromInstance(exec, instance.get()); instance->end(); return result; } JSValue RuntimeObjectImp::methodGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { RuntimeObjectImp* thisObj = static_cast<RuntimeObjectImp*>(asObject(slot.slotBase())); RefPtr<Instance> instance = thisObj->m_instance; if (!instance) return throwInvalidAccessError(exec); instance->begin(); Class *aClass = instance->getClass(); MethodList methodList = aClass->methodsNamed(propertyName, instance.get()); JSValue result = new (exec) RuntimeMethod(exec, propertyName, methodList); instance->end(); return result; } bool RuntimeObjectImp::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) { if (!m_instance) { throwInvalidAccessError(exec); return false; } RefPtr<Instance> instance = m_instance; instance->begin(); Class *aClass = instance->getClass(); if (aClass) { // See if the instance has a field with the specified name. Field *aField = aClass->fieldNamed(propertyName, instance.get()); if (aField) { slot.setCustom(this, fieldGetter); instance->end(); return true; } else { // Now check if a method with specified name exists, if so return a function object for // that method. MethodList methodList = aClass->methodsNamed(propertyName, instance.get()); if (methodList.size() > 0) { slot.setCustom(this, methodGetter); instance->end(); return true; } } // Try a fallback object. if (!aClass->fallbackObject(exec, instance.get(), propertyName).isUndefined()) { slot.setCustom(this, fallbackObjectGetter); instance->end(); return true; } } instance->end(); return instance->getOwnPropertySlot(this, exec, propertyName, slot); } bool RuntimeObjectImp::getOwnPropertyDescriptor(ExecState *exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { if (!m_instance) { throwInvalidAccessError(exec); return false; } RefPtr<Instance> instance = m_instance; instance->begin(); Class *aClass = instance->getClass(); if (aClass) { // See if the instance has a field with the specified name. Field *aField = aClass->fieldNamed(propertyName, instance.get()); if (aField) { PropertySlot slot; slot.setCustom(this, fieldGetter); instance->end(); descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete); return true; } else { // Now check if a method with specified name exists, if so return a function object for // that method. MethodList methodList = aClass->methodsNamed(propertyName, instance.get()); if (methodList.size() > 0) { PropertySlot slot; slot.setCustom(this, methodGetter); instance->end(); descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete | ReadOnly); return true; } } // Try a fallback object. if (!aClass->fallbackObject(exec, instance.get(), propertyName).isUndefined()) { PropertySlot slot; slot.setCustom(this, fallbackObjectGetter); instance->end(); descriptor.setDescriptor(slot.getValue(exec, propertyName), DontDelete | ReadOnly | DontEnum); return true; } } instance->end(); return instance->getOwnPropertyDescriptor(this, exec, propertyName, descriptor); } void RuntimeObjectImp::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot) { if (!m_instance) { throwInvalidAccessError(exec); return; } RefPtr<Instance> instance = m_instance; instance->begin(); // Set the value of the property. Field *aField = instance->getClass()->fieldNamed(propertyName, instance.get()); if (aField) aField->setValueToInstance(exec, instance.get(), value); else if (!instance->setValueOfUndefinedField(exec, propertyName, value)) instance->put(this, exec, propertyName, value, slot); instance->end(); } bool RuntimeObjectImp::deleteProperty(ExecState*, const Identifier&) { // Can never remove a property of a RuntimeObject. return false; } JSValue RuntimeObjectImp::defaultValue(ExecState* exec, PreferredPrimitiveType hint) const { if (!m_instance) return throwInvalidAccessError(exec); RefPtr<Instance> instance = m_instance; instance->begin(); JSValue result = instance->defaultValue(exec, hint); instance->end(); return result; } static JSValue JSC_HOST_CALL callRuntimeObject(ExecState* exec, JSObject* function, JSValue, const ArgList& args) { RefPtr<Instance> instance(static_cast<RuntimeObjectImp*>(function)->getInternalInstance()); instance->begin(); JSValue result = instance->invokeDefaultMethod(exec, args); instance->end(); return result; } CallType RuntimeObjectImp::getCallData(CallData& callData) { if (!m_instance) return CallTypeNone; RefPtr<Instance> instance = m_instance; if (!instance->supportsInvokeDefaultMethod()) return CallTypeNone; callData.native.function = callRuntimeObject; return CallTypeHost; } static JSObject* callRuntimeConstructor(ExecState* exec, JSObject* constructor, const ArgList& args) { RefPtr<Instance> instance(static_cast<RuntimeObjectImp*>(constructor)->getInternalInstance()); instance->begin(); JSValue result = instance->invokeConstruct(exec, args); instance->end(); ASSERT(result); return result.isObject() ? static_cast<JSObject*>(result.asCell()) : constructor; } ConstructType RuntimeObjectImp::getConstructData(ConstructData& constructData) { if (!m_instance) return ConstructTypeNone; RefPtr<Instance> instance = m_instance; if (!instance->supportsConstruct()) return ConstructTypeNone; constructData.native.function = callRuntimeConstructor; return ConstructTypeHost; } void RuntimeObjectImp::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames) { if (!m_instance) { throwInvalidAccessError(exec); return; } RefPtr<Instance> instance = m_instance; instance->begin(); instance->getPropertyNames(exec, propertyNames); instance->end(); } void RuntimeObjectImp::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames) { getOwnPropertyNames(exec, propertyNames); } JSObject* RuntimeObjectImp::throwInvalidAccessError(ExecState* exec) { return throwError(exec, ReferenceError, "Trying to access object from destroyed plug-in."); } }
32.178788
128
0.679725
[ "object" ]
9587d53f11226c7eba04d29bf1431b80fb4e9e2d
2,968
hpp
C++
src/map/include/MIIteratorL2.hpp
mu94-csl/wfmash
98e26fcdfec6a98fe4d0528240a8f5d957604505
[ "MIT" ]
218
2017-11-03T12:38:08.000Z
2022-03-31T22:24:55.000Z
src/map/include/MIIteratorL2.hpp
mu94-csl/wfmash
98e26fcdfec6a98fe4d0528240a8f5d957604505
[ "MIT" ]
94
2017-11-30T14:21:38.000Z
2022-03-30T16:04:35.000Z
src/map/include/MIIteratorL2.hpp
mu94-csl/wfmash
98e26fcdfec6a98fe4d0528240a8f5d957604505
[ "MIT" ]
44
2018-02-16T11:03:59.000Z
2022-01-21T00:09:21.000Z
/** * @file MIIteratorL2.hpp * @brief implements iterator over minimizer index to process L2 mapping stage * @author Chirag Jain <cjain7@gatech.edu> */ #ifndef INDEX_ITERATOR_L2_HPP #define INDEX_ITERATOR_L2_HPP #include <vector> #include <algorithm> #include <map> //Own includes #include "map/include/base_types.hpp" //External includes namespace skch { /** * @class skch::MIIteratorL2 * @brief L1 and L2 mapping stages */ class MIIteratorL2 { private: //Container type for saving read sketches during L1 and L2 both typedef Sketch::MI_Type MinVec_Type; typedef Sketch::MIIter_t MIIter_t; //Current begin position of a super-window //each next operation advances this value offset_t sw_pos; //Count of minimizer windows in a 'super-window' offset_t countMinimizerWindows; public: //Delete default constructor MIIteratorL2() = delete; //Current super-window range is bounded by [beg, end) on minimizer index MIIter_t sw_beg; MIIter_t sw_end; /** * @brief constructor for MIIteratorL2 class * @details sets the position and iterator values for the * first super-window */ MIIteratorL2( MIIter_t firstSuperWindowRangeStart, MIIter_t firstSuperWindowRangeEnd, offset_t countMinimizerWindows_ ) : sw_beg (firstSuperWindowRangeStart), sw_end (firstSuperWindowRangeEnd), countMinimizerWindows (countMinimizerWindows_) { //Search for the end iterator of the first super-window over index this->sw_pos = this->sw_beg->wpos; } /** * @brief advances the current super-window by a minimum shift * possible on the minimizer index * @details begin position of super-window is advanced by atleast 1 position * Either or both 'beg' and 'end' iterators get right shifted * @NOTE Calling function is expected to respect the bound of the reference index, * this function will mis-behave if reached outside the index range */ inline void next() { offset_t beginPos = this->sw_pos; offset_t lastPos = this->sw_pos + this->countMinimizerWindows - 1; // Always, range [beg, end) represents the minimizers in the // current super-window assert( (this->sw_beg+1)->wpos - beginPos > 0 ); assert( (this->sw_end )->wpos - lastPos > 0 ); offset_t advanceBy = std::min( (this->sw_beg+1)->wpos - beginPos, (this->sw_end)->wpos - lastPos); //Advance current super-window this->sw_pos += advanceBy; //Advance 'beg' and 'end' iterators if(advanceBy == (this->sw_beg + 1)->wpos - beginPos) this->sw_beg++; if(advanceBy == (this->sw_end)->wpos - lastPos) this->sw_end++; } }; } #endif
29.386139
106
0.628369
[ "vector" ]
95885a32be7752124d0d15925647285625ea718a
15,742
cpp
C++
STAccel/src/iopinChecker.cpp
UCLA-VAST/EISC
6455dff287beddc82c5880309943b82bb9d8642d
[ "MIT" ]
25
2019-06-16T00:19:03.000Z
2022-02-22T02:38:59.000Z
STAccel/src/iopinChecker.cpp
UCLA-VAST/EISC
6455dff287beddc82c5880309943b82bb9d8642d
[ "MIT" ]
6
2020-04-21T03:24:31.000Z
2020-11-06T18:45:44.000Z
STAccel/src/iopinChecker.cpp
UCLA-VAST/EISC
6455dff287beddc82c5880309943b82bb9d8642d
[ "MIT" ]
12
2019-08-01T17:06:21.000Z
2022-02-12T00:52:56.000Z
#include <fstream> #include <iostream> #include <map> #include <string> #include <vector> using namespace std; map<string, string> neccessaryPinsMap; vector<string> stringOccurs; vector<string> unmatchedStrings; void setup() { neccessaryPinsMap["peek_req_V_dout"] = "input [31:0] peek_req_V_dout;"; neccessaryPinsMap["peek_req_V_empty_n"] = "input peek_req_V_empty_n;"; neccessaryPinsMap["peek_req_V_read"] = "output peek_req_V_read;"; neccessaryPinsMap["peek_resp_V_din"] = "output [31:0] peek_resp_V_din;"; neccessaryPinsMap["peek_resp_V_full_n"] = "input peek_resp_V_full_n;"; neccessaryPinsMap["peek_resp_V_write"] = "output peek_resp_V_write;"; neccessaryPinsMap["poke_V_data_dout"] = "input [31:0] poke_V_data_dout;"; neccessaryPinsMap["poke_V_data_empty_n"] = "input poke_V_data_empty_n;"; neccessaryPinsMap["poke_V_data_read"] = "output poke_V_data_read;"; neccessaryPinsMap["poke_V_tag_dout"] = "input [31:0] poke_V_tag_dout;"; neccessaryPinsMap["poke_V_tag_empty_n"] = "input poke_V_tag_empty_n;"; neccessaryPinsMap["poke_V_tag_read"] = "output poke_V_tag_read;"; neccessaryPinsMap["pcie_write_req_data_V_last_din"] = "output pcie_write_req_data_V_last_din;"; neccessaryPinsMap["pcie_write_req_data_V_last_full_n"] = "input pcie_write_req_data_V_last_full_n;"; neccessaryPinsMap["pcie_write_req_data_V_last_write"] = "output pcie_write_req_data_V_last_write;"; neccessaryPinsMap["pcie_write_req_data_V_data_V_din"] = "output [511:0] pcie_write_req_data_V_data_V_din;"; neccessaryPinsMap["pcie_write_req_data_V_data_V_full_n"] = "input pcie_write_req_data_V_data_V_full_n;"; neccessaryPinsMap["pcie_write_req_data_V_data_V_write"] = "output pcie_write_req_data_V_data_V_write;"; neccessaryPinsMap["pcie_write_req_apply_V_num_din"] = "output [7:0] pcie_write_req_apply_V_num_din;"; neccessaryPinsMap["pcie_write_req_apply_V_num_full_n"] = "input pcie_write_req_apply_V_num_full_n;"; neccessaryPinsMap["pcie_write_req_apply_V_num_write"] = "output pcie_write_req_apply_V_num_write;"; neccessaryPinsMap["pcie_write_req_apply_V_addr_din"] = "output [63:0] pcie_write_req_apply_V_addr_din;"; neccessaryPinsMap["pcie_write_req_apply_V_addr_full_n"] = "input pcie_write_req_apply_V_addr_full_n;"; neccessaryPinsMap["pcie_write_req_apply_V_addr_write"] = "output pcie_write_req_apply_V_addr_write;"; neccessaryPinsMap["pcie_read_req_V_num_din"] = "output [7:0] pcie_read_req_V_num_din;"; neccessaryPinsMap["pcie_read_req_V_num_full_n"] = "input pcie_read_req_V_num_full_n;"; neccessaryPinsMap["pcie_read_req_V_num_write"] = "output pcie_read_req_V_num_write;"; neccessaryPinsMap["pcie_read_req_V_addr_din"] = "output [63:0] pcie_read_req_V_addr_din;"; neccessaryPinsMap["pcie_read_req_V_addr_full_n"] = "input pcie_read_req_V_addr_full_n;"; neccessaryPinsMap["pcie_read_req_V_addr_write"] = "output pcie_read_req_V_addr_write;"; neccessaryPinsMap["pcie_read_resp_V_last_dout"] = "input pcie_read_resp_V_last_dout;"; neccessaryPinsMap["pcie_read_resp_V_last_empty_n"] = "input pcie_read_resp_V_last_empty_n;"; neccessaryPinsMap["pcie_read_resp_V_last_read"] = "output pcie_read_resp_V_last_read;"; neccessaryPinsMap["pcie_read_resp_V_data_V_dout"] = "input [511:0] pcie_read_resp_V_data_V_dout;"; neccessaryPinsMap["pcie_read_resp_V_data_V_empty_n"] = "input pcie_read_resp_V_data_V_empty_n;"; neccessaryPinsMap["pcie_read_resp_V_data_V_read"] = "output pcie_read_resp_V_data_V_read;"; neccessaryPinsMap["dramA_read_req_V_num_din"] = "output [7:0] dramA_read_req_V_num_din;"; neccessaryPinsMap["dramA_read_req_V_num_full_n"] = "input dramA_read_req_V_num_full_n;"; neccessaryPinsMap["dramA_read_req_V_num_write"] = "output dramA_read_req_V_num_write;"; neccessaryPinsMap["dramA_read_req_V_addr_din"] = "output [63:0] dramA_read_req_V_addr_din;"; neccessaryPinsMap["dramA_read_req_V_addr_full_n"] = "input dramA_read_req_V_addr_full_n;"; neccessaryPinsMap["dramA_read_req_V_addr_write"] = "output dramA_read_req_V_addr_write;"; neccessaryPinsMap["dramA_read_resp_V_last_dout"] = "input dramA_read_resp_V_last_dout;"; neccessaryPinsMap["dramA_read_resp_V_last_empty_n"] = "input dramA_read_resp_V_last_empty_n;"; neccessaryPinsMap["dramA_read_resp_V_last_read"] = "output dramA_read_resp_V_last_read;"; neccessaryPinsMap["dramA_read_resp_V_data_V_dout"] = "input [511:0] dramA_read_resp_V_data_V_dout;"; neccessaryPinsMap["dramA_read_resp_V_data_V_empty_n"] = "input dramA_read_resp_V_data_V_empty_n;"; neccessaryPinsMap["dramA_read_resp_V_data_V_read"] = "output dramA_read_resp_V_data_V_read;"; neccessaryPinsMap["dramA_write_req_data_V_last_din"] = "output dramA_write_req_data_V_last_din;"; neccessaryPinsMap["dramA_write_req_data_V_last_full_n"] = "input dramA_write_req_data_V_last_full_n;"; neccessaryPinsMap["dramA_write_req_data_V_last_write"] = "output dramA_write_req_data_V_last_write;"; neccessaryPinsMap["dramA_write_req_data_V_data_V_din"] = "output [511:0] dramA_write_req_data_V_data_V_din;"; neccessaryPinsMap["dramA_write_req_data_V_data_V_full_n"] = "input dramA_write_req_data_V_data_V_full_n;"; neccessaryPinsMap["dramA_write_req_data_V_data_V_write"] = "output dramA_write_req_data_V_data_V_write;"; neccessaryPinsMap["dramA_write_req_apply_V_num_din"] = "output [7:0] dramA_write_req_apply_V_num_din;"; neccessaryPinsMap["dramA_write_req_apply_V_num_full_n"] = "input dramA_write_req_apply_V_num_full_n;"; neccessaryPinsMap["dramA_write_req_apply_V_num_write"] = "output dramA_write_req_apply_V_num_write;"; neccessaryPinsMap["dramA_write_req_apply_V_addr_din"] = "output [63:0] dramA_write_req_apply_V_addr_din;"; neccessaryPinsMap["dramA_write_req_apply_V_addr_full_n"] = "input dramA_write_req_apply_V_addr_full_n;"; neccessaryPinsMap["dramA_write_req_apply_V_addr_write"] = "output dramA_write_req_apply_V_addr_write;"; neccessaryPinsMap["dramB_read_req_V_num_din"] = "output [7:0] dramB_read_req_V_num_din;"; neccessaryPinsMap["dramB_read_req_V_num_full_n"] = "input dramB_read_req_V_num_full_n;"; neccessaryPinsMap["dramB_read_req_V_num_write"] = "output dramB_read_req_V_num_write;"; neccessaryPinsMap["dramB_read_req_V_addr_din"] = "output [63:0] dramB_read_req_V_addr_din;"; neccessaryPinsMap["dramB_read_req_V_addr_full_n"] = "input dramB_read_req_V_addr_full_n;"; neccessaryPinsMap["dramB_read_req_V_addr_write"] = "output dramB_read_req_V_addr_write;"; neccessaryPinsMap["dramB_read_resp_V_last_dout"] = "input dramB_read_resp_V_last_dout;"; neccessaryPinsMap["dramB_read_resp_V_last_empty_n"] = "input dramB_read_resp_V_last_empty_n;"; neccessaryPinsMap["dramB_read_resp_V_last_read"] = "output dramB_read_resp_V_last_read;"; neccessaryPinsMap["dramB_read_resp_V_data_V_dout"] = "input [511:0] dramB_read_resp_V_data_V_dout;"; neccessaryPinsMap["dramB_read_resp_V_data_V_empty_n"] = "input dramB_read_resp_V_data_V_empty_n;"; neccessaryPinsMap["dramB_read_resp_V_data_V_read"] = "output dramB_read_resp_V_data_V_read;"; neccessaryPinsMap["dramB_write_req_data_V_last_din"] = "output dramB_write_req_data_V_last_din;"; neccessaryPinsMap["dramB_write_req_data_V_last_full_n"] = "input dramB_write_req_data_V_last_full_n;"; neccessaryPinsMap["dramB_write_req_data_V_last_write"] = "output dramB_write_req_data_V_last_write;"; neccessaryPinsMap["dramB_write_req_data_V_data_V_din"] = "output [511:0] dramB_write_req_data_V_data_V_din;"; neccessaryPinsMap["dramB_write_req_data_V_data_V_full_n"] = "input dramB_write_req_data_V_data_V_full_n;"; neccessaryPinsMap["dramB_write_req_data_V_data_V_write"] = "output dramB_write_req_data_V_data_V_write;"; neccessaryPinsMap["dramB_write_req_apply_V_num_din"] = "output [7:0] dramB_write_req_apply_V_num_din;"; neccessaryPinsMap["dramB_write_req_apply_V_num_full_n"] = "input dramB_write_req_apply_V_num_full_n;"; neccessaryPinsMap["dramB_write_req_apply_V_num_write"] = "output dramB_write_req_apply_V_num_write;"; neccessaryPinsMap["dramB_write_req_apply_V_addr_din"] = "output [63:0] dramB_write_req_apply_V_addr_din;"; neccessaryPinsMap["dramB_write_req_apply_V_addr_full_n"] = "input dramB_write_req_apply_V_addr_full_n;"; neccessaryPinsMap["dramB_write_req_apply_V_addr_write"] = "output dramB_write_req_apply_V_addr_write;"; neccessaryPinsMap["dramC_read_req_V_num_din"] = "output [7:0] dramC_read_req_V_num_din;"; neccessaryPinsMap["dramC_read_req_V_num_full_n"] = "input dramC_read_req_V_num_full_n;"; neccessaryPinsMap["dramC_read_req_V_num_write"] = "output dramC_read_req_V_num_write;"; neccessaryPinsMap["dramC_read_req_V_addr_din"] = "output [63:0] dramC_read_req_V_addr_din;"; neccessaryPinsMap["dramC_read_req_V_addr_full_n"] = "input dramC_read_req_V_addr_full_n;"; neccessaryPinsMap["dramC_read_req_V_addr_write"] = "output dramC_read_req_V_addr_write;"; neccessaryPinsMap["dramC_read_resp_V_last_dout"] = "input dramC_read_resp_V_last_dout;"; neccessaryPinsMap["dramC_read_resp_V_last_empty_n"] = "input dramC_read_resp_V_last_empty_n;"; neccessaryPinsMap["dramC_read_resp_V_last_read"] = "output dramC_read_resp_V_last_read;"; neccessaryPinsMap["dramC_read_resp_V_data_V_dout"] = "input [511:0] dramC_read_resp_V_data_V_dout;"; neccessaryPinsMap["dramC_read_resp_V_data_V_empty_n"] = "input dramC_read_resp_V_data_V_empty_n;"; neccessaryPinsMap["dramC_read_resp_V_data_V_read"] = "output dramC_read_resp_V_data_V_read;"; neccessaryPinsMap["dramC_write_req_data_V_last_din"] = "output dramC_write_req_data_V_last_din;"; neccessaryPinsMap["dramC_write_req_data_V_last_full_n"] = "input dramC_write_req_data_V_last_full_n;"; neccessaryPinsMap["dramC_write_req_data_V_last_write"] = "output dramC_write_req_data_V_last_write;"; neccessaryPinsMap["dramC_write_req_data_V_data_V_din"] = "output [511:0] dramC_write_req_data_V_data_V_din;"; neccessaryPinsMap["dramC_write_req_data_V_data_V_full_n"] = "input dramC_write_req_data_V_data_V_full_n;"; neccessaryPinsMap["dramC_write_req_data_V_data_V_write"] = "output dramC_write_req_data_V_data_V_write;"; neccessaryPinsMap["dramC_write_req_apply_V_num_din"] = "output [7:0] dramC_write_req_apply_V_num_din;"; neccessaryPinsMap["dramC_write_req_apply_V_num_full_n"] = "input dramC_write_req_apply_V_num_full_n;"; neccessaryPinsMap["dramC_write_req_apply_V_num_write"] = "output dramC_write_req_apply_V_num_write;"; neccessaryPinsMap["dramC_write_req_apply_V_addr_din"] = "output [63:0] dramC_write_req_apply_V_addr_din;"; neccessaryPinsMap["dramC_write_req_apply_V_addr_full_n"] = "input dramC_write_req_apply_V_addr_full_n;"; neccessaryPinsMap["dramC_write_req_apply_V_addr_write"] = "output dramC_write_req_apply_V_addr_write;"; neccessaryPinsMap["dramD_read_req_V_num_din"] = "output [7:0] dramD_read_req_V_num_din;"; neccessaryPinsMap["dramD_read_req_V_num_full_n"] = "input dramD_read_req_V_num_full_n;"; neccessaryPinsMap["dramD_read_req_V_num_write"] = "output dramD_read_req_V_num_write;"; neccessaryPinsMap["dramD_read_req_V_addr_din"] = "output [63:0] dramD_read_req_V_addr_din;"; neccessaryPinsMap["dramD_read_req_V_addr_full_n"] = "input dramD_read_req_V_addr_full_n;"; neccessaryPinsMap["dramD_read_req_V_addr_write"] = "output dramD_read_req_V_addr_write;"; neccessaryPinsMap["dramD_read_resp_V_last_dout"] = "input dramD_read_resp_V_last_dout;"; neccessaryPinsMap["dramD_read_resp_V_last_empty_n"] = "input dramD_read_resp_V_last_empty_n;"; neccessaryPinsMap["dramD_read_resp_V_last_read"] = "output dramD_read_resp_V_last_read;"; neccessaryPinsMap["dramD_read_resp_V_data_V_dout"] = "input [511:0] dramD_read_resp_V_data_V_dout;"; neccessaryPinsMap["dramD_read_resp_V_data_V_empty_n"] = "input dramD_read_resp_V_data_V_empty_n;"; neccessaryPinsMap["dramD_read_resp_V_data_V_read"] = "output dramD_read_resp_V_data_V_read;"; neccessaryPinsMap["dramD_write_req_data_V_last_din"] = "output dramD_write_req_data_V_last_din;"; neccessaryPinsMap["dramD_write_req_data_V_last_full_n"] = "input dramD_write_req_data_V_last_full_n;"; neccessaryPinsMap["dramD_write_req_data_V_last_write"] = "output dramD_write_req_data_V_last_write;"; neccessaryPinsMap["dramD_write_req_data_V_data_V_din"] = "output [511:0] dramD_write_req_data_V_data_V_din;"; neccessaryPinsMap["dramD_write_req_data_V_data_V_full_n"] = "input dramD_write_req_data_V_data_V_full_n;"; neccessaryPinsMap["dramD_write_req_data_V_data_V_write"] = "output dramD_write_req_data_V_data_V_write;"; neccessaryPinsMap["dramD_write_req_apply_V_num_din"] = "output [7:0] dramD_write_req_apply_V_num_din;"; neccessaryPinsMap["dramD_write_req_apply_V_num_full_n"] = "input dramD_write_req_apply_V_num_full_n;"; neccessaryPinsMap["dramD_write_req_apply_V_num_write"] = "output dramD_write_req_apply_V_num_write;"; neccessaryPinsMap["dramD_write_req_apply_V_addr_din"] = "output [63:0] dramD_write_req_apply_V_addr_din;"; neccessaryPinsMap["dramD_write_req_apply_V_addr_full_n"] = "input dramD_write_req_apply_V_addr_full_n;"; neccessaryPinsMap["dramD_write_req_apply_V_addr_write"] = "output dramD_write_req_apply_V_addr_write;"; } string eliminateSpc(string str) { int l = 0; int r = str.size() - 1; while (str[l] == ' ' || str[l] == '\t') l++; while (str[r] == ' ' || str[r] == '\t') r--; return str.substr(l, r - l + 1); } int main() { setup(); freopen("project/design/interconnects.v", "r", stdin); freopen("project/design/interconnects.v.new", "w", stdout); string s; bool reachModuleStart = false; bool finished = false; while (getline(cin, s)) { bool noPrint = false; if (!finished) { if (reachModuleStart) { if (eliminateSpc(s) == ");") { cout << "," << endl; bool first = true; for (auto it = neccessaryPinsMap.begin(); it != neccessaryPinsMap.end(); ++it) { string key = it->first; bool matched = false; for (auto s : stringOccurs) { if (s == key) { matched = true; break; } } if (!matched) { unmatchedStrings.push_back(key); if (first) { first = false; cout << key << endl; } else { cout << "," << key << endl; } } } noPrint = true; cout << ");" << endl; for (auto s : unmatchedStrings) { cout << neccessaryPinsMap[s] << endl; } finished = true; } else { stringOccurs.push_back(eliminateSpc(s.substr(0, s.size() - 1))); } } else if (s.substr(0, 6) == "module") { reachModuleStart = true; } } if (!noPrint) { cout << s << endl; } } return 0; }
46.436578
76
0.740884
[ "vector" ]
9593956f8d0aab5557ad6980ff4b4276ab1146cd
4,001
cc
C++
xpdf/Outline.cc
haephrati/SG_PDF2Text
393ba8b500de6d10ab7c38936c009a5c44fa4189
[ "Apache-2.0" ]
1
2021-10-30T07:53:44.000Z
2021-10-30T07:53:44.000Z
xpdf/Outline.cc
haephrati/SG_PDF2Text
393ba8b500de6d10ab7c38936c009a5c44fa4189
[ "Apache-2.0" ]
1
2018-11-13T17:41:46.000Z
2018-11-13T20:54:38.000Z
xpdf/Outline.cc
haephrati/SG_PDF2Text
393ba8b500de6d10ab7c38936c009a5c44fa4189
[ "Apache-2.0" ]
1
2018-11-13T16:43:10.000Z
2018-11-13T16:43:10.000Z
//======================================================================== // // Outline.cc // // Copyright 2002-2013 Glyph & Cog, LLC // //======================================================================== #include <aconf.h> #ifdef USE_GCC_PRAGMAS #pragma implementation #endif #include "gmem.h" #include "gmempp.h" #include "GString.h" #include "GList.h" #include "Error.h" #include "Link.h" #include "TextString.h" #include "Outline.h" //------------------------------------------------------------------------ Outline::Outline(Object *outlineObj, XRef *xref) { Object first, last; items = NULL; if (!outlineObj->isDict()) { return; } outlineObj->dictLookupNF("First", &first); outlineObj->dictLookupNF("Last", &last); if (first.isRef() && last.isRef()) { items = OutlineItem::readItemList(&first, &last, NULL, xref); } first.free(); last.free(); } Outline::~Outline() { if (items) { deleteGList(items, OutlineItem); } } //------------------------------------------------------------------------ OutlineItem::OutlineItem(Object *itemRefA, Dict *dict, OutlineItem *parentA, XRef *xrefA) { Object obj1; xref = xrefA; title = NULL; action = NULL; kids = NULL; parent = parentA; if (dict->lookup("Title", &obj1)->isString()) { title = new TextString(obj1.getString()); } obj1.free(); if (!dict->lookup("Dest", &obj1)->isNull()) { action = LinkAction::parseDest(&obj1); } else { obj1.free(); if (!dict->lookup("A", &obj1)->isNull()) { action = LinkAction::parseAction(&obj1); } } obj1.free(); itemRefA->copy(&itemRef); dict->lookupNF("First", &firstRef); dict->lookupNF("Last", &lastRef); dict->lookupNF("Next", &nextRef); startsOpen = gFalse; if (dict->lookup("Count", &obj1)->isInt()) { if (obj1.getInt() > 0) { startsOpen = gTrue; } } obj1.free(); pageNum = -1; } OutlineItem::~OutlineItem() { close(); if (title) { delete title; } if (action) { delete action; } itemRef.free(); firstRef.free(); lastRef.free(); nextRef.free(); } GList *OutlineItem::readItemList(Object *firstItemRef, Object *lastItemRef, OutlineItem *parentA, XRef *xrefA) { GList *items; OutlineItem *item, *sibling; Object obj; Object *p; OutlineItem *ancestor; int i; items = new GList(); if (!firstItemRef->isRef() || !lastItemRef->isRef()) { return items; } p = firstItemRef; do { if (!p->fetch(xrefA, &obj)->isDict()) { obj.free(); break; } item = new OutlineItem(p, obj.getDict(), parentA, xrefA); obj.free(); // check for loops with parents for (ancestor = parentA; ancestor; ancestor = ancestor->parent) { if (p->getRefNum() == ancestor->itemRef.getRefNum() && p->getRefGen() == ancestor->itemRef.getRefGen()) { error(errSyntaxError, -1, "Loop detected in outline"); break; } } if (ancestor) { delete item; break; } // check for loops with siblings for (i = 0; i < items->getLength(); ++i) { sibling = (OutlineItem *)items->get(i); if (p->getRefNum() == sibling->itemRef.getRefNum() && p->getRefGen() == sibling->itemRef.getRefGen()) { error(errSyntaxError, -1, "Loop detected in outline"); break; } } if (i < items->getLength()) { delete item; break; } items->append(item); if (p->getRefNum() == lastItemRef->getRef().num && p->getRefGen() == lastItemRef->getRef().gen) { break; } p = &item->nextRef; if (!p->isRef()) { break; } } while (p); return items; } void OutlineItem::open() { if (!kids) { kids = readItemList(&firstRef, &lastRef, this, xref); } } void OutlineItem::close() { if (kids) { deleteGList(kids, OutlineItem); kids = NULL; } } Unicode *OutlineItem::getTitle() { return title ? title->getUnicode() : (Unicode *)NULL; } int OutlineItem::getTitleLength() { return title ? title->getLength() : 0; }
21.395722
75
0.553112
[ "object" ]
d2fa7e937125ed74fb6a347615d36dbae975a13b
58,785
cpp
C++
third_party/pdfium/core/src/reflow/layoutprocessor_reflow.cpp
satorumpen/node-pdfium-native
90e5bf8bc69c80620f9f4231ebf8e39ef1178b8c
[ "BSD-2-Clause" ]
303
2015-03-13T08:31:24.000Z
2022-03-21T10:06:45.000Z
third_party/pdfium/core/src/reflow/layoutprocessor_reflow.cpp
satorumpen/node-pdfium-native
90e5bf8bc69c80620f9f4231ebf8e39ef1178b8c
[ "BSD-2-Clause" ]
15
2015-04-03T02:33:53.000Z
2020-01-28T10:42:29.000Z
third_party/pdfium/core/src/reflow/layoutprocessor_reflow.cpp
satorumpen/node-pdfium-native
90e5bf8bc69c80620f9f4231ebf8e39ef1178b8c
[ "BSD-2-Clause" ]
100
2015-03-13T08:28:56.000Z
2022-02-18T03:19:39.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../include/reflow/reflowengine.h" #include "reflowedpage.h" #include "layoutprovider_taggedpdf.h" IPDF_LayoutProcessor* IPDF_LayoutProcessor::Create_LayoutProcessor_Reflow(FX_FLOAT TopIndent, FX_FLOAT fWidth, FX_FLOAT fHeight, void* pReflowedPage, int flags, FX_FLOAT lineSpace ) { if(pReflowedPage == NULL || fWidth <= 20) { return NULL; } CPDF_LayoutProcessor_Reflow* pReflowEngine = FX_NEW CPDF_LayoutProcessor_Reflow(); if (NULL == pReflowEngine) { return NULL; } pReflowEngine->Init(TopIndent, fWidth, fHeight, (CPDF_ReflowedPage*)pReflowedPage, flags, lineSpace); return pReflowEngine; } CPDF_LayoutProcessor_Reflow::CPDF_LayoutProcessor_Reflow() { m_pPause = NULL; m_pLayoutElement = NULL; m_fRefWidth = 0; m_fRefWidth = 0; m_fCurrLineWidth = 0; m_fCurrLineHeight = 0; m_bIllustration = FALSE; m_pPreObj = NULL; m_pCurrLine = FX_NEW CRF_DataPtrArray(50); m_pTempLine = FX_NEW CRF_DataPtrArray(50); m_StartIndent = 0; m_PausePosition = 0; } CPDF_LayoutProcessor_Reflow::~CPDF_LayoutProcessor_Reflow() { if (m_pCurrLine) { m_pCurrLine->RemoveAll(); delete m_pCurrLine; } m_pCurrLine = NULL; if (m_pTempLine) { m_pTempLine->RemoveAll(); delete m_pTempLine; } m_pTempLine = NULL; } void CPDF_LayoutProcessor_Reflow::Init(FX_FLOAT TopIndent, FX_FLOAT fWidth, FX_FLOAT fHeight, CPDF_ReflowedPage* pReflowedPage, int flags, FX_FLOAT lineSpace) { m_pLayoutElement = NULL; m_TopIndent = TopIndent; m_Status = LayoutReady; m_flags = flags; m_pReflowedPage = pReflowedPage; m_fScreenHeight = fHeight; m_fRefWidth = fWidth; m_fCurrLineHeight = 0; m_fCurrLineWidth = 0; m_fLineSpace = lineSpace; pReflowedPage->m_PageWidth = fWidth; pReflowedPage->m_PageHeight = TopIndent; } void CPDF_LayoutProcessor_Reflow::FitPageMode() { if(m_flags & RF_PARSER_PAGEMODE && m_fScreenHeight > 20) { float fitPageHeight = m_fScreenHeight; CPDF_ReflowedPage* pRFPage = m_pReflowedPage; int count = pRFPage->m_pReflowed->GetSize(); CFX_WordArray dy; dy.Add(0); int pos = 0; int screenCount = 1; FX_FLOAT h = pRFPage->GetPageHeight(); while (h > screenCount * fitPageHeight) { FX_FLOAT tempPageHeight = screenCount * fitPageHeight; int j = 0; FX_FLOAT tempDy = 0; for(int i = 0; i < count; i++) { CRF_Data* pData = (*pRFPage->m_pReflowed)[i]; FX_FLOAT posY; posY = pData->m_PosY; if(FXSYS_fabs(posY) > tempPageHeight && FXSYS_fabs(posY + pData->m_Height) < tempPageHeight) { if(j == 0) { j = i; } if(pData->m_Height > fitPageHeight) { FX_FLOAT zoom; FX_FLOAT spaceh = screenCount * fitPageHeight + posY + pData->m_Height; if(spaceh < fitPageHeight / 3 * 2) { spaceh = fitPageHeight; } zoom = spaceh / pData->m_Height; tempDy = spaceh - pData->m_Height; pData->m_Height = spaceh; pData->m_Width *= zoom; break; } FX_FLOAT dy = pData->m_PosY + pData->m_Height + tempPageHeight; if(dy > tempDy) { tempDy = dy; } } else if(FXSYS_fabs(posY + pData->m_Height) > tempPageHeight) { break; } } for(; j < count; j++) { CRF_Data* pData = (*pRFPage->m_pReflowed)[j]; FX_FLOAT posY; posY = pData->m_PosY; if(FXSYS_fabs(posY) > tempPageHeight ) { pData->m_PosY -= tempDy; } if(pData->m_Height >= fitPageHeight) { pData->m_Height = fitPageHeight - 1; if(pData->GetType() == CRF_Data::Text) { CRF_CharData* pCharData = (CRF_CharData*)pData; pCharData->m_pCharState->m_fFontSize = pData->m_Height; } } } pRFPage->m_PageHeight += tempDy; h += tempDy; screenCount++; } } } LayoutStatus CPDF_LayoutProcessor_Reflow::StartProcess(IPDF_LayoutElement* pElement, IFX_Pause* pPause, const CFX_AffineMatrix* pPDFMatrix) { if(!pElement) { return LayoutError; } m_pPause = pPause; m_PDFMatrix = *pPDFMatrix; m_pRootElement = pElement; ProcessElement(m_pRootElement, m_fRefWidth); if(m_Status == LayoutToBeContinued) { return LayoutToBeContinued; } m_Status = LayoutFinished; FitPageMode(); return LayoutFinished; } LayoutStatus CPDF_LayoutProcessor_Reflow::Continue() { int size = m_pReflowedPage->m_pReflowed->GetSize(); ProcessElement(m_pRootElement, m_CurrRefWidth); size = m_pReflowedPage->m_pReflowed->GetSize(); if(m_Status == LayoutReady) { m_Status = LayoutFinished; FitPageMode(); } return m_Status; } int CPDF_LayoutProcessor_Reflow::GetPosition() { return m_PausePosition; } FX_BOOL CPDF_LayoutProcessor_Reflow::IsCanBreakAfter(FX_DWORD unicode) { if(unicode == -1) { return FALSE; } switch(unicode) { case 40: case 91: case 123: return FALSE; } if(unicode >= 256) { return TRUE; } else if(unicode >= 48 && unicode <= 57) { return FALSE; } else if(unicode >= 64 && unicode <= 90) { return FALSE; } else if(unicode >= 97 && unicode <= 122) { return FALSE; } return TRUE; } FX_BOOL CPDF_LayoutProcessor_Reflow::IsCanBreakBefore(FX_DWORD unicode) { if(unicode == -1) { return FALSE; } switch(unicode) { case 33: case 41: case 44: case 46: case 59: case 63: case 93: case 125: return FALSE; } if(unicode >= 256) { return TRUE; } else if(unicode >= 48 && unicode <= 57) { return FALSE; } else if(unicode >= 64 && unicode <= 90) { return FALSE; } else if(unicode >= 97 && unicode <= 122) { return FALSE; } return TRUE; } void CPDF_LayoutProcessor_Reflow::ProcessTable(FX_FLOAT dx) { if(m_pReflowedPage->m_pReflowed->GetSize() == 0) { return; } CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); int rowCount = pTable->m_nCell.GetSize(); int n = 0; FX_FLOAT* dyRow = FX_Alloc(FX_FLOAT, rowCount + 1); FXSYS_memset32(dyRow, 0, sizeof(FX_FLOAT) * (rowCount + 1)); dyRow[0] = 0 ; dyRow[0] = - pTable->m_ReflowPageHeight; int tableColCount = 0; int i; for(i = 0; i < rowCount; i++) { int colCount = pTable->m_nCell.GetAt(i); if(colCount > tableColCount) { tableColCount = colCount; } } int cellCount = tableColCount * rowCount; RF_TableCell** pVirtualTable = FX_Alloc(RF_TableCell*, cellCount); FXSYS_memset32(pVirtualTable, 0, sizeof(RF_TableCell*) * cellCount); for(i = 0; i < rowCount; i++) { int colCount = pTable->m_nCell.GetAt(i); FX_FLOAT rowWidth = 0; int j = 0; int s = pTable->m_pCellArray.GetSize(); for(j = 0; j < colCount; j++) { RF_TableCell* pCell = (RF_TableCell*)pTable->m_pCellArray.GetAt(n++); if(pCell->m_EndPos < pCell->m_BeginPos) { continue; } int pos = i * tableColCount; while(pos < cellCount && pVirtualTable[pos] != NULL) { pos++; } if(pos >= (i + 1) * tableColCount) { pos = i * tableColCount + j; } int RowSpan = pCell->m_RowSpan; int ColSpan = pCell->m_ColSpan; if(RowSpan + i > rowCount) { RowSpan = rowCount - i; } if(ColSpan + j > colCount) { ColSpan = colCount - j; } for(int m = 0; m < RowSpan; m++) { for(int nn = 0; nn < ColSpan; nn++) { if(pos + nn >= cellCount) { break; } pVirtualTable[pos + nn] = pCell; } pos += tableColCount; } FX_FLOAT dxCell = dx; for(pos = i * tableColCount; pVirtualTable[pos] != pCell && pos < cellCount; pos++) { dxCell += (pVirtualTable[pos])->m_MaxWidth; } CRF_Data* pData = (*m_pReflowedPage->m_pReflowed)[pCell->m_BeginPos]; FX_FLOAT dy = dyRow[i] - pData->m_Height - pData->m_PosY; CFX_AffineMatrix matrix(1, 0, 0, 1, dxCell, dy); Transform(&matrix, m_pReflowedPage->m_pReflowed, pCell->m_BeginPos, pCell->m_EndPos - pCell->m_BeginPos + 1); if(pCell->m_RowSpan + i <= rowCount) { if(FXSYS_fabs(dyRow[pCell->m_RowSpan + i]) < FXSYS_fabs(dyRow[i] - pCell->m_CellHeight)) { dyRow[pCell->m_RowSpan + i] = dyRow[i] - pCell->m_CellHeight; } } } } n = 0; for(i = 0; i < rowCount; i++) { int colCount = pTable->m_nCell.GetAt(i); for(int j = 0; j < colCount; j++) { RF_TableCell* pCell = (RF_TableCell*)pTable->m_pCellArray.GetAt(n++); switch(pCell->m_BlockAlign) { case LayoutAfter: { FX_FLOAT dy = dyRow[i + pCell->m_RowSpan] - pCell->m_CellHeight - dyRow[i]; CFX_AffineMatrix matrix(1, 0, 0, 1, 0, dy); Transform(&matrix, m_pReflowedPage->m_pReflowed, pCell->m_BeginPos, pCell->m_EndPos - pCell->m_BeginPos + 1); } break; case LayoutMiddle: case LayoutJustify: { FX_FLOAT dy = (dyRow[i + pCell->m_RowSpan] + pCell->m_CellHeight - dyRow[i]) / 2; CFX_AffineMatrix matrix(1, 0, 0, 1, 0, dy); Transform(&matrix, m_pReflowedPage->m_pReflowed, pCell->m_BeginPos, pCell->m_EndPos - pCell->m_BeginPos + 1); break; } default: break; } } } CRF_Data* pData = (*m_pReflowedPage->m_pReflowed)[m_pReflowedPage->m_pReflowed->GetSize() - 1]; m_pReflowedPage->m_PageHeight = - dyRow[rowCount] + pData->m_Height; FX_Free(pVirtualTable); FX_Free(dyRow); int size = pTable->m_pCellArray.GetSize(); for(i = 0; i < size; i++) { RF_TableCell* pCell = pTable->m_pCellArray.GetAt(i); FX_Free(pCell); } pTable->m_pCellArray.RemoveAll(); pTable->m_nCell.RemoveAll(); int s = sizeof(CRF_Table); delete pTable; m_TableArray.RemoveAt(m_TableArray.GetSize() - 1); } CFX_FloatRect CPDF_LayoutProcessor_Reflow::GetElmBBox(IPDF_LayoutElement* pElement) { CFX_FloatRect rect; int objCount = pElement->CountObjects(); int count = pElement->CountChildren(); if(objCount == 0 && count == 0) { return rect; } CFX_AffineMatrix matrix; int i; for(i = 0; i < objCount; i++) { CPDF_PageObject* pObj = pElement->GetObject(0); if(!pObj) { continue; } if( rect.Height() == 0 ) { rect = pObj->GetBBox(&matrix); } else { rect.Union(pObj->GetBBox(&matrix)); } } for(i = 0; i < count; i++) { IPDF_LayoutElement* pChildElement = pElement->GetChild(i); if( rect.Height() == 0 ) { rect = GetElmBBox(pChildElement); } else { rect.Union(GetElmBBox(pChildElement)); } } return rect; } FX_FLOAT CPDF_LayoutProcessor_Reflow::GetElmWidth(IPDF_LayoutElement* pElement) { if(!pElement) { return 0; } LayoutType layoutType = pElement->GetType(); FX_FLOAT width = 0; if(layoutType == LayoutTable || layoutType == LayoutTableDataCell || layoutType == LayoutTableHeaderCell) { width = pElement->GetNumberAttr(LayoutWidth); if(width > 0) { return width; } } else if( layoutType == LayoutTableRow) { int count = pElement->CountChildren(); for(int i = 0; i < count; i++) { IPDF_LayoutElement* pElm = pElement->GetChild(i); width += pElm->GetNumberAttr(LayoutWidth); } if(width > 0) { return width; } } CFX_FloatRect rect = GetElmBBox(pElement); return rect.Width(); } FX_BOOL GetIntersection(FX_FLOAT low1, FX_FLOAT high1, FX_FLOAT low2, FX_FLOAT high2, FX_FLOAT& interlow, FX_FLOAT& interhigh); FX_BOOL IsSameLine(FX_BOOL bHorizontal, CFX_FloatRect Rect1, CFX_FloatRect Rect2) { if(bHorizontal) { FX_FLOAT inter_top, inter_bottom; if (!GetIntersection(Rect1.bottom, Rect1.top, Rect2.bottom, Rect2.top, inter_bottom, inter_top)) { return FALSE; } FX_FLOAT lineHeight = Rect1.top - Rect1.bottom; if(lineHeight > 20 && lineHeight > Rect2.Height() * 2) { return FALSE; } if(lineHeight > 5 && Rect2.Height() / 2 > lineHeight) { return FALSE; } FX_FLOAT inter_h = inter_top - inter_bottom; if (inter_h < (lineHeight) / 2 && inter_h < Rect2.Height() / 2) { return FALSE; } } else { FX_FLOAT inter_left, inter_right; if(!GetIntersection(Rect1.left, Rect1.right, Rect2.left, Rect2.right, inter_left, inter_right)) { return FALSE; } FX_FLOAT inter_w = inter_right - inter_left; if (inter_w < (Rect1.right - Rect1.left) / 2 && inter_w < (Rect2.right - Rect2.left) / 2) { return FALSE; } } return TRUE; } FX_INT32 IsCanMergeParagraph(IPDF_LayoutElement* pPrevElement, IPDF_LayoutElement* pNextElement) { FX_INT32 analogial = 100; FX_INT32 nPrevObj = pPrevElement->CountObjects(), i; CPDF_PageObject* pPrevObj = NULL; CFX_FloatRect prevRect, rect; CFX_PtrArray prevLine, line; FX_BOOL bParagraphStart = FALSE; for(i = 0; i < nPrevObj; i++) { CPDF_PageObject* pObj = pPrevElement->GetObject(i); if(!pPrevObj) { pPrevObj = pObj; rect = CFX_FloatRect(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); line.Add(pObj); continue; } CFX_FloatRect objRect = CFX_FloatRect(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); if(IsSameLine(TRUE, rect, objRect)) { line.Add(pObj); rect.Union(objRect); } else { prevLine.RemoveAll(); prevLine.Append(line); prevRect = rect; line.RemoveAll(); line.Add(pObj); rect = objRect; if(!bParagraphStart) { if (prevRect.left > rect.left + rect.Height() * 1.5) { bParagraphStart = TRUE; } } } } if(prevLine.GetSize()) { if(FXSYS_fabs(rect.right - prevRect.right) > rect.Height()) { analogial -= 50; } } CPDF_PageObject* pObj = pPrevElement->GetObject(nPrevObj - 1); if(pObj->m_Type == PDFPAGE_TEXT) { CPDF_TextObject* pText = (CPDF_TextObject*)pObj; FX_INT32 nItem = pText->CountItems(); CPDF_TextObjectItem item; pText->GetItemInfo(nItem - 1, &item); CFX_WideString wStr = pText->GetFont()->UnicodeFromCharCode(item.m_CharCode); if(wStr.IsEmpty()) { wStr = (FX_WCHAR)item.m_CharCode; } FX_WCHAR wch = wStr.GetAt(wStr.GetLength() - 1); switch(wch) { case '.': case 12290: case 65311: case 63: case 33: case 65281: analogial -= 50; break; } } prevLine.RemoveAll(); prevLine.Append(line); line.RemoveAll(); FX_INT32 nNextObj = pNextElement->CountObjects(); pPrevObj = NULL; FX_BOOL bFirst = TRUE; for(i = 0; i < nNextObj; i++) { CPDF_PageObject* pObj = pNextElement->GetObject(i); if(!pPrevObj) { pPrevObj = pObj; rect = CFX_FloatRect(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); line.Add(pObj); continue; } CFX_FloatRect objRect = CFX_FloatRect(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); if(IsSameLine(TRUE, rect, objRect)) { line.Add(pObj); rect.Union(objRect); } else { if(FXSYS_fabs(rect.right - prevRect.right) < rect.Height() && FXSYS_fabs(rect.left - prevRect.left) < rect.Height()) { analogial += 50; } prevLine.RemoveAll(); prevLine.Append(line); prevRect = rect; line.RemoveAll(); line.Add(pObj); rect = objRect; if(!bFirst) { break; } bFirst = FALSE; } } if(prevLine.GetSize()) { if(bParagraphStart) { if(prevRect.left - rect.left > rect.Height() && prevRect.left - rect.left < rect.Height() * 3) { analogial -= 50; } } else { if(FXSYS_fabs(prevRect.left - rect.left) < rect.Height()) { analogial -= 50; } } } return analogial; } void CPDF_LayoutProcessor_Reflow::ProcessElement(IPDF_LayoutElement* pElement, FX_FLOAT reflowWidth) { if(pElement == NULL) { return; } if(m_Status == LayoutReady) { LayoutType layoutType = pElement->GetType(); FX_INT32 ElementType = GetElementTypes(layoutType); switch(ElementType) { case SST_IE: m_bIllustration = TRUE; break; case SST_BLSE: FinishedCurrLine(); FX_FLOAT StartIndent = 0; if(IPDF_LayoutElement* pParent = pElement->GetParent()) { StartIndent = pParent->GetNumberAttr(LayoutStartIndent); } FX_FLOAT currStartIndent = pElement->GetNumberAttr(LayoutStartIndent); m_StartIndent = ConverWidth(currStartIndent); FX_FLOAT width = reflowWidth; if(StartIndent != currStartIndent) { reflowWidth -= m_StartIndent; } FX_FLOAT spaceBefore = pElement->GetNumberAttr(LayoutSpaceBefore); m_pReflowedPage->m_PageHeight += spaceBefore; m_TextAlign = pElement->GetEnumAttr(LayoutTextAlign); if(IPDF_LayoutElement* pParent = pElement->GetParent()) { StartIndent = pParent->GetNumberAttr(LayoutEndIndent); FX_FLOAT currEndIndent = pElement->GetNumberAttr(LayoutEndIndent); if(StartIndent != currStartIndent) { reflowWidth -= ConverWidth(currEndIndent); } } if(reflowWidth * 2 < width) { reflowWidth = width; m_StartIndent = 0; } break; } switch(layoutType) { case LayoutTable: { CRF_Table* pTable = FX_NEW CRF_Table; if (NULL == pTable) { break; } m_TableArray.Add(pTable); pTable->m_ReflowPageHeight = m_pReflowedPage->m_PageHeight; pTable->m_TableWidth = GetElmWidth(pElement); break; } case LayoutTableRow: { if(!m_TableArray.GetSize()) { break; } int count = pElement->CountChildren(); CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); int f = 0; for(int i = 0; i < count; i++) { IPDF_LayoutElement* pChildElement = pElement->GetChild(i); LayoutType type = pChildElement->GetType(); if(type == LayoutTableDataCell || type == LayoutTableHeaderCell) { f++; } } pTable->m_nCell.Add(f); break; } case LayoutTableDataCell: case LayoutTableHeaderCell: { if(!m_TableArray.GetSize()) { break; } RF_TableCell* pCell = FX_Alloc(RF_TableCell, 1); FXSYS_memset32(pCell, 0 , sizeof(RF_TableCell)); CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); int pos = pTable->m_nCell.GetSize() - 1; pCell->m_BeginPos = m_pReflowedPage->m_pReflowed->GetSize(); FX_FLOAT cellWidth = pElement->GetNumberAttr(LayoutWidth); if(cellWidth == 0 || pCell->m_MaxWidth > pTable->m_TableWidth) { CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); pCell->m_MaxWidth = reflowWidth / pTable->m_nCell.GetAt(pTable->m_nCell.GetSize() - 1); } else { pCell->m_MaxWidth = pElement->GetNumberAttr(LayoutWidth) * reflowWidth / pTable->m_TableWidth; } pCell->m_ColSpan = (int)(pElement->GetNumberAttr(LayoutColSpan)); pCell->m_RowSpan = (int)(pElement->GetNumberAttr(LayoutRowSpan)); if(!pCell->m_ColSpan) { pCell->m_ColSpan = 1; } if(!pCell->m_RowSpan ) { pCell->m_RowSpan = 1; } pCell->m_BlockAlign = pElement->GetEnumAttr(LayoutBlockAlign); m_TextAlign = pElement->GetEnumAttr(LayoutInlineAlign); pCell->m_PosX = 0; pCell->m_PosY = 0; reflowWidth = pCell->m_MaxWidth; pTable->m_pCellArray.Add(pCell); break; } default: break; } m_fLineHeight = pElement->GetNumberAttr(LayoutLineHeight); int ReflowedSize = m_pReflowedPage->m_pReflowed->GetSize(); if(pElement->CountObjects()) { ProcessObjs(pElement, reflowWidth); } } int count = pElement->CountChildren(); for(int i = 0; i < count; i++) { IPDF_LayoutElement* pChildElement = pElement->GetChild(i); ProcessElement(pChildElement, reflowWidth); if(m_pPause && m_pRootElement == pElement && m_Status != LayoutToBeContinued ) { if(m_pPause->NeedToPauseNow()) { m_pLayoutElement = pChildElement; m_Status = LayoutToBeContinued; m_CurrRefWidth = reflowWidth; m_PausePosition = (i + 1) * 100 / (count + 1); return ; } } if(m_Status == LayoutToBeContinued && m_pLayoutElement == pChildElement) { m_Status = LayoutReady; } } if(m_Status == LayoutReady) { FX_FLOAT dx = 0; LayoutType layoutType = pElement->GetType(); FX_INT32 ElementType = GetElementTypes(layoutType); switch(ElementType) { case SST_IE: m_bIllustration = FALSE; FinishedCurrLine(); break; case SST_BLSE: FinishedCurrLine(); FX_FLOAT StartIndent = 0; if(IPDF_LayoutElement* pParent = pElement->GetParent()) { StartIndent = pParent->GetNumberAttr(LayoutStartIndent); } FX_FLOAT currStartIndent = pElement->GetNumberAttr(LayoutStartIndent); if(StartIndent != currStartIndent) { reflowWidth += ConverWidth(currStartIndent); dx += ConverWidth(currStartIndent); } FX_FLOAT spaceAfter = pElement->GetNumberAttr(LayoutSpaceAfter); m_pReflowedPage->m_PageHeight += spaceAfter; break; } switch(layoutType) { case LayoutTableDataCell: case LayoutTableHeaderCell: { if(!m_TableArray.GetSize()) { break; } CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); RF_TableCell* pCell = pTable->m_pCellArray.GetAt(pTable->m_pCellArray.GetSize() - 1); pCell->m_EndPos = m_pReflowedPage->m_pReflowed->GetSize() - 1; if(pCell->m_EndPos < pCell->m_BeginPos) { pCell->m_CellHeight = 0; } else { CRF_Data* pBeginData = (*m_pReflowedPage->m_pReflowed)[pCell->m_BeginPos]; CRF_Data* pEndData = (*m_pReflowedPage->m_pReflowed)[pCell->m_EndPos]; pCell->m_CellHeight = pBeginData->m_Height > pEndData->m_Height ? pBeginData->m_Height : pEndData->m_Height; pCell->m_CellHeight -= pEndData->m_PosY - pBeginData->m_PosY; } break; } case LayoutTableRow: { if(!m_TableArray.GetSize()) { break; } CRF_Table* pTable = m_TableArray.GetAt(m_TableArray.GetSize() - 1); if(pTable->m_nCol == 0) { pTable->m_nCol = pTable->m_pCellArray.GetSize(); } break; } case LayoutTable: { ProcessTable(dx); break; } default: if(dx) { CFX_AffineMatrix matrix(1, 0, 0, 1, dx, 0); int ReflowedSize = m_pReflowedPage->m_pReflowed->GetSize(); Transform(&matrix, m_pReflowedPage->m_pReflowed, ReflowedSize, m_pReflowedPage->m_pReflowed->GetSize() - ReflowedSize); } } } if(m_pRootElement == pElement) { m_PausePosition = 100; } } FX_INT32 CPDF_LayoutProcessor_Reflow::GetElementTypes(LayoutType layoutType) { switch(layoutType) { case LayoutParagraph: case LayoutHeading: case LayoutHeading1: case LayoutHeading2: case LayoutHeading3: case LayoutHeading4: case LayoutHeading5: case LayoutHeading6: case LayoutList: case LayoutListItem: case LayoutListLabel: case LayoutListBody: case LayoutTable: case LayoutTableHeaderCell: case LayoutTableDataCell: case LayoutTableRow: case LayoutTableHeaderGroup: case LayoutTableBodyGroup: case LayoutTableFootGroup: case LayoutTOCI: case LayoutCaption: return SST_BLSE; case LayoutFigure: case LayoutFormula: case LayoutForm: return SST_IE; case LayoutSpan: case LayoutQuote: case LayoutNote: case LayoutReference: case LayoutBibEntry: case LayoutCode: case LayoutLink: case LayoutAnnot: case LayoutRuby: case LayoutWarichu: return SST_ILSE; default: return SST_GE; } return FALSE; } FX_FLOAT CPDF_LayoutProcessor_Reflow::ConverWidth(FX_FLOAT width) { return width; } void CPDF_LayoutProcessor_Reflow::ProcessObject(CPDF_PageObject* pObj, FX_FLOAT reflowWidth, CFX_AffineMatrix objMatrix) { if(!pObj) { return; } if(pObj->m_Type == PDFPAGE_TEXT) { ProcessTextObject( (CPDF_TextObject *)pObj, reflowWidth, objMatrix); } else if(pObj->m_Type == PDFPAGE_IMAGE) { if(!(m_flags & RF_PARSER_IMAGE)) { return; } CPDF_PageObjects* pObjs = FX_NEW CPDF_PageObjects(FALSE); if (NULL == pObjs) { return; } FX_POSITION pos = pObjs->GetLastObjectPosition(); pos = pObjs->InsertObject(pos, pObj); CFX_AffineMatrix matrix; FX_RECT rect = pObj->GetBBox(&matrix); CPDF_ImageObject* ImageObj = (CPDF_ImageObject*)pObj; ProcessUnitaryObjs(pObjs, reflowWidth, objMatrix); delete pObjs; } else if(pObj->m_Type == PDFPAGE_PATH) { } else if(pObj->m_Type == PDFPAGE_FORM) { CPDF_FormObject* pForm = (CPDF_FormObject*)pObj; FX_POSITION pos = pForm->m_pForm->GetFirstObjectPosition(); objMatrix.Concat(pForm->m_FormMatrix); while (pos) { CPDF_PageObject* pObj1 = pForm->m_pForm->GetNextObject(pos); ProcessObject(pObj1, reflowWidth, objMatrix); } } } void CPDF_LayoutProcessor_Reflow::ProcessObjs(IPDF_LayoutElement* pElement, FX_FLOAT reflowWidth) { m_fCurrMaxWidth = reflowWidth; int ObjCount = pElement->CountObjects(); for(int i = 0; i < ObjCount; i++) { CPDF_PageObject* pObj = pElement->GetObject(i); ProcessObject(pObj, reflowWidth, m_PDFMatrix); continue; } } void CPDF_LayoutProcessor_Reflow::AddTemp2CurrLine(int begin, int count) { if(begin < 0 || count <= 0 || !m_pReflowedPage || !m_pReflowedPage->m_pReflowed || !m_pTempLine) { return; } else { count += begin; } int size = m_pReflowedPage->m_pReflowed->GetSize(); int temps = m_pTempLine->GetSize(); for(int i = begin; i < count; i++) { CRF_Data* pData = (*m_pTempLine)[i]; AddData2CurrLine(pData); } } void CPDF_LayoutProcessor_Reflow::AddData2CurrLine(CRF_Data* pData) { if(pData == NULL || m_pCurrLine == NULL) { return; } m_pCurrLine->Add(pData); m_fCurrLineWidth = pData->m_PosX + pData->m_Width; if(pData->m_Height > m_fCurrLineHeight) { m_fCurrLineHeight = pData->m_Height; } } void CPDF_LayoutProcessor_Reflow::UpdateCurrLine() { } void CPDF_LayoutProcessor_Reflow::Transform(const CFX_AffineMatrix* pMatrix, CRF_DataPtrArray* pDataArray, int beginPos, int count) { if (!pDataArray) { return; } if(count == 0) { count = pDataArray->GetSize(); } else { count += beginPos; } for(int i = beginPos; i < count; i++) { CRF_Data* pData = (*pDataArray)[i]; Transform(pMatrix, pData); } } void CPDF_LayoutProcessor_Reflow::Transform(const CFX_AffineMatrix* pMatrix, CRF_Data* pData) { if(pData->GetType() == CRF_Data::Path) { CRF_PathData* pPathData = (CRF_PathData*)pData; pPathData->m_pPath2Device.Concat(*pMatrix); } pMatrix->Transform(pData->m_PosX, pData->m_PosY, pData->m_PosX, pData->m_PosY); } FX_BOOL CPDF_LayoutProcessor_Reflow::FinishedCurrLine() { if (NULL == m_pCurrLine) { return FALSE; } int count = m_pCurrLine->GetSize(); if(count == 0) { return FALSE; } if(m_fLineHeight > m_fCurrLineHeight) { m_fCurrLineHeight = m_fLineHeight; } else { m_fCurrLineHeight += 2; } if(m_pReflowedPage->m_pReflowed->GetSize() > 0) { m_fCurrLineHeight += m_fLineSpace; } FX_FLOAT height = m_pReflowedPage->m_PageHeight + m_fCurrLineHeight; FX_FLOAT lineHeight = m_fLineHeight; if(lineHeight == 0) { lineHeight = m_fCurrLineHeight; } FX_FLOAT dx = 0; switch(m_TextAlign) { case LayoutCenter: dx = (m_fCurrMaxWidth - m_fCurrLineWidth) / 2; break; case LayoutEnd: dx = m_fCurrMaxWidth - m_fCurrLineWidth; break; case LayoutJustify: break; default: break; } FX_FLOAT dy = - height; int refedSize = m_pReflowedPage->m_pReflowed->GetSize(); if(count == 13) { int a = 0; } for(int i = 0; i < count; i++) { CRF_Data* pData = (*m_pCurrLine)[i]; m_pReflowedPage->m_pReflowed->Add(pData); FX_FLOAT x = m_StartIndent + dx * (m_TextAlign == LayoutJustify ? i + 1 : 1); CFX_AffineMatrix matrix(1, 0, 0, 1, x, dy); Transform(&matrix, pData); } m_pCurrLine->RemoveAll(); m_fCurrLineWidth = 0; m_pReflowedPage->m_PageHeight += m_fCurrLineHeight; m_fCurrLineHeight = 0; return TRUE; } CRF_CharState* CPDF_LayoutProcessor_Reflow::GetCharState(CPDF_TextObject* pObj, CPDF_Font* pFont, FX_FLOAT fHeight, FX_ARGB color) { if (NULL == m_pReflowedPage->m_pCharState) { return NULL; } int count = m_pReflowedPage->m_pCharState->GetSize(); for(int i = count - 1; i >= 0; i--) { CRF_CharState* pState = (CRF_CharState*)m_pReflowedPage->m_pCharState->GetAt(i); if(pState->m_Color == color && pState->m_fFontSize == fHeight && pState->m_pFont == pFont && pState->m_pTextObj == pObj) { return pState; } } CRF_CharState pState; pState.m_pTextObj = pObj; pState.m_Color = color; pState.m_pFont = pFont; pState.m_fFontSize = fHeight; int ascent = pFont->GetTypeAscent(); int descent = pFont->GetTypeDescent(); pState.m_fAscent = ascent * fHeight / (ascent - descent); if(descent == 0) { pState.m_fDescent = 0; } else { pState.m_fDescent = descent * fHeight / (ascent - descent); } pState.m_bVert = FALSE; CPDF_CIDFont *pCIDFont = pFont->GetCIDFont(); if(pCIDFont) { pState.m_bVert = pCIDFont->IsVertWriting(); } m_pReflowedPage->m_pCharState->Add(pState); return (CRF_CharState*)m_pReflowedPage->m_pCharState->GetAt(count); } int CPDF_LayoutProcessor_Reflow::GetCharWidth(FX_DWORD charCode, CPDF_Font* pFont) const { if(charCode == -1) { return 0; } int w = pFont->GetCharWidthF(charCode); if(w == 0) { CFX_ByteString str; pFont->AppendChar(str, charCode); w = pFont->GetStringWidth(str, 1); if(w == 0) { FX_RECT BBox; pFont->GetCharBBox(charCode, BBox); w = BBox.right - BBox.left; } } return w; } void CPDF_LayoutProcessor_Reflow::CreateRFData(CPDF_PageObject* pObj, CFX_AffineMatrix* pObjMatrix) { if (NULL == m_pReflowedPage->m_pMemoryPool) { return; } if(pObj->m_Type == PDFPAGE_TEXT) { CPDF_TextObject* pTextObj = (CPDF_TextObject* )pObj; int count = pTextObj->CountItems(); if(!count) { return; } if(count == 1) { CPDF_TextObjectItem Item; pTextObj->GetItemInfo(0, &Item); if(Item.m_CharCode == 49) { int a = 0; } } CPDF_Font * pFont = pTextObj->GetFont(); FX_FLOAT fs = pTextObj->GetFontSize(); FX_FLOAT* pmatrix = pTextObj->m_TextState.GetMatrix(); FX_FLOAT matrix1 = pmatrix[1]; if(pmatrix[2] == 0) { matrix1 = 0; } CFX_AffineMatrix textMatrix(pmatrix[0], matrix1, pmatrix[2], pmatrix[3], 0, 0); FX_FLOAT height = FXSYS_fabs(textMatrix.TransformDistance(fs)); if(pObjMatrix) { height = FXSYS_fabs(pObjMatrix->TransformDistance(height)); } int r = 0, g = 0, b = 0; pTextObj->m_ColorState.GetFillColor()->GetRGB(r, g, b); FX_ARGB col = r * 0x10000; col += g * 0x100; col += b; CRF_CharState* pState = GetCharState(pTextObj, pFont, height, col); FX_FLOAT dx = 0, dy = 0; FX_RECT ObjBBox; if(pObjMatrix) { ObjBBox = pTextObj->GetBBox(pObjMatrix); dx = (float)ObjBBox.left; dy = (float)ObjBBox.bottom; } else { CFX_AffineMatrix matrix; ObjBBox = pTextObj->GetBBox(&matrix); } FX_FLOAT objWidth = 0; CFX_ByteString str; FX_BOOL bOrder = TRUE; CFX_PtrArray tempArray; int i = 0; CPDF_TextObjectItem Item; pTextObj->GetItemInfo(i, &Item); dx = Item.m_OriginX; dy = Item.m_OriginY; textMatrix.Transform(Item.m_OriginX, Item.m_OriginY, dx, dy); CRF_CharData* pLastData = NULL; FX_FLOAT horzScale = pTextObj->m_TextState.GetFontSizeV() / pTextObj->m_TextState.GetFontSizeH(); while(i < count) { pTextObj->GetItemInfo(i, &Item); if(Item.m_CharCode == -1) { i++; continue; } FX_FLOAT OriginX, OriginY; textMatrix.Transform(Item.m_OriginX, Item.m_OriginY, OriginX, OriginY); CRF_CharData* pData = (CRF_CharData*)m_pReflowedPage->m_pMemoryPool->Alloc(sizeof(CRF_CharData)); if (NULL == pData) { continue; } pData->m_Type = CRF_Data::Text; if(FXSYS_fabs(OriginY - dy) > FXSYS_fabs(OriginX - dx)) { pData->m_PosY = dy; pData->m_PosX = pLastData->m_PosX + pLastData->m_Width + textMatrix.TransformDistance(pTextObj->m_TextState.GetObject()->m_CharSpace); } else { pData->m_PosY = OriginY; pData->m_PosX = OriginX; } int size = tempArray.GetSize(); if(size && pData->m_PosX < pLastData->m_PosX ) { for (int j = 0; j < size; j++) { CRF_CharData* pData1 = (CRF_CharData*)tempArray.GetAt(j); if(pData1->m_PosX > pData->m_PosX) { tempArray.InsertAt(j, pData); break; } } } else { tempArray.Add(pData); } pLastData = pData; pData->m_CharCode = Item.m_CharCode; pData->m_Height = FXSYS_fabs(height); int w = GetCharWidth(Item.m_CharCode, pFont); pData->m_Width = FXSYS_fabs(fs * textMatrix.TransformDistance((FX_FLOAT)w) / 1000); if(horzScale) { pData->m_Width /= horzScale; } pData->m_pCharState = pState; i++; } count = tempArray.GetSize(); for (int j = 0; j < count; j++) { CRF_CharData* pData = (CRF_CharData*)tempArray.GetAt(j); if (m_pTempLine) { m_pTempLine->Add(pData); } } tempArray.RemoveAll(); } else if(pObj->m_Type == PDFPAGE_IMAGE) { CPDF_ImageObject* pImageObj = (CPDF_ImageObject* )pObj; CRF_ImageData* pRFImage = (CRF_ImageData*)m_pReflowedPage->m_pMemoryPool->Alloc(sizeof(CRF_ImageData)); if (NULL == pRFImage) { return; } pRFImage->m_pBitmap = NULL; pRFImage->m_Type = CRF_Data::Image; if (m_pTempLine) { m_pTempLine->Add(pRFImage); } CPDF_Image *pImage = pImageObj->m_pImage; if (!pImage->m_pDIBSource || !pImage->m_pMask) { if(pImage->StartLoadDIBSource(m_pReflowedPage->GetFormResDict(pImageObj), m_pReflowedPage->m_pPDFPage->m_pResources, 0, 0, TRUE)) { pImage->Continue(NULL); } } CFX_DIBSource* pDibSource = pImage->DetachBitmap(); if (pDibSource) { pRFImage->m_pBitmap = pDibSource->Clone(); delete pDibSource; } CFX_DIBSource* pMask = pImage->DetachMask(); if (pMask) { if (!pMask->IsAlphaMask()) { CFX_DIBitmap* pMaskBmp = pMask->Clone(); pMaskBmp->ConvertFormat(FXDIB_8bppMask); pRFImage->m_pBitmap->MultiplyAlpha(pMaskBmp); delete pMaskBmp; } else { pRFImage->m_pBitmap->MultiplyAlpha(pMask); } delete pMask; } CFX_FloatRect ObjBBox; if(pObjMatrix) { ObjBBox = pImageObj->GetBBox(pObjMatrix); } else { CFX_AffineMatrix matrix; ObjBBox = pImageObj->GetBBox(&matrix); } pRFImage->m_Width = ObjBBox.Width(); pRFImage->m_Height = ObjBBox.Height(); pRFImage->m_PosX = 0; pRFImage->m_PosY = 0; CFX_AffineMatrix matrix(1, 0, 0, -1, 0, 0); matrix.Concat(pImageObj->m_Matrix); matrix.Concat(*pObjMatrix); pRFImage->m_Matrix.Set(matrix.a == 0 ? 0 : matrix.a / FXSYS_fabs(matrix.a), matrix.b == 0 ? 0 : matrix.b / FXSYS_fabs(matrix.b), matrix.c == 0 ? 0 : matrix.c / FXSYS_fabs(matrix.c), matrix.d == 0 ? 0 : matrix.d / FXSYS_fabs(matrix.d), 0, 0); } else if(pObj->m_Type == PDFPAGE_PATH) { } } FX_FLOAT CPDF_LayoutProcessor_Reflow:: GetDatasWidth(int beginPos, int endpos) { if(endpos < beginPos || !m_pTempLine) { return 0; } if(endpos > m_pTempLine->GetSize() - 1) { endpos = m_pTempLine->GetSize() - 1; } CRF_Data* pBeginData = (*m_pTempLine)[beginPos]; CRF_Data* pEndData = (*m_pTempLine)[endpos]; return pEndData->m_PosX - pBeginData->m_PosX + pEndData->m_Width; } FX_WCHAR CPDF_LayoutProcessor_Reflow::GetPreChar() { if (NULL == m_pCurrLine) { return -1; } int index = m_pCurrLine->GetSize() - 1; CRF_CharData* pCharData = NULL; while (index >= 0 && !pCharData) { CRF_Data* pData = (*m_pCurrLine)[index]; if(pData->GetType() == CRF_Data::Text) { pCharData = (CRF_CharData*)pData; } else { return -1; } index --; } if(m_pReflowedPage) { index = m_pReflowedPage->m_pReflowed->GetSize() - 1; } while(!pCharData && index >= 0) { CRF_Data* pData = (*m_pReflowedPage->m_pReflowed)[index]; if(pData->GetType() == CRF_Data::Text) { pCharData = (CRF_CharData*)pData; } else { return -1; } index --; } if(pCharData) { CFX_WideString str = pCharData->m_pCharState->m_pFont->UnicodeFromCharCode(pCharData->m_CharCode); return str.GetAt(0); } return -1; } int CPDF_LayoutProcessor_Reflow::ProcessInsertObject(CPDF_TextObject* pObj, CFX_AffineMatrix formMatrix) { if(!pObj || !m_pPreObj || !m_pCurrLine) { return 0; } if(m_pCurrLine->GetSize() == 0) { return 0; } CPDF_TextObjectItem item; int nItem = m_pPreObj->CountItems(); m_pPreObj->GetItemInfo(nItem - 1, &item); FX_FLOAT last_pos = item.m_OriginX; FX_FLOAT last_width = GetCharWidth(item.m_CharCode, m_pPreObj->GetFont()) * m_pPreObj->GetFontSize() / 1000; last_width = FXSYS_fabs(last_width); pObj->GetItemInfo(0, &item); FX_FLOAT this_width = GetCharWidth(item.m_CharCode, pObj->GetFont()) * pObj->GetFontSize() / 1000; this_width = FXSYS_fabs(this_width); FX_FLOAT threshold = last_width > this_width ? last_width / 4 : this_width / 4; CFX_AffineMatrix prev_matrix, prev_reverse; m_pPreObj->GetTextMatrix(&prev_matrix); prev_matrix.Concat(m_perMatrix); prev_reverse.SetReverse(prev_matrix); FX_FLOAT x = pObj->GetPosX(), y = pObj->GetPosY(); formMatrix.Transform(x, y); prev_reverse.Transform(x, y); FX_WCHAR preChar = GetPreChar(); CFX_WideString wstrItem = pObj->GetFont()->UnicodeFromCharCode(item.m_CharCode); FX_WCHAR curChar = wstrItem.GetAt(0); if (FXSYS_fabs(y) > threshold * 2) { if (preChar == L'-') { return 3; } if (preChar != L' ') { return 1; } return 2; } if ((x - last_pos - last_width) > threshold && curChar != L' ' && preChar != L' ') { return 1; } return 0; } FX_INT32 CPDF_LayoutProcessor_Reflow::LogicPreObj(CPDF_TextObject* pObj) { CPDF_TextObject* pPreObj = m_pPreObj; m_pPreObj = pObj; if(!pObj || !pPreObj) { return 0; } CPDF_TextObjectItem item; pPreObj->GetItemInfo(pPreObj->CountItems() - 1, &item); FX_FLOAT last_pos = item.m_OriginX; FX_FLOAT last_width = pPreObj->GetFont()->GetCharWidthF(item.m_CharCode) * pPreObj->GetFontSize() / 1000; last_width = FXSYS_fabs(last_width); pObj->GetItemInfo(0, &item); FX_FLOAT this_width = pObj->GetFont()->GetCharWidthF(item.m_CharCode) * pObj->GetFontSize() / 1000; this_width = FXSYS_fabs(this_width); FX_FLOAT threshold = last_width > this_width ? last_width / 4 : this_width / 4; CFX_AffineMatrix prev_matrix, prev_reverse; pPreObj->GetTextMatrix(&prev_matrix); prev_reverse.SetReverse(prev_matrix); FX_FLOAT x = pObj->GetPosX(), y = pObj->GetPosY(); prev_reverse.Transform(x, y); CFX_WideString wstrItem = pObj->GetFont()->UnicodeFromCharCode(item.m_CharCode); FX_WCHAR curChar = wstrItem.GetAt(0); if (FXSYS_fabs(y) > threshold * 2) { return 2; } FX_WCHAR preChar = 0; if (FXSYS_fabs(last_pos + last_width - x) > threshold && curChar != L' ') { return 1; } return 0; m_pPreObj = pObj; if(!pPreObj) { return 0; } if(pPreObj->m_Type != pObj->m_Type) { return 0; } CFX_FloatRect rcCurObj(pObj->m_Left, pObj->m_Bottom, pObj->m_Right, pObj->m_Top); CFX_FloatRect rcPreObj(pPreObj->m_Left, pPreObj->m_Bottom, pPreObj->m_Right, pPreObj->m_Top); if(pObj->m_Type == PDFPAGE_IMAGE) { if(rcPreObj.Contains(rcCurObj)) { return 2; } if(rcCurObj.Contains(rcPreObj)) { return 2; } return 0; } if(pObj->m_Type == PDFPAGE_TEXT) { if(!((rcPreObj.bottom > rcCurObj.top) || (rcPreObj.top < rcCurObj.bottom))) { FX_FLOAT height = FX_MIN(rcPreObj.Height(), rcCurObj.Height()); if((rcCurObj.left - rcPreObj.right) > height / 3) { return 3; } } if(FXSYS_fabs(rcPreObj.Width() - rcCurObj.Width()) >= 2 || FXSYS_fabs(rcPreObj.Height() - rcCurObj.Height()) >= 2 ) { return 0; } CPDF_TextObject* pPreTextObj = (CPDF_TextObject*)pPreObj; CPDF_TextObject* pCurTextObj = (CPDF_TextObject*)pObj; int nPreCount = pPreTextObj->CountItems(); int nCurCount = pCurTextObj->CountItems(); if (nPreCount != nCurCount) { return 0; } FX_BOOL bSame = TRUE; for (int i = 0; i < nPreCount; i++) { CPDF_TextObjectItem itemPer, itemCur; pPreTextObj->GetItemInfo(i, &itemPer); pCurTextObj->GetItemInfo(i, &itemCur); if (itemCur.m_CharCode != itemPer.m_CharCode) { return 0; } if (itemCur.m_OriginX != itemPer.m_OriginX) { bSame = FALSE; } if (itemCur.m_OriginY != itemPer.m_OriginY) { bSame = FALSE; } } if(rcPreObj.left == rcCurObj.left && rcPreObj.top == rcCurObj.top) { return 1; } if(FXSYS_fabs(rcPreObj.left - rcCurObj.left) < rcPreObj.Width() / 3 && FXSYS_fabs(rcPreObj.top - rcCurObj.top) < rcPreObj.Height() / 3) { return 2; } } return 0; } FX_BOOL CPDF_LayoutProcessor_Reflow::IsSameTextObject(CPDF_TextObject* pTextObj1, CPDF_TextObject* pTextObj2) { if (!pTextObj1 || !pTextObj2) { return FALSE; } CFX_FloatRect rcPreObj(pTextObj2->m_Left, pTextObj2->m_Bottom, pTextObj2->m_Right, pTextObj2->m_Top); CFX_FloatRect rcCurObj(pTextObj1->m_Left, pTextObj1->m_Bottom, pTextObj1->m_Right, pTextObj1->m_Top); if (rcPreObj.IsEmpty() && rcCurObj.IsEmpty()) { return FALSE; } if (!rcPreObj.IsEmpty() || !rcCurObj.IsEmpty()) { rcPreObj.Intersect(rcCurObj); if (rcPreObj.IsEmpty()) { return FALSE; } if (FXSYS_fabs(rcPreObj.Width() - rcCurObj.Width()) > rcCurObj.Width() / 2) { return FALSE; } if (pTextObj2->GetFontSize() != pTextObj1->GetFontSize()) { return FALSE; } } int nPreCount = pTextObj2->CountItems(); int nCurCount = pTextObj1->CountItems(); if (nPreCount != nCurCount) { return FALSE; } for (int i = 0; i < nPreCount; i++) { CPDF_TextObjectItem itemPer, itemCur; pTextObj2->GetItemInfo(i, &itemPer); pTextObj1->GetItemInfo(i, &itemCur); if (itemCur.m_CharCode != itemPer.m_CharCode) { return FALSE; } } return TRUE; } void CPDF_LayoutProcessor_Reflow::ProcessTextObject(CPDF_TextObject *pTextObj, FX_FLOAT reflowWidth, CFX_AffineMatrix objMatrix) { if(reflowWidth < 0 || !m_pCurrLine || !m_pTempLine) { return; } if(IsSameTextObject(pTextObj, m_pPreObj)) { return; } CPDF_PageObject* pPreObj = m_pPreObj; FX_INT32 logic = ProcessInsertObject(pTextObj, objMatrix); m_pPreObj = pTextObj; m_perMatrix.Copy(objMatrix); int size = m_pTempLine->GetSize(); int curs = m_pCurrLine->GetSize(); CreateRFData(pTextObj); size = m_pTempLine->GetSize(); int reds = m_pReflowedPage->m_pReflowed->GetSize(); if(size == 0) { return; } if(logic == 1) { m_fCurrLineWidth += pTextObj->GetBBox(&objMatrix).Height() / 3; } else if(logic == 3 && curs) { m_fCurrLineWidth -= (*m_pCurrLine)[curs - 1]->m_Width; m_pCurrLine->Delete(curs - 1); } int beginPos = 0, endPos = m_pTempLine->GetSize() - 1; while(beginPos <= endPos) { int tempBeginPos = beginPos; int tempEndPos = endPos; FX_FLOAT all_width = GetDatasWidth( beginPos, endPos); if(all_width < reflowWidth - m_fCurrLineWidth) { CRF_CharData* pBeginData = (CRF_CharData*)(*m_pTempLine)[beginPos]; CFX_AffineMatrix matrix(1, 0, 0, 1, -pBeginData->m_PosX + m_fCurrLineWidth, -pBeginData->m_PosY); Transform(&matrix, m_pTempLine, beginPos, endPos - beginPos + 1); AddTemp2CurrLine(beginPos, endPos - beginPos + 1); m_pTempLine->RemoveAll(); return; } int midPos ; if(tempBeginPos >= tempEndPos && tempEndPos != 0) { midPos = tempEndPos; } else { while (tempBeginPos < tempEndPos ) { midPos = (tempEndPos - tempBeginPos) / 2 + tempBeginPos; if(midPos == tempBeginPos || midPos == tempEndPos) { break; } FX_FLOAT w = GetDatasWidth( beginPos, midPos); if(w < reflowWidth - m_fCurrLineWidth) { tempBeginPos = midPos; } else { tempEndPos = midPos; } } midPos = tempBeginPos; if(midPos == 0) { FX_FLOAT w = GetDatasWidth( beginPos, 1); if(w > reflowWidth - m_fCurrLineWidth) { midPos = -1; } } } if(midPos == -1) { int count = m_pCurrLine->GetSize(); if(count == 0) { midPos = 0; } } int f = -1; int i = 0; for(i = midPos; i >= beginPos; i--) { CRF_CharData* pData = (CRF_CharData*)(*m_pTempLine)[i]; CFX_WideString Wstr = pData->m_pCharState->m_pFont->UnicodeFromCharCode(pData->m_CharCode); FX_WCHAR cha = Wstr.GetAt(0); if(i < m_pTempLine->GetSize() - 1) { CRF_CharData* pNextData = (CRF_CharData*)(*m_pTempLine)[i + 1]; if(pNextData->m_PosX - (pData->m_PosX + pData->m_Width) >= pData->m_Height / 4) { f = i; i++; } } if(f == -1) { if(IsCanBreakAfter((FX_DWORD)cha)) { f = i; i++; } else if(IsCanBreakBefore((FX_DWORD)cha)) { f = i - 1; if(f < beginPos) { f = -1; } } } if(f != -1) { CRF_CharData* pBeginData = (CRF_CharData*)(*m_pTempLine)[beginPos]; CFX_AffineMatrix matrix(1, 0, 0, 1, -pBeginData->m_PosX + m_fCurrLineWidth, -pBeginData->m_PosY); Transform(&matrix, m_pTempLine, beginPos, f - beginPos + 1); CRF_Data* pData = (*m_pTempLine)[0]; AddTemp2CurrLine(beginPos, f - beginPos + 1); beginPos = i; FinishedCurrLine(); f = 1; break; } } if(f == -1 && i < beginPos) { if( m_pCurrLine->GetSize()) { int count = m_pCurrLine->GetSize(); f = -1; for(int i = count - 1; i >= 0; i--) { CRF_Data* pData = (*m_pCurrLine)[i]; if(pData->GetType() != CRF_Data::Text) { f = i + 1; } else { CRF_CharData* pCharData = (CRF_CharData*)pData; CFX_WideString Wstr = pCharData->m_pCharState->m_pFont->UnicodeFromCharCode(pCharData->m_CharCode); FX_WCHAR cha = Wstr.GetAt(0); if(IsCanBreakAfter(cha)) { f = i + 1; i++; } else if(IsCanBreakBefore(cha)) { f = i; } if(f == 0) { f = -1; } } if(f != -1) { FinishedCurrLine(); if(f < count) { int reflowdCount = m_pReflowedPage->m_pReflowed->GetSize(); int pos = reflowdCount + f - count; CRF_CharData* pData = (CRF_CharData*)(*m_pReflowedPage->m_pReflowed)[pos]; CFX_AffineMatrix matrix(1, 0, 0, 1, -pData->m_PosX + m_fCurrLineWidth, -pData->m_PosY); Transform(&matrix, m_pReflowedPage->m_pReflowed, pos, reflowdCount - pos); for(int j = pos; j < reflowdCount; j++) { AddData2CurrLine((*m_pReflowedPage->m_pReflowed)[j]); } m_pReflowedPage->m_pReflowed->Delete(pos, count - f); if(logic == 3) { m_fCurrLineWidth += pTextObj->GetBBox(&objMatrix).Height() / 3; } } break; } } } if(f == -1) { CRF_CharData* pData = (CRF_CharData*)(*m_pTempLine)[beginPos]; CFX_AffineMatrix matrix(1, 0, 0, 1, -pData->m_PosX + m_fCurrLineWidth, -pData->m_PosY); if(beginPos == midPos) { Transform(&matrix, pData); FX_RECT rect; pData->m_pCharState->m_pFont->GetFontBBox(rect); FX_FLOAT* pmatrix = pTextObj->m_TextState.GetMatrix(); CFX_AffineMatrix textMatrix(pmatrix[0], pmatrix[1], pmatrix[2], pmatrix[3], 0, 0); FX_FLOAT width = pData->m_Height * (rect.right - rect.left) / 1000; FX_FLOAT f = (reflowWidth - m_fCurrLineWidth) / width; pData->m_PosY *= f; pData->m_Width *= f; pData->m_Height *= f; pData->m_pCharState = GetCharState(pData->m_pCharState->m_pTextObj, pData->m_pCharState->m_pFont, pData->m_Height, pData->m_pCharState->m_Color); AddData2CurrLine(pData); } else { for(int m = beginPos; m <= midPos; m++) { CRF_CharData* pData = (CRF_CharData*)(*m_pTempLine)[m]; Transform(&matrix, pData); AddData2CurrLine(pData); } } FinishedCurrLine(); beginPos = midPos + 1; } } } m_pTempLine->RemoveAll(); return; } void CPDF_LayoutProcessor_Reflow::ProcessUnitaryObjs(CPDF_PageObjects *pObjs, FX_FLOAT reflowWidth, CFX_AffineMatrix objMatrix) { if(!pObjs) { return; } CFX_FloatRect ObjBBox = pObjs->CalcBoundingBox(); objMatrix.TransformRect(ObjBBox); FX_FLOAT ObjWidth = ObjBBox.Width(); FX_FLOAT ObjHeight = ObjBBox.Height(); CFX_AffineMatrix matrix; if(ObjWidth <= reflowWidth - m_fCurrLineWidth) { matrix.Set(1, 0, 0, 1, m_fCurrLineWidth , 0); } else if(ObjWidth <= reflowWidth) { FinishedCurrLine(); matrix.Set(1, 0, 0, 1, 0, 0); } else { FinishedCurrLine(); FX_FLOAT f = reflowWidth / ObjWidth ; matrix.Set(f, 0, 0, f, 0, 0); } CFX_AffineMatrix tempMatrix = matrix; matrix.Concat(objMatrix); FX_POSITION pos = pObjs->GetFirstObjectPosition(); while(pos) { CPDF_PageObject* pObj = pObjs->GetNextObject(pos); if(pObj->m_Type == PDFPAGE_TEXT) { FX_INT32 ret = LogicPreObj((CPDF_TextObject*)pObj); if(ret == 1 || ret == 2) { continue; } } CreateRFData(pObj, &matrix); } if (m_pTempLine) { Transform(&tempMatrix, m_pTempLine, 0, m_pTempLine->GetSize()); AddTemp2CurrLine(0, m_pTempLine->GetSize()); m_pTempLine->RemoveAll(); } } void CPDF_LayoutProcessor_Reflow::ProcessPathObject(CPDF_PathObject *pObj, FX_FLOAT reflowWidth) { }
37.658552
181
0.546092
[ "transform" ]
961d6b29349c06ee8f08a809cfb1bc241b83e988
4,343
cpp
C++
Source/nn/RLLSTMAgent.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
66
2015-01-05T02:31:21.000Z
2021-04-11T18:45:42.000Z
Source/nn/RLLSTMAgent.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
null
null
null
Source/nn/RLLSTMAgent.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
16
2015-01-23T19:55:24.000Z
2021-11-07T20:41:22.000Z
/* AI Lib Copyright (C) 2014 Eric Laukien This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <nn/RLLSTMAgent.h> using namespace nn; RLLSTMAgent::RLLSTMAgent() : _selectedAction(0), _prevError(0.0f), _alpha(2.0f), _gamma(0.8f), _k(1.2f), _numExpBackpropPasses(8), _explorationMultiplier(10.0f), _expAlpha(0.01f), _expMomentum(0.05f), _expGamma(0.8f) {} void RLLSTMAgent::createRandom(size_t numInputs, size_t numActions, size_t recNumHiddenLayers, size_t recNumNeuronsPerHiddenLayer, size_t expNumHiddenLayers, size_t expNumNeuronsPerHiddenLayer, size_t numMemoryCells, float minWeight, float maxWeight, unsigned long seed) { _numInputs = numInputs; _numActions = numActions; std::mt19937 generator; generator.seed(seed); _rnn.createRandom(_numInputs + numMemoryCells, _numActions + numMemoryCells * 4, recNumHiddenLayers, recNumNeuronsPerHiddenLayer, minWeight, maxWeight, generator); _expnn.createRandom(_numInputs, 1, expNumHiddenLayers, expNumNeuronsPerHiddenLayer, minWeight, maxWeight, generator); _memoryCells.resize(numMemoryCells); _prevInputs.resize(_numInputs, 0.0f); _generator.seed(seed); } void RLLSTMAgent::step(float fitness) { size_t prevSeletedAction = _selectedAction; float prevAdvantage = _rnn.getOutput(prevSeletedAction); float prevValue = _rnn.getOutput(0); for (size_t i = 1; i < _numActions; i++) if (_rnn.getOutput(i) > prevValue) prevValue = _rnn.getOutput(i); // Update to find new action for (size_t i = 0; i < _memoryCells.size(); i++) _rnn.setInput(_numInputs + i, _memoryCells[i]._output); _rnn.activateLinearOutputLayer(); // Update memory cells size_t outputIndex = _numActions; for (size_t i = 0; i < _memoryCells.size(); i++) { _memoryCells[i]._input = _rnn.getOutput(outputIndex++); _memoryCells[i]._gateInput = _rnn.getOutput(outputIndex++); _memoryCells[i]._gateOutput = _rnn.getOutput(outputIndex++); _memoryCells[i]._gateForget = _rnn.getOutput(outputIndex++); _memoryCells[i].activate(_rnn._activationMultiplier, _rnn._outputTraceDecay); } // Find exploration factor _expnn.activateLinearOutputLayer(); float predictedError = _expnn.getOutput(0); float explorationStd = predictedError * _explorationMultiplier; // Find new value _selectedAction = 0; float value = _rnn.getOutput(0); std::normal_distribution<float> distribution(0.0f, explorationStd); float perturbedValue = _rnn.getOutput(0) + distribution(_generator); for (size_t i = 1; i < _numActions; i++) { float perturbedOutput = _rnn.getOutput(i) + distribution(_generator); if (perturbedOutput > perturbedValue) { perturbedValue = perturbedOutput; _selectedAction = i; } if (_rnn.getOutput(i) > value) value = _rnn.getOutput(i); } // Find TD error float error = prevValue + (fitness + _gamma * value - prevValue) / _k - prevAdvantage; _rnn.reinforce(error * _alpha); // Update exploration error predictor for (size_t i = 0; i < _numInputs; i++) _expnn.setInput(i, _prevInputs[i]); float expTarget = _prevError + _expGamma * error; for (size_t p = 0; p < _numExpBackpropPasses; p++) { _expnn.activateLinearOutputLayer(); FeedForwardNeuralNetwork::Gradient gradient; _expnn.getGradientLinearOutputLayer(std::vector<float>(1, expTarget), gradient); _expnn.moveAlongGradientMomentum(gradient, _expAlpha, _expMomentum); } for (size_t i = 0; i < _numInputs; i++) _prevInputs[i] = _rnn.getInput(i); _prevError = error; }
32.17037
165
0.734285
[ "vector" ]
961dcef3c935313c1083db6823b2cd57a7d431d2
485
cpp
C++
leetcode/algorithms/0771_jewels-and-stones/cpp/Solution2.cpp
shoukailiang/idea
bd0e6c59581d9763aa691914d1f4ac8733a02274
[ "MIT" ]
1
2019-08-08T12:12:30.000Z
2019-08-08T12:12:30.000Z
leetcode/algorithms/0771_jewels-and-stones/cpp/Solution2.cpp
shoukailiang/algorithm
91892634ac03bc26c442771769189ccff73159cd
[ "MIT" ]
null
null
null
leetcode/algorithms/0771_jewels-and-stones/cpp/Solution2.cpp
shoukailiang/algorithm
91892634ac03bc26c442771769189ccff73159cd
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <unordered_set> using namespace std; class Solution { public: int numJewelsInStones(string J, string S) { int size = 0; unordered_set<char> jew; for (auto j:J) { jew.insert(j); } for (auto s:S) { cout << jew.count(s) << endl; if (jew.count(s)) { size++; } } return size; } }; // 测试 int main() { cout << Solution().numJewelsInStones("az", "aaZZ"); }
16.724138
53
0.569072
[ "vector" ]
96200bcc19f0e6fd1a3b9dd15b38eb1b86a94fcf
4,172
hpp
C++
private/inc/avb_streamhandler/IasTestToneStream.hpp
tnishiok/AVBStreamHandler
7621daf8c9238361e030fe35188b921ee8ea2466
[ "BSL-1.0", "BSD-3-Clause" ]
13
2018-09-26T13:32:35.000Z
2021-05-20T10:01:12.000Z
private/inc/avb_streamhandler/IasTestToneStream.hpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
23
2018-10-03T22:45:21.000Z
2020-03-05T23:40:12.000Z
private/inc/avb_streamhandler/IasTestToneStream.hpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
22
2018-09-14T03:55:34.000Z
2021-12-07T01:13:27.000Z
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasTestToneStream.hpp * @brief Test tone generator pseudo-stream class * @details This class generates audio streams with test tones. * This class is derived from IasLocalAudioStream * @date 2013 */ #ifndef IAS_MEDIATRANSPORT_AVBSTREAMHANDLER_TESTTONESTREAM_HPP #define IAS_MEDIATRANSPORT_AVBSTREAMHANDLER_TESTTONESTREAM_HPP #include "avb_streamhandler/IasAvbTypes.hpp" #include "avb_streamhandler/IasLocalAudioStream.hpp" #include "media_transport/avb_streamhandler_api/IasAvbStreamHandlerInterface.hpp" namespace IasMediaTransportAvb { class IasTestToneStream : public IasLocalAudioStream { public: /** * @brief Constructor. */ IasTestToneStream(DltContext &dltContext, uint16_t streamId); /** * @brief Destructor, virtual by default. */ virtual ~IasTestToneStream(); /** * @brief Initialize method. * * Pass component specific initialization parameters. */ IasAvbProcessingResult init(uint16_t numChannels, uint32_t sampleFrequency, uint8_t channelLayout); /** * @brief Clean up all allocated resources. */ void cleanup(); /** * @brief set tone generation params per channel */ IasAvbProcessingResult setChannelParams(uint16_t channel, uint32_t signalFrequency, int32_t level, IasAvbTestToneMode mode, int32_t userParam ); private: typedef float AudioData; struct GeneratorParams { GeneratorParams(); IasAvbTestToneMode mode; int32_t userParam; uint32_t signalFreq; int32_t level; AudioData peak; AudioData coeff; AudioData buf1; AudioData buf2; }; typedef uint32_t (IasTestToneStream::*ProcessMethod)(IasLocalAudioBuffer::AudioData *buf, uint32_t numSamples, GeneratorParams & params); struct ChannelData { GeneratorParams params; ProcessMethod method; }; typedef std::vector<ChannelData> ChannelVec; /** * @brief Copy constructor, private unimplemented to prevent misuse. */ IasTestToneStream(IasTestToneStream const &other); /** * @brief Assignment operator, private unimplemented to prevent misuse. */ IasTestToneStream& operator=(IasTestToneStream const &other); /** * @brief overwritten version of base class implementation, only as debug safeguard */ virtual IasAvbProcessingResult writeLocalAudioBuffer(uint16_t channelIdx, IasLocalAudioBuffer::AudioData *buffer, uint32_t bufferSize, uint16_t &samplesWritten, uint32_t timeStamp); /** * @brief overwritten version of base class implementation */ virtual IasAvbProcessingResult readLocalAudioBuffer(uint16_t channelIdx, IasLocalAudioBuffer::AudioData *buffer, uint32_t bufferSize, uint16_t &samplesRead, uint64_t &timeStamp); /** * @brief must be implemented by each class derived from IasLocalStream * our implementation does nothing */ IasAvbProcessingResult resetBuffers() { return eIasAvbProcOK; } ///@brief helper for coeff calculation void calcCoeff(uint32_t sampleFreq, GeneratorParams & params); ///@brief helper for setting the right process method void setProcessMethod(ChannelData & ch); inline int16_t convertFloatToPcm16(AudioData val); uint32_t generateSineWave(IasLocalAudioBuffer::AudioData *buf, uint32_t numSamples, GeneratorParams & params); uint32_t generatePulseWave(IasLocalAudioBuffer::AudioData *buf, uint32_t numSamples, GeneratorParams & params); uint32_t generateSawtoothWaveRising(IasLocalAudioBuffer::AudioData *buf, uint32_t numSamples, GeneratorParams & params); uint32_t generateSawtoothWaveFalling(IasLocalAudioBuffer::AudioData *buf, uint32_t numSamples, GeneratorParams & params); /// /// Members /// ChannelVec mChannels; AudioData mConversionGain; bool mUseSaturation; }; } // namespace IasMediaTransportAvb #endif /* IAS_MEDIATRANSPORT_AVBSTREAMHANDLER_TESTTONESTREAM_HPP */
29.174825
185
0.722196
[ "vector" ]
96210c7975f9c435d26afbc4a8d564672a4d38e4
6,073
cpp
C++
engine/source/Math/Ray.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
11
2020-10-21T15:03:41.000Z
2020-11-03T09:15:28.000Z
engine/source/Math/Ray.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
null
null
null
engine/source/Math/Ray.cpp
MaxSigma/SGEngine
68a01012911b8d91c9ff6d960a0f7d1163940e09
[ "MIT" ]
1
2020-10-27T00:13:41.000Z
2020-10-27T00:13:41.000Z
///////////////////////////////////////////////////// // Sirnic's Game Engine © Max Gittel // ///////////////////////////////////////////////////// #include "Ray.h" #include "Plane.h" #include "Frustum.h" #include "BoundingSphere.h" #include "BoundingBox.h" namespace sge { Ray::Ray() : _direction(0, 0, 1) { } Ray::Ray(const Vec3& origin, const Vec3& direction) { set(origin, direction); } Ray::Ray(float originX, float originY, float originZ, float dirX, float dirY, float dirZ) { set(Vec3(originX, originY, originZ), Vec3(dirX, dirY, dirZ)); } Ray::Ray(const Ray& copy) { set(copy); } Ray::~Ray() { } const Vec3& Ray::getOrigin() const { return _origin; } void Ray::setOrigin(const Vec3& origin) { _origin = origin; } void Ray::setOrigin(float x, float y, float z) { _origin.set(x, y, z); } const Vec3& Ray::getDirection() const { return _direction; } void Ray::setDirection(const Vec3& direction) { _direction = direction; normalize(); } void Ray::setDirection(float x, float y, float z) { _direction.set(x, y, z); normalize(); } float Ray::intersects(const BoundingSphere& sphere) const { return sphere.intersects(*this); } float Ray::intersects(const BoundingBox& box) const { return box.intersects(*this); } float Ray::intersects(const Frustum& frustum) const { Plane n = frustum.getNear(); float nD = intersects(n); float nOD = n.distance(_origin); Plane f = frustum.getFar(); float fD = intersects(f); float fOD = f.distance(_origin); Plane l = frustum.getLeft(); float lD = intersects(l); float lOD = l.distance(_origin); Plane r = frustum.getRight(); float rD = intersects(r); float rOD = r.distance(_origin); Plane b = frustum.getBottom(); float bD = intersects(b); float bOD = b.distance(_origin); Plane t = frustum.getTop(); float tD = intersects(t); float tOD = t.distance(_origin); // If the ray's origin is in the negative half-space of one of the frustum's planes // and it does not intersect that same plane, then it does not intersect the frustum. if ((nOD < 0.0f && nD < 0.0f) || (fOD < 0.0f && fD < 0.0f) || (lOD < 0.0f && lD < 0.0f) || (rOD < 0.0f && rD < 0.0f) || (bOD < 0.0f && bD < 0.0f) || (tOD < 0.0f && tD < 0.0f)) { return Ray::INTERSECTS_NONE; } // Otherwise, the intersection distance is the minimum positive intersection distance. float d = (nD > 0.0f) ? nD : 0.0f; d = (fD > 0.0f) ? ((d == 0.0f) ? fD : min(fD, d)) : d; d = (lD > 0.0f) ? ((d == 0.0f) ? lD : min(lD, d)) : d; d = (rD > 0.0f) ? ((d == 0.0f) ? rD : min(rD, d)) : d; d = (tD > 0.0f) ? ((d == 0.0f) ? bD : min(bD, d)) : d; d = (bD > 0.0f) ? ((d == 0.0f) ? tD : min(tD, d)) : d; return d; } // From Cinder lib // algorithm from "Fast, Minimum Storage Ray-Triangle Intersection" bool Ray::calcTriangleIntersection( const Vec3 &vert0, const Vec3 &vert1, const Vec3 &vert2, float *result ) const { Vec3 edge1, edge2, tvec, pvec, qvec; float det; float u, v; const float EPSILON = 0.000001f; edge1 = vert1 - vert0; edge2 = vert2 - vert0; pvec = _direction.cross( edge2 ); det = edge1.dot( pvec ); #if 0 // we don't want to backface cull if ( det < EPSILON ) return false; tvec = _origin - vert0; u = tvec.dot( pvec ); if ( ( u < 0.0f ) || ( u > det ) ) return false; qvec = tvec.cross( edge1 ); v = _direction.dot( qvec ); if ( v < 0.0f || u + v > det ) return false; *result = edge2.dot( qvec ) / det; return true; #else if( det > -EPSILON && det < EPSILON ) return false; float inv_det = 1.0f / det; tvec = _origin - vert0; u = tvec.dot( pvec ) * inv_det; if( u < 0.0f || u > 1.0f ) return false; qvec = tvec.cross( edge1 ); v = _direction.dot( qvec ) * inv_det; if( v < 0.0f || u + v > 1.0f ) return 0; *result = edge2.dot( qvec ) * inv_det; return true; #endif } Vec3 Ray::getPointForLength(float length){ return _origin+_direction*length; } float Ray::intersects(const Plane& plane) const { const Vec3& normal = plane.getNormal(); // If the origin of the ray is on the plane then the distance is zero. float alpha = (normal.dot(_origin) + plane.getDistance()); if (fabs(alpha) < MATH_EPSILON) { return 0.0f; } float dot = normal.dot(_direction); // If the dot product of the plane's normal and this ray's direction is zero, // then the ray is parallel to the plane and does not intersect it. if (dot == 0.0f) { return INTERSECTS_NONE; } // Calculate the distance along the ray's direction vector to the point where // the ray intersects the plane (if it is negative the plane is behind the ray). float d = -alpha / dot; if (d < 0.0f) { return INTERSECTS_NONE; } return d; } void Ray::set(const Vec3& origin, const Vec3& direction) { _origin = origin; _direction = direction; normalize(); } void Ray::set(const Ray& ray) { _origin = ray._origin; _direction = ray._direction; normalize(); } void Ray::transform(const Mat4& matrix) { // matrix.transformPoint(&_origin); // matrix.transformVector(&_direction); _direction.normalize(); } void Ray::normalize() { if (_direction.length()==0){ return; } // Normalize the ray's direction vector. float normalizeFactor = 1.0f / sqrtf(_direction.x * _direction.x + _direction.y * _direction.y + _direction.z * _direction.z); if (normalizeFactor != 1.0f) { _direction.x *= normalizeFactor; _direction.y *= normalizeFactor; _direction.z *= normalizeFactor; } } }
23.909449
130
0.56216
[ "vector", "transform" ]
9622068a040ce24173b43d2086f312ec4f754d8f
332
cpp
C++
CppMunk/src/CircleShape.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
63
2017-05-18T16:10:19.000Z
2022-03-26T18:05:59.000Z
CppMunk/src/CircleShape.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
1
2018-02-10T12:40:33.000Z
2019-01-11T07:33:13.000Z
CppMunk/src/CircleShape.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
4
2017-12-31T21:38:14.000Z
2019-11-20T15:13:00.000Z
#include "CircleShape.h" #include "Body.h" namespace cp { CircleShape::CircleShape(std::shared_ptr<Body> body, cpFloat radius, cpVect offset) : Shape(cpCircleShapeNew(body ? (*body) : (cpBody*)0, radius, offset), body) { } }
25.538462
70
0.487952
[ "shape" ]
9623a19774043f381cb59eb72ce39016d788c885
3,030
hpp
C++
libs/perpix/src/FeatureComputer.hpp
malreddysid/ofxPerPixelSegment
196d3a48726ce17ea42e14fcbd891880510ec9f8
[ "MIT" ]
8
2018-08-20T09:44:59.000Z
2021-11-24T02:02:34.000Z
libs/perpix/src/FeatureComputer.hpp
malreddysid/ofxPerPixelSegment
196d3a48726ce17ea42e14fcbd891880510ec9f8
[ "MIT" ]
2
2017-01-12T10:21:34.000Z
2017-02-15T07:22:31.000Z
libs/perpix/src/FeatureComputer.hpp
malreddysid/ofxPerPixelSegment
196d3a48726ce17ea42e14fcbd891880510ec9f8
[ "MIT" ]
5
2018-07-06T19:35:18.000Z
2020-12-28T09:02:02.000Z
#ifndef Define_LcFeatureComputer #define Define_LcFeatureComputer #include <cstring> #include <opencv2/opencv.hpp> #include <opencv2/flann/config.h> #include <opencv2/legacy/legacy.hpp> // EM #include <opencv2/contrib/contrib.hpp> // colormap #include <opencv2/nonfree/nonfree.hpp> // SIFT #include "LcBasic.h" using namespace std; using namespace cv; //a father class class LcFeatureComputer { public: int dim; int bound; int veb; bool use_motion; virtual void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc){;} }; class LcFeatureExtractor { public: LcFeatureExtractor(); int veb; int bound_setting; void img2keypts( Mat & img, vector<KeyPoint> & keypts,Mat & img_ext, vector<KeyPoint> & keypts_ext, int step_size); void work(Mat & img , Mat & desc, int step_size, vector<KeyPoint> * p_keypoint = NULL); void work(Mat & img , Mat & desc, vector<KeyPoint> * p_keypoint = NULL); // That's the main interface member which return a descriptor matrix // with an image input void work(Mat & img, Mat & desc, Mat & img_gt, Mat & lab, vector<KeyPoint> * p_keypoint = NULL); //with ground truth image output at same time void work(Mat & img, Mat & desc, Mat & img_gt, Mat & lab, int step_size, vector<KeyPoint> * p_keypoint = NULL); void set_extractor( string setting_string ); private: vector < LcFeatureComputer * > computers; int get_dim(); int get_maximal_bound(); void allocate_memory(Mat & desc,int dims,int data_n); void extract_feature( Mat & img,vector<KeyPoint> & keypts, Mat & img_ext, vector<KeyPoint> & keypts_ext, Mat & desc); void Groundtruth2Label( Mat & img_gt, cv::Size _size , vector< KeyPoint> , Mat & lab); }; //================ #ifndef Define_LcColorSpaceType #define Define_LcColorSpaceType enum ColorSpaceType{ LC_RGB,LC_LAB,LC_HSV }; #endif template< ColorSpaceType color_type, int win_size> class LcColorComputer: public LcFeatureComputer { public: LcColorComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; //================ class LcHoGComputer: public LcFeatureComputer { public: LcHoGComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; //================ class LcBRIEFComputer: public LcFeatureComputer { public: LcBRIEFComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; //=================== class LcSIFTComputer: public LcFeatureComputer { public: LcSIFTComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; //=================== class LcSURFComputer: public LcFeatureComputer { public: LcSURFComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; //==================== class LcOrbComputer: public LcFeatureComputer { public: LcOrbComputer(); void compute( Mat & img, vector<KeyPoint> & keypts, Mat & desc); }; #endif
21.338028
117
0.657096
[ "vector" ]
9623fafaeb96acc5576d076ade7d6e75cd0d9b33
4,766
cc
C++
test/08InstantiationEventArgumentsTest.cc
iwasz/libstatemachine
6e6accc3085bd2d5ea130665a9618b16fea38980
[ "MIT" ]
null
null
null
test/08InstantiationEventArgumentsTest.cc
iwasz/libstatemachine
6e6accc3085bd2d5ea130665a9618b16fea38980
[ "MIT" ]
null
null
null
test/08InstantiationEventArgumentsTest.cc
iwasz/libstatemachine
6e6accc3085bd2d5ea130665a9618b16fea38980
[ "MIT" ]
null
null
null
#include "AndCondition.h" #include "BoolCondition.h" #include "DelayAction.h" #include "GsmCommandAction.h" #include "OrCondition.h" #include "StateMachine.h" #include "StringCondition.h" #include "TimePassedCondition.h" #include "catch.hpp" #include <cstdint> #include <cstring> #include <etl/cstring.h> #include <etl/vector.h> #include <unistd.h> #include <variant> // using namespace sm; enum MyStates { INITIAL, ALIVE, POWER_DOWN, X, Y, Z }; struct Event { using PayloadType = etl::vector<uint8_t, 64>; size_t size () const { return payload.size (); } PayloadType::value_type &at (size_t i) { return payload.at (i); } PayloadType::value_type const &at (size_t i) const { return payload.at (i); } PayloadType payload; std::variant<int, float> arg1; }; using EventType = Event; /** * @brief TEST_CASE */ TEST_CASE ("Arguments basic", "[InstantiationArguments]") { gsmModemCommandsIssued.clear (); StateMachine<EventType> machine; auto &inputQueue = machine.getEventQueue (); /* clang-format off */ machine.state (INITIAL, StateFlags::INITIAL)->entry (gsm <EventType>("AT")) ->transition (ALIVE)->when (eq <EventType>("OK"))->then (gsm<EventType> ("XYZ")); machine.state (ALIVE)->entry (gsm <EventType>("POWEROFF"))->exit (gsm <EventType>("BLAH")) ->transition (POWER_DOWN)->when (eq<EventType> ("OK"))->then (gsm <EventType>("XYZ")); machine.state (POWER_DOWN); /* clang-format on */ /*---------------------------------------------------------------------------*/ /* Uruchamiamy urządzenie */ /*---------------------------------------------------------------------------*/ // Maszyna stanów nie wysłała żadnej komendy do modemu REQUIRE (gsmModemCommandsIssued.empty ()); // To będzie się cały czas odpalało w pętli. Tu symulujemy, że odpaliło się pierwszy raz. // Czyli maszyna przejdzie ze stanu nieustalonego do stanu początkowego "initialState". machine.run (); // Drugie wywołanie żeby odpalić akcje. machine.run (); // Maszyna wysłała pierwszą komendę, bo wykonała się entry action z initialState. REQUIRE (gsmModemCommandsIssued.size () == 1); REQUIRE (gsmModemCommandsIssued.back () == "AT"); /*---------------------------------------------------------------------------*/ /* Drugie uruchomienie maszyny. */ /*---------------------------------------------------------------------------*/ // Następne uruchomienie maszyny bez danych wejściowych nie powinno zmienić stanu i wywołać żadnej akcji machine.run (); REQUIRE (gsmModemCommandsIssued.size () == 1); REQUIRE (machine.currentState->getLabel () == INITIAL); // Symulujemy, że modem odpowiedział "OK", co pojawiło się na kolejce danych we. Maszyna // monitoruje tę kolejkę. inputQueue.push_back (); inputQueue.back ().payload = { 'O', 'K' }; inputQueue.back ().arg1 = 1; inputQueue.push_back (); inputQueue.back ().payload = { '7', '8', '6', '7', '8', '6' }; // Trzecie uruchomienie maszyny, transition złapała odpowiedź "OK" i zadecydowała o zmianie stanu. machine.run (); // Akcje. machine.run (); REQUIRE (machine.currentState); REQUIRE (machine.currentState->getLabel () == ALIVE); // Jeżeli maszyna stanów dokonała zmiany stanu, to automatycznie powinna zdjąć element z kolejki. // REQUIRE (inputQueue.size () == 0); REQUIRE (gsmModemCommandsIssued.size () == 3); REQUIRE (gsmModemCommandsIssued[0] == "AT"); // To jest pierwsza komenda, ktorą maszyna wysłała z entry action ze stanu initialState. REQUIRE (gsmModemCommandsIssued[1] == "XYZ"); // To jest transition action. REQUIRE (gsmModemCommandsIssued[2] == "POWEROFF"); // A to dodała entry action ze stanu aliveState /*---------------------------------------------------------------------------*/ // Symulujemy znów odpowieddź od modemu, że OK inputQueue.push_back (); inputQueue.back ().payload = { 'O', 'K' }; machine.run (); machine.run (); REQUIRE (machine.currentState->getLabel () == POWER_DOWN); REQUIRE (gsmModemCommandsIssued.size () == 5); REQUIRE (gsmModemCommandsIssued[3] == "BLAH"); // Z exit action stanu aliveState REQUIRE (gsmModemCommandsIssued[4] == "XYZ"); // Z transition action między alive a powerdown REQUIRE (inputQueue.size () == 0); }
38.747967
142
0.561687
[ "vector" ]
9631e3eb30d56596012c317514970147f8ad5882
527
cpp
C++
aws-cpp-sdk-groundstation/source/model/DescribeContactRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-groundstation/source/model/DescribeContactRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-groundstation/source/model/DescribeContactRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/groundstation/model/DescribeContactRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::GroundStation::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DescribeContactRequest::DescribeContactRequest() : m_contactIdHasBeenSet(false) { } Aws::String DescribeContactRequest::SerializePayload() const { return {}; }
18.821429
69
0.751423
[ "model" ]
963473ece03a1549d33a513cac41f3fbb297abe7
1,490
cpp
C++
26_cpp_stl/01_stl_foreach.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
26_cpp_stl/01_stl_foreach.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
26_cpp_stl/01_stl_foreach.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Person { public: Person(string name, int age) { this->name = name; this->age = age; } public: string name; int age; }; // 运算符重载 ostream &operator<<(ostream &out, Person &p) { out << "Name: " << p.name << " Age: " << p.age << endl; return out; } void print_person(Person &p) { cout << p.name << " | " << p.age << endl; } void test_foreach() { vector<Person> list; list.push_back(Person("afterloe", 10)); list.push_back(Person("grace", 8)); list.push_back(Person("jor", 11)); list.push_back(Person("blu", 7)); list.push_back(Person("hu", 6)); vector<Person>::iterator begin = list.begin(); vector<Person>::iterator end = list.end(); // 回调函数 // for_each(begin, end, print_person); // lambda for_each(begin, end, [](Person &p) { cout << p.name << " - " << p.age << endl; }); } void test_iterator() { vector<Person> list; list.push_back(Person("afterloe", 10)); list.push_back(Person("grace", 8)); list.push_back(Person("jor", 11)); list.push_back(Person("blu", 7)); list.push_back(Person("hu", 6)); vector<Person>::iterator begin = list.begin(); vector<Person>::iterator end = list.end(); while (begin != end) { cout << *begin << endl; begin++; } } int main() { test_foreach(); return EXIT_SUCCESS; }
19.350649
60
0.571141
[ "vector" ]
96366a3f7dfe79bea5309c1cf606ce41fce5cef5
40,255
cpp
C++
createSAM/ConcreteShearWall/ConcreteShearWall.cpp
charlesxwang/WorkflowRegionalEarthquake
db29681c56104d684890e44e44be32bd278394b2
[ "BSD-3-Clause" ]
14
2018-07-23T15:08:55.000Z
2019-05-27T11:14:54.000Z
createSAM/ConcreteShearWall/ConcreteShearWall.cpp
charlesxwang/WorkflowRegionalEarthquake
db29681c56104d684890e44e44be32bd278394b2
[ "BSD-3-Clause" ]
1
2019-02-07T01:11:26.000Z
2019-02-07T01:11:26.000Z
createSAM/ConcreteShearWall/ConcreteShearWall.cpp
charlesxwang/WorkflowRegionalEarthquake
db29681c56104d684890e44e44be32bd278394b2
[ "BSD-3-Clause" ]
10
2018-07-23T02:51:11.000Z
2019-04-11T11:47:59.000Z
#include "ConcreteShearWall.h" #include <jansson.h> // for Json #include <iostream> #include <cmath> #include <cstring> #include <string> static int nL = 1; static int nH = 1; static ConcreteShearWall *theModel = 0; static int eleTag = 0; static double tol = 1e-7; //1e-15; //double maxEleWallLength = Node::Node(int t, double x, double y, double z) : tag(t), xLoc(x), yLoc(y), zLoc(z) { } int Material::numTagND = 0; int Material::numTagUni = 0; Material::Material() : writtenUniaxial(false), writtenND(false) { } int Material::getNewTag() { int thisTag = ++numTagND; return thisTag; } int Concrete::readFromJSON(json_t *obj) { // double masspervolume, E, fpc, nu; masspervolume = json_number_value(json_object_get(obj, "masspervolume")); E = json_number_value(json_object_get(obj, "E")); fpc = json_number_value(json_object_get(obj, "fpc")); nu = json_number_value(json_object_get(obj, "nu")); return 0; } int Concrete::writeUniaxialJSON(json_t *obj) { std::cerr << "concrete: E: " << E << " fpc: " << fpc << " nu:" << nu << "\n"; return 0; } int Concrete::writeNDJSON(json_t *ndMaterials) { if (this->writtenND == false) { ndTag = ++numTagND; json_t *obj = json_object(); json_object_set(obj, "name", json_integer(ndTag)); json_object_set(obj, "type", json_string("Concrete")); json_object_set(obj, "E", json_real(E)); json_object_set(obj, "fpc", json_real(fpc)); // json_object_set(obj,"b",json_real((fu-fy)/(epsu-fy/E))); json_object_set(obj, "nu", json_real(nu)); json_array_append(ndMaterials, obj); writtenND = true; } return 0; } int Steel::writeUniaxialJSON(json_t *obj) { return 0; } int Steel::writeNDJSON(json_t *obj) { return 0; } int Steel::readFromJSON(json_t *obj) { // double masspervolume, E, fu,fy,nu; masspervolume = json_number_value(json_object_get(obj, "masspervolume")); E = json_number_value(json_object_get(obj, "E")); fu = json_number_value(json_object_get(obj, "fu")); fy = json_number_value(json_object_get(obj, "fy")); nu = json_number_value(json_object_get(obj, "nu")); return 0; } int SteelRebar::readFromJSON(json_t *obj) { // double masspervolume, E, epsu,fu,fy; masspervolume = json_number_value(json_object_get(obj, "masspervolume")); E = json_number_value(json_object_get(obj, "E")); fu = json_number_value(json_object_get(obj, "fu")); fy = json_number_value(json_object_get(obj, "fy")); epsu = json_number_value(json_object_get(obj, "epsu")); return 0; } int SteelRebar::writeUniaxialJSON(json_t *uniaxialArray) { if (json_array_size(uniaxialArray) < 1) { uniaxialTag = ++numTagUni; json_t *obj = json_object(); json_object_set(obj, "name", json_integer(uniaxialTag)); json_object_set(obj, "type", json_string("Steel01")); json_object_set(obj, "E", json_real(E)); json_object_set(obj, "fy", json_real(fy)); // json_object_set(obj,"b",json_real((fu-fy)/(epsu-fy/E))); json_object_set(obj, "b", json_real(.01)); json_array_append(uniaxialArray, obj); return uniaxialTag; } else { json_t *unixialMat; int index; json_array_foreach(uniaxialArray, index, unixialMat) { int thisunixialMatTag = json_integer_value(json_object_get(unixialMat, "name")); double thisunixialMatE = json_number_value(json_object_get(unixialMat, "E")); double thisunixialMatfy = json_number_value(json_object_get(unixialMat, "fy")); double thisunixialMatb = json_number_value(json_object_get(unixialMat, "b")); if (abs(thisunixialMatE - E) < 1e-7 && abs(thisunixialMatfy - fy) < 1e-7 && abs(thisunixialMatb - 0.01) < 1e-7) //(abs(thisunixialMat-uniaxialTag)<1e-7) { printf("unixal mat %d already exists in uniaxialMaterials. \n", thisunixialMatTag); return thisunixialMatTag; } } uniaxialTag = ++numTagUni; json_t *obj = json_object(); json_object_set(obj, "name", json_integer(uniaxialTag)); json_object_set(obj, "type", json_string("Steel01")); json_object_set(obj, "E", json_real(E)); json_object_set(obj, "fy", json_real(fy)); // json_object_set(obj,"b",json_real((fu-fy)/(epsu-fy/E))); json_object_set(obj, "b", json_real(.01)); json_array_append(uniaxialArray, obj); return uniaxialTag; } /* if (this->writtenUniaxial == false) { uniaxialTag = numTag++; json_t *obj = json_object(); json_object_set(obj, "name", json_integer(uniaxialTag)); json_object_set(obj, "type", json_string("Steel01")); json_object_set(obj, "E", json_real(E)); json_object_set(obj, "fy", json_real(fy)); // json_object_set(obj,"b",json_real((fu-fy)/(epsu-fy/E))); json_object_set(obj, "b", json_real(.01)); json_array_append(uniaxialArray, obj); writtenUniaxial = true; } */ return 0; } int SteelRebar::writeNDJSON(json_t *obj) { std::cerr << "steel rebar: E: " << E << " fu: " << fu << " fy: " << fy << " epsu:" << epsu << "\n"; return 0; } WallSection::WallSection() : writtenBeamSection(false), writtenND(false), beamTag(0), ndTag(0) { } int ConcreteRectangularWallSection::readFromJSON(json_t *obj) { thickness = json_number_value(json_object_get(obj, "thickness")); be_length = json_number_value(json_object_get(obj, "boundaryElementLength")); json_t *long_rebar = json_object_get(obj, "longitudinalRebar"); const char *t = json_string_value(json_object_get(long_rebar, "material")); lr_mat.assign(t); lr_numBarsThickness = json_integer_value(json_object_get(long_rebar, "numBarsThickness")); lr_area = json_number_value(json_object_get(long_rebar, "barArea")); lr_spacing = json_number_value(json_object_get(long_rebar, "spacing")); lr_cover = json_number_value(json_object_get(long_rebar, "cover")); json_t *tran_rebar = json_object_get(obj, "transverseRebar"); t = json_string_value(json_object_get(tran_rebar, "material")); tr_mat.assign(t); tr_numBarsThickness = json_integer_value(json_object_get(tran_rebar, "numBarsThickness")); tr_area = json_number_value(json_object_get(tran_rebar, "barArea")); tr_cover = json_number_value(json_object_get(tran_rebar, "cover")); tr_spacing = json_number_value(json_object_get(tran_rebar, "spacing")); if (be_length > 0.0) // has boundary elements { json_t *long_rebarB = json_object_get(obj, "longitudinalBoundaryElementRebar"); //t = json_string_value(json_object_get(long_rebarB, "material")); lrb_mat.assign(json_string_value(json_object_get(long_rebarB, "material"))); lrb_numBarsThickness = json_integer_value(json_object_get(long_rebarB, "numBarsThickness")); lrb_numBarsLength = json_integer_value(json_object_get(long_rebarB, "numBarsLength")); lrb_area = json_number_value(json_object_get(long_rebarB, "barArea")); lrb_cover = json_number_value(json_object_get(long_rebarB, "cover")); json_t *tranb_rebar = json_object_get(obj, "transverseBoundaryElementRebar"); //t = json_string_value(json_object_get(tranb_rebar, "material")); if (tranb_rebar != nullptr) { trb_mat.assign(json_string_value(json_object_get(tranb_rebar, "material"))); trb_numBarsThickness = json_integer_value(json_object_get(tranb_rebar, "numBarsThickness")); trb_numBarsLength = json_integer_value(json_object_get(tranb_rebar, "numBarsLength")); trb_area = json_number_value(json_object_get(tranb_rebar, "barArea")); //trb_cover = json_number_value(json_object_get(tranb_rebar, "cover")); trb_spacing = json_number_value(json_object_get(tranb_rebar, "spacing")); } else { // didn't find transverse rebar for BE, assume there is. set barArea=0; trb_mat.assign(json_string_value(json_object_get(long_rebarB, "material"))); trb_numBarsThickness = 0; trb_numBarsLength = 0; trb_area = 0.0; trb_spacing = json_number_value(json_object_get(long_rebarB, "spacing")); } } return 0; } int ConcreteRectangularWallSection::writeBeamSectionJSON(json_t *obj) { return 0; } int ConcreteRectangularWallSection::writeNDJSON(json_t *elements, json_t *nodes, json_t *properties, json_t *nodeMapping, string cline1, string cline2, string floor1, string floor2) { json_t *uniaxialMaterials = json_object_get(properties, "uniaxialMaterials"); json_t *ndMaterials = json_object_get(properties, "ndMaterials"); int lr_tag, lrb_tag, tr_tag, trb_tag, lrb_tag_ND, trb_tag_ND; std::cout << "lr_mat: " << lr_mat << std::endl; // Write out unixial steel materials Material *theLR_Material = theModel->getMaterial(lr_mat); // longitudinalRebar if (theLR_Material != 0) { lr_tag = theLR_Material->writeUniaxialJSON(uniaxialMaterials); //lr_tag = theLR_Material->uniaxialTag; } else { std::cerr << "ConcreteRectangularWallSection: long reinf mat not found: " << lr_mat << "\n"; return 0; } if (be_length > 0.0) { Material *theLRB_Material = theModel->getMaterial(lrb_mat); // longitudinalBoundaryElementRebar if (theLRB_Material != 0) { lrb_tag = theLRB_Material->writeUniaxialJSON(uniaxialMaterials); //lrb_tag = theLRB_Material->uniaxialTag; //printf("lrb_tag is = %d\n", lrb_tag); } else { std::cerr << "ConcreteRectangularWallSection: long reinf mat not found: " << lrb_mat << "\n"; return 0; } } Material *theTR_Material = theModel->getMaterial(tr_mat); // transverseRebar if (theTR_Material != 0) { tr_tag = theTR_Material->writeUniaxialJSON(uniaxialMaterials); //printf("tr_tag is = %d\n", tr_tag); cout << "tr_mat is: " << tr_mat << endl; //tr_tag = theTR_Material->uniaxialTag; } else { std::cerr << "ConcreteRectangularWallSection: long reinf mat not found: " << lrb_mat << "\n"; return 0; } Material *theTRb_Material = theModel->getMaterial(trb_mat); // transverseRebar if (theTRb_Material != 0) { trb_tag = theTRb_Material->writeUniaxialJSON(uniaxialMaterials); //printf("trb_tag is = %d\n", trb_tag); //tr_tag = theTR_Material->uniaxialTag; } else { // TODO std::cerr << "ConcreteRectangularWallSection: transverse boundary elem reinf mat not found: " << trb_mat << "\n"; trb_tag = tr_tag; //return 0; } //printf("Material::numTagND = %d\n", Material::numTagND); //printf("size of ndMaterial = %d\n", json_array_size(ndMaterials)); // Write out ND rebar (utilizes steel) json_t *rebarLR = json_object(); json_t *rebarLRB = json_object(); json_t *rebarTR = json_object(); json_t *rebarTRB = json_object(); json_object_set(rebarLR, "material", json_integer(lr_tag)); json_object_set(rebarLR, "angle", json_real(90)); int lr_tag_ND = ndMaterialExistInArray(rebarLR, ndMaterials); if (!lr_tag_ND) { int lr_name = ++Material::numTagND; lr_tag_ND = lr_name; json_object_set(rebarLR, "name", json_integer(lr_name)); json_object_set(rebarLR, "type", json_string("PlaneStressRebar")); json_array_append(ndMaterials, rebarLR); } if (be_length > 0.0) { json_object_set(rebarLRB, "material", json_integer(lrb_tag)); json_object_set(rebarLRB, "angle", json_real(90)); lrb_tag_ND = ndMaterialExistInArray(rebarLRB, ndMaterials); if (!lrb_tag_ND) { int lrb_name = ++Material::numTagND; lrb_tag_ND = lrb_name; json_object_set(rebarLRB, "name", json_integer(lrb_name)); json_object_set(rebarLRB, "type", json_string("PlaneStressRebar")); json_array_append(ndMaterials, rebarLRB); } json_object_set(rebarTRB, "material", json_integer(trb_tag)); json_object_set(rebarTRB, "angle", json_real(0)); trb_tag_ND = ndMaterialExistInArray(rebarTRB, ndMaterials); if (!trb_tag_ND) { int trb_name = ++Material::numTagND; trb_tag_ND = trb_name; json_object_set(rebarTRB, "name", json_integer(trb_name)); json_object_set(rebarTRB, "type", json_string("PlaneStressRebar")); json_array_append(ndMaterials, rebarTRB); } } json_object_set(rebarTR, "material", json_integer(tr_tag)); json_object_set(rebarTR, "angle", json_real(0)); int tr_tag_ND = ndMaterialExistInArray(rebarTR, ndMaterials); if (!tr_tag_ND) { int tr_name = ++Material::numTagND; tr_tag_ND = tr_name; json_object_set(rebarTR, "name", json_integer(tr_name)); json_object_set(rebarTR, "type", json_string("PlaneStressRebar")); json_array_append(ndMaterials, rebarTR); } //printf("Material = %d\n", json_integer_value(json_object_get(rebarTR, "material"))); //printf("Material::numTagND = %d\n", Material::numTagND); int ndMatSize = json_array_size(json_object_get(properties, "ndMaterials")); //printf("ndMatSize at entry of writeToJSON: %d\n", ndMatSize); // write out concrete Material *concrete = theModel->getMaterial(string("Concrete")); concrete->writeNDJSON(ndMaterials); int concTag = concrete->ndTag; // now write out the reinforced-sections double tTR = tr_area * tr_numBarsThickness / tr_spacing; // thickness of transver bar double tLR = lr_area * lr_numBarsThickness / lr_spacing; // thickness of logitudinal bar double tConc = thickness - tTR - tLR; // thickness of concrete int tag_matM = concrete->getNewTag(); int tag_matB; json_t *matM = json_object(); json_object_set(matM, "name", json_integer(tag_matM)); json_object_set(matM, "type", json_string("LayeredConcrete")); json_t *matLayers = json_array(); json_t *conc = json_object(); json_object_set(conc, "thickness", json_real(tConc)); json_object_set(conc, "material", json_integer(concTag)); json_array_append(matLayers, conc); json_t *longM = json_object(); json_object_set(longM, "thickness", json_real(tLR)); json_object_set(longM, "material", json_integer(lr_tag_ND)); json_array_append(matLayers, longM); json_t *horizM = json_object(); json_object_set(horizM, "thickness", json_real(tTR)); json_object_set(horizM, "material", json_integer(tr_tag_ND)); json_array_append(matLayers, horizM); json_object_set(matM, "layers", matLayers); json_array_append(ndMaterials, matM); if (be_length > 0.0) { tag_matB = concrete->getNewTag(); double tLRB = lrb_area * lrb_numBarsThickness * lrb_numBarsLength / be_length; // thickness logitudinal rebar double tTRB = trb_area * trb_numBarsThickness * trb_numBarsLength / be_length; // ask Frank how to calculate, TODO double tConcB = thickness - tLRB - tTRB; // thickness of concrete json_t *matBE = json_object(); json_object_set(matBE, "name", json_integer(tag_matB)); json_object_set(matBE, "type", json_string("LayeredConcrete")); json_t *matLayersB = json_array(); json_t *concB = json_object(); json_object_set(concB, "thickness", json_real(tConcB)); json_object_set(concB, "material", json_integer(concTag)); json_array_append(matLayersB, concB); json_t *longB = json_object(); json_object_set(longB, "thickness", json_real(tLRB)); json_object_set(longB, "material", json_integer(lrb_tag_ND)); json_array_append(matLayersB, longB); json_t *horizB = json_object(); json_object_set(horizB, "thickness", json_real(tTRB)); json_object_set(horizB, "material", json_integer(trb_tag_ND)); json_array_append(matLayersB, horizB); json_object_set(matBE, "layers", matLayersB); json_array_append(ndMaterials, matBE); } double floor1Loc = theModel->getFloorLocation(floor1); double floor2Loc = theModel->getFloorLocation(floor2); vector<double> loc1 = theModel->getCLineLoc(cline1); vector<double> loc2 = theModel->getCLineLoc(cline2); double cline1XLoc = loc1[0]; double cline1YLoc = loc1[1]; double cline2XLoc = loc2[0]; double cline2YLoc = loc2[1]; double dX = cline2XLoc - cline1XLoc; double dY = cline2YLoc - cline1YLoc; double dZ = floor2Loc - floor1Loc; double length = sqrt(dX * dX + dY * dY); if (length == 0 || dZ == 0) { std::cerr << "ERROR Wall : has 0 length or height"; return -1; } // mesh the section int numBoundary = 2; /* int numLength = nL; //int numLength = ceil(dX/maxWallEleLength); int numHeight = nH; // int numHeight = ceil(dX/maxWallEleLength); double deltaX1 = be_length / 2.0; double deltaX2 = (dX - 2 * be_length) / (numLength * 1.0); double deltaY = dY / numLength; double deltaZ = dZ / numHeight; */ double deltaX1 = be_length / 2.0; int numLength, numHeight; if (nL < 1.0) { numLength = ceil((dX - 2 * be_length) / deltaX1); } else { numLength = nL; } double deltaX2 = (dX - 2 * be_length) / numLength; double deltaY = dY / deltaX2; // TODO if (nH < 1.0) { numHeight = ceil(dZ / deltaX2); } else { numHeight = nH; } double deltaZ = dZ / numHeight; double x1Loc = 0; double x2Loc = deltaX1; for (int j = 0; j < numLength + (numBoundary * 2); j++) { for (int k = 0; k < numHeight; k++) { int iNode = theModel->addNode(cline1XLoc + x1Loc, cline1YLoc + deltaY * j, floor1Loc + deltaZ * k, nodes); int jNode = theModel->addNode(cline1XLoc + x2Loc, cline1YLoc + deltaY * (j + 1), floor1Loc + deltaZ * k, nodes); int kNode = theModel->addNode(cline1XLoc + x2Loc, cline1YLoc + deltaY * (j + 1), floor1Loc + deltaZ * (k + 1), nodes); int lNode = theModel->addNode(cline1XLoc + x1Loc, cline1YLoc + deltaY * j, floor1Loc + deltaZ * (k + 1), nodes); if (abs(iNode - jNode) > 1e-7) { json_t *theElement = json_object(); json_object_set(theElement, "name", json_integer(eleTag++)); json_object_set(theElement, "type", json_string("FourNodeQuad")); json_t *theNodes = json_array(); json_array_append(theNodes, json_integer(iNode)); json_array_append(theNodes, json_integer(jNode)); json_array_append(theNodes, json_integer(kNode)); json_array_append(theNodes, json_integer(lNode)); json_object_set(theElement, "nodes", theNodes); if (j < 2 || j > numLength + 1) // boundary json_object_set(theElement, "material", json_integer(tag_matB)); else json_object_set(theElement, "material", json_integer(tag_matM)); json_array_append(elements, theElement); } } x1Loc = x2Loc; if (j < numBoundary - 1) { x2Loc += deltaX1; } else if (j > numLength + numBoundary - 2) { x2Loc += deltaX1; } else { x2Loc += deltaX2; } } // add nodeMapping int cline1Floor1 = theModel->addNode(cline1XLoc, cline1YLoc, floor1Loc, nodes); int cline1Floor2 = theModel->addNode(cline1XLoc, cline1YLoc, floor2Loc, nodes); int cline2Floor1 = theModel->addNode(cline2XLoc, cline2YLoc, floor1Loc, nodes); int cline2Floor2 = theModel->addNode(cline2XLoc, cline2YLoc, floor2Loc, nodes); json_t *nodeMap = json_object(); json_object_set(nodeMap, "cline", json_integer(std::stoi(cline1))); json_object_set(nodeMap, "floor", json_integer(std::stoi(floor1))); json_object_set(nodeMap, "node", json_integer(cline1Floor1)); json_array_append(nodeMapping, nodeMap); nodeMap = json_object(); json_object_set(nodeMap, "cline", json_integer(std::stoi(cline1))); json_object_set(nodeMap, "floor", json_integer(std::stoi(floor2))); json_object_set(nodeMap, "node", json_integer(cline1Floor2)); json_array_append(nodeMapping, nodeMap); nodeMap = json_object(); json_object_set(nodeMap, "cline", json_integer(std::stoi(cline2))); json_object_set(nodeMap, "floor", json_integer(std::stoi(floor1))); json_object_set(nodeMap, "node", json_integer(cline2Floor1)); json_array_append(nodeMapping, nodeMap); nodeMap = json_object(); json_object_set(nodeMap, "cline", json_integer(std::stoi(cline2))); json_object_set(nodeMap, "floor", json_integer(std::stoi(floor2))); json_object_set(nodeMap, "node", json_integer(cline2Floor2)); json_array_append(nodeMapping, nodeMap); return 0; } int Wall::readFromJSON(json_t *theWall) { json_t *clineArray = json_object_get(theWall, "cline"); json_t *floorArray = json_object_get(theWall, "floor"); cline1 = string(json_string_value(json_array_get(clineArray, 0))); cline2 = string(json_string_value(json_array_get(clineArray, 1))); floor1 = string(json_string_value(json_array_get(floorArray, 0))); floor2 = string(json_string_value(json_array_get(floorArray, 1))); json_t *segments = json_object_get(theWall, "segment"); int numSegment = json_array_size(segments); if (numSegment > 1) { std::cerr << "CANNOT HABDLE MORE THAN 1 WALL SEGMENT .. UISNG LAST ALL WAY UP\n"; } for (int i = 0; i < numSegment; i++) { json_t *segment = json_array_get(segments, i); section = string(json_string_value(json_object_get(segment, "section"))); } return 0; } int Wall::writeToJSON(json_t *elements, json_t *nodes, json_t *properties, json_t *nodeMapping) { WallSection *theSection = theModel->getWallSection(section); if (theSection != 0) theSection->writeNDJSON(elements, nodes, properties, nodeMapping, cline1, cline2, floor1, floor2); /* double floor1Loc = theModel->getFloorLocation(floor1); double floor2Loc = theModel->getFloorLocation(floor2); vector<double> loc1 = theModel->getCLineLoc(cline1); vector<double> loc2 = theModel->getCLineLoc(cline2); double cline1XLoc = loc1[0]; double cline1YLoc = loc1[1]; double cline2XLoc = loc2[0]; double cline2YLoc = loc2[1]; double dX = cline2XLoc - cline1XLoc; double dY = cline2YLoc - cline1YLoc; double dZ = floor2Loc - floor1Loc; double length = sqrt(dX * dX + dY * dY); if (length == 0 || dZ == 0) { std::cerr << "ERROR Wall : " << name << " has 0 length or height"; return -1; } int numLength = 10; //int numLength = ceil(dX/maxWallEleLength); int numHeight = 10; // int numHeight = ceil(dX/maxWallEleLength); double deltaX = dX / numLength; double deltaY = dY / numLength; double deltaZ = dZ / numHeight; for (int j = 0; j < numLength; j++) { for (int k = 0; k < numHeight; k++) { int iNode = theModel->addNode(cline1XLoc + deltaX * j, cline1YLoc + deltaY * j, floor1Loc + deltaZ * k, nodes); int jNode = theModel->addNode(cline1XLoc + deltaX * (j + 1), cline1YLoc + deltaY * (j + 1), floor1Loc + deltaZ * k, nodes); int kNode = theModel->addNode(cline1XLoc + deltaX * (j + 1), cline1YLoc + deltaY * (j + 1), floor1Loc + deltaZ * (k + 1), nodes); int lNode = theModel->addNode(cline1XLoc + deltaX * j, cline1YLoc + deltaY * j, floor1Loc + deltaZ * (k + 1), nodes); json_t *theElement = json_object(); json_object_set(theElement, "name", json_integer(eleTag++)); json_object_set(theElement, "type", json_string("FourNodeQuad")); json_t *theNodes = json_array(); json_array_append(theNodes, json_integer(iNode)); json_array_append(theNodes, json_integer(jNode)); json_array_append(theNodes, json_integer(kNode)); json_array_append(theNodes, json_integer(lNode)); json_object_set(theElement, "nodes", theNodes); json_object_set(theElement, "material", json_string("FourNodeQuad")); json_array_append(elements, theElement); } } */ return 0; } ConcreteShearWall::ConcreteShearWall() : numFloors(0), numNode(0) { theModel = this; } void ConcreteShearWall::error(string message, int errorFlag) { std::cerr << message << "\n"; if (errorFlag != 1) exit(errorFlag); } int ConcreteShearWall::readBIM(const char *event, const char *bim) { //Parse BIM Json input file json_error_t error; json_t *rootBIM = json_load_file(bim, 0, &error); json_t *GI = json_object_get(rootBIM, "GI"); json_t *yType = json_object_get(GI, "yearBuilt"); int nStory = json_integer_value(json_object_get(GI, "numStory")); numFloors = nStory; SI = json_object_get(rootBIM, "StructuralInformation"); const char *type = json_string_value(json_object_get(SI, "type")); int year = json_integer_value(yType); if (strcmp(type, "ReinforcedConcreteShearWall") != 0) { return -1; } // // read floor and cline locations // json_t *layout = json_object_get(SI, "layout"); json_t *floorArray = json_object_get(layout, "floors"); if (floorArray == NULL) { return -2; } int numFLOOR = json_array_size(floorArray); for (int i = 0; i < numFLOOR; i++) { json_t *theFloor = json_array_get(floorArray, i); const char *name = json_string_value(json_object_get(theFloor, "name")); double location = json_number_value(json_object_get(theFloor, "elevation")); floors.insert(std::pair<string, double>(string(name), location)); std::cerr << "floor name: " << name << " loc: " << location << "\n"; } json_t *clineArray = json_object_get(layout, "clines"); if (clineArray == NULL) { return -2; } int numCLINE = json_array_size(clineArray); for (int i = 0; i < numCLINE; i++) { json_t *theCline = json_array_get(clineArray, i); const char *name = json_string_value(json_object_get(theCline, "name")); json_t *location = json_object_get(theCline, "location"); std::vector<double> loc(2); loc[0] = json_number_value(json_array_get(location, 0)); loc[1] = json_number_value(json_array_get(location, 1)); clines.insert(std::pair<string, vector<double>>(string(name), loc)); std::cerr << "cline name: " << name << " loc: " << loc[0] << " " << loc[1] << "\n"; } // // read the geometry & process elements // // read materials json_t *properties = json_object_get(SI, "properties"); json_t *materialsArray = json_object_get(properties, "materials"); if (materialsArray != NULL) { int numMat = json_array_size(materialsArray); for (int i = 0; i < numMat; i++) { json_t *material = json_array_get(materialsArray, i); const char *name = json_string_value(json_object_get(material, "name")); const char *type = json_string_value(json_object_get(material, "type")); Material *theMaterial = 0; if (strcmp(type, "concrete") == 0) { theMaterial = new Concrete(); } else if (strcmp(type, "steel") == 0) { theMaterial = new Steel(); } else if (strcmp(type, "steel rebar") == 0) { theMaterial = new SteelRebar(); } else { std::cerr << "unknown material type: " << type << "\n"; } theMaterial->readFromJSON(material); theMaterials.insert(std::pair<string, Material *>(string(name), theMaterial)); } } json_t *wallSectionsArray = json_object_get(properties, "wallsections"); if (wallSectionsArray != NULL) { int numSection = json_array_size(wallSectionsArray); for (int i = 0; i < numSection; i++) { json_t *section = json_array_get(wallSectionsArray, i); const char *name = json_string_value(json_object_get(section, "name")); const char *type = json_string_value(json_object_get(section, "type")); WallSection *theSection = 0; if (strcmp(type, "concrete rectangular wall") == 0) { theSection = new ConcreteRectangularWallSection(); } else { std::cerr << "unknown wall section type: " << type << "\n"; exit(-1); } theSection->readFromJSON(section); theWallSections.insert(std::pair<string, WallSection *>(string(name), theSection)); } } // // process wall information // json_t *geometry = json_object_get(SI, "geometry"); json_t *wallArray = json_object_get(geometry, "walls"); if (wallArray != NULL) { int numWall = json_array_size(wallArray); for (int i = 0; i < numWall; i++) { json_t *theWallData = json_array_get(wallArray, i); Wall *theWall = new Wall(); theWall->readFromJSON(theWallData); const char *name = json_string_value(json_object_get(theWallData, "name")); theWalls.insert(std::pair<string, Wall *>(string(name), theWall)); } /* json_t *clineArray = json_object_get(theWall,"cline"); json_t *floorArray = json_object_get(theWall,"floor"); const char *cline1 = json_string_value(json_array_get(clineArray,0)); const char *cline2 = json_string_value(json_array_get(clineArray,1)); const char *floor1 = json_string_value(json_array_get(floorArray,0)); const char *floor2 = json_string_value(json_array_get(floorArray,1)); double floor1Loc = this->getFloorLocation(string(floor1)); double floor2Loc = this->getFloorLocation(string(floor2)); vector<double> loc1 = this->getCLineLoc(cline1); vector<double> loc2 = this->getCLineLoc(cline2); double cline1XLoc = loc1[0]; double cline1YLoc = loc1[1]; double cline2XLoc = loc2[0]; double cline2YLoc = loc2[1]; double dX = cline2XLoc - cline1XLoc; double dY = cline2YLoc - cline1YLoc; double dZ = floor2Loc - floor1Loc; double length = sqrt(dX*dX + dY*dY); if (length == 0 || dZ == 0) { std::cerr << "ERROR Wall : " << name << " has 0 length or height"; break; } int numLength = 10; //int numLength = ceil(dX/maxWallEleLength); int numHeight = 10; // int numHeight = ceil(dX/maxWallEleLength); double deltaX = dX/numLength; double deltaY = dY/numLength; double deltaZ = dZ/numHeight; for (int j=0; j<numLength; j++) { for (int k=0; k<numHeight; k++) { int iNode = addNode(cline1XLoc + deltaX*j, cline1YLoc + deltaY*j, floor1Loc + deltaZ*k); int jNode = addNode(cline1XLoc + deltaX*(j+1), cline1YLoc + deltaY*(j+1), floor1Loc + deltaZ*k); int kNode = addNode(cline1XLoc + deltaX*(j+1), cline1YLoc + deltaY*(j+1), floor1Loc + deltaZ*(k+1)); int lNode = addNode(cline1XLoc + deltaX*j, cline1YLoc + deltaY*j, floor1Loc + deltaZ*(k+1)); } } */ } return 0; } int ConcreteShearWall::writeSAM(const char *path, int nLtmp, int nHtmp) { nL = nLtmp; nH = nHtmp; int nStory = numFloors; json_t *root = json_object(); json_t *sam = json_object(); json_t *properties = json_object(); json_t *geometry = json_object(); json_t *uniaxialMaterials = json_array(); json_t *ndMaterials = json_array(); json_t *sections = json_array(); json_t *crdTransformations = json_array(); json_t *nodes = json_array(); json_t *elements = json_array(); // // write the model // json_object_set(properties, "uniaxialMaterials", uniaxialMaterials); json_object_set(properties, "ndMaterials", ndMaterials); json_object_set(properties, "sections", sections); json_object_set(properties, "crdTransformations", crdTransformations); json_t *nodeMapping = json_array(); map<string, Wall *>::iterator it; for (it = theWalls.begin(); it != theWalls.end(); it++) { it->second->writeToJSON(elements, nodes, properties, nodeMapping); } json_object_set(geometry, "nodes", nodes); json_object_set(geometry, "elements", elements); json_object_set(sam, "geometry", geometry); json_object_set(sam, "properties", properties); json_object_set(root, "Structural Analysis Model", sam); /* // add nodeMapping json_t *nodeMapping = json_array(); json_t *nodeMap = json_object(); json_object_set(nodeMap,"cline",json_integer(1)); json_object_set(nodeMap,"floor",json_integer(1)); json_object_set(nodeMap,"node",json_integer(1)); json_array_append(nodeMapping, nodeMap); for(int i=0;i<nStory;++i) { nodeMap = json_object(); json_object_set(nodeMap,"cline",json_integer(1)); json_object_set(nodeMap,"floor",json_integer(i+2)); json_object_set(nodeMap,"node",json_integer(i+2)); json_array_append(nodeMapping, nodeMap); } */ json_object_set(sam, "nodeMapping", nodeMapping); /* json_t *properties = json_object(); json_t *geometry = json_object(); json_t *materials = json_array(); json_t *nodes = json_array(); json_t *elements = json_array(); json_t *nodeMapping = json_array(); // add node at ground json_t *node = json_object(); json_object_set(node, "name", json_integer(1)); // +2 as we need node at 1 json_t *nodePosn = json_array(); json_array_append(nodePosn,json_real(0.0)); json_array_append(nodePosn,json_real(0.0)); json_object_set(node, "crd", nodePosn); json_object_set(node, "ndf", json_integer(ndf)); json_array_append(nodes,node); json_t *nodeMap = json_object(); json_object_set(nodeMap,"cline",json_integer(1)); json_object_set(nodeMap,"floor",json_integer(1)); json_object_set(nodeMap,"node",json_integer(1)); json_array_append(nodeMapping, nodeMap); for(int i=0;i<nStory;++i) { json_t *node = json_object(); json_t *element = json_object(); json_t *material = json_object(); json_object_set(node, "name", json_integer(i+2)); // +2 as we need node at 1 json_object_set(node, "mass", json_real(floorParams[i].mass)); json_t *nodePosn = json_array(); json_array_append(nodePosn,json_real(floorParams[i].floor*storyheight)); json_array_append(nodePosn,json_real(0.0)); json_object_set(node, "crd", nodePosn); json_object_set(node, "ndf", json_integer(ndf)); nodeMap = json_object(); json_object_set(nodeMap,"cline",json_integer(1)); json_object_set(nodeMap,"floor",json_integer(i+2)); json_object_set(nodeMap,"node",json_integer(i+2)); json_array_append(nodeMapping, nodeMap); json_object_set(element, "name", json_integer(interstoryParams[i].story)); if (ndf == 1) json_object_set(element, "type", json_string("shear_beam")); else json_object_set(element, "type", json_string("shear_beam2d")); json_object_set(element, "uniaxial_material", json_integer(i+1)); json_t *eleNodes = json_array(); json_array_append(eleNodes,json_integer(i+1)); json_array_append(eleNodes,json_integer(i+2)); json_object_set(element, "nodes", eleNodes); json_object_set(material,"name",json_integer(i+1)); json_object_set(material,"type",json_string("shear")); json_object_set(material,"K0",json_real(interstoryParams[i].K0*kFactor)); json_object_set(material,"Sy",json_real(interstoryParams[i].Sy)); json_object_set(material,"eta",json_real(interstoryParams[i].eta)); json_object_set(material,"C",json_real(interstoryParams[i].C)); json_object_set(material,"gamma",json_real(interstoryParams[i].gamma)); json_object_set(material,"alpha",json_real(interstoryParams[i].alpha)); json_object_set(material,"beta",json_real(interstoryParams[i].beta)); json_object_set(material,"omega",json_real(interstoryParams[i].omega)); json_object_set(material,"eta_soft",json_real(interstoryParams[i].eta_soft)); json_object_set(material,"a_k",json_real(interstoryParams[i].a_k)); json_array_append(nodes,node); json_array_append(materials,material); json_array_append(elements, element); } json_object_set(properties,"dampingRatio",json_real(dampingRatio*dampFactor)); json_object_set(properties,"uniaxialMaterials",materials) json_object_set(root,"Properties",propertiesn); json_object_set(geometry,"nodes",nodes); json_object_set(geometry,"elements",elements); json_object_set(root,"Geometry",geometry); json_object_set(root,"NodeMapping",nodeMapping); */ json_object_set(root, "RandomVariables", json_array()); // write the file & clean memory json_dump_file(root, path, 0); //json_dump_file(sam,path,0); json_object_clear(root); return 0; } int ConcreteShearWall::writeOpenSeesModel(const char *path) { return 0; } int ConcreteShearWall::addNode(double x, double y, double z, json_t *theNodeArray) { // // iterate over nodes to see if one exists, if not add one // int result = -1; for (std::list<Node>::iterator it = nodes.begin(); it != nodes.end(); ++it) { double xLoc = it->xLoc; double yLoc = it->yLoc; double zLoc = it->zLoc; if (fabs(xLoc - x) < tol && fabs(yLoc - y) < tol && fabs(zLoc - z) < tol) result = it->tag; } if (result == -1) { numNode++; Node *newNode = new Node(numNode, x, y, z); nodes.push_back(*newNode); json_t *theNode = json_object(); json_object_set(theNode, "name", json_integer(numNode)); json_object_set(theNode, "ndf", json_integer(2)); json_t *crdArray = json_array(); json_array_append(crdArray, json_real(x)); //json_array_append(crdArray, json_real(y)); json_array_append(crdArray, json_real(z)); json_object_set(theNode, "crd", crdArray); json_array_append(theNodeArray, theNode); return numNode; } return result; } int ConcreteShearWall::addNode(double x, double y, double z, char *floor, char *col, json_t *) { return -1; } vector<double> ConcreteShearWall::getCLineLoc(string cline) { std::map<string, vector<double>>::iterator it; it = clines.find(cline); if (it != clines.end()) return it->second; else { std::cerr << "ConcreteShearWall = floor not found: " << cline << "\n"; std::vector<double> err(2); return err; } } double ConcreteShearWall::getFloorLocation(string floor) { std::map<string, double>::iterator it; it = floors.find(floor); if (it != floors.end()) return it->second; else { std::cerr << "ConcreteShearWall = floor not found: " << floor << "\n"; return 0; } } Material * ConcreteShearWall::getMaterial(string name) { std::map<string, Material *>::iterator it; it = theMaterials.find(name); if (it != theMaterials.end()) { cout << "Found material '" << it->first << "' exists in theMaterials." << endl; return it->second; } else { std::cerr << "ConcreteShearWall = material not found: " << name << "\n"; return 0; } } WallSection * ConcreteShearWall::getWallSection(string name) { std::map<string, WallSection *>::iterator it; it = theWallSections.find(name); if (it != theWallSections.end()) { return it->second; } else { std::cerr << "ConcreteShearWall = material not found: " << name << "\n"; return 0; } } int ConcreteRectangularWallSection::ndMaterialExistInArray(json_t *obj, json_t *array) { if (json_array_size(array) < 1) { return 0; } else { double material = json_number_value(json_object_get(obj, "material")); double angle = json_number_value(json_object_get(obj, "angle")); json_t *ndlMat; size_t index; json_array_foreach(array, index, ndlMat) { double thisMaterial = json_number_value(json_object_get(ndlMat, "material")); double thisAngle = json_number_value(json_object_get(ndlMat, "angle")); int name = json_integer_value(json_object_get(ndlMat, "name")); if (abs(thisMaterial - material) < 1e-7 && abs(thisAngle - angle) < 1e-7) //(abs(thisunixialMat-uniaxialTag)<1e-7) { printf("This nd mat already exists. \n"); return name; } } } return 0; }
34.288756
182
0.658303
[ "mesh", "geometry", "vector", "model" ]
963c8fdffa1e435a12e32c16a27561f5201b1cd2
1,552
hpp
C++
src/modules/memory/task_memory.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/modules/memory/task_memory.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
src/modules/memory/task_memory.hpp
abelov-spirent/openperf
303b6b5534973ea145a8223a55ee7b65e7464e25
[ "Apache-2.0" ]
null
null
null
#ifndef _OP_MEMORY_TASK_MEMORY_HPP_ #define _OP_MEMORY_TASK_MEMORY_HPP_ #include <atomic> #include <vector> #include <chrono> #include "timesync/chrono.hpp" #include "utils/worker/task.hpp" #include "memory/io_pattern.hpp" #include "memory/memory_stat.hpp" namespace openperf::memory::internal { struct task_memory_config { size_t block_size = 0; size_t op_per_sec = 0; io_pattern pattern = io_pattern::NONE; struct { void* ptr = nullptr; size_t size = 0; } buffer; }; class task_memory : public openperf::utils::worker::task<task_memory_config, memory_stat> { using chronometer = openperf::timesync::chrono::monotime; protected: task_memory_config m_config; std::vector<unsigned> m_indexes; uint8_t* m_buffer = nullptr; struct { void* ptr; size_t size; } m_scratch; stat_t m_stat_data; std::atomic<stat_t*> m_stat; std::atomic_bool m_stat_clear; size_t m_op_index; double m_avg_rate; public: task_memory(); explicit task_memory(const task_memory_config&); ~task_memory() override; void spin() override; void config(const config_t&) override; void clear_stat() override { m_stat_clear = true; }; stat_t stat() const override; config_t config() const override { return m_config; } protected: virtual void operation(uint64_t nb_ops) = 0; private: void scratch_allocate(size_t size); void scratch_free(); }; } // namespace openperf::memory::internal #endif // _OP_MEMORY_TASK_MEMORY_HPP_
21.555556
75
0.697165
[ "vector" ]
963ce284b4b16b61ddf302b9220f942a63930937
3,083
hpp
C++
kvm_pipeline/include/kvm_pipeline.hpp
catid/kvm
acc2ae7dc67838cf28b1e1ae8f9c231f8d470f52
[ "BSD-3-Clause" ]
26
2020-12-03T11:13:42.000Z
2022-03-25T05:36:33.000Z
kvm_pipeline/include/kvm_pipeline.hpp
catid/kvm
acc2ae7dc67838cf28b1e1ae8f9c231f8d470f52
[ "BSD-3-Clause" ]
4
2021-01-28T19:32:17.000Z
2021-06-01T15:01:42.000Z
kvm_pipeline/include/kvm_pipeline.hpp
catid/kvm
acc2ae7dc67838cf28b1e1ae8f9c231f8d470f52
[ "BSD-3-Clause" ]
8
2020-12-04T01:30:21.000Z
2021-12-01T11:19:11.000Z
// Copyright 2020 Christopher A. Taylor /* Video Pipeline: HDMI Capture -> JPEG Decode -> H.264 Encode -> Video Parser */ #pragma once #include "kvm_core.hpp" #include "kvm_capture.hpp" #include "kvm_jpeg.hpp" #include "kvm_encode.hpp" #include "kvm_video.hpp" #include <atomic> #include <thread> #include <mutex> #include <condition_variable> namespace kvm { //------------------------------------------------------------------------------ // PipelineNode class PipelineNode { public: ~PipelineNode() { Shutdown(); } void Initialize(const std::string& name, int max_queue_depth); void Shutdown(); bool IsTerminated() const { return Terminated; } void Queue(std::function<void()> func); protected: std::string Name; int MaxQueueDepth = 0; int Count = 0; int64_t TotalUsec = 0; int64_t FastestUsec = 0; int64_t SlowestUsec = 0; uint64_t LastReportUsec = 0; mutable std::mutex Lock; std::condition_variable Condition; std::vector<std::function<void()>> QueuePublic; std::vector<std::function<void()>> QueuePrivate; std::atomic<bool> Terminated = ATOMIC_VAR_INIT(false); std::shared_ptr<std::thread> Thread; void Loop(); }; //------------------------------------------------------------------------------ // PiplineStatistics /* Report statistics on how well we are compressing the input data */ class PiplineStatistics { public: void AddInput(int bytes); void AddVideo(int bytes); void OnOutputFrame(); void TryReport(); private: std::mutex Lock; static const int64_t ReportIntervalUsec = 20 * 1000 * 1000; // 20 seconds uint64_t LastReportUsec = 0; int InputBytes = 0; int InputCount = 0; int VideoBytes = 0; int VideoCount = 0; int MaxVideoBytes = 0; int MinVideoBytes = 0; uint64_t LastOutputFrameUsec = 0; uint64_t LastOutputReportUsec = 0; void Report(); }; //------------------------------------------------------------------------------ // VideoPipeline using PiplineCallback = std::function<void( uint64_t frame_number, uint64_t shutter_usec, const uint8_t* data, int bytes)>; class VideoPipeline { public: ~VideoPipeline() { Shutdown(); } void Initialize(PiplineCallback callback); void Shutdown(); bool IsTerminated() const { return Terminated; } protected: PiplineCallback Callback; V4L2Capture Capture; uint64_t LastFrameNumber = 0; PipelineNode DecoderNode; JpegDecoder Decoder; PipelineNode EncoderNode; MmalEncoder Encoder; VideoParser Parser; std::shared_ptr<std::vector<uint8_t>> VideoParameters; PipelineNode AppNode; std::atomic<bool> Terminated = ATOMIC_VAR_INIT(false); std::atomic<bool> ErrorState = ATOMIC_VAR_INIT(false); std::shared_ptr<std::thread> Thread; PiplineStatistics Stats; // Raw format image pool FramePool RawPool; void Start(); void Stop(); void Loop(); }; } // namespace kvm
18.79878
80
0.610444
[ "vector" ]
963d2ac980fef4017173d16dc0bf3957b684aac1
3,885
hpp
C++
include/parsergen/parser_formatter.hpp
Conqu3red/parsergen-cpp
1435ce4b9fe64541142791ff75c32b968d88ac21
[ "MIT" ]
1
2021-09-04T14:18:39.000Z
2021-09-04T14:18:39.000Z
include/parsergen/parser_formatter.hpp
Conqu3red/parsergen-cpp
1435ce4b9fe64541142791ff75c32b968d88ac21
[ "MIT" ]
null
null
null
include/parsergen/parser_formatter.hpp
Conqu3red/parsergen-cpp
1435ce4b9fe64541142791ff75c32b968d88ac21
[ "MIT" ]
null
null
null
#include "parsergen/lexer.hpp" #include "parsergen/grammar_ast.hpp" #include "parsergen/utils.hpp" #include "parsergen/parser.hpp" #include "fmt/core.h" #include <string> #include <vector> #include <memory> #include <tuple> #include <iostream> #pragma once using namespace Parsergen::AST; namespace Parsergen { /* std::string parser_format(std::shared_ptr<> item){ std::string rv = ""; return rv; } */ std::string parser_format(std::shared_ptr<ASTNode> expr); std::string parser_format_ParserDefinition(std::shared_ptr<ParserDefinition> item){ std::string rv = ""; for (auto &section : item->sections){ if (section->is("StatementGroup")){ auto a = std::dynamic_pointer_cast<StatementGroup>(section); rv += parser_format(a); } else { rv += parser_format(std::dynamic_pointer_cast<ConfigurationCall>(section)); } rv += "\n"; } return rv; } std::string parser_format_StatementGroup(std::shared_ptr<StatementGroup> item){ std::string rv = fmt::format("{}[{}]\n", item->name, item->return_type); for (auto &statement : item->statements){ rv += " : " + parser_format(statement) + "\n"; } return rv; } std::string parser_format_ConfigurationCall(std::shared_ptr<ConfigurationCall> item){ return fmt::format("@{} = '{}'\n", item->name, item->value); } std::string parser_format_Statement(std::shared_ptr<Statement> item){ std::string rv = ""; for (auto &expr : item->exprs){ rv += parser_format(expr) + " "; } rv += "{ " + item->action + " };"; return rv; } std::string parser_format_TokenPointer(std::shared_ptr<TokenPointer> item){ return fmt::format("{}", item->target); } std::string parser_format_StatementPointer(std::shared_ptr<StatementPointer> item){ return fmt::format("{}", item->target); } std::string parser_format_ConstantString(std::shared_ptr<ConstantString> item){ return fmt::format("'{}'", item->value); } std::string parser_format_AndPredicate(std::shared_ptr<AndPredicate> item){ return fmt::format("&{}", parser_format(item->expr)); } std::string parser_format_NotPredicate(std::shared_ptr<NotPredicate> item){ return fmt::format("!{}", parser_format(item->expr)); } std::string parser_format_ZeroOrMore(std::shared_ptr<ZeroOrMore> item){ return fmt::format("{}*", parser_format(item->expr)); } std::string parser_format_OneOrMore(std::shared_ptr<OneOrMore> item){ return fmt::format("{}+", parser_format(item->expr)); } std::string parser_format_ZeroOrOne(std::shared_ptr<ZeroOrOne> item){ return fmt::format("{}?", parser_format(item->expr)); } std::string parser_format_ExprList(std::shared_ptr<ExprList> item){ std::string rv = "("; for (auto &expr : item->exprs){ rv += parser_format(expr) + " "; } rv.pop_back(); return rv + ")"; } std::string parser_format_NamedItem(std::shared_ptr<NamedItem> item){ return fmt::format("{}={}", item->name, parser_format(item->expr)); } #define PFORMAT_DISPATCH(type) if (expr->is(#type)) return parser_format_ ##type(std::dynamic_pointer_cast<type>(expr)) std::string parser_format(std::shared_ptr<ASTNode> expr){ PFORMAT_DISPATCH(ParserDefinition); else PFORMAT_DISPATCH(StatementGroup); else PFORMAT_DISPATCH(ConfigurationCall); else PFORMAT_DISPATCH(Statement); else PFORMAT_DISPATCH(TokenPointer); else PFORMAT_DISPATCH(StatementPointer); else PFORMAT_DISPATCH(ConstantString); else PFORMAT_DISPATCH(AndPredicate); else PFORMAT_DISPATCH(NotPredicate); else PFORMAT_DISPATCH(ZeroOrMore); else PFORMAT_DISPATCH(OneOrMore); else PFORMAT_DISPATCH(ZeroOrOne); else PFORMAT_DISPATCH(ExprList); else PFORMAT_DISPATCH(NamedItem); else throw std::runtime_error(fmt::format("Invalid type '{}'", expr->class_name())); } }
29.884615
119
0.683912
[ "vector" ]
964d3968f43ebe0de00fa77968c34c997404a85b
4,069
hpp
C++
src/elona/quest.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/quest.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/quest.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
1
2020-02-24T18:52:19.000Z
2020-02-24T18:52:19.000Z
#pragma once #include <vector> namespace elona { template <typename T> struct elona_vector2; struct Quest { /** * 0 if empty. */ int client_chara_index; int originating_map_id; int deadline_hours; /** * TODO: enum class * * 0 - do not show * 1001 - hunt * 1002 - deliver * 1003 - cook * 1004 - supply * 1006 - harvest * 1007 - escort * 1008 - conquer * 1009 - party * 1010 - huntex * 1011 - collect */ int id; /** * Used only for escort quests. * * 0 - hard (assassin) * 1 - moderate (poison) * 2 - normal (delivery) */ int escort_difficulty; /** * For hunting quests, target character level is determined as follows. * * hunt - difficulty * 10 / 6 * huntex - difficulty * 3 / 2 */ int difficulty; int reward_gold; /** * If < 10000: * 1 - equipment * 2 - magical goods * 3 - armor * 4 - weapons * 5 - ores * 6 - furnitures (but no code path?) * * If <= 10000, acts as flttypemajor */ int reward_item_id; /** * 0: not taken * 1: accepted * 3: complete */ int progress; /** * If -1, deadline is immediate */ int deadline_days; /** * Target character for quests like "collect" (person bragging about item) * * Also may point to the quest giver. */ int target_chara_index; /** * Used for "deliver", "supply" and "collect". */ int target_item_id; /** * cook - food type * harvest - required weight * escort - destination map id * party - required points * huntex - target character id */ int extra_info_1; /** * cook - food rank * harvest - weight delivered so far * escort - escorted character id * party - points so far */ int extra_info_2; /** * Used in dialog option insertion when talking to client. * * 1 - hunt * 2 - deliver * 3 - supply * 4 - conquer (old) * 5 - harvest * 6 - escort * 7 - party * 8 - conquer */ int client_chara_type; /** * If a character has a related quest and this flag is set on the quest, the * emotion icon for the character will indicate they are the package * recipient. */ int delivery_has_package_flag; void clear(); /** * Moves this struct's fields into `qdata` so they can be serialized, for * compatibility. To be called before serializing `qdata`. */ void pack_to(elona_vector2<int>& legacy_qdata, int quest_id); /** * Moves `qdata` fields into this struct. To be called after deserializing * `qdata`. */ void unpack_from(elona_vector2<int>& legacy_qdata, int quest_id); }; struct QuestData { static constexpr size_t quest_size = 500; QuestData() : quests(quest_size) { } Quest& operator[](int i) { return quests.at(static_cast<size_t>(i)); } Quest& immediate(); void clear(); // Helper method to pack all quests to `qdata`. void pack_to(elona_vector2<int>& legacy_qdata); // Helper method to unpack all quests from `qdata`. void unpack_from(elona_vector2<int>& legacy_qdata); private: std::vector<Quest> quests; }; extern QuestData quest_data; enum class TurnResult; void quest_on_map_initialize(); void quest_place_target(); int quest_targets_remaining(); void quest_set_data(int); void quest_refresh_list(); void quest_update_journal_msg(); void quest_check(); void quest_check_all_for_failed(); void quest_update_main_quest_journal(); void quest_all_targets_killed(); void quest_failed(int); void quest_complete(); int quest_is_return_forbidden(); void quest_enter_map(); void quest_exit_map(); void quest_team_victorious(); TurnResult quest_pc_died_during_immediate_quest(); int quest_generate(); void quest_gen_scale_by_level(); } // namespace elona
19.014019
80
0.600147
[ "vector" ]
9661ad5e9f665ad6601bfb7da5c942bcdd9535d3
7,760
cpp
C++
Source/Main/initializationAux.cpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
Source/Main/initializationAux.cpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
Source/Main/initializationAux.cpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 Vitaly Dikov // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) ///#include"ammo.hpp" #include"initializationAux.hpp" #include"locator.hpp" #include"character.hpp" namespace init { using namespace std; constexpr int initialMoney = 50'000; void initializeSquad(game::object::Squad& squad) { initializeInventory(squad.inventory()); initializeMembers(squad.members()); squad.moneyAdd(game::common::Money{ initialMoney }); } void initializeInventory(game::object::Inventory& inventory) { using game::object::Item; using game::object::Ammo; using game::object::Weapon; using game::object::WeaponMod; const game::global::Factory& f = game::global::Locator::getFactory(); /// add AR with installed mods auto weapon{ f.createItem<Weapon>(Weapon::Model::AR_SOCOM) }; auto modBarrel{ f.createItem<WeaponMod>(WeaponMod::Model::BARREL_TITANIUM_COBALT) }; auto modMag{ f.createItem<WeaponMod>(WeaponMod::Model::MAG_QUICKFIRE) }; static_cast<Weapon*>(weapon.get())->setMod(0, modBarrel, game::object::isCompatible); static_cast<Weapon*>(weapon.get())->setMod(3, modMag, game::object::isCompatible); inventory.insert(weapon, true); /// weapons inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_SOCOM)); inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_KALASH97)); inventory.insert(f.createItem<Weapon>(Weapon::Model::SMG_RIPPER)); inventory.insert(f.createItem<Weapon>(Weapon::Model::SMG_RIPPER)); /// weapon mods inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_SHORTENED)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_LIGHTWEIGHT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_TITANIUM_COBALT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_HAMMERFORGE_RIFLED), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_BROACH_RIFLED), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_COLUMBIUM)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_CUT_RIFLED), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_PHASE_SILENCER)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_SOUND_SUPRESSOR)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_BLAST_MUFFLER)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_ALLOY)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_ADVANCED_MATERIALS)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_QUICKFIRE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_OVERSIZED)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_MAX_CAPACITY), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_EXTENDED)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_LONG)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_FARSIGHT), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_DEADEYE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_38MM)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_32MM)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_21MM)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_HOLOGRAPHIC), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_RED_DOT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::SCOPE_REFLEX)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_HE_FUSE_LINKAGE), true); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_PLASMA_LINKAGE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_CRYOCELL_LINKAGE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_INCENDIARY_LINKAGE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_SWAT_LIGHT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_TACTICAL_LIGHT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_UNDERBARREL_LIGHT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_COMP_ASSISTED_LS)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_ULTRAVIOLET_LS)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_SPEC_OPS_LS)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::UB_LASER_SIGHT)); /// ammo inventory.insert(f.createAmmo(Ammo::Type::A_5_56, 15), true); inventory.insert(f.createAmmo(Ammo::Type::A_5_56, 90)); inventory.insert(f.createAmmo(Ammo::Type::A_5_56, 10)); inventory.insert(f.createAmmo(Ammo::Type::FROZEN_FERRET, 6), true); inventory.insert(f.createAmmo(Ammo::Type::ENERGY_CELLS, 55)); inventory.insert(f.createAmmo(Ammo::Type::ROCKET, 4)); } void initializeShop(game::object::Inventory& inventory) { using game::object::Ammo; using game::object::Weapon; using game::object::WeaponMod; const game::global::Factory& f = game::global::Locator::getFactory(); /// weapons inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_SOCOM)); inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_SOCOM)); inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_KALASH97)); inventory.insert(f.createItem<Weapon>(Weapon::Model::AR_KALASH97)); inventory.insert(f.createItem<Weapon>(Weapon::Model::SMG_RIPPER)); /// weapon mods inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_LIGHTWEIGHT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_SHORTENED)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_TITANIUM_COBALT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_TITANIUM_COBALT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::BARREL_TITANIUM_COBALT)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_ADVANCED_MATERIALS)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_OVERSIZED)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_QUICKFIRE)); inventory.insert(f.createItem<WeaponMod>(WeaponMod::Model::MAG_QUICKFIRE)); /// ammo inventory.insert(f.createAmmo(Ammo::Type::A_5_56, 1500)); inventory.insert(f.createAmmo(Ammo::Type::A_7_62, 2000)); inventory.insert(f.createAmmo(Ammo::Type::A_D45, 1500)); inventory.insert(f.createAmmo(Ammo::Type::A_D38, 1000)); inventory.insert(f.createAmmo(Ammo::Type::ENERGY_CELLS, 1000)); inventory.insert(f.createAmmo(Ammo::Type::ROCKET, 50)); } void initializeMembers(array<unique_ptr<game::object::Unit>, game::object::nMembers>& members) { using game::object::Character; const game::global::Factory& f = game::global::Locator::getFactory(); int i = 0; /// member 1 if (i < members.size()) { members[i] = f.createUnit<Character>(Character::Model::RANGER_TEMPLATE); auto& c = *static_cast<Character*>(members[i++].get()); c.name("YURI"); } /// member 2 if (i < members.size()) { members[i] = f.createUnit<Character>(Character::Model::RANGER_TEMPLATE); auto& c = *static_cast<Character*>(members[i++].get()); c.name("ECHO"); } /// member 3 if (i < members.size()) { members[i] = f.createUnit<Character>(Character::Model::RANGER_TEMPLATE); auto& c = *static_cast<Character*>(members[i++].get()); c.name("RUST"); } } } // namespace init
48.805031
97
0.730155
[ "object", "model" ]
966955e345d89794dff38e3e2e7b36ca88d92e70
1,021
hpp
C++
doc/quickbook/oglplus/quickref/enums/access_specifier_class.hpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
doc/quickbook/oglplus/quickref/enums/access_specifier_class.hpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
doc/quickbook/oglplus/quickref/enums/access_specifier_class.hpp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File doc/quickbook/oglplus/quickref/enums/access_specifier_class.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/access_specifier.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //[oglplus_enums_access_specifier_class #if !__OGLPLUS_NO_ENUM_VALUE_CLASSES namespace enums { template <typename Base, template<__AccessSpecifier> class Transform> class __EnumToClass<Base, __AccessSpecifier, Transform> /*< Specialization of __EnumToClass for the __AccessSpecifier enumeration. >*/ : public Base { public: EnumToClass(void); EnumToClass(Base&& base); Transform<AccessSpecifier::ReadOnly> ReadOnly; Transform<AccessSpecifier::WriteOnly> WriteOnly; Transform<AccessSpecifier::ReadWrite> ReadWrite; }; } // namespace enums #endif //]
26.868421
72
0.773751
[ "transform" ]
966eafe0c015b6d9b736e5e9ccec4afad6455f60
13,670
cpp
C++
lib/djvSystem/FileIOUnix.cpp
belzecue/DJV
94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0
[ "BSD-3-Clause" ]
456
2018-10-06T00:07:14.000Z
2022-03-31T06:14:22.000Z
lib/djvSystem/FileIOUnix.cpp
belzecue/DJV
94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0
[ "BSD-3-Clause" ]
438
2018-10-31T15:05:51.000Z
2022-03-31T09:01:24.000Z
lib/djvSystem/FileIOUnix.cpp
belzecue/DJV
94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0
[ "BSD-3-Clause" ]
54
2018-10-29T10:18:36.000Z
2022-03-23T06:56:11.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2018-2020 Darby Johnston // All rights reserved. #include <djvSystem/FileIO.h> #include <djvSystem/File.h> #include <djvSystem/Path.h> #include <djvCore/Error.h> #include <djvCore/Memory.h> #include <djvCore/String.h> #include <djvCore/StringFormat.h> #include <iostream> #include <sstream> #if defined(DJV_PLATFORM_LINUX) #include <linux/limits.h> #endif // DJV_PLATFORM_LINUX #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #define _STAT struct stat #define _STAT_FNC stat using namespace djv::Core; namespace djv { namespace System { namespace File { namespace { enum class ErrorType { Open, Stat, MemoryMap, Close, CloseMemoryMap, Read, ReadMemoryMap, Write, Seek, SeekMemoryMap }; std::string getErrorString() { std::string out; char buf[String::cStringLength] = ""; #if defined(_GNU_SOURCE) out = strerror_r(errno, buf, String::cStringLength); #else // _GNU_SOURCE strerror_r(errno, buf, String::cStringLength); out = buf; #endif // _GNU_SOURCE return out; } std::string getErrorMessage(ErrorType type, const std::string& fileName) { //! \todo How can we translate this? std::vector<std::string> out; switch (type) { case ErrorType::Open: out.push_back(String::Format("{0}: Cannot open file:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::Stat: out.push_back(String::Format("{0}: Cannot stat file:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::MemoryMap: out.push_back(String::Format("{0}: Cannot memory map:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::Close: out.push_back(String::Format("{0}: Cannot close:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::CloseMemoryMap: out.push_back(String::Format("{0}: Cannot unmap:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::Read: out.push_back(String::Format("{0}: Cannot read.").arg(fileName)); break; case ErrorType::ReadMemoryMap: out.push_back(String::Format("{0}: Cannot read memory map.").arg(fileName)); break; case ErrorType::Write: out.push_back(String::Format("{0}: Cannot write:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::Seek: out.push_back(String::Format("{0}: Cannot seek:").arg(fileName)); out.push_back(getErrorString()); break; case ErrorType::SeekMemoryMap: out.push_back(String::Format("{0}: Cannot seek memory map.").arg(fileName)); break; default: break; } return String::join(out, ' '); } } // namespace void IO::open(const std::string& fileName, Mode mode) { close(); // Open the file. int openFlags = 0; int openMode = 0; switch (mode) { case Mode::Read: openFlags = O_RDONLY; break; case Mode::Write: openFlags = O_WRONLY | O_CREAT | O_TRUNC; openMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case Mode::ReadWrite: openFlags = O_RDWR | O_CREAT; openMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case Mode::Append: openFlags = O_WRONLY | O_CREAT | O_APPEND; openMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; default: break; } _f = ::open(fileName.c_str(), openFlags, openMode); if (-1 == _f) { throw Error(getErrorMessage(ErrorType::Open, fileName)); } // Stat the file. _STAT info; memset(&info, 0, sizeof(_STAT)); if (_STAT_FNC(fileName.c_str(), &info) != 0) { throw Error(getErrorMessage(ErrorType::Stat, fileName)); } _fileName = fileName; _mode = mode; _pos = 0; _size = info.st_size; #if defined(DJV_MMAP) // Memory mapping. if (Mode::Read == _mode && _size > 0) { _mmap = mmap(0, _size, PROT_READ, MAP_SHARED, _f, 0); madvise(_mmap, _size, MADV_SEQUENTIAL | MADV_SEQUENTIAL); if (_mmap == (void *) - 1) { throw Error(getErrorMessage(ErrorType::MemoryMap, fileName)); } _mmapStart = reinterpret_cast<const uint8_t *>(_mmap); _mmapEnd = _mmapStart + _size; _mmapP = _mmapStart; } #endif // DJV_MMAP } void IO::openTemp() { close(); // Open the file. const Path path(getTemp(), "XXXXXX"); const std::string fileName = path.get(); const size_t size = fileName.size(); std::vector<char> buf(size + 1); memcpy(buf.data(), fileName.c_str(), size); buf[size] = 0; _f = mkstemp(buf.data()); if (-1 == _f) { throw Error(getErrorMessage(ErrorType::Open, fileName)); } // Stat the file. _STAT info; memset(&info, 0, sizeof(_STAT)); if (_STAT_FNC(buf.data(), &info) != 0) { throw Error(getErrorMessage(ErrorType::Stat, fileName)); } _fileName = std::string(buf.data()); _mode = Mode::ReadWrite; _pos = 0; _size = info.st_size; } bool IO::close(std::string* error) { bool out = true; _fileName = std::string(); #if defined(DJV_MMAP) if (_mmap != (void *) - 1) { int r = munmap(_mmap, _size); if (-1 == r) { out = false; if (error) { *error = getErrorMessage(ErrorType::CloseMemoryMap, _fileName); } } _mmap = (void *)-1; } _mmapStart = 0; _mmapEnd = 0; #endif // DJV_MMAP if (_f != -1) { int r = ::close(_f); if (-1 == r) { out = false; if (error) { *error = getErrorMessage(ErrorType::Close, _fileName); } } _f = -1; } _mode = Mode::First; _pos = 0; _size = 0; return out; } bool IO::isOpen() const { return _f != -1; } bool IO::isEOF() const { return -1 == _f || (_size ? _pos >= _size : true); } void IO::read(void* in, size_t size, size_t wordSize) { if (-1 == _f) { throw Error(getErrorMessage(ErrorType::Read, _fileName)); } switch (_mode) { case Mode::Read: { #if defined(DJV_MMAP) const uint8_t* mmapP = _mmapP + size * wordSize; if (mmapP > _mmapEnd) { throw Error(getErrorMessage(ErrorType::ReadMemoryMap, _fileName)); } if (_endianConversion && wordSize > 1) { Memory::endian(_mmapP, in, size, wordSize); } else { memcpy(in, _mmapP, size * wordSize); } _mmapP = mmapP; #else // DJV_MMAP const size_t r = ::read(_f, in, size * wordSize); if (r != size * wordSize) { throw Error(getErrorMessage(ErrorType::Read, _fileName)); } if (_endianConversion && wordSize > 1) { Memory::endian(in, size, wordSize); } #endif // DJV_MMAP break; } case Mode::ReadWrite: { const size_t r = ::read(_f, in, size * wordSize); if (r != size * wordSize) { throw Error(getErrorMessage(ErrorType::Read, _fileName)); } if (_endianConversion && wordSize > 1) { Memory::endian(in, size, wordSize); } break; } default: break; } _pos += size * wordSize; } void IO::write(const void* in, size_t size, size_t wordSize) { if (-1 == _f) { throw Error(getErrorMessage(ErrorType::Write, _fileName)); } const uint8_t* inP = reinterpret_cast<const uint8_t*>(in); std::vector<uint8_t> tmp; if (_endianConversion && wordSize > 1) { tmp.resize(size * wordSize); inP = tmp.data(); Memory::endian(in, tmp.data(), size, wordSize); } if (::write(_f, inP, size * wordSize) == -1) { throw Error(getErrorMessage(ErrorType::Write, _fileName)); } _pos += size * wordSize; _size = std::max(_pos, _size); } void IO::_setPos(size_t in, bool seek) { switch (_mode) { case Mode::Read: { #if defined(DJV_MMAP) if (!seek) { _mmapP = reinterpret_cast<const uint8_t*>(_mmapStart) + in; } else { _mmapP += in; } if (_mmapP > _mmapEnd) { throw Error(getErrorMessage(ErrorType::SeekMemoryMap, _fileName)); } #else // DJV_MMAP if (::lseek(_f, in, ! seek ? SEEK_SET : SEEK_CUR) == (off_t) - 1) { throw Error(getErrorMessage(ErrorType::Seek, _fileName)); } #endif // DJV_MMAP break; } case Mode::Write: case Mode::ReadWrite: { if (::lseek(_f, in, ! seek ? SEEK_SET : SEEK_CUR) == (off_t) - 1) { throw Error(getErrorMessage(ErrorType::Seek, _fileName)); } break; } default: break; } if (!seek) { _pos = in; } else { _pos += in; } } } // namespace File } // namespace System } // namespace djv
34.433249
100
0.384931
[ "vector" ]
967651b23aed626c7dde0ac4c3a112d25076569e
10,671
cpp
C++
src/org/apache/poi/hssf/record/AbstractEscherHolderRecord.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/record/AbstractEscherHolderRecord.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/record/AbstractEscherHolderRecord.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/hssf/record/AbstractEscherHolderRecord.java #include <org/apache/poi/hssf/record/AbstractEscherHolderRecord.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/SecurityException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/System.hpp> #include <java/util/ArrayList.hpp> #include <java/util/Iterator.hpp> #include <java/util/List.hpp> #include <org/apache/poi/ddf/DefaultEscherRecordFactory.hpp> #include <org/apache/poi/ddf/EscherContainerRecord.hpp> #include <org/apache/poi/ddf/EscherRecord.hpp> #include <org/apache/poi/ddf/EscherRecordFactory.hpp> #include <org/apache/poi/ddf/NullEscherSerializationListener.hpp> #include <org/apache/poi/hssf/record/Record.hpp> #include <org/apache/poi/hssf/record/RecordInputStream.hpp> #include <org/apache/poi/hssf/util/LazilyConcatenatedByteArray_.hpp> #include <org/apache/poi/util/LittleEndian.hpp> #include <Array.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::hssf::record::AbstractEscherHolderRecord::AbstractEscherHolderRecord(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::hssf::record::AbstractEscherHolderRecord::AbstractEscherHolderRecord() : AbstractEscherHolderRecord(*static_cast< ::default_init_tag* >(0)) { ctor(); } poi::hssf::record::AbstractEscherHolderRecord::AbstractEscherHolderRecord(RecordInputStream* in) : AbstractEscherHolderRecord(*static_cast< ::default_init_tag* >(0)) { ctor(in); } void poi::hssf::record::AbstractEscherHolderRecord::init() { rawDataContainer = new ::poi::hssf::util::LazilyConcatenatedByteArray_(); } bool& poi::hssf::record::AbstractEscherHolderRecord::DESERIALISE() { clinit(); return DESERIALISE_; } bool poi::hssf::record::AbstractEscherHolderRecord::DESERIALISE_; void poi::hssf::record::AbstractEscherHolderRecord::ctor() { super::ctor(); init(); escherRecords = new ::java::util::ArrayList(); } void poi::hssf::record::AbstractEscherHolderRecord::ctor(RecordInputStream* in) { super::ctor(); init(); escherRecords = new ::java::util::ArrayList(); if(!DESERIALISE_) { npc(rawDataContainer)->concatenate(npc(in)->readRemainder()); } else { auto data = npc(in)->readAllContinuedRemainder(); convertToEscherRecords(0, npc(data)->length, data); } } void poi::hssf::record::AbstractEscherHolderRecord::convertRawBytesToEscherRecords() { if(!DESERIALISE_) { auto rawData = getRawData(); convertToEscherRecords(0, npc(rawData)->length, rawData); } } void poi::hssf::record::AbstractEscherHolderRecord::convertToEscherRecords(int32_t offset, int32_t size, ::int8_tArray* data) { npc(escherRecords)->clear(); ::poi::ddf::EscherRecordFactory* recordFactory = new ::poi::ddf::DefaultEscherRecordFactory(); auto pos = offset; while (pos < offset + size) { auto r = npc(recordFactory)->createRecord(data, pos); auto bytesRead = npc(r)->fillFields(data, pos, recordFactory); npc(escherRecords)->add(static_cast< ::java::lang::Object* >(r)); pos += bytesRead; } } java::lang::String* poi::hssf::record::AbstractEscherHolderRecord::toString() { auto buffer = new ::java::lang::StringBuffer(); auto const nl = ::java::lang::System::getProperty(u"line.separator"_j); npc(buffer)->append(::java::lang::StringBuilder().append(u'[')->append(getRecordName()) ->append(u']') ->append(nl)->toString()); if(npc(escherRecords)->size() == 0) npc(buffer)->append(::java::lang::StringBuilder().append(u"No Escher Records Decoded"_j)->append(nl)->toString()); for (auto _i = npc(escherRecords)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* r = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { npc(buffer)->append(static_cast< ::java::lang::Object* >(r)); } } npc(buffer)->append(::java::lang::StringBuilder().append(u"[/"_j)->append(getRecordName()) ->append(u']') ->append(nl)->toString()); return npc(buffer)->toString(); } int32_t poi::hssf::record::AbstractEscherHolderRecord::serialize(int32_t offset, ::int8_tArray* data) { ::poi::util::LittleEndian::putShort(data, int32_t(0) + offset, getSid()); ::poi::util::LittleEndian::putShort(data, int32_t(2) + offset, static_cast< int16_t >((getRecordSize() - int32_t(4)))); auto rawData = getRawData(); if(npc(escherRecords)->size() == 0 && rawData != nullptr) { ::poi::util::LittleEndian::putShort(data, int32_t(0) + offset, getSid()); ::poi::util::LittleEndian::putShort(data, int32_t(2) + offset, static_cast< int16_t >((getRecordSize() - int32_t(4)))); ::java::lang::System::arraycopy(rawData, 0, data, int32_t(4) + offset, npc(rawData)->length); return npc(rawData)->length + int32_t(4); } ::poi::util::LittleEndian::putShort(data, int32_t(0) + offset, getSid()); ::poi::util::LittleEndian::putShort(data, int32_t(2) + offset, static_cast< int16_t >((getRecordSize() - int32_t(4)))); auto pos = offset + int32_t(4); for (auto _i = npc(escherRecords)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* r = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { pos += npc(r)->serialize(pos, data, new ::poi::ddf::NullEscherSerializationListener()); } } return getRecordSize(); } int32_t poi::hssf::record::AbstractEscherHolderRecord::getRecordSize() { auto rawData = getRawData(); if(npc(escherRecords)->size() == 0 && rawData != nullptr) { return npc(rawData)->length; } auto size = int32_t(0); for (auto _i = npc(escherRecords)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* r = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { size += npc(r)->getRecordSize(); } } return size; } poi::hssf::record::AbstractEscherHolderRecord* poi::hssf::record::AbstractEscherHolderRecord::clone() { return java_cast< AbstractEscherHolderRecord* >(cloneViaReserialise()); } void poi::hssf::record::AbstractEscherHolderRecord::addEscherRecord(int32_t index, ::poi::ddf::EscherRecord* element) { npc(escherRecords)->add(index, element); } bool poi::hssf::record::AbstractEscherHolderRecord::addEscherRecord(::poi::ddf::EscherRecord* element) { return npc(escherRecords)->add(static_cast< ::java::lang::Object* >(element)); } java::util::List* poi::hssf::record::AbstractEscherHolderRecord::getEscherRecords() { return escherRecords; } void poi::hssf::record::AbstractEscherHolderRecord::clearEscherRecords() { npc(escherRecords)->clear(); } poi::ddf::EscherContainerRecord* poi::hssf::record::AbstractEscherHolderRecord::getEscherContainer() { for (auto _i = npc(escherRecords)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* er = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { if(dynamic_cast< ::poi::ddf::EscherContainerRecord* >(er) != nullptr) { return java_cast< ::poi::ddf::EscherContainerRecord* >(er); } } } return nullptr; } poi::ddf::EscherRecord* poi::hssf::record::AbstractEscherHolderRecord::findFirstWithId(int16_t id) { return findFirstWithId(id, getEscherRecords()); } poi::ddf::EscherRecord* poi::hssf::record::AbstractEscherHolderRecord::findFirstWithId(int16_t id, ::java::util::List* records) { for (auto _i = npc(records)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* r = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { if(npc(r)->getRecordId() == id) { return r; } } } for (auto _i = npc(records)->iterator(); _i->hasNext(); ) { ::poi::ddf::EscherRecord* r = java_cast< ::poi::ddf::EscherRecord* >(_i->next()); { if(npc(r)->isContainerRecord()) { auto found = findFirstWithId(id, npc(r)->getChildRecords()); if(found != nullptr) { return found; } } } } return nullptr; } poi::ddf::EscherRecord* poi::hssf::record::AbstractEscherHolderRecord::getEscherRecord(int32_t index) { return java_cast< ::poi::ddf::EscherRecord* >(npc(escherRecords)->get(index)); } void poi::hssf::record::AbstractEscherHolderRecord::join(AbstractEscherHolderRecord* record) { npc(rawDataContainer)->concatenate(npc(record)->getRawData()); } void poi::hssf::record::AbstractEscherHolderRecord::processContinueRecord(::int8_tArray* record) { npc(rawDataContainer)->concatenate(record); } int8_tArray* poi::hssf::record::AbstractEscherHolderRecord::getRawData() { return npc(rawDataContainer)->toArray_(); } void poi::hssf::record::AbstractEscherHolderRecord::setRawData(::int8_tArray* rawData) { npc(rawDataContainer)->clear(); npc(rawDataContainer)->concatenate(rawData); } void poi::hssf::record::AbstractEscherHolderRecord::decode() { if(nullptr == escherRecords || 0 == npc(escherRecords)->size()) { auto rawData = getRawData(); convertToEscherRecords(0, npc(rawData)->length, rawData); } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::hssf::record::AbstractEscherHolderRecord::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.record.AbstractEscherHolderRecord", 53); return c; } void poi::hssf::record::AbstractEscherHolderRecord::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; { try { DESERIALISE_ = (::java::lang::System::getProperty(u"poi.deserialize.escher"_j) != nullptr); } catch (::java::lang::SecurityException* e) { DESERIALISE_ = false; } } } }; if(!in_cl_init) { static clinit_ clinit_instance; } } int8_tArray* poi::hssf::record::AbstractEscherHolderRecord::serialize() { return super::serialize(); } java::lang::Class* poi::hssf::record::AbstractEscherHolderRecord::getClass0() { return class_(); }
33.87619
127
0.662543
[ "object" ]
9678ce73238a8585ccd80b6195dd8b9e0a3dd1a7
6,979
cpp
C++
Context/Image.cpp
Joeppie/Backprojec
ed925bf9801f27eeae98711f246e5ef884e2a0ed
[ "Unlicense", "MIT" ]
7
2019-03-15T12:32:07.000Z
2021-02-20T04:07:23.000Z
Context/Image.cpp
Joeppie/Backprojec
ed925bf9801f27eeae98711f246e5ef884e2a0ed
[ "Unlicense", "MIT" ]
6
2017-08-18T13:22:15.000Z
2017-08-29T19:39:56.000Z
Context/Image.cpp
Joeppie/Backprojec
ed925bf9801f27eeae98711f246e5ef884e2a0ed
[ "Unlicense", "MIT" ]
2
2018-07-06T14:46:50.000Z
2019-04-17T13:47:48.000Z
#include <math.h> #include "Image.h" #include "../util.h" #include <iomanip> #include <stdexcept> #include <sstream> //constructors Image::Image() {} Image::Image(int _height, int _width, const std::string &_fileName, const std::shared_ptr<InteriorOrientation> &_IO, const std::shared_ptr<ExteriorOrientation> &_EO) : _height(_height), _width(_width), _fileName(_fileName), _IO(_IO), _EO(_EO) {} //getters and setters. int Image::get_height() const { return _height; } void Image::set_height(int height) { if (height <= 0) { throw std::invalid_argument("Image height must be greater than zero."); } Image::_height = height; } int Image::get_width() const { return _width; } void Image::set_width(int width) { if (width <= 0) { throw std::invalid_argument("Image width must be greater than zero."); } Image::_width = width; } const std::string &Image::get_fileName() const { return _fileName; } void Image::set_fileName(const std::string &fileName) { Image::_fileName = fileName; } const std::shared_ptr<InteriorOrientation> &Image::get_IO() const { return _IO; } void Image::set_IO(const std::shared_ptr<InteriorOrientation> &IO) { if (IO.get() == nullptr) { throw std::invalid_argument("Image IO must not contain nullptr."); } auto pp = IO->get_principalPoint(); if (pp.x <= 0 || pp.y <= 0 || pp.x > this->_width || pp.y > this->_height) { throw std::invalid_argument("Error: IO specifies that principal point lies outside of image."); } Image::_IO = IO; } const std::shared_ptr<ExteriorOrientation> &Image::get_EO() const { return _EO; } void Image::set_EO(const std::shared_ptr<ExteriorOrientation> &EO) { if (EO.get() == nullptr) { throw std::invalid_argument("Image EO must not contain nullptr."); } Image::_EO = EO; } bool Image::backProject(const vector &worldCoordinate, Point &imageCoordinate) { //Avoid spamming when normally executing program (due to printmatrix statements that help debug) //Create a column 'vector' (or really just a 3x1 matrix, so that we can multiply and happily use results.) matrix X = {{worldCoordinate[0]}, {worldCoordinate[1]}, {worldCoordinate[2]}, {1} }; /*printMatrix(X);*/ //Backproject use the transpose of the rotation+translation matrix. matrix transformation = this->_EO->get_transformation(); //K=[F 0 cxp; 0 F cyp; 0 0 1]; %Camera matrix //Create camera matrix double f = this->get_IO()->get_focalLength(); Point pp = this->get_IO()->get_principalPoint(); //The camera matrix, it is populated with Interior Orientation information; focal length and principal point. matrix k = {{f, 0, pp.x}, {0, f, pp.y}, {0, 0, 1}}; std::stringstream fmt; fmt << this->_fileName << " Camera matrix"; printMatrix(k, fmt.str()); //Rotate camera properly into world frame const double deg_to_rad = M_PI / 180.0; double pitch2 = 180 * deg_to_rad; double yaw2 = 90 * deg_to_rad; double roll2 = 0 * deg_to_rad; //Assemble outer rotation matrix const matrix rotationY2 = {{cos(pitch2), 0, sin(pitch2)}, {0, 1, 0}, {-sin(pitch2), 0, cos(pitch2)}}; const matrix rotationX2 = {{1, 0, 0}, {0, cos(roll2), -sin(roll2)}, {0, sin(roll2), cos(roll2)}}; const matrix rotationZ2 = {{cos(yaw2), -sin(yaw2), 0}, {sin(yaw2), cos(yaw2), 0}, {0, 0, 1}}; matrix RMtemp = multiply(multiply(rotationX2, rotationY2), rotationZ2); matrix RM = multiply(transformation, RMtemp); //Compute transpose matrix RMt = transpose(RM); //Relate translation component to world frame vector translation = this->_EO->get_translation(); matrix columnVectorTranslation = {{translation[0]}, {translation[1]}, {translation[2]}}; matrix RMtn = negate(RMt); matrix tR = multiply(RMtn, columnVectorTranslation); /*printMatrix(tR);*/ //Concatenate rotation and translation elements matrix Rt = concatenate(RMt, tR); /*printMatrix(Rt);*/ //Compute Projection matrix matrix P = multiply(k, Rt); std::stringstream fmt2; fmt2 << this->_fileName << " Projection Matrix"; printMatrix(P, fmt2.str()); //Return image coordinates from object point matrix x = multiply(P, X); /*printMatrix(x);*/ imageCoordinate.x = x[0][0] / x[2][0]; imageCoordinate.y = x[1][0] / x[2][0]; //Return true when the image row-column coordinate calculated lies within the image. return imageCoordinate.x < this->_height && imageCoordinate.x > 0 && imageCoordinate.y < this->_height && imageCoordinate.y > 0; } std::_Setw indent(int level) { const int indentSize = 12; return std::setw(level * indentSize); } std::ostream &operator<<(std::ostream &stream, const Image &image) { stream << indent(1) << std::left << "filename: " << indent(1) << image.get_fileName() << "\n"; stream << indent(1) << std::left << "width: " << indent(1) << image.get_width() << "\n"; stream << indent(1) << std::left << "height: " << indent(1) << image.get_height() << "\n"; stream << "\n"; stream << indent(1) << std::left << "\nInterior Orientation:" << "\n"; stream << indent(2) << std::left << " focal length: " << indent(1) << image.get_IO()->get_focalLength() << "\n"; stream << indent(2) << std::left << "\n Principal Point: " << "\n"; Point pp = image.get_IO()->get_principalPoint(); stream << indent(3) << std::left << " x: " << indent(1) << pp.x << "\n"; stream << indent(3) << std::left << " y: " << indent(1) << pp.y << "\n"; stream << "\n"; stream << indent(1) << std::left << "\nExterior Orientation:" << "\n"; vector rotation = image.get_EO()->get_rotation(); stream << indent(1) << std::left << "\n rotation:" << "\n"; stream << indent(1) << std::left << " roll: " << indent(1) << rotation[0] << "\n"; stream << indent(1) << std::left << " pitch: " << indent(1) << rotation[1] << "\n"; stream << indent(1) << std::left << " yaw: " << indent(1) << rotation[2] << "\n"; vector translation = image.get_EO()->get_translation(); stream << indent(1) << std::left << "\n translation:" << "\n"; stream << indent(1) << std::left << " x: " << indent(1) << translation[0] << "\n"; stream << indent(1) << std::left << " y: " << indent(1) << translation[1] << "\n"; stream << indent(1) << std::left << " z: " << indent(1) << translation[2] << "\n"; return stream; }
34.043902
119
0.5763
[ "object", "vector" ]
9680c922a0f2e3b0c1d179ccc725fc81ed792e69
6,019
cpp
C++
src/unit.cpp
tomalexander/topaz
a0776a3b14629e5e1af3a4ed89fded3fe06cfea3
[ "Zlib" ]
1
2015-07-23T00:26:23.000Z
2015-07-23T00:26:23.000Z
src/unit.cpp
tomalexander/topaz
a0776a3b14629e5e1af3a4ed89fded3fe06cfea3
[ "Zlib" ]
null
null
null
src/unit.cpp
tomalexander/topaz
a0776a3b14629e5e1af3a4ed89fded3fe06cfea3
[ "Zlib" ]
null
null
null
/* * Copyright (c) 2012 Tom Alexander, Tate Larsen * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #include "def.h" #include "unit.h" #include "types.h" #include <algorithm> #include <cstdlib> #include <sstream> #include "rigidbody.h" #include "sqt.h" #include <glm/gtc/matrix_transform.hpp> #include "print.h" using std::min; using std::max; using std::stringstream; namespace topaz { unit::unit() { model_ptr = NULL; light_program = NULL; light_source = NULL; root_joint = NULL; current_animation = NULL; animation_progress = 0; rigid_body = NULL; transform = new sqt(); add_pre_draw_function(id, std::bind(&topaz::unit::update, this, std::placeholders::_1)); add_draw_function(id, std::bind(&topaz::unit::draw, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } unit::unit(model* _model_ptr) { light_program = NULL; light_source = NULL; root_joint = NULL; model_ptr = NULL; set_model(_model_ptr); current_animation = NULL; animation_progress = 0; rigid_body = NULL; transform = new sqt(); add_pre_draw_function(id, std::bind(&topaz::unit::update, this, std::placeholders::_1)); add_draw_function(id, std::bind(&topaz::unit::draw, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } unit::~unit() { delete root_joint; delete rigid_body; delete transform; } void unit::draw(const glm::mat4 & V, const glm::mat4 & P, camera* C) { topaz::gl_program* program = light_program; if (light_program == NULL) program = model_ptr->model_program; model_ptr->prep_for_draw(transform->to_matrix(), V, P, C, program, light_source); if (model_ptr->has_joints) { root_joint->update(animation_progress, current_animation); float joint_matricies[model_ptr->get_num_joints()*16]; root_joint->populate_float_array(joint_matricies); glUniformMatrix4fv(program->uniform_locations["joints"], model_ptr->get_num_joints(), GL_FALSE, &(joint_matricies[0])); CHECK_GL_ERROR("filling joint matricies"); } model_ptr->draw(); if (model_ptr->has_joints) draw_joints(V, P, C); } void unit::draw_joints(const glm::mat4 & V, const glm::mat4 & P, camera* C) { list<joint*> to_draw; to_draw.push_back(root_joint); while (!to_draw.empty()) { joint* current = to_draw.front(); to_draw.pop_front(); for (const pair<string, joint*> & child : current->joints) to_draw.push_back(child.second); if (current == root_joint) continue; // draw_sphere_single_frame(transform->to_matrix() * current->world * glm::scale(glm::mat4(1.0f), glm::vec3(25.0f)), V, P, C, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); //if (current->name == "joint1") //draw_sphere_single_frame(transform->to_matrix() * current->world, V, P, C, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); } } void unit::set_scale(float new_scale) { transform->scale(new_scale); } void unit::update(int milliseconds) { if (current_animation != NULL) { animation_progress += milliseconds; while (animation_progress > 1000) animation_progress -= 1000; } } float unit::get_distance_to(unit* other) { glm::vec3 difference = transform->get_t() - other->transform->get_t(); glm::vec3 square = difference * difference; float sum = square.x + square.y + square.z; return sqrt(sum); } float unit::get_distance_to(const glm::vec3 & other) { glm::vec3 difference = -other + transform->get_t(); glm::vec3 square = difference * difference; float sum = square.x + square.y + square.z; return sqrt(sum); } void unit::set_model(model* _model_ptr) { if (model_ptr != NULL) delete model_ptr; model_ptr = _model_ptr; if (root_joint != NULL) delete root_joint; root_joint = duplicate_joint_tree(model_ptr->root_joint); } bool unit::set_animation(const string & animation_name) { if (model_ptr == NULL) return false; auto it = model_ptr->animations.find(animation_name); if (it == model_ptr->animations.end()) return false; current_animation = it->second; return true; } void unit::set_rigidbody(const string & type) { if (type == "SPHERE") rigid_body = new rigidbody(transform, this, SPHERE_TENSOR, type); else if (type == "BOX") rigid_body = new rigidbody(transform, this, SPHERE_TENSOR, type); } void unit::add_location(const glm::vec3 & diff) { transform->translateXYZ(diff); //transform->t += diff; } }
31.513089
173
0.604752
[ "model", "transform" ]
968804c0a17c6030a94764d9bf7416e4f034df90
12,548
cpp
C++
source/utopian/vulkan/handles/Device.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
62
2020-11-06T17:29:24.000Z
2022-03-21T19:21:16.000Z
source/utopian/vulkan/handles/Device.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
134
2017-02-25T20:47:43.000Z
2022-03-14T06:54:58.000Z
source/utopian/vulkan/handles/Device.cpp
simplerr/Papageno
7ec1da40dc0459e26f5b9a8a3f72d8962237040d
[ "MIT" ]
6
2021-02-19T07:20:19.000Z
2021-12-27T09:07:27.000Z
#include <stdexcept> #include <array> #include "vulkan/handles/Device.h" #include "vulkan/handles/Instance.h" #include "vulkan/handles/Queue.h" #include "vulkan/handles/CommandPool.h" #include "vulkan/handles/Buffer.h" #include "vulkan/handles/Image.h" #include "vulkan/handles/DescriptorSet.h" #include "vulkan/Debug.h" #include "core/Log.h" #include <fstream> #define VMA_IMPLEMENTATION #include "../external/vk_mem_alloc.h" namespace Utopian::Vk { Device::Device(Instance* instance, bool enableValidation) { mEnabledFeatures.geometryShader = VK_TRUE; mEnabledFeatures.shaderTessellationAndGeometryPointSize = VK_TRUE; mEnabledFeatures.fillModeNonSolid = VK_TRUE; mEnabledFeatures.samplerAnisotropy = VK_TRUE; mEnabledFeatures.tessellationShader = VK_TRUE; mEnabledFeatures.pipelineStatisticsQuery = VK_TRUE; mEnabledFeatures.occlusionQueryPrecise = VK_TRUE; mEnabledFeatures.independentBlend = VK_TRUE; mEnabledFeatures.fragmentStoresAndAtomics = VK_TRUE; mEnabledFeatures.vertexPipelineStoresAndAtomics = VK_TRUE; RetrievePhysical(instance); RetrieveSupportedExtensions(); RetrieveQueueFamilyProperites(); vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mAvailableFeatures); vkGetPhysicalDeviceMemoryProperties(mPhysicalDevice, &mDeviceMemoryProperties); CreateLogical(enableValidation); VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = mPhysicalDevice; allocatorInfo.device = mDevice; allocatorInfo.instance = instance->GetVkHandle(); vmaCreateAllocator(&allocatorInfo, &mAllocator); uint32_t queueFamilyIndex = GetQueueFamilyIndex(VK_QUEUE_GRAPHICS_BIT); mCommandPool = new CommandPool(this, queueFamilyIndex); mQueue = new Queue(this); } Device::~Device() { delete mCommandPool; delete mQueue; GarbageCollect(); vmaDestroyAllocator(mAllocator); vkDestroyDevice(mDevice, nullptr); } void Device::RetrievePhysical(Instance* instance) { // Query for the number of GPUs uint32_t gpuCount = 0; VkResult result = vkEnumeratePhysicalDevices(instance->GetVkHandle(), &gpuCount, NULL); if (result != VK_SUCCESS) UTO_LOG("vkEnumeratePhysicalDevices failed"); if (gpuCount < 1) UTO_LOG("vkEnumeratePhysicalDevices didn't find any valid devices for Vulkan"); // Enumerate devices std::vector<VkPhysicalDevice> physicalDevices(gpuCount); result = vkEnumeratePhysicalDevices(instance->GetVkHandle(), &gpuCount, physicalDevices.data()); // Assume that there only is 1 GPU mPhysicalDevice = physicalDevices[0]; vkGetPhysicalDeviceProperties(mPhysicalDevice, &mPhysicalDeviceProperties); mVulkanVersion = VulkanVersion(mPhysicalDeviceProperties.apiVersion); UTO_LOG("Retrieved physical device supporting Vulkan " + mVulkanVersion.version); } void Device::RetrieveQueueFamilyProperites() { // Queue family properties, used for setting up requested queues upon device creation uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueFamilyCount, nullptr); assert(queueFamilyCount > 0); mQueueFamilyProperties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueFamilyCount, mQueueFamilyProperties.data()); } uint32_t Device::GetQueueFamilyIndex(VkQueueFlagBits queueFlags) const { for (uint32_t i = 0; i < static_cast<uint32_t>(mQueueFamilyProperties.size()); i++) { if (mQueueFamilyProperties[i].queueFlags & queueFlags) { return i; } } // No queue was found assert(0); return 0; } void Device::CreateLogical(bool enableValidation) { // Some implementations use vkGetPhysicalDeviceQueueFamilyProperties and uses the result to find out // the first queue that support graphic operations (queueFlags & VK_QUEUE_GRAPHICS_BIT) // Here I simply set queueInfo.queueFamilyIndex = 0 and (hope) it works // In Sascha Willems examples he has a compute queue with queueFamilyIndex = 1 std::array<float, 1> queuePriorities = { 1.0f }; VkDeviceQueueCreateInfo queueInfo = {}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.pNext = nullptr; queueInfo.flags = 0; queueInfo.queueFamilyIndex = GetQueueFamilyIndex(VK_QUEUE_GRAPHICS_BIT); queueInfo.pQueuePriorities = queuePriorities.data(); queueInfo.queueCount = 1; // VK_KHR_SWAPCHAIN_EXTENSION_NAME always needs to be used std::vector<const char*> enabledExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; if (IsExtensionSupported(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { enabledExtensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); } VkDeviceCreateInfo deviceInfo = {}; deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceInfo.pNext = nullptr; deviceInfo.flags = 0; deviceInfo.queueCreateInfoCount = 1; deviceInfo.pQueueCreateInfos = &queueInfo; deviceInfo.pEnabledFeatures = &mEnabledFeatures; deviceInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size(); deviceInfo.ppEnabledExtensionNames = enabledExtensions.data(); if (enableValidation) { deviceInfo.enabledLayerCount = (uint32_t)Debug::validation_layers.size(); deviceInfo.ppEnabledLayerNames = Debug::validation_layers.data(); } Debug::ErrorCheck(vkCreateDevice(mPhysicalDevice, &deviceInfo, nullptr, &mDevice)); } void Device::RetrieveSupportedExtensions() { uint32_t extCount = 0; vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extCount, nullptr); if (extCount > 0) { std::vector<VkExtensionProperties> extensions(extCount); if (vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extCount, &extensions.front()) == VK_SUCCESS) { for (const auto& ext : extensions) { mSupportedExtensions.push_back(ext.extensionName); } } } } bool Device::IsExtensionSupported(std::string extension) { return (std::find(mSupportedExtensions.begin(), mSupportedExtensions.end(), extension) != mSupportedExtensions.end()); } bool Device::IsDebugMarkersEnabled() const { return mDebugMarkersEnabled; } VkPhysicalDevice Device::GetPhysicalDevice() const { return mPhysicalDevice; } VkDevice Device::GetVkDevice() const { return mDevice; } VkBool32 Device::GetMemoryType(uint32_t typeBits, VkFlags properties, uint32_t* typeIndex) const { for (uint32_t i = 0; i < 32; i++) { if ((typeBits & 1) == 1) { if ((mDeviceMemoryProperties.memoryTypes[i].propertyFlags & properties) == properties) { *typeIndex = i; return true; } } typeBits >>= 1; } return false; } const VkPhysicalDeviceMemoryProperties& Device::GetMemoryProperties() const { return mDeviceMemoryProperties; } const VkPhysicalDeviceProperties& Device::GetProperties() const { return mPhysicalDeviceProperties; } Queue* Device::GetQueue() const { return mQueue; } void Device::QueueDestroy(SharedPtr<Vk::Buffer>& buffer) { mBuffersToFree.push_back(buffer); buffer = nullptr; } void Device::QueueDestroy(VkPipeline pipeline) { mPipelinesToFree.push_back(pipeline); } void Device::QueueDestroy(SharedPtr<Vk::Image> image) { mImagesToFree.push_back(image); } void Device::QueueDestroy(SharedPtr<Vk::Sampler> sampler) { mSamplersToFree.push_back(sampler); } void Device::GarbageCollect() { if (mBuffersToFree.size() > 0) { mBuffersToFree.clear(); } if (mImagesToFree.size() > 0) { mImagesToFree.clear(); } if (mSamplersToFree.size() > 0) { mSamplersToFree.clear(); } for (auto& pipeline : mPipelinesToFree) vkDestroyPipeline(GetVkDevice(), pipeline, nullptr); if (mPipelinesToFree.size() > 0) mPipelinesToFree.clear(); } void Device::QueueDescriptorUpdate(Vk::DescriptorSet* descriptorSet) { mDescriptorSetUpdateQueue.push_back(descriptorSet); } void Device::UpdateDescriptorSets() { for (auto& descriptorSet : mDescriptorSetUpdateQueue) descriptorSet->UpdateDescriptorSets(); mDescriptorSetUpdateQueue.clear(); } VmaAllocation Device::AllocateMemory(Image* image, VkMemoryPropertyFlags flags) { VmaAllocationCreateInfo allocCI = {}; allocCI.requiredFlags = flags; allocCI.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT; std::string imageName = image->GetDebugName(); allocCI.pUserData = (void*)imageName.c_str(); VmaAllocationInfo allocInfo; VmaAllocation allocation; Debug::ErrorCheck(vmaAllocateMemoryForImage(mAllocator, image->GetVkHandle(), &allocCI, &allocation, &allocInfo)); Debug::ErrorCheck(vkBindImageMemory(mDevice, image->GetVkHandle(), allocInfo.deviceMemory, allocInfo.offset)); return allocation; } VmaAllocation Device::AllocateMemory(Buffer* buffer, VkMemoryPropertyFlags flags) { VmaAllocationCreateInfo allocCI = {}; allocCI.requiredFlags = flags; allocCI.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT; std::string bufferName = buffer->GetDebugName(); allocCI.pUserData = (void*)bufferName.c_str(); VmaAllocationInfo allocInfo; VmaAllocation memory; Debug::ErrorCheck(vmaAllocateMemoryForBuffer(mAllocator, buffer->GetVkHandle(), &allocCI, &memory, &allocInfo)); Debug::ErrorCheck(vkBindBufferMemory(mDevice, buffer->GetVkHandle(), allocInfo.deviceMemory, allocInfo.offset)); return memory; } void Device::MapMemory(VmaAllocation allocation, void** data) { Debug::ErrorCheck(vmaMapMemory(mAllocator, allocation, data)); } void Device::UnmapMemory(VmaAllocation allocation) { vmaUnmapMemory(mAllocator, allocation); } void Device::FreeMemory(VmaAllocation allocation) { vmaFreeMemory(mAllocator, allocation); } void Device::GetAllocationInfo(VmaAllocation allocation, VkDeviceMemory& memory, VkDeviceSize& offset) { VmaAllocationInfo allocInfo; vmaGetAllocationInfo(mAllocator, allocation, &allocInfo); memory = allocInfo.deviceMemory; offset = allocInfo.offset; } VmaBudget Device::GetMemoryBudget(VkMemoryHeapFlags heapFlags) { std::vector<VmaBudget> budget(mDeviceMemoryProperties.memoryHeapCount); vmaGetBudget(mAllocator, budget.data()); uint32_t deviceMemoryUsage = 0u; VmaBudget totalBudget = { 0u }; for (uint32_t i = 0; i < mDeviceMemoryProperties.memoryHeapCount; i++) { if ((mDeviceMemoryProperties.memoryHeaps[i].flags & heapFlags) != 0) { totalBudget.blockBytes += budget[i].blockBytes; totalBudget.allocationBytes += budget[i].allocationBytes; totalBudget.usage += budget[i].usage; totalBudget.budget += budget[i].budget; } deviceMemoryUsage += (uint32_t)budget[i].usage; } return totalBudget; } void Device::GetMemoryStats(VmaStats* stats) { vmaCalculateStats(mAllocator, stats); } void Device::DumpMemoryStats(std::string filename) { char* statsPtr; vmaBuildStatsString(mAllocator, &statsPtr, true); std::string statsString = statsPtr; std::ofstream fout(filename); fout << statsString; fout.close(); vmaFreeStatsString(mAllocator, statsPtr); } CommandPool* Device::GetCommandPool() const { return mCommandPool; } VulkanVersion Device::GetVulkanVersion() const { return mVulkanVersion; } VulkanVersion::VulkanVersion() { } VulkanVersion::VulkanVersion(uint32_t apiVersion) { major = VK_VERSION_MAJOR(apiVersion); minor = VK_VERSION_MINOR(apiVersion); patch = VK_VERSION_PATCH(apiVersion); version = std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); } }
30.754902
124
0.688476
[ "vector" ]
968832e4f74d1a902e6c04a336392400dbabc30f
956
cpp
C++
Arrays/merge-overlapping-intervals.cpp
atitoa93/interviewbit-solutions
9723c9cb767119bf5751e465548de4046b5a3d33
[ "MIT" ]
null
null
null
Arrays/merge-overlapping-intervals.cpp
atitoa93/interviewbit-solutions
9723c9cb767119bf5751e465548de4046b5a3d33
[ "MIT" ]
null
null
null
Arrays/merge-overlapping-intervals.cpp
atitoa93/interviewbit-solutions
9723c9cb767119bf5751e465548de4046b5a3d33
[ "MIT" ]
null
null
null
// https://www.interviewbit.com/problems/merge-overlapping-intervals/ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ void insertInterval(vector<Interval> &a, Interval v) { int x = a.size(); for (int i = a.size() - 1; i >= 0; --i) if (v.start <= a[i].end) x = i; int y = -1; for (int i = 0; i < a.size(); ++i) if (v.end >= a[i].start) y = i; if (x == a.size()) a.insert(a.end(), v); else if (y == -1) a.insert(a.begin(), v); else { Interval start = a[x], end = a[y]; a.erase(a.begin() + x, a.begin() + y + 1); a.insert(a.begin() + x, Interval(min(v.start, start.start), max(v.end, end.end))); } } vector<Interval> Solution::merge(vector<Interval> &A) { vector <Interval> ret; for (int i = 0; i < A.size(); ++i) { insertInterval(ret, A[i]); } return ret; }
25.157895
86
0.534519
[ "vector" ]
968d2f6d7ed6539d37b903a509269f598621e182
1,422
hpp
C++
sparse/L2/include/hw/fp64/loadParXkernel.hpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
4
2021-08-16T18:25:48.000Z
2022-03-22T08:49:43.000Z
L2/sparse/include/hw/fp64/loadParXkernel.hpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
null
null
null
L2/sparse/include/hw/fp64/loadParXkernel.hpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file loadColKernel.hpp * @brief loadColKernel definition. * * This file is part of Vitis SPARSE Library. */ #ifndef XF_SPARSE_LOADPARXKERNEL_HPP #define XF_SPARSE_LOADPARXKERNEL_HPP #include "kernel.hpp" /** * @brief loadParXkernel is used to read the input vector X and partition parameters out of device memory * @param p_parParamPtr device memory pointer for reading the partition parameters * @param p_xPtr device memory pointer for reading vector X * @param p_paramStr output axis stream of partition parameters * @param p_xStr output axis stream of X entries */ extern "C" void loadParXkernel(HBM_InfTyp* p_parParamPtr, HBM_InfTyp* p_xPtr, WideParamStrTyp& p_paramStr, HBM_StrTyp& p_outXstr); #endif
33.857143
105
0.708158
[ "vector" ]
9690e2742986cd9d1b125d116f21b5a6e9f1e4d0
4,983
cc
C++
src/basic_structure/search_tree.cc
FlyAlCode/RCLGeolocalization-2.0
2325fd11b23789630b6c12ecd0258c9dec84644a
[ "MIT" ]
4
2021-02-06T07:59:14.000Z
2022-02-22T10:58:27.000Z
src/basic_structure/search_tree.cc
FlyAlCode/RCLGeolocalization
7a2ead4bf9ee188a8ab7f07c1cdca9659ef0cc50
[ "MIT" ]
null
null
null
src/basic_structure/search_tree.cc
FlyAlCode/RCLGeolocalization
7a2ead4bf9ee188a8ab7f07c1cdca9659ef0cc50
[ "MIT" ]
1
2021-09-15T13:48:00.000Z
2021-09-15T13:48:00.000Z
#include "search_tree.h" namespace rcll{ /*********************************************************************** * Search Tree * ***********************************************************************/ void SearchTree::BuildTree(const PointCloud1D<double> &points ){ pts_1d_ = points; search_tree_1d_.reset(new SearchTree1D(1, pts_1d_, nanoflann::KDTreeSingleIndexAdaptorParams(20))); search_tree_1d_->buildIndex(); } void SearchTree::BuildTree(const PointCloud2D<double> &points ){ pts_2d_ = points; search_tree_2d_.reset(new SearchTree2D(2, pts_2d_, nanoflann::KDTreeSingleIndexAdaptorParams(20))); search_tree_2d_->buildIndex(); } void SearchTree::BuildTree(const PointCloud5D<double> &points ){ pts_5d_ = points; search_tree_5d_.reset(new SearchTree5D(5, pts_5d_, nanoflann::KDTreeSingleIndexAdaptorParams(20))); search_tree_5d_->buildIndex(); } void SearchTree::BuildTree(const PointCloud6D<double> &points ){ pts_6d_ = points; search_tree_6d_.reset(new SearchTree6D(6, pts_6d_, nanoflann::KDTreeSingleIndexAdaptorParams(20))); search_tree_6d_->buildIndex(); } void SearchTree::BuildTree(const PointCloud10D<double> &points ){ pts_10d_ = points; search_tree_10d_.reset(new SearchTree10D(10, pts_10d_, nanoflann::KDTreeSingleIndexAdaptorParams(20))); search_tree_10d_->buildIndex(); } void SearchTree::RadiusSearch( const PointCloud1D<double> &requry_pts, const double threshold_distance, std::vector<std::vector<std::pair<size_t,double> > > &ret_matches)const{ if(search_tree_1d_==nullptr) return; ret_matches.clear(); ret_matches.resize(requry_pts.kdtree_get_point_count()); nanoflann::SearchParams params; double query_pt; for(int i=0; i<requry_pts.kdtree_get_point_count(); ++i){ query_pt = requry_pts.kdtree_get_pt(i, 0); const size_t nMatches = search_tree_1d_->radiusSearch(&query_pt, threshold_distance, ret_matches[i], params); } } void SearchTree::RadiusSearch( const PointCloud2D<double> &requry_pts, const double threshold_distance, std::vector<std::vector<std::pair<size_t,double> > > &ret_matches)const{ if(search_tree_2d_==nullptr) return; ret_matches.clear(); ret_matches.resize(requry_pts.kdtree_get_point_count()); nanoflann::SearchParams params; double query_pt[2]; for(int i=0; i<requry_pts.kdtree_get_point_count(); ++i){ for(int j=0; j<2; ++j) query_pt[j] = requry_pts.kdtree_get_pt(i, j); const size_t nMatches = search_tree_2d_->radiusSearch(query_pt, threshold_distance, ret_matches[i], params); } } void SearchTree::RadiusSearch( const PointCloud5D<double> &requry_pts, const double threshold_distance, std::vector<std::vector<std::pair<size_t,double> > > &ret_matches)const{ if(search_tree_5d_==nullptr) return; ret_matches.clear(); ret_matches.resize(requry_pts.kdtree_get_point_count()); nanoflann::SearchParams params; double query_pt[5]; for(int i=0; i<requry_pts.kdtree_get_point_count(); ++i){ for(int j=0; j<5; ++j) query_pt[j] = requry_pts.kdtree_get_pt(i, j); const size_t nMatches = search_tree_5d_->radiusSearch(query_pt, threshold_distance, ret_matches[i], params); } } void SearchTree::RadiusSearch( const PointCloud6D<double> &requry_pts, const double threshold_distance, std::vector<std::vector<std::pair<size_t,double> > > &ret_matches)const{ if(search_tree_6d_==nullptr) return; ret_matches.clear(); ret_matches.resize(requry_pts.kdtree_get_point_count()); nanoflann::SearchParams params; double query_pt[6]; for(int i=0; i<requry_pts.kdtree_get_point_count(); ++i){ for(int j=0; j<6; ++j) query_pt[j] = requry_pts.kdtree_get_pt(i, j); const size_t nMatches = search_tree_6d_->radiusSearch(query_pt, threshold_distance, ret_matches[i], params); } } void SearchTree::RadiusSearch( const PointCloud10D<double> &requry_pts, const double threshold_distance, std::vector<std::vector<std::pair<size_t,double> > > &ret_matches)const{ if(search_tree_10d_==nullptr) return; ret_matches.clear(); ret_matches.resize(requry_pts.kdtree_get_point_count()); nanoflann::SearchParams params; double query_pt[10]; for(int i=0; i<requry_pts.kdtree_get_point_count(); ++i){ for(int j=0; j<10; ++j) query_pt[j] = requry_pts.kdtree_get_pt(i, j); const size_t nMatches = search_tree_10d_->radiusSearch(query_pt, threshold_distance, ret_matches[i], params); } } }
40.185484
117
0.639374
[ "vector" ]
969389447d21cbebb32b7ee70fc7dcf3c6222675
2,414
cpp
C++
exec/setup_hamiltonian.cpp
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
exec/setup_hamiltonian.cpp
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
exec/setup_hamiltonian.cpp
cheshyre/negele-srg-solver-cpp
9510a40665480508c28de784f9af2eb4c7e6c0ae
[ "MIT" ]
null
null
null
// Copyright 2020 Matthias Heinz #include <iostream> #include <vector> #include <boost/numeric/odeint.hpp> #include "negele/matrix.h" #include "negele/potential.h" #include "negele/quad.h" #include "negele/srg.h" int main(void) { auto quadrature = negele::quad::get_gauss_legendre_quadrature(100, 0.0, 25.0); auto pts = std::get<0>(quadrature); auto weights = std::get<1>(quadrature); int dim = pts.size(); double v1 = 12.0; double sig1 = 0.2; double v2 = -12.0; double sig2 = 0.8; negele::potential::NegelePotential pot(v1, v2, sig1, sig2); std::vector<double> pot_mels(dim * dim, 0.0); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { pot_mels[i * dim + j] = pot.eval(pts[j], pts[i]) + pot.eval(pts[j], -1 * pts[i]); } } // for (int i = 0; i < dim; i++) { // std::cout << pot_mels[i] << ", "; // } // std::cout << std::endl; // negele::matrix::SquareMatrix pot_matrix(dim, pot_mels); negele::matrix::MomentumSpaceMatrix pot_matrix(pts, weights, pot_mels); auto ham_matrix = pot_matrix.matrix_elements_with_weights() + pot_matrix.kinetic_energy(); auto evs = ham_matrix.eigenvalues(); for (int i = 0; i < 10; i++) { std::cout << evs[i] << std::endl; } // typedef boost::numeric::odeint::runge_kutta4< // negele::matrix::MomentumSpaceMatrix, double, // negele::matrix::MomentumSpaceMatrix, double, // boost::numeric::odeint::vector_space_algebra> // stepper_type; // stepper_type stepper; // const double dlambda = -0.01; // for (double lambda = 50.0; lambda >= 10.0; lambda += dlambda) { // stepper.do_step(negele::srg::rhs, pot_matrix, lambda, dlambda); // auto ham_matrix_new = // pot_matrix.matrix_elements_with_weights() + // pot_matrix.kinetic_energy(); // auto evs_new = ham_matrix_new.eigenvalues(); // std::cout << lambda << ", " << evs_new[0] << ", " << ham_matrix_new[30] // << std::endl; // } typedef boost::numeric::odeint::runge_kutta_dopri5< negele::matrix::MomentumSpaceMatrix, double, negele::matrix::MomentumSpaceMatrix, double, boost::numeric::odeint::vector_space_algebra> stepper; int steps = boost::numeric::odeint::integrate_adaptive( boost::numeric::odeint::make_controlled<stepper>(1E-6, 1E-6), negele::srg::rhs, pot_matrix, 50.0, 2.0, -0.1); return 0; }
29.802469
80
0.624689
[ "vector" ]
9694636ef301b5761e54291ba32b973a44f344c1
2,379
cpp
C++
1139/d.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1139/d.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1139/d.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int MOD = 1e9 + 7; const int MAXN = 1e5 + 5; int f[MAXN]; int phi[MAXN]; vector<int> divisors[MAXN]; void init(int n) { phi[0] = phi[1] = 0; for (int i = 1; i <= n; ++i) { if (i > 1) { phi[i] += (i - 1); } for (int j = i + i; j <= n; j += i) { divisors[j].push_back(i); phi[j] -= phi[i]; } } } int binpow(int x, int pow) { if (pow == 0) { return 1; } if (pow & 1) { return (x * 1ll * binpow(x, pow - 1)) % MOD; } else { int res = binpow(x, pow / 2); return (res * 1ll * res) % MOD; } } int div_mod(int a, int b) { return (a * 1ll * binpow(b, MOD - 2)) % MOD; } int mul_mod(int a, int b) { return (a * 1ll * b) % MOD; } int add_mod(int a, int b) { return (a + b) % MOD; } int cnt_ortagonal(int x, int m) { if (x == 1) { return m; } // cout << "cnt_ort " << x << " " << m << endl; int ans = m; vector<int> prime_factors; while (x != 1) { prime_factors.push_back(divisors[x].size() == 1 ? x : divisors[x][1]); while (!(x % prime_factors.back())) { x /= prime_factors.back(); } } for (int i = 1; i < (1 << prime_factors.size()); ++i) { int cur_div = 1; int parity = 0; for (int j = 0; j < prime_factors.size(); ++j) { if (i & (1 << j)) { parity ^= 1; cur_div *= prime_factors[j]; } } if (parity) { //cout << "- " << m / cur_div << endl; ans -= m / cur_div; } else { //cout << "+ " << m / cur_div << endl; ans += m / cur_div; } } // cout << "result: " << ans << endl; return ans; } int main() { int m; scanf("%d", &m); init(m); f[1] = 0; int invm = div_mod(1, m); for (int i = 2; i <= m; ++i) { //cout << "i = " << i << endl; int rhs = 0; for (auto &gcd: divisors[i]) { //cout << "gcd: " << gcd << ", cnt: " << cnt_ortagonal(i / gcd, m / gcd) << endl; rhs = add_mod(rhs, mul_mod(f[gcd], cnt_ortagonal(i / gcd, m / gcd))); } rhs = add_mod(1, mul_mod(rhs, invm)); f[i] = mul_mod(rhs, div_mod(1, MOD + 1 - mul_mod(m / i, invm))); //cout << "f(" << i << ") = " << f[i] << endl; } int ans = 1; for (int i = 1; i <= m; ++i) { ans = add_mod(ans, mul_mod(f[i], invm)); } cout << ans << "\n"; return 0; }
19.991597
87
0.467423
[ "vector" ]
f7b3d77fb41e4d86e790484aa997daad2852d520
1,478
cpp
C++
engine/common/util/src/cpp/string_util.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
1
2021-02-23T09:36:42.000Z
2021-02-23T09:36:42.000Z
engine/common/util/src/cpp/string_util.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
engine/common/util/src/cpp/string_util.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
#include <cstdlib> #include <sstream> #include "string_util.h" using namespace std; namespace ae { namespace util { /** */ bool startsWith(const string& str,const string& prefix) { if (prefix.length() > str.length()) { return false; } return prefix == str.substr(0,prefix.length()); } /** */ static void split(const string &str,char delim,vector<string> &items) { stringstream strStream(str); string item; while (getline(strStream,item,delim)) { items.push_back(item); } } /** */ vector<string> split(const string &str,char delim) { vector<string> items; split(str,delim,items); return items; } /** */ void ltrim(string &str,const string &characters) { size_t index = str.find_first_not_of(characters); str.erase(0,index); } /** */ bool isInt(const string &str) { unsigned int index = 0; // negative if (str.at(0) == '-') { index++; } // ciphers while (index < str.length()) { int ch = (int)str.at(index); if (ch < (int)'0' || ch > (int)'9') { return false; } index++; } return true; } /** */ bool parseInt(const std::string &str,int &value) { if (isInt(str) == false) { return false; } value = (int)strtol(str.c_str(),(char **)0,10); return true; } } // namespace } // namespace
19.706667
72
0.52977
[ "vector" ]
f7b45dc6a88fba7a0b65fe6de16274ec5428a206
347
hpp
C++
Exercicio-1_Contagem de Palavras/WordCounter.hpp
ViniciusCarvalhoDev/Algoritmos-e-Estrutura-de-Dados
157f2c3f30a156fdeb183df7bba783765673ddb0
[ "MIT" ]
1
2021-03-05T13:06:15.000Z
2021-03-05T13:06:15.000Z
Exercicio-1_Contagem de Palavras/WordCounter.hpp
ViniciusCarvalhoDev/Algoritmos-e-Estrutura-de-Dados
157f2c3f30a156fdeb183df7bba783765673ddb0
[ "MIT" ]
null
null
null
Exercicio-1_Contagem de Palavras/WordCounter.hpp
ViniciusCarvalhoDev/Algoritmos-e-Estrutura-de-Dados
157f2c3f30a156fdeb183df7bba783765673ddb0
[ "MIT" ]
null
null
null
#ifndef WORDCOUNT #define WORDCOUNT #include <map> #include <vector> #include <iostream> #include <string> #include "Word.hpp" using namespace std; class WordCounter { public: Word *words; int size = 0; WordCounter(int num_words); int countWord(string palavra); ~WordCounter(); void addWord(string w); void print(); }; #endif
12.851852
34
0.697406
[ "vector" ]
f7b4d9f7e6b7d7b427410c3fdbc3afe3c22ee14e
2,583
cpp
C++
src/menu/overlay.cpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
1
2022-01-16T07:06:13.000Z
2022-01-16T07:06:13.000Z
src/menu/overlay.cpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
src/menu/overlay.cpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
#include <spdlog/spdlog.h> #include <apostellein/konst.hpp> #include "./overlay.hpp" #include "./widget-detail.hpp" #include "./headsup.hpp" #include "./dialogue.hpp" #include "../ctrl/controller.hpp" #include "../hw/audio.hpp" #include "../hw/vfs.hpp" #include "../util/buttons.hpp" #include "../x2d/renderer.hpp" namespace { constexpr udx MAXIMUM_WIDGETS = 4; } void overlay::fix() { if (!widgets_.empty()) { auto font = vfs::find_font(0); for (auto&& wgt : widgets_) { wgt->fix(font); } } invalidated_ = true; } void overlay::handle(buttons& bts, controller& ctl, headsup& hud) { if (release_) { release_ = false; widgets_.clear(); } else if (!widgets_.empty()) { auto& wgt = *widgets_.back(); if (!wgt.ready()) { auto font = vfs::find_font(0); wgt.build(font, ctl, *this); hud.clear_title(); } wgt.handle(bts, ctl, *this, hud); if (release_) { release_ = false; widgets_.clear(); } else if (!wgt.active()) { widgets_.pop_back(); if (!widgets_.empty()) { auto& next = *widgets_.back(); next.invalidate(); } } } else if (!ctl.state().locked) { if (bts.pressed.options) { this->push(widget_type::option); } } } void overlay::render(renderer& rdr) const { if (!widgets_.empty()) { widgets_.back()->render(rdr); auto& list = rdr.query( priority_type::deferred, blending_type::alpha, pipeline_type::blank ); if (invalidated_) { invalidated_ = false; list.batch_blank( konst::WINDOW_DIMENSIONS<r32>(), chroma::TRANSLUCENT() ); } else { list.skip(display_list::QUAD); } } } void overlay::push(widget_type type) { invalidated_ = true; if (widgets_.size() >= MAXIMUM_WIDGETS) { spdlog::error("Too many widgets in the menu stack!"); return; } switch (type) { case widget_type::option: widgets_.emplace_back(std::make_unique<option_widget>()); break; case widget_type::input: widgets_.emplace_back(std::make_unique<input_widget>()); break; case widget_type::video: widgets_.emplace_back(std::make_unique<video_widget>()); break; case widget_type::audio: widgets_.emplace_back(std::make_unique<audio_widget>()); break; case widget_type::language: widgets_.emplace_back(std::make_unique<language_widget>()); break; case widget_type::record: widgets_.emplace_back(std::make_unique<profile_widget>(widget_type::record)); break; case widget_type::resume: widgets_.emplace_back(std::make_unique<profile_widget>(widget_type::resume)); break; default: spdlog::warn("Invalid widget type! This code should not run!"); break; } }
23.481818
79
0.670151
[ "render" ]
f7b5b175783511e9fa3f85317a24425963ba1472
601
cpp
C++
src/single_tests/memory_leaks/memory_leaks.cpp
Booritas/slideio
fdee97747cc73f087a5538aef6a0315ec75becca
[ "BSD-3-Clause" ]
6
2021-01-25T15:21:31.000Z
2022-03-07T09:23:37.000Z
src/single_tests/memory_leaks/memory_leaks.cpp
Booritas/slideio
fdee97747cc73f087a5538aef6a0315ec75becca
[ "BSD-3-Clause" ]
3
2020-12-30T16:21:42.000Z
2022-03-07T09:23:18.000Z
src/single_tests/memory_leaks/memory_leaks.cpp
Booritas/slideio
fdee97747cc73f087a5538aef6a0315ec75becca
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include "slideio/drivers/czi/cziimagedriver.hpp" using namespace slideio; int main() { CZIImageDriver driver; auto slide = driver.openFile("/src/images/czi/30-10-2020_NothingRecognized-15986.czi"); auto scene = slide->getScene(0); cv::Rect blockRect = { 0,0,1000,1000 }; cv::Range zSliceRange = { 0, 3 }; cv::Range timeFrameRange = { 0, 1 }; std::vector<int> channelIndices = { 0 }; cv::Mat mat; scene->read4DBlockChannels(blockRect, channelIndices, zSliceRange, timeFrameRange, mat); std::cout << "Done" << std::endl; return 0; }
31.631579
92
0.663894
[ "vector" ]
f7c435cb2d78d40980d9343750937fb84a74435e
1,240
cpp
C++
mppi/src/experts/expert.cpp
ethz-asl/mppi_mobile_manipulation
1ec4b792f05b9cab97f149d41ad97573a77fc749
[ "BSD-3-Clause" ]
3
2021-04-06T17:44:03.000Z
2021-11-05T13:22:56.000Z
mppi/src/experts/expert.cpp
ethz-asl/mppi_mobile_manipulation
1ec4b792f05b9cab97f149d41ad97573a77fc749
[ "BSD-3-Clause" ]
null
null
null
mppi/src/experts/expert.cpp
ethz-asl/mppi_mobile_manipulation
1ec4b792f05b9cab97f149d41ad97573a77fc749
[ "BSD-3-Clause" ]
3
2021-04-20T12:27:13.000Z
2021-07-23T02:38:25.000Z
/*! * @file expert.cpp * @author Etienne Walther * @date 08.12.2020 * @version 1.0 * @brief description */ #include "mppi/experts/expert.h" namespace mppi { Expert::Expert(config_t config, const dynamics_ptr& dynamics) { config_ = config; dynamics_ = dynamics; assert(config_.expert_types.size() == config_.expert_weights.size()); for (auto& expert_type : config_.expert_types) { switch (expert_type) { case 0: experts_[expert_type] = new NormExp('N', config_, dynamics_); case 1: experts_[expert_type] = new ImpExp('I', config_, dynamics_); } } } Eigen::VectorXd Expert::get_sample(size_t expert_type, size_t step) { return experts_[expert_type]->get_sample(step); } Eigen::MatrixXd Expert::get_sigma_inv(size_t expert_type, size_t step) { return experts_[expert_type]->get_sigma_inv(step); } void Expert::update_expert(size_t expert_type, const std::vector<Eigen::VectorXd>& mean) { switch (expert_type) { case 0: std::cout << "This expert can not be updated" << std::endl; assert(1 == 0); case 1: experts_[expert_type]->update_expert(mean); default: assert(0 == 1); } } } // namespace mppi
24.313725
72
0.647581
[ "vector" ]
f7c9b10a3a400cdf53ea3df43e86a65863f6b9d6
4,234
hpp
C++
src/objeto.hpp
lucasjoao/ine5420-cg
2965e9c31aec03fe245e987de8394f12d2433984
[ "MIT" ]
null
null
null
src/objeto.hpp
lucasjoao/ine5420-cg
2965e9c31aec03fe245e987de8394f12d2433984
[ "MIT" ]
null
null
null
src/objeto.hpp
lucasjoao/ine5420-cg
2965e9c31aec03fe245e987de8394f12d2433984
[ "MIT" ]
null
null
null
#ifndef OBJETO_HPP #define OBJETO_HPP #include <string> #include "coordenada.hpp" typedef std::vector<Coordenada> coordenadas_t; enum tipo_t { PONTO, RETA, POLIGONO, CURVA_BEZIER, CURVA_BSPLINE }; class Clipping; class Objeto { friend class Clipping; public: static size_t _id; public: Objeto(const std::string nome, tipo_t tipo); ~Objeto(); const std::string nome() const; tipo_t tipo() const; Coordenada coordenada(size_t posicao); Coordenada coordenada_scn(size_t posicao); Coordenada centro(); Coordenada centro_scn(); size_t tamanho(); size_t tamanho_scn(); void reset_scn(); void aplicar_tranformacao(const Transformacao &t); void aplicar_tranformacao_scn(const Transformacao &t); bool visivel(); bool operator==(const Objeto& obj) const; bool operator!=(const Objeto& obj) const; void set_preenchido(bool valor); bool preenchido(); protected: bool _visivel{true}; std::string _nome; tipo_t _tipo; std::vector<Coordenada> _coordenadas; std::vector<Coordenada> _coordenadas_scn; bool _preenchido; }; size_t Objeto::_id = 0; Objeto::Objeto(const std::string nome, tipo_t tipo) { if (nome.empty()) { _id++; auto apelido = std::to_string(_id) + "-"; switch (tipo) { case PONTO: apelido += "PONTO"; break; case RETA: apelido += "RETA"; break; case POLIGONO: apelido += "POLIGONO"; break; case CURVA_BEZIER: apelido += "CURVA_BEZIER"; break; case CURVA_BSPLINE: apelido += "CURVA_BSPLINE"; break; default: break; } _nome = apelido; } else { _nome = nome; } _tipo = tipo; _coordenadas = coordenadas_t(); _coordenadas_scn = coordenadas_t(); _preenchido = false; } Objeto::~Objeto() {} const std::string Objeto::nome() const { return _nome; } tipo_t Objeto::tipo() const { return _tipo; } Coordenada Objeto::coordenada(size_t posicao) { return _coordenadas.at(posicao); } Coordenada Objeto::coordenada_scn(size_t posicao) { return _coordenadas_scn.at(posicao); } Coordenada Objeto::centro() { double x = 0; double y = 0; size_t tamanho = this->tamanho(); for(size_t i = 0; i < tamanho; i++) { x += _coordenadas[i].valor(Coordenada::x); y += _coordenadas[i].valor(Coordenada::y); } x = x/tamanho; y = y/tamanho; return Coordenada(x,y); } Coordenada Objeto::centro_scn() { double x = 0; double y = 0; size_t tamanho = this->tamanho_scn(); for(size_t i = 0; i < tamanho; i++) { x += _coordenadas_scn[i].valor(Coordenada::x); y += _coordenadas_scn[i].valor(Coordenada::y); } x = x/tamanho; y = y/tamanho; return Coordenada(x,y); } size_t Objeto::tamanho() { return _coordenadas.size(); } size_t Objeto::tamanho_scn() { return _coordenadas_scn.size(); } void Objeto::aplicar_tranformacao_scn(const Transformacao &t) { for (size_t i = 0; i < tamanho(); i++) { Coordenada &c = _coordenadas_scn[i]; c *= t; } } void Objeto::reset_scn() { _coordenadas_scn.clear(); for (size_t i = 0; i < tamanho(); i++) { _coordenadas_scn.push_back( Coordenada(_coordenadas[i].valor(Coordenada::x), _coordenadas[i].valor(Coordenada::y)) ); } } void Objeto::aplicar_tranformacao(const Transformacao &t) { for (size_t i = 0; i < tamanho(); i++) { _coordenadas[i] *= t; } } bool Objeto::visivel() { return _visivel; } bool Objeto::operator==(const Objeto& obj) const { return (_nome.compare(obj._nome) == 0) && _tipo == obj._tipo; } bool Objeto::operator!=(const Objeto& obj) const { return !operator==(obj); } void Objeto::set_preenchido(bool valor) { _preenchido = valor; } bool Objeto::preenchido() { return _preenchido; } #endif
19.877934
98
0.579121
[ "vector" ]
f7cc1cf321db623e408538d8b56ad6e70ccf2e44
9,878
cpp
C++
doric-Qt/example/doric/plugin/DoricModalPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
116
2019-12-30T11:34:47.000Z
2022-03-31T05:32:58.000Z
doric-Qt/example/doric/plugin/DoricModalPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
9
2020-04-26T02:04:27.000Z
2022-01-26T07:31:01.000Z
doric-Qt/example/doric/plugin/DoricModalPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
18
2020-01-24T15:42:03.000Z
2021-12-28T08:17:36.000Z
#include "DoricModalPlugin.h" #include "engine/DoricPromise.h" #include "shader/DoricRootNode.h" #include "utils/DoricLayouts.h" #include <QJsonDocument> #include <QObject> #include <QQmlComponent> #include <QQuickWindow> #include <QTimer> void DoricModalPlugin::toast(QString jsValueString, QString callbackId) { getContext()->getDriver()->asyncCall( [this, jsValueString] { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QString msg = jsValue["msg"].toString(); int gravity = jsValue["gravity"].toInt(); QQmlComponent component(getContext()->getQmlEngine()); const QUrl url(QStringLiteral("qrc:/doric/qml/toast.qml")); component.loadUrl(url); if (component.isError()) { qCritical() << component.errorString(); } QQuickWindow *window = qobject_cast<QQuickWindow *>(component.create()); QQuickWindow *parentWindow = getContext()->getRootNode()->getRootView()->window(); window->contentItem() ->childItems() .at(0) ->childItems() .at(0) ->childItems() .at(0) ->setProperty("text", msg); std::function<void()> setX = [window, parentWindow]() { window->setProperty("x", (parentWindow->width() - window->width()) / 2.f + parentWindow->x()); }; std::function<void()> setY = [window, parentWindow, gravity]() { if ((gravity & DoricGravity::DoricGravityBottom) == DoricGravity::DoricGravityBottom) { window->setProperty("y", parentWindow->height() - window->height() - 20 + parentWindow->y()); } else if ((gravity & DoricGravity::DoricGravityTop) == DoricGravity::DoricGravityTop) { window->setProperty("y", 20 + parentWindow->y()); } else { window->setProperty( "y", (parentWindow->height() - window->height()) / 2 + parentWindow->y()); } }; // init set x setX(); // init set y setY(); // update x connect(window, &QQuickWindow::widthChanged, setX); // update y connect(window, &QQuickWindow::heightChanged, setY); QTimer::singleShot(2000, qApp, [window]() { window->deleteLater(); }); }, DoricThreadMode::UI); } void DoricModalPlugin::alert(QString jsValueString, QString callbackId) { getContext()->getDriver()->asyncCall( [this, jsValueString, callbackId] { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QJsonValue titleVal = jsValue["title"]; QJsonValue msgVal = jsValue["msg"]; QJsonValue okBtn = jsValue["okLabel"]; QQmlComponent component(getContext()->getQmlEngine()); const QUrl url(QStringLiteral("qrc:/doric/qml/alert.qml")); component.loadUrl(url); if (component.isError()) { qCritical() << component.errorString(); } QQuickWindow *window = qobject_cast<QQuickWindow *>(component.create()); window->setProperty("pointer", QString::number((qint64)window)); window->setProperty("plugin", QString::number((qint64)this)); window->setProperty("callbackId", callbackId); window->setProperty("title", titleVal.toString()); window->setProperty("msg", msgVal.toString()); if (okBtn.isString()) { window->setProperty("okLabel", okBtn.toString()); } else { window->setProperty("okLabel", "ok"); } QQuickWindow *parentWindow = getContext()->getRootNode()->getRootView()->window(); std::function<void()> setX = [window, parentWindow]() { window->setProperty("x", (parentWindow->width() - window->width()) / 2.f + parentWindow->x()); }; std::function<void()> setY = [window, parentWindow]() { window->setProperty("y", (parentWindow->height() - window->height()) / 2 + parentWindow->y()); }; // init set x setX(); // init set y setY(); // update x connect(window, &QQuickWindow::widthChanged, setX); // update y connect(window, &QQuickWindow::heightChanged, setY); }, DoricThreadMode::UI); } void DoricModalPlugin::confirm(QString jsValueString, QString callbackId) { getContext()->getDriver()->asyncCall( [this, jsValueString, callbackId] { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QJsonValue titleVal = jsValue["title"]; QJsonValue msgVal = jsValue["msg"]; QJsonValue okBtn = jsValue["okLabel"]; QJsonValue cancelBtn = jsValue["cancelLabel"]; QQmlComponent component(getContext()->getQmlEngine()); const QUrl url(QStringLiteral("qrc:/doric/qml/confirm.qml")); component.loadUrl(url); if (component.isError()) { qCritical() << component.errorString(); } QQuickWindow *window = qobject_cast<QQuickWindow *>(component.create()); window->setProperty("pointer", QString::number((qint64)window)); window->setProperty("plugin", QString::number((qint64)this)); window->setProperty("callbackId", callbackId); window->setProperty("title", titleVal.toString()); window->setProperty("msg", msgVal.toString()); window->setProperty("okLabel", okBtn.toString()); window->setProperty("cancelLabel", cancelBtn.toString()); QQuickWindow *parentWindow = getContext()->getRootNode()->getRootView()->window(); std::function<void()> setX = [window, parentWindow]() { window->setProperty("x", (parentWindow->width() - window->width()) / 2.f + parentWindow->x()); }; std::function<void()> setY = [window, parentWindow]() { window->setProperty("y", (parentWindow->height() - window->height()) / 2 + parentWindow->y()); }; // init set x setX(); // init set y setY(); // update x connect(window, &QQuickWindow::widthChanged, setX); // update y connect(window, &QQuickWindow::heightChanged, setY); }, DoricThreadMode::UI); } void DoricModalPlugin::prompt(QString jsValueString, QString callbackId) { getContext()->getDriver()->asyncCall( [this, jsValueString, callbackId] { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QJsonValue titleVal = jsValue["title"]; QJsonValue msgVal = jsValue["msg"]; QJsonValue okBtn = jsValue["okLabel"]; QJsonValue cancelBtn = jsValue["cancelLabel"]; QQmlComponent component(getContext()->getQmlEngine()); const QUrl url(QStringLiteral("qrc:/doric/qml/prompt.qml")); component.loadUrl(url); if (component.isError()) { qCritical() << component.errorString(); } QQuickWindow *window = qobject_cast<QQuickWindow *>(component.create()); window->setProperty("pointer", QString::number((qint64)window)); window->setProperty("plugin", QString::number((qint64)this)); window->setProperty("callbackId", callbackId); window->setProperty("title", titleVal.toString()); window->setProperty("msg", msgVal.toString()); if (okBtn.isString()) { window->setProperty("okLabel", okBtn.toString()); } else { window->setProperty("okLabel", "ok"); } if (cancelBtn.isString()) { window->setProperty("cancelLabel", cancelBtn.toString()); } else { window->setProperty("cancelLabel", "cancel"); } QQuickWindow *parentWindow = getContext()->getRootNode()->getRootView()->window(); std::function<void()> setX = [window, parentWindow]() { window->setProperty("x", (parentWindow->width() - window->width()) / 2.f + parentWindow->x()); }; std::function<void()> setY = [window, parentWindow]() { window->setProperty("y", (parentWindow->height() - window->height()) / 2 + parentWindow->y()); }; // init set x setX(); // init set y setY(); // update x connect(window, &QQuickWindow::widthChanged, setX); // update y connect(window, &QQuickWindow::heightChanged, setY); }, DoricThreadMode::UI); } void DoricModalPlugin::onAccepted(QString callbackId) { QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } void DoricModalPlugin::onAcceptedWithInput(QString callbackId, QString input) { QVariantList args; args.append(input); DoricPromise::resolve(getContext(), callbackId, args); } void DoricModalPlugin::onRejected(QString callbackId) { QVariantList args; DoricPromise::reject(getContext(), callbackId, args); } void DoricModalPlugin::onRejectedWithInput(QString callbackId, QString input) { QVariantList args; args.append(input); DoricPromise::reject(getContext(), callbackId, args); }
36.051095
80
0.57299
[ "object" ]
f7e5e9b4d84aca3efa6659fdda56a78150fac977
3,104
cpp
C++
src/netlib/ssl_tcp_client_socket.cpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
src/netlib/ssl_tcp_client_socket.cpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
src/netlib/ssl_tcp_client_socket.cpp
axilmar/netlib
ab1ad27bd8adaffbcb4c481b7972324202c8882e
[ "Apache-2.0" ]
null
null
null
#include "platform.hpp" #include <system_error> #include "ssl.hpp" #include "netlib/ssl_tcp_client_socket.hpp" #include "netlib/numeric_cast.hpp" #include "netlib/ssl_error.hpp" #include "netlib/message_size_t.hpp" #include "netlib/endianess.hpp" namespace netlib::ssl::tcp { //create the socket and the ssl static std::shared_ptr<SSL> create_ssl(const client_context& context, const std::optional<socket_address>& this_addr, const socket_address& server_addr, bool reuse_address_and_port) { //create the socket socket::handle_type sock = ::socket(server_addr.address_family(), SOCK_STREAM, IPPROTO_TCP); //failure to create the socket if (sock < 0) { throw std::system_error(get_last_error_number(), std::system_category()); } //set reuse if (reuse_address_and_port) { socket::set_reuse_address_and_port(sock); } //optionally bind the socket if (this_addr.has_value() && ::bind(sock, reinterpret_cast<const sockaddr*>(this_addr.value().data()), sizeof(sockaddr_storage))) { throw std::system_error(get_last_error_number(), std::system_category()); } //connect to the server; if error, throw exception if (::connect(sock, reinterpret_cast<const sockaddr*>(server_addr.data()), sizeof(sockaddr_storage))) { throw std::system_error(get_last_error_number(), std::system_category()); } //crreate the ssl std::shared_ptr<SSL> ssl{SSL_new(context.ctx().get()), SSL_close}; //connect the ssl and the socket SSL_set_fd(ssl.get(), numeric_cast<int>(sock)); //connect the SLL part if (SSL_connect(ssl.get()) != 1) { throw ssl::error(ERR_get_error()); } //ssl socket was successfully created return ssl; } //constructor client_socket::client_socket(const client_context& context, const std::optional<socket_address>& this_addr, const socket_address& server_addr, bool reuse_address_and_port) : ssl::socket(context.ctx(), create_ssl(context, this_addr, server_addr, reuse_address_and_port)) { } //Sends data to the server. bool client_socket::send(const std::vector<char>& data) { message_size_t size = numeric_cast<message_size_t>(data.size()); //send size set_endianess(size); if (!ssl_send(ssl().get(), reinterpret_cast<const char*>(&size), sizeof(size))) { return false; } //send data return ssl_send(ssl().get(), data.data(), numeric_cast<int>(data.size())); } //Receives data from the server. bool client_socket::receive(std::vector<char>& data) { message_size_t size; //receive size if (!ssl_receive(ssl().get(), reinterpret_cast<char*>(&size), sizeof(size))) { return false; } set_endianess(size); //receive data data.resize(size); return ssl_receive(ssl().get(), data.data(), numeric_cast<int>(size)); } } //namespace netlib::ssl::tcp
33.021277
187
0.642075
[ "vector" ]
f7f26187c52560d068502472eb0345f01bad1ea7
3,943
cpp
C++
src/modules/OpenCV/src/SampleSetWriter.cpp
AtsushiHashimoto/TableObjectManager
d1c15e41d2e4d737f3b1e15354ed561bd2a3e942
[ "BSD-3-Clause" ]
null
null
null
src/modules/OpenCV/src/SampleSetWriter.cpp
AtsushiHashimoto/TableObjectManager
d1c15e41d2e4d737f3b1e15354ed561bd2a3e942
[ "BSD-3-Clause" ]
null
null
null
src/modules/OpenCV/src/SampleSetWriter.cpp
AtsushiHashimoto/TableObjectManager
d1c15e41d2e4d737f3b1e15354ed561bd2a3e942
[ "BSD-3-Clause" ]
null
null
null
/*! * @file SampleSetWriter.cpp * @author a_hasimoto * @date Date Created: 2012/May/30 * @date Last Change: 2012/Jun/29. */ #include "SampleSetWriter.h" using namespace skl; /*! * @brief デフォルトコンストラクタ */ SampleSetWriter::SampleSetWriter(){ } /*! * @brief デストラクタ */ SampleSetWriter::~SampleSetWriter(){ } bool SampleSetWriter::write(const std::string& filename, const cv::Mat* samples, const cv::Mat* responces, const cv::Mat* likelihoods,const std::vector<skl::Time>* timestamps, const std::vector<cv::KeyPoint>* keypoints){ std::ofstream fout; fout.open(filename.c_str()); if(!fout) return false; bool isSuccess = write(fout,samples,responces,likelihoods,timestamps,keypoints); fout.close(); return isSuccess; } bool SampleSetWriter::_writeHeader(std::ostream& out, size_t sample_num, size_t sample_dim, bool has_responce, size_t class_num, bool has_timestamp,bool has_keypoint){ out << sample_num << "," << sample_dim << "," << has_responce << "," << class_num << "," << has_timestamp << "," << has_keypoint << std::endl; return true; } bool SampleSetWriter::write(std::ostream& out, const cv::Mat* samples, const cv::Mat* responces, const cv::Mat* likelihoods,const std::vector<skl::Time>* timestamps, const std::vector<cv::KeyPoint>* keypoints){ // each column corresponds to a sample in samples // each row corresponds to a feature dimension in samples // responces must be a matrix with cols==1, rows==sample_num // likelihood must be a matrix with cols==class_num, rows==sample_num size_t sample_num = samples->rows; size_t sample_dim = samples->cols; bool has_responce = (responces != NULL); size_t class_num = 0; if(likelihoods!=NULL){ class_num = likelihoods->cols; } bool has_timestamp = timestamps != NULL; if(timestamps->size()!=sample_num) return false; bool has_keypoint = keypoints != NULL; if(keypoints->size()!=sample_num) return false; // write header if(!_writeHeader(out,sample_num,sample_dim,has_responce,class_num,has_timestamp,has_keypoint)) return false; // write samples if(!_writeSamples(out,*samples)) return false; // write responce if(has_responce){ if(responces->rows!=(int)sample_num) return false; if(responces->cols!=1) return false; if(!_writeResponces(out,*responces)) return false; } // write likelihood if(class_num > 0){ if(likelihoods->rows!=(int)sample_num) return false; if(!_writeLikelihoods(out,*likelihoods)) return false; } // write timestamps if(has_timestamp){ if(!_writeTimeStamps(out,*timestamps)) return false; } // write keypoints if(has_keypoint){ if(!_writeKeyPoints(out,*keypoints)) return false; } return true; } bool SampleSetWriter::_writeTimeStamps(std::ostream& out,const std::vector<skl::Time>& timestamps){ for(size_t i=0;i<timestamps.size();i++){ if(i!=0) out << ","; out << timestamps[i]; } out << std::endl; return true; } bool SampleSetWriter::_writeKeyPoints(std::ostream& out, const std::vector<cv::KeyPoint>& keypoints){ for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].pt.x; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].pt.y; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].size; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].angle; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].response; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].octave; } out << std::endl; for(size_t i=0;i<keypoints.size();i++){ if(i!=0) out << ","; out << keypoints[i].class_id; } out << std::endl; return true; }
28.781022
221
0.654324
[ "vector" ]
f7f28d5cb2b4e665c48eba488cbdfcee0aa2d44a
8,307
cc
C++
src/afw/table/BaseTable.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/afw/table/BaseTable.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/afw/table/BaseTable.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
// -*- lsst-c++ -*- #include <memory> #include "boost/shared_ptr.hpp" // only for ndarray #include "lsst/afw/table/BaseColumnView.h" #include "lsst/afw/table/BaseRecord.h" #include "lsst/afw/table/BaseTable.h" #include "lsst/afw/table/Catalog.h" #include "lsst/afw/table/SchemaMapper.h" #include "lsst/afw/table/io/FitsWriter.h" #include "lsst/afw/table/detail/Access.h" namespace lsst { namespace afw { namespace table { // =============== Block ==================================================================================== // This is a block of memory that doles out record-sized chunks when a table asks for them. // It inherits from ndarray::Manager so we can return ndarrays that refer to the memory in the // block with correct reference counting (ndarray::Manager is just an empty base class with an // internal reference count - it's like a shared_ptr without the pointer and template parameter. // // Records are allocated in Blocks for two reasons: // - it allows tables to be either totally contiguous in memory (enabling column views) or // not (enabling dynamic addition of records) all in one class. // - it saves us from ever having to reallocate all the records associated with a table // when we run out of space (that's what a std::vector-like model would require). This keeps // records and/or iterators to them from being invalidated, and it keeps tables from having // to track all the records whose data it owns. namespace { class Block : public ndarray::Manager { public: typedef boost::intrusive_ptr<Block> Ptr; // If the last chunk allocated isn't needed after all (usually because of an exception in a constructor) // we reuse it immediately. If it wasn't the last chunk allocated, it can't be reclaimed until // the entire block goes out of scope. static void reclaim(std::size_t recordSize, void *data, ndarray::Manager::Ptr const &manager) { Ptr block = boost::static_pointer_cast<Block>(manager); if (reinterpret_cast<char *>(data) + recordSize == block->_next) { block->_next -= recordSize; } } // Ensure we have space for at least the given number of records as a contiguous block. // May not actually allocate anything if we already do. static void preallocate(std::size_t recordSize, std::size_t recordCount, ndarray::Manager::Ptr &manager) { Ptr block = boost::static_pointer_cast<Block>(manager); if (!block || static_cast<std::size_t>(block->_end - block->_next) < recordSize * recordCount) { block = Ptr(new Block(recordSize, recordCount)); manager = block; } } static std::size_t getBufferSize(std::size_t recordSize, ndarray::Manager::Ptr const &manager) { Ptr block = boost::static_pointer_cast<Block>(manager); return static_cast<std::size_t>(block->_end - block->_next) / recordSize; } // Get the next chunk from the block, making a new block and installing it into the table // if we're all out of space. static void *get(std::size_t recordSize, ndarray::Manager::Ptr &manager) { Ptr block = boost::static_pointer_cast<Block>(manager); if (!block || block->_next == block->_end) { block = Ptr(new Block(recordSize, BaseTable::nRecordsPerBlock)); manager = block; } void *r = block->_next; block->_next += recordSize; return r; } // Block is also keeper of the special number that says what alignment boundaries are needed for // schemas. Before we start using a schema, we need to first ensure it meets that requirement, // and pad it if not. static void padSchema(Schema &schema) { static int const MIN_RECORD_ALIGN = sizeof(AllocType); int remainder = schema.getRecordSize() % MIN_RECORD_ALIGN; if (remainder) { detail::Access::padSchema(schema, MIN_RECORD_ALIGN - remainder); } } private: struct AllocType { double element[2]; }; explicit Block(std::size_t recordSize, std::size_t recordCount) : _mem(new AllocType[(recordSize * recordCount) / sizeof(AllocType)]), _next(reinterpret_cast<char *>(_mem.get())), _end(_next + recordSize * recordCount) { assert((recordSize * recordCount) % sizeof(AllocType) == 0); std::fill(_next, _end, 0); // initialize to zero; we'll later initialize floats to NaN. } std::unique_ptr<AllocType[]> _mem; char *_next; char *_end; }; } // namespace // =============== BaseTable implementation (see header for docs) =========================================== void BaseTable::preallocate(std::size_t n) { Block::preallocate(_schema.getRecordSize(), n, _manager); } std::size_t BaseTable::getBufferSize() const { if (_manager) { return Block::getBufferSize(_schema.getRecordSize(), _manager); } else { return 0; } } std::shared_ptr<BaseTable> BaseTable::make(Schema const &schema) { return std::shared_ptr<BaseTable>(new BaseTable(schema)); } std::shared_ptr<BaseRecord> BaseTable::copyRecord(BaseRecord const &input) { std::shared_ptr<BaseRecord> output = makeRecord(); output->assign(input); return output; } std::shared_ptr<BaseRecord> BaseTable::copyRecord(BaseRecord const &input, SchemaMapper const &mapper) { std::shared_ptr<BaseRecord> output = makeRecord(); output->assign(input, mapper); return output; } std::shared_ptr<io::FitsWriter> BaseTable::makeFitsWriter(fits::Fits *fitsfile, int flags) const { return std::make_shared<io::FitsWriter>(fitsfile, flags); } std::shared_ptr<BaseTable> BaseTable::_clone() const { return std::shared_ptr<BaseTable>(new BaseTable(*this)); } std::shared_ptr<BaseRecord> BaseTable::_makeRecord() { return constructRecord<BaseRecord>(); } BaseTable::BaseTable(Schema const &schema) : _schema(schema) { Block::padSchema(_schema); _schema.disconnectAliases(); _schema.getAliasMap()->_table = this; } BaseTable::~BaseTable() { _schema.getAliasMap()->_table = 0; } namespace { // A Schema Functor used to set destroy variable-length array fields using an explicit call to their // destructor (necessary since we used placement new). All other fields are ignored, as they're POD. struct RecordDestroyer { template <typename T> void operator()(SchemaItem<T> const &item) const {} template <typename T> void operator()(SchemaItem<Array<T> > const &item) const { typedef ndarray::Array<T, 1, 1> Element; if (item.key.isVariableLength()) { (*reinterpret_cast<Element *>(data + item.key.getOffset())).~Element(); } } void operator()(SchemaItem<std::string> const &item) const { if (item.key.isVariableLength()) { using std::string; // invoking the destructor on a qualified name doesn't compile in gcc 4.8.1 // https://stackoverflow.com/q/24593942 (*reinterpret_cast<string *>(data + item.key.getOffset())).~string(); } } char *data; }; } // namespace detail::RecordData BaseTable::_makeNewRecordData() { auto data = Block::get(_schema.getRecordSize(), _manager); return detail::RecordData{ data, shared_from_this(), _manager // manager always points to the most recently-used block. }; } void BaseTable::_destroy(BaseRecord &record) { assert(record._table.get() == this); RecordDestroyer f = {reinterpret_cast<char *>(record._data)}; _schema.forEach(f); if (record._manager == _manager) Block::reclaim(_schema.getRecordSize(), record._data, _manager); } /* * JFB has no idea whether the default value below is sensible, or even whether * it should be expressed ultimately as an approximate size in bytes rather than a * number of records; the answer probably depends on both the typical size of * records and the typical number of records. */ int BaseTable::nRecordsPerBlock = 100; // =============== BaseCatalog instantiation ================================================================= template class CatalogT<BaseRecord>; template class CatalogT<BaseRecord const>; } // namespace table } // namespace afw } // namespace lsst
38.281106
110
0.660287
[ "vector", "model" ]
f7f351d9c62ad9901ba2042e55c51376dfebaae5
2,814
cpp
C++
src/blast.cpp
garethcmurphy/mph-mhd-fv
50a50ccd056016e235675d6f229789d33b31b7e2
[ "MIT" ]
9
2016-11-03T13:46:09.000Z
2021-02-26T10:39:56.000Z
src/blast.cpp
garethcmurphy/mph-mhd-fv
50a50ccd056016e235675d6f229789d33b31b7e2
[ "MIT" ]
1
2018-02-10T03:46:34.000Z
2018-02-10T03:46:34.000Z
src/blast.cpp
garethcmurphy/mph-mhd-fv
50a50ccd056016e235675d6f229789d33b31b7e2
[ "MIT" ]
5
2017-11-03T19:46:36.000Z
2019-12-14T07:12:14.000Z
#include "initialise_blast.h" int Blast::initial_condition(TNT::Array2D<unk> mesh, TNT::Array2D<double> faceBx, TNT::Array2D<double> faceBy, MPI_Comm new_comm, int ndims) { nx = mesh.dim1(); ny = mesh.dim2(); gammam1i = 1 / (PhysConsts::gamma - 1); pressure = 0; bx = 10; by = 10; sqr4piei = 0.5 / std::sqrt(PhysConsts::pi); myx = 0; myy = 0; rh = 1.0; vx = 0; vy = 0.0; vz = 0.0; myid = 99; xmax = 0; ymax = 0; bx = bx * sqr4piei; by = by * sqr4piei; MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Cart_coords(new_comm, myid, ndims, coords); MPI_Cartdim_get(new_comm, dims); MPI_Allreduce(coords, &xmax, 1, MPI_INT, MPI_MAX, new_comm); MPI_Allreduce(coords + 1, &ymax, 1, MPI_INT, MPI_MAX, new_comm); xmax++; ymax++; std::cout << "Proc" << myid << " " << xmax << " " << ymax << std::endl; int myaddress[] = {0, 0}; myaddress[0] = (nx - 2 * NGC) * coords[0]; myaddress[1] = (ny - 2 * NGC) * coords[1]; // Initialise face-centered B fields for (int ii = 0; ii < nx + 1; ii++) for (int jj = 0; jj < ny + 1; jj++) { faceBx[ii][jj] = bx; faceBy[ii][jj] = by; } for (int jj = 0; jj < ny; jj++) for (int ii = 0; ii < nx; ii++) { int gg = ii - NGC; int hh = jj - NGC; bx = 0.5 * (faceBx[ii][jj] + faceBx[ii + 1][jj]); by = 0.5 * (faceBy[ii][jj] + faceBy[ii][jj + 1]); pressure = 0.1; mesh[ii][jj]_MASS = 1.0; mesh[ii][jj]_MOMX = 0.0; mesh[ii][jj]_MOMY = 0.0; mesh[ii][jj]_MOMZ = 0.0; mesh[ii][jj]_ENER = pressure * gammam1i + 0.5 * (bx * bx + by * by); mesh[ii][jj]_B_X = bx; mesh[ii][jj]_B_Y = by; mesh[ii][jj]_B_Z = 0.0; mesh[ii][jj].temperature = myid; centre[0] = xmax * (nx - 2 * NGC) / 2 + 10; centre[1] = ymax * (ny - 2 * NGC) / 2 + 10; myx = (float) myaddress[0] + gg - centre[0]; myy = (float) myaddress[1] + hh - centre[1]; double dist = 0; dist = sqrt((myx * myx) + (myy * myy)); if (dist < 0.1 * nx) { mesh[ii][jj]_MASS = rh; mesh[ii][jj]_MOMX = vx; mesh[ii][jj]_MOMY = vy; mesh[ii][jj]_MOMZ = vz; mesh[ii][jj]_B_X = bx; mesh[ii][jj]_B_Y = by; mesh[ii][jj]_B_Z = 0.0; mesh[ii][jj]_ENER = 10.0 * gammam1i + 0.5 * rh * (vx * vx + vy * vy) + 0.5 * (bx * bx + by * by); } } return 0; };
26.8
97
0.434968
[ "mesh" ]
f7fdee243cb5cc0a0767c03ef7d4caed9da65441
1,988
cpp
C++
petanque/tests/sorted_vector.cpp
Liblor/arybo
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
[ "BSD-3-Clause" ]
223
2016-09-12T16:31:12.000Z
2022-03-14T08:32:04.000Z
petanque/tests/sorted_vector.cpp
Liblor/arybo
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
[ "BSD-3-Clause" ]
17
2016-11-02T15:20:15.000Z
2021-10-02T23:30:58.000Z
petanque/tests/sorted_vector.cpp
Liblor/arybo
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
[ "BSD-3-Clause" ]
33
2016-09-13T07:28:31.000Z
2022-01-18T07:06:42.000Z
#include <pa/sorted_vector.h> #include <iostream> #include <vector> typedef std::vector<int> vec_int; typedef pa::SortedVector<vec_int> svec_int; #define CHECK(b) _CHECK(__LINE__,b) #define _CHECK(L,b)\ if (!(b)) {\ std::cerr << "error line " << L << std::endl;\ ret = 1;\ } int main() { int ret = 0; { vec_int ref{{10,20,40,50}}; svec_int v0{true,ref}; svec_int v1{true,ref}; v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{10,20,40,50}}; svec_int v0; svec_int v1{true,ref}; v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{10,20,40,50}}; svec_int v0{true,ref}; svec_int v1; v0.insert(v1); CHECK(v0 == ref); } { vec_int ref; svec_int v0; svec_int v1; v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{1,10,20,40,45,50,55,56}}; svec_int v0(true,vec_int{10,20,40,50}); svec_int v1(true,vec_int{1,45,55,56}); v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{1,10,20,40,50}}; svec_int v0(true,vec_int{10,20,40,50}); svec_int v1(true,vec_int{1}); v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{10,20,40,50,55}}; svec_int v0(true,vec_int{10,20,40,50}); svec_int v1(true,vec_int{55}); v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{1,10,11,12,14,15,20,21,40,50}}; svec_int v0(true,vec_int{10,20,40,50}); svec_int v1(true,vec_int{1,11,12,14,15,20,21}); v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{1,2,4}}; svec_int v0(true,vec_int{1,2}); svec_int v1(true,vec_int{1,4}); v0.insert(v1); CHECK(v0 == ref); } { vec_int ref{{0,9,10,11,12,15,16}}; svec_int v0(true,vec_int{0,1,2,4,8,10,11,12}); svec_int v1(true,vec_int{1,2,4,8,9,15,16}); v0.insert(v1.begin(), v1.end(), [](svec_int& v, svec_int::const_iterator it) { return v.erase(it); }); CHECK(v0 == ref); } { svec_int v(true, vec_int{5,6}); v.insert(4); v.insert(3); v.insert(2); v.insert(1); v.insert(0); vec_int ref{{0,1,2,3,4,5,6}}; CHECK(v == ref); } return ret; }
17.75
104
0.595573
[ "vector" ]
f7fef3c41ee9e74612c4ef8eec0c097a2b2e2f80
3,185
cc
C++
internal/ceres/array_selector_test.cc
hitxiaomi/ceres-solver
c3129c3d4a4830d23a310bd78c240898c82b36e9
[ "Apache-2.0" ]
2,425
2015-01-23T00:02:03.000Z
2022-03-31T22:15:00.000Z
internal/ceres/array_selector_test.cc
hitxiaomi/ceres-solver
c3129c3d4a4830d23a310bd78c240898c82b36e9
[ "Apache-2.0" ]
624
2015-03-18T14:36:29.000Z
2022-03-31T16:06:14.000Z
internal/ceres/array_selector_test.cc
hitxiaomi/ceres-solver
c3129c3d4a4830d23a310bd78c240898c82b36e9
[ "Apache-2.0" ]
989
2015-01-14T14:50:27.000Z
2022-03-30T15:20:06.000Z
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2020 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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 Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: darius.rueckert@fau.de (Darius Rueckert) // #include "ceres/internal/array_selector.h" #include "gtest/gtest.h" namespace ceres { namespace internal { // This test only checks, if the correct array implementations are selected. The // test for FixedArray is in fixed_array_test.cc. Tests for std::array and // std::vector are not included in ceres. TEST(ArraySelector, FixedArray) { ArraySelector<int, DYNAMIC, 20> array1(10); static_assert( std::is_base_of<internal::FixedArray<int, 20>, decltype(array1)>::value, ""); EXPECT_EQ(array1.size(), 10); ArraySelector<int, DYNAMIC, 10> array2(20); static_assert( std::is_base_of<internal::FixedArray<int, 10>, decltype(array2)>::value, ""); EXPECT_EQ(array2.size(), 20); } TEST(ArraySelector, Array) { ArraySelector<int, 10, 20> array1(10); static_assert(std::is_base_of<std::array<int, 10>, decltype(array1)>::value, ""); EXPECT_EQ(array1.size(), 10); ArraySelector<int, 20, 20> array2(20); static_assert(std::is_base_of<std::array<int, 20>, decltype(array2)>::value, ""); EXPECT_EQ(array2.size(), 20); } TEST(ArraySelector, Vector) { ArraySelector<int, 20, 10> array1(20); static_assert(std::is_base_of<std::vector<int>, decltype(array1)>::value, ""); EXPECT_EQ(array1.size(), 20); ArraySelector<int, 1, 0> array2(1); static_assert(std::is_base_of<std::vector<int>, decltype(array2)>::value, ""); EXPECT_EQ(array2.size(), 1); } } // namespace internal } // namespace ceres
39.8125
80
0.726845
[ "vector" ]
7902abc4aa0f7ea5e0e3711a9d9f86c2f00f213c
205,226
cpp
C++
win/devkit/plug-ins/gpuCache/gpuCacheCmd.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
10
2018-03-30T16:09:02.000Z
2021-12-07T07:29:19.000Z
win/devkit/plug-ins/gpuCache/gpuCacheCmd.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
null
null
null
win/devkit/plug-ins/gpuCache/gpuCacheCmd.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
9
2018-06-02T09:18:49.000Z
2021-12-20T09:24:35.000Z
//- //**************************************************************************/ // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk // license agreement provided at the time of installation or download, // or which otherwise accompanies this software in either electronic // or hard copy form. //**************************************************************************/ //+ /////////////////////////////////////////////////////////////////////////////// // // gpuCache MEL command // // Creates one or more cache files on disk to store attribute data for // a span of frames. // //////////////////////////////////////////////////////////////////////////////// #include "gpuCacheCmd.h" #include "gpuCacheShapeNode.h" #include "gpuCacheStrings.h" #include "gpuCacheUtil.h" #include "gpuCacheConfig.h" #include "gpuCacheVBOProxy.h" #include "gpuCacheVramQuery.h" #include "gpuCacheMaterialBakers.h" #include "gpuCacheSubSceneOverride.h" #include "gpuCacheUnitBoundingBox.h" #include "CacheWriter.h" #include "CacheReader.h" #include "gpuCacheGeometry.h" #include <maya/MArgList.h> #include <maya/MAnimControl.h> #include <maya/MDagPathArray.h> #include <maya/MFnDagNode.h> #include <maya/MFnMesh.h> #include <maya/MFnMeshData.h> #include <maya/MFnNurbsSurface.h> #include <maya/MFnSet.h> #include <maya/MFnSubd.h> #include <maya/MGlobal.h> #include <maya/MPlugArray.h> #include <maya/MSyntax.h> #include <maya/MBoundingBox.h> #include <maya/MFileObject.h> #include <maya/MItDag.h> #include <maya/MVector.h> #include <maya/MFnTransform.h> #include <maya/MFnSingleIndexedComponent.h> #include <maya/MFnComponentListData.h> #include <maya/MFnLambertShader.h> #include <maya/MViewport2Renderer.h> #include <maya/MDagPath.h> #include <maya/MPointArray.h> #include <maya/MUintArray.h> #include <boost/foreach.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <boost/unordered_set.hpp> #include <cfloat> #include <limits> #include <list> #include <iomanip> #include <map> #include <sstream> #include <fstream> #define MStatError(status,msg) \ if ( MS::kSuccess != (status) ) { \ MPxCommand::displayError( \ (msg) + MString(":") + (status).errorString()); \ return (status); \ } #define MStatErrorNullObj(status,msg) \ if ( MS::kSuccess != (status) ) { \ MPxCommand::displayError( \ (msg) + MString(":") + (status).errorString()); \ return MObject::kNullObj; \ } #define MCheckReturn(expression) \ { \ MStatus status = (expression); \ if ( MS::kSuccess != (status) ) { \ return (status); \ } \ } #define MUpdateProgressAndCheckInterruption(progressBar) \ { \ (progressBar).stepProgress(); \ if ((progressBar).isCancelled()) { \ return MS::kFailure; \ } \ } \ namespace { using namespace GPUCache; //============================================================================== // LOCAL FUNCTIONS //============================================================================== // Create a cache writer object that will write to the specified file path. // If the directory does not exist, a new one will be created. // If the file already exists, the existing file will be deleted. (Overwrite) // Writing to a read-only file will return an error. // Args: // targetFile The target file path that the new writer will write files to. // compressLevel Hint the compress level: -1 (Store), 0~9 (Fastest~Best). // dataFormat Hint the file format: ogawa or hdf. boost::shared_ptr<CacheWriter> createWriter(const MFileObject& targetFile, const char compressLevel, const MString& dataFormat) { // Get the directory of the target file. MFileObject cacheDirectory; cacheDirectory.setRawFullName(targetFile.resolvedPath()); // Make sure the cache folder exists. if (!cacheDirectory.exists()) { // Create the cache folder. MString createFolderCmd; createFolderCmd.format("sysFile -md \"^1s\"", EncodeString(targetFile.resolvedPath())); MGlobal::executeCommand(createFolderCmd); } // Delete the existing file. // We have already confirmed that the file is going to be overwritten. if (MFileObject(targetFile).exists()) { // The file already exists! MString resolvedFullName = targetFile.resolvedFullName(); // Check if the file is writeable. bool writeable; { std::ofstream ofs(resolvedFullName.asChar()); writeable = ofs.is_open(); } // We can't overwrite a read-only file. if (!writeable) { MStatus stat; MString fmt = MStringResource::getString(kCouldNotSaveFileMsg, stat); MString msg; msg.format(fmt, resolvedFullName); MPxCommand::displayError(msg); return boost::shared_ptr<CacheWriter>(); } // We are going to overwrite the file. Delete it!! if (remove(resolvedFullName.asChar()) != 0) { MStatus stat; MString fmt = MStringResource::getString(kCouldNotSaveFileMsg, stat); MString msg; msg.format(fmt, resolvedFullName); MPxCommand::displayError(msg); return boost::shared_ptr<CacheWriter>(); } } // first parameter is the file to write // second parameter is gzip compress level, -1 or 0~9 // third parameter is data format, hdf or ogawa boost::shared_ptr<CacheWriter> cacheWriter = CacheWriter::create("Alembic", targetFile, compressLevel, dataFormat); if (!cacheWriter) { MStatus stat; MString msg = MStringResource::getString(kCreateCacheWriterErrorMsg, stat); MPxCommand::displayError(msg); return boost::shared_ptr<CacheWriter>(); } if (!cacheWriter->valid()) { // release the file handle cacheWriter.reset(); MString errorMsg; errorMsg.format("Couldn't open cache file: ^1s", targetFile.resolvedFullName()); MPxCommand::displayError(errorMsg); return boost::shared_ptr<CacheWriter>(); } return cacheWriter; } bool isPlugConnectedToTexture2d(const MPlug& plug) { MPlugArray connections; if (plug.connectedTo(connections, true, false)) { assert(connections.length() == 1); //return false immediately if connections is empty, in order to fix the crash MAYA-41542 if(connections.length() == 0) return false; MObject srcNode = connections[0].node(); return srcNode.hasFn(MFn::kTexture2d); } return false; } MColor getTexture2dDefaultColor(const MPlug& plug) { MPlugArray connections; if (plug.connectedTo(connections, true, false)) { assert(connections.length() == 1); //return immediately if connections is empty if(connections.length() == 0) return MColor(0.5, 0.5, 0.5); MFnDependencyNode srcNode(connections[0].node()); MPlug diffusePlugR = srcNode.findPlug("defaultColorR"); MPlug diffusePlugG = srcNode.findPlug("defaultColorG"); MPlug diffusePlugB = srcNode.findPlug("defaultColorB"); assert(!diffusePlugR.isNull()); assert(!diffusePlugG.isNull()); assert(!diffusePlugB.isNull()); MStatus statusR, statusG, statusB; float r = diffusePlugR.asFloat(MDGContext::fsNormal, &statusR); float g = diffusePlugG.asFloat(MDGContext::fsNormal, &statusG); float b = diffusePlugB.asFloat(MDGContext::fsNormal, &statusB); assert(statusR == MS::kSuccess); assert(statusG == MS::kSuccess); assert(statusB == MS::kSuccess); return MColor(r, g, b); } return MColor(0.5, 0.5, 0.5); } bool isPlugConnectedToTextureNode(const MPlug& plug) { MPlugArray connections; if (plug.connectedTo(connections, true, false)) { assert(connections.length() == 1); //return false immediately if connections is empty if(connections.length() == 0) return false; MObject srcNode = connections[0].node(); if (srcNode.hasFn(MFn::kTexture2d) || srcNode.hasFn(MFn::kTexture3d) || srcNode.hasFn(MFn::kTextureEnv) || srcNode.hasFn(MFn::kLayeredTexture) || srcNode.hasFn(MFn::kImageSource)) { return true; } } return false; } MStatus getShapeDiffuseColors(const std::vector<MDagPath>& paths, std::vector<MColor>& diffuseColors) { MStatus status; diffuseColors.resize(paths.size(), Config::kDefaultGrayColor); // Get the diffuse color for each instance for (size_t pathIndex = 0; pathIndex < paths.size(); pathIndex++) { MFnDagNode shape(paths[pathIndex], &status); assert(status == MS::kSuccess); MObject shadingGroup; MObject shaderObj; // Find the instObjGroups plug MPlug instObjectGroupsParent = shape.findPlug("instObjGroups"); assert(!instObjectGroupsParent.isNull()); MPlug instObjectGroups = instObjectGroupsParent.elementByLogicalIndex( paths[pathIndex].instanceNumber()); assert(!instObjectGroups.isNull()); // instObjGroups is connected, the whole shape is assigned a material if (instObjectGroups.isConnected()) { // instObjGroups[instanceNumber] -> shadingGroup MPlugArray dstPlugs; instObjectGroups.connectedTo(dstPlugs, false, true, &status); if (status && dstPlugs.length() > 0) { // Found shadingGroup assigned to the whole shape shadingGroup = dstPlugs[0].node(); } } // For per-component shader assignment, we use the first shading group. // Find the objectGroups plug MPlug objectGroupsParent = instObjectGroups.child(0); assert(!objectGroupsParent.isNull()); for (unsigned int parts = 0; parts < objectGroupsParent.numElements() && shadingGroup.isNull(); parts++) { MPlug objectGroups = objectGroupsParent[parts]; // objectGroups is connected, there is per-component material if (objectGroups.isConnected()) { // objectGroups[i] -> shadingGroup MPlugArray dstPlugs; objectGroups.connectedTo(dstPlugs, false, true, &status); if (status && dstPlugs.length() > 0) { // Found shadingGroup assigned to components shadingGroup = dstPlugs[0].node(); } } } // for each objectGroup plug if (!shadingGroup.isNull()) { // Found a shading group, find its surface shader MFnDependencyNode shadingEngine(shadingGroup, &status); assert(status == MS::kSuccess); // Find surfaceShader plug MPlug surfaceShaderPlug = shadingEngine.findPlug("surfaceShader"); assert(!surfaceShaderPlug.isNull()); // outColor -> surfaceShader if (surfaceShaderPlug.isConnected()) { MPlugArray srcPlugs; surfaceShaderPlug.connectedTo(srcPlugs, true, false, &status); if (status && srcPlugs.length() > 0) { // Found the material node shaderObj = srcPlugs[0].node(); } } } if (!shaderObj.isNull()) { MColor diffuseColor = Config::kDefaultGrayColor; MColor transparency = Config::kDefaultTransparency; // Found a material node, get its color if (shaderObj.hasFn(MFn::kLambert)) { MFnLambertShader lambert(shaderObj, &status); assert(status == MS::kSuccess); MPlug colorPlug = lambert.findPlug("color"); assert(!colorPlug.isNull()); MPlug diffusePlug = lambert.findPlug("diffuse"); assert(!diffusePlug.isNull()); MPlug transparencyPlug = lambert.findPlug("transparency"); assert(!transparencyPlug.isNull()); if (isPlugConnectedToTexture2d(colorPlug)) { diffuseColor = getTexture2dDefaultColor(colorPlug); } else if (!isPlugConnectedToTextureNode(colorPlug)) { diffuseColor = lambert.color(); } if (!isPlugConnectedToTextureNode(diffusePlug)) { diffuseColor *= lambert.diffuseCoeff(); } if (!isPlugConnectedToTextureNode(transparencyPlug)) { transparency = lambert.transparency(); } } // Transparency RGB Luminance as alpha diffuseColor.a = 1.0f - (transparency.r * 0.3f + transparency.g * 0.59f + transparency.b * 0.11f); diffuseColors[pathIndex] = diffuseColor; } } return MS::kSuccess; } MString getSceneName() { MString sceneName = MGlobal::executeCommandStringResult( "basenameEx(`file -q -sceneName`)"); if (sceneName.length() == 0) { sceneName = MGlobal::executeCommandStringResult("untitledFileName"); } return sceneName; } MString getSceneNameAsValidObjectName() { return MGlobal::executeCommandStringResult("formValidObjectName \"" + EncodeString(getSceneName()) + "\""); } size_t maxNumVerts(const ShapeData::Ptr& geom) { size_t maxNumVerts = 0; BOOST_FOREACH( const ShapeData::SampleMap::value_type& smv, geom->getSamples() ) { maxNumVerts = std::max(maxNumVerts, smv.second->numVerts()); } return maxNumVerts; } double toHumanUnits(MUint64 bytes, MString& units) { const MUint64 KB = 1024; const MUint64 MB = 1024 * KB; const MUint64 GB = 1024 * MB; const MUint64 TB = 1024 * GB; double value; if (bytes >= TB) { units = "TB"; value = double(bytes)/TB; } else if (bytes >= GB) { units = "GB"; value = double(bytes)/GB; } else if (bytes >= MB) { units = "MB"; value = double(bytes)/MB; } else if (bytes >= KB) { units = "KB"; value = double(bytes)/KB; } else { units = "bytes"; value = double(bytes); } return value; } //============================================================================== // CLASS Baker //============================================================================== class Baker { public: static boost::shared_ptr<Baker> create(const MObject& object, const std::vector<MDagPath>& paths); static bool isBakeable(const MObject& dagNode); Baker(const MObject& object, const std::vector<MDagPath>& paths) : fNode(object), fPaths(paths) {} virtual ~Baker() {} virtual MStatus sample(const MTime& time) = 0; virtual const SubNode::MPtr getNode(size_t instIndex) const = 0; virtual void setWriteMaterials() {} virtual void setUseBaseTessellation() {} protected: MFnDagNode fNode; std::vector<MDagPath> fPaths; }; //============================================================================== // CLASS ShapeBaker //============================================================================== // Base class for wrappers that encapsulate the logic necessary to // bake particular types of shapes (meshes, nurbs, subds, etc.). class ShapeBaker : public Baker { public: virtual ~ShapeBaker() {} void enableUVs() { fCacheMeshSampler->enableUVs(); } // The function is called to sample the geometry at the specified time virtual MStatus sample(const MTime& time) { // Sample the shape MCheckReturn( sampleTopologyAndAttributes() ); // Sample the diffuse color std::vector<MColor> diffuseColors; MCheckReturn( getShapeDiffuseColors(fPaths, diffuseColors) ); bool diffuseColorsAnimated = (fPrevDiffuseColors != diffuseColors); // add sample to geometry if (fCacheMeshSampler->isAnimated() || diffuseColorsAnimated) { for (size_t i = 0; i < fGeometryInstances.size(); i++) { fGeometryInstances[i]->addSample( fCacheMeshSampler->getSample( time.as(MTime::kSeconds), diffuseColors[i])); } } fPrevDiffuseColors.swap(diffuseColors); return MS::kSuccess; } // The function is called at the end of baking process to get the baked geometry virtual const SubNode::MPtr getNode(size_t instIndex) const { return SubNode::create( fNode.name(), fGeometryInstances[instIndex] ); } protected: ShapeBaker(const MObject& node, const std::vector<MDagPath>& paths) : Baker(node, paths), fCacheMeshSampler( // note: the UVs can always get enabled later by calling our method enableUVs() CacheMeshSampler::create(!Config::isIgnoringUVs())), fGeometryInstances(paths.size()) { // Create one geometry for each instance for (size_t i = 0; i < paths.size(); i++) { fGeometryInstances[i] = ShapeData::create(); } } virtual void setWriteMaterials() { // Create one geometry for each instance for (size_t i = 0; i < fPaths.size(); i++) { // Set material to the shape data. MString surfaceMaterial; InstanceMaterialLookup lookup(fPaths[i]); if (lookup.hasWholeObjectMaterial()) { // Whole object material assignment. MObject material = lookup.findWholeObjectSurfaceMaterial(); if (!material.isNull()) { MFnDependencyNode dgMaterial(material); surfaceMaterial = dgMaterial.name(); } } else if (lookup.hasComponentMaterials()) { // Per-component material assignment. std::vector<MObject> materials; lookup.findSurfaceMaterials(materials); // Use the first surface material // TODO: Support per-component material assignment. BOOST_FOREACH (const MObject& material, materials) { if (!material.isNull()) { MFnDependencyNode dgMaterial(material); surfaceMaterial = dgMaterial.name(); break; } } } if (surfaceMaterial.length() > 0) { fGeometryInstances[i]->setMaterial(surfaceMaterial); } } } virtual void setUseBaseTessellation() { fCacheMeshSampler->setUseBaseTessellation(); } virtual MStatus sampleTopologyAndAttributes() = 0; private: // Forbidden and not implemented. ShapeBaker(const ShapeBaker&); const ShapeBaker& operator=(const ShapeBaker&); protected: const boost::shared_ptr<CacheMeshSampler> fCacheMeshSampler; std::vector<MColor> fPrevDiffuseColors; std::vector<ShapeData::MPtr> fGeometryInstances; }; //============================================================================== // CLASS XformBaker //============================================================================== // Class for baking a transform MObject class XformBaker : public Baker { public: virtual ~XformBaker() {} XformBaker(const MObject& xformNode, const std::vector<MDagPath>& xformPaths) : Baker(xformNode, xformPaths), fCacheXformSamplers(CacheXformSampler::create(xformNode)), fXformInstances(xformPaths.size()) { for (size_t i = 0; i < fXformInstances.size(); i++) { fXformInstances[i] = XformData::create(); } } virtual MStatus sample(const MTime& currentTime) { fCacheXformSamplers->addSample(); if (fCacheXformSamplers->isAnimated()) { for (size_t i = 0; i < fXformInstances.size(); i++) { fXformInstances[i]->addSample( fCacheXformSamplers->getSample(currentTime.as(MTime::kSeconds))); } } return MS::kSuccess; } virtual const SubNode::MPtr getNode(size_t instIndex) const { return SubNode::create( fNode.name(), fXformInstances[instIndex] ); } private: boost::shared_ptr<CacheXformSampler> fCacheXformSamplers; std::vector<XformData::MPtr> fXformInstances; }; //============================================================================== // CLASS MeshDataBaker //============================================================================== // Base class for baking a mesh MObject class MeshDataBaker : public ShapeBaker { public: virtual ~MeshDataBaker() {} protected: virtual MStatus sampleTopologyAndAttributes() { MStatus status; MObject meshData = getMeshData(&status); MStatError(status, "getMeshData()"); bool shapeVisibility = ShapeVisibilityChecker(fNode.object()).isVisible(); // Snapshot the topology and vertex attributes. return fCacheMeshSampler->addSample(meshData, shapeVisibility) ? MS::kSuccess : MS::kFailure; } virtual MObject getMeshData(MStatus* status) = 0; MeshDataBaker(const MObject& shapeNode, const std::vector<MDagPath>& shapePaths) : ShapeBaker(shapeNode, shapePaths) {} private: // Forbidden and not implemented. MeshDataBaker(const MeshDataBaker&); const MeshDataBaker& operator=(const MeshDataBaker&); }; //============================================================================== // CLASS MeshBaker //============================================================================== class MeshBaker : public ShapeBaker { public: MeshBaker(const MObject& meshNode, const std::vector<MDagPath>& meshPaths) : ShapeBaker(meshNode, meshPaths), fMeshNode(meshNode) {} virtual ~MeshBaker() {} protected: virtual MStatus sampleTopologyAndAttributes() { return fCacheMeshSampler->addSampleFromMesh(fMeshNode) ? MS::kSuccess : MS::kFailure; } private: // Forbidden and not implemented. MeshBaker(const MeshBaker&); const MeshBaker& operator=(const MeshBaker&); MFnMesh fMeshNode; }; //============================================================================== // CLASS NurbsBaker //============================================================================== class NurbsBaker : public MeshDataBaker { public: NurbsBaker(const MObject& nurbsNode, const std::vector<MDagPath>& nurbsPaths) : MeshDataBaker(nurbsNode, nurbsPaths) { // Disable Viewport 2.0 updates while baking NURBS surfaces. MHWRender::MRenderer::disableChangeManagementUntilNextRefresh(); } protected: virtual MObject getMeshData(MStatus* status) { MObject mesh; MDGModifier modifier; MFnNurbsSurface nurbsNode(fNode.object()); MObject tessellator = modifier.createNode("nurbsTessellate"); MFnDependencyNode tessellatorNode(tessellator); modifier.connect(nurbsNode.findPlug("explicitTessellationAttributes"), tessellatorNode.findPlug("explicitTessellationAttributes")); modifier.connect(nurbsNode.findPlug("curvatureTolerance"), tessellatorNode.findPlug("curvatureTolerance")); modifier.connect(nurbsNode.findPlug("uDivisionsFactor"), tessellatorNode.findPlug("uDivisionsFactor")); modifier.connect(nurbsNode.findPlug("vDivisionsFactor"), tessellatorNode.findPlug("vDivisionsFactor")); modifier.connect(nurbsNode.findPlug("modeU"), tessellatorNode.findPlug("uType")); modifier.connect(nurbsNode.findPlug("modeV"), tessellatorNode.findPlug("vType")); modifier.connect(nurbsNode.findPlug("numberU"), tessellatorNode.findPlug("uNumber")); modifier.connect(nurbsNode.findPlug("numberV"), tessellatorNode.findPlug("vNumber")); modifier.connect(nurbsNode.findPlug("useChordHeight"), tessellatorNode.findPlug("useChordHeight")); modifier.connect(nurbsNode.findPlug("useChordHeightRatio"), tessellatorNode.findPlug("useChordHeightRatio")); modifier.connect(nurbsNode.findPlug("chordHeight"), tessellatorNode.findPlug("chordHeight")); modifier.connect(nurbsNode.findPlug("chordHeightRatio"), tessellatorNode.findPlug("chordHeightRatio")); modifier.connect(nurbsNode.findPlug("smoothEdge"), tessellatorNode.findPlug("smoothEdge")); modifier.connect(nurbsNode.findPlug("smoothEdgeRatio"), tessellatorNode.findPlug("smoothEdgeRatio")); modifier.connect(nurbsNode.findPlug("edgeSwap"), tessellatorNode.findPlug("edgeSwap")); modifier.connect(nurbsNode.findPlug("local"), tessellatorNode.findPlug("inputSurface")); // poly type - 0 means triangles modifier.newPlugValueInt(tessellatorNode.findPlug("polygonType"),0); // format - 2 means general fit modifier.newPlugValueInt(tessellatorNode.findPlug("format"),2); modifier.doIt(); tessellatorNode.findPlug("outputPolygon").getValue(mesh); modifier.undoIt(); return mesh; } }; //============================================================================== // CLASS SubdBaker //============================================================================== class SubdBaker : public MeshDataBaker { public: SubdBaker(const MObject& subdNode, const std::vector<MDagPath>& subdPaths) : MeshDataBaker(subdNode, subdPaths) {} protected: virtual MObject getMeshData(MStatus* status) { MFnSubd subdNode(fNode.object()); MFnMeshData meshData; meshData.create(status); if (!*status) return meshData.object(); int format = -1; int depth = -1; int sampleCount = -1; MPlug formatPlug = subdNode.findPlug("format"); MPlug depthPlug = subdNode.findPlug("depth"); MPlug sampleCountPlug = subdNode.findPlug("sampleCount"); formatPlug.getValue(format); depthPlug.getValue(depth); sampleCountPlug.getValue(sampleCount); subdNode.tesselate( format==0, depth, sampleCount, meshData.object(), status); return meshData.object(); } }; //============================================================================== // CLASS RecursiveBaker //============================================================================== // This class simply extracts the hierarchy from gpuCache node. class RecursiveBaker : public Baker { public: RecursiveBaker(const MObject& shapeNode, const std::vector<MDagPath>& shapePaths) : Baker(shapeNode, shapePaths) { // Find the user node MPxNode* userNode = fNode.userNode(); assert(userNode); ShapeNode* bakedNode = userNode ? dynamic_cast<ShapeNode*>(userNode) : NULL; assert(bakedNode); // Extract the baked geometry if (bakedNode) { GlobalReaderCache::theCache().waitForRead(bakedNode->getCacheFileEntry().get()); fSrcTopNode = bakedNode->getCachedGeometry(); if (fSrcTopNode) { fSampleReplicator.reset(new SampleReplicator); fSrcTopNode->accept(*fSampleReplicator); } } } virtual ~RecursiveBaker() {} virtual MStatus sample(const MTime& time) { if (!fSrcTopNode) { return MS::kFailure; } return fSampleReplicator->sample(time); } virtual const SubNode::MPtr getNode(size_t instIndex) const { // We ignore the material assigned to the gpuCache node. if (fSrcTopNode && !fDstTopNode) { // We replicate the hierarchy after all xform/shape data are // filled with samples. HierarchyReplicator hierarchyReplicator(fSampleReplicator); fSrcTopNode->accept(hierarchyReplicator); RecursiveBaker* nonConstThis = const_cast<RecursiveBaker*>(this); nonConstThis->fDstTopNode = hierarchyReplicator.dstSubNode(); } return fDstTopNode; } private: // Forbidden and not implemented. RecursiveBaker(const RecursiveBaker&); const RecursiveBaker& operator=(const RecursiveBaker&); class SampleReplicator : public SubNodeVisitor { public: typedef boost::shared_ptr<SampleReplicator> MPtr; SampleReplicator() {} virtual void visit(const XformData& srcXform, const SubNode& srcSubNode) { // Create a new xform data, it will be filled later in sample() XformData::MPtr dstXform = XformData::create(); fXforms[&srcXform] = std::make_pair( dstXform, boost::shared_ptr<const XformSample>()); // Recursively replicate xform/shape data in the child hierarchy BOOST_FOREACH(const SubNode::Ptr& srcChild, srcSubNode.getChildren()) { srcChild->accept(*this); } } virtual void visit(const ShapeData& srcShape, const SubNode& srcSubNode) { // Create a new shape data, it will be filled later in sample() ShapeData::MPtr dstShape = ShapeData::create(); dstShape->setMaterials(srcShape.getMaterials()); fShapes[&srcShape] = std::make_pair( dstShape, boost::shared_ptr<const ShapeSample>()); } MStatus sample(const MTime& time) { BOOST_FOREACH(XformMapping::value_type& xform, fXforms) { // Get the already baked sample boost::shared_ptr<const XformSample> srcXformSample = xform.first->getSample(time); // Only add the sample if it's different than prev sample if (xform.second.second != srcXformSample) { // Create a new sample with the same content but different time boost::shared_ptr<XformSample> dstXformSample = XformSample::create( time.as(MTime::kSeconds), srcXformSample->xform(), srcXformSample->boundingBox(), srcXformSample->visibility()); xform.second.first->addSample(dstXformSample); xform.second.second = srcXformSample; } } BOOST_FOREACH(ShapeMapping::value_type& shape, fShapes) { // Get the already baked sample boost::shared_ptr<const ShapeSample> srcShapeSample = shape.first->getSample(time); // Only add the sample if it's different than prev sample if (shape.second.second != srcShapeSample) { // Create a new sample with the same content but different time boost::shared_ptr<ShapeSample> dstShapeSample = ShapeSample::create( time.as(MTime::kSeconds), srcShapeSample->numWires(), srcShapeSample->numVerts(), srcShapeSample->wireVertIndices(), srcShapeSample->triangleVertexIndexGroups(), srcShapeSample->positions(), srcShapeSample->boundingBox(), srcShapeSample->diffuseColor(), srcShapeSample->visibility()); if (srcShapeSample->normals()) { dstShapeSample->setNormals(srcShapeSample->normals()); } if (srcShapeSample->uvs()) { dstShapeSample->setUVs(srcShapeSample->uvs()); } shape.second.first->addSample(dstShapeSample); shape.second.second = srcShapeSample; } } return MS::kSuccess; } XformData::MPtr xform(const XformData& xform) { XformMapping::iterator iter = fXforms.find(&xform); assert(iter != fXforms.end()); return (*iter).second.first; } ShapeData::MPtr shape(const ShapeData& shape) { ShapeMapping::iterator iter = fShapes.find(&shape); assert(iter != fShapes.end()); return (*iter).second.first; } private: // Forbidden and not implemented. SampleReplicator(const SampleReplicator&); const SampleReplicator& operator=(const SampleReplicator&); typedef std::pair<XformData::MPtr,boost::shared_ptr<const XformSample> > XformWithPrev; typedef std::pair<ShapeData::MPtr,boost::shared_ptr<const ShapeSample> > ShapeWithPrev; typedef std::map<const XformData*,XformWithPrev> XformMapping; typedef std::map<const ShapeData*,ShapeWithPrev> ShapeMapping; XformMapping fXforms; ShapeMapping fShapes; }; class HierarchyReplicator : public SubNodeVisitor { public: HierarchyReplicator(SampleReplicator::MPtr sampleReplicator) : fSampleReplicator(sampleReplicator) {} virtual void visit(const XformData& srcXform, const SubNode& srcSubNode) { // Create a new sub node for the xform // We rename "|" to "top" as we don't want "|" to appear in hierarchy. XformData::MPtr dstXform = fSampleReplicator->xform(srcXform); fDstSubNode = SubNode::create(srcSubNode.getName() != "|" ? srcSubNode.getName() : "top", dstXform); // Recursively replicate the child hierarchy BOOST_FOREACH(const SubNode::Ptr& srcChild, srcSubNode.getChildren()) { HierarchyReplicator replicator(fSampleReplicator); srcChild->accept(replicator); SubNode::connect(fDstSubNode, replicator.dstSubNode()); } } virtual void visit(const ShapeData& srcShape, const SubNode& srcSubNode) { // Create a new sub node for the shape ShapeData::MPtr dstShape = fSampleReplicator->shape(srcShape); fDstSubNode = SubNode::create(srcSubNode.getName(), dstShape); } SubNode::MPtr dstSubNode() const { return fDstSubNode; } private: // Forbidden and not implemented. HierarchyReplicator(const HierarchyReplicator&); const HierarchyReplicator& operator=(const HierarchyReplicator&); SampleReplicator::MPtr fSampleReplicator; SubNode::MPtr fDstSubNode; }; SubNode::Ptr fSrcTopNode; SubNode::MPtr fDstTopNode; SampleReplicator::MPtr fSampleReplicator; }; //============================================================================== // CLASS Baker //============================================================================== bool Baker::isBakeable(const MObject& dagNode) { if (dagNode.hasFn(MFn::kTransform) || dagNode.hasFn(MFn::kMesh) || dagNode.hasFn(MFn::kNurbsSurface) || dagNode.hasFn(MFn::kSubdiv)) { return true; } return false; } boost::shared_ptr<Baker> Baker::create(const MObject& shapeNode, const std::vector<MDagPath>& shapePaths) { if (shapeNode.hasFn(MFn::kTransform)) { return boost::make_shared<XformBaker>(shapeNode, shapePaths); } else if (shapeNode.hasFn(MFn::kMesh)) { return boost::make_shared<MeshBaker>(shapeNode, shapePaths); } else if (shapeNode.hasFn(MFn::kNurbsSurface)) { return boost::make_shared<NurbsBaker>(shapeNode, shapePaths); } else if (shapeNode.hasFn(MFn::kSubdiv)) { return boost::make_shared<SubdBaker>(shapeNode, shapePaths); } MStatus status; MFnDagNode shape(shapeNode, &status); assert(status == MS::kSuccess); if (shape.typeId() == ShapeNode::id) { return boost::make_shared<RecursiveBaker>(shapeNode, shapePaths); } assert(false); return boost::shared_ptr<Baker>(); } //============================================================================== // CLASS Writer //============================================================================== class Writer : boost::noncopyable { public: Writer(const char compressLevel, const MString& dataFormat, const MTime& timePerCycle, const MTime& startTime) : fCompressLevel(compressLevel), fDataFormat(dataFormat), fTimePerCycleInSeconds(timePerCycle.as(MTime::kSeconds)), fStartTimeInSeconds(startTime.as(MTime::kSeconds)) {} // Write a sub-node hierarchy to the specified file. MStatus writeNode(const SubNode::Ptr& subNode, const MaterialGraphMap::Ptr& materials, const MFileObject& targetFile) { boost::shared_ptr<CacheWriter> writer = createWriter( targetFile, fCompressLevel, fDataFormat ); if (!writer) { return MS::kFailure; } writer->writeSubNodeHierarchy( subNode, fTimePerCycleInSeconds, fStartTimeInSeconds); if (materials) { writer->writeMaterials( materials, fTimePerCycleInSeconds, fStartTimeInSeconds); } return MS::kSuccess; } // Write a list of sub-node hierarchies to the specified file. MStatus writeNodes(const std::vector<SubNode::Ptr>& subNodes, const MaterialGraphMap::Ptr& materials, const MFileObject& targetFile) { boost::shared_ptr<CacheWriter> writer = createWriter( targetFile, fCompressLevel, fDataFormat ); if (!writer) { return MS::kFailure; } BOOST_FOREACH(const SubNode::Ptr& subNode, subNodes) { writer->writeSubNodeHierarchy( subNode, fTimePerCycleInSeconds, fStartTimeInSeconds); } if (materials) { writer->writeMaterials(materials, fTimePerCycleInSeconds, fStartTimeInSeconds); } return MS::kSuccess; } private: const char fCompressLevel; const MString fDataFormat; const double fTimePerCycleInSeconds; const double fStartTimeInSeconds; }; //========================================================================== // CLASS Stat //========================================================================== class Stat { public: Stat(MUint64 bytesPerUnit) : fMin(std::numeric_limits<MUint64>::max()), fMax(0), fTotal(0), fInstancedTotal(0), fBytesPerUnit(bytesPerUnit) {} void addSample( const boost::shared_ptr<const IndexBuffer> buffer, const int indicesPerElem) { addSample(buffer->numIndices() / indicesPerElem, buffer.get()); }; void addSample( const boost::shared_ptr<const VertexBuffer> buffer) { addSample(buffer->numVerts(), buffer.get()); }; void addSample( const MHWRender::MIndexBuffer* buffer, size_t numIndices) { addSample(numIndices, (void*)buffer); } void addSample( const MHWRender::MVertexBuffer* buffer, size_t numVertices) { addSample(numVertices, (void*)buffer); } void addSample( const boost::shared_ptr<const VBOBuffer> buffer, size_t numPrimitives) { addSample(numPrimitives, buffer.get()); } MUint64 getNbSamples() const { return fUniqueEntries.size(); } MUint64 getMin() const { return fMin;} MUint64 getMax() const { return fMin;} MUint64 getTotal() const { return fTotal;} MUint64 getInstancedTotal() const { return fInstancedTotal;} double getAverage() const { return double(getTotal())/double(getNbSamples()); } MUint64 getSize() const { return fTotal * fBytesPerUnit; } MString print(MString name) const { MStatus status; MString result; if (getNbSamples() == 0) { MString msg; msg.format( MStringResource::getString(kStatsZeroBuffersMsg, status), name); result = msg; } else { MString memUnit; double memSize = toHumanUnits(getSize(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)getNbSamples(); MString msg_avrg; msg_avrg += (double)getAverage(); MString msg_min; msg_min += (double)fMin; MString msg_max; msg_max += (double)fMax; MString msg_total; msg_total += (double)fTotal; MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kStatsBuffersMsg, status), name, msg_buffers, msg_avrg, msg_min, msg_max, msg_total, msg_memSize, memUnit); result = msg; } return result; } private: void addSample(MUint64 value, const void* buffer) { if (fUniqueEntries.insert(buffer).second) { fMin = std::min(fMin, value); fMax = std::max(fMax, value); fTotal += value; } fInstancedTotal += value; }; boost::unordered_set<const void*> fUniqueEntries; MUint64 fMin; MUint64 fMax; MUint64 fTotal; const MUint64 fBytesPerUnit; // Total number of instanced geometry. MUint64 fInstancedTotal; }; //========================================================================== // CLASS Stats //========================================================================== class Stats { public: Stats() : fNbNodes(0), fNbSubNodes(0), fWires( 2 * sizeof(IndexBuffer::index_t)), fTriangles( 3 * sizeof(IndexBuffer::index_t)), fVerts( 3 * sizeof(float)), fNormals( 3 * sizeof(float)), fUVs( 2 * sizeof(float)), fVP2Index( sizeof(IndexBuffer::index_t)), fVP2Vertex( sizeof(float)), fVBOIndex( sizeof(IndexBuffer::index_t)), fVBOVertex( sizeof(float)), fNbMaterialGraphs(0), fNbMaterialNodes(0) {} void accumulateNode() { ++fNbNodes; } void accumulateMaterialGraph(const MaterialGraph::Ptr&) { ++fNbMaterialGraphs; } void accumulateMaterialNode(const MaterialNode::Ptr&) { ++fNbMaterialNodes; } void accumulate(const ShapeData& shape) { ++fNbSubNodes; BOOST_FOREACH(const ShapeData::SampleMap::value_type& v, shape.getSamples()) { accumSample(v.second); } } void accumulate(const ShapeData& shape, MTime time) { ++fNbSubNodes; accumSample(shape.getSample(time)); } void print(MStringArray& result, bool printInstancedInfo) const { MStatus status; { MString msg; MString msg_nbGeom; msg_nbGeom += fNbNodes; MString msg_nbSubNodes; msg_nbSubNodes += fNbSubNodes; msg.format( MStringResource::getString(kStatsNbGeomMsg, status), msg_nbGeom, msg_nbSubNodes); result.append(msg); } result.append(fWires.print( MStringResource::getString(kStatsWiresMsg, status))); result.append(fTriangles.print(MStringResource::getString(kStatsTrianglesMsg, status))); result.append(fVerts.print( MStringResource::getString(kStatsVerticesMsg, status))); result.append(fNormals.print( MStringResource::getString(kStatsNormalsMsg, status))); result.append(fUVs.print( MStringResource::getString(kStatsUVsMsg, status))); if (printInstancedInfo) { MString msg; MString msgInstWires; msgInstWires += (double)fWires.getInstancedTotal(); MString msgInstTris; msgInstTris += (double)fTriangles.getInstancedTotal(); msg.format( MStringResource::getString(kStatsTotalInstancedMsg, status), msgInstWires, msgInstTris); result.append(msg); } { MUint64 totalMem = (fWires.getSize() + fTriangles.getSize() + fVerts.getSize() + fNormals.getSize() + fUVs.getSize()); MString memUnit; double memSize = toHumanUnits(totalMem, memUnit); MString msg; MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kStatsSystemTotalMsg, status), msg_memSize, memUnit); result.append(msg); } { MUint64 totalMem = (fVBOIndex.getSize() + fVBOVertex.getSize()); result.append(fVBOIndex.print( MStringResource::getString(kStatsVBOIndexMsg, status))); result.append(fVBOVertex.print(MStringResource::getString(kStatsVBOVertexMsg, status))); if (Config::vp2OverrideAPI() != Config::kMPxDrawOverride) { result.append(fVP2Index.print( MStringResource::getString(kStatsVP2IndexMsg, status))); result.append(fVP2Vertex.print(MStringResource::getString(kStatsVP2VertexMsg, status))); totalMem += (fVP2Index.getSize() + fVP2Vertex.getSize()); } MString memUnit; double memSize = toHumanUnits(totalMem, memUnit); MString msg; MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kStatsVideoTotalMsg, status), msg_memSize, memUnit); result.append(msg); } { MString msg_nbGraphs; msg_nbGraphs += fNbMaterialGraphs; MString msg_nbNodes; msg_nbNodes += fNbMaterialNodes; MString msg; msg.format( MStringResource::getString(kStatsMaterialsMsg, status), msg_nbGraphs, msg_nbNodes); result.append(msg); } } private: /*----- member functions -----*/ void accumSample(const boost::shared_ptr<const ShapeSample>& sample) { accumIndexBuffer(fWires, sample->wireVertIndices(), 2); for(size_t i=0; i<sample->numIndexGroups(); ++i) { accumIndexBuffer(fTriangles, sample->triangleVertIndices(i), 3); } accumVertexBuffer(fVerts, sample->positions()); accumVertexBuffer(fNormals, sample->normals()); accumVertexBuffer(fUVs, sample->uvs()); } void accumIndexBuffer( Stat& stat, const boost::shared_ptr<const IndexBuffer> indexBuffer, const int indicesPerElem ) { if (indexBuffer && indexBuffer != UnitBoundingBox::indices()) { stat.addSample(indexBuffer, indicesPerElem); { MHWRender::MIndexBuffer* vp2Buffer = SubSceneOverride::lookup(indexBuffer); if (vp2Buffer) fVP2Index.addSample(vp2Buffer, indexBuffer->numIndices()); } { boost::shared_ptr<const VBOBuffer> vboBuffer = VBOBuffer::lookup(indexBuffer); if (vboBuffer) fVBOIndex.addSample(vboBuffer, indexBuffer->numIndices()); } } } void accumVertexBuffer( Stat& stat, const boost::shared_ptr<const VertexBuffer> vertexBuffer ) { if (vertexBuffer && vertexBuffer != UnitBoundingBox::positions()) { stat.addSample(vertexBuffer); { MHWRender::MVertexBuffer* vp2Buffer = SubSceneOverride::lookup(vertexBuffer); if (vp2Buffer) fVP2Vertex.addSample( vp2Buffer, 3 * vertexBuffer->numVerts()); } { boost::shared_ptr<const VBOBuffer> vboBuffer = VBOBuffer::lookup(vertexBuffer); if (vboBuffer) fVBOVertex.addSample( vboBuffer, 3 * vertexBuffer->numVerts()); } { boost::shared_ptr<const VBOBuffer> vboBuffer = VBOBuffer::lookupFlippedNormals(vertexBuffer); if (vboBuffer) fVBOVertex.addSample( vboBuffer, 3 * vertexBuffer->numVerts()); } } } /*----- data members -----*/ int fNbNodes; int fNbSubNodes; Stat fWires; Stat fTriangles; Stat fVerts; Stat fNormals; Stat fUVs; Stat fVP2Index; Stat fVP2Vertex; Stat fVBOIndex; Stat fVBOVertex; int fNbMaterialGraphs; int fNbMaterialNodes; }; //========================================================================== // CLASS StatsVisitor //========================================================================== class StatsVisitor : public SubNodeVisitor { public: StatsVisitor() : fAtGivenTime(false) {} StatsVisitor(MTime time) : fAtGivenTime(true), fTime(time) {} void accumulateNode(const SubNode::Ptr& topNode) { fStats.accumulateNode(); if (topNode) { topNode->accept(*this); } } void accumulateMaterialGraph(const MaterialGraphMap::Ptr& materials) { if (materials) { BOOST_FOREACH ( const MaterialGraphMap::NamedMap::value_type& val, materials->getGraphs()) { fStats.accumulateMaterialGraph(val.second); accumulateMaterialNode(val.second); } } } void accumulateMaterialNode(const MaterialGraph::Ptr& material) { if (material) { BOOST_FOREACH ( const MaterialGraph::NamedMap::value_type& val, material->getNodes()) { fStats.accumulateMaterialNode(val.second); } } } void print(MStringArray& result, bool printInstancedInfo) const { fStats.print(result, printInstancedInfo); } private: virtual void visit(const XformData& /*xform*/, const SubNode& subNode) { // Recurse into children sub nodes. Expand all instances. BOOST_FOREACH(const SubNode::Ptr& child, subNode.getChildren() ) { child->accept(*this); } } virtual void visit(const ShapeData& shape, const SubNode& /*subNode*/) { if (fAtGivenTime) { fStats.accumulate(shape, fTime); } else { fStats.accumulate(shape); } } const bool fAtGivenTime; const MTime fTime; Stats fStats; }; //========================================================================== // CLASS DumpHierarchyVisitor //========================================================================== class DumpHierarchyVisitor : public SubNodeVisitor { public: DumpHierarchyVisitor(MStringArray& result) : fResult(result), fLevel(0) {} virtual void visit(const XformData& xform, const SubNode& subNode) { using namespace std; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "xform name = " << subNode.getName().asChar() << ", tt = " << subNode.transparentType() << ", ptr = " << (void*)&subNode << " {" << ends; fResult.append(MString(tmp.str().c_str())); } ++fLevel; { std::string indent(kIndent*fLevel, ' '); BOOST_FOREACH(const XformData::SampleMap::value_type& sample, xform.getSamples()) { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "time = " << setw(10) << sample.first << ", ptr = " << (void*)sample.second.get() << ", vis = " << sample.second->visibility() << ", bbox = (" << setw(8) << sample.second->boundingBox().min().x << "," << setw(8) << sample.second->boundingBox().min().y << "," << setw(8) << sample.second->boundingBox().min().z << ") - (" << setw(8) << sample.second->boundingBox().max().x << "," << setw(8) << sample.second->boundingBox().max().y << "," << setw(8) << sample.second->boundingBox().max().z << ")" << ends; fResult.append(MString(tmp.str().c_str())); } // Recurse into children sub nodes. Expand all instances. BOOST_FOREACH(const SubNode::Ptr& child, subNode.getChildren() ) { child->accept(*this); } } --fLevel; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "}" << ends; fResult.append(MString(tmp.str().c_str())); } } virtual void visit(const ShapeData& shape, const SubNode& subNode) { using namespace std; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "shape name = " << subNode.getName().asChar() << ", tt = " << subNode.transparentType() << ", ptr = " << (void*)&subNode << " {" << ends; fResult.append(MString(tmp.str().c_str())); } ++fLevel; { std::string indent(kIndent*fLevel, ' '); BOOST_FOREACH(const ShapeData::SampleMap::value_type& sample, shape.getSamples()) { { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "time = " << setw(10) << sample.first << ", ptr = " << (void*)sample.second.get() << ", vis = " << sample.second->visibility() << ", nT = " << sample.second->numTriangles() << ", nW = " << sample.second->numWires() << ", nV = " << sample.second->numVerts() << "," << ends; fResult.append(MString(tmp.str().c_str())); } { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "P = " << (void*)sample.second->positions().get() << ", N = " << (void*)sample.second->normals().get() << "," << ends; fResult.append(MString(tmp.str().c_str())); } { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "C = (" << setw(8) << sample.second->diffuseColor()[0] << "," << setw(8) << sample.second->diffuseColor()[1] << "," << setw(8) << sample.second->diffuseColor()[2] << "," << setw(8) << sample.second->diffuseColor()[3] << "," << "), bbox = (" << setw(8) << sample.second->boundingBox().min().x << "," << setw(8) << sample.second->boundingBox().min().y << "," << setw(8) << sample.second->boundingBox().min().z << ") - (" << setw(8) << sample.second->boundingBox().max().x << "," << setw(8) << sample.second->boundingBox().max().y << "," << setw(8) << sample.second->boundingBox().max().z << ")" << ends; fResult.append(MString(tmp.str().c_str())); } { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "bbox place holder = " << (sample.second->isBoundingBoxPlaceHolder() ? "yes" : "no") << ends; fResult.append(MString(tmp.str().c_str())); } } } if (!shape.getMaterials().empty()) { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "materials = "; BOOST_FOREACH (const MString& material, shape.getMaterials()) { tmp << material.asChar() << ' '; } tmp << ends; fResult.append(MString(tmp.str().c_str())); } --fLevel; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "}" << ends; fResult.append(MString(tmp.str().c_str())); } } private: static const int kIndent = 2; MStringArray& fResult; int fLevel; }; //========================================================================== // CLASS DumpMaterialVisitor //========================================================================== class DumpMaterialVisitor { public: DumpMaterialVisitor(MStringArray& result) : fResult(result), fLevel(0) {} void dumpMaterials(const MaterialGraphMap::Ptr& materials) { using namespace std; BOOST_FOREACH (const MaterialGraphMap::NamedMap::value_type& val, materials->getGraphs()) { const MaterialGraph::Ptr& graph = val.second; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "material graph name = " << graph->name().asChar() << ", nNodes = " << graph->getNodes().size() << ", ptr = " << (void*)graph.get() << " {" << ends; fResult.append(MString(tmp.str().c_str())); } ++fLevel; BOOST_FOREACH (const MaterialGraph::NamedMap::value_type& val, graph->getNodes()) { dumpMaterialNode(val.second); } --fLevel; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "}" << ends; fResult.append(MString(tmp.str().c_str())); } } } void dumpMaterialNode(const MaterialNode::Ptr& node) { using namespace std; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "material node name = " << node->name().asChar() << ", type = " << node->type() << ", ptr = " << (void*)node.get() << " {" << ends; fResult.append(MString(tmp.str().c_str())); } ++fLevel; BOOST_FOREACH (const MaterialNode::PropertyMap::value_type& val, node->properties()) { dumpMaterialProperty(val.second); } --fLevel; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "}" << ends; fResult.append(MString(tmp.str().c_str())); } } void dumpMaterialProperty(const MaterialProperty::Ptr& prop) { using namespace std; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "prop name = " << prop->name().asChar() << ", type = " << propertyTypeString(prop) << ", ptr = " << (void*)prop.get() << " {" << ends; fResult.append(MString(tmp.str().c_str())); } ++fLevel; BOOST_FOREACH (const MaterialProperty::SampleMap::value_type& val, prop->getSamples()) { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "time = " << setw(10) << val.first << ", value = " << propertyValueString(val.first, prop) << ", ptr = " << (void*)val.second.get() << ends; fResult.append(MString(tmp.str().c_str())); } const MaterialNode::Ptr srcNode = prop->srcNode(); const MaterialProperty::Ptr srcProp = prop->srcProp(); if (srcNode && srcProp) { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "src node = " << srcNode->name().asChar() << ", src prop = " << srcProp->name().asChar() << ends; fResult.append(MString(tmp.str().c_str())); } --fLevel; { ostringstream tmp; tmp << setw(kIndent*fLevel) << ' ' << "}" << ends; fResult.append(MString(tmp.str().c_str())); } } std::string propertyTypeString(const MaterialProperty::Ptr& prop) { switch (prop->type()) { case MaterialProperty::kBool: return "bool"; case MaterialProperty::kInt32: return "int32"; case MaterialProperty::kFloat: return "float"; case MaterialProperty::kFloat2: return "float2"; case MaterialProperty::kFloat3: return "float3"; case MaterialProperty::kRGB: return "rgb"; case MaterialProperty::kString: return "string"; default: assert(0); return "unknown"; } } std::string propertyValueString(double seconds, const MaterialProperty::Ptr& prop) { std::ostringstream tmp; switch (prop->type()) { case MaterialProperty::kBool: tmp << (prop->asBool(seconds) ? "true" : "false"); break; case MaterialProperty::kInt32: tmp << prop->asInt32(seconds); break; case MaterialProperty::kFloat: tmp << prop->asFloat(seconds); break; case MaterialProperty::kFloat2: { float x, y; prop->asFloat2(seconds, x, y); tmp << "(" << x << "," << y << ")"; break; } case MaterialProperty::kFloat3: { float x, y, z; prop->asFloat3(seconds, x, y, z); tmp << "(" << x << "," << y << "," << z << ")"; break; } case MaterialProperty::kRGB: { MColor c = prop->asColor(seconds); tmp << "rgb(" << c.r << "," << c.g << "," << c.b << ")"; break; } case MaterialProperty::kString: tmp << prop->asString(seconds).asChar(); break; default: assert(0); tmp << "unknown type"; break; } return tmp.str(); } private: static const int kIndent = 2; MStringArray& fResult; int fLevel; }; //============================================================================== // CLASS ProgressBar //============================================================================== class ProgressBar { public: ProgressBar(const MStringResourceId& msg, unsigned int max) { // Display a progress bar if Maya is running in UI mode fShowProgress = (MGlobal::mayaState() == MGlobal::kInteractive); reset(msg, max); } void reset(const MStringResourceId& msg, unsigned int max) { MStatus status; beginProgress(MStringResource::getString(msg, status), max); } ~ProgressBar() { endProgress(); } void stepProgress() const { if (fShowProgress) { MGlobal::executeCommand("progressBar -e -s 1 $gMainProgressBar"); } } bool isCancelled() const { int isCancelled = 0; if (fShowProgress) { MGlobal::executeCommand("progressBar -q -ic $gMainProgressBar", isCancelled); } if (isCancelled) { MStatus status; const MString interruptMsg = MStringResource::getString(kInterruptedMsg, status); MGlobal::displayInfo(interruptMsg); return true; } return false; } private: // Forbidden and not implemented. ProgressBar(const ProgressBar&); const ProgressBar& operator=(const ProgressBar&); ProgressBar(const MString& msg, unsigned int max) { beginProgress(msg, max); } void beginProgress(const MString& msg, unsigned int max) const { if (fShowProgress) { MString maxValue, progressBarCmd; // Progress from 0 to max if (max <= 0) { max = 1; } maxValue += max; // Clear previous isCancelled flag MGlobal::executeCommand("progressBar -e -bp -ii 1 $gMainProgressBar"); MGlobal::executeCommand("progressBar -e -ep $gMainProgressBar"); // Initialize the progress bar progressBarCmd.format("progressBar -e -bp -ii 1 -st \"^1s\" -max ^2s $gMainProgressBar", msg, maxValue); MGlobal::executeCommand(progressBarCmd); } } void endProgress() const { if (fShowProgress) { MGlobal::executeCommand("progressBar -e -ep $gMainProgressBar"); } } bool fShowProgress; // whether to show the progress bar }; //============================================================================== // CLASS GroupCreator //============================================================================== class GroupCreator { public: GroupCreator() {} ~GroupCreator() {} void addChild(const SubNode::MPtr& childNode) { XformData::Ptr childXform = boost::dynamic_pointer_cast<const XformData>( childNode->getData()); assert(childXform); if (childXform) { fChildNodes.push_back(childNode); fChildXforms.push_back(childXform); } } void group() { assert(!fGroup); fGroup = XformData::create(); // Collect time samples std::set<double> times; BOOST_FOREACH(const XformData::Ptr child, fChildXforms) { BOOST_FOREACH(const XformData::SampleMap::value_type& val, child->getSamples()) { times.insert(val.first); } } std::set<double>::const_iterator timeIt = times.begin(); std::set<double>::const_iterator timeEnd = times.end(); if (timeIt != timeEnd) { fGroup->addSample(XformSample::create( *timeIt, MMatrix::identity, MBoundingBox(), true)); } } SubNode::MPtr getSubNode(const MString& name) { SubNode::MPtr subNode = SubNode::create(name, fGroup); BOOST_FOREACH(const SubNode::MPtr& childNode, fChildNodes) { SubNode::connect(subNode, childNode); } return subNode; } private: // Prohibited and not implemented. GroupCreator(const GroupCreator&); const GroupCreator& operator= (const GroupCreator&); std::vector<SubNode::MPtr> fChildNodes; std::vector<XformData::Ptr> fChildXforms; XformData::MPtr fGroup; }; //============================================================================== // CLASS XformFreezer //============================================================================== class XformFreezer : public SubNodeVisitor { public: typedef std::vector<ShapeData::Ptr> FrozenGeometries; typedef std::vector<std::pair<XformData::Ptr,ShapeData::Ptr> > AnimatedGeometries; typedef std::set<double> TimeSet; XformFreezer(const XformData::Ptr& parentXform, FrozenGeometries& frozenGeometries, bool dontFreezeAnimatedObjects, AnimatedGeometries& animatedGeometries) : fParentXform(parentXform), fFrozenGeometries(frozenGeometries), fDontFreezeAnimatedObjects(dontFreezeAnimatedObjects), fAnimatedGeometries(animatedGeometries) {} virtual void visit(const XformData& xform, const SubNode& subNode) { // Aggregate the list of sample times. TimeSet times; BOOST_FOREACH(const XformData::SampleMap::value_type& val, fParentXform->getSamples() ) { times.insert(val.first); } BOOST_FOREACH(const XformData::SampleMap::value_type& val, xform.getSamples()) { times.insert(val.first); } // Freeze xform sample XformData::MPtr frozenXform = XformData::create(); BOOST_FOREACH(const double& time, times) { // Parent xform sample boost::shared_ptr<const XformSample> parentSample = fParentXform->getSample(time); // Child xform sample boost::shared_ptr<const XformSample> sample = xform.getSample(time); frozenXform->addSample(XformSample::create( time, sample->xform() * parentSample->xform(), MBoundingBox(), // not used sample->visibility() && parentSample->visibility())); } // Recursive into children BOOST_FOREACH(const SubNode::Ptr& child, subNode.getChildren()) { XformFreezer xformFreezer(frozenXform, fFrozenGeometries, fDontFreezeAnimatedObjects, fAnimatedGeometries); child->accept(xformFreezer); } } virtual void visit(const ShapeData& shape, const SubNode& subNode) { // Don't freeze animated objects for motion blur. if (fDontFreezeAnimatedObjects) { // If the shape matches all the following conditions, we don't freeze/consolidate it. // 1) Any of the parents (direct,indirect) is animated. // 2) Shape is not animated. if (fParentXform->getSamples().size() > 1 && shape.getSamples().size() <= 1) { // Duplicate the xform data. XformData::MPtr animatedXform = XformData::create(); BOOST_FOREACH (const XformData::SampleMap::value_type& val, fParentXform->getSamples()) { animatedXform->addSample(val.second); } // Duplicate the shape data. ShapeData::MPtr animatedShape = ShapeData::create(); BOOST_FOREACH (const ShapeData::SampleMap::value_type& val, shape.getSamples()) { animatedShape->addSample(val.second); } animatedShape->setMaterials(shape.getMaterials()); // Give up. We don't freeze and consolidate shapes with // animated xforms. fAnimatedGeometries.push_back( std::make_pair(animatedXform, animatedShape)); return; } } // Aggregate the list of sample times. TimeSet times; BOOST_FOREACH(const XformData::SampleMap::value_type& val, fParentXform->getSamples()) { times.insert(val.first); } BOOST_FOREACH(const ShapeData::SampleMap::value_type& val, shape.getSamples()) { times.insert(val.first); } // Freeze shape sample ShapeData::MPtr frozenShape = ShapeData::create(); TimeSet::const_iterator it = times.begin(); TimeSet::const_iterator end = times.end(); if (it != end) { // The first xform and shape sample boost::shared_ptr<const XformSample> xformSample = fParentXform->getSample(*it); boost::shared_ptr<const ShapeSample> shapeSample = shape.getSample(*it); // Freeze the shape sample boost::shared_ptr<const ShapeSample> frozenSample; if (xformSample->visibility() && shapeSample->visibility()) { frozenSample = freezeSample(*it, xformSample, shapeSample); } else { frozenSample = ShapeSample::createEmptySample(*it); } // Add the frozen shape sample frozenShape->addSample(frozenSample); ++it; for (; it != end; ++it) { // Save the previous sample boost::shared_ptr<const XformSample> prevXformSample = xformSample; boost::shared_ptr<const ShapeSample> prevShapeSample = shapeSample; // The next xform and shape sample xformSample = fParentXform->getSample(*it); shapeSample = shape.getSample(*it); if (xformSample->visibility() && shapeSample->visibility()) { if (!xformSample->xform().isEquivalent(prevXformSample->xform()) || xformSample->visibility() != prevXformSample->visibility() || shapeSample->wireVertIndices() != prevShapeSample->wireVertIndices() || shapeSample->triangleVertexIndexGroups() != prevShapeSample->triangleVertexIndexGroups() || shapeSample->positions() != prevShapeSample->positions() || shapeSample->normals() != prevShapeSample->normals() || shapeSample->diffuseColor() != prevShapeSample->diffuseColor() || shapeSample->visibility() != prevShapeSample->visibility()) { // Something changed, need to re-freeze the shape sample frozenSample = freezeSample(*it, xformSample, shapeSample); } else { // Reuse the last freezeSample() result. boost::shared_ptr<ShapeSample> newFrozenSample = ShapeSample::create( *it, shapeSample->numWires(), shapeSample->numVerts(), shapeSample->wireVertIndices(), shapeSample->triangleVertexIndexGroups(), frozenSample->positions(), frozenSample->boundingBox(), shapeSample->diffuseColor(), xformSample->visibility() && shapeSample->visibility()); newFrozenSample->setNormals(frozenSample->normals()); newFrozenSample->setUVs(shapeSample->uvs()); frozenSample = newFrozenSample; } } else { frozenSample = ShapeSample::createEmptySample(*it); } // Add the frozen shape sample frozenShape->addSample(frozenSample); } } frozenShape->setMaterials(shape.getMaterials()); fFrozenGeometries.push_back(frozenShape); } private: boost::shared_ptr<const ShapeSample> freezeSample( const double time, const boost::shared_ptr<const XformSample>& xform, const boost::shared_ptr<const ShapeSample>& shape) { const size_t numWires = shape->numWires(); const size_t numVerts = shape->numVerts(); boost::shared_ptr<IndexBuffer> wireVertIndices = shape->wireVertIndices(); std::vector<boost::shared_ptr<IndexBuffer> > triangleVertexIndexGroups = shape->triangleVertexIndexGroups(); boost::shared_ptr<VertexBuffer> uvs = shape->uvs(); MColor diffuseColor = shape->diffuseColor(); bool visibility = shape->visibility() && xform->visibility(); // Check bad polys if (numWires == 0 || numVerts == 0 || !wireVertIndices || triangleVertexIndexGroups.empty()) { return ShapeSample::createEmptySample(time); } boost::shared_ptr<VertexBuffer> positions; boost::shared_ptr<VertexBuffer> normals; MBoundingBox boundingBox; MMatrix xformMatrix = xform->xform(); if (xformMatrix.isEquivalent(MMatrix::identity)) { // Nothing to bake for an identity transform. positions = shape->positions(); normals = shape->normals(); boundingBox = shape->boundingBox(); } else { float xform[4][4]; float xformIT[4][4]; xformMatrix.get(xform); xformMatrix.inverse().transpose().get(xformIT); const bool isReflection = xformMatrix.det3x3() < 0.0; if (isReflection) { // Change the winding order of the triangles if // the matrix contains a reflection along one the // axis to preserve front facing. std::vector<boost::shared_ptr<IndexBuffer> > newTriangleVertexIndexGroups; BOOST_FOREACH(const boost::shared_ptr<IndexBuffer>& srcIdxBuf, triangleVertexIndexGroups) { typedef IndexBuffer::index_t index_t; const size_t numIndices = srcIdxBuf->numIndices(); IndexBuffer::ReadInterfacePtr readable = srcIdxBuf->readableInterface(); const index_t* srcIndices = readable->get(); const boost::shared_array<IndexBuffer::index_t> dstIndices( new index_t[numIndices]); for (size_t i=0; i<numIndices; i+=3) { dstIndices[i + 0] = srcIndices[i + 2]; dstIndices[i + 1] = srcIndices[i + 1]; dstIndices[i + 2] = srcIndices[i + 0]; } boost::shared_ptr<IndexBuffer> dstIdxBuf( IndexBuffer::create( SharedArray<index_t>::create(dstIndices, numIndices))); newTriangleVertexIndexGroups.push_back(dstIdxBuf); } triangleVertexIndexGroups.swap(newTriangleVertexIndexGroups); } VertexBuffer::ReadInterfacePtr srcPosRead = shape->positions()->readableInterface(); const float* srcPositions = srcPosRead->get(); VertexBuffer::ReadInterfacePtr srcNormRead = shape->normals()->readableInterface(); const float* srcNormals = srcNormRead->get(); boost::shared_array<float> dstPositions(new float[3 * numVerts]); boost::shared_array<float> dstNormals(new float[3 * numVerts]); float minX = +std::numeric_limits<float>::max(); float minY = +std::numeric_limits<float>::max(); float minZ = +std::numeric_limits<float>::max(); float maxX = -std::numeric_limits<float>::max(); float maxY = -std::numeric_limits<float>::max(); float maxZ = -std::numeric_limits<float>::max(); for (size_t i=0; i<numVerts; ++i) { const float x = srcPositions[3*i + 0]; const float y = srcPositions[3*i + 1]; const float z = srcPositions[3*i + 2]; const float xp = xform[0][0] * x + xform[1][0] * y + xform[2][0] * z + xform[3][0]; const float yp = xform[0][1] * x + xform[1][1] * y + xform[2][1] * z + xform[3][1]; const float zp = xform[0][2] * x + xform[1][2] * y + xform[2][2] * z + xform[3][2]; minX = std::min(xp, minX); minY = std::min(yp, minY); minZ = std::min(zp, minZ); maxX = std::max(xp, maxX); maxY = std::max(yp, maxY); maxZ = std::max(zp, maxZ); dstPositions[3*i + 0] = xp; dstPositions[3*i + 1] = yp; dstPositions[3*i + 2] = zp; const float nx = srcNormals[3*i + 0]; const float ny = srcNormals[3*i + 1]; const float nz = srcNormals[3*i + 2]; dstNormals[3*i + 0] = xformIT[0][0] * nx + xformIT[1][0] * ny + xformIT[2][0] * nz + xformIT[3][0]; dstNormals[3*i + 1] = xformIT[0][1] * nx + xformIT[1][1] * ny + xformIT[2][1] * nz + xformIT[3][1]; dstNormals[3*i + 2] = xformIT[0][2] * nx + xformIT[1][2] * ny + xformIT[2][2] * nz + xformIT[3][2]; } positions = VertexBuffer::createPositions( SharedArray<float>::create(dstPositions, 3 * numVerts)); normals = VertexBuffer::createNormals( SharedArray<float>::create(dstNormals, 3 * numVerts)); boundingBox = MBoundingBox(MPoint(minX, minY, minZ), MPoint(maxX, maxY, maxZ)); } boost::shared_ptr<ShapeSample> frozenSample = ShapeSample::create( time, numWires, numVerts, wireVertIndices, triangleVertexIndexGroups, positions, boundingBox, diffuseColor, visibility); frozenSample->setNormals(normals); frozenSample->setUVs(uvs); return frozenSample; } // Prohibited and not implemented. XformFreezer(const XformFreezer&); const XformFreezer& operator= (const XformFreezer&); XformData::Ptr fParentXform; FrozenGeometries& fFrozenGeometries; AnimatedGeometries& fAnimatedGeometries; bool fDontFreezeAnimatedObjects; }; //============================================================================== // CLASS ConsolidateBuckets //============================================================================== class ConsolidateBuckets { public: struct BucketKey { typedef std::map<double,MColor> DiffuseColorMap; typedef std::map<double,bool> VisibilityMap; typedef std::map<double,size_t> IndexGroupMap; typedef std::vector<MString> MaterialsAssignment; BucketKey(const ShapeData::Ptr& shape) { ShapeData::SampleMap::const_iterator it = shape->getSamples().begin(); ShapeData::SampleMap::const_iterator end = shape->getSamples().end(); if (it != end) { MColor diffuseColor = (*it).second->diffuseColor(); bool visibility = (*it).second->visibility(); size_t indexGroups = (*it).second->numIndexGroups(); fDiffuseColor[(*it).first] = diffuseColor; fVisibility[(*it).first] = visibility; fIndexGroup[(*it).first] = indexGroups; ++it; for (; it != end; ++it) { MColor prevDiffuseColor = diffuseColor; bool prevVisibility = visibility; size_t prevIndexGroups = indexGroups; MColor diffuseColor = (*it).second->diffuseColor(); bool visibility = (*it).second->visibility(); size_t indexGroups = (*it).second->numIndexGroups(); if (prevDiffuseColor != diffuseColor) { fDiffuseColor[(*it).first] = diffuseColor; } if (prevVisibility != visibility) { fVisibility[(*it).first] = visibility; } if (prevIndexGroups != indexGroups) { fIndexGroup[(*it).first] = indexGroups; } } } fMaterials = shape->getMaterials(); } struct Hash : std::unary_function<BucketKey, std::size_t> { std::size_t operator()(const BucketKey& key) const { std::size_t seed = 0; BOOST_FOREACH(const DiffuseColorMap::value_type& val, key.fDiffuseColor) { boost::hash_combine(seed, val.first); boost::hash_combine(seed, val.second.r); boost::hash_combine(seed, val.second.g); boost::hash_combine(seed, val.second.b); boost::hash_combine(seed, val.second.a); } BOOST_FOREACH(const VisibilityMap::value_type& val, key.fVisibility) { boost::hash_combine(seed, val.first); boost::hash_combine(seed, val.second); } BOOST_FOREACH(const IndexGroupMap::value_type& val, key.fIndexGroup) { boost::hash_combine(seed, val.first); boost::hash_combine(seed, val.second); } BOOST_FOREACH(const MString& material, key.fMaterials) { unsigned int length = material.length(); const char* begin = material.asChar(); size_t hash = boost::hash_range(begin, begin + length); boost::hash_combine(seed, hash); } return seed; } }; struct EqualTo : std::binary_function<BucketKey, BucketKey, bool> { bool operator()(const BucketKey& x, const BucketKey& y) const { return x.fDiffuseColor == y.fDiffuseColor && x.fVisibility == y.fVisibility && x.fIndexGroup == y.fIndexGroup && x.fMaterials == y.fMaterials; } }; DiffuseColorMap fDiffuseColor; VisibilityMap fVisibility; IndexGroupMap fIndexGroup; MaterialsAssignment fMaterials; }; typedef std::multimap<size_t,ShapeData::Ptr> Bucket; typedef boost::unordered_map<BucketKey,Bucket,BucketKey::Hash,BucketKey::EqualTo> BucketMap; typedef std::list<Bucket> BucketList; ConsolidateBuckets(const XformFreezer::FrozenGeometries& shapes) : fShapes(shapes) {} void divide() { BOOST_FOREACH(const ShapeData::Ptr& shape , fShapes) { BucketKey key(shape); std::pair<BucketMap::iterator,bool> ret = fBucketMap.insert(std::make_pair(key, Bucket())); ret.first->second.insert(std::make_pair(maxNumVerts(shape), shape)); } } void getBucketList(BucketList& bucketList) { bucketList.clear(); BOOST_FOREACH(const BucketMap::value_type& val, fBucketMap) { bucketList.push_back(val.second); } } private: // Prohibited and not implemented. ConsolidateBuckets(const ConsolidateBuckets&); const ConsolidateBuckets& operator= (const ConsolidateBuckets&); const XformFreezer::FrozenGeometries& fShapes; BucketMap fBucketMap; }; //============================================================================== // CLASS FirstSampleTime //============================================================================== class FirstSampleTime : public SubNodeVisitor { public: FirstSampleTime() : fTime(0) {} virtual void visit(const XformData& xform, const SubNode& subNode) { fTime = xform.getSamples().begin()->first; } virtual void visit(const ShapeData& shape, const SubNode& subNode) { fTime = shape.getSamples().begin()->first; } double get() { return fTime; } private: // Prohibited and not implemented. FirstSampleTime(const FirstSampleTime&); const FirstSampleTime& operator= (const FirstSampleTime&); double fTime; }; //============================================================================== // CLASS Consolidator //============================================================================== class Consolidator { public: Consolidator(SubNode::MPtr rootNode, const int threshold, const bool motionBlur) : fRootNode(rootNode), fThreshold(threshold), fMotionBlur(motionBlur) {} ~Consolidator() {} MStatus consolidate() { // We currently unconditionally expand all instances. This is kind // of brute force as it assumes that the instances have a low poly // count so that consolidating them is worthwhile and that also // the instance count is low so that the data expansion is // reasonable. // // FIXME: Obviously, a more intelligent heuristic would be needed // at one point. // Get the time of the first sample, useful when creating new xform // samples. double firstSampleTime = 0; { FirstSampleTime firstSampleTimeVisitor; fRootNode->accept(firstSampleTimeVisitor); firstSampleTime = firstSampleTimeVisitor.get(); } // Freeze transforms. XformFreezer::FrozenGeometries frozenGeometries; XformFreezer::AnimatedGeometries animatedGeometries; { // Create an dummy identity xform data as the root of traversal XformData::MPtr identityXformData = XformData::create(); identityXformData->addSample(XformSample::create( firstSampleTime, MMatrix::identity, MBoundingBox(), // not used when freeze transform true)); // Traversal the hierarchy to freeze transforms XformFreezer xformFreezer(identityXformData, frozenGeometries, fMotionBlur, animatedGeometries); fRootNode->accept(xformFreezer); } // Divide shapes into buckets ConsolidateBuckets::BucketList bucketList; { ConsolidateBuckets buckets(frozenGeometries); buckets.divide(); buckets.getBucketList(bucketList); } // Set up consolidation progress bar ProgressBar progressBar(kOptimizingMsg, (unsigned int)frozenGeometries.size()); // Consolidate each bucket std::vector<ShapeData::Ptr> newShapes; std::vector<ShapeData::Ptr> consolidatedShapes; BOOST_FOREACH(ConsolidateBuckets::Bucket& bucket, bucketList) { // Consolidate shapes until the bucket becomes empty while (!bucket.empty()) { const ConsolidateBuckets::Bucket::iterator largestNode = --bucket.end(); MInt64 numRemainingVerts = fThreshold - largestNode->first; if (numRemainingVerts < 0) { // Already too large to be consolidated. newShapes.push_back(largestNode->second); bucket.erase(largestNode); MUpdateProgressAndCheckInterruption(progressBar); } else { // Find nodes that could make up a consolidation group. consolidatedShapes.push_back(largestNode->second); bucket.erase(largestNode); MUpdateProgressAndCheckInterruption(progressBar); while (numRemainingVerts > 0 && !bucket.empty()) { ConsolidateBuckets::Bucket::iterator node = bucket.upper_bound((size_t)numRemainingVerts); if (node == bucket.begin()) break; --node; numRemainingVerts -= (MInt64)node->first; consolidatedShapes.push_back(node->second); bucket.erase(node); MUpdateProgressAndCheckInterruption(progressBar); } // Consolidate the consolidation group consolidateGeometry(newShapes, consolidatedShapes); } } } // Attach a xform data to each new shape data std::vector<XformData::Ptr> newXforms; BOOST_FOREACH(const ShapeData::Ptr& newShape, newShapes) { XformData::MPtr newXform = XformData::create(); ShapeData::SampleMap::const_iterator it = newShape->getSamples().begin(); ShapeData::SampleMap::const_iterator end = newShape->getSamples().end(); if (it != end) { newXform->addSample(XformSample::create( (*it).first, MMatrix::identity, MBoundingBox(), true)); } newXforms.push_back(newXform); } // Build a vector of all nodes (consolidated + animated nodes). std::vector<std::pair<XformData::Ptr,ShapeData::Ptr> > finalXformsAndShapes; for (size_t i = 0; i < newXforms.size(); i++) { finalXformsAndShapes.push_back(std::make_pair(newXforms[i], newShapes[i])); } finalXformsAndShapes.insert(finalXformsAndShapes.end(), animatedGeometries.begin(), animatedGeometries.end()); // Done if (finalXformsAndShapes.size() == 1) { // Only one shape, use its xform node as the consolidation root SubNode::MPtr xformNode = SubNode::create( fRootNode->getName(), finalXformsAndShapes[0].first); SubNode::MPtr shapeNode = SubNode::create( fRootNode->getName() + "Shape", finalXformsAndShapes[0].second); SubNode::connect(xformNode, shapeNode); fConsolidatedRootNode = xformNode; } else if (finalXformsAndShapes.size() > 1) { // There are more than one shape // We create one more xform node as the consolidation root XformData::MPtr topXform = XformData::create(); std::set<double> times; for (size_t i = 0; i < finalXformsAndShapes.size(); i++) { BOOST_FOREACH(const XformData::SampleMap::value_type& val, finalXformsAndShapes[i].first->getSamples()) { times.insert(val.first); } BOOST_FOREACH(const ShapeData::SampleMap::value_type& val, finalXformsAndShapes[i].second->getSamples()) { times.insert(val.first); } } std::set<double>::const_iterator timeIt = times.begin(); std::set<double>::const_iterator timeEnd = times.end(); if (timeIt != timeEnd) { topXform->addSample(XformSample::create( *timeIt, MMatrix::identity, MBoundingBox(), true)); } SubNode::MPtr topXformNode = SubNode::create( fRootNode->getName(), topXform); // Create shapes' parent xform sub nodes. // They are children of the consolidation root. for (size_t i = 0; i < finalXformsAndShapes.size(); i++) { SubNode::MPtr xformNode = SubNode::create( fRootNode->getName() + (i + 1), finalXformsAndShapes[i].first); SubNode::MPtr shapeNode = SubNode::create( fRootNode->getName() + "Shape" + (i + 1), finalXformsAndShapes[i].second); SubNode::connect(xformNode, shapeNode); SubNode::connect(topXformNode, xformNode); } fConsolidatedRootNode = topXformNode; } return MS::kSuccess; } SubNode::MPtr consolidatedRootNode() { return fConsolidatedRootNode; } private: // Prohibited and not implemented. Consolidator(const Consolidator&); const Consolidator& operator= (const Consolidator&); void consolidateGeometry(std::vector<ShapeData::Ptr>& newShapes, std::vector<ShapeData::Ptr>& consolidatedShapes) { // Aggregate the list of sample times. std::set<double> times; BOOST_FOREACH(const ShapeData::Ptr& shape, consolidatedShapes) { BOOST_FOREACH(const ShapeData::SampleMap::value_type& smv, shape->getSamples()) { times.insert(smv.first); } } // Consolidated geometry. ShapeData::MPtr newShape = ShapeData::create(); const size_t nbShapes = consolidatedShapes.size(); std::set<double>::const_iterator timeIt = times.begin(); std::set<double>::const_iterator timeEnd = times.end(); // Consolidate the first sample. typedef IndexBuffer::index_t index_t; boost::shared_array<index_t> wireVertIndices; std::vector<boost::shared_array<index_t> > triangleVertIndices; boost::shared_array<float> positions; boost::shared_array<float> normals; boost::shared_array<float> uvs; MBoundingBox boundingBox; MColor diffuseColor; bool visibility = true; { size_t totalWires = 0; size_t totalVerts = 0; std::vector<size_t> totalTriangles; size_t numIndexGroups = 0; bool uvExists = false; for (size_t i = 0; i < nbShapes; i++) { ShapeData::Ptr& shape = consolidatedShapes[i]; const boost::shared_ptr<const ShapeSample>& sample = shape->getSample(*timeIt); totalWires += sample->numWires(); totalVerts += sample->numVerts(); if (numIndexGroups == 0) { // Initialize totalTriangles, assume that // all shapes has the same number of index groups numIndexGroups = sample->numIndexGroups(); totalTriangles.resize(numIndexGroups, 0); diffuseColor = sample->diffuseColor(); visibility = sample->visibility(); } // Shapes with different number of index groups, diffuseColor and visibility // should be divided into separate buckets. assert(numIndexGroups == sample->numIndexGroups()); assert(fabs(diffuseColor.r - sample->diffuseColor().r) < 1e-5); assert(fabs(diffuseColor.g - sample->diffuseColor().g) < 1e-5); assert(fabs(diffuseColor.b - sample->diffuseColor().b) < 1e-5); assert(fabs(diffuseColor.a - sample->diffuseColor().a) < 1e-5); assert(visibility == sample->visibility()); for (size_t j = 0; j < totalTriangles.size(); j++) { totalTriangles[j] += sample->numTriangles(j); } // Check whether UV exists if (!uvExists && sample->uvs()) { uvExists = true; } } wireVertIndices = boost::shared_array<index_t>( new index_t[2 * totalWires]); triangleVertIndices.resize(totalTriangles.size()); for (size_t i = 0; i < totalTriangles.size(); i++) { triangleVertIndices[i] = boost::shared_array<index_t>( new index_t[3 * totalTriangles[i]]); } positions = boost::shared_array<float>( new float[3 * totalVerts]); normals = boost::shared_array<float>( new float[3 * totalVerts]); if (uvExists) { uvs = boost::shared_array<float>( new float[2 * totalVerts]); } { size_t wireIdx = 0; size_t vertIdx = 0; std::vector<size_t> triangleIdx(numIndexGroups, 0); for (size_t i = 0; i < nbShapes; i++) { const boost::shared_ptr<const ShapeSample>& sample = consolidatedShapes[i]->getSample(*timeIt); const size_t numWires = sample->numWires(); const size_t numVerts = sample->numVerts(); // Wires if (sample->wireVertIndices()) { IndexBuffer::ReadInterfacePtr readable = sample->wireVertIndices()->readableInterface(); const index_t* srcWireVertIndices = readable->get(); for (size_t j = 0; j < numWires; j++) { wireVertIndices[2*(j + wireIdx) + 0] = index_t(srcWireVertIndices[2*j + 0] + vertIdx); wireVertIndices[2*(j + wireIdx) + 1] = index_t(srcWireVertIndices[2*j + 1] + vertIdx); } } // Triangles for (size_t group = 0; group < numIndexGroups; group++) { const size_t numTriangles = sample->numTriangles(group); if (sample->triangleVertIndices(group)) { IndexBuffer::ReadInterfacePtr readable = sample->triangleVertIndices(group)->readableInterface(); const index_t* srcTriangleVertIndices = readable->get(); for (size_t j = 0; j < numTriangles; j++) { triangleVertIndices[group][3*(j + triangleIdx[group]) + 0] = index_t(srcTriangleVertIndices[3*j + 0] + vertIdx); triangleVertIndices[group][3*(j + triangleIdx[group]) + 1] = index_t(srcTriangleVertIndices[3*j + 1] + vertIdx); triangleVertIndices[group][3*(j + triangleIdx[group]) + 2] = index_t(srcTriangleVertIndices[3*j + 2] + vertIdx); } } } // Positions if (sample->positions()) { VertexBuffer::ReadInterfacePtr readable = sample->positions()->readableInterface(); memcpy(&positions[3*vertIdx], readable->get(), 3*numVerts*sizeof(float)); } // Normals if (sample->normals()) { VertexBuffer::ReadInterfacePtr readable = sample->normals()->readableInterface(); memcpy(&normals[3*vertIdx], readable->get(), 3*numVerts*sizeof(float)); } // UVs if (sample->uvs()) { VertexBuffer::ReadInterfacePtr readable = sample->uvs()->readableInterface(); memcpy(&uvs[2*vertIdx], readable->get(), 2*numVerts*sizeof(float)); } else if (uvExists) { memset(&uvs[2*vertIdx], 0, 2*numVerts*sizeof(float)); } wireIdx += numWires; vertIdx += numVerts; for (size_t i = 0; i < numIndexGroups; i++) { triangleIdx[i] += sample->numTriangles(i); } boundingBox.expand(sample->boundingBox()); } } std::vector<boost::shared_ptr<IndexBuffer> > newTriangleVertIndices(numIndexGroups); for (size_t i = 0; i < numIndexGroups; i++) { newTriangleVertIndices[i] = IndexBuffer::create( SharedArray<index_t>::create( triangleVertIndices[i], 3 * totalTriangles[i])); } boost::shared_ptr<ShapeSample> newSample = ShapeSample::create( *timeIt, totalWires, totalVerts, IndexBuffer::create( SharedArray<index_t>::create( wireVertIndices, 2 * totalWires)), newTriangleVertIndices, VertexBuffer::createPositions( SharedArray<float>::create( positions, 3 * totalVerts)), boundingBox, diffuseColor, visibility); if (normals) { newSample->setNormals( VertexBuffer::createNormals( SharedArray<float>::create( normals, 3 * totalVerts))); } if (uvs) { newSample->setUVs( VertexBuffer::createUVs( SharedArray<float>::create( uvs, 2 * totalVerts))); } newShape->addSample(newSample); } // Consolidate the remaining samples. std::set<double>::const_iterator timePrev = timeIt; ++timeIt; for (; timeIt != timeEnd; ++timeIt) { size_t totalWires = 0; size_t totalVerts = 0; std::vector<size_t> totalTriangles; size_t numIndexGroups = 0; bool uvExists = false; bool wiresDirty = false; bool trianglesDirty = false; bool positionsDirty = false; bool normalsDirty = false; bool uvsDirty = false; for (size_t i = 0; i < nbShapes; i++) { ShapeData::Ptr& shape = consolidatedShapes[i]; const boost::shared_ptr<const ShapeSample>& sample = shape->getSample(*timeIt); const boost::shared_ptr<const ShapeSample>& prevSample = shape->getSample(*timePrev); totalWires += sample->numWires(); totalVerts += sample->numVerts(); if (numIndexGroups == 0) { // Initialize totalTriangles, assume that // all shapes has the same number of index groups numIndexGroups = sample->numIndexGroups(); totalTriangles.resize(numIndexGroups, 0); diffuseColor = sample->diffuseColor(); visibility = sample->visibility(); } // Shapes with different number of index groups, diffuseColor and visibility // should be divided into separate buckets. assert(numIndexGroups == sample->numIndexGroups()); assert(fabs(diffuseColor.r - sample->diffuseColor().r) < 1e-5); assert(fabs(diffuseColor.g - sample->diffuseColor().g) < 1e-5); assert(fabs(diffuseColor.b - sample->diffuseColor().b) < 1e-5); assert(fabs(diffuseColor.a - sample->diffuseColor().a) < 1e-5); assert(visibility == sample->visibility()); for (size_t j = 0; j < totalTriangles.size(); j++) { totalTriangles[j] += sample->numTriangles(j); } // Check whether UV exists if (!uvExists && sample->uvs()) { uvExists = true; } for (size_t j = 0; j < numIndexGroups; j++) { trianglesDirty |= sample->triangleVertIndices(j) != prevSample->triangleVertIndices(j); } wiresDirty |= sample->wireVertIndices() != prevSample->wireVertIndices(); positionsDirty |= sample->positions() != prevSample->positions(); normalsDirty |= sample->normals() != prevSample->normals(); uvsDirty |= sample->uvs() != prevSample->uvs(); } if (wiresDirty || trianglesDirty || positionsDirty || normalsDirty || uvsDirty) { if (wiresDirty) { wireVertIndices = boost::shared_array<index_t>( new index_t[2 * totalWires]); } if (trianglesDirty) { triangleVertIndices.resize(totalTriangles.size()); for (size_t i = 0; i < totalTriangles.size(); i++) { triangleVertIndices[i] = boost::shared_array<index_t>( new index_t[3 * totalTriangles[i]]); } } if (positionsDirty) { positions = boost::shared_array<float>( new float[3 * totalVerts]); } if (normalsDirty) { normals = boost::shared_array<float>( new float[3 * totalVerts]); } if (uvsDirty) { uvs.reset(); if (uvExists) { uvs = boost::shared_array<float>( new float[2 * totalVerts]); } } boundingBox.clear(); { size_t wireIdx = 0; size_t vertIdx = 0; std::vector<size_t> triangleIdx(numIndexGroups, 0); for (size_t i = 0; i < nbShapes; i++) { const boost::shared_ptr<const ShapeSample>& sample = consolidatedShapes[i]->getSample(*timeIt); const size_t numWires = sample->numWires(); const size_t numVerts = sample->numVerts(); // Wires if (wiresDirty && sample->wireVertIndices()) { IndexBuffer::ReadInterfacePtr readable = sample->wireVertIndices()->readableInterface(); const index_t* srcWireVertIndices = readable->get(); for (size_t j = 0; j < numWires; j++) { wireVertIndices[2*(j + wireIdx) + 0] = index_t(srcWireVertIndices[2*j + 0] + vertIdx); wireVertIndices[2*(j + wireIdx) + 1] = index_t(srcWireVertIndices[2*j + 1] + vertIdx); } } // Triangles if (trianglesDirty) { for (size_t group = 0; group < numIndexGroups; group++) { const size_t numTriangles = sample->numTriangles(group); if (sample->triangleVertIndices(group)) { IndexBuffer::ReadInterfacePtr readable = sample->triangleVertIndices(group)->readableInterface(); const index_t* srcTriangleVertIndices = readable->get(); for (size_t j = 0; j < numTriangles; j++) { triangleVertIndices[group][3*(j + triangleIdx[group]) + 0] = index_t(srcTriangleVertIndices[3*j + 0] + vertIdx); triangleVertIndices[group][3*(j + triangleIdx[group]) + 1] = index_t(srcTriangleVertIndices[3*j + 1] + vertIdx); triangleVertIndices[group][3*(j + triangleIdx[group]) + 2] = index_t(srcTriangleVertIndices[3*j + 2] + vertIdx); } } } } // Positions if (positionsDirty && sample->positions()) { VertexBuffer::ReadInterfacePtr readable = sample->positions()->readableInterface(); memcpy(&positions[3*vertIdx], readable->get(), 3*numVerts*sizeof(float)); } // Normals if (normalsDirty && sample->normals()) { VertexBuffer::ReadInterfacePtr readable = sample->normals()->readableInterface(); memcpy(&normals[3*vertIdx], readable->get(), 3*numVerts*sizeof(float)); } // UVs if (uvsDirty) { if (sample->uvs()) { VertexBuffer::ReadInterfacePtr readable = sample->uvs()->readableInterface(); memcpy(&uvs[2*vertIdx], readable->get(), 2*numVerts*sizeof(float)); } else if (uvExists) { memset(&uvs[2*vertIdx], 0, 2*numVerts*sizeof(float)); } } wireIdx += numWires; vertIdx += numVerts; for (size_t i = 0; i < numIndexGroups; i++) { triangleIdx[i] += sample->numTriangles(i); } boundingBox.expand(sample->boundingBox()); } // for each nodes } } // if anything dirty std::vector<boost::shared_ptr<IndexBuffer> > newTriangleVertIndices(numIndexGroups); for (size_t i = 0; i < numIndexGroups; i++) { newTriangleVertIndices[i] = IndexBuffer::create( SharedArray<index_t>::create( triangleVertIndices[i], 3 * totalTriangles[i])); } boost::shared_ptr<ShapeSample> newSample = ShapeSample::create( *timeIt, totalWires, totalVerts, IndexBuffer::create( SharedArray<index_t>::create( wireVertIndices, 2 * totalWires)), newTriangleVertIndices, VertexBuffer::createPositions( SharedArray<float>::create( positions, 3 * totalVerts)), boundingBox, diffuseColor, visibility); if (normals) { newSample->setNormals( VertexBuffer::createNormals( SharedArray<float>::create( normals, 3 * totalVerts))); } if (uvs) { newSample->setUVs( VertexBuffer::createUVs( SharedArray<float>::create( uvs, 2 * totalVerts))); } newShape->addSample(newSample); timePrev = timeIt; } // All consolidated shapes should have the same materials. newShape->setMaterials(consolidatedShapes[0]->getMaterials()); // Re-use the largest node infos. newShapes.push_back(newShape); consolidatedShapes.clear(); } SubNode::MPtr fRootNode; const int fThreshold; const bool fMotionBlur; SubNode::MPtr fConsolidatedRootNode; }; //============================================================================== // CLASS SelectionChecker //============================================================================== class SelectionChecker { public: SelectionChecker(const MSelectionList& selection) { MStatus status; MDagPath dagPath; // A selected node should be ignored // if its parent/grandparent is selected. for (unsigned int i = 0; i < selection.length(); i++) { status = selection.getDagPath(i, dagPath); if (status == MS::kSuccess) { std::string fullDagPath = dagPath.fullPathName().asChar(); fSelectionPaths.insert(fullDagPath); } } // Check each selected DAG Path for (unsigned int i = 0; i < selection.length(); i++) { status = selection.getDagPath(i, dagPath); if (status == MS::kSuccess && check(dagPath)) { fSelection.add(dagPath); } } } const MSelectionList& selection() { return fSelection; } private: // Prohibited and not implemented. SelectionChecker(const SelectionChecker&); const SelectionChecker& operator= (const SelectionChecker&); bool check(const MDagPath& dagPath) { // This node should not have its parent/grandparent selected MDagPath parent = dagPath; parent.pop(); for (; parent.length() > 0; parent.pop()) { std::string fullDagPath = parent.fullPathName().asChar(); if (fSelectionPaths.find(fullDagPath) != fSelectionPaths.end()) { return false; } } return checkGeometry(dagPath); } bool checkGeometry(const MDagPath& dagPath) { // Check we have bakeable geometry MFnDagNode dagNode(dagPath); MObject object = dagPath.node(); if ((Baker::isBakeable(object) || dagNode.typeId() == ShapeNode::id) && !object.hasFn(MFn::kTransform)) { return true; } // At least one descendant must be bakeable geometry bool hasGeometry = false; for (unsigned int i = 0; i < dagPath.childCount(); i++) { MDagPath child = dagPath; child.push(dagPath.child(i)); MFnDagNode childNode(child); if (childNode.isIntermediateObject()) { continue; } if (checkGeometry(child)) { hasGeometry= true; break; } } return hasGeometry; } MSelectionList fSelection; std::set<std::string> fSelectionPaths; }; //============================================================================== // CLASS ScopedPauseWorkerThread //============================================================================== class ScopedPauseWorkerThread : boost::noncopyable { public: ScopedPauseWorkerThread() { GlobalReaderCache::theCache().pauseRead(); } ~ScopedPauseWorkerThread() { GlobalReaderCache::theCache().resumeRead(); } }; //============================================================================== // CLASS FileAndSubNodeList //============================================================================== // This is a list of files and corresponding hierarchy roots. // The dummy flag means that the top-level transform is a dummy sub-node. The // dummy sub-node should be ignored and its children should be written instead. class FileAndSubNode { public: MFileObject targetFile; SubNode::MPtr subNode; bool isDummy; FileAndSubNode() : isDummy(false) {} FileAndSubNode(const MFileObject& f, const SubNode::MPtr& n, bool d) : targetFile(f), subNode(n), isDummy(d) {} }; typedef std::vector<FileAndSubNode> FileAndSubNodeList; //============================================================================== // CLASS NodePathRegistry //============================================================================== // This class is responsible for re-constructing the sub-node hierarchy // according to the original dag paths. // This class should encapsulate all the logic to determine the file paths. // // If we are going to write a single hierarchy, // targetFile = [directory] / [filePrefix] [fileName] [extension] // // Assuming we are going to bake the following hierarchies: // |-A // |-B // |-C // |-D // We have 4 dag paths: |A, |A|B, |C and |C|D. // In this case, we have two hierarchy roots: |A and |C // // 1) Either -allDagObjects or -saveMultipleFiles false is specified. // We are going to write two hierarchies to a single file. // targetFile = [directory] / [filePrefix] [fileName] [extension] // e.g. ... / filename_specified_by_fileName_arg.abc // (containing |A, |A|B, |C and |C|D) // // 2) -saveMultipleFiles true is specified. (default) // We are going to write two hierarchies to two files. // 2.1) -clashOption numericalIncrement // targetFile = [directory] / [filePrefix] [numericalIncrement] [extension] // e.g. ... / scene1_0.abc (containing |A and |A|B) // ... / scene1_1.abc (containing |C and |C|D) // // 2.2) -clashOption nodeName (default) // targetFile = [directory] / [filePrefix] [nodeName] [extension] // [nodeName] is the name of the dag node. If there is any conflicts, the // full dag path is used as [nodeName]. // e.g. ... / scene1_A.abc (containing |A and |A|B) // ... / scene1_C.abc (containing |C and |C|D) // class NodePathRegistry : boost::noncopyable { public: enum Stages { kResolveStage, // Adding MDagPath objects. kConstructStage, // Adding sub-node objects. kComplete // Get a list of files and hierarchy roots. }; NodePathRegistry(const bool allDagObjects, const bool saveMultipleFiles, const MString& directory, const MString& filePrefix, const MString& fileName, const MString& clashOption) : fStage(kResolveStage), fAllDagObjects(allDagObjects), fSaveMultipleFiles(saveMultipleFiles), fDirectory(directory), fFilePrefix(filePrefix), fFileName(fileName), fClashOption(clashOption), fExtension(".abc") {} ~NodePathRegistry() {} // Add a MDagPath object to this class. When all MDagPath objects are added, // call resolve() to move to the next stage. void add(const MDagPath& dagPath) { // We can only add dag paths at resolve stage. assert(fStage == kResolveStage); assert(dagPath.isValid()); // The full path name of this dag path. std::string fullPath = fullPathName(dagPath); assert(fPathMap.find(fullPath) == fPathMap.end()); // The full path name of the parent dag path. MDagPath parentPath = dagPath; parentPath.pop(); std::string parentFullPath = fullPathName(parentPath); // Insert into path map. PathEntry pathEntry; pathEntry.dagPath = dagPath; pathEntry.parentPath = parentFullPath; fPathMap[fullPath] = pathEntry; } // Determine the hierarchy roots and file names based on all input dag paths. // Resolve the hierarchy root node name conflict. void resolve() { // We should be at resolve stage. assert(fStage == kResolveStage); fStage = kConstructStage; // Find all hierarchy root nodes. BOOST_FOREACH (const PathMapType::value_type& v, fPathMap) { // If the path doesn't have a parent, it's a hierarchy root. PathMapType::const_iterator it = fPathMap.find(v.second.parentPath); if (it == fPathMap.end()) { assert(fRootMap.find(v.first) == fRootMap.end()); // Get the node name. MFnDagNode dagNode(v.second.dagPath); std::string nodeName = dagNode.name().asChar(); // Strip namespace ":" character. std::replace(nodeName.begin(), nodeName.end(), ':', '_'); // Insert into root map. RootEntry rootEntry; rootEntry.nodeName = nodeName; rootEntry.uniqueName = "Not_Specified"; rootEntry.sequence = std::numeric_limits<size_t>::max(); rootEntry.overwrite = true; fRootMap[v.first] = rootEntry; } } // Count the occurance of base names of the hierarchy roots. std::map<std::string,size_t> nameTable; // name -> occurance BOOST_FOREACH (const RootMapType::value_type& v, fRootMap) { nameTable.insert(std::make_pair(v.second.nodeName, 0)).first->second++; } // Resolve root node name conflicts and compute sequences. size_t counter = 0; BOOST_FOREACH (RootMapType::value_type& v, fRootMap) { std::string uniqueName = v.second.nodeName; // The name conflicts with other names. // We use full path instead of its name. if (nameTable.find(uniqueName)->second > 1) { uniqueName = v.first.substr(1); // remove leading | std::replace(uniqueName.begin(), uniqueName.end(), '|', '_'); std::replace(uniqueName.begin(), uniqueName.end(), ':', '_'); } v.second.uniqueName = uniqueName; v.second.sequence = counter++; } // Determine the directory we are going to export. const bool singleFile = fAllDagObjects || !fSaveMultipleFiles || fRootMap.size() == 1; const MString directory = validatedDirectory(); const MString fileName = validatedFileName(); // Determine the absolute file path for hierarchy roots. BOOST_FOREACH (RootMapType::value_type& v, fRootMap) { MString targetFileName = fFilePrefix; if (singleFile) { // We are going to save to a single file. targetFileName += fileName; } else { // We are going to save each hierarchy root to a separate file. if (fClashOption == "numericalIncrement") { // Clash Option: Numerical Increment targetFileName += (unsigned int)v.second.sequence; } else { // Clash Option: Node Name targetFileName += v.second.uniqueName.c_str(); } } MString targetFullName = directory + "/" + targetFileName + fExtension; v.second.targetFile.setRawFullName(targetFullName); } } // Pop up a dialog to prompt the user we are going to overwrite the file. void promptOverwrite() { // We have resolved hierarchy roots and their target files. assert(fStage == kConstructStage); // Make sure we have the dialog proc. MGlobal::executeCommand( "if (!(`exists showGpuCacheExportConfirmDialog`))\n" "{\n" " eval(\"source \\\"doGpuCacheExportArgList.mel\\\"\");\n" "}\n" ); // Prompt every file or we remember the choice. const bool singleFile = fAllDagObjects || !fSaveMultipleFiles || fRootMap.size() == 1; enum OverwriteChoice { kUnknownOverwrite, kAlwaysOverwrite, kNeverOverwrite }; OverwriteChoice choice = kUnknownOverwrite; BOOST_FOREACH (RootMapType::value_type& v, fRootMap) { // Skip non-exist files. if (!v.second.targetFile.exists()) continue; if (choice == kUnknownOverwrite) { // Show the dialog. MString result = MGlobal::executeCommandStringResult( "showGpuCacheExportConfirmDialog \"" + EncodeString(v.second.targetFile.resolvedFullName()) + "\"" ); if (result == "yes") { // Overwrite this file. v.second.overwrite = true; // All hierarchy roots are going to be written to a single file. // Pop up the dialog only once for all hierarchy roots. if (singleFile) choice = kAlwaysOverwrite; } else if (result == "no") { // Skip this file. v.second.overwrite = false; // All hierarchy roots are going to be written to a single file. // Pop up the dialog only once for all hierarchy roots. if (singleFile) choice = kNeverOverwrite; } else if (result == "yesAll") { // Overwrite this file and all following files. v.second.overwrite = true; choice = kAlwaysOverwrite; } else if (result == "noAll" || result == "dismiss") { // Skip this file and all following files. v.second.overwrite = false; choice = kNeverOverwrite; } else { // Something goes wrong with the dialog proc. // We assume overwrite. assert(0); } } else if (choice == kAlwaysOverwrite) { v.second.overwrite = true; } else if (choice == kNeverOverwrite) { v.second.overwrite = false; } else { assert(0); } } } // Associate the sub-node with the MDagPath object. void associateSubNode(const MDagPath& dagPath, const SubNode::MPtr& subNode) { assert(fStage == kConstructStage); assert(dagPath.isValid()); assert(subNode); // Set the sub node member. std::string fullPath = fullPathName(dagPath); PathMapType::iterator it = fPathMap.find(fullPath); assert(it != fPathMap.end()); if (it != fPathMap.end()) { it->second.subNode = subNode; } } // Construct sub-node hierarchy according to the MDagPath hierarchy. void constructHierarchy() { assert(fStage == kConstructStage); fStage = kComplete; // Connect child with its parent. // Instances are already expanded. BOOST_FOREACH (const PathMapType::value_type& v, fPathMap) { // Find this sub node. const SubNode::MPtr& thisSubNode = v.second.subNode; // Find parent sub node. PathMapType::iterator parentIt = fPathMap.find(v.second.parentPath); if (parentIt != fPathMap.end()) { // Find a parent, connect them. const SubNode::MPtr& parentSubNode = parentIt->second.subNode; SubNode::connect(parentSubNode, thisSubNode); } else { // This must be a hierarchy root. RootMapType::iterator rootIt = fRootMap.find(v.first); assert(rootIt != fRootMap.end()); if (rootIt != fRootMap.end()) { rootIt->second.subNode = thisSubNode; } } } } // Get a list of file paths and corresponding hierarchy root sub-node. void generateFileAndSubNodes(FileAndSubNodeList& list) { // Sub-node hierarchies are ready. assert(fStage == kComplete); // When -allDagObjects is set, we are going to save all dag objects in // the scene to a single file. // When -saveMultipleFiles is false, we are going to save all selected // dag objects to a single file. // In both cases, we need to create a dummy root node ("|") for root nodes. if (fAllDagObjects || !fSaveMultipleFiles) { if (!fRootMap.empty() && fRootMap.begin()->second.overwrite) { // Create the "|" node GroupCreator groupCreator; BOOST_FOREACH (const RootMapType::value_type& v, fRootMap) { // We are going to write root nodes to a single file. // To prevent root node name clash, we bake the unique name to the root node. v.second.subNode->setName(v.second.uniqueName.c_str()); // Add the root node to the dummy group. groupCreator.addChild(v.second.subNode); } groupCreator.group(); // Replace all nodes with a single "|" node. // If there is one node, we use the node name as the "|" node name. // If there are more than one node, we use the scene name as the "|" node name. const RootEntry& rootEntry = fRootMap.begin()->second; const MString rootNodeName = (fRootMap.size() == 1) ? rootEntry.subNode->getName() : getSceneNameAsValidObjectName(); // Only one file. list.push_back(FileAndSubNode( rootEntry.targetFile, groupCreator.getSubNode(rootNodeName), true /* isDummy */ )); } } else { // One hierarchy root to one file. BOOST_FOREACH (const RootMapType::value_type& v, fRootMap) { // Skip files that we are not going to overwrite. if (!v.second.overwrite) continue; list.push_back(FileAndSubNode( v.second.targetFile, v.second.subNode, false /* isDummy */ )); } } } void dump() { using namespace std; stringstream out; out << "Current Stage: "; switch (fStage) { case kResolveStage: out << "ResolveStage"; break; case kConstructStage: out << "ConstructStage"; break; case kComplete: out << "Complete"; break; } out << endl; out << "Path Map: " << endl; BOOST_FOREACH (const PathMapType::value_type& v, fPathMap) { out << "Path: " << v.first << ", Parent: " << v.second.parentPath << ", SubNode: " << (void*)v.second.subNode.get() << endl; } out << "Root Map: " << endl; BOOST_FOREACH (const RootMapType::value_type& v, fRootMap) { out << "Path: " << v.first << ", Node: " << v.second.nodeName << ", Unique: " << v.second.uniqueName << ", Sequence: " << v.second.sequence << ", Overwrite: " << v.second.overwrite << ", Target: " << v.second.targetFile.resolvedFullName().asChar() << ", SubNode: " << (void*)v.second.subNode.get() << endl; } cout << out.str() << endl; } private: static std::string fullPathName(const MDagPath& dagPath) { MString buffer = dagPath.fullPathName(); return std::string(buffer.asChar()); } MString validatedDirectory() { MFileObject directory; if (fDirectory.length() > 0) { // If there is a directory specified, we use that directory. directory.setRawFullName(fDirectory); } else { MString fileRule, expandName; const MString alembicFileRule = "alembicCache"; const MString alembicFilePath = "cache/alembic"; MString queryFileRuleCmd; queryFileRuleCmd.format("workspace -q -fre \"^1s\"", alembicFileRule); MString queryFolderCmd; queryFolderCmd.format("workspace -en `workspace -q -fre \"^1s\"`", alembicFileRule); // Query the file rule for alembic cache MGlobal::executeCommand(queryFileRuleCmd, fileRule); if (fileRule.length() > 0) { // We have alembic file rule, query the folder MGlobal::executeCommand(queryFolderCmd, expandName); } else { // Alembic file rule does not exist, create it MString addFileRuleCmd; addFileRuleCmd.format("workspace -fr \"^1s\" \"^2s\"", alembicFileRule, alembicFilePath); MGlobal::executeCommand(addFileRuleCmd); // Save the workspace. maya may discard file rules on exit MGlobal::executeCommand("workspace -s"); // Query the folder MGlobal::executeCommand(queryFolderCmd, expandName); } // Resolve the expanded file rule if (expandName.length() == 0) { expandName = alembicFilePath; } directory.setRawFullName(expandName); } return directory.resolvedFullName(); } MString validatedFileName() { MString fileName; if (fFileName.length() > 0) { // If there is a file name specified, we use that file name. fileName = fFileName; } else { // Generate a default file name. if (fRootMap.size() == 1) { fileName = fRootMap.begin()->second.uniqueName.c_str(); } else { fileName = getSceneName(); } } return fileName; } // This map contains name/path info for all dag paths. struct PathEntry { MDagPath dagPath; std::string parentPath; SubNode::MPtr subNode; }; typedef boost::unordered_map<std::string,PathEntry> PathMapType; // This map contains name/path info for all hierarchy roots. struct RootEntry { std::string nodeName; std::string uniqueName; size_t sequence; bool overwrite; MFileObject targetFile; SubNode::MPtr subNode; }; typedef boost::unordered_map<std::string,RootEntry> RootMapType; Stages fStage; PathMapType fPathMap; RootMapType fRootMap; const bool fAllDagObjects; const bool fSaveMultipleFiles; const MString fDirectory; const MString fFilePrefix; const MString fFileName; const MString fClashOption; const MString fExtension; }; } namespace GPUCache { //============================================================================== // CLASS Command //============================================================================== void* Command::creator() { return new Command(); } MSyntax Command::cmdSyntax() { MSyntax syntax; syntax.addFlag("-dir", "-directory", MSyntax::kString ); syntax.addFlag("-f", "-fileName", MSyntax::kString ); syntax.addFlag("-smf", "-saveMultipleFiles", MSyntax::kBoolean ); syntax.addFlag("-fp", "-filePrefix", MSyntax::kString ); syntax.addFlag("-clo", "-clashOption", MSyntax::kString ); syntax.addFlag("-o", "-optimize" ); syntax.addFlag("-ot", "-optimizationThreshold", MSyntax::kUnsigned ); syntax.addFlag("-st", "-startTime", MSyntax::kTime ); syntax.addFlag("-et", "-endTime", MSyntax::kTime ); syntax.addFlag("-smr", "-simulationRate", MSyntax::kTime ); syntax.addFlag("-spm", "-sampleMultiplier", MSyntax::kLong ); syntax.addFlag("-cl", "-compressLevel", MSyntax::kLong ); syntax.addFlag("-df", "-dataFormat", MSyntax::kString ); syntax.addFlag("-sf", "-showFailed" ); syntax.addFlag("-ss", "-showStats" ); syntax.addFlag("-sgs", "-showGlobalStats" ); syntax.addFlag("-dh", "-dumpHierarchy", MSyntax::kString ); syntax.addFlag("-atr", "-animTimeRange" ); syntax.addFlag("-gma", "-gpuManufacturer" ); syntax.addFlag("-gmo", "-gpuModel" ); syntax.addFlag("-gdv", "-gpuDriverVersion" ); syntax.addFlag("-gms", "-gpuMemorySize" ); syntax.addFlag("-ado", "-allDagObjects" ); syntax.addFlag("-r", "-refresh" ); syntax.addFlag("-ra", "-refreshAll" ); syntax.addFlag("-rs", "-refreshSettings" ); syntax.addFlag("-wbr", "-waitForBackgroundReading" ); syntax.addFlag("-wm", "-writeMaterials" ); syntax.addFlag("-wuv", "-writeUVs" ); syntax.addFlag("-omb", "-optimizeAnimationsForMotionBlur" ); syntax.addFlag("-ubt", "-useBaseTessellation" ); syntax.addFlag("-p", "-prompt" ); syntax.addFlag("-lfe", "-listFileEntries" ); syntax.addFlag("-lse", "-listShapeEntries" ); syntax.makeFlagQueryWithFullArgs("-dumpHierarchy", true); syntax.useSelectionAsDefault(true); syntax.setObjectType(MSyntax::kSelectionList, 0); syntax.enableQuery(true); syntax.enableEdit(true); return syntax; } Command::Command() : fMode(kCreate) {} Command::~Command() {} bool Command::isUndoable() const { return false; } bool Command::hasSyntax() const { return true; } void Command::AddHierarchy( const MDagPath& dagPath, std::map<std::string, int>* idMap, std::vector<MObject>* sourceNodes, std::vector<std::vector<MDagPath> >* sourcePaths, std::vector<MObject>* gpuCacheNodes) { MFnDagNode dagNode(dagPath.node()); MDagPath firstDagPath; MStatus status = dagNode.getPath(firstDagPath); if (status != MS::kSuccess) return; std::string firstPath(firstDagPath.partialPathName().asChar()); std::map<std::string, int>::iterator pos = idMap->find(firstPath); if (pos != idMap->end()){ // Already traversed. Only store its DAG Path. (*sourcePaths)[pos->second].push_back(dagPath); } else { MObject object(dagNode.object()); MString msgFmt; bool isWarning = true; if (dagNode.typeId() == ShapeNode::id) { if (fMode == kCreate) { // Recursive bake a gpuCache node (*idMap)[firstPath] = (int)sourceNodes->size(); sourceNodes->push_back(object); sourcePaths->push_back(std::vector<MDagPath>(1, dagPath)); } else { // Query flag is set gpuCacheNodes->push_back(object); } } else if (Baker::isBakeable(object)) { (*idMap)[firstPath] = (int)sourceNodes->size(); sourceNodes->push_back(object); sourcePaths->push_back(std::vector<MDagPath>(1, dagPath)); if (fMode != kCreate && fShowFailedFlag.isSet()) { MStatus status; msgFmt = MStringResource::getString(kNodeWontBakeErrorMsg, status); } } else if (fShowFailedFlag.isSet()) { MStatus status; msgFmt = MStringResource::getString(kNodeBakedFailedErrorMsg, status); } if (msgFmt.length() > 0) { MString nodeName = firstDagPath.fullPathName(); MString msg; msg.format(msgFmt, nodeName); if (isWarning) { MGlobal::displayWarning(msg); } else { MGlobal::displayInfo(msg); } } } unsigned int numChild = dagPath.childCount(); for(unsigned int i = 0; i < numChild; ++i) { MDagPath childPath = dagPath; childPath.push(dagPath.child(i)); MFnDagNode childNode(childPath); if (!childNode.isIntermediateObject()) AddHierarchy(childPath, idMap, sourceNodes, sourcePaths, gpuCacheNodes); } } bool Command::AddSelected( const MSelectionList& objects, std::vector<MObject>* sourceNodes, std::vector<std::vector<MDagPath> >* sourcePaths, std::vector<MObject>* gpuCacheNodes) { MStatus status; // map first DAG path to node index std::map<std::string, int> idMap; for (unsigned int i = 0; i<objects.length(); ++i) { MDagPath sourceDagPath; status = objects.getDagPath(i, sourceDagPath); if (status == MS::kSuccess) { AddHierarchy(sourceDagPath, &idMap, sourceNodes, sourcePaths, gpuCacheNodes); } } if (fMode == kCreate) { if (sourceNodes->empty()) { MStatus stat; MString msg; if (gpuCacheNodes->empty()) { msg = MStringResource::getString(kNoObjBakable2ErrorMsg, stat); } else { msg = MStringResource::getString(kNoObjBakable1ErrorMsg, stat); } displayWarning(msg); return false; } return true; } else { if (!fRefreshSettingsFlag.isSet() && gpuCacheNodes->empty()) { MStatus stat; MString msg; if (sourceNodes->empty()) { msg = MStringResource::getString(kNoObjBaked2ErrorMsg, stat); } else { msg = MStringResource::getString(kNoObjBaked1ErrorMsg, stat); } displayWarning(msg); return false; } return true; } } MStatus Command::doIt(const MArgList& args) { MStatus status; MArgDatabase argsDb(syntax(), args, &status); if (!status) return status; unsigned int numFlags = 0; // Save the command arguments for undo/redo purposes. if (argsDb.isEdit()) { if (argsDb.isQuery()) { MStatus stat; MString msg = MStringResource::getString(kEditQueryFlagErrorMsg, stat); displayError(msg); return MS::kFailure; } fMode = kEdit; numFlags++; } else if (argsDb.isQuery()) { fMode = kQuery; numFlags++; } numFlags += fDirectoryFlag.parse(argsDb, "-directory"); if (!fDirectoryFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kDirectoryWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fFileNameFlag.parse(argsDb, "-fileName"); if (!fFileNameFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kFileNameWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fSaveMultipleFilesFlag.parse(argsDb, "-saveMultipleFiles"); if (!fSaveMultipleFilesFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kSaveMultipleFilesWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fFilePrefixFlag.parse(argsDb, "-filePrefix"); if (!fFilePrefixFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kFilePrefixWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fClashOptionFlag.parse(argsDb, "-clashOption"); if (!fClashOptionFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kClashOptionWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fOptimizeFlag.parse(argsDb, "-optimize"); if (!fOptimizeFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kOptimizeWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fOptimizationThresholdFlag.parse(argsDb, "-optimizationThreshold"); if (!fOptimizationThresholdFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kOptimizationThresholdWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fStartTimeFlag.parse(argsDb, "-startTime"); if (!fStartTimeFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kStartTimeWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fEndTimeFlag.parse(argsDb, "-endTime"); if (!fEndTimeFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kEndTimeWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fSimulationRateFlag.parse(argsDb, "-simulationRate"); if (!fSimulationRateFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kSimulationRateWrongModeMsg, stat); displayError(msg); return MS::kFailure; } if (fSimulationRateFlag.isSet()) { MTime minRate(0.004, MTime::kFilm); if (fSimulationRateFlag.arg() < minRate) { // Simulation rate was below 1 tick, issue an appropriate error message. MStatus stat; MString msg, fmt = MStringResource::getString(kSimulationRateWrongValueMsg, stat); msg.format(fmt, MString() + minRate.as(MTime::uiUnit())); displayError(msg); return MS::kFailure; } } numFlags += fSampleMultiplierFlag.parse(argsDb, "-sampleMultiplier"); if (!fSampleMultiplierFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kSampleMultiplierWrongModeMsg, stat); displayError(msg); return MS::kFailure; } if (fSampleMultiplierFlag.isSet() && fSampleMultiplierFlag.arg() <= 0) { MStatus stat; MString msg = MStringResource::getString(kSampleMultiplierWrongValueMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fCompressLevelFlag.parse(argsDb, "-compressLevel"); if (!fCompressLevelFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kCompressLevelWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fDataFormatFlag.parse(argsDb, "-dataFormat"); if (!fDataFormatFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kDataFormatWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fShowFailedFlag.parse(argsDb, "-showFailed"); assert(fShowFailedFlag.isModeValid(fMode)); numFlags += fShowStats.parse(argsDb, "-showStats"); assert(fShowStats.isModeValid(fMode)); numFlags += fShowGlobalStats.parse(argsDb, "-showGlobalStats"); assert(fShowGlobalStats.isModeValid(fMode)); numFlags += fDumpHierarchy.parse(argsDb, "-dumpHierarchy"); assert(fDumpHierarchy.isModeValid(fMode)); numFlags += fAnimTimeRangeFlag.parse(argsDb, "-animTimeRange"); if (!fAnimTimeRangeFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kAnimTimeRangeWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fAllDagObjectsFlag.parse(argsDb, "-allDagObjects"); if (!fAllDagObjectsFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kAllDagObjectsWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fRefreshFlag.parse(argsDb, "-refresh"); if (!fRefreshFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kRefreshWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fRefreshAllFlag.parse(argsDb, "-refreshAll"); if (!fRefreshAllFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kRefreshAllWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fListFileEntriesFlag.parse(argsDb, "-listFileEntries"); if (!fListFileEntriesFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kListFileEntriesWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fListShapeEntriesFlag.parse(argsDb, "-listShapeEntries"); if (!fListShapeEntriesFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kListShapeEntriesWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fRefreshSettingsFlag.parse(argsDb, "-refreshSettings"); if (!fRefreshSettingsFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kRefreshSettingsWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fGpuManufacturerFlag.parse(argsDb, "-gpuManufacturer"); if (!fGpuManufacturerFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kGpuManufacturerWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fGpuModelFlag.parse(argsDb, "-gpuModel"); if (!fGpuModelFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kGpuModelWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fGpuDriverVersion.parse(argsDb, "-gpuDriverVersion"); if (!fGpuDriverVersion.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kGpuDriverVersionWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fGpuMemorySize.parse(argsDb, "-gpuMemorySize"); if (!fGpuMemorySize.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kGpuMemorySizeWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fWaitForBackgroundReadingFlag.parse(argsDb, "-waitForBackgroundReading"); if (!fWaitForBackgroundReadingFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kWaitForBackgroundReadingWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fWriteMaterials.parse(argsDb, "-writeMaterials"); if (!fWriteMaterials.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kWriteMaterialsWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fUVsFlag.parse(argsDb, "-writeUVs"); if( !fUVsFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kWriteUVsWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fOptimizeAnimationsForMotionBlurFlag.parse(argsDb, "-optimizeAnimationsForMotionBlur"); if (!fOptimizeAnimationsForMotionBlurFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kOptimizeAnimationsForMotionBlurWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fUseBaseTessellationFlag.parse(argsDb, "-useBaseTessellation"); if (!fUseBaseTessellationFlag.isModeValid(fMode)) { MStatus stat; MString msg = MStringResource::getString(kUseBaseTessellationWrongModeMsg, stat); displayError(msg); return MS::kFailure; } numFlags += fPromptFlag.parse(argsDb, "-prompt"); if (fRefreshAllFlag.isSet()) { // Ideally, we would use MArgParser to determine number of other flags used. // However, MArgParser returns an error when usesSelectionAsDefault() == true // and no objects are found. // // Instead, we manually test for the presence of other flags. if( numFlags > 1 ) { MStatus stat; MString msg = MStringResource::getString(kRefreshAllOtherFlagsMsg, stat); displayError(msg); return MS::kFailure; } refreshAll(); return MS::kSuccess; } if (fListFileEntriesFlag.isSet()) { if( numFlags > 1 ) { MStatus stat; MString msg = MStringResource::getString(kListFileEntriesOtherFlagsMsg, stat); displayError(msg); return MS::kFailure; } listFileEntries(); return MS::kSuccess; } if (fListShapeEntriesFlag.isSet()) { if( numFlags > 1 ) { MStatus stat; MString msg = MStringResource::getString(kListShapeEntriesOtherFlagsMsg, stat); displayError(msg); return MS::kFailure; } listShapeEntries(); return MS::kSuccess; } // Backup the current selection MSelectionList selectionBackup; MGlobal::getActiveSelectionList(selectionBackup); MSelectionList objects; if (fAllDagObjectsFlag.isSet()) { // -allDagObjects flag is set, export all the top-level DAG Nodes MStringArray result; MGlobal::executeCommand("ls -assemblies -long", result); for (unsigned int i = 0; i < result.length(); i++) { objects.add(result[i]); } } else { // -allDagObjects flag is not set, export the selection or gpuCache arguments // Duplicates are removed by merge(). MSelectionList selectedObjectArgs; status = argsDb.getObjects(selectedObjectArgs); MStatError(status, "argsDb.getObjects()"); if (!selectedObjectArgs.isEmpty()) { status = objects.merge(selectedObjectArgs, MSelectionList::kMergeNormal); MStatError(status, "objects.merge()"); } } if (objects.length() == 0 && !(fMode == kQuery && fShowGlobalStats.isSet()) && !(fMode == kEdit && fRefreshSettingsFlag.isSet()) && !(fMode == kQuery && fGpuManufacturerFlag.isSet()) && !(fMode == kQuery && fGpuModelFlag.isSet()) && !(fMode == kQuery && fGpuDriverVersion.isSet()) && !(fMode == kQuery && fGpuMemorySize.isSet()) ) { MString msg = MStringResource::getString(kNoObjectsMsg,status); MPxCommand::displayError(msg); return MS::kFailure; } { SelectionChecker selectionChecker(objects); objects = selectionChecker.selection(); } std::vector<MObject> sourceNodes; std::vector<std::vector<MDagPath> > sourcePaths; std::vector<MObject> gpuCacheNodes; if (fMode == kCreate || fMode == kEdit || fShowStats.isSet() || fDumpHierarchy.isSet() || fAnimTimeRangeFlag.isSet() || fWaitForBackgroundReadingFlag.isSet()) { if (!AddSelected(objects, &sourceNodes, &sourcePaths, &gpuCacheNodes)) return MS::kFailure; } // We flush the selection list before executing any MEL command // through MDGModifier::commandToExecute. This saves a LOT of // memory!!! This is due to the fact that each executed MEL // command might take a copy of the selection list to restore it // on undo. But, this is totally unnecessary since we invoking // them from another MEL command that already takes care of // restoring the selection list on undo!!! MGlobal::setActiveSelectionList(MSelectionList(), MGlobal::kReplaceList); switch (fMode) { case kCreate: status = doCreate(sourceNodes, sourcePaths, objects); break; case kEdit: status = doEdit(gpuCacheNodes); break; case kQuery: status = doQuery(gpuCacheNodes); break; } // Restore the selection. MGlobal::setActiveSelectionList(selectionBackup, MGlobal::kReplaceList); return status; } MStatus Command::doCreate(const std::vector<MObject>& sourceNodes, const std::vector<std::vector<MDagPath> >& sourcePaths, const MSelectionList& objects) { MStatus status; // Compute the baked mesh before committing the Dag modifier so // that the Dag modifier includes the baking. MCheckReturn( Command::doBaking( sourceNodes, sourcePaths, fStartTimeFlag.arg(MAnimControl::animationStartTime()), fEndTimeFlag.arg(MAnimControl::animationEndTime()), fSimulationRateFlag.arg(MTime(1, MTime::uiUnit())), fSampleMultiplierFlag.arg(1))); return MS::kSuccess; } MStatus Command::doQuery(const std::vector<MObject>& gpuCacheNodes) const { // set the result of gpuCache command if (fShowStats.isSet() || fShowGlobalStats.isSet() || fDumpHierarchy.isSet() ) { // String array result is incompatible with double[2] if (fAnimTimeRangeFlag.isSet()) { MStatus stat; MString msg = MStringResource::getString(kIncompatibleQueryMsg,stat); MPxCommand::displayError(msg); return MS::kFailure; } MStringArray result; if (fShowStats.isSet()) { showStats(gpuCacheNodes, result); } if (fShowGlobalStats.isSet()) { showGlobalStats(result); } if (fDumpHierarchy.isSet()) { if (fDumpHierarchy.isArgValid()) { // Dump to a text file MFileObject file; file.setRawFullName(fDumpHierarchy.arg()); MCheckReturn( dumpHierarchyToFile(gpuCacheNodes, file) ); result.append("Dumping hierarchy to: " + file.resolvedFullName()); } else { // Dump to script editor dumpHierarchy(gpuCacheNodes, result); } } { MString output; for (unsigned int i = 0; i < result.length(); i++) { if (i > 0) output += "\n"; output += result[i]; } MPxCommand::setResult(output); } } else if (fAnimTimeRangeFlag.isSet()) { // -animTimeRange will return double[2] in current time unit MDoubleArray animTimeRange; showAnimTimeRange(gpuCacheNodes, animTimeRange); MPxCommand::setResult(animTimeRange); } else if (fGpuManufacturerFlag.isSet()) { MPxCommand::setResult(VramQuery::manufacturer()); } else if (fGpuModelFlag.isSet()) { MPxCommand::setResult(VramQuery::model()); } else if (fGpuDriverVersion.isSet()) { int driverVersion[3]; VramQuery::driverVersion(driverVersion); MString verionStr; verionStr += driverVersion[0]; verionStr += "."; verionStr += driverVersion[1]; verionStr += "."; verionStr += driverVersion[2]; MPxCommand::setResult(verionStr); } else if (fGpuMemorySize.isSet()) { MPxCommand::setResult((int)(VramQuery::queryVram() / 1024 / 1024)); } else if (fWaitForBackgroundReadingFlag.isSet()) { // Wait until the background reading is finished. BOOST_FOREACH (const MObject& node, gpuCacheNodes) { // Request the geometry to begin reading MFnDagNode dagNode(node); ShapeNode* shapeNode = (ShapeNode*)dagNode.userNode(); if (shapeNode) { shapeNode->getCachedGeometry(); } // Wait for the reading GlobalReaderCache::theCache().waitForRead(shapeNode->getCacheFileEntry().get()); // Pull the data if (shapeNode) { shapeNode->getCachedGeometry(); } } } return MS::kSuccess; } MStatus Command::doEdit(const std::vector<MObject>& gpuCacheNodes) { if (fRefreshSettingsFlag.isSet()) { Config::refresh(); } if (fRefreshFlag.isSet()) { refresh(gpuCacheNodes); } return MS::kSuccess; } MStatus Command::doBaking( const std::vector<MObject>& sourceNodes, const std::vector<std::vector<MDagPath> >& sourcePaths, MTime startTime, MTime endTime, MTime simulationRate,// The time interval to do the simulation. int samplingRate // How many time intervals to sample once. ) { // Check the start time and end time. if (startTime > endTime) { MStatus stat; MString msg = MStringResource::getString(kStartEndTimeErrorMsg, stat); MPxCommand::displayError(msg); return MS::kFailure; } // Find out the file names that we are going to write to. NodePathRegistry pathRegistry( fAllDagObjectsFlag.isSet(), fSaveMultipleFilesFlag.arg(true), fDirectoryFlag.arg(), fFilePrefixFlag.arg(), fFileNameFlag.arg(), fClashOptionFlag.arg() ); BOOST_FOREACH (const std::vector<MDagPath>& dagPaths, sourcePaths) { BOOST_FOREACH (const MDagPath& path, dagPaths) { pathRegistry.add(path); } } pathRegistry.resolve(); // Prompt for overwriting files. (Default is overwrite) if (MGlobal::mayaState() == MGlobal::kInteractive && fPromptFlag.isSet()) { pathRegistry.promptOverwrite(); } // Set up the progress bar for baking ProgressBar progressBar(kExportingMsg, (unsigned int)(sourceNodes.size() * (int)( (endTime - startTime + simulationRate).as(MTime::kSeconds) / simulationRate.as(MTime::kSeconds)) / samplingRate)); // First save the current time, so we can restore it later. const MTime previousTime = MAnimControl::currentTime(); // For go to start time. MTime currentTime = startTime; MAnimControl::setCurrentTime(currentTime); // The DAG object bakers. typedef std::vector< boost::shared_ptr<Baker> > Bakers; Bakers bakers; // The top-level baker for materials. boost::shared_ptr<MaterialBaker> materialBaker; if (fWriteMaterials.isSet()) { materialBaker = boost::make_shared<MaterialBaker>(); } for (size_t i = 0; i < sourceNodes.size(); i++) { // Create a new DAG object baker. const boost::shared_ptr<Baker> baker( Baker::create(sourceNodes[i], sourcePaths[i])); if (!baker) { MStatus stat; MString msg = MStringResource::getString(kCreateBakerErrorMsg, stat); MPxCommand::displayError(msg); return MS::kFailure; } const boost::shared_ptr<ShapeBaker> shapeBaker = boost::dynamic_pointer_cast<ShapeBaker,Baker>( baker ); if( shapeBaker && fUVsFlag.isSet() ) { shapeBaker->enableUVs(); } if (materialBaker) { baker->setWriteMaterials(); } if (fUseBaseTessellationFlag.isSet()) { baker->setUseBaseTessellation(); } bakers.push_back(baker); // sample all shapes at start time MCheckReturn(baker->sample(currentTime)); // Add the connected shaders to the material baker. if (materialBaker) { BOOST_FOREACH (const MDagPath& path, sourcePaths[i]) { if (path.node().hasFn(MFn::kShape)) { MCheckReturn( materialBaker->addShapePath(path) ); } } } MUpdateProgressAndCheckInterruption(progressBar); } // Sample all materials at start time. if (materialBaker) { MCheckReturn( materialBaker->sample(currentTime) ); } // Sample the vertex attributes over time. currentTime += simulationRate; for (int sampleIdx = 1; currentTime<=endTime; currentTime += simulationRate, ++sampleIdx) { // Advance time. MAnimControl::setCurrentTime(currentTime); if (sampleIdx % samplingRate == 0) { BOOST_FOREACH(const boost::shared_ptr<Baker>& baker, bakers) { MCheckReturn(baker->sample(currentTime)); MUpdateProgressAndCheckInterruption(progressBar); } // for each baker if (materialBaker) { MCheckReturn( materialBaker->sample(currentTime) ); } } } // for each time sample // Construct the material graphs MaterialGraphMap::Ptr materials; if (materialBaker) { materialBaker->buildGraph(); materials = materialBaker->get(); } // Construct SubNode hierarchy. { assert(bakers.size() == sourceNodes.size()); assert(bakers.size() == sourcePaths.size()); // Create a SubNode for each instance. for (size_t i = 0; i < sourcePaths.size(); i++) { for (size_t j = 0; j < sourcePaths[i].size(); j++) { const MDagPath& path = sourcePaths[i][j]; SubNode::MPtr subNode = bakers[i]->getNode(j); pathRegistry.associateSubNode(path, subNode); } } pathRegistry.constructHierarchy(); } // We are done with the bakers now. bakers.clear(); materialBaker.reset(); // Restore current time. MAnimControl::setCurrentTime(previousTime); // Preparing the root nodes and files to write. FileAndSubNodeList fileList; pathRegistry.generateFileAndSubNodes(fileList); // Do consolidation if (fOptimizeFlag.isSet()) { const int threshold = fOptimizationThresholdFlag.arg(40000); const bool motionBlur = fOptimizeAnimationsForMotionBlurFlag.isSet(); BOOST_FOREACH (FileAndSubNode& v, fileList) { Consolidator consolidator(v.subNode, threshold, motionBlur); MCheckReturn( consolidator.consolidate() ); SubNode::MPtr consolidatedRootNode = consolidator.consolidatedRootNode(); if (consolidatedRootNode) { v.subNode = consolidatedRootNode; v.isDummy = false; } } } // Set up progress bar for writing // // FIXME: The cache writer should provide more granularity for // updating the progress bar. progressBar.reset(kWritingMsg, (unsigned int)fileList.size()); // Write the baked geometry to the cache file. const MTime timePerCycle = simulationRate * samplingRate; Writer gpuCacheWriter( (char)fCompressLevelFlag.arg(-1), fDataFormatFlag.arg("hdf"), timePerCycle, startTime ); BOOST_FOREACH (const FileAndSubNode& v, fileList) { if (v.isDummy) { // This is a dummy root node. We are going to write its children. MCheckReturn( gpuCacheWriter.writeNodes( v.subNode->getChildren(), materials, v.targetFile ) ); } else { // We write the node to its taget file. MCheckReturn( gpuCacheWriter.writeNode( v.subNode, materials, v.targetFile ) ); } appendToResult(v.targetFile.resolvedFullName()); MUpdateProgressAndCheckInterruption(progressBar); } return MS::kSuccess; } void Command::showStats( const std::vector<MObject>& gpuCacheNodes, MStringArray& result ) const { MStatus status; { result.append(MStringResource::getString(kStatsAllFramesMsg, status)); StatsVisitor stats; BOOST_FOREACH(const MObject& gpuCacheObject, gpuCacheNodes) { MFnDagNode gpuCacheFn(gpuCacheObject); MPxNode* node = gpuCacheFn.userNode(); assert(node); assert(dynamic_cast<ShapeNode*>(node)); ShapeNode* gpuCacheNode = static_cast<ShapeNode*>(node); stats.accumulateNode(gpuCacheNode->getCachedGeometry()); stats.accumulateMaterialGraph(gpuCacheNode->getCachedMaterial()); } stats.print(result, false); } { result.append(MStringResource::getString(kStatsCurrentFrameMsg, status)); StatsVisitor stats(MAnimControl::currentTime()); BOOST_FOREACH(const MObject& gpuCacheObject, gpuCacheNodes) { MFnDagNode gpuCacheFn(gpuCacheObject); MPxNode* node = gpuCacheFn.userNode(); assert(node); assert(dynamic_cast<ShapeNode*>(node)); ShapeNode* gpuCacheNode = static_cast<ShapeNode*>(node); stats.accumulateNode(gpuCacheNode->getCachedGeometry()); stats.accumulateMaterialGraph(gpuCacheNode->getCachedMaterial()); } stats.print(result, true); } } void Command::showGlobalStats( MStringArray& result ) const { MStatus status; // Exclude internal unit bounding box const size_t unitBoundingBoxIndicesBytes = UnitBoundingBox::indices()->bytes(); const size_t unitBoundingBoxPositionsBytes = UnitBoundingBox::positions()->bytes(); const size_t unitBoundingBoxBytes = unitBoundingBoxIndicesBytes + unitBoundingBoxPositionsBytes; const size_t unitBoundingBoxNbIndices = 1; const size_t unitBoundingBoxNbVertices = 1; const size_t unitBoundingBoxNbBuffers = unitBoundingBoxNbIndices + unitBoundingBoxNbVertices; // System memory buffers { MString memUnit; double memSize = toHumanUnits(IndexBuffer::nbAllocatedBytes() + VertexBuffer::nbAllocatedBytes() - unitBoundingBoxBytes, memUnit); MString msg; MString msg_buffers; msg_buffers += (double)(IndexBuffer::nbAllocated() + VertexBuffer::nbAllocated() - unitBoundingBoxNbBuffers); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalSystemStatsMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(IndexBuffer::nbAllocatedBytes() - unitBoundingBoxIndicesBytes, memUnit); MString msg; MString msg_buffers; msg_buffers += (double)(IndexBuffer::nbAllocated() - unitBoundingBoxNbIndices); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalSystemStatsIndexMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(VertexBuffer::nbAllocatedBytes() - unitBoundingBoxPositionsBytes, memUnit); MString msg; MString msg_buffers; msg_buffers += (double)(VertexBuffer::nbAllocated() - unitBoundingBoxNbVertices); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalSystemStatsVertexMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } // Video memory buffers { MString memUnit; double memSize = toHumanUnits(VBOBuffer::nbAllocatedBytes(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)(VBOBuffer::nbAllocated()); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalVideoStatsMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(VBOBuffer::nbIndexAllocatedBytes(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)VBOBuffer::nbIndexAllocated(); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalVideoStatsIndexMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(VBOBuffer::nbVertexAllocatedBytes(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)VBOBuffer::nbVertexAllocated(); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalVideoStatsVertexMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } // Last refresh statistics { MString msg; msg.format(MStringResource::getString(kGlobalRefreshStatsMsg, status)); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(VBOBuffer::nbUploadedBytes(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)VBOBuffer::nbUploaded(); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalRefreshStatsUploadMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } { MString memUnit; double memSize = toHumanUnits(VBOBuffer::nbEvictedBytes(), memUnit); MString msg; MString msg_buffers; msg_buffers += (double)VBOBuffer::nbEvicted(); MString msg_memSize; msg_memSize += memSize; msg.format( MStringResource::getString(kGlobalRefreshStatsEvictionMsg, status), msg_buffers, msg_memSize, memUnit); result.append(msg); } } void Command::dumpHierarchy( const std::vector<MObject>& gpuCacheNodes, MStringArray& result ) const { BOOST_FOREACH(const MObject& gpuCacheObject, gpuCacheNodes) { MFnDagNode gpuCacheFn(gpuCacheObject); MPxNode* node = gpuCacheFn.userNode(); assert(node); assert(dynamic_cast<ShapeNode*>(node)); ShapeNode* gpuCacheNode = static_cast<ShapeNode*>(node); SubNode::Ptr rootNode = gpuCacheNode->getCachedGeometry(); if (rootNode) { DumpHierarchyVisitor visitor(result); rootNode->accept(visitor); } MaterialGraphMap::Ptr materials = gpuCacheNode->getCachedMaterial(); if (materials) { DumpMaterialVisitor visitor(result); visitor.dumpMaterials(materials); } } } MStatus Command::dumpHierarchyToFile( const std::vector<MObject>& gpuCacheNodes, const MFileObject& file ) const { MStringArray result; dumpHierarchy(gpuCacheNodes, result); std::ofstream output(file.resolvedFullName().asChar()); if (!output.is_open()) { MStatus stat; MString fmt = MStringResource::getString(kCouldNotSaveFileMsg, stat); MString msg; msg.format(fmt, file.resolvedFullName()); MPxCommand::displayError(msg); return MS::kFailure; } for (unsigned int i = 0; i < result.length(); i++) { output << result[i].asChar() << std::endl; } output.close(); return MS::kSuccess; } void Command::showAnimTimeRange( const std::vector<MObject>& gpuCacheNodes, MDoubleArray& result ) const { TimeInterval animTimeRange(TimeInterval::kInvalid); BOOST_FOREACH(const MObject& node, gpuCacheNodes) { MFnDagNode dagNode(node); if (dagNode.typeId() != ShapeNode::id) { continue; } ShapeNode* userNode = dynamic_cast<ShapeNode*>(dagNode.userNode()); if (userNode == NULL) { continue; } const SubNode::Ptr topNode = userNode->getCachedGeometry(); if (userNode->backgroundReadingState() != CacheFileEntry::kReadingDone) { // Background reading in progress but we need the animation time // range information immediately. MString cacheFileName = MPlug(node, ShapeNode::aCacheFileName).asString(); MFileObject cacheFile; cacheFile.setRawFullName(cacheFileName); cacheFile.setResolveMethod(MFileObject::kInputFile); if (cacheFileName.length() > 0 && cacheFile.exists()) { // Temporarily pause the worker thread and read the time range. ScopedPauseWorkerThread pause; GlobalReaderCache::CacheReaderProxy::Ptr proxy = GlobalReaderCache::theCache().getCacheReaderProxy(cacheFile); GlobalReaderCache::CacheReaderHolder holder(proxy); boost::shared_ptr<CacheReader> reader = holder.getCacheReader(); if (reader && reader->valid()) { TimeInterval interval(TimeInterval::kInvalid); if (reader->readAnimTimeRange(interval)) { animTimeRange |= interval; } } } } else if (topNode) { const SubNodeData::Ptr data = topNode->getData(); if (data) { animTimeRange |= data->animTimeRange(); } } } result.setLength(2); result[0] = MTime(animTimeRange.startTime(), MTime::kSeconds).as(MTime::uiUnit()); result[1] = MTime(animTimeRange.endTime(), MTime::kSeconds).as(MTime::uiUnit()); } void Command::refresh(const std::vector<MObject>& gpuCacheNodes) { BOOST_FOREACH(const MObject& node, gpuCacheNodes) { MFnDagNode dagNode(node); if (dagNode.typeId() != ShapeNode::id) { continue; } ShapeNode* userNode = dynamic_cast<ShapeNode*>(dagNode.userNode()); if (userNode == NULL) { continue; } userNode->refreshCachedGeometry( true ); } // Schedule an idle refresh. A normal refresh will cause the Alembic file to be // loaded immediately. We want this load operation to happen later. if (MGlobal::mayaState() == MGlobal::kInteractive) { MGlobal::executeCommandOnIdle("refresh"); } } void Command::refreshAll() { // Clear the CacheFileRegistry CacheFileRegistry::theCache().clear(); // Force a refresh on all ShapeNodes MFnDependencyNode nodeFn; std::vector<MObjectHandle> shapes; CacheShapeRegistry::theCache().getAll( shapes ); for( size_t i = 0; i < shapes.size(); i++ ) { if( !shapes[i].isValid() ) { continue; } nodeFn.setObject( shapes[i].object() ); assert( nodeFn.typeId() == ShapeNode::id ); ShapeNode* shape = (ShapeNode*) nodeFn.userNode(); assert( shape ); // File cache has already been cleared, do not request clearFileCache shape->refreshCachedGeometry( false ); } // Schedule an idle refresh. A normal refresh will cause the Alembic file to be // loaded immediately. We want this load operation to happen later. if (MGlobal::mayaState() == MGlobal::kInteractive) { MGlobal::executeCommandOnIdle("refresh"); } } void Command::listFileEntries() { MStringArray output; std::vector<CacheFileEntry::MPtr> entries; CacheFileRegistry::theCache().getAll(entries); size_t nEntries = entries.size(); for( size_t i = 0; i < nEntries; i++ ) { output.append( entries[i]->fResolvedCacheFileName ); } MPxCommand::setResult(output); } void Command::listShapeEntries() { MStringArray output; std::vector<MObjectHandle> shapes; CacheShapeRegistry::theCache().getAll(shapes); MFnDependencyNode nodeFn; size_t nShapes = shapes.size(); for( size_t i = 0; i < nShapes; i++ ) { MString str; MObject obj = shapes[i].object(); MStatus stat = nodeFn.setObject(obj); if( stat ) { ShapeNode* shapeNode = (ShapeNode*) nodeFn.userNode(); CacheFileEntry::MPtr entry = shapeNode->getCacheFileEntry(); str += nodeFn.name(); str += ":"; if( entry ) { str += entry->fResolvedCacheFileName; } } else { str += "kNullObj:"; } output.append( str ); } MPxCommand::setResult(output); } }
38.773097
161
0.494776
[ "mesh", "geometry", "object", "shape", "vector", "model", "transform" ]
7906746abb0738aedfbb5119a273833c6e700964
20,878
hpp
C++
dev/Basic/medium/config/MT_Config.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/medium/config/MT_Config.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/medium/config/MT_Config.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology //Licensed under the terms of the MIT License, as described in the file: // license.txt (http://opensource.org/licenses/MIT) #pragma once #include <string> #include <map> #include <vector> #include <utility> #include "behavioral/StopType.hpp" #include "conf/ConfigManager.hpp" #include "conf/ConfigParams.hpp" #include "conf/Constructs.hpp" #include "conf/RawConfigParams.hpp" #include "database/DB_Connection.hpp" #include "entities/conflux/Conflux.hpp" #include "entities/conflux/SegmentStats.hpp" #include "models/EnergyModelBase.hpp" #include "util/ProtectedCopyable.hpp" namespace sim_mob { namespace medium { class ParseMidTermConfigFile; class PredayCalibrationParams { public: PredayCalibrationParams(); double getAlgorithmCoefficient1() const { return algorithmCoefficient1; } void setAlgorithmCoefficient1(double algorithmCoefficient1) { this->algorithmCoefficient1 = algorithmCoefficient1; } double getAlgorithmCoefficient2() const { return algorithmCoefficient2; } void setAlgorithmCoefficient2(double algorithmCoefficient2) { this->algorithmCoefficient2 = algorithmCoefficient2; } const std::string& getCalibrationVariablesFile() const { return calibrationVariablesFile; } void setCalibrationVariablesFile(const std::string& calibrationVariablesFile) { this->calibrationVariablesFile = calibrationVariablesFile; } double getInitialGradientStepSize() const { return initialGradientStepSize; } void setInitialGradientStepSize(double initialGradientStepSize) { this->initialGradientStepSize = initialGradientStepSize; } double getInitialStepSize() const { return initialStepSize; } void setInitialStepSize(double initialStepSize) { this->initialStepSize = initialStepSize; } unsigned getIterationLimit() const { return iterationLimit; } void setIterationLimit(unsigned iterationLimit) { this->iterationLimit = iterationLimit; } double getStabilityConstant() const { return stabilityConstant; } void setStabilityConstant(double stabilityConstant) { this->stabilityConstant = stabilityConstant; } double getTolerance() const { return tolerance; } void setTolerance(double tolerance) { this->tolerance = tolerance; } const std::string& getObservedStatisticsFile() const { return observedStatisticsFile; } void setObservedStatisticsFile(const std::string& observedStatisticsFile) { this->observedStatisticsFile = observedStatisticsFile; } const std::string& getWeightMatrixFile() const { return weightMatrixFile; } void setWeightMatrixFile(const std::string& weightMatrixFile) { this->weightMatrixFile = weightMatrixFile; } private: /**path and file name of csv containing variables to calibrate*/ std::string calibrationVariablesFile; unsigned iterationLimit; double tolerance; double initialGradientStepSize; double algorithmCoefficient2; double initialStepSize; double stabilityConstant; double algorithmCoefficient1; std::string observedStatisticsFile; std::string weightMatrixFile; }; /** * Represents the "Workers" section of the config file. */ class WorkerParams { public: struct WorkerConf { WorkerConf() : count(0), granularityMs(0) {} unsigned int count; unsigned int granularityMs; }; WorkerConf person; }; struct DB_Details { DB_Details() : database(std::string()), credentials(std::string()) { } std::string database; std::string credentials; }; /** * Represents the loop-detector_counts section of the configuration file */ struct ScreenLineParams { ScreenLineParams() : interval(0), outputEnabled(false), fileName("") {} ///The frequency of aggregating the vehicle counts at the loop detector unsigned int interval; ///Indicates whether the counts have to be output to a file bool outputEnabled; ///Name of the output file std::string fileName; }; /** * represent the incident data section of the config file */ struct IncidentParams { IncidentParams() : incidentId(-1), visibilityDistance(0), segmentId(-1), position(0), severity(0), capFactor(0), startTime(0), duration(0), length(0), compliance(0), accessibility(0) {} struct LaneParams { LaneParams() : laneId(0), speedLimit(0), xLaneStartPos(0), yLaneStartPos(0), xLaneEndPos(0), yLaneEndPos(0) {} unsigned int laneId; float speedLimit; float xLaneStartPos; float yLaneStartPos; float xLaneEndPos; float yLaneEndPos; }; unsigned int incidentId; float visibilityDistance; unsigned int segmentId; float position; unsigned int severity; float capFactor; unsigned int startTime; unsigned int duration; float length; float compliance; float accessibility; std::vector<LaneParams> laneParams; }; /** * simple struct to hold speed density parameters * * \author Harish Loganathan */ struct SpeedDensityParams { public: double getAlpha() const { return alpha; } double getBeta() const { return beta; } double getJamDensity() const { return jamDensity; } double getMinDensity() const { return minDensity; } void setAlpha(double alpha) { this->alpha = alpha; } void setBeta(double beta) { this->beta = beta; } void setJamDensity(double jamDensity) { this->jamDensity = jamDensity; } void setMinDensity(double minDensity) { this->minDensity = minDensity; } private: /** outer exponent in speed density function */ double alpha; /** inner exponent in speed density function */ double beta; /** upper limit of density beyond which the speed of the moving part will be min speed */ double jamDensity; /** lower limit of density below which the speed of the moving part will be free flow speed */ double minDensity; }; /** * Structure to store das table config information */ struct TripChainOutputConfig { /// Flag to check whether trip chain output is enabled bool enabled; /// File name where the trips and activities are stored std::string tripActivitiesFile; /// File name where the subtrips are stored std::string subTripsFile; TripChainOutputConfig() : enabled(false), tripActivitiesFile(""), subTripsFile("") {} }; /** * Structure to store das table config information */ struct DAS_Config { DAS_Config() : schema(""), table(""), updateProc(""), fileName(""), vehicleTable("") {} std::string schema; std::string table; std::string updateProc; std::string fileName; std::string vehicleTable; // Eytan Gross }; /** * Singleton class to hold Mid-term related configurations */ class MT_Config : private ProtectedCopyable { friend class ParseMidTermConfigFile; public: /** * Destructor */ virtual ~MT_Config(); /** * Retrieves the singleton instance of MT_Config * * @return reference to the singleton instance */ static MT_Config& getInstance(); /** * Retrived pedestrian walk speed * * @return pedestrian walk speed */ double getPedestrianWalkSpeed() const; /** * Retrieves dwell time parameters * * @return dwell time params */ std::vector<float>& getDwellTimeParams(); /** * Sets pedestrian walk speed * * @param pedestrianWalkSpeed speed to be set */ void setPedestrianWalkSpeed(double pedestrianWalkSpeed); /** - * Retrieves model scripts map - * - * @return model scritps map - */ const ModelScriptsMap& getModelScriptsMap() const; /** - * Sets model scripts map - * - * @param modelScriptsMap model scripts map to be set - */ void setModelScriptsMap(const ModelScriptsMap& modelScriptsMap); ModelScriptsMap modelScriptsMap; /** @@ -785,9 +772,6 @@ class MT_Config : private ProtectedCopyable /// flag to indicate whether console output is required bool consoleOutput; /// Container for lua scripts /** * Retrieves number of threads allocated for Preday * * @return number of threads */ unsigned getNumPredayThreads() const; /** * Sets number of threads allocated for preday * * @param numPredayThreads number of threads */ void setNumPredayThreads(unsigned numPredayThreads); /** * the object of this class gets sealed when this function is called. No more changes will be allowed via the setters */ void sealConfig(); /** * Retrieves Preday calibration params * * @return preday calibration params */ const PredayCalibrationParams& getPredayCalibrationParams() const; /** * Retrieves SPSA Calibration params * * @return SPSA Calibration params */ const PredayCalibrationParams& getSPSA_CalibrationParams() const; /** * Sets SPSA Calibration params * * @param spsaCalibrationParams SPSA calibration params to be set */ void setSPSA_CalibrationParams(const PredayCalibrationParams& spsaCalibrationParams); /** * Retrieves WSPSA Calibration params * * @return WSPSA Calibration params */ const PredayCalibrationParams& getWSPSA_CalibrationParams() const; /** * Sets WSPSA Calibration params * * @param wspsaCalibrationParams WSPSA Calibration params to be set */ void setWSPSA_CalibrationParams(const PredayCalibrationParams& wspsaCalibrationParams); /** * Checks whether output to file is enabled * * @return true if enabled, else false */ bool isFileOutputEnabled() const; /** * Sets output file enabled/disabled status * * @param outputTripchains status to be set */ void setFileOutputEnabled(bool outputTripchains); /** * Checks whether console output enabled/disabled status * * @return true if enabled, else false */ bool isConsoleOutput() const; /** * Sets console output enabled/disabled status * * @param consoleOutput status to be set */ void setConsoleOutput(bool consoleOutput); /** * Checks whether preday simulation is running * * @return true if preday simulation is running, else false */ bool runningPredaySimulation() const; /** * Checks whether preday calibration is running * * @return true if preday calibration is running, else false */ bool runningPredayCalibration() const; /** * Checks whether preday logsum computation is running * * @return true if preday logsum computation is running, else false */ bool runningPredayLogsumComputation() const; /** * Sets the preday run mode * * @param runMode run mode to be set */ void setPredayRunMode(const std::string runMode); /** * Checks whether SPSA is running * * @return true if SPSA is running, else false */ bool runningSPSA() const; /** * Checks whether WSPSA is running * * @return true if WSPSA is running */ bool runningWSPSA() const; /** * Sets calibration methodology * * @param calibrationMethod calibration method to be set */ void setCalibrationMethodology(const std::string calibrationMethod); /** * Retrieves calibration output file name * * @return calibration output file name */ const std::string& getCalibrationOutputFile() const; /** * Sets the calibration output file name * * @param calibrationOutputFile filname to be set */ void setCalibrationOutputFile(const std::string& calibrationOutputFile); /** * Retrieves logsum computation frequency * * @return logsum computation frequency */ unsigned getLogsumComputationFrequency() const; /** * Sets logsum computation frequency * * @param logsumComputationFrequency logsum computation frequency to be set */ void setLogsumComputationFrequency(unsigned logsumComputationFrequency); /** * Retrieves activity schedule loading interval * * @return activity schedule load interval */ unsigned getActivityScheduleLoadInterval() const; /** * Sets activity schedule loading interval * * @param activityScheduleLoadInterval interval to be set */ void setActivityScheduleLoadInterval(unsigned activityScheduleLoadInterval); /** * Retrieves supply update interval * * @return supply update interval */ unsigned getSupplyUpdateInterval() const; /** * Sets supply update interval * * @param supplyUpdateInterval interval to be set */ void setSupplyUpdateInterval(unsigned supplyUpdateInterval); /** * Retrieves bus capacity * * @return bus capacity */ const unsigned int getBusCapacity() const; /** * Sets bus capacity * * @param busCapcacity bus capacity to be set */ void setBusCapacity(const unsigned int busCapcacity); /** * Retrieves population source database type * * @return population source database */ db::BackendType getPopulationSource() const; /** * Sets population source database * * @param src population source database to be set */ void setPopulationSource(const std::string& src); /** * Checks whether CBD area restriction enforced * * @return true if restriction enforced, else false */ bool isRegionRestrictionEnabled() const; /** * Retrives the confluxes * * @return confluxes */ std::set<Conflux*>& getConfluxes(); /** * Retrives the confluxes * * @return confluxes (const reference) */ const std::set<Conflux*>& getConfluxes() const; /** * Retrieves number of workers for handling agents * * @return number of workers */ unsigned int& personWorkGroupSize(); /** * Retrieves number of workers for handling agents * * @return number of workers */ unsigned int personWorkGroupSize() const; void setPublicTransitEnabled(bool val); /** * Retrives the confluxes * * @return confluxes (const reference) */ std::map<const Node*, Conflux*>& getConfluxNodes(); /** * Retrieves conflux nodes * * @return conflux nodes (const reference) */ const std::map<const Node*, Conflux*>& getConfluxNodes() const; /** * Retrives the conflux corresponding to a node * * @param multinode node for which the conflux to be found * * @return conflux */ Conflux* getConfluxForNode(const Node* multinode) const; /** * Retrives the segment stats with bus stops * * @return segment stats with bus stops */ std::set<SegmentStats*>& getSegmentStatsWithBusStops(); /** * returns the energy model used for simulation * @return energyModel, the selected energy model for simulation */ EnergyModelBase* getEnergyModel(); /** * sets the energy model used * @param energyModel, the selected energy model for simulation */ void setEnergyModel(EnergyModelBase* energyModel); /** * Retrieves energy model usage flag * * @return energy model usage flag */ bool isEnergyModelEnabled() const; /** * Sets energy model usage flag * * @param energyModelEnabled flag to be set */ void setEnergyModelEnabled(bool energyModelEnabled); /** * Checks whether mid term supply is running * * @return true if mid term supply is running, else false */ /** * Checks whether mid term supply is running * * @return true if mid term supply is running, else false */ bool RunningMidSupply() const; /** * Checks whether mid term preday simulation is running * * @return true if mid term preday simulation is running, else false */ bool RunningMidPredaySimulation() const; /** * Checks whether mid term preday logsum is running * * @return true if mid term preday logsum is running, else false */ bool RunningMidPredayLogsum() const; /** * Checks whether preday full mode is running * * @return true if preday full mode is running, else false */ bool RunningMidPredayFull() const; /** * Checks whether mid term full mode is running * * @return true if mid term full mode is running, else false */ bool RunningMidFullLoop() const; /** * Sets the mid term run mode * * @param runMode run mode (supply/demand/withinday) to be set */ void setMidTermRunMode(const std::string& runMode); /** * Retrives the incident params list * * @return incidents */ std::vector<IncidentParams>& getIncidents(); /** * Retrieve the disruption params * @return disruption definition */ std::vector<DisruptionParams>& getDisruption_rw(); /** * get person timestep in milliseconds * @return timestep in milliseconds */ unsigned int personTimeStepInMilliSeconds() const; /** * Retrieves the segment stats with taxi stands * @return segment stats with taxi-stands */ std::set<SegmentStats*>& getSegmentStatsWithTaxiStands(); const WorkerParams& getWorkerParams() const; /** * returns speed density params for a given link category * @param linkCategory link category (1=A, 2=B, 3=C, 4=D, 5=E, 6=SLIPROAD, 7=ROUNDABOUT) * @return SpeedDensityParams for the given link category */ SpeedDensityParams getSpeedDensityParam(int linkCategory) const; /** * sets speed density params for a given link category * @param linkCategory link category (1=A, 2=B, 3=C, 4=D, 5=E, 6=SLIPROAD, 7=ROUNDABOUT) * @param sdParams speed density parameters for the link category */ void setSpeedDensityParam(int linkCategory, SpeedDensityParams sdParams); /** * get name of table storing logsums * @return name of table storing logsums */ const std::string& getLogsumTableName() const; /** * sets name of table containing logsums * @param name of table storing logsums */ void setLogsumTableName(const std::string& logsumTableName); /** * get threads number for person loader * @return the threads number in use of person loader */ const unsigned int getThreadsNumInPersonLoader() const; /** * set threads number for person loader * @param number is threads number for person loader */ void setThreadsNumInPersonLoader(unsigned int number); /** * Enumerator for mid term run mode */ enum MidTermRunMode { MT_NONE, MT_SUPPLY, MT_PREDAY_LOGSUM, MT_PREDAY_SIMULATION, MT_PREDAY_FULL,MT_FULL }; /// Mid term run mode identifier MidTermRunMode midTermRunMode; /// screen line counts parameter ScreenLineParams screenLineParams; /// Number of ticks to wait before updating all Person agents. unsigned int granPersonTicks; /// Generic properties, for testing new features. std::map<std::string, std::string> genericProps; /// Configuration for trip chain output TripChainOutputConfig tripChainOutput; /// Day Activity Schedule config information DAS_Config dasConfig; private: /** * Constructor */ MT_Config(); /// Singleton instance static MT_Config* instance; /// protection for changes after config is loaded bool configSealed; /// store parameters for dwelling time calculation std::vector<float> dwellTimeParams; /// store parameters for pedestrian walking speed double pedestrianWalkSpeed; /** * control variable for running preday simulation/logsum computation */ enum PredayRunMode { PREDAY_NONE, PREDAY_SIMULATION, PREDAY_CALIBRATION, PREDAY_LOGSUM_COMPUTATION }; PredayRunMode predayRunMode; /// num of threads to run for preday unsigned numPredayThreads; /// flag to indicate whether output files need to be enabled bool fileOutputEnabled; /// flag to indicate whether console output is required bool consoleOutput; /// Container for service controller script ModelScriptsMap ServiceControllerScriptsMap; /** default capacity for bus*/ unsigned int busCapacity; /** the threads number in person loader*/ unsigned int threadsNumInPersonLoader; /// supply update interval in frames unsigned supplyUpdateInterval; /// activity schedule loading interval in seconds unsigned activityScheduleLoadInterval; /// population database type db::BackendType populationSource; /// name of table containing pre-computed values std::string logsumTableName; /// worker allocation details WorkerParams workers; /** * Enumerator for calibration methodology */ enum CalibrationMethodology { SPSA, WSPSA }; /// Calibration methodology identifier CalibrationMethodology calibrationMethodology; /// SPSA Calibration params PredayCalibrationParams spsaCalibrationParams; /// WSPSA Calibration params PredayCalibrationParams wspsaCalibrationParams; /// Calibration output file name std::string calibrationOutputFile; /// Logsum computation frequency unsigned logsumComputationFrequency; /// is CBD area restriction enforced bool regionRestrictionEnabled; ///setting for the incidents std::vector<IncidentParams> incidents; ///setting for disruptions std::vector<DisruptionParams> disruptions; /// set of confluxes std::set<Conflux*> confluxes; /// key:value (MultiNode:Conflux) map std::map<const Node*, Conflux*> multinode_confluxes; /// set of segment stats with bus stops std::set<SegmentStats*> segmentStatsWithBusStops; /// array of speed density function parameters indexed by link category SpeedDensityParams speedDensityParams[7]; /**set of segment stats with taxi-stands*/ std::set<SegmentStats*> segmentStatsWithTaxiStands; /** flag to indicate whether to run energy model */ bool energyModelEnabled; /** energy model used for the simulation*/ EnergyModelBase* energyModel; }; } }
22.046463
127
0.7312
[ "object", "vector", "model" ]
7907ddf7ba0f0b70a57aa09a766313d8cd89f485
2,502
cpp
C++
quantitative_finance/L1/tests/pentadiag_pcr/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-06-14T17:02:06.000Z
2021-06-14T17:02:06.000Z
quantitative_finance/L1/tests/pentadiag_pcr/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L1/tests/pentadiag_pcr/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @file main.cpp * @brief Testbench application file. */ #include <stdio.h> #include <iostream> #include "pentadiag_top.hpp" int main() { // pentadiag TEST_DT d[P_SIZE]; TEST_DT a[P_SIZE]; TEST_DT b[P_SIZE]; TEST_DT e[P_SIZE]; TEST_DT c[P_SIZE]; TEST_DT f[P_SIZE]; TEST_DT r[P_SIZE]; TEST_DT u[P_SIZE]; TEST_DT inrhs[P_SIZE]; TEST_DT sol[P_SIZE]; unsigned int N = P_SIZE; bool fail; /* * Generate diagonals */ for (int i = 0; i < N; i++) { e[i] = -1.0 - 0.37 * i; d[i] = 1.0; a[i] = 4.0 + i; b[i] = -2.0; c[i] = -3.0; sol[i] = i + 1; } d[0] = 0.0; b[N - 1] = 0.0; /* * Compute right hand side vector based on a generated diagonals */ inrhs[0] = a[0] * sol[0] + b[0] * sol[1] + c[0] * sol[2]; inrhs[1] = d[1] * sol[0] + a[1] * sol[1] + b[1] * sol[2] + c[1] * sol[3]; inrhs[N - 1] = e[N - 1] * sol[N - 3] + d[N - 1] * sol[N - 2] + a[N - 1] * sol[N - 1]; inrhs[N - 2] = e[N - 2] * sol[N - 4] + d[N - 2] * sol[N - 3] + a[N - 2] * sol[N - 2] + b[N - 2] * sol[N - 1]; for (int i = 2; i < N - 2; i++) { inrhs[i] = e[i] * sol[i - 2] + d[i] * sol[i - 1] + a[i] * sol[i] + b[i] * sol[i + 1] + c[i] * sol[i + 2]; }; /* * Print generated solution */ for (int k = 0; k < N; k++) { std::cout << sol[k] << " "; }; std::cout << std::endl; pentadiag_top(e, d, a, b, c, inrhs, u); /* * Print solved solution */ for (int k = 0; k < P_SIZE; k++) { std::cout << u[k] << " "; if (u[k] - sol[k] > 0.1) { fail = true; } } std::cout << std::endl; if (fail == true) { std::cout << " TEST FAILED: calculated solution is different than reference\n"; return 1; } else { std::cout << " TEST PASSED\n"; return 0; } }
27.494505
113
0.510392
[ "vector" ]
790decdb88e3bccc263def5ebb45f0a57b1b854c
19,202
cpp
C++
Tools/EntityInterface/EnvironmentSettings.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
3
2015-12-04T09:16:53.000Z
2021-05-28T23:22:49.000Z
Tools/EntityInterface/EnvironmentSettings.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
null
null
null
Tools/EntityInterface/EnvironmentSettings.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
2
2015-03-03T05:32:39.000Z
2015-12-04T09:16:54.000Z
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #pragma warning(disable:4793) // 'Exceptions::BasicLabel::BasicLabel' : function compiled as native : #include "EnvironmentSettings.h" #include "RetainedEntities.h" #include "../../RenderCore/LightingEngine/StandardLightOperators.h" #if defined(GUILAYER_SCENEENGINE) #include "../../SceneEngine/Ocean.h" #include "../../SceneEngine/DeepOceanSim.h" #include "../../SceneEngine/VolumetricFog.h" #include "../../SceneEngine/ShallowSurface.h" #endif #include "../../RenderCore/LightingEngine/SunSourceConfiguration.h" #include "../../SceneEngine/BasicLightingStateDelegate.h" #include "../../Math/Transformations.h" #include "../../Math/MathSerialization.h" #include "../../Utility/StringUtils.h" #include "../../Utility/StringFormat.h" #include "../../Utility/Conversion.h" #include "../../Utility/Streams/StreamFormatter.h" #include "../../Utility/Streams/OutputStreamFormatter.h" #include "../../Utility/Meta/AccessorSerialize.h" #include <memory> #if defined(GUILAYER_SCENEENGINE) namespace SceneEngine { extern DeepOceanSimSettings GlobalOceanSettings; extern OceanLightingSettings GlobalOceanLightingSettings; } #endif namespace EntityInterface { #define ParamName(x) static auto x = ParameterBox::MakeParameterNameHash(#x); /////////////////////////////////////////////////////////////////////////////////////////////////// static void ReadTransform(SceneEngine::LightDesc& light, const ParameterBox& props) { static const auto transformHash = ParameterBox::MakeParameterNameHash("Transform"); auto transform = Transpose(props.GetParameter(transformHash, Identity<Float4x4>())); ScaleRotationTranslationM decomposed(transform); light._position = decomposed._translation; light._orientation = decomposed._rotation; light._radii = Float2(decomposed._scale[0], decomposed._scale[1]); // For directional lights we need to normalize the position (it will be treated as a direction) if (light._shape == RenderCore::LightingEngine::LightSourceShape::Directional) light._position = (MagnitudeSquared(light._position) > 1e-5f) ? Normalize(light._position) : Float3(0.f, 0.f, 0.f); } namespace EntityTypeName { static const auto* EnvSettings = "EnvSettings"; static const auto* AmbientSettings = "AmbientSettings"; static const auto* DirectionalLight = "DirectionalLight"; static const auto* AreaLight = "AreaLight"; static const auto* ToneMapSettings = "ToneMapSettings"; static const auto* ShadowFrustumSettings = "ShadowFrustumSettings"; static const auto* OceanLightingSettings = "OceanLightingSettings"; static const auto* OceanSettings = "OceanSettings"; static const auto* FogVolumeRenderer = "FogVolumeRenderer"; } namespace Attribute { static const auto Flags = ParameterBox::MakeParameterNameHash("Flags"); static const auto Name = ParameterBox::MakeParameterNameHash("Name"); static const auto AttachedLight = ParameterBox::MakeParameterNameHash("Light"); } SceneEngine::EnvironmentSettings BuildEnvironmentSettings( const RetainedEntities& flexGobInterface, const RetainedEntity& obj) { using namespace SceneEngine; const auto typeAmbient = flexGobInterface.GetTypeId(EntityTypeName::AmbientSettings); const auto typeDirectionalLight = flexGobInterface.GetTypeId(EntityTypeName::DirectionalLight); const auto typeAreaLight = flexGobInterface.GetTypeId(EntityTypeName::AreaLight); const auto typeToneMapSettings = flexGobInterface.GetTypeId(EntityTypeName::ToneMapSettings); const auto typeShadowFrustumSettings = flexGobInterface.GetTypeId(EntityTypeName::ShadowFrustumSettings); EnvironmentSettings result; result._environmentalLightingDesc = SceneEngine::DefaultEnvironmentalLightingDesc(); for (const auto& cid : obj._children) { const auto* child = flexGobInterface.GetEntity(obj._doc, cid.second); if (!child) continue; if (child->_type == typeAmbient) { result._environmentalLightingDesc = MakeEnvironmentalLightingDesc(child->_properties); } if (child->_type == typeDirectionalLight || child->_type == typeAreaLight) { const auto& props = child->_properties; auto light = SceneEngine::MakeLightDesc(props); if (child->_type == typeDirectionalLight) light._shape = RenderCore::LightingEngine::LightSourceShape::Directional; ReadTransform(light, props); if (props.GetParameter(Attribute::Flags, 0u) & (1<<0)) { // look for frustum settings that match the "name" parameter auto frustumSettings = SceneEngine::DefaultSunSourceFrustumSettings(); auto fsRef = props.GetParameterAsString(Attribute::Name); if (fsRef.has_value()) { for (const auto& cid2 : obj._children) { const auto* fsSetObj = flexGobInterface.GetEntity(obj._doc, cid2.second); if (!fsSetObj || fsSetObj->_type != typeShadowFrustumSettings) continue; auto attachedLight = fsSetObj->_properties.GetParameterAsString(Attribute::AttachedLight); if (!attachedLight.has_value() || XlCompareStringI(attachedLight.value().c_str(), fsRef.value().c_str())!=0) continue; frustumSettings = CreateFromParameters<RenderCore::LightingEngine::SunSourceFrustumSettings>(fsSetObj->_properties); break; } } result._sunSourceShadowProj.push_back( EnvironmentSettings::SunSourceShadowProj { unsigned(result._lights.size()), frustumSettings }); } result._lights.push_back(light); } if (child->_type == typeToneMapSettings) { result._toneMapSettings = CreateFromParameters<ToneMapSettings>(child->_properties); } } return std::move(result); } EnvSettingsVector BuildEnvironmentSettings(const RetainedEntities& flexGobInterface) { EnvSettingsVector result; const auto typeSettings = flexGobInterface.GetTypeId(EntityTypeName::EnvSettings); auto allSettings = flexGobInterface.FindEntitiesOfType(typeSettings); for (const auto& s : allSettings) result.push_back( std::make_pair( s->_properties.GetParameterAsString(Attribute::Name).value(), BuildEnvironmentSettings(flexGobInterface, *s))); return std::move(result); } template<typename CharType> void SerializeBody( OutputStreamFormatter& formatter, const RetainedEntity& obj, const RetainedEntities& entities) { obj._properties.SerializeWithCharType<CharType>(formatter); for (auto c=obj._children.cbegin(); c!=obj._children.cend(); ++c) { const auto* child = entities.GetEntity(obj._doc, c->second); if (child) SerializationOperator<CharType>(formatter, *child, entities); } } template<typename CharType> void SerializationOperator( OutputStreamFormatter& formatter, const RetainedEntity& obj, const RetainedEntities& entities) { auto name = entities.GetTypeName(obj._type); auto eleId = formatter.BeginKeyedElement(name); if (!obj._children.empty()) formatter.NewLine(); // properties can continue on the same line, but only if we don't have children SerializeBody<CharType>(formatter, obj, entities); formatter.EndElement(eleId); } void ExportEnvSettings( OutputStreamFormatter& formatter, const RetainedEntities& flexGobInterface, DocumentId docId) { // Save out the environment settings in the given document // in native format. // Our environment settings are stored in the flex object interface, // so we first need to convert them into native format, and then // we'll write those settings to a basic text file. // There are two ways to handle this: // 1) convert from the flex gob objects into SceneEngine::EnvironmentSettings // and then serialise from there // 2) just get the parameter boxes in the flex gob objects, and write // them out // The second way is a lot easier. And it's much more straight-forward to // maintain. const auto typeSettings = flexGobInterface.GetTypeId(EntityTypeName::EnvSettings); auto allSettings = flexGobInterface.FindEntitiesOfType(typeSettings); bool foundAtLeastOne = false; for (const auto& s : allSettings) if (s->_doc == docId) { { auto name = s->_properties.GetParameterAsString(Attribute::Name); auto eleId = formatter.BeginKeyedElement(name.value()); formatter.NewLine(); SerializeBody<utf8>(formatter, *s, flexGobInterface); formatter.EndElement(eleId); } foundAtLeastOne = true; } if (!foundAtLeastOne) Throw(::Exceptions::BasicLabel("No environment settings found")); formatter.Flush(); } /////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(GUILAYER_SCENEENGINE) static SceneEngine::DeepOceanSimSettings BuildOceanSettings( const RetainedEntities& sys, const RetainedEntity& obj) { return SceneEngine::DeepOceanSimSettings(obj._properties); } static SceneEngine::OceanLightingSettings BuildOceanLightingSettings( const RetainedEntities& sys, const RetainedEntity& obj) { return SceneEngine::OceanLightingSettings(obj._properties); } #endif void EnvEntitiesManager::RegisterEnvironmentFlexObjects() { #if defined(GUILAYER_SCENEENGINE) _flexSys->RegisterCallback( _flexSys->GetTypeId("OceanSettings"), [](const RetainedEntities& flexSys, const Identifier& obj, RetainedEntities::ChangeType changeType) { if (changeType != RetainedEntities::ChangeType::Delete) { auto* object = flexSys.GetEntity(obj); if (object) SceneEngine::GlobalOceanSettings = BuildOceanSettings(flexSys, *object); } else { SceneEngine::GlobalOceanSettings._enable = false; } }); _flexSys->RegisterCallback( _flexSys->GetTypeId("OceanLightingSettings"), [](const RetainedEntities& flexSys, const Identifier& obj, RetainedEntities::ChangeType changeType) { if (changeType != RetainedEntities::ChangeType::Delete) { auto* object = flexSys.GetEntity(obj); if (object) SceneEngine::GlobalOceanLightingSettings = BuildOceanLightingSettings(flexSys, *object); } else { SceneEngine::GlobalOceanLightingSettings = SceneEngine::OceanLightingSettings(); } }); #endif } /////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(GUILAYER_SCENEENGINE) static void UpdateVolumetricFog( const RetainedEntities& sys, SceneEngine::VolumetricFogManager& mgr) { using namespace SceneEngine; VolumetricFogConfig cfg; const auto volumeType = sys.GetTypeId("FogVolume"); auto volumes = sys.FindEntitiesOfType(volumeType); for (auto v:volumes) { const auto& props = v->_properties; cfg._volumes.push_back(VolumetricFogConfig::FogVolume(props)); } const auto rendererConfigType = sys.GetTypeId("FogVolumeRenderer"); auto renderers = sys.FindEntitiesOfType(rendererConfigType); if (!renderers.empty()) cfg._renderer = VolumetricFogConfig::Renderer(renderers[0]->_properties); mgr.Load(cfg); } #endif void EnvEntitiesManager::RegisterVolumetricFogFlexObjects( std::shared_ptr<SceneEngine::VolumetricFogManager> manager) { #if defined(GUILAYER_SCENEENGINE) std::weak_ptr<SceneEngine::VolumetricFogManager> weakPtrToManager = manager; const char* types[] = { "FogVolume", "FogVolumeRenderer" }; for (unsigned c=0; c<dimof(types); ++c) { _flexSys->RegisterCallback( _flexSys->GetTypeId(types[c]), [weakPtrToManager](const RetainedEntities& flexSys, const Identifier&, RetainedEntities::ChangeType) { auto mgr = weakPtrToManager.lock(); if (!mgr) return; UpdateVolumetricFog(flexSys, *mgr); }); } #endif } /////////////////////////////////////////////////////////////////////////////////////////////////// static Float4x4 GetTransform(const RetainedEntity& obj) { ParamName(Transform); ParamName(Translation); auto xform = obj._properties.GetParameter<Float4x4>(Transform); if (xform.has_value()) return Transpose(xform.value()); auto transl = obj._properties.GetParameter<Float3>(Translation); if (transl.has_value()) { return AsFloat4x4(transl.value()); } return Identity<Float4x4>(); } std::vector<Float2> ExtractVertices(const RetainedEntities& sys, const RetainedEntity& obj) { // Find the vertices within a tri mesh marker type entity, // and return as a triangle list of 2d positions. ParamName(IndexList); auto indexListType = obj._properties.GetParameterType(IndexList); if (indexListType._type == ImpliedTyping::TypeCat::Void || indexListType._arrayCount < 3) return std::vector<Float2>(); auto ibData = std::make_unique<unsigned[]>(indexListType._arrayCount); bool success = obj._properties.GetParameter( IndexList, ibData.get(), ImpliedTyping::TypeDesc{ImpliedTyping::TypeCat::UInt32, indexListType._arrayCount}); if (!success) std::vector<Float2>(); const auto& chld = obj._children; if (!chld.size()) std::vector<Float2>(); auto vbData = std::make_unique<Float3[]>(chld.size()); for (size_t c=0; c<chld.size(); ++c) { const auto* e = sys.GetEntity(obj._doc, chld[c].second); if (e) { vbData[c] = ExtractTranslation(GetTransform(*e)); } else { vbData[c] = Zero<Float3>(); } } std::vector<Float2> result; result.reserve(indexListType._arrayCount); for (unsigned c=0; c<indexListType._arrayCount; ++c) { auto i = ibData[c]; result.push_back(Truncate(vbData[i])); } return std::move(result); } #if defined(GUILAYER_SCENEENGINE) static void UpdateShallowSurface( const RetainedEntities& sys, SceneEngine::ShallowSurfaceManager& mgr) { using namespace SceneEngine; ParamName(Marker); ParamName(name); mgr.Clear(); const auto surfaceType = sys.GetTypeId("ShallowSurface"); const auto markerType = sys.GetTypeId("TriMeshMarker"); // Create new surface objects for all of the "ShallowSurface" objects auto surfaces = sys.FindEntitiesOfType(surfaceType); auto markers = sys.FindEntitiesOfType(markerType); for (auto s:surfaces) { const auto& props = s->_properties; auto markerName = props.GetParameterAsString(Marker); if (!markerName.has_value()) continue; // Look for the marker with the matching name const RetainedEntity* marker = nullptr; for (auto m:markers) { auto testName = m->_properties.GetParameterAsString(name); if (testName.has_value() && XlEqStringI(testName.value(), markerName.value())) { marker = m; break; } } if (marker) { // We have to be careful here -- because we get update // callbacks when the markers change, the marker might // only be partially constructed. Sometimes the vertex // positions aren't properly set -- which causes us to // generate bad triangles. auto verts = ExtractVertices(sys, *marker); if (verts.empty()) continue; auto cfg = CreateFromParameters<ShallowSurface::Config>(s->_properties); auto lcfg = CreateFromParameters<ShallowSurface::LightingConfig>(s->_properties); mgr.Add( std::make_shared<ShallowSurface>( AsPointer(verts.cbegin()), sizeof(Float2), verts.size(), cfg, lcfg)); } } } #endif void EnvEntitiesManager::RegisterShallowSurfaceFlexObjects( std::shared_ptr<SceneEngine::ShallowSurfaceManager> manager) { _shallowWaterManager = manager; std::weak_ptr<EnvEntitiesManager> weakPtrToThis = shared_from_this(); const char* types[] = { "ShallowSurface", "TriMeshMarker" }; for (unsigned c=0; c<dimof(types); ++c) { _flexSys->RegisterCallback( _flexSys->GetTypeId(types[c]), [weakPtrToThis](const RetainedEntities&, const Identifier&, RetainedEntities::ChangeType) { auto mgr = weakPtrToThis.lock(); if (!mgr) return; mgr->_pendingShallowSurfaceUpdate = true; }); } } void EnvEntitiesManager::FlushUpdates() { #if defined(GUILAYER_SCENEENGINE) if (_pendingShallowSurfaceUpdate) { auto mgr = _shallowWaterManager.lock(); if (mgr) { UpdateShallowSurface(*_flexSys, *mgr); } _pendingShallowSurfaceUpdate = false; } #endif } EnvEntitiesManager::EnvEntitiesManager(std::shared_ptr<RetainedEntities> sys) : _flexSys(std::move(sys)) , _pendingShallowSurfaceUpdate(false) {} EnvEntitiesManager::~EnvEntitiesManager() {} }
40.855319
146
0.608426
[ "mesh", "object", "vector", "transform" ]
79180a02197c88b4fb3c5e58ee6a95c678e9c8bf
665
cpp
C++
source/view/GltfMesh.cpp
Fahien/sunspot
1ed579ee0016c2f95e5f6f54f5c703e1dc281da6
[ "Apache-2.0" ]
6
2017-12-20T10:40:25.000Z
2021-01-21T23:03:50.000Z
source/view/GltfMesh.cpp
Fahien/sunspot
1ed579ee0016c2f95e5f6f54f5c703e1dc281da6
[ "Apache-2.0" ]
null
null
null
source/view/GltfMesh.cpp
Fahien/sunspot
1ed579ee0016c2f95e5f6f54f5c703e1dc281da6
[ "Apache-2.0" ]
null
null
null
#include <Gltf.h> #include "ShaderProgram.h" #include "view/GltfPrimitive.h" #include "view/GltfMesh.h" using namespace std; using namespace gltfspot; using namespace sunspot; GltfMesh::GltfMesh(GltfMesh&& other) : mName { move(other.mName) } , mPrimitives{ move(other.mPrimitives) } {} GltfMesh::GltfMesh(Gltf& model, Gltf::Mesh& mesh) : mName{ mesh.name } { for (auto p : mesh.primitives) { GltfPrimitive primitive{ model, p }; mPrimitives.push_back(move(primitive)); } } void GltfMesh::Draw(const ShaderProgram& program) const { for (auto& primitive : mPrimitives) { primitive.Draw(program); } }
18.472222
56
0.666165
[ "mesh", "model" ]
791c8d70bd5013455c54d2c6fcd9f68d06dcffd0
8,717
cpp
C++
traceStream/stream/subscribe.cpp
imperial-qore/openforest
1f8e880b1de7f76137baad949705744812319dc8
[ "BSD-3-Clause" ]
null
null
null
traceStream/stream/subscribe.cpp
imperial-qore/openforest
1f8e880b1de7f76137baad949705744812319dc8
[ "BSD-3-Clause" ]
null
null
null
traceStream/stream/subscribe.cpp
imperial-qore/openforest
1f8e880b1de7f76137baad949705744812319dc8
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <unordered_map> #include <cstring> #include <fstream> #include <vector> #include <sw/redis++/redis++.h> #include <nlohmann/json.hpp> #include <dirent.h> #include <sys/types.h> #include<unistd.h> #include <thread> #include <pthread.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> using namespace sw::redis; using namespace std::chrono; using namespace std; using json = nlohmann::json; using Attrs = std::vector<std::pair<std::string, std::string>>; using Item = std::pair<std::string, Attrs>; //id and attributes using ItemStream = std::vector<Item>; unordered_map <string, deque <Item> > traces; unordered_map <string, clock_t > remTime; unordered_map <string, ItemStream > tracesToProcess; unordered_map <string, bool> isComp; bool streamComp = false; int numConsumers; long long sizeTrace; //Can we normalise the traces in some way?? //ID, Agent, Host, ProcessName, Source, clientType void processTrace(vector <float> &trace, vector <string> &dictionary, deque <Item> traceStream){ for(int i=0; i<dictionary.size()+1; i++){ trace.push_back(0); } while(!traceStream.empty()){ Item curr = traceStream.front(); Attrs report = curr.second; traceStream.pop_front(); string agent = report[1].second; string host = report[2].second; string processName = report[3].second; string source = report[4].second; string clientType = report[5].second; int anomaly = stoi(report[6].second); vector <string>::iterator it; it=find(dictionary.begin(), dictionary.end(), agent); if(agent!=""){ trace[it-dictionary.begin()]+=1; } it=find(dictionary.begin(), dictionary.end(), host); if(host!=""){ trace[it-dictionary.begin()]+=1; } it=find(dictionary.begin(), dictionary.end(), processName); if(processName!=""){ trace[it-dictionary.begin()]+=1; } it=find(dictionary.begin(), dictionary.end(), source); if(source!=""){ trace[it-dictionary.begin()]+=1; } it=find(dictionary.begin(), dictionary.end(), clientType); if(clientType!=""){ trace[it-dictionary.begin()]+=1; } trace[dictionary.size()]=anomaly; } } void* collect(void* arg){ Redis *redis_ptr = (Redis*) arg; clock_t start = clock(); int numFails = 0; while(numFails<30){ clock_t now = clock(); std::vector<pair<std::string, ItemStream>> result; //streamName and item for(int i=0; i<numConsumers; i++){ string name = "consumer" + to_string(i); (*redis_ptr).xreadgroup("group", name, "stream1", ">", std::chrono::milliseconds(500), std::inserter(result, result.end())); } if(result.size()==0){ numFails++; continue; } for(int i=0; i<result.size(); i++){ //If the trace to which the collected span belongs in not completed. if(isComp.find(result[i].second[0].second[0].second)==isComp.end()){ if(traces[result[i].second[0].second[0].second].size()==sizeTrace/sizeof(Item)){ traces[result[i].second[0].second[0].second].pop_front(); } traces[result[i].second[0].second[0].second].push_back(result[i].second[0]); remTime[result[i].second[0].second[0].second]=now; } //A delayed span found. else{ cout<<result[i].second[0].second[0].second<<"\n"; } string id = result[i].second[0].first; (*redis_ptr).xack("stream1", "group", id); } numFails = 0; } (*redis_ptr).xgroup_destroy("stream1", "group"); cout<<"Stream Reading Terminated\n"; streamComp = true; pthread_exit(0); } void communicate(int PORT, int numClient, vector <float> &trace){ for(int i=0; i<=trace.size(); i++){ char buff[255] = {0}; if(i==0){ string msg = "Sending trace\n"; send(numClient, msg.c_str(), 255, 0); continue; } string curr = to_string(trace[i-1]); send(numClient, curr.c_str(), 255, 0); unsigned int microsecond = 1000; usleep(microsecond); } } int main(int argc, char* argv[]){ //Connecting to the anomaly detection code. if(argc!=4){ cout<<"Invalid number of arguments\n"; return -1; } int PORT = stoi(argv[1]); numConsumers = stoi(argv[2]); sizeTrace = stoi(argv[3]); int numClient = socket(AF_INET, SOCK_STREAM, 0); if(numClient<0){ cout<<"Client Socket was not initialized\n"; exit(EXIT_FAILURE); } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(&(addr.sin_zero), 0, 8); int nRet = connect(numClient, (sockaddr*)&addr, sizeof(addr)); if(nRet<0){ cout<<"Could not connect to the anomaly detection program\n"; exit(EXIT_FAILURE); } //Connection completed. //Clear Redis before subscribing. auto redis = Redis("tcp://127.0.0.1:6379"); redis.flushall(); Redis *redis_ptr = (Redis*) &redis; string prevID = "$"; clock_t start = clock(); //Create the consumer group. (*redis_ptr).xgroup_create("stream1", "group", prevID, true); //Span the subscriber thread. pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid, &attr, collect, &redis); vector <string> dictionary; ifstream file ("dict.txt"); //File which contains the collected traces. ofstream outputFile("collectedData.txt"); string line; while (getline(file,line)) { dictionary.push_back(line); } file.close(); vector <vector<float>> trainData; int fails = 0; while(true){ //Terminate polling if the stream is completed. if(streamComp){ pthread_join(tid, NULL); break; } trainData.clear(); vector <string> completedTraces; for(auto itr: remTime){ clock_t now = clock(); //If some span of the current trace has not arrived since the last second, process and communicate it to the anomaly detection code. if((double)(now-itr.second)/double(CLOCKS_PER_SEC)>1){ cout<<"Collecting Trace "<<itr.first<<" "<<traces[itr.first].size()<<"\n"; vector <float> trace; processTrace(trace, dictionary, traces[itr.first]); trainData.push_back(trace); isComp[itr.first]=true; completedTraces.push_back(itr.first); communicate(PORT, numClient, trace); } } //Erase the completed traces. for(int i=0; i<completedTraces.size(); i++){ remTime.erase(completedTraces[i]); traces.erase(completedTraces[i]); } //Print the collected traces in the output file. for(int i=0; i<trainData.size(); i++){ for(int j=0; j<trainData[0].size(); j++){ outputFile<<trainData[i][j]<<" "; } outputFile<<"\n"; } //Sleep for 1ms. unsigned int microsecond = 1000; usleep(microsecond); } vector <string> completedTraces; //Final collect for(auto itr: remTime){ clock_t now = clock(); cout<<"Collecting Trace "<<itr.first<<" "<<traces[itr.first].size()<<"\n"; vector <float> trace; processTrace(trace, dictionary, traces[itr.first]); trainData.push_back(trace); isComp[itr.first]=true; completedTraces.push_back(itr.first); communicate(PORT, numClient, trace); } //Erase the completed traces. for(int i=0; i<completedTraces.size(); i++){ remTime.erase(completedTraces[i]); traces.erase(completedTraces[i]); } //Final output for(int i=0; i<trainData.size(); i++){ for(int j=0; j<trainData[0].size(); j++){ outputFile<<trainData[i][j]<<" "; } outputFile<<"\n"; } cout<<"\nNo more traces to process. Terminating\n"; }
26.256024
144
0.556269
[ "vector" ]
791cd3077ebbb930af979bf9fb1a4cf2ac0cce27
1,675
hpp
C++
src/AGameObject.hpp
brwagner/Quarri
c66297c3e20763b5f986ba3ce4156c747bda4227
[ "MIT" ]
1
2017-04-13T16:29:36.000Z
2017-04-13T16:29:36.000Z
src/AGameObject.hpp
brwagner/Quarri
c66297c3e20763b5f986ba3ce4156c747bda4227
[ "MIT" ]
null
null
null
src/AGameObject.hpp
brwagner/Quarri
c66297c3e20763b5f986ba3ce4156c747bda4227
[ "MIT" ]
null
null
null
/** abstract class that represents an entity in the game world that can handle events, render itself to the screen based on its position, and update every frame. **/ #ifndef AGameObject_hpp #define AGameObject_hpp #include "SDL.h" #include <utility> #include "LevelState.hpp" // Forward declaration to prevent cycles class LevelState; class AGameObject { public: AGameObject(std::pair<double, double> pos, bool movable, bool player); virtual ~AGameObject() {} // update is called every frame virtual void update() = 0; // respond to events such as key input virtual void handleEvent(SDL_Event event) = 0; // render this GameObject to the screen virtual void draw(SDL_Renderer* renderer, int xOff) = 0; // checks if there's already someone in the position // update's position in the GameObject and LevelState // returns true if the move was successful bool move(std::pair<double, double> pos); // helpers for directions std::pair<double, double> relativePosition(int x, int y); std::pair<double, double> up(); std::pair<double, double> down(); std::pair<double, double> left(); std::pair<double, double> right(); // getters and setters void setLevelState(LevelState * level_state); const std::pair<double, double> getPos() const; const bool isMovable() const; const bool isPlayer() const; protected: // a reference to other gameobejcts LevelState * m_level_state; private: // this GameObject's position in the game world std::pair<double,double> m_pos; // can this be picked up? bool m_movable; // is this the player bool m_player; }; #endif
31.603774
160
0.695522
[ "render" ]
792a7065324eb9c513d1a5227e592db7908ae36f
4,035
cpp
C++
UrhoEditor/Views/MultiGizmo.cpp
elix22/UrhoEditor
8b2578610b21e60f4126e351a1c7e01d639be695
[ "MIT" ]
23
2017-06-14T02:22:10.000Z
2021-11-25T05:09:21.000Z
UrhoEditor/Views/MultiGizmo.cpp
elix22/UrhoEditor
8b2578610b21e60f4126e351a1c7e01d639be695
[ "MIT" ]
null
null
null
UrhoEditor/Views/MultiGizmo.cpp
elix22/UrhoEditor
8b2578610b21e60f4126e351a1c7e01d639be695
[ "MIT" ]
22
2017-06-15T12:09:23.000Z
2021-01-02T13:05:15.000Z
#include "MultiGizmo.h" #include <EditorLib/Commands/CompoundCommand.h> #include <EditorLib/DocumentBase.h> #include <EditorLib/Selectron.h> #include <sstream> using namespace Urho3D; namespace SprueEditor { MultiGizmo::MultiGizmo(Urho3D::Node* holdingNode, std::vector< std::shared_ptr<Gizmo> > gizmos) : Gizmo(), wrappedGizmos_(gizmos) { for (int i = 0; i < gizmos.size(); ++i) { if (i == 0) gizmoCapabilities_ = gizmos[i]->GetCapabilities(); else gizmoCapabilities_ = gizmoCapabilities_ & gizmos[i]->GetCapabilities(); } std::vector<std::shared_ptr<DataSource> > srcs; for (auto giz : gizmos) srcs.push_back(giz->GetEditObject()); dataSource_.reset(new MultiDataSource(srcs)); PrepareCenter(); } MultiGizmo::~MultiGizmo() { } void MultiGizmo::Construct() { Gizmo::Construct(); SetForTranslation(); } void MultiGizmo::NotifyDataChanged(void* src, Selectron* sel) { for (unsigned i = 0; i < wrappedGizmos_.size(); ++i) wrappedGizmos_[i]->NotifyDataChanged(src, sel); } void MultiGizmo::RefreshValue() { for (auto giz : wrappedGizmos_) giz->RefreshValue(); PrepareCenter(); Gizmo::RefreshValue(); } Matrix3x4 MultiGizmo::GetTransform() { return Matrix3x4(centerPosition_, Quaternion(), Vector3(1,1,1)); } void MultiGizmo::ApplyTransform(const Matrix3x4& transform) { Vector3 pos; Quaternion rot; Vector3 scl; transform.Decompose(pos, rot, scl); for (auto giz : wrappedGizmos_) { Matrix3x4 trans = giz->GetTransform(); Vector3 thisPos; Quaternion thisRot; Vector3 thisScl; trans.Decompose(thisPos, thisRot, thisScl); thisPos += (pos - centerPosition_); //thisRot = (thisRot * rot).Normalized(); giz->ApplyTransform(Matrix3x4(thisPos, rot, scl)); } PrepareCenter(); } void MultiGizmo::PrepareCenter() { centerPosition_ = Vector3(); for (auto giz : wrappedGizmos_) { Matrix3x4 mat = giz->GetTransform(); centerPosition_ += mat.Translation(); } centerPosition_ /= wrappedGizmos_.size(); } void MultiGizmo::RecordTransforms() { recordedTransforms_.clear(); for (int i = 0; i < wrappedGizmos_.size(); ++i) recordedTransforms_.push_back(wrappedGizmos_[i]->GetTransform()); } void MultiGizmo::PushUndo(DocumentBase* document, const Urho3D::Matrix3x4& oldMatrix) { std::vector<SmartCommand*> cmds; std::stringstream ss; ss << "Transform "; for (int i = 0; i < wrappedGizmos_.size(); ++i) { if (auto undo = wrappedGizmos_[i]->CreateUndo(document, recordedTransforms_[i])) { cmds.push_back(undo); if (cmds.size() > 0) ss << ", "; ss << wrappedGizmos_[i]->GetEditObject()->GetName().toStdString(); } } if (cmds.size() > 0) document->GetUndoStack()->Push(new CompoundCommand(QString::fromStdString(ss.str()), cmds)); } SmartCommand* MultiGizmo::CreateUndo(DocumentBase* document, const Urho3D::Matrix3x4& oldMatrix) { return 0x0; } bool MultiGizmo::Equal(Gizmo* rhs) const { if (auto other = dynamic_cast<MultiGizmo*>(rhs)) { if (wrappedGizmos_.size() != other->wrappedGizmos_.size()) return false; for (unsigned i = 0; i < wrappedGizmos_.size(); ++i) { if (!wrappedGizmos_[i]->Equal(other->wrappedGizmos_[i].get())) return false; } return true; } return false; } }
28.617021
104
0.554895
[ "vector", "transform" ]
792d81c1491d06aa89007027d2e418623f4d6e18
1,389
cpp
C++
MySpaceShooter/src/Core/ModelLoader.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Core/ModelLoader.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Core/ModelLoader.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
#include "ModelLoader.h" #include <fstream> #include <iostream> #include <vector> #include "glm/glm.hpp" namespace Core { std::vector<Quad> Core::ModelLoader::Load(const std::string& filePath) { // Open file. std::fstream file; file.open(filePath.c_str()); // Check if file is succesfully opened. if (!file.is_open()) std::cout << "File not found - " << filePath; // Write words to string vector. std::string word; std::vector<std::string> words; while (file >> word) words.push_back(word); file.close(); // Create quads and convert string to float. std::vector<Quad> quads; for (size_t i = 0; i < words.size(); i += 16) { glm::vec3 vert1 = { std::stof(words[i]), std::stof(words[i + 1]), std::stof(words[i + 2]), }; glm::vec3 vert2 = { std::stof(words[i + 3]), std::stof(words[i + 4]), std::stof(words[i + 5]), }; glm::vec3 vert3 = { std::stof(words[i + 6]), std::stof(words[i + 7]), std::stof(words[i + 8]), }; glm::vec3 vert4 = { std::stof(words[i + 9]), std::stof(words[i + 10]), std::stof(words[i + 11]), }; glm::vec4 color = { std::stof(words[i + 12]), std::stof(words[i + 13]), std::stof(words[i + 14]), std::stof(words[i + 15]), }; quads.push_back(Quad({vert1, vert2, vert3, vert4}, color)); } return quads; } }
19.291667
71
0.558675
[ "vector" ]
79315b93cb1bd7aa0476a6200d96d8bac3b42b85
4,022
hpp
C++
packages/monte_carlo/collision/photon/src/MonteCarlo_AdjointPhotoatomCore_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/photon/src/MonteCarlo_AdjointPhotoatomCore_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/photon/src/MonteCarlo_AdjointPhotoatomCore_def.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_AdjointPhotoatomCore_def.hpp //! \author Alex Robinson //! \brief The adjoint photoatom core class template definitions //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_ADJOINT_PHOTOATOM_CORE_DEF_HPP #define MONTE_CARLO_ADJOINT_PHOTOATOM_CORE_DEF_HPP // FRENSIE Includes #include "MonteCarlo_AbsorptionAdjointPhotoatomicReaction.hpp" #include "MonteCarlo_VoidAbsorptionAdjointPhotoatomicReaction.hpp" #include "MonteCarlo_VoidAtomicRelaxationModel.hpp" #include "Utility_DesignByContract.hpp" namespace MonteCarlo{ // Constructor /*! \details Care must be taken when setting the critical line energies, * scattering reactions and line energy reactions. The critical line energies * must correspond to the critical line energies that are being used by the * incoherent scattering reactions. In addition, every line energy reaction * must have a corresponding critical line energy. Without a critical line * energy the line energy reaction will never occur. */ template<typename InterpPolicy> AdjointPhotoatomCore::AdjointPhotoatomCore( const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const std::shared_ptr<const std::vector<double> >& critical_line_energies, const std::shared_ptr<const PhotoatomicReaction>& total_forward_reaction, const ConstReactionMap& scattering_reactions, const ConstReactionMap& absorption_reactions, const ConstLineEnergyReactionMap& line_energy_reactions, const bool processed_atomic_cross_section, const InterpPolicy policy ) : BaseType( critical_line_energies, total_forward_reaction, scattering_reactions, absorption_reactions, line_energy_reactions, std::make_shared<VoidAtomicRelaxationModel>(), grid_searcher ) { // Make sure the energy grid is valid testPrecondition( energy_grid->size() > 1 ); testPrecondition( Utility::Sort::isSortedAscending( energy_grid->begin(), energy_grid->end() ) ); // Create the total absorption and total reactions if( processed_atomic_cross_section ) { if( this->getAbsorptionReactions().size() > 0 ) { this->createProcessedTotalAbsorptionReaction<InterpPolicy,AbsorptionAdjointPhotoatomicReaction>( energy_grid, TOTAL_ABSORPTION_ADJOINT_PHOTOATOMIC_REACTION ); } else { // Create void absorption reaction this->setTotalAbsorptionReaction( std::make_shared<VoidAbsorptionAdjointPhotoatomicReaction>() ); } this->createProcessedTotalReaction<InterpPolicy,AbsorptionAdjointPhotoatomicReaction>( energy_grid, TOTAL_ADJOINT_PHOTOATOMIC_REACTION ); } else { if( this->getAbsorptionReactions().size() > 0 ) { this->createTotalAbsorptionReaction<InterpPolicy,AbsorptionAdjointPhotoatomicReaction>( energy_grid, TOTAL_ABSORPTION_ADJOINT_PHOTOATOMIC_REACTION ); } else { // Create void absorption reaction this->setTotalAbsorptionReaction( std::make_shared<VoidAbsorptionAdjointPhotoatomicReaction>() ); } this->createTotalReaction<InterpPolicy,AbsorptionAdjointPhotoatomicReaction>( energy_grid, TOTAL_ADJOINT_PHOTOATOMIC_REACTION ); } } } // end MonteCarlo namespace #endif // end MONTE_CARLO_ADJOINT_PHOTOATOM_CORE_DEF_HPP //---------------------------------------------------------------------------// // end MonteCarlo_AdjointPhotoatomCore_def.hpp //---------------------------------------------------------------------------//
40.626263
103
0.649428
[ "vector" ]
a6a9be3f381f9dfeb83c014b5689f5769c68f0b0
4,741
cpp
C++
aladdin/core/SceneConfiguration.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
2
2017-11-08T16:27:25.000Z
2018-08-10T09:08:35.000Z
aladdin/core/SceneConfiguration.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
null
null
null
aladdin/core/SceneConfiguration.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
4
2017-11-08T16:25:30.000Z
2021-05-23T06:14:59.000Z
#include "SceneConfiguration.h" #include "../pugixml/pugixml.hpp" NAMESPACE_ALA { ALA_CLASS_SOURCE_1(SceneConfiguration, ala::GameResource) const std::vector<SceneObjectConfiguration>& SceneConfiguration::getObjectConfigurations() const { return _objectConfigurations; } bool SceneConfiguration::isPhysicsEnabled() const { return _physicsEnabled; } const Vec2& SceneConfiguration::getPhysicsGravity() const { return _physicsGravity; } bool SceneConfiguration::isQuadTreeEnabled() const { return _quadTreeEnabled; } float SceneConfiguration::getSpaceMinX() const { return _spaceMinX; } float SceneConfiguration::getSpaceMinY() const { return _spaceMinY; } float SceneConfiguration::getSpaceWidth() const { return _spaceWidth; } float SceneConfiguration::getSpaceHeight() const { return _spaceHeight; } int SceneConfiguration::getQuadTreeLevel() const { return _quadTreeLevel; } void SceneConfiguration::onLoad() { pugi::xml_document document; pugi::xml_parse_result result = document.load_file( _sourceFile.c_str() ); ALA_ASSERT(result); std::stringstream stringBuilder; std::string str; const auto& sceneNode = document.child( "Scene" ); const auto& physicsNode = sceneNode.child( "physics" ); if ( !physicsNode.empty() ) { str = physicsNode.attribute( "gravity" ).as_string( "" ); if ( !str.empty() ) { stringBuilder.clear(); stringBuilder.str( str ); float x, y; stringBuilder >> x >> y; _physicsEnabled = true; _physicsGravity = Vec2( x, y ); } else { _physicsEnabled = false; } } else { _physicsEnabled = false; } const auto& quadNode = sceneNode.child( "quad" ); if ( !quadNode.empty() ) { _quadTreeLevel = quadNode.attribute( "level" ).as_int( 3 ); _spaceMinX = quadNode.attribute( "minX" ).as_float( 0 ); _spaceMinY = quadNode.attribute( "minY" ).as_float( 0 ); _spaceWidth = quadNode.attribute( "width" ).as_float( 0 ); _spaceHeight = quadNode.attribute( "height" ).as_float( 0 ); _quadTreeEnabled = true; } else { _quadTreeEnabled = false; } const auto& objectNodes = sceneNode.children( "object" ); _objectConfigurations.clear(); for ( const auto& objectNode : objectNodes ) { SceneObjectConfiguration objectConfiguration; objectConfiguration.name = objectNode.attribute( "name" ).as_string( "" ); objectConfiguration.layer = objectNode.attribute( "layer" ).as_string( "" ); objectConfiguration.tag = objectNode.attribute( "tag" ).as_int( -1 ); objectConfiguration.quadIndex = objectNode.attribute( "quadIndex" ).as_string( "" ); const auto& prefabNode = objectNode.child( "prefab" ); if ( !prefabNode.empty() ) { objectConfiguration.prefabName = prefabNode.attribute( "name" ).as_string( "" ); objectConfiguration.prefabVersion = prefabNode.attribute( "version" ).as_int( 1 ); objectConfiguration.prefabArgs = prefabNode.attribute( "args" ).as_string( "" ); } else { objectConfiguration.prefabName = ""; objectConfiguration.prefabVersion = 0; } const auto& transformNode = objectNode.child( "transform" ); if ( !transformNode.empty() ) { str = transformNode.attribute( "position" ).as_string( "" ); if ( !str.empty() ) { stringBuilder.clear(); stringBuilder.str( str ); float x, y; stringBuilder >> x >> y; objectConfiguration.applyTransformPosition = true; objectConfiguration.transformPosition = Vec2( x, y ); } else { objectConfiguration.applyTransformPosition = false; } str = transformNode.attribute( "scale" ).as_string( "" ); if ( !str.empty() ) { stringBuilder.clear(); stringBuilder.str( str ); float x, y; stringBuilder >> x >> y; objectConfiguration.applyTransformScale = true; objectConfiguration.transformScale = Vec2( x, y ); } else { objectConfiguration.applyTransformScale = false; } str = transformNode.attribute( "rotation" ).as_string( "" ); if ( !str.empty() ) { stringBuilder.clear(); stringBuilder.str( str ); float r; stringBuilder >> r; objectConfiguration.applyTransformRotation = true; objectConfiguration.transformRotation = r; } else { objectConfiguration.applyTransformRotation = false; } } else { objectConfiguration.applyTransformPosition = false; objectConfiguration.applyTransformScale = false; objectConfiguration.applyTransformRotation = false; } _objectConfigurations.push_back( objectConfiguration ); } } void SceneConfiguration::onRelease() {} }
29.447205
98
0.669057
[ "object", "vector", "transform" ]
a6ae600c3bca11c94718648c7a480291badb7b26
4,952
cc
C++
Util.cc
simoncblyth/OptiXTest
1c800add9b5b49c9441cbd3c54c689cfe1cac9dd
[ "Apache-2.0" ]
null
null
null
Util.cc
simoncblyth/OptiXTest
1c800add9b5b49c9441cbd3c54c689cfe1cac9dd
[ "Apache-2.0" ]
null
null
null
Util.cc
simoncblyth/OptiXTest
1c800add9b5b49c9441cbd3c54c689cfe1cac9dd
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <string> #include <cstring> #include <cstdlib> #include <iostream> #include <iomanip> #include <vector> #include <cassert> #include "Util.h" #include <glm/gtx/transform.hpp> const char* Util::PTXPath( const char* install_prefix, const char* cmake_target, const char* cu_stem, const char* cu_ext ) // static { std::stringstream ss ; ss << install_prefix << "/ptx/" << cmake_target << "_generated_" << cu_stem << cu_ext << ".ptx" ; std::string path = ss.str(); return strdup(path.c_str()); } template <typename T> T Util::ato_( const char* a ) // static { std::string s(a); std::istringstream iss(s); T v ; iss >> v ; return v ; } /** Util::ParseGridSpec ---------------------- Parse a python style xyz gridspec eg "-10:11:2,-10:11:2,-10:11:2" into a list of 9 ints. **/ void Util::ParseGridSpec( std::array<int,9>& grid, const char* spec) // static { int idx = 0 ; std::stringstream ss(spec); std::string s; while (std::getline(ss, s, ',')) { std::stringstream tt(s); std::string t; while (std::getline(tt, t, ':')) grid[idx++] = std::atoi(t.c_str()) ; } std::cout << "Util::ParseGridSpec " << spec << " : " ; for(int i=0 ; i < 9 ; i++) std::cout << grid[i] << " " ; std::cout << std::endl ; } void Util::GridMinMax(const std::array<int,9>& grid, int3&mn, int3& mx) // static { mn.x = grid[0] ; mx.x = grid[1] ; mn.y = grid[3] ; mx.y = grid[4] ; mn.z = grid[6] ; mx.z = grid[7] ; } void Util::GridMinMax(const std::array<int,9>& grid, int&mn, int& mx) // static { for(int a=0 ; a < 3 ; a++) for(int i=grid[a*3+0] ; i < grid[a*3+1] ; i+=grid[a*3+2] ) { if( i > mx ) mx = i ; if( i < mn ) mn = i ; } std::cout << "Util::GridMinMax " << mn << " " << mx << std::endl ; } template <typename T> T Util::GetEValue(const char* key, T fallback) // static { const char* sval = getenv(key); T val = sval ? ato_<T>(sval) : fallback ; return val ; } template <typename T> void Util::GetEVector(std::vector<T>& vec, const char* key, const char* fallback ) { const char* sval = getenv(key); std::stringstream ss(sval ? sval : fallback); std::string s ; while(getline(ss, s, ',')) vec.push_back(ato_<T>(s.c_str())); } void Util::GetEVec(glm::vec3& v, const char* key, const char* fallback ) { std::vector<float> vec ; Util::GetEVector<float>(vec, key, fallback); std::cout << key << Util::Present(vec) << std::endl ; assert( vec.size() == 3 ); for(int i=0 ; i < 3 ; i++) v[i] = vec[i] ; } void Util::GetEVec(glm::vec4& v, const char* key, const char* fallback ) { std::vector<float> vec ; Util::GetEVector<float>(vec, key, fallback); std::cout << key << Util::Present(vec) << std::endl ; assert( vec.size() == 4 ); for(int i=0 ; i < 4 ; i++) v[i] = vec[i] ; } template <typename T> std::string Util::Present(std::vector<T>& vec) { std::stringstream ss ; for(unsigned i=0 ; i < vec.size() ; i++) ss << vec[i] << " " ; return ss.str(); } bool Util::StartsWith( const char* s, const char* q) // static { return strlen(q) <= strlen(s) && strncmp(s, q, strlen(q)) == 0 ; } void Util::DumpGrid(const std::array<int,9>& cl) { int i0 = cl[0] ; int i1 = cl[1] ; int is = cl[2] ; int j0 = cl[3] ; int j1 = cl[4] ; int js = cl[5] ; int k0 = cl[6] ; int k1 = cl[7] ; int ks = cl[8] ; unsigned num = 0 ; for(int i=i0 ; i < i1 ; i+=is ) for(int j=j0 ; j < j1 ; j+=js ) for(int k=k0 ; k < k1 ; k+=ks ) { std::cout << std::setw(2) << num << " (i,j,k) " << "(" << i << "," << j << "," << k << ") " << std::endl ; num += 1 ; } } unsigned Util::Encode4(const char* s) // static { unsigned u4 = 0u ; for(unsigned i=0 ; i < std::min(4ul, strlen(s)) ; i++ ) { unsigned u = unsigned(s[i]) ; u4 |= ( u << (i*8) ) ; } return u4 ; } template float Util::GetEValue<float>(const char* key, float fallback); template int Util::GetEValue<int>(const char* key, int fallback); template unsigned Util::GetEValue<unsigned>(const char* key, unsigned fallback); template std::string Util::GetEValue<std::string>(const char* key, std::string fallback); template bool Util::GetEValue<bool>(const char* key, bool fallback); template void Util::GetEVector<unsigned>(std::vector<unsigned>& vec, const char* key, const char* fallback ); template void Util::GetEVector<float>(std::vector<float>& vec, const char* key, const char* fallback ); template std::string Util::Present<float>(std::vector<float>& ); template std::string Util::Present<unsigned>(std::vector<unsigned>& ); template std::string Util::Present<int>(std::vector<int>& );
26.623656
132
0.551696
[ "vector", "transform" ]
a6ae61ecdc428482cacb1674fc27ec7768085dd1
866
hpp
C++
deps/src/boost_1_65_1/boost/mpi/detail/antiques.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
deps/src/boost_1_65_1/boost/mpi/detail/antiques.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
deps/src/boost_1_65_1/boost/mpi/detail/antiques.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
// Copyright Alain Miniussi 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Alain Miniussi #ifndef BOOST_MPI_ANTIQUES_HPP #define BOOST_MPI_ANTIQUES_HPP #include <vector> // Support for some obsolette compilers namespace boost { namespace mpi { namespace detail { // Some old gnu compiler have no support for vector<>::data // Use this in the mean time, the cumbersome syntax should // serve as an incentive to get rid of this when those compilers // are dropped. template <typename T, typename A> T* c_data(std::vector<T,A>& v) { return &(v[0]); } template <typename T, typename A> T const* c_data(std::vector<T,A> const& v) { return &(v[0]); } } } } #endif
28.866667
70
0.665127
[ "vector" ]
a6b0fad9723b33dcc965a92217a18bcfa00c0d21
4,527
cc
C++
media/mojo/services/media_type_converters.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/mojo/services/media_type_converters.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/mojo/services/media_type_converters.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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. #include "media/mojo/services/media_type_converters.h" #include "base/macros.h" #include "media/base/buffering_state.h" #include "media/base/decoder_buffer.h" #include "mojo/public/cpp/system/data_pipe.h" namespace mojo { #define ASSERT_ENUM_VALUES_EQUAL(value) \ COMPILE_ASSERT(media::BUFFERING_##value == \ static_cast<media::BufferingState>(BUFFERING_STATE_##value), \ value##_enum_value_matches) ASSERT_ENUM_VALUES_EQUAL(HAVE_NOTHING); ASSERT_ENUM_VALUES_EQUAL(HAVE_ENOUGH); // static MediaDecoderBufferPtr TypeConverter<MediaDecoderBufferPtr, scoped_refptr<media::DecoderBuffer> >::Convert( const scoped_refptr<media::DecoderBuffer>& input) { MediaDecoderBufferPtr mojo_buffer(MediaDecoderBuffer::New()); mojo_buffer->timestamp_usec = input->timestamp().InMicroseconds(); mojo_buffer->duration_usec = input->duration().InMicroseconds(); mojo_buffer->data_size = input->data_size(); mojo_buffer->side_data_size = input->side_data_size(); mojo_buffer->front_discard_usec = input->discard_padding().first.InMicroseconds(); mojo_buffer->back_discard_usec = input->discard_padding().second.InMicroseconds(); mojo_buffer->splice_timestamp_usec = input->splice_timestamp().InMicroseconds(); // TODO(tim): Assuming this is small so allowing extra copies. std::vector<uint8> side_data(input->side_data(), input->side_data() + input->side_data_size()); mojo_buffer->side_data.Swap(&side_data); MojoCreateDataPipeOptions options; options.struct_size = sizeof(MojoCreateDataPipeOptions); options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE; options.element_num_bytes = 1; options.capacity_num_bytes = input->data_size(); DataPipe data_pipe(options); mojo_buffer->data = data_pipe.consumer_handle.Pass(); uint32_t num_bytes = input->data_size(); // TODO(tim): ALL_OR_NONE isn't really appropriate. Check success? // If fails, we'd still return the buffer, but we'd need to HandleWatch // to fill the pipe at a later time, which means the de-marshalling code // needs to wait for a readable pipe (which it currently doesn't). WriteDataRaw(data_pipe.producer_handle.get(), input->data(), &num_bytes, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE); return mojo_buffer.Pass(); } // static scoped_refptr<media::DecoderBuffer> TypeConverter< scoped_refptr<media::DecoderBuffer>, MediaDecoderBufferPtr>::Convert( const MediaDecoderBufferPtr& input) { uint32_t num_bytes = 0; // TODO(tim): We're assuming that because we always write to the pipe above // before sending the MediaDecoderBuffer that the pipe is readable when // we get here. ReadDataRaw(input->data.get(), NULL, &num_bytes, MOJO_READ_DATA_FLAG_QUERY); CHECK_EQ(num_bytes, input->data_size) << "Pipe error converting buffer"; scoped_ptr<uint8[]> data(new uint8[num_bytes]); // Uninitialized. ReadDataRaw(input->data.get(), data.get(), &num_bytes, MOJO_READ_DATA_FLAG_ALL_OR_NONE); CHECK_EQ(num_bytes, input->data_size) << "Pipe error converting buffer"; // TODO(tim): We can't create a media::DecoderBuffer that has side_data // without copying data because it wants to ensure alignment. Could we // read directly into a pre-padded DecoderBuffer? scoped_refptr<media::DecoderBuffer> buffer; if (input->side_data_size) { buffer = media::DecoderBuffer::CopyFrom(data.get(), num_bytes, input->side_data.storage().data(), input->side_data_size); } else { buffer = media::DecoderBuffer::CopyFrom(data.get(), num_bytes); } buffer->set_timestamp( base::TimeDelta::FromMicroseconds(input->timestamp_usec)); buffer->set_duration( base::TimeDelta::FromMicroseconds(input->duration_usec)); media::DecoderBuffer::DiscardPadding discard_padding( base::TimeDelta::FromMicroseconds(input->front_discard_usec), base::TimeDelta::FromMicroseconds(input->back_discard_usec)); buffer->set_discard_padding(discard_padding); buffer->set_splice_timestamp( base::TimeDelta::FromMicroseconds(input->splice_timestamp_usec)); return buffer; } } // namespace mojo
42.707547
78
0.709079
[ "vector" ]
a6b58113827f53b44f4d9b6d130f8cb59a1375eb
6,566
inl
C++
inc/vec/v.inl
TomSmartBishop/avl
75475d2648de5f771d7c7186061d60508a608ad6
[ "MIT" ]
2
2016-08-03T22:19:54.000Z
2016-08-26T08:55:55.000Z
inc/vec/v.inl
TomSmartBishop/avl
75475d2648de5f771d7c7186061d60508a608ad6
[ "MIT" ]
null
null
null
inc/vec/v.inl
TomSmartBishop/avl
75475d2648de5f771d7c7186061d60508a608ad6
[ "MIT" ]
null
null
null
#ifndef AVL_V_INL #define AVL_V_INL #pragma once /// avl: A Vector Library /// \author Thomas Pollak namespace avl { /// \defgroup Helper functions /// \{ //Component type helper avl_ainl_res constexpr auto cmp(const v& vec) noexcept -> rem_const_ref_t<decltype(vec[0])> { return vec[0]; } /// \} /// \defgroup Getters and setters for all vectors /// \{ /// Access the vector components by a range checked index from 0 to dim-1 avl_ainl_res constexpr auto get(const v& vec, const s::size_t idx) noexcept(ndebug||exuse) -> decltype(cmp(vec)) { assert(idx < dim< rem_const_ref_t< decltype( vec ) > >::value); return vec[idx]; } /// Access the vector components by a static range checked index from 0 to dim-1 template<s::size_t _Idx> avl_ainl_res constexpr auto get(const v& vec) noexcept -> decltype(cmp(vec)) { static_assert(_Idx < dim< rem_const_ref_t< decltype( vec ) > >::value, "Index is out of range"); return vec[_Idx]; } /// Set a single component by index from 0 to dim-1 avl_ainl constexpr auto set(v& vec, const s::size_t idx, const sc scalar) noexcept(ndebug||exuse) -> void { static_assert(eq< decltype( vec[idx] ), decltype( scalar ) >::value, "Supply a scalar of the vectors element type."); assert(idx < dim< rem_const_ref_t< decltype( vec ) > >::value); vec[idx] = scalar; } /// Set a single component by static index from 0 to dim-1 template<s::size_t _Idx> avl_ainl constexpr auto set(v& vec, const sc scalar) noexcept -> void { static_assert(eq< decltype( vec[_Idx] ), decltype( scalar ) >::value, "Supply a scalar of the vectors element type."); static_assert(_Idx < dim< rem_const_ref_t< decltype( vec ) > >::value, "Index is out of range"); vec[_Idx] = scalar; } /// \} /// \defgroup Vector length operations /// \{ /// Returns a new vector with the requested length avl_ainl_res constexpr auto setlen_mk(const v& vec, const sc len_to_set) noexcept(ndebug||exuse) { const auto vec_len = len(vec); assert(vec_len!=cnst<decltype(vec_len)>::zero); return mul_mk(vec, len_to_set / vec_len); } /// Set the length of the vector avl_ainl constexpr auto setlen_set(v& vec, const sc len_to_set) noexcept(ndebug||exuse) -> void { const auto vec_len = len(vec); assert(vec_len!=cnst<decltype(vec_len)>::zero); mul_set(vec, len_to_set / vec_len); } /// Set the length of the vector and return the same vector (chained) avl_ainl_res constexpr auto setlen(v& vec, const sc len_to_set) noexcept(ndebug||exuse) -> decltype(vec) { const auto vec_len = len(vec); assert(vec_len!=cnst<decltype(vec_len)>::zero); mul_set(vec, len_to_set / vec_len); return vec; } /// Calculate the length of the vector, prefere len_sqr when comparing distances avl_ainl_res constexpr auto len(const v& vec) noexcept -> decltype(cmp(vec)) { //len_sqr will never return any negativ values so we can gurantee noexcept const auto vec_square_len = len_sqr(vec); return static_cast<decltype(cmp(vec))>( s::sqrt( vec_square_len ) ); } /// Returns a normalized vector avl_ainl_res constexpr auto norm_mk(const v& vec ) noexcept(ndebug||exuse) { const auto vec_len = len(vec); return div_mk(vec, vec_len); //div might assert in debug } /// Returns a normalized vector, use alternative vector if the current vector length is 0 avl_ainl_res constexpr auto norm_mk(const v& vec , const v& vec_if_zero_len) noexcept { const auto vec_len = len(vec); if(vec_len==cnst<decltype(vec_len)>::zero) return vec_if_zero_len; return div_mk(vec, vec_len); //div might assert in debug } /// Normalize the current vector avl_ainl constexpr auto norm_set(v& vec ) noexcept -> void { const auto vec_len = len(vec); div_set(vec, vec_len); //div might assert in debug } /// Normalize the current vector, use alternative vector if the current vector length is 0 avl_ainl constexpr auto norm_set(v& vec , const v& vec_if_zero_len) noexcept -> void { const auto vec_len = len(vec); if(vec_len==cnst<decltype(vec_len)>::zero) { vec = vec_if_zero_len; return; } div_set(vec, vec_len); //div might assert in debug } /// Normalize the current vector and return the same vector (chained) avl_ainl_res constexpr auto norm(v& vec ) noexcept -> decltype(vec) { const auto vec_len = len(vec); div_set(vec, vec_len); //div might assert in debug return vec; } /// Normalize the current vector and return the same vector (chained), use alternative vector if the current vector length is 0 avl_ainl_res constexpr auto norm(v& vec , const v& vec_if_zero_len) noexcept -> decltype(vec) { const auto vec_len = len(vec); if(vec_len==cnst<decltype(vec_len)>::zero) { vec = vec_if_zero_len; return vec; } div_set(vec, vec_len); //div might assert in debug return vec; } /// \} /// \defgroup Spacial operations /// \{ /// Calculate the angle between two vectors in radian avl_ainl_res constexpr auto angle_rd(const v& vec, const decltype(vec) other) noexcept -> decltype(cmp(vec)) { const auto vec_len = len(vec); const auto other_len = len(other); const auto dot_prod = dot(vec, other); return s::acos( dot_prod / ( vec_len * other_len ) ); } /// Calculate the angle between two vectors in degree avl_ainl_res constexpr auto angle_dg(const v& vec, const decltype(vec) other) noexcept -> decltype(cmp(vec)) { const auto vec_len = len(vec); const auto other_len = len(other); const auto dot_prod = dot(vec, other); return s::acos( dot_prod / ( vec_len * other_len ) ) * cnst<decltype(cmp(vec))>::to_deg; } /// Get the direction relative to another point excluding colinear and opposite-but-colinear (faster than get_dir_col) avl_ainl_res constexpr auto get_dir(const v& vec, const v& other) noexcept -> dir { const auto dotProduct = dot(vec, other); if( utl::eqls(dotProduct, decltype(dotProduct){0}, cnst<decltype(cmp(vec))>::big_epsln) ) { return dir::perpend; } else if( dotProduct > decltype(dotProduct){0}) { return dir::same; } else { return dir::opp; } } /// Get the direction relative to another point excluding colinear and opposite-but-colinear (faster than get_dir_col) avl_ainl_res constexpr auto get_dir(const v& vec, const v& other, const sc epsilon) noexcept -> dir { const auto dotProduct = dot(vec, other); if( utl::eqls(dotProduct, decltype(dotProduct){0}, epsilon) ) { return dir::perpend; } else if( dotProduct > decltype(dotProduct){0}) { return dir::same; } else { return dir::opp; } } /// \} } #endif // AVL_V_INL
33.161616
128
0.699208
[ "vector" ]
a6c5ef5e5eed1e35b04e889bc69545f250149cd8
2,469
cpp
C++
Problems/Hackerrank/smartNumber.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
1
2021-07-08T01:02:06.000Z
2021-07-08T01:02:06.000Z
Problems/Hackerrank/smartNumber.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
Problems/Hackerrank/smartNumber.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
/*********************************************************************************************/ /* Problem: Smart Number (HR) ********/ /*********************************************************************************************/ /* --Problem statement: In this challenge, the task is to debug the existing code to successfully execute all provided test files. A number is called a smart number if it has an odd number of factors. Given some numbers, find whether they are smart numbers or not. Debug the given function "is_smart_number" to correctly check if a given number is a smart number. Note: You can modify only one line in the given code and you cannot add or remove any new lines. -- Inputs: - int n: integer number --Outputs: - bool: boolean indicating whether or not the number has an odd numbers of factors. --Reasoning: Perfect squares have odd unique factors. For a given number 'N', we can group its divisors, 'D', in pairs (D,N/D), except that if N=M^2, this would pair M with itself. You can always list the factors of a number, 'N', into pairs (Ai,Bi) where Ai<=sqrt(N)<=Bi. This means that a number will always have an even number of factors, unless the number is a perfect square, in which case one pair will consist of the same two numbers. > Example - factors of 36 (1,36) (2,18) (3,12) (4,9) (6,6) A total of 9 unique factors since 6 repeats itself. Or, 5 unique divisors. In the solution below, since a casting to <int> is being performed to the result of the square root operation, in order to check if it's a perfect square we cast 'val' to <double> to make sure that we're not neglecting anything after the decimal point and check if (num/val) is equal to 'val' itself, which would make num = val*val, hence 'num' is a perfect square and should have odd factors. --Time complexity: O(1) --Space complexity: O(1) */ #include <iostream> #include <vector> #include <cmath> bool is_smart_number(int num) { int val = (int)std::sqrt(num); if ((num / (double)val == val)) return true; return false; } int main() { std::vector<int> test_cases{1, 2, 7, 169}; for (int i = 0; i < test_cases.size(); i++) { bool ans = is_smart_number(test_cases.at(i)); if (ans) { std::cout << "YES" << std::endl; } else std::cout << "NO" << std::endl; } return 0; } /* Expected: YES NO NO YES */
30.109756
102
0.611989
[ "vector" ]
a6cd1b1041e018643b04a927fcfaf86a9c240c5b
20,661
hpp
C++
src/toolkits/sparse_similarity/neighbor_search.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/toolkits/sparse_similarity/neighbor_search.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/toolkits/sparse_similarity/neighbor_search.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_SPARSE_SIMILARITY_NEIGHBOR_SEARCH_H #define TURI_SPARSE_SIMILARITY_NEIGHBOR_SEARCH_H #include <core/storage/sframe_data/sarray.hpp> #include <vector> #include <core/parallel/pthread_tools.hpp> #include <core/util/try_finally.hpp> #include <core/util/dense_bitset.hpp> #include <toolkits/sparse_similarity/similarities.hpp> #include <toolkits/sparse_similarity/item_processing.hpp> namespace turi { namespace sparse_sim { /** Efficiently perform an all-pairs brute force processing as * possible over sarrays of sparse, sorted vectors. * * reference_data and query_data are two sarrays of sparse vectors. * A similarity score is calculated between each entry of * reference_data and each entry of query_data, with process_function * called for each (minus exceptions below). * * * Reference_item_info and query_item_info are obtained from calling * one of the methods in item_processing.hpp. * * The SimilarityType similarity function is defined as one of the * classes in similarities.hpp, or a class that also conforms to a * similar interface. * * process_function should have the signature * * process_function(size_t reference_idx, size_t query_idx, double similarity) * * It is called in parallel for each reference and query entry. * * num_dimensions is the maximum dimension of each sparse vector. An * error is raised if any index is >= num_dimensions. * * max_memory_usage is used to determine the block size for doing the * query; a larger value of this means fewer passes through the * reference set. * * skip_pair has the signature * * skip_pair(size_t reference_idx, size_t query_idx) -> bool * * If true, then the similarity score for that item is not calculated * for that reference_idx and query_idx pair. Normally, this can be * set to return false, in which case nothing is skipped. (This is * used, for example, if the reference_data and the query_data are the * same, and only one direction is calculated. * * If provided, query_mask is a dense_bitset of the same length as * query_data. If a particular entry is false, then that row is * skipped in the similarity comparisons. */ template <typename SimilarityType, typename ProcessFunction, typename SkipFunction> void brute_force_all_pairs_similarity_with_vector_reference( std::shared_ptr<sarray<std::vector<std::pair<size_t, double> > > > reference_data, const std::vector<item_processing_info<SimilarityType> >& reference_item_info, std::shared_ptr<sarray<std::vector<std::pair<size_t, double> > > > query_data, const std::vector<item_processing_info<SimilarityType> >& query_item_info, const SimilarityType& similarity, ProcessFunction&& process_function, size_t num_dimensions, size_t max_memory_usage, SkipFunction&& skip_pair, const dense_bitset* query_mask = nullptr) { // The vertex type is used as reference later on. typedef typename SimilarityType::item_data_type item_data_type; typedef typename SimilarityType::interaction_data_type interaction_data_type; typedef typename SimilarityType::final_item_data_type final_item_data_type; typedef typename SimilarityType::final_interaction_data_type final_interaction_data_type; // Set constants used later. static constexpr bool use_final_item_data = ( !std::is_same<unused_value_type, final_item_data_type>::value); static constexpr bool missing_values_are_zero = SimilarityType::missing_values_are_zero(); final_item_data_type _unused; // constants used later size_t max_num_threads = thread::cpu_count(); size_t num_query_rows = query_data->size(); size_t num_reference_rows = reference_data->size(); bool using_mask = (query_mask != nullptr); //////////////////////////////////////////////////////////////////////////////// // Check input DASSERT_NE(num_dimensions, 0); DASSERT_EQ(reference_item_info.size(), reference_data->size()); DASSERT_EQ(query_item_info.size(), query_data->size()); if(using_mask) { DASSERT_EQ(query_mask->size(), query_data->size()); } //////////////////////////////////////////////////////////////////////////////// // If we are using a mask, then the number of query rows is // calculated from that. if(using_mask) { num_query_rows = query_mask->popcount(); } // Nothing to do here. if(num_query_rows == 0) return; // Set the block size as a function of the maximum memory usage. size_t max_query_rows_per_block = max_memory_usage / (num_dimensions * sizeof(double)); max_query_rows_per_block = std::max(max_num_threads, max_query_rows_per_block); max_query_rows_per_block = std::min(num_query_rows, max_query_rows_per_block); // This is needed, as we use an int counter in the inner loop to // enable easier autovectorization (see // http://www.slideshare.net/linaroorg/using-gcc-autovectorizer). max_query_rows_per_block = std::min<size_t>( std::numeric_limits<int>::max() / 2, max_query_rows_per_block); // Set up the number of blocks. Number of blocks is the ceiling of // all this. size_t num_blocks = (num_query_rows + (max_query_rows_per_block - 1)) / max_query_rows_per_block; // Now that we have the number of blocks, further minimize memory // use by making the number of query rows per block as even as // possible. That way we won't end up with a single block that has // like 1 row and the rest that have many more. max_query_rows_per_block = (num_query_rows + (num_blocks - 1)) / num_blocks; // Get the reader for the query data. auto query_reader = query_data->get_reader(max_num_threads); // Get the reader for the reference data auto reference_reader = reference_data->get_reader(max_num_threads); // Set up the query data so that all dimensions are contiguous in // memory. That way, on a query, we can do everything for this // element together, thereby optimizing memory access and the // increasing the likelihood that the compiler can vectorize it. std::vector<double> block_data(max_query_rows_per_block * num_dimensions); auto block_data_index = [&](size_t row_idx, size_t element_idx) { DASSERT_LT(row_idx, max_query_rows_per_block); DASSERT_LT(element_idx, num_dimensions); return element_idx * max_query_rows_per_block + row_idx; }; // For all the rows in the current block, this is the actual row // index within that block. std::vector<size_t> block_query_row_indices(max_query_rows_per_block); // The vertex info for each of these rows. std::vector<item_data_type> block_item_data(max_query_rows_per_block); std::vector<final_item_data_type> block_final_item_data; if(use_final_item_data) { block_final_item_data.resize(max_query_rows_per_block); } // Counters indicating where we are within each segment, as each // thread reads a new segment. std::vector<size_t> query_row_counters(max_num_threads, size_t(-1)); // Loop over the blocks. for(size_t block_idx = 0; block_idx < num_blocks; ++block_idx) { // This is the location of the current open slot for dumping one of the rows atomic<size_t> block_write_idx = 0; // Clear out the data in this block. std::fill(block_data.begin(), block_data.end(), missing_values_are_zero ? 0 : NAN); // Fill the block with appropriate rows. in_parallel([&](size_t thread_idx, size_t num_threads) GL_GCC_ONLY(GL_HOT_NOINLINE_FLATTEN) { // This is the segment we are responsible for in this thread. size_t query_row_idx_start = (query_data->size() * thread_idx) / num_threads; size_t query_row_idx_end = (query_data->size() * (thread_idx+1)) / num_threads; // Get the overall current_query_row_index where we are at within the segment // this thread is assigned to. size_t& current_query_row_index = query_row_counters[thread_idx]; // Check for initializing it at the appropriate location. if(current_query_row_index == size_t(-1)) { // It has not been initialized yet; do it at the start of our segment. current_query_row_index = query_row_idx_start; } // Row buffer. std::vector<std::vector<std::pair<size_t, double> > > row_v(1); // Now, read in rows until we are out of space in this block, // or until we are out of rows in this reading segment. while(current_query_row_index < query_row_idx_end) { // If we are using the query mask, then check if we are in a // valid spot. If not, then advance forward until we are. if(using_mask && !query_mask->get(current_query_row_index)) { size_t new_q_idx = current_query_row_index; bool any_more = query_mask->next_bit(new_q_idx); if(UNLIKELY(!any_more || new_q_idx >= query_row_idx_end)) { // Done. current_query_row_index = query_row_idx_end; break; } else { DASSERT_NE(current_query_row_index, new_q_idx); // Next row. current_query_row_index = new_q_idx; } } if(using_mask) { // Just make sure we've got a live one. DASSERT_TRUE(query_mask->get(current_query_row_index)); } // Get the next index. size_t internal_block_idx = (++block_write_idx) - 1; // Do we have a place in the to put this? If not, break and // leave this position for the next block. if(internal_block_idx >= max_query_rows_per_block) { break; } // Assert that we do indeed have a row left. DASSERT_LT(current_query_row_index, query_row_idx_end); // Now that we know we have a spot in the block, write it // out to the block data. query_reader->read_rows(current_query_row_index, current_query_row_index + 1, row_v); const auto& row = row_v[0]; // Write block_query_row_indices[internal_block_idx] = current_query_row_index; block_item_data[internal_block_idx] = query_item_info[current_query_row_index].item_data; // Write out the final vertex data. if(use_final_item_data) { block_final_item_data[internal_block_idx] = query_item_info[current_query_row_index].final_item_data; } // Write the row out to the block data. for(size_t i = 0; i < row.size(); ++i) { size_t idx = block_data_index(internal_block_idx, row[i].first); block_data[idx] = row[i].second; } // Finally, advance the counter to continue. ++current_query_row_index; } // If we are on the last pass, make sure that we have // covered all the query data. if(block_idx == num_blocks - 1) { DASSERT_EQ(current_query_row_index, query_row_idx_end); } }); // Check to make sure our math is correct regarding the number of query // rows and the number of blocks. #ifndef NDEBUG { size_t _block_write_idx = block_write_idx; // cause of atomic if(block_idx < num_blocks - 1) { DASSERT_GE(_block_write_idx, max_query_rows_per_block); } else { DASSERT_LE(_block_write_idx, max_query_rows_per_block); } // Readjust the size of the block (num_query_rows_in_block) if needed. if(block_write_idx < max_query_rows_per_block) { // Everything is done, so it must be in the last block DASSERT_EQ(block_idx, num_blocks - 1); } } #endif // Set the number of query rows in this block. The // block_write_idx may have been incremented multiple times by // different threads. size_t num_query_rows_in_block = std::min<size_t>(block_write_idx, max_query_rows_per_block); // If all the math is correct, this block will never be empty. DASSERT_GT(num_query_rows_in_block, 0); // Now, if we're using a mask, make sure all the indices are // masked properly. #ifndef NDEBUG { if(using_mask) { for(size_t i = 0; i < num_query_rows_in_block; ++i) { DASSERT_TRUE(query_mask->get(block_query_row_indices[i])); } } } #endif // Okay, now that we have a specific block of query data, go // through and perform the nearest neighbors query on it. in_parallel([&](size_t thread_idx, size_t num_threads) GL_GCC_ONLY(GL_HOT_NOINLINE_FLATTEN) { // This is the segment we are responsible for in this thread. size_t reference_row_idx_start = (num_reference_rows * thread_idx) / num_threads; size_t reference_row_idx_end = (num_reference_rows * (thread_idx+1)) / num_threads; const size_t n_reference_rows_per_block = 16; std::vector<std::vector<std::pair<size_t, double> > > reference_rows_v; std::vector<interaction_data_type> edges(num_query_rows_in_block); // Read it in in blocks of n_reference_rows_per_block rows for efficiency. for(size_t outer_idx = reference_row_idx_start; outer_idx < reference_row_idx_end; outer_idx += n_reference_rows_per_block) { //////////////////////////////////////////////////////////////////////////////// reference_reader->read_rows( outer_idx, std::min(outer_idx + n_reference_rows_per_block, reference_row_idx_end), reference_rows_v); if(reference_rows_v.size() != n_reference_rows_per_block) { DASSERT_EQ(outer_idx + reference_rows_v.size(), reference_row_idx_end); } // Now over rows in the buffer. for(size_t inner_idx = 0; inner_idx < reference_rows_v.size(); ++inner_idx) { // Now, for each row, go through and calculate the full intersection. const size_t ref_idx = outer_idx + inner_idx; const auto& row = reference_rows_v[inner_idx]; // Get the information for this particular vertex. item_data_type ref_item_data = reference_item_info[ref_idx].item_data; const final_item_data_type& ref_final_item_data = reference_item_info[ref_idx].final_item_data; // Zero the edges. edges.assign(num_query_rows_in_block, interaction_data_type()); // Get the vertex for this one here. for(const auto& p : row) { size_t dim_index = p.first; double ref_value = p.second; if(missing_values_are_zero) { // This is in the inner loop, so a lot of time is spent // in this computation. Try to make it as friendly as // possible to the vectorizer as possible. double* __restrict__ bd_ptr = &(block_data[block_data_index(0, dim_index)]); item_data_type* __restrict__ it_data_ptr = block_item_data.data(); interaction_data_type* __restrict__ int_data_ptr = edges.data(); for(int i = 0; i < int(num_query_rows_in_block); ++i, ++bd_ptr, ++it_data_ptr, ++int_data_ptr) { similarity.update_interaction_unsafe( *int_data_ptr, ref_item_data, *it_data_ptr, ref_value, *bd_ptr); } } else { for(size_t i = 0; i < num_query_rows_in_block; ++i) { // branching on individual entries, so can't do // vectorization here anyway. double block_data_entry = block_data[block_data_index(i, dim_index)]; if(std::isnan(block_data_entry)) continue; // Aggregate it along this edge. similarity.update_interaction_unsafe( edges[i], ref_item_data, block_item_data[i], ref_value, block_data_entry); } } } // Now, go through, finalize the answers, and record them. for(size_t i = 0; i < num_query_rows_in_block; ++i) { size_t query_index = block_query_row_indices[i]; if(skip_pair(query_index, ref_idx)) continue; // Get the vertex and value info for this query row. const auto& q_item_data = block_item_data[i]; const auto& q_final_item_data = (use_final_item_data ? block_final_item_data[i] : _unused); // Set up the output value. final_interaction_data_type e_out = final_interaction_data_type(); similarity.finalize_interaction(e_out, ref_final_item_data, q_final_item_data, edges[i], ref_item_data, q_item_data); // Now do the meat of the operation -- record the result. process_function(ref_idx, query_index, e_out); } } } }); // Now, we're done, so go to the next block. } } /** An easier-to-use wrapper for the above nearest neighbors search. * reference_data and query_data are two sarrays of sparse vectors. * A similarity score is calculated between each entry of * reference_data and each entry of query_data, with process_function * called for each (minus exceptions below). * The SimilarityType similarity function is defined as one of the * classes in similarities.hpp, or a class that also conforms to a * similar interface. * * process_function should have the signature * * process_function(size_t reference_idx, size_t query_idx, double similarity) * * It is called in parallel for each reference and query entry. * * max_memory_usage is used to determine the block size for doing the * query; a larger value of this means fewer passes through the * reference set. * * skip_pair has the signature * * skip_pair(size_t reference_idx, size_t query_idx) -> bool * * If true, then the similarity score for that item is not calculated * for that reference_idx and query_idx pair. Normally, this can be * set to return false, in which case nothing is skipped. (This is * used, for example, if the reference_data and the query_data are the * same, and only one direction is calculated. * * If provided, query_mask is a dense_bitset of the same length as * query_data. If a particular entry is false, then that row is * skipped in the similarity comparisons. */ template<typename T, typename SimilarityType, typename ProcessFunction, typename SkipFunction> void all_pairs_similarity( std::shared_ptr<sarray<std::vector<std::pair<size_t, T> > > > reference_data, std::shared_ptr<sarray<std::vector<std::pair<size_t, T> > > > query_data, const SimilarityType& similarity, ProcessFunction&& process_function, size_t max_memory_usage, SkipFunction&& skip_pair, const dense_bitset* query_mask = nullptr) { std::vector<item_processing_info<SimilarityType> > reference_item_info; std::vector<item_processing_info<SimilarityType> > query_item_info; size_t reference_num_users = 0; size_t query_num_users = 0; reference_num_users = calculate_item_processing_rowwise( reference_item_info, similarity, reference_data); if(query_data.get() != reference_data.get()) { query_num_users = calculate_item_processing_rowwise(query_item_info, similarity, query_data); } size_t num_dimensions = std::max(reference_num_users, query_num_users); // Now, we have everything we need to use the above function. brute_force_all_pairs_similarity_with_vector_reference( reference_data, reference_item_info, query_data, (query_data.get() == reference_data.get()) ? reference_item_info : query_item_info, similarity, // The process function similarity has has to be translated, so do that here. [&](size_t i, size_t j, const typename SimilarityType::final_interaction_data_type& v) GL_GCC_ONLY(GL_HOT_INLINE_FLATTEN) { process_function(i, j, similarity.export_similarity_score(v)); }, num_dimensions, max_memory_usage, skip_pair, query_mask); } }} #endif
40.118447
99
0.669619
[ "vector" ]
a6cfbef55d813dd9f30c693827475dae5a6c9b96
1,026
cpp
C++
source/geometry/GeometryTanH.cpp
bringtree/MNN
ab711d484cacab41bc90461923bceb1466238217
[ "Apache-2.0" ]
2
2020-12-15T13:56:31.000Z
2022-01-26T03:20:28.000Z
source/geometry/GeometryTanH.cpp
microvn/MNN
a9976c93c58afa9abe974d6b0fc9160a7bc7f0c3
[ "Apache-2.0" ]
null
null
null
source/geometry/GeometryTanH.cpp
microvn/MNN
a9976c93c58afa9abe974d6b0fc9160a7bc7f0c3
[ "Apache-2.0" ]
1
2021-11-24T06:26:27.000Z
2021-11-24T06:26:27.000Z
// // GeometryTanH.cpp // MNN // // Created by MNN on 2020/07/27. // Copyright © 2018, Alibaba Group Holding Limited // #include "geometry/GeometryComputer.hpp" #include "core/OpCommonUtils.hpp" #include "geometry/GeometryComputerUtils.hpp" namespace MNN { class GeometryTanH : public GeometryComputer { public: virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& res) const override { MNN_ASSERT(1 == inputs.size()); MNN_ASSERT(1 == outputs.size()); auto input = inputs[0]; auto output = outputs[0]; auto cmd = GeometryComputerUtils::makeUnary(UnaryOpOperation_TANH, input, output); res.command.emplace_back(std::move(cmd)); return true; } }; static void _create() { std::shared_ptr<GeometryComputer> comp(new GeometryTanH); GeometryComputer::registerGeometryComputer(comp, {OpType_TanH}); } REGISTER_GEOMETRY(GeometryTanH, _create); } // namespace MNN
29.314286
168
0.69883
[ "geometry", "vector" ]
a6d05deb9f1f7c3182141c3411c448cdfdc57ff5
1,472
hpp
C++
core/src/builders/misc/BarrierBuilder.hpp
hexrain/utymap
39cb7684bf014ecc770ed1c46d953f13e103f3f5
[ "Apache-2.0" ]
946
2016-03-13T23:00:37.000Z
2022-03-29T08:35:30.000Z
core/src/builders/misc/BarrierBuilder.hpp
hexrain/utymap
39cb7684bf014ecc770ed1c46d953f13e103f3f5
[ "Apache-2.0" ]
136
2016-03-30T11:54:45.000Z
2020-10-31T13:05:27.000Z
core/src/builders/misc/BarrierBuilder.hpp
hexrain/utymap
39cb7684bf014ecc770ed1c46d953f13e103f3f5
[ "Apache-2.0" ]
168
2016-05-02T15:04:53.000Z
2022-03-28T17:23:26.000Z
#ifndef BUILDERS_MISC_BARRIER_BUILDER_HPP_DEFINED #define BUILDERS_MISC_BARRIER_BUILDER_HPP_DEFINED #include "builders/ElementBuilder.hpp" #include "builders/MeshContext.hpp" namespace utymap { namespace builders { /// Provides the way to build barrier. class BarrierBuilder final : public ElementBuilder { public: explicit BarrierBuilder(const utymap::builders::BuilderContext &context) : ElementBuilder(context) { } void visitNode(const utymap::entities::Node &) override; void visitArea(const utymap::entities::Area &) override; void visitWay(const utymap::entities::Way &way) override; void visitRelation(const utymap::entities::Relation &) override; private: typedef std::vector<GeoCoordinate>::const_iterator Iterator; /// Builds barrier from element. template<typename T> void build(const T &element, Iterator begin, Iterator end); /// Builds barrier as wall. template<typename T> void buildWall(const T &element, Iterator begin, Iterator end, MeshContext &meshContext); /// Builds barrier as pillars. template<typename T> void buildPillar(const T &element, Iterator begin, Iterator end, MeshContext &meshContext); /// Set style if necessary. bool setStyle(const utymap::entities::Element &element); /// Reset style if necessary. void resetStyle(bool isSet); /// Holds style of the element. std::unique_ptr<utymap::mapcss::Style> style_; }; } } #endif // BUILDERS_MISC_BARRIER_BUILDER_HPP_DEFINED
27.259259
93
0.754755
[ "vector" ]
a6d9ef2f8d11155964394584638d1969dd773743
4,072
cpp
C++
lab-midterm-1/part-2/lab-midterm-2.cpp
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
lab-midterm-1/part-2/lab-midterm-2.cpp
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
lab-midterm-1/part-2/lab-midterm-2.cpp
tejashah88/COMSC-165
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
[ "MIT" ]
null
null
null
/* * Name: Question 52 * Class: COMSC-165 * Date: 10/19/2018 * Author: Tejas Shah */ #include <iostream> #include <string> #include <iomanip> #include <vector> using namespace std; const int NUM_QUARTERS = 4; int readInt(); float readFloat(); string readWord(); int readInt() { int input; cin >> input; while (cin.fail()) { cin.clear(); cin.ignore(); cin >> input; } cin.ignore(); return input; } float readFloat() { float input; cin >> input; while (cin.fail()) { cin.clear(); cin.ignore(); cin >> input; } cin.ignore(); return input; } string readWord() { string input; cin >> input; while (cin.fail()) { cin.clear(); cin.ignore(); cin >> input; } cin.ignore(); return input; } /* 3 Americas EMEA APAC 12018 22018 33018 42018 7500 10000 15000 10000 10000 10000 8000 55000 7500 10000 15000 10000 */ void promptQuarterlySales(vector<string> regions, vector<int> quarters, int sales[][NUM_QUARTERS]) { cout << "Enter the quarterly sales data, with all four quarters in one line for each region: " << endl; for (int r = 0; r < regions.size(); r++) { cout << regions[r] << ": "; for (int i = 0; i < 4; i++) sales[r][i] = readInt(); } } float getSingleAverage(int sales[][NUM_QUARTERS], int numRegions, int numQuarters) { float avg = 0.0f; for (int row = 0; row < numRegions; row++) for (int col = 0; col < numQuarters; col++) avg += sales[row][col]; avg /= (numQuarters * numRegions); return avg; } void getRowAverage(int sales[][NUM_QUARTERS], int numRegions, int numQuarters, float avg[]) { float sum = 0.0f; for (int row = 0; row < numRegions; row++) { for (int col = 0; col < numQuarters; col++) avg[row] += sales[row][col]; avg[row] /= numQuarters; } } void getColAverage(int sales[][NUM_QUARTERS], int numRegions, int numQuarters, float avg[]) { float sum = 0.0f; for (int col = 0; col < numQuarters; col++) { for (int row = 0; row < numRegions; row++) avg[col] += sales[row][col]; avg[col] /= numRegions; } } void printAverageStats(vector<string> regions, vector<int> quarters, int sales[][NUM_QUARTERS]) { float wholeCompAvg = getSingleAverage(sales, regions.size(), quarters.size()); cout << "Average sales across the whole company: $" << setprecision(2) << fixed << wholeCompAvg << endl; cout << endl; float quarterAvgs[4]; getColAverage(sales, regions.size(), quarters.size(), quarterAvgs); cout << "Average sales per quarter across all regions: " << endl; for (int i = 0; i < quarters.size(); i++) cout << quarters[i] << ": $" << setprecision(2) << fixed << quarterAvgs[i] << endl; cout << endl; float regionAvgs[3]; getRowAverage(sales, regions.size(), quarters.size(), regionAvgs); cout << "Average sales per region: " << endl; for (int i = 0; i < regions.size(); i++) cout << regions[i] << ": $" << setprecision(2) << fixed << regionAvgs[i] << endl; } int main() { vector<string> regions; cout << "Number of regions: "; int numRegions = readInt(); for (int i = 0; i < numRegions; i++) { cout << "Region " << (i + 1) << ": "; regions.push_back(readWord()); } cout << endl; vector<int> quarters; for (int i = 0; i < NUM_QUARTERS; i++) { cout << "Q" << (i + 1) << ": "; quarters.push_back(readInt()); } cout << endl; int QuarterlySales[numRegions][NUM_QUARTERS]; promptQuarterlySales(regions, quarters, QuarterlySales); cout << endl; printAverageStats(regions, quarters, QuarterlySales); cout << endl; cout << "Regions analyzed: " << endl; for (string region : regions) cout << " " << region << endl; cout << endl; cout << "Quarters analyzed: " << endl; for (int quarter : quarters) cout << " " << quarter << endl; return 0; }
23.674419
108
0.573183
[ "vector" ]
a6dee571de7a14866c91baabe9ad9c2ea0c51554
3,110
cpp
C++
libs/renderer/impl/src/renderer/impl/vf/dynamic/element_converter.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/impl/src/renderer/impl/vf/dynamic/element_converter.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/impl/src/renderer/impl/vf/dynamic/element_converter.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/image/algorithm/may_overlap.hpp> #include <sge/image/algorithm/uninitialized.hpp> #include <sge/image/color/format.hpp> #include <sge/image/color/format_stride.hpp> #include <sge/image2d/dim.hpp> #include <sge/image2d/pitch.hpp> #include <sge/image2d/algorithm/copy_and_convert.hpp> #include <sge/image2d/view/const_object.hpp> #include <sge/image2d/view/make.hpp> #include <sge/image2d/view/make_const.hpp> #include <sge/image2d/view/object.hpp> #include <sge/renderer/exception.hpp> #include <sge/renderer/raw_pointer.hpp> #include <sge/renderer/impl/vf/dynamic/element_converter.hpp> #include <sge/renderer/impl/vf/dynamic/lock_interval.hpp> #include <sge/renderer/impl/vf/dynamic/unlock.hpp> #include <sge/renderer/vertex/first.hpp> #include <sge/renderer/vf/dynamic/offset.hpp> #include <sge/renderer/vf/dynamic/stride.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/to_signed.hpp> sge::renderer::impl::vf::dynamic::element_converter::element_converter( original_format const _original_format, backend_format const _backend_format, sge::renderer::vf::dynamic::stride const _stride, sge::renderer::vf::dynamic::offset const _offset) : original_format_(_original_format), backend_format_(_backend_format), stride_(_stride), offset_(_offset) { if (sge::image::color::format_stride(original_format_.get()) != sge::image::color::format_stride(backend_format_.get())) { throw sge::renderer::exception{ FCPPT_TEXT("vf::dynamic::element_converter: Cannot handle different format strides!")}; } } void sge::renderer::impl::vf::dynamic::element_converter::convert( sge::renderer::impl::vf::dynamic::lock_interval const &_interval, sge::renderer::raw_pointer const _data, sge::renderer::vertex::first const _pos, sge::renderer::impl::vf::dynamic::unlock const _unlock) const { if (original_format_.get() == backend_format_.get()) { return; } // pos refers to the beginning of the lock if (_interval.lower() < _pos.get()) { throw sge::renderer::exception{ FCPPT_TEXT("vf::dynamic::element_converter: Lock out of range!")}; } sge::renderer::raw_pointer const begin( _data + (_interval.lower() - _pos.get()) * stride_.get() + offset_.get()); sge::image2d::dim const dim(1U, _interval.upper() - _interval.lower()); sge::image2d::pitch const pitch{fcppt::cast::to_signed( stride_.get() - sge::image::color::format_stride(original_format_.get()))}; sge::image2d::algorithm::copy_and_convert( sge::image2d::view::make_const( begin, dim, _unlock.get() ? original_format_.get() : backend_format_.get(), pitch), sge::image2d::view::make( begin, dim, _unlock.get() ? backend_format_.get() : original_format_.get(), pitch), sge::image::algorithm::may_overlap::yes, sge::image::algorithm::uninitialized::no); }
38.875
95
0.713505
[ "object" ]
a6f2daf3838040bf5c89539291106eb45c54d1ea
1,476
hpp
C++
glm/ext/vector_transform.hpp
gchunev/Dice4D
f96db406204fdca0155d26db856b66a2afd4e664
[ "MIT" ]
1
2019-05-22T08:53:46.000Z
2019-05-22T08:53:46.000Z
glm/ext/vector_transform.hpp
gchunev/Dice4D
f96db406204fdca0155d26db856b66a2afd4e664
[ "MIT" ]
null
null
null
glm/ext/vector_transform.hpp
gchunev/Dice4D
f96db406204fdca0155d26db856b66a2afd4e664
[ "MIT" ]
null
null
null
/// @ref ext_vector_transform /// @file glm/ext/vector_transform.hpp /// /// @defgroup ext_vector_transform GLM_EXT_vector_transform /// @ingroup ext /// /// Defines functions that generate common transformations using vectors. /// /// Include <glm/ext/vector_transform.hpp> to use the features of this extension. /// /// @see ext_matrix_projection /// @see ext_matrix_clip_space #pragma once // Dependencies #include "../gtc/constants.hpp" #include "../geometric.hpp" #include "../trigonometric.hpp" #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_EXT_vector_transform extension included") #endif namespace glm { /// @addtogroup ext_vector_transform /// @{ /// Performs a rotation in the plane spanned by the two given unit vectors. /// For positive angles, the rotation takes the first vector towards the second. /// The two vectors should be of unit length and not be collinear. /// /// @param t the first tangent vector to the rotation plane /// @param b the second tangent vector to the rotation plane /// @param angle Rotation angle expressed in radians. /// @param v the vector to be rotated. /// /// @tparam T A floating-point scalar type /// @tparam Q A value from qualifier enum /// template<length_t N, typename T, qualifier Q> GLM_FUNC_DECL vec<N, T, Q> rotate( vec<N, T, Q> const& t, vec<N, T, Q> const& b, T angle, vec<N, T, Q> const& v); /// @} }//namespace glm #include "vector_transform.inl"
29.52
81
0.714092
[ "vector" ]
a6f9521213577eb23ddc84d7682b355e256ccd09
4,576
inl
C++
Code/Framework/AzCore/AzCore/Math/Frustum.inl
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzCore/AzCore/Math/Frustum.inl
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/AzCore/Math/Frustum.inl
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * 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 namespace AZ { inline Frustum::PlaneId operator++(Frustum::PlaneId& planeId) { planeId = (Frustum::PlaneId)(planeId + 1); return planeId; } AZ_MATH_INLINE Frustum::Frustum() { #ifdef AZ_DEBUG_BUILD for (PlaneId i = PlaneId::Near; i < PlaneId::MAX; ++i) { m_planes[i] = Simd::Vec4::Splat(std::numeric_limits<float>::signaling_NaN()); } #endif } AZ_MATH_INLINE Plane Frustum::GetPlane(PlaneId planeId) const { return Plane(m_planes[planeId]); } AZ_MATH_INLINE void Frustum::SetPlane(PlaneId planeId, const Plane& plane) { using namespace Simd; m_serializedPlanes[planeId] = plane; //normalize the plane by dividing each element by the length of the normal const Vec4::FloatType lengthSquared = Vec4::FromVec1(Vec3::Dot(plane.GetNormal().GetSimdValue(), plane.GetNormal().GetSimdValue())); const Vec4::FloatType length = Vec4::Sqrt(lengthSquared); m_planes[planeId] = Vec4::Div(plane.GetSimdValue(), length); } AZ_MATH_INLINE IntersectResult Frustum::IntersectSphere(const Vector3& center, float radius) const { bool intersect = false; for (PlaneId i = PlaneId::Near; i < PlaneId::MAX; ++i) { const float distance = Simd::Vec1::SelectFirst(Simd::Vec4::PlaneDistance(m_planes[i], center.GetSimdValue())); if (distance < -radius) { return IntersectResult::Exterior; } intersect |= (fabsf(distance) < radius); } return intersect ? IntersectResult::Overlaps : IntersectResult::Interior; } AZ_MATH_INLINE IntersectResult Frustum::IntersectSphere(const Sphere& sphere) const { return IntersectSphere(sphere.GetCenter(), sphere.GetRadius()); } AZ_MATH_INLINE IntersectResult Frustum::IntersectAabb(const Vector3& minimum, const Vector3& maximum) const { return IntersectAabb(Aabb::CreateFromMinMax(minimum, maximum)); } AZ_MATH_INLINE IntersectResult Frustum::IntersectAabb(const Aabb& aabb) const { // Count the number of planes where the AABB is inside uint32_t numInterior = 0; for (PlaneId i = PlaneId::Near; i < PlaneId::MAX; ++i) { const Vector3 disjointSupport = aabb.GetSupport(-Vector3(Simd::Vec4::ToVec3(m_planes[i]))); const float disjointDistance = Simd::Vec1::SelectFirst(Simd::Vec4::PlaneDistance(m_planes[i], disjointSupport.GetSimdValue())); if (disjointDistance < 0.0f) { return IntersectResult::Exterior; } // We now know the interior point we just checked passes the plane check.. // Check an exterior support point to determine whether or not the whole AABB is contained or if this is an intersection const Vector3 intersectSupport = aabb.GetSupport(Vector3(Simd::Vec4::ToVec3(m_planes[i]))); const float intersectDistance = Simd::Vec1::SelectFirst(Simd::Vec4::PlaneDistance(m_planes[i], intersectSupport.GetSimdValue())); if (intersectDistance >= 0.0f) { // If the whole AABB passes the plane check, increment the number of planes the AABB is 'interior' to ++numInterior; } } // If the AABB is interior to all planes, we're contained, else we intersect return (numInterior < PlaneId::MAX) ? IntersectResult::Overlaps : IntersectResult::Interior; } AZ_MATH_INLINE bool Frustum::IsClose(const Frustum& rhs, float tolerance) const { return Vector4(m_planes[PlaneId::Near ]).IsClose(Vector4(rhs.m_planes[PlaneId::Near ]), tolerance) && Vector4(m_planes[PlaneId::Far ]).IsClose(Vector4(rhs.m_planes[PlaneId::Far ]), tolerance) && Vector4(m_planes[PlaneId::Left ]).IsClose(Vector4(rhs.m_planes[PlaneId::Left ]), tolerance) && Vector4(m_planes[PlaneId::Right ]).IsClose(Vector4(rhs.m_planes[PlaneId::Right ]), tolerance) && Vector4(m_planes[PlaneId::Top ]).IsClose(Vector4(rhs.m_planes[PlaneId::Top ]), tolerance) && Vector4(m_planes[PlaneId::Bottom]).IsClose(Vector4(rhs.m_planes[PlaneId::Bottom]), tolerance); } } // namespace AZ
37.508197
158
0.644886
[ "3d" ]