hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | 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 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32996bfaec9335f6b2f29e28da28ded7a2b9e1e7 | 324 | cpp | C++ | Sources/Graphics/Picture/qt4main/origin.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 27 | 2017-12-19T09:15:36.000Z | 2021-07-30T13:02:00.000Z | Sources/Graphics/Picture/qt4main/origin.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | null | null | null | Sources/Graphics/Picture/qt4main/origin.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 29 | 2018-04-10T13:25:54.000Z | 2021-12-24T01:51:03.000Z | #include <QApplication>
#include <QLabel>
#include <QPixmap>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLabel label;
//C++11
//string path = R"(test.jpg)";
//QPixmap pix(path.c_str());
QPixmap pix(argv[1]); //图片路径
label.setPixmap(pix);
label.show();
label.resize(640,480);
return a.exec();
} | 19.058824 | 32 | 0.657407 |
3299c337d5c45106d83004e7bb91ae6c4f89d1e3 | 32,774 | cc | C++ | farmhash_golden_test.cc | dietmarkuehl/hashing-demo | 006f61c4221c2119c893fcfda8c505c08ed5b006 | [
"Apache-2.0"
] | 35 | 2015-03-26T03:38:41.000Z | 2022-01-03T04:32:53.000Z | farmhash_golden_test.cc | dietmarkuehl/hashing-demo | 006f61c4221c2119c893fcfda8c505c08ed5b006 | [
"Apache-2.0"
] | null | null | null | farmhash_golden_test.cc | dietmarkuehl/hashing-demo | 006f61c4221c2119c893fcfda8c505c08ed5b006 | [
"Apache-2.0"
] | 16 | 2015-03-26T02:53:23.000Z | 2021-07-12T12:31:07.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.
// Golden tests of farmhash, based on tests in original FarmHash source.
#include <cassert>
#include <iostream>
#include "farmhash.h"
#include "std.h"
namespace farmhashna {
uint64_t HashLen16(uint64_t u, uint64_t v) {
static constexpr uint64_t kMul = 0x9ddfea08eb382d69ULL;
uint64_t a = (u ^ v) * kMul;
a ^= (a >> 47);
uint64_t b = (v ^ a) * kMul;
b ^= (b >> 47);
b *= kMul;
return b;
}
// Adapt our API to the one the test fixture expects
uint64_t Hash64(const char* str, size_t len) {
hashing::farmhash::state_type state;
return static_cast<size_t>(
hash_combine_range(hashing::farmhash(&state), str, str + len));
}
uint64_t Hash64WithSeeds(const char *s, size_t len,
uint64_t seed0, uint64_t seed1) {
return HashLen16(Hash64(s, len) - seed0, seed1);
}
uint64_t Hash64WithSeed(const char *s, size_t len,
uint64_t seed) {
static constexpr uint64_t k2 = 0x9ae16a3b2f90404fULL;
return Hash64WithSeeds(s, len, k2, seed);
}
} // namespace farmhashna
using std::cout;
using std::cerr;
using std::endl;
using std::hex;
constexpr int kDataSize = 1 << 20;
static const int kTestSize = 300;
char data[kDataSize];
int errors = 0;
template <typename T> constexpr bool IsNonZero(T x) {
return x != 0;
}
// Initialize data to pseudorandom values.
void Setup() {
static constexpr uint64_t k0 = 0xc3a5c85c97cb3127ULL;
uint64_t a = 9;
uint64_t b = 777;
for (int i = 0; i < kDataSize; i++) {
a += b;
b += a;
a = (a ^ (a >> 41)) * k0;
b = (b ^ (b >> 41)) * k0 + i;
uint8_t u = b >> 37;
memcpy(data + i, &u, 1); // uint8_t -> char
}
}
uint32_t CreateSeed(int offset, int salt) {
static constexpr uint32_t c1 = 0xcc9e2d51;
uint32_t h = static_cast<uint32_t>(salt & 0xffffffff);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h += static_cast<uint32_t>(offset & 0xffffffff);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
return h;
}
#undef SEED
#undef SEED1
#undef SEED0
#define SEED CreateSeed(offset, -1)
#define SEED0 CreateSeed(offset, 0)
#define SEED1 CreateSeed(offset, 1)
uint32_t expected[] = {
1140953930u, 861465670u,
3277735313u, 2681724312u,
2598464059u, 797982799u,
890626835u, 800175912u,
2603993599u, 921001710u,
1410420968u, 2134990486u,
3283896453u, 1867689945u,
2914424215u, 2244477846u,
255297188u, 2992121793u,
1110588164u, 4186314283u,
161451183u, 3943596029u,
4019337850u, 452431531u,
283198166u, 2741341286u,
3379021470u, 2557197665u,
299850021u, 2532580744u,
452473466u, 1706958772u,
1298374911u, 3099673830u,
2199864459u, 3696623795u,
236935126u, 2976578695u,
4055299123u, 3281581178u,
1053458494u, 1882212500u,
2305012065u, 2169731866u,
3456121707u, 275903667u,
458884671u, 3033004529u,
3058973506u, 2379411653u,
1898235244u, 1402319660u,
2700149065u, 2699376854u,
147814787u, 720739346u,
2433714046u, 4222949502u,
4220361840u, 1712034059u,
3425469811u, 3690733394u,
4148372108u, 1330324210u,
594028478u, 2921867846u,
1635026870u, 192883107u,
780716741u, 1728752234u,
3280331829u, 326029180u,
3969463346u, 1436364519u,
393215742u, 3349570000u,
3824583307u, 1612122221u,
2859809759u, 3808705738u,
1379537552u, 1646032583u,
2233466664u, 1432476832u,
4023053163u, 2650381482u,
2052294713u, 3552092450u,
1628777059u, 1499109081u,
3476440786u, 3829307897u,
2960536756u, 1554038301u,
1145519619u, 3190844552u,
2902102606u, 3600725550u,
237495366u, 540224401u,
65721842u, 489963606u,
1448662590u, 397635823u,
1596489240u, 1562872448u,
1790705123u, 2128624475u,
180854224u, 2604346966u,
1435705557u, 1262831810u,
155445229u, 1672724608u,
1669465176u, 1341975128u,
663607706u, 2077310004u,
3610042449u, 1911523866u,
1043692997u, 1454396064u,
2563776023u, 294527927u,
1099072299u, 1389770549u,
703505868u, 678706990u,
2952353448u, 2026137563u,
3603803785u, 629449419u,
1933894405u, 3043213226u,
226132789u, 2489287368u,
1552847036u, 645684964u,
3828089804u, 3632594520u,
187883449u, 230403464u,
3151491850u, 3272648435u,
3729087873u, 1303930448u,
2002861219u, 165370827u,
916494250u, 1230085527u,
3103338579u, 3064290191u,
3807265751u, 3628174014u,
231181488u, 851743255u,
2295806711u, 1781190011u,
2988893883u, 1554380634u,
1142264800u, 3667013118u,
1968445277u, 315203929u,
2638023604u, 2290487377u,
732137533u, 1909203251u,
440398219u, 1891630171u,
1380301172u, 1498556724u,
4072067757u, 4165088768u,
4204318635u, 441430649u,
3931792696u, 197618179u,
956300927u, 914413116u,
3010839769u, 2837339569u,
2148126371u, 1913303225u,
3074915312u, 3117299654u,
4139181436u, 2993479124u,
3178848746u, 1357272220u,
1438494951u, 507436733u,
667183474u, 2084369203u,
3854939912u, 1413396341u,
126024219u, 146044391u,
1016656857u, 3022024459u,
3254014218u, 429095991u,
165589978u, 1578546616u,
985653208u, 1718653828u,
623071693u, 366414107u,
249776086u, 1207522198u,
3047342438u, 2991127487u,
3120876698u, 1684583131u,
46987739u, 1157614300u,
863214540u, 1087193030u,
199124911u, 520792961u,
3614377032u, 586863115u,
3331828431u, 1013201099u,
1716848157u, 4033596884u,
1164298657u, 4140791139u,
1146169032u, 1434258493u,
3824360466u, 3242407770u,
3725511003u, 232064808u,
872586426u, 762243036u,
2736953692u, 816692935u,
512845449u, 3748861010u,
2266795890u, 3781899767u,
4290630595u, 517646945u,
22638523u, 648000590u,
959214578u, 558910384u,
1283799121u, 3047062993u,
1024246061u, 4027776454u,
3544509313u, 622325861u,
834785312u, 382936554u,
411505255u, 1973395102u,
1825135056u, 2725923798u,
580988377u, 2826990641u,
3474970689u, 1029055034u,
812546227u, 2506885666u,
2584372201u, 1758123094u,
589567754u, 325737734u,
345313518u, 2022370576u,
3886113119u, 3338548567u,
257578986u, 3698087965u,
1776047957u, 1771384107u,
3604937815u, 3198590202u,
2305332220u, 191910725u,
4232136669u, 427759438u,
4244322689u, 542201663u,
3315355162u, 2135941665u,
556609672u, 45845311u,
1175961330u, 3948351189u,
23075771u, 3252374102u,
1634635545u, 4151937410u,
713127376u, 1467786451u,
663013031u, 3444053918u,
2638154051u, 810082938u,
3077742128u, 1062268187u,
2115441882u, 4081398201u,
3735739145u, 2794294783u,
2335576331u, 2560479831u,
1379288194u, 4225182569u,
2442302747u, 3948961926u,
3958366652u, 3067277639u,
3667516477u, 1709989541u,
1516711748u, 2339636583u,
4188504038u, 59581167u,
2725013602u, 3639843023u,
2658147000u, 2643979752u,
3758739543u, 4189944477u,
2470483982u, 877580602u,
2995362413u, 118817200u,
3252925478u, 2062343506u,
3981838403u, 3762572073u,
1231633714u, 4168280671u,
2931588131u, 3284356565u,
1129162571u, 732225574u,
4173605289u, 1407328702u,
1677744031u, 3532596884u,
3232041815u, 1652884780u,
2256541290u, 3459463480u,
3740979556u, 259034107u,
2227121257u, 1426140634u,
3606709555u, 3424793077u,
315836068u, 3200749877u,
1386256573u, 24035717u,
2982018998u, 1811050648u,
234531934u, 1115203611u,
1598686658u, 3146815575u,
1603559457u, 323296368u,
2632963283u, 1778459926u,
739944537u, 579625482u,
3486330348u, 492621815u,
1231665285u, 2457048126u,
3903349120u, 389846205u,
3355404249u, 3275550588u,
1052645068u, 862072556u,
2834153464u, 1481069623u,
2657392572u, 4279236653u,
1688445808u, 701920051u,
3740748788u, 3388062747u,
1873358321u, 2152785640u,
883382081u, 1005815394u,
1020177209u, 734239551u,
2371453141u, 100326520u,
3488500412u, 1279682138u,
2610427744u, 49703572u,
3026361211u, 605900428u,
302392721u, 2509302188u,
1416453607u, 2815915291u,
1862819968u, 519710058u,
2450888314u, 4017598378u,
937074653u, 3035635454u,
1590230729u, 3268013438u,
2710029305u, 12886044u,
3711259084u, 2627383582u,
3895772404u, 648534979u,
260307902u, 855990313u,
3669691805u, 263366740u,
2938543471u, 414331688u,
3080542944u, 3405007814u,
3565059103u, 1190977418u,
390836981u, 1606450012u,
2649808239u, 2514169310u,
2747519432u, 4129538640u,
1721522849u, 492099164u,
792990594u, 3625507637u,
2271095827u, 2993032712u,
2302363854u, 4013112951u,
1111617969u, 2183845740u,
795918276u, 1116991810u,
3110898804u, 3963062126u,
2737064702u, 462795667u,
937372240u, 1343017609u,
1091041189u, 2790555455u,
277024217u, 25485284u,
1166522068u, 1623631848u,
241727183u, 2836158787u,
3112996740u, 573836428u,
2721658101u, 1937681565u,
4175169209u, 3190765433u,
1970000788u, 1668258120u,
114616703u, 954762543u,
199237753u, 4094644498u,
2522281978u, 732086117u,
1756889687u, 2936126607u,
2437031370u, 4103143808u,
3883389541u, 3171090854u,
2483004780u, 1927385370u,
2360538162u, 2740855009u,
4241185118u, 1492209542u,
1672737098u, 2148675559u,
1789864670u, 2434313103u,
2319172611u, 2760941207u,
2636210123u, 1338083267u,
1128080590u, 822806371u,
1199583556u, 314727461u,
1335160250u, 2084630531u,
1156261526u, 316766066u,
112090465u, 3129033323u,
2746885618u, 636616055u,
2582210744u, 1721064910u,
3468394263u, 470463518u,
2076016059u, 408721884u,
2121041886u, 378460278u,
1915948002u, 357324860u,
2301682622u, 2691859523u,
1869756364u, 2429314418u,
2193146527u, 1185564327u,
2614088922u, 1975527044u,
919067651u, 2855948894u,
3662539576u, 1943802836u,
3529473373u, 1490330107u,
366036094u, 3384241033u,
4276268604u, 448403661u,
4271796078u, 1910401882u,
3077107698u, 299427366u,
2035665349u, 3201262636u,
3738454258u, 2554452696u,
3588997135u, 3363895827u,
1267505995u, 1852004679u,
2237827073u, 2803250686u,
3468044908u, 2143572850u,
1728158656u, 1022551180u,
1996680960u, 839529273u,
2400647871u, 2201096054u,
3606433628u, 2597259793u,
3544595875u, 3909443124u,
819278607u, 3447346709u,
806136613u, 2711436388u,
3656063205u, 837475154u,
694525336u, 4070212073u,
4011303412u, 1068395209u,
438095290u, 484603494u,
2673730227u, 737767009u,
642310823u, 3914002299u,
308425103u, 268427550u,
1334387085u, 4069797497u,
4280783219u, 2914011058u,
4243643405u, 2849988118u,
2504230175u, 1817156623u,
2804200483u, 3406991497u,
2948254999u, 2102063419u,
1071272117u, 514889942u,
571972433u, 1246595599u,
1735616066u, 1539151988u,
1230831543u, 277987182u,
4269526481u, 991511607u,
95237878u, 2005032160u,
1291113144u, 626619670u,
3560835907u, 164940926u,
1433635018u, 116647396u,
3039097112u, 2868163232u,
1141645918u, 1764165478u,
881378302u, 2159170082u,
2953647681u, 1011320066u,
184856151u, 1723308975u,
336034862u, 2017579106u,
1476681709u, 147523618u,
3896252223u, 2264728166u,
944743644u, 1694443528u,
2690700128u, 1947321519u,
735478508u, 4058183171u,
260177668u, 505662155u,
2391691262u, 1920739747u,
3216960415u, 1898176786u,
3722741628u, 1511077569u,
449636564u, 983350414u,
2580237367u, 2055059789u,
1103819072u, 2089123665u,
3873755579u, 2718467458u,
3124338704u, 3204250304u,
2475035432u, 1120017626u,
3873758287u, 1982999824u,
2950794582u, 780634378u,
2842141483u, 4029205195u,
1656892865u, 3330993377u,
80890710u, 1953796601u,
3873078673u, 136118734u,
2317676604u, 4199091610u,
1864448181u, 3063437608u,
1699452298u, 1403506686u,
1513069466u, 2348491299u,
4273657745u, 4055855649u,
1805475756u, 2562064338u,
973124563u, 4197091358u,
172861513u, 2858726767u,
4271866024u, 3071338162u,
3590386266u, 2328277259u,
1096050703u, 1189614342u,
459509140u, 771592405u,
817999971u, 3740825152u,
520400189u, 1941874618u,
185232757u, 4032960199u,
3928245258u, 3527721294u,
1301118856u, 752188080u,
3512945009u, 308584855u,
2105373972u, 752872278u,
3823368815u, 3760952096u,
4250142168u, 2565680167u,
3646354146u, 1259957455u,
1085857127u, 3471066607u,
38924274u, 3770488806u,
1083869477u, 3312508103u,
71956383u, 3738784936u,
3099963860u, 1255084262u,
4286969992u, 3621849251u,
1190908967u, 1831557743u,
2363435042u, 54945052u,
4059585566u, 4023974274u,
1788578453u, 3442180039u,
2534883189u, 2432427547u,
3909757989u, 731996369u,
4168347425u, 1356028512u,
2741583197u, 1280920000u,
312887059u, 3259015297u,
3946278527u, 4135481831u,
1281043691u, 1121403845u,
3312292477u, 1819941269u,
1741932545u, 3293015483u,
2127558730u, 713121337u,
2635469238u, 486003418u,
4015067527u, 2976737859u,
2108187161u, 927011680u,
1970188338u, 4177613234u,
1799789551u, 2118505126u,
4134691985u, 1958963937u,
1929210029u, 2555835851u,
2768832862u, 910892050u,
2567532373u, 4075249328u,
86689814u, 3726640307u,
1392137718u, 1240000030u,
4104757832u, 3026358429u,
313797689u, 1435798509u,
3101500919u, 1241665335u,
3573008472u, 3615577014u,
3767659003u, 3134294021u,
4063565523u, 2296824134u,
1541946015u, 3087190425u,
2693152531u, 2199672572u,
2123763822u, 1034244398u,
857839960u, 2515339233u,
2228007483u, 1628096047u,
2116502287u, 2502657424u,
2809830736u, 460237542u,
450205998u, 3646921704u,
3818199357u, 1808504491u,
1950698961u, 2069753399u,
3657033172u, 3734547671u,
4067859590u, 3292597295u,
1106466069u, 356742959u,
2469567432u, 3495418823u,
183440071u, 3248055817u,
3662626864u, 1750561299u,
3926138664u, 4088592524u,
567122118u, 3810297651u,
992181339u, 3384018814u,
3272124369u, 3177596743u,
320086295u, 2316548367u,
100741310u, 451656820u,
4086604273u, 3759628395u,
2553391092u, 1745659881u,
3650357479u, 2390172694u,
330172533u, 767377322u,
526742034u, 4102497288u,
2088767754u, 164402616u,
2482632320u, 2352347393u,
1873658044u, 3861555476u,
2751052984u, 1767810825u,
20037241u, 545143220u,
2594532522u, 472304191u,
3441135892u, 3323383489u,
258785117u, 2977745165u,
2781737565u, 2963590112u,
2756998822u, 207428029u,
2581558559u, 3824717027u,
1258619503u, 3472047571u,
2648427775u, 2360400900u,
2393763818u, 2332399088u,
3932701729u, 884421165u,
1396468647u, 1377764574u,
4061795938u, 1559119087u,
3343596838u, 3604258095u,
1435134775u, 1099809675u,
908163739u, 1418405656u,
368446627u, 3741651161u,
3374512975u, 3542220540u,
3244772570u, 200009340u,
3198975081u, 2521038253u,
4081637863u, 337070226u,
3235259030u, 3897262827u,
736956644u, 641040550u,
644850146u, 1306761320u,
4219448634u, 193750500u,
3293278106u, 1383997679u,
1242645122u, 4109252858u,
450747727u, 3716617561u,
362725793u, 2252520167u,
3377483696u, 1788337208u,
8130777u, 3226734120u,
759239140u, 1012411364u,
1658628529u, 2911512007u,
1002580201u, 1681898320u,
3039016929u, 4294520281u,
367022558u, 3071359622u,
3205848570u, 152989999u,
3839042136u, 2357687350u,
4273132307u, 3898950547u,
1176841812u, 1314157485u,
75443951u, 1027027239u,
1858986613u, 2040551642u,
36574105u, 2603059541u,
3456147251u, 2137668425u,
4077477194u, 3565689036u,
491832241u, 363703593u,
2579177168u, 3589545214u,
265993036u, 1864569342u,
4149035573u, 3189253455u,
1072259310u, 3153745937u,
923017956u, 490608221u,
855846773u, 845706553u,
1018226240u, 1604548872u,
3833372385u, 3287246572u,
2757959551u, 2452872151u,
1553870564u, 1713154780u,
2649450292u, 500120236u,
84251717u, 661869670u,
1444911517u, 2489716881u,
2810524030u, 1561519055u,
3884088359u, 2509890699u,
4247155916u, 1005636939u,
3224066062u, 2774151984u,
2035978240u, 2514910366u,
1478837908u, 3144450144u,
2107011431u, 96459446u,
3587732908u, 2389230590u,
3287635953u, 250533792u,
1235983679u, 4237425634u,
3704645833u, 3882376657u,
2976369049u, 1187061987u,
276949224u, 4100839753u,
1698347543u, 1629662314u,
1556151829u, 3784939568u,
427484362u, 4246879223u,
3155311770u, 4285163791u,
1693376813u, 124492786u,
1858777639u, 3476334357u,
1941442701u, 1121980173u,
3485932087u, 820852908u,
358032121u, 2511026735u,
1873607283u, 2556067450u,
2248275536u, 1528632094u,
1535473864u, 556796152u,
1499201704u, 1472623890u,
1526518503u, 3692729434u,
1476438092u, 2913077464u,
335109599u, 2167614601u,
4121131078u, 3158127917u,
3051522276u, 4046477658u,
2857717851u, 1863977403u,
1341023343u, 692059110u,
1802040304u, 990407433u,
3285847572u, 319814144u,
561105582u, 1540183799u,
4052924496u, 2926590471u,
2244539806u, 439121871u,
3317903224u, 3178387550u,
4265214507u, 82077489u,
1978918971u, 4279668976u,
128732476u, 2853224222u,
464407878u, 4190838199u,
997819001u, 3250520802u,
2330081301u, 4095846095u,
733509243u, 1583801700u,
722314527u, 3552883023u,
1403784280u, 432327540u,
1877837196u, 3912423882u,
505219998u, 696031431u,
908238873u, 4189387259u,
8759461u, 2540185277u,
3385159748u, 381355877u,
2519951681u, 1679786240u,
2019419351u, 4051584612u,
1933923923u, 3768201861u,
1670133081u, 3454981037u,
700836153u, 1675560450u,
371560700u, 338262316u,
847351840u, 2222395828u,
3130433948u, 405251683u,
3037574880u, 184098830u,
453340528u, 1385561439u,
2224044848u, 4071581802u,
1431235296u, 5570097u,
570114376u, 2287305551u,
2272418128u, 803575837u,
3943113491u, 414959787u,
708083137u, 2452657767u,
4019147902u, 3841480082u,
3791794715u, 2965956183u,
2763690963u, 2350937598u,
3424361375u, 779434428u,
1274947212u, 686105485u,
3426668051u, 3692865672u,
3057021940u, 2285701422u,
349809124u, 1379278508u,
3623750518u, 215970497u,
1783152480u, 823305654u,
216118434u, 1787189830u,
3692048450u, 2272612521u,
3032187389u, 4159715581u,
1388133148u, 1611772864u,
2544383526u, 552925303u,
3420960112u, 3198900547u,
3503230228u, 2603352423u,
2318375898u, 4064071435u,
3006227299u, 4194096960u,
1283392422u, 1510460996u,
174272138u, 3671038966u,
1775955687u, 1719108984u,
1763892006u, 1385029063u,
4083790740u, 406757708u,
684087286u, 531310503u,
3329923157u, 3492083607u,
1059031410u, 3037314475u,
3105682208u, 3382290593u,
2292208503u, 426380557u,
97373678u, 3842309471u,
777173623u, 3241407531u,
303065016u, 1477104583u,
4234905200u, 2512514774u,
2649684057u, 1397502982u,
1802596032u, 3973022223u,
2543566442u, 3139578968u,
3193669211u, 811750340u,
4013496209u, 567361887u,
4169410406u, 3622282782u,
3403136990u, 2540585554u,
895210040u, 3862229802u,
1145435213u, 4146963980u,
784952939u, 943914610u,
573034522u, 464420660u,
2356867109u, 3054347639u,
3985088434u, 1911188923u,
583391304u, 176468511u,
2990150068u, 2338031599u,
519948041u, 3181425568u,
496106033u, 4110294665u,
2736756930u, 1196757691u,
1089679033u, 240953857u,
3399092928u, 4040779538u,
2843673626u, 240495962u,
3017658263u, 3828377737u,
4243717901u, 2448373688u,
2759616657u, 2246245780u,
308018483u, 4262383425u,
2731780771u, 328023017u,
2884443148u, 841480070u,
3188015819u, 4051263539u,
2298178908u, 2944209234u,
1372958390u, 4164532914u,
4074952232u, 1683612329u,
2155036654u, 1872815858u,
2041174279u, 2368092311u,
206775997u, 2283918569u,
645945606u, 115406202u,
4206471368u, 3923500892u,
2217060665u, 350160869u,
706531239u, 2824302286u,
509981657u, 1469342315u,
140980u, 1891558063u,
164887091u, 3094962711u,
3437115622u, 13327420u,
422986366u, 330624974u,
3630863408u, 2425505046u,
824008515u, 3543885677u,
918718096u, 376390582u,
3224043675u, 3724791476u,
1837192976u, 2968738516u,
3424344721u, 3187805406u,
1550978788u, 1743089918u,
4251270061u, 645016762u,
3855037968u, 1928519266u,
1373803416u, 2289007286u,
1889218686u, 1610271373u,
3059200728u, 2108753646u,
582042641u, 812347242u,
3188172418u, 191994904u,
1343511943u, 2247006571u,
463291708u, 2697254095u,
1534175504u, 1106275740u,
622521957u, 917121602u,
4095777215u, 3955972648u,
3852234638u, 2845309942u,
3299763344u, 2864033668u,
2554947496u, 799569078u,
2551629074u, 1102873346u,
2661022773u, 2006922227u,
2900438444u, 1448194126u,
1321567432u, 1983773590u,
1237256330u, 3449066284u,
1691553115u, 3274671549u,
4271625619u, 2741371614u,
3285899651u, 786322314u,
1586632825u, 564385522u,
2530557509u, 2974240289u,
1244759631u, 3263135197u,
3592389776u, 3570296884u,
2749873561u, 521432811u,
987586766u, 3206261120u,
1327840078u, 4078716491u,
1753812954u, 976892272u,
1827135136u, 1781944746u,
1328622957u, 1015377974u,
3439601008u, 2209584557u,
2482286699u, 1109175923u,
874877499u, 2036083451u,
483570344u, 1091877599u,
4190721328u, 1129462471u,
640035849u, 1867372700u,
920761165u, 3273688770u,
1623777358u, 3389003793u,
3241132743u, 2734783008u,
696674661u, 2502161880u,
1646071378u, 1164309901u,
350411888u, 1978005963u,
2253937037u, 7371540u,
989577914u, 3626554867u,
3214796883u, 531343826u,
398899695u, 1145247203u,
1516846461u, 3656006011u,
529303412u, 3318455811u,
3062828129u, 1696355359u,
3698796465u, 3155218919u,
1457595996u, 3191404246u,
1395609912u, 2917345728u,
1237411891u, 1854985978u,
1091884675u, 3504488111u,
3109924189u, 1628881950u,
3939149151u, 878608872u,
778235395u, 1052990614u,
903730231u, 2069566979u,
2437686324u, 3163786257u,
2257884264u, 2123173186u,
939764916u, 2933010098u,
1235300371u, 1256485167u,
1950274665u, 2180372319u,
2648400302u, 122035049u,
1883344352u, 2083771672u,
3712110541u, 321199441u,
1896357377u, 508560958u,
3066325351u, 2770847216u,
3177982504u, 296902736u,
1486926688u, 456842861u,
601221482u, 3992583643u,
2794121515u, 1533934172u,
1706465470u, 4281971893u,
2557027816u, 900741486u,
227175484u, 550595824u,
690918144u, 2825943628u,
90375300u, 300318232u,
1985329734u, 1440763373u,
3670603707u, 2533900859u,
3253901179u, 542270815u,
3677388841u, 307706478u,
2570910669u, 3320103693u,
1273768482u, 1216399252u,
1652924805u, 1043647584u,
1120323676u, 639941430u,
325675502u, 3652676161u,
4241680335u, 1545838362u,
1991398008u, 4100211814u,
1097584090u, 3262252593u,
2254324292u, 1765019121u,
4060211241u, 2315856188u,
3704419305u, 411263051u,
238929055u, 3540688404u,
3094544537u, 3250435765u,
3460621305u, 1967599860u,
2016157366u, 847389916u,
1659615591u, 4020453639u,
901109753u, 2682611693u,
1661364280u, 177155177u,
3210561911u, 3802058181u,
797089608u, 3286110054u,
2110358240u, 1353279028u,
2479975820u, 471725410u,
2219863904u, 3623364733u,
3167128228u, 1052188336u,
3656587111u, 721788662u,
3061255808u, 1615375832u,
924941453u, 2547780700u,
3328169224u, 1310964134u,
2701956286u, 4145497671u,
1421461094u, 1221397398u,
1589183618u, 1492533854u,
449740816u, 2686506989u,
3035198924u, 1682886232u,
2529760244u, 3342031659u,
1235084019u, 2151665147u,
2315686577u, 3282027660u,
1140138691u, 2754346599u,
2091754612u, 1178454681u,
4226896579u, 2942520471u,
2122168506u, 3751680858u,
3213794286u, 2601416506u,
4142747914u, 3951404257u,
4243249649u, 748595836u,
4004834921u, 238887261u,
1927321047u, 2217148444u,
205977665u, 1885975275u,
186020771u, 2367569534u,
2941662631u, 2608559272u,
3342096731u, 741809437u,
1962659444u, 3539886328u,
3036596491u, 2282550094u,
2366462727u, 2748286642u,
2144472852u, 1390394371u,
1257385924u, 2205425874u,
2119055686u, 46865323u,
3597555910u, 3188438773u,
2372320753u, 3641116924u,
3116286108u, 2680722658u,
3371014971u, 2058751609u,
2966943726u, 2345078707u,
2330535244u, 4013841927u,
1169588594u, 857915866u,
1875260989u, 3175831309u,
3193475664u, 1955181430u,
923161569u, 4068653043u,
776445899u, 954196929u,
61509556u, 4248237857u,
3808667664u, 581227317u,
2893240187u, 4159497403u,
4212264930u, 3973886195u,
2077539039u, 851579036u,
2957587591u, 772351886u,
1173659554u, 946748363u,
2794103714u, 2094375930u,
4234750213u, 3671645488u,
2614250782u, 2620465358u,
3122317317u, 2365436865u,
3393973390u, 523513960u,
3645735309u, 2766686992u,
2023960931u, 2312244996u,
1875932218u, 3253711056u,
3622416881u, 3274929205u,
612094988u, 1555465129u,
2114270406u, 3553762793u,
1832633644u, 1087551556u,
3306195841u, 1702313921u,
3675066046u, 1735998785u,
1690923980u, 1482649756u,
1171351291u, 2043136409u,
1962596992u, 461214626u,
3278253346u, 1392428048u,
3744621107u, 1028502697u,
3991171462u, 1014064003u,
3642345425u, 3186995039u,
6114625u, 3359104346u,
414856965u, 2814387514u,
3583605071u, 2497896367u,
1024572712u, 1927582962u,
2892797583u, 845302635u,
328548052u, 1523379748u,
3392622118u, 1347167673u,
1012316581u, 37767602u,
2647726017u, 1070326065u,
2075035198u, 4202817168u,
2502924707u, 2612406822u,
2187115553u, 1180137213u,
701024148u, 1481965992u,
3223787553u, 2083541843u,
203230202u, 3876887380u,
1334816273u, 2870251538u,
2186205850u, 3985213979u,
333533378u, 806507642u,
1010064531u, 713520765u,
3084131515u, 2637421459u,
1703168933u, 1517562266u,
4089081247u, 3231042924u,
3079916123u, 3154574447u,
2253948262u, 1725190035u,
2452539325u, 1343734533u,
213706059u, 2519409656u,
108055211u, 2916327746u,
587001593u, 1917607088u,
4202913084u, 926304016u,
469255411u, 4042080256u,
3498936874u, 246692543u,
495780578u, 438717281u,
2259272650u, 4011324645u,
2836854664u, 2317249321u,
946828752u, 1280403658u,
1905648354u, 2034241661u,
774652981u, 1285694082u,
2200307766u, 2158671727u,
1135162148u, 232040752u,
397012087u, 1717527689u,
1720414106u, 918797022u,
2580119304u, 3568069742u,
2904461070u, 3893453420u,
973817938u, 667499332u,
3785870412u, 2088861715u,
1565179401u, 600903026u,
591806775u, 3512242245u,
997964515u, 2339605347u,
1134342772u, 3234226304u,
4084179455u, 302315791u,
2445626811u, 2590372496u,
345572299u, 2274770442u,
3600587867u, 3706939009u,
1430507980u, 2656330434u,
1079209397u, 2122849632u,
1423705223u, 3826321888u,
3683385276u, 1057038163u,
1242840526u, 3987000643u,
2398253089u, 1538190921u,
1295898647u, 3570196893u,
3065138774u, 3111336863u,
2524949549u, 4203895425u,
3025864372u, 968800353u,
1023721001u, 3763083325u,
526350786u, 635552097u,
2308118370u, 2166472723u,
2196937373u, 2643841788u,
3040011470u, 4010301879u,
2782379560u, 3474682856u,
4201389782u, 4223278891u,
1457302296u, 2251842132u,
1090062008u, 3188219189u,
292733931u, 1424229089u,
1590782640u, 1365212370u,
3975957073u, 3982969588u,
2927147928u, 1048291071u,
2766680094u, 884908196u,
35237839u, 2221180633u,
2490333812u, 4098360768u,
4029081103u, 3490831871u,
2392516272u, 3455379186u,
3948800722u, 335456628u,
2105117968u, 4181629008u,
1044201772u, 3335754111u,
540133451u, 3313113759u,
3786107905u, 2627207327u,
3540337875u, 3473113388u,
3430536378u, 2514123129u,
2124531276u, 3872633376u,
3272957388u, 3501994650u,
2418881542u, 487365389u,
3877672368u, 1512866656u,
3486531087u, 2102955203u,
1136054817u, 3004241477u,
1549075351u, 1302002008u,
3936430045u, 2258587644u,
4109233936u, 3679809321u,
3467083076u, 2484463221u,
1594979755u, 529218470u,
3527024461u, 1147434678u,
106799023u, 1823161970u,
1704656738u, 1675883700u,
3308746763u, 1875093248u,
1352868568u, 1898561846u,
2508994984u, 3177750780u,
4217929592u, 400784472u,
80090315u, 3564414786u,
3841585648u, 3379293868u,
160353261u, 2413172925u,
2378499279u, 673436726u,
1505702418u, 1330977363u,
1853298225u, 3201741245u,
2135714208u, 4069554166u,
3715612384u, 3692488887u,
3680311316u, 4274382900u,
914186796u, 2264886523u,
3869634032u, 1254199592u,
1131020455u, 194781179u,
429923922u, 2763792336u,
2052895198u, 3997373194u,
3440090658u, 2165746386u,
1575500242u, 3463310191u,
2064974716u, 3779513671u,
3106421434u, 880320527u,
3281914119u, 286569042u,
3909096631u, 122359727u,
1429837716u, 252230074u,
4111461225u, 762273136u,
93658514u, 2766407143u,
3623657004u, 3869801679u,
3925695921u, 2390397316u,
2499025338u, 2741806539u,
2507199021u, 1659221866u,
361292116u, 4048761557u,
3797133396u, 1517903247u,
3121647246u, 3884308578u,
1697201500u, 1558800262u,
4150812360u, 3161302278u,
2610217849u, 641564641u,
183814518u, 2075245419u,
611996508u, 2223461433u,
329123979u, 121860586u,
860985829u, 1137889144u,
4018949439u, 2904348960u,
947795261u, 1992594155u,
4255427501u, 2281583851u,
2892637604u, 1478186924u,
3050771207u, 2767035539u,
373510582u, 1963520320u,
3763848370u, 3756817798u,
627269409u, 1806905031u,
1814444610u, 3646665053u,
1822693920u, 278515794u,
584050483u, 4142579188u,
2149745808u, 3193071606u,
1179706341u, 2693495182u,
3259749808u, 644172091u,
880509048u, 3340630542u,
3365160815u, 2384445068u,
3053081915u, 2840648309u,
1986990122u, 1084703471u,
2370410550u, 1627743573u,
2244943480u, 4057483496u,
2611595995u, 2470013639u,
4024732359u, 3987190386u,
873421687u, 2447660175u,
3226583022u, 767655877u,
2528024413u, 1962070688u,
1233635843u, 2163464207u,
659054446u, 854207134u,
258410943u, 4197831420u,
2515400215u, 3100476924u,
1961549594u, 2219491151u,
3997658851u, 163850514u,
470325051u, 2598261204u,
3052145580u, 59836528u,
1376188597u, 966733415u,
850667549u, 3622479237u,
1083731990u, 1525777459u,
4005126532u, 1428155540u,
2781907007u, 943739431u,
1493961005u, 2839096988u,
2000057832u, 1941829603u,
1901484772u, 939810041u,
3377407371u, 3090115837u,
3310840540u, 2068409688u,
3261383939u, 2212130277u,
2594774045u, 2912652418u,
4179816101u, 3534504531u,
3349254805u, 2796552902u,
1385421283u, 4259908631u,
3714780837u, 3070073945u,
3372846298u, 3835884044u,
3047965714u, 3009018735u,
744091167u, 1861124263u,
2764936304u, 1338171648u,
4222019554u, 1395200692u,
1371426007u, 3338031581u,
2525665319u, 4196233786u,
2332743921u, 1474702008u,
2274266301u, 4255175517u,
2290169528u, 1793910997u,
2188254024u, 354202001u,
3864458796u, 4280290498u,
1554419340u, 1733094688u,
2010552302u, 1561807039u,
664313606u, 2548990879u,
1084699349u, 3233936866u,
973895284u, 2386881969u,
1831995860u, 2961465052u,
1428704144u, 3269904970u,
231648253u, 2602483763u,
4125013173u, 3319187387u,
3347011944u, 1892898231u,
4019114049u, 868879116u,
4085937045u, 2378411019u,
1072588531u, 3547435717u,
2208070766u, 1069899078u,
3142980597u, 2337088907u,
1593338562u, 919414554u,
688077849u, 3625708135u,
1472447348u, 1947711896u,
3953006207u, 877438080u,
845995820u, 3150361443u,
3053496713u, 2484577841u,
224271045u, 2914958001u,
2682612949u, 806655563u,
2436224507u, 1907729235u,
2920583824u, 1251814062u,
2070814520u, 4034325578u,
497847539u, 2714317144u,
385182008u, 640855184u,
1327075087u, 1062468773u,
1757405994u, 1374270191u,
4263183176u, 3041193150u,
1037871524u, 3633173991u,
4231821821u, 2830131945u,
3505072908u, 2830570613u,
4195208715u, 575398021u,
3992840257u, 3691788221u,
1949847968u, 2999344380u,
3183782163u, 3723754342u,
759716128u, 3284107364u,
1714496583u, 15918244u,
820509475u, 2553936299u,
2201876606u, 4237151697u,
2605688266u, 3253705097u,
1008333207u, 712158730u,
1722280252u, 1933868287u,
4152736859u, 2097020806u,
584426382u, 2836501956u,
2522777566u, 1996172430u,
2122199776u, 1069285218u,
1474209360u, 690831894u,
107482532u, 3695525410u,
670591796u, 768977505u,
2412057331u, 3647886687u,
3110327607u, 1072658422u,
379861934u, 1557579480u,
4124127129u, 2271365865u,
3880613089u, 739218494u,
547346027u, 388559045u,
3147335977u, 176230425u,
3094853730u, 2554321205u,
1495176194u, 4093461535u,
3521297827u, 4108148413u,
1913727929u, 1177947623u,
1911655402u, 1053371241u,
3265708874u, 1266515850u,
1045540427u, 3194420196u,
3717104621u, 1144474110u,
1464392345u, 52070157u,
4144237690u, 3350490823u,
4166253320u, 2747410691u,
};
// Return false only if offset is -1 and a spot check of 3 hashes all yield 0.
bool Test(int offset, int len = 0) {
#undef Check
#undef IsAlive
#define Check(x) do { \
const uint32_t actual = (x), e = expected[index++]; \
bool ok = actual == e; \
if (!ok) { \
cerr << "expected " << hex << e << " but got " << actual << endl; \
++errors; \
} \
assert(ok); \
} while (0)
#define IsAlive(x) do { alive += IsNonZero(x); } while (0)
// After the following line is where the uses of "Check" and such will go.
static int index = 0;
if (offset == -1) { int alive = 0; { uint64_t h = farmhashna::Hash64WithSeeds(data, len++, SEED0, SEED1); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64WithSeed(data, len++, SEED); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64(data, len++); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } len -= 3; return alive > 0; }
{ uint64_t h = farmhashna::Hash64WithSeeds(data + offset, len, SEED0, SEED1); Check(h >> 32); Check((h << 32) >> 32); }
{ uint64_t h = farmhashna::Hash64WithSeed(data + offset, len, SEED); Check(h >> 32); Check((h << 32) >> 32); }
{ uint64_t h = farmhashna::Hash64(data + offset, len); Check(h >> 32); Check((h << 32) >> 32); }
return true;
#undef Check
#undef IsAlive
}
int RunTest() {
Setup();
int i = 0;
cout << "Running farmhashnaTest";
if (!Test(-1)) {
cout << "... Unavailable\n";
return errors;
}
// Good. The function is attempting to hash, so run the full test.
int errors_prior_to_test = errors;
for ( ; i < kTestSize - 1; i++) {
Test(i * i, i);
}
for ( ; i < kDataSize; i += i / 7) {
Test(0, i);
}
Test(0, kDataSize);
cout << (errors == errors_prior_to_test ? "... OK\n" : "... Failed\n");
return errors;
}
#undef SEED
#undef SEED1
#undef SEED0
int main(int argc, char* argv[]) {
return RunTest();
}
| 26.052464 | 383 | 0.801947 |
3299c5a5c960b8e0e3a203a2fd5acd556c37ff53 | 18,489 | cpp | C++ | src/configator.cpp | MickaelBlet/Configator | e5679106d9946885e88b18430562ea4a6b47dbd4 | [
"MIT"
] | null | null | null | src/configator.cpp | MickaelBlet/Configator | e5679106d9946885e88b18430562ea4a6b47dbd4 | [
"MIT"
] | null | null | null | src/configator.cpp | MickaelBlet/Configator | e5679106d9946885e88b18430562ea4a6b47dbd4 | [
"MIT"
] | 1 | 2020-07-14T02:26:16.000Z | 2020-07-14T02:26:16.000Z | /**
* configator.cpp
*
* Licensed under the MIT License <http://opensource.org/licenses/MIT>.
* Copyright (c) 2020 BLET Mickaël.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <list>
#include "configator.hpp"
namespace mblet {
Configator::Configator():
_mapConfig(Configator::Map()),
_filename(std::string()),
_isRead(false) {
return ;
}
Configator::Configator(const char* filename):
_mapConfig(Configator::Map()),
_filename(std::string()),
_isRead(false) {
readFile(filename);
return ;
}
Configator::Configator(const Configator& src):
_mapConfig(src._mapConfig),
_filename(src._filename),
_isRead(src._isRead) {
return ;
}
Configator::~Configator() {
return ;
}
Configator& Configator::operator=(const Configator& rhs) {
_mapConfig = rhs._mapConfig;
_filename = rhs._filename;
_isRead = rhs._isRead;
return *this;
}
const Configator::Map& Configator::operator[](std::size_t index) const {
return _mapConfig[index];
}
const Configator::Map& Configator::operator[](const std::string& str) const {
return _mapConfig[str];
}
bool Configator::readFile(const char* filename) {
_mapConfig.clear();
_filename = "";
_isRead = false;
std::ifstream fileStream(filename); // open file
if (fileStream.is_open()) {
_filename = filename;
_isRead = true;
readStream(fileStream); // parse file
fileStream.close();
}
return _isRead;
}
void Configator::setConfig(const Configator::Map& mapConfig) {
_mapConfig.clear();
_mapConfig = mapConfig;
}
const Configator::Map& Configator::getConfig() const {
return _mapConfig;
}
const std::string& Configator::getFilename() const {
return _filename;
}
bool Configator::isRead() const {
return _isRead;
}
// =============================================================================
// dump
static void s_printCommentDump(std::ostream& oss, const std::string& str) {
if (!str.empty()) {
oss << " ; " << str;
}
}
static void s_printDump(std::ostream& oss, const std::string& str) {
unsigned int i;
for (i = 0; i < str.size(); ++i) {
if (str[i] == ' ' || str[i] == '"' || str[i] == '#' || str[i] == ';' || str[i] == '\\' || str[i] == '['
|| str[i] == ']') {
break;
}
}
if (i < str.size()) {
oss << '"';
for (i = 0; i < str.size(); ++i) {
if (str[i] == '"' || str[i] == '\\') {
oss << '\\' << str[i];
}
else {
oss << str[i];
}
}
oss << '"';
}
else {
oss << str;
}
}
static void s_sectionCommentDump(std::ostream& oss, const std::string& str) {
if (!str.empty()) {
oss << "; ";
unsigned int i;
for (i = 0; i < str.size(); ++i) {
oss << str[i];
if (str[i] == '\n') {
oss << "; ";
}
}
oss << '\n';
}
}
static void s_sectionDump(std::ostream& oss, const std::string& str, std::size_t sectionIndex) {
oss << std::string(sectionIndex + 1, '[');
s_printDump(oss, str);
oss << std::string(sectionIndex + 1, ']');
}
static void s_recurseDump(std::ostream& oss, const Configator::Map& map, std::size_t sectionIndex = 0) {
Configator::Map::const_iterator itSection;
for (itSection = map.begin(); itSection != map.end(); ++itSection) {
if (itSection->second.size() > 0) {
if (!itSection->second.value.empty()) {
s_printDump(oss, itSection->first);
oss << " = ";
s_printDump(oss, itSection->second.value);
oss << '\n';
}
s_sectionDump(oss, itSection->first, sectionIndex);
oss << '\n';
s_sectionCommentDump(oss, itSection->second.comment);
s_recurseDump(oss, itSection->second, sectionIndex + 1);
}
else {
s_printDump(oss, itSection->first);
oss << " = ";
s_printDump(oss, itSection->second.value);
s_printCommentDump(oss, itSection->second.comment);
oss << '\n';
}
}
}
std::ostream& Configator::dump(std::ostream& oss) const {
s_recurseDump(oss, _mapConfig);
return oss;
}
// =============================================================================
// parse
/**
* @brief check if character is comment
*
* @param c
* @return true : c is comment character
* @return false : c is not comment character
*/
static bool s_isComment(const char& c) {
if (c == ';' || c == '#') {
return true;
}
else {
return false;
}
}
/**
* @brief move index to character after spaces
*
* @param str
* @param index
*/
static void s_stringJumpSpace(const std::string& str, std::size_t& index) {
while (::isspace(str[index])) {
++index;
}
}
/**
* @brief detect if line is empty or comment
*
* @param line
* @return true : line is empty or comment
* @return false : line is not empty or comment
*/
static bool s_emptyOrComment(const std::string& line, std::string* retComment) {
std::size_t start;
std::size_t end;
std::size_t i = 0;
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false;
}
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
return true;
}
/**
* @brief parse section name
*
* @param line
* @param retSection
* @param retComment
* @return true
* @return false
*/
static bool s_parseSections(std::string line, std::list<std::string>* retSection, std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t level = 0;
std::size_t i = 0;
s_stringJumpSpace(line, i);
// if not begin section
if (line[i] != '[') {
return false;
}
while (line[i] == '[') {
++i; // jump character '['
++level;
s_stringJumpSpace(line, i);
if (line[i] == '[') {
return false;
}
// start section name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump ']'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
if (line[i] != ']') {
return false;
}
++i; // jump ]
if (level == 1) {
retSection->clear();
}
retSection->push_back(line.substr(start, end - start));
s_stringJumpSpace(line, i);
}
if (line[i] != '\0' && !s_isComment(line[i])) {
retSection->pop_back();
return false;
}
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief parse section name
*
* @param line
* @param retSection
* @param retComment
* @return true
* @return false
*/
static bool s_parseSectionLevel(std::string line, std::list<std::string>* retSection, std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t level = 0;
std::size_t saveLevel = 0;
std::size_t i = 0;
s_stringJumpSpace(line, i);
// if not begin section
if (line[i] != '[') {
return false;
}
while (line[i] == '[') {
++i; // jump character '['
++level;
s_stringJumpSpace(line, i);
}
// start section name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump ']'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
saveLevel = level;
while (line[i] == ']') {
++i; // jump character ']'
--level;
s_stringJumpSpace(line, i);
}
if (level != 0) {
return false;
}
--saveLevel;
while (retSection->size() > saveLevel) {
retSection->pop_back();
}
if (saveLevel == retSection->size()) {
retSection->push_back(line.substr(start, end - start));
}
else {
return false;
}
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false;
}
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief parse key
*
* @param line
* @param retKey
* @param retValue
* @param retComment
* @return true
* @return false
*/
static bool s_parseKey(std::string line, std::list<std::string>* retKey, std::string* retValue,
std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t i = 0;
s_stringJumpSpace(line, i);
if (line[i] == '=') {
return false; // not key element
}
// start key name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != '=' && line[i] != '[') {
return false; // not valid key
}
}
else {
start = i;
while (line[i] != '=' && line[i] != '[') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump '=' or '['
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
retKey->push_back(line.substr(start, end - start));
// check table key
while (line[i] == '[') {
++i; // jump '['
s_stringJumpSpace(line, i);
// start key name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != ']') {
return false; // not valid key
}
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump '=' or '['
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
++i; // jump ']'
s_stringJumpSpace(line, i);
retKey->push_back(line.substr(start, end - start));
}
s_stringJumpSpace(line, i);
if (line[i] != '=') {
return false;
}
++i; // jump '='
s_stringJumpSpace(line, i);
// start value
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false; // not valid value
}
}
else {
start = i;
while (line[i] != '\0' && !s_isComment(line[i])) {
++i;
}
last = i;
--i; // revert jump '\0' or ';' or '#'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
*retValue = line.substr(start, end - start);
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief get map of section
*
* @param map
* @param sections
* @return Configator::Map&
*/
static Configator::Map& s_section(Configator::Map& map, const std::list<std::string>& sections) {
std::list<std::string>::const_iterator itSection;
Configator::Map* pMap = ↦
for (itSection = sections.begin(); itSection != sections.end(); ++itSection) {
pMap = &((*pMap)[*itSection]);
}
return *pMap;
}
void Configator::readStream(std::istream& stream) {
std::string line("");
std::list<std::string> sections;
sections.push_back("");
while (std::getline(stream, line)) {
std::list<std::string> keys;
std::string comment = "";
std::string value = "";
if (s_emptyOrComment(line, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
if (!map.comment.empty()) {
map.comment.append("\n");
}
map.comment.append(comment);
}
else if (s_parseSections(line, §ions, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
map.comment = comment;
}
else if (s_parseSectionLevel(line, §ions, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
map.comment = comment;
}
else if (s_parseKey(line, &keys, &value, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
Configator::Map* tmpMap = &(map);
std::list<std::string>::iterator it;
for (it = keys.begin(); it != keys.end() ; ++it) {
if (it->empty()) {
std::ostringstream oss("");
oss << tmpMap->size();
tmpMap = &((*tmpMap)[oss.str()]);
}
else {
tmpMap = &((*tmpMap)[*it]);
}
}
*tmpMap = value;
tmpMap->comment = comment;
}
}
}
}
| 26.679654 | 112 | 0.467683 |
329fe9fec81dd232d8f5d189629999932344b660 | 12,190 | cpp | C++ | src/select/tcpsocket_impl.cpp | tempbottle/zsummerX | b5a6b306329d6877cb53c1f30b586a2363c7682a | [
"MIT"
] | 1 | 2021-07-14T01:42:21.000Z | 2021-07-14T01:42:21.000Z | src/select/tcpsocket_impl.cpp | tempbottle/zsummerX | b5a6b306329d6877cb53c1f30b586a2363c7682a | [
"MIT"
] | null | null | null | src/select/tcpsocket_impl.cpp | tempbottle/zsummerX | b5a6b306329d6877cb53c1f30b586a2363c7682a | [
"MIT"
] | 1 | 2021-07-14T01:42:25.000Z | 2021-07-14T01:42:25.000Z | /*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include <zsummerX/select/tcpsocket_impl.h>
using namespace zsummer::network;
TcpSocket::TcpSocket()
{
g_appEnvironment.addCreatedSocketCount();
_register._type = tagRegister::REG_TCP_SOCKET;
}
TcpSocket::~TcpSocket()
{
g_appEnvironment.addClosedSocketCount();
if (_onRecvHandler || _onSendHandler || _onConnectHandler)
{
LCT("TcpSocket::~TcpSocket[this0x" << this << "] Handler status error. " << logSection());
}
if (_register._fd != InvalideFD)
{
closesocket(_register._fd);
_register._fd = InvalideFD;
}
}
std::string TcpSocket::logSection()
{
std::stringstream os;
os << ";; Status: summer.user_count()=" << _summer.use_count() << ", remoteIP=" << _remoteIP << ", remotePort=" << _remotePort
<< ", _onConnectHandler = " << (bool)_onConnectHandler
<< ", _onRecvHandler = " << (bool)_onRecvHandler << ", _pRecvBuf=" << (void*)_pRecvBuf << ", _iRecvLen=" << _iRecvLen
<< ", _onSendHandler = " << (bool)_onSendHandler << ", _pSendBuf=" << (void*)_pSendBuf << ", _iSendLen=" << _iSendLen
<< "; _register=" << _register;
return os.str();
}
bool TcpSocket::initialize(const EventLoopPtr & summer)
{
_summer = summer;
if (_register._linkstat != LS_UNINITIALIZE)
{
if (!_summer->registerEvent(0, _register))
{
LCE("TcpSocket::initialize[this0x" << this << "] socket already used or not initilize." << logSection());
return false;
}
_register._linkstat = LS_ESTABLISHED;
}
else
{
if (_register._fd != -1)
{
LCE("TcpSocket::doConnect[this0x" << this << "] fd aready used!" << logSection());
return false;
}
_register._fd = socket(AF_INET, SOCK_STREAM, 0);
if (_register._fd == -1)
{
LCE("TcpSocket::doConnect[this0x" << this << "] fd create failed!" << logSection());
return false;
}
setNonBlock(_register._fd);
setNoDelay(_register._fd);
_register._linkstat = LS_WAITLINK;
}
return true;
}
bool TcpSocket::attachSocket(SOCKET s, const std::string& remoteIP, unsigned short remotePort)
{
_register._fd = s;
_remoteIP = remoteIP;
_remotePort = remotePort;
_register._linkstat = LS_WAITLINK;
return true;
}
bool TcpSocket::doConnect(const std::string & remoteIP, unsigned short remotePort, _OnConnectHandler && handler)
{
if (!_summer)
{
LCE("TcpSocket::doConnect[this0x" << this << "] summer not bind!" << logSection());
return false;
}
if (_register._linkstat != LS_WAITLINK)
{
LCE("TcpSocket::doConnect[this0x" << this << "] _linkstat not LS_WAITLINK!" << logSection());
return false;
}
_register._wt = true;
_remoteIP = remoteIP;
_remotePort = remotePort;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(_remoteIP.c_str());
addr.sin_port = htons(_remotePort);
int ret = connect(_register._fd, (sockaddr *) &addr, sizeof(addr));
#ifndef WIN32
if (ret != 0 && errno != EINPROGRESS)
#else
if (ret != 0 && WSAGetLastError() != WSAEWOULDBLOCK)
#endif
{
LCT("TcpSocket::doConnect[this0x" << this << "] ::connect error. " << OSTREAM_GET_LASTERROR << logSection());
closesocket(_register._fd);
_register._fd = InvalideFD;
return false;
}
_register._tcpSocketConnectPtr = shared_from_this();
if (!_summer->registerEvent(0, _register))
{
LCE("TcpSocket::doConnect[this0x" << this << "] registerEvent Error" << logSection());
closesocket(_register._fd);
_register._fd = InvalideFD;
_register._tcpSocketConnectPtr.reset();
return false;
}
_onConnectHandler = std::move(handler);
return true;
}
bool TcpSocket::doSend(char * buf, unsigned int len, _OnSendHandler && handler)
{
if (_register._linkstat != LS_ESTABLISHED)
{
LCT("TcpSocket::doSend[this0x" << this << "] _linkstat not REG_ESTABLISHED_TCP!" << logSection());
return false;
}
if (!_summer)
{
LCE("TcpSocket::doSend[this0x" << this << "] _summer not bind!" << logSection());
return false;
}
if (len == 0)
{
LCE("TcpSocket::doSend[this0x" << this << "] argument err! len ==0" << logSection());
return false;
}
if (_pSendBuf != NULL || _iSendLen != 0)
{
LCE("TcpSocket::doSend[this0x" << this << "] _pSendBuf =" << (void *) _pSendBuf << " _iSendLen =" << _iSendLen<< logSection());
return false;
}
if (_onSendHandler)
{
LCE("TcpSocket::doSend[this0x" << this << "] _onSendHandler == TRUE" << logSection());
return false;
}
_pSendBuf = buf;
_iSendLen = len;
_register._wt = true;
_register._tcpSocketSendPtr = shared_from_this();
if (!_summer->registerEvent(1, _register))
{
LCT("TcpSocket::doSend[this0x" << this << "] registerEvent Error" << logSection());
_pSendBuf = nullptr;
_iSendLen = 0;
_register._tcpSocketSendPtr.reset();
doClose();
return false;
}
_onSendHandler = std::move(handler);
return true;
}
bool TcpSocket::doRecv(char * buf, unsigned int len, _OnRecvHandler && handler)
{
if (_register._linkstat != LS_ESTABLISHED)
{
LCT("TcpSocket::doRecv[this0x" << this << "] type not REG_ESTABLISHED_TCP!" << logSection());
return false;
}
if (!_summer)
{
LCE("TcpSocket::doRecv[this0x" << this << "] _summer not bind!" << logSection());
return false;
}
if (len == 0 )
{
LCE("TcpSocket::doRecv[this0x" << this << "] argument err !!! len==0" << logSection());
return false;
}
if (_pRecvBuf != NULL || _iRecvLen != 0)
{
LCE("TcpSocket::doRecv[this0x" << this << "] (_pRecvBuf != NULL || _iRecvLen != 0) == TRUE" << logSection());
return false;
}
if (_onRecvHandler)
{
LCE("TcpSocket::doRecv[this0x" << this << "] (_onRecvHandler) == TRUE" << logSection());
return false;
}
_pRecvBuf = buf;
_iRecvLen = len;
_register._rd = true;
_register._tcpSocketRecvPtr = shared_from_this();
if (!_summer->registerEvent(1, _register))
{
LCT("TcpSocket::doRecv[this0x" << this << "] registerEvent Error" << logSection());
_pRecvBuf = nullptr;
_iRecvLen = 0;
_register._tcpSocketRecvPtr.reset();
return false;
}
_onRecvHandler = std::move(handler);
return true;
}
void TcpSocket::onSelectMessage(bool rd, bool wt, bool err)
{
unsigned char linkstat = _register._linkstat;
NetErrorCode ec = NEC_ERROR;
if (!_onRecvHandler && !_onSendHandler && !_onConnectHandler)
{
LCE("TcpSocket::onSelectMessage[this0x" << this << "] unknown error. " << OSTREAM_GET_LASTERROR << logSection());
return ;
}
if (linkstat == LS_WAITLINK)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketConnectPtr));
_OnConnectHandler onConnect(std::move(_onConnectHandler));
int errCode = 0;
socklen_t len = sizeof(int);
if (err || getsockopt(_register._fd, SOL_SOCKET, SO_ERROR, (char*)&errCode, &len) != 0 || errCode != 0)
{
LOGT("onConnect False. " << OSTREAM_GET_LASTERROR);
_register._linkstat = LS_WAITLINK;
_summer->registerEvent(2, _register);
onConnect(NEC_ERROR);
return;
}
else
{
_register._wt = 0;
_summer->registerEvent(1, _register);
_register._linkstat = LS_ESTABLISHED;
onConnect(NEC_SUCCESS);
return;
}
return ;
}
if (rd && _onRecvHandler)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketRecvPtr));
int ret = recv(_register._fd, _pRecvBuf, _iRecvLen, 0);
_register._rd = false;
if (!_summer->registerEvent(1, _register))
{
LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection());
}
if (ret == 0 || (ret == -1 && !IS_WOULDBLOCK))
{
ec = NEC_ERROR;
_register._linkstat = LS_CLOSED;
if (rd && _onRecvHandler)
{
_OnRecvHandler onRecv(std::move(_onRecvHandler));
onRecv(ec, 0);
}
if (!_onSendHandler && !_onRecvHandler)
{
if (!_summer->registerEvent(2, _register))
{
LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection());
}
}
return ;
}
else if (ret != -1)
{
_OnRecvHandler onRecv(std::move(_onRecvHandler));
_pRecvBuf = NULL;
_iRecvLen = 0;
onRecv(NEC_SUCCESS,ret);
}
return;
}
else if (wt && _onSendHandler)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketSendPtr));
int ret = send(_register._fd, _pSendBuf, _iSendLen, 0);
_register._wt = false;
if (!_summer->registerEvent(1, _register))
{
LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection());
}
if ((ret == -1 && !IS_WOULDBLOCK) || _register._linkstat == LS_CLOSED)
{
ec = NEC_ERROR;
_register._linkstat = LS_CLOSED;
_onSendHandler = nullptr;
if (!_onSendHandler && !_onRecvHandler)
{
if (!_summer->registerEvent(2, _register))
{
LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection());
}
}
return ;
}
else if (ret != -1)
{
_OnSendHandler onSend(std::move(_onSendHandler));
_pSendBuf = NULL;
_iSendLen = 0;
onSend(NEC_SUCCESS, ret);
}
}
return ;
}
bool TcpSocket::doClose()
{
if (_register._fd != InvalideFD)
{
shutdown(_register._fd, SHUT_RDWR);
}
return true;
}
| 30.860759 | 151 | 0.579655 |
32a0a7fba84f4162d3de29e78fc6b8c5121fc1a1 | 5,967 | cpp | C++ | src/isodata/isodata.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | src/isodata/isodata.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | src/isodata/isodata.cpp | wmotte/toolkid | 2a8f82e1492c9efccde9a4935ce3019df1c68cde | [
"MIT"
] | null | null | null | #include "tkdCmdParser.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkTimeProbe.h"
#include "IsoDataImage.cpp"
/**
* ISODATA.
*/
class IsoData {
protected:
// Split function; return true if we should split...
bool split( IsoDataImage& img, double STDV, unsigned int minPointsPerCluster ) {
bool split = false;
//STEP 7:
img.calculateSTDVector();
//STEP 8:
img.calculateVmax();
// STEP 9:
// the vector to_split will contain integers that
// represent the cluster numbers that need to be split.
std::vector< unsigned int > to_split = img.shouldSplit( STDV, minPointsPerCluster );
if ( to_split.size() != 0 ) {
img.split( to_split );
split = true;
}
return split;
}
// Merge...
void merge( IsoDataImage& img, double LUMP, int MAXPAIR ) {
// STEP 11:
std::vector< IsoDataImage::PairDistanceNode > centerDistances = img.computeCenterDistances();
// STEP 12:
std::vector< IsoDataImage::PairDistanceNode > to_lump = img.findLumpCandidates( centerDistances, LUMP, MAXPAIR );
// STEP 13:
if ( to_lump.size() != 0 ) {
img.lump( to_lump );
}
}
// ************************************************************************************************
public:
/**
* Run.
*/
void run( const std::vector< std::string >& inputs, const std::string& output,
const std::string& mask, unsigned int NUMCLUS, unsigned int SAMPRM,
unsigned int MAXITER, double STDV, double LUMP, int MAXPAIR, bool normalize ) {
itk::TimeProbe probe;
probe.Start();
// initialize raw data...
IsoDataImage img = IsoDataImage( inputs, output, mask, normalize );
// STEP 1: arbitrarily choose k and init clusters...
img.initClusters( NUMCLUS );
for ( unsigned int i = 0; i < MAXITER; i++ ) {
std::cout << "Iter: " << i << std::endl;
// STEP 2: assign each point to the clostest cluster center...
img.assignPointsToClosestClusterCenter();
// STEP 3: discard clusters with less than min. samples per cluster...
// If any clusters were deleted, then go back to STEP 2...
if ( img.discardSmallClusters( SAMPRM ) ) {
continue;
}
// STEP 4: update each remaining cluster center...
img.updateClusters();
// STEP 5: compute the average distance of points in clusters from
// their corresponding cluster center...
// also compute overall average distance...
img.computeAverageDistance();
img.computeOverallAverageDistance();
// STEP 6:
if ( i == MAXITER ) {
LUMP = 0.0;
// goto STEP 9:
merge( img, LUMP, MAXPAIR );
} else if ( ( i % 2 == 0 ) || ( img.getNumCenters() >= 2 * NUMCLUS ) ) {
// goto STEP 9:
merge( img, LUMP, MAXPAIR );
} else if ( img.getNumCenters() <= ( NUMCLUS / 2 ) ) {
// goto STEP 7:
// if we are in last iteration and split is performed, we need to rerun from STEP 2 again
// as cluster centers need to be updated before final run...
if ( ( split( img, STDV, SAMPRM ) ) && ( i == MAXITER ) ) {
i--;
}
}
}
img.writeOutput( output );
probe.Stop();
std::cout << "Total runtime: " << probe.GetMeanTime() << " s." << std::endl;
}
};
/**
* Main.
*/
int main( int argc, char * argv[] ) {
// arguments...
std::vector< std::string > inputs;
std::string output;
std::string mask;
int numberOfClusters = 10; // kinit
int minNumberOfClusterPoints = 30; // nmin 1/5 average kluster size -> nmin = n/5 kinit.
int maxNumberOfIter = 20; // Imax default 20
double maxStdev = 0.1; // STDV default 2 * sigma
double minRequiredDistance = 0.001; // Lmin default 0.001
int maxPair = 4; // MAXPAIR
bool normalize = false; // normalize input images...
tkd::CmdParser parser( argv[0], "Isodata" );
parser.AddArgument( inputs, "inputs" ) -> AddAlias( "i" ) -> SetInput( "<strings>" ) -> SetDescription( "Input images" ) -> SetRequired(
true ) -> SetMinMax( 1, 10000 );
parser.AddArgument( output, "output" ) -> AddAlias( "o" ) -> SetInput( "<string>" ) -> SetDescription( "Output cluster image file" ) -> SetRequired(
true ) -> SetMinMax( 1, 1 );
parser.AddArgument( mask, "mask" ) -> AddAlias( "m" ) -> SetInput( "<string>" ) -> SetDescription( "Mask image" ) -> SetRequired(
false ) -> SetMinMax( 0, 1 );
parser.AddArgument( numberOfClusters, "clusters" ) -> AddAlias( "c" ) -> SetInput( "<int>" ) -> SetDescription(
"Initial number of clusters (NUMCLUS)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( minNumberOfClusterPoints, "min-clusters" ) -> AddAlias( "m" ) -> SetInput( "<int>" ) -> SetDescription(
"Minimum number of points that can form a cluster (SAMPRM)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxNumberOfIter, "max-itererations" ) -> AddAlias( "it" ) -> SetInput( "<int>" ) -> SetDescription(
"Maximum number of iterations (MAXITER)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxStdev, "standard-deviation" ) -> AddAlias( "s" ) -> SetInput( "<double>" ) -> SetDescription(
"Maximum standard deviation of points from their cluster center along each axis (STDV)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( minRequiredDistance, "min-distance" ) -> AddAlias( "d" ) -> SetInput( "<double>" ) -> SetDescription(
" Minimum required distance between two cluster centers (LUMP)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxPair, "max-pairs" ) -> AddAlias( "p" ) -> SetInput( "<int>" ) -> SetDescription(
"Maximum number of cluster pairs that can be merged per iteration (MAXPAIR)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( normalize, "normalize" ) -> AddAlias( "n" ) -> SetInput( "<bool>" ) -> SetDescription(
"Normalize input images before clustering (default: false)" );
if ( !parser.Parse( argc, argv ) ) {
parser.PrintUsage( std::cout );
return EXIT_FAILURE;
}
IsoData isoData = IsoData();
isoData.run( inputs, output, mask, numberOfClusters, minNumberOfClusterPoints, maxNumberOfIter, maxStdev, minRequiredDistance, maxPair, normalize );
}
| 33.335196 | 149 | 0.64002 |
32a2a7171e1f335a70241b41cb2874d2ec40de69 | 457 | hpp | C++ | v3/include/AsyncWatchResponse.hpp | chijinxina/etcd-cpp-api | 70946a5d4eff340a821096d247031d083fd0148e | [
"BSD-3-Clause"
] | null | null | null | v3/include/AsyncWatchResponse.hpp | chijinxina/etcd-cpp-api | 70946a5d4eff340a821096d247031d083fd0148e | [
"BSD-3-Clause"
] | null | null | null | v3/include/AsyncWatchResponse.hpp | chijinxina/etcd-cpp-api | 70946a5d4eff340a821096d247031d083fd0148e | [
"BSD-3-Clause"
] | 1 | 2021-07-13T07:19:37.000Z | 2021-07-13T07:19:37.000Z | #ifndef __ASYNC_WATCH_HPP__
#define __ASYNC_WATCH_HPP__
#include <grpc++/grpc++.h>
#include "proto/rpc.grpc.pb.h"
#include "proto/rpc.pb.h"
#include "v3/include/V3Response.hpp"
using etcdserverpb::WatchRequest;
using etcdserverpb::WatchResponse;
using etcdserverpb::KV;
namespace etcdv3
{
class AsyncWatchResponse : public etcdv3::V3Response
{
public:
AsyncWatchResponse(){};
void ParseResponse(WatchResponse& resp);
};
}
#endif
| 17.576923 | 54 | 0.73523 |
32a41e70dacf34144ee21b788e81882f3e67b773 | 224 | cpp | C++ | Aaaah/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | Aaaah/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | Aaaah/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
string pat, doc;
cin>> pat >> doc;
if(pat.size() >= doc.size() ){
cout << "go\n";}
else{
cout << "no\n";}
return 0;} | 20.363636 | 34 | 0.508929 |
32a734a47f29b1a3bd0f4f996292d833c6b809f3 | 636 | hpp | C++ | LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | #include <algorithm>
#include <string>
class Solution
{
public:
bool checkString(std::string &s);
};
/*
? Solution 1: Accepted
? 8ms(23.53% faster)
*/
// bool Solution::checkString(std::string s)
// {
// std::string sSorted = s;
// std::sort(sSorted.begin(), sSorted.end());
// return s == sSorted;
// }
/*
? Solution 1: Accepted
? 5ms(70% faster)
*/
bool Solution::checkString(std::string &s)
{
bool bSeen = false;
for (const auto &ch : s)
{
if (!bSeen && ch == 'b')
bSeen = true;
if (bSeen && ch == 'a')
return false;
}
return true;
} | 16.307692 | 49 | 0.528302 |
32ab54505766855b05cb8df09bf8afb467aafed8 | 3,726 | cpp | C++ | ert/ertlibc/syscall.cpp | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | null | null | null | ert/ertlibc/syscall.cpp | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | null | null | null | ert/ertlibc/syscall.cpp | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | null | null | null | // Copyright (c) Edgeless Systems GmbH.
// Licensed under the MIT License.
#include "syscall.h"
#include <openenclave/internal/malloc.h>
#include <openenclave/internal/trace.h>
#include <sys/syscall.h>
#include <cerrno>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <stdexcept>
#include <system_error>
#include "ertthread.h"
#include "locale.h"
#include "syscalls.h"
using namespace std;
using namespace ert;
long ert_syscall(long n, long x1, long x2, long x3, long, long, long)
{
try
{
switch (n)
{
case SYS_sched_yield:
__builtin_ia32_pause();
return 0;
case SYS_clock_gettime:
return sc::clock_gettime(
static_cast<int>(x1), reinterpret_cast<timespec*>(x2));
case SYS_gettid:
return ert_thread_self()->tid;
case SYS_exit_group:
sc::exit_group(static_cast<int>(x1));
return 0;
case SYS_getrandom:
return sc::getrandom(
reinterpret_cast<void*>(x1), // buf
static_cast<size_t>(x2), // buflen
static_cast<unsigned int>(x3) // flags
);
case SYS_sched_getaffinity:
return sc::sched_getaffinity(
static_cast<pid_t>(x1),
static_cast<size_t>(x2),
reinterpret_cast<cpu_set_t*>(x3));
case SYS_mprotect:
case SYS_madvise:
case SYS_mlock:
case SYS_munlock:
case SYS_mlockall:
case SYS_munlockall:
case SYS_mlock2:
// These can all be noops.
return 0;
case SYS_rt_sigaction:
sc::rt_sigaction(
static_cast<int>(x1), // signum
reinterpret_cast<k_sigaction*>(x2), // act
reinterpret_cast<k_sigaction*>(x3)); // oldact
return 0;
case SYS_rt_sigprocmask:
return 0; // Not supported. Silently ignore and return success.
case SYS_sigaltstack:
sc::sigaltstack(
reinterpret_cast<stack_t*>(x1),
reinterpret_cast<stack_t*>(x2));
return 0;
}
}
catch (const system_error& e)
{
OE_TRACE_ERROR("%s", e.what());
return -e.code().value();
}
catch (const runtime_error& e)
{
OE_TRACE_ERROR("%s", e.what());
}
catch (const exception& e)
{
OE_TRACE_FATAL("%s", e.what());
abort();
}
return -ENOSYS;
}
// This function is defined in this source file to guarantee that it overrides
// the weak symbol in ert/libc/locale.c.
extern "C" locale_t __newlocale(int mask, const char* locale, locale_t loc)
{
if (!(mask > 0 && !loc && locale && strcmp(locale, "C") == 0))
return newlocale(mask, locale, loc);
// Caller may be stdc++. We must return a struct that satisfies glibc
// internals (see glibc/locale/global-locale.c). The following struct is
// also compatible with musl.
static const __locale_struct c_locale{
{}, reinterpret_cast<const unsigned short*>(nl_C_LC_CTYPE_class + 128)};
return const_cast<locale_t>(&c_locale);
}
// The debug malloc check runs on enclave termination and prints errors for heap
// memory that has not been freed. As some global objects in (std)c++ use heap
// memory and don't free it by design, we cannot use this feature.
static int _init = [] {
oe_disable_debug_malloc_check = true;
return 0;
}();
| 31.310924 | 80 | 0.567901 |
32abb8fe555c12e7c93a94570e29a92f8d04d5ac | 30,229 | hh | C++ | sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | /*
libSDL2pp - C++11 bindings/wrapper for SDL2
Copyright (C) 2014-2015 Dmitry Marakasov <amdmi3@amdmi3.ru>
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.
*/
#ifndef SDL2PP_FONT_HH
#define SDL2PP_FONT_HH
#include <string>
#include <SDL2/SDL_ttf.h>
#include <SDL2pp/Optional.hh>
#include <SDL2pp/Point.hh>
#include <SDL2pp/Surface.hh>
#include <SDL2pp/Export.hh>
namespace SDL2pp {
class RWops;
////////////////////////////////////////////////////////////
/// \brief Holder of a loaded font
///
/// \ingroup ttf
///
/// \headerfile SDL2pp/Font.hh
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC56
///
////////////////////////////////////////////////////////////
class SDL2PP_EXPORT Font {
private:
TTF_Font* font_; ///< Managed TTF_Font object
public:
///@{
/// \name Construction and destruction
////////////////////////////////////////////////////////////
/// \brief Construct from existing TTF_Font structure
///
/// \param[in] font Existing TTF_Font to manage
///
////////////////////////////////////////////////////////////
Font(TTF_Font* font);
////////////////////////////////////////////////////////////
/// \brief Loads font from .ttf or .fon file
///
/// \param[in] file Pointer File name to load font from
/// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height
/// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC14
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC16
///
////////////////////////////////////////////////////////////
Font(const std::string& file, int ptsize, long index = 0);
////////////////////////////////////////////////////////////
/// \brief Loads font with RWops
///
/// \param[in] rwops RWops to load font from
/// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height
/// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC15
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC17
///
////////////////////////////////////////////////////////////
Font(RWops& rwops, int ptsize, long index = 0);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC18
///
////////////////////////////////////////////////////////////
virtual ~Font();
///@}
///@{
/// \name Copy and move
////////////////////////////////////////////////////////////
/// \brief Move constructor
///
/// \param[in] other SDL2pp::Font object to move data from
///
////////////////////////////////////////////////////////////
Font(Font&& other) noexcept;
////////////////////////////////////////////////////////////
/// \brief Move assignment
///
/// \param[in] other SDL2pp::Font object to move data from
///
/// \returns Reference to self
///
////////////////////////////////////////////////////////////
Font& operator=(Font&& other) noexcept;
////////////////////////////////////////////////////////////
/// \brief Deleted copy constructor
///
/// This class is not copyable
///
////////////////////////////////////////////////////////////
Font(const Font&) = delete;
////////////////////////////////////////////////////////////
/// \brief Deleted assignment operator
///
/// This class is not copyable
///
////////////////////////////////////////////////////////////
Font& operator=(const Font&) = delete;
///@}
///@{
/// \name Compatibility with legacy SDL code
////////////////////////////////////////////////////////////
/// \brief Get pointer to managed TTF_Font structure
///
/// \returns Pointer to managed TTF_Font structure
///
////////////////////////////////////////////////////////////
TTF_Font* Get() const;
///@{
/// \name Attributes: font style
////////////////////////////////////////////////////////////
/// \brief Get the rendering style of the loaded font
///
/// \returns The style as a bitmask composed of the following masks:
/// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE,
/// TTF_STYLE_STRIKETHROUGH. If no style is set then
/// TTF_STYLE_NORMAL is returned
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC21
///
////////////////////////////////////////////////////////////
int GetStyle() const;
////////////////////////////////////////////////////////////
/// \brief Set the rendering style of the loaded font
///
/// \param[in] style The style as a bitmask composed of the following masks:
/// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE,
/// TTF_STYLE_STRIKETHROUGH. If no style is desired then use
/// TTF_STYLE_NORMAL, which is the default.
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in style, so it may be best
/// to check the current style by using GetStyle() first
///
/// \note TTF_STYLE_UNDERLINE may cause surfaces created by TTF_RenderGlyph_*
/// functions to be extended vertically, downward only, to encompass the
/// underline if the original glyph metrics didn't allow for the underline
/// to be drawn below. This does not change the math used to place a glyph
/// using glyph metrics.
/// On the other hand TTF_STYLE_STRIKETHROUGH doesn't extend the glyph,
/// since this would invalidate the metrics used to position the glyph
/// when blitting, because they would likely be extended vertically upward.
/// There is perhaps a workaround, but it would require programs to be
/// smarter about glyph blitting math than they are currently designed for.
/// Still, sometimes the underline or strikethrough may be outside of the
/// generated surface, and thus not visible when blitted to the screen.
/// In this case, you should probably turn off these styles and draw your
/// own strikethroughs and underlines.
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC22
///
////////////////////////////////////////////////////////////
Font& SetStyle(int style = TTF_STYLE_NORMAL);
////////////////////////////////////////////////////////////
/// \brief Get the current outline size of the loaded font
///
/// \returns The size of the outline currently set on the font, in pixels
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC23
///
////////////////////////////////////////////////////////////
int GetOutline() const;
////////////////////////////////////////////////////////////
/// \brief Set the outline pixel width of the loaded font
///
/// \param[in] outline The size of outline desired, in pixels.
/// Use 0 (zero) to turn off outlining.
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in outline size, so it may be best
/// to check the current outline size by using GetOutline() first
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC24
///
////////////////////////////////////////////////////////////
Font& SetOutline(int outline = 0);
///@}
///@{
/// \name Attributes: font settings
////////////////////////////////////////////////////////////
/// \brief Get the current hinting setting of the loaded font
///
/// \returns The hinting type matching one of the following defined values:
/// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO,
/// TTF_HINTING_NONE. If no hinting is set then TTF_HINTING_NORMAL is returned
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC25
///
////////////////////////////////////////////////////////////
int GetHinting() const;
////////////////////////////////////////////////////////////
/// \brief Set the hinting of the loaded font
///
/// \param[in] hinting The hinting setting desired, which is one of:
/// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO,
/// TTF_HINTING_NONE. The default is TTF_HINTING_NORMAL
///
/// You should experiment with this setting if you know which font
/// you are using beforehand, especially when using smaller sized
/// fonts. If the user is selecting a font, you may wish to let them
/// select the hinting mode for that font as well
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in hinting, so it may be best
/// to check the current hinting by using GetHinting() first
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC26
///
////////////////////////////////////////////////////////////
Font& SetHinting(int hinting = TTF_HINTING_NORMAL);
////////////////////////////////////////////////////////////
/// \brief Get the current kerning setting of the loaded font
///
/// \returns False if kerning is disabled. True when enabled.
/// The default for a newly loaded font is true, enabled
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC27
///
////////////////////////////////////////////////////////////
bool GetKerning() const;
////////////////////////////////////////////////////////////
/// \brief Set whether to use kerning when rendering the loaded font
///
/// \param[in] allowed False to disable kerning, true to enable kerning.
/// The default is true, enabled
///
/// Set whether to use kerning when rendering the loaded font.
/// This has no effect on individual glyphs, but rather when
/// rendering whole strings of characters, at least a word at
/// a time. Perhaps the only time to disable this is when kerning
/// is not working for a specific font, resulting in overlapping
/// glyphs or abnormal spacing within words.
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC28
///
////////////////////////////////////////////////////////////
Font& SetKerning(bool allowed = true);
///@}
///@{
/// \name Attributes: font metrics
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel height of all glyphs of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// You may use this height for rendering text as close together
/// vertically as possible, though adding at least one pixel height
/// to it will space it so they can't touch. Remember that SDL_ttf
/// doesn't handle multiline printing, so you are responsible for
/// line spacing, see the GetLineSkip() as well.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC29
///
////////////////////////////////////////////////////////////
int GetHeight() const;
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel ascent of all glyphs of the loaded font
///
/// \returns The maximum pixel ascent of all glyphs in the font
///
/// This can also be interpreted as the distance from the top of
/// the font to the baseline. It could be used when drawing an
/// individual glyph relative to a top point, by combining it
/// with the glyph's maxy metric to resolve the top of the
/// rectangle used when blitting the glyph on the screen.
///
/// \code{.cpp}
/// rect.y = top + Font.GetAscent() - glyph_metric.maxy;
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC30
///
////////////////////////////////////////////////////////////
int GetAscent() const;
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel descent of all glyphs of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// This can also be interpreted as the distance from the
/// baseline to the bottom of the font.
/// It could be used when drawing an individual glyph relative
/// to a bottom point, by combining it with the glyph's maxy
/// metric to resolve the top of the rectangle used when blitting
/// the glyph on the screen.
///
/// \code{.cpp}
/// rect.y = bottom - TTF_FontDescent(font) - glyph_metric.maxy;
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC31
///
////////////////////////////////////////////////////////////
int GetDescent() const;
////////////////////////////////////////////////////////////
/// \brief Get the recommended pixel height of a rendered line of text of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// This is usually larger than the GetHeight() of the font
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC32
///
////////////////////////////////////////////////////////////
int GetLineSkip() const;
///@}
///@{
/// \name Attributes: face attributes
////////////////////////////////////////////////////////////
/// \brief Get the number of faces ("sub-fonts") available in the loaded font
///
/// \returns The number of faces in the font
///
/// This is a count of the number of specific fonts (based on size
/// and style and other typographical features perhaps) contained
/// in the font itself. It seems to be a useless fact to know,
/// since it can't be applied in any other SDL_ttf functions.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC33
///
////////////////////////////////////////////////////////////
long GetNumFaces() const;
////////////////////////////////////////////////////////////
/// \brief Test if the current font face of the loaded font is a fixed width font
///
/// \returns True if font is a fixed width font. False if not a fixed width font
///
/// Fixed width fonts are monospace, meaning every character
/// that exists in the font is the same width, thus you can
/// assume that a rendered string's width is going to be the
/// result of a simple calculation:
///
/// \code{.cpp}
/// glyph_width * string_length
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC34
///
////////////////////////////////////////////////////////////
bool IsFixedWidth() const;
////////////////////////////////////////////////////////////
/// \brief Get the current font face family name from the loaded font
///
/// \returns The current family name of of the face of the font, or NullOpt perhaps
///
/// This function may return NullOpt, in which case the information is not available.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC35
///
////////////////////////////////////////////////////////////
Optional<std::string> GetFamilyName() const;
////////////////////////////////////////////////////////////
/// \brief Get the current font face style name from the loaded font
///
/// \returns The current style name of of the face of the font, or NullOpt perhaps
///
/// This function may return NullOpt, in which case the information is not available
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC36
///
////////////////////////////////////////////////////////////
Optional<std::string> GetStyleName() const;
///@}
///@{
/// \name Attributes: glyphs
////////////////////////////////////////////////////////////
/// \brief Get the status of the availability of the glyph from the loaded font
///
/// \param[in] ch Unicode character to test glyph availability of
///
/// \returns The index of the glyph for ch in font, or 0 for an undefined character code
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC37
///
////////////////////////////////////////////////////////////
int IsGlyphProvided(Uint16 ch) const;
////////////////////////////////////////////////////////////
/// \brief Get glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
/// \param[out] minx Variable to store the returned minimum X offset into
/// \param[out] maxx Variable to store the returned maximum X offset into
/// \param[out] miny Variable to store the returned minimum Y offset into
/// \param[out] maxy Variable to store the returned maximum Y offset into
/// \param[out] advance Variable to store the returned advance offset into
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
void GetGlyphMetrics(Uint16 ch, int& minx, int& maxx, int& miny, int& maxy, int& advance) const;
////////////////////////////////////////////////////////////
/// \brief Get rect part of glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
///
/// \returns Rect representing glyph offset info
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
Rect GetGlyphRect(Uint16 ch) const;
////////////////////////////////////////////////////////////
/// \brief Get advance part of glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
///
/// \returns Advance offset into
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
int GetGlyphAdvance(Uint16 ch) const;
///@}
///@{
/// \name Attributes: text metrics
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the LATIN1 encoded text rendered using font
///
/// \param[in] text String to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC39
///
////////////////////////////////////////////////////////////
Point GetSizeText(const std::string& text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UTF8 encoded text rendered using font
///
/// \param[in] text UTF8 encoded string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC40
///
////////////////////////////////////////////////////////////
Point GetSizeUTF8(const std::string& text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font
///
/// \param[in] text UNICODE null terminated string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41
///
////////////////////////////////////////////////////////////
Point GetSizeUNICODE(const Uint16* text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font
///
/// \param[in] text UNICODE null terminated string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41
///
////////////////////////////////////////////////////////////
Point GetSizeUNICODE(const std::u16string& text) const;
///@}
///@{
/// \name Rendering: solid
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using solid mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC43
///
////////////////////////////////////////////////////////////
Surface RenderText_Solid(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using solid mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC44
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Solid(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using solid mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Solid(const Uint16* text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using solid mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Solid(const std::u16string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using solid mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC46
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Solid(Uint16 ch, SDL_Color fg);
///@}
///@{
/// \name Rendering: shaded
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using shaded mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC47
///
////////////////////////////////////////////////////////////
Surface RenderText_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using shaded mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC48
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using shaded mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Shaded(const Uint16* text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using shaded mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Shaded(const std::u16string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using shaded mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC50
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Shaded(Uint16 ch, SDL_Color fg, SDL_Color bg);
///@}
///@{
/// \name Rendering: blended
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using blended mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC51
///
////////////////////////////////////////////////////////////
Surface RenderText_Blended(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using blended mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC52
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Blended(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using blended mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Blended(const Uint16* text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using blended mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Blended(const std::u16string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using blended mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC54
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Blended(Uint16 ch, SDL_Color fg);
///@}
};
}
#endif
| 36.289316 | 117 | 0.553012 |
32ad881ee3d62285faa1035437facfee4bb8c9c5 | 4,859 | cpp | C++ | vislib/src/sys/Event.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 49 | 2017-08-23T13:24:24.000Z | 2022-03-16T09:10:58.000Z | vislib/src/sys/Event.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 200 | 2018-07-20T15:18:26.000Z | 2022-03-31T11:01:44.000Z | vislib/src/sys/Event.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 31 | 2017-07-31T16:19:29.000Z | 2022-02-14T23:41:03.000Z | /*
* Event.cpp
*
* Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "vislib/sys/Event.h"
#ifndef _WIN32
#include <climits>
#endif /* !_WIN32 */
#include "vislib/IllegalParamException.h"
#include "vislib/Trace.h"
#include "vislib/UnsupportedOperationException.h"
#include "vislib/assert.h"
#include "vislib/sys/SystemException.h"
#include "vislib/sys/error.h"
/*
* vislib::sys::Event::TIMEOUT_INFINITE
*/
#ifdef _WIN32
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = INFINITE;
#else /* _WIN32 */
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = UINT_MAX;
#endif /* _WIN32 */
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const bool isManualReset, const bool isInitiallySignaled)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(isInitiallySignaled ? 1 : 0, 1)
#endif /* _WIN32 */
{
#ifdef _WIN32
this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, NULL);
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const char* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
if (outIsNew != NULL) {
*outIsNew = false;
}
/* Try to open existing event first. */
if ((this->handle = ::OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) {
this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name);
if (outIsNew != NULL) {
*outIsNew = true;
}
}
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const wchar_t* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
if (outIsNew != NULL) {
*outIsNew = false;
}
/* Try to open existing event first. */
if ((this->handle = ::OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) {
this->handle = ::CreateEventW(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name);
if (outIsNew != NULL) {
*outIsNew = true;
}
}
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::~Event
*/
vislib::sys::Event::~Event(void) {
#ifdef _WIN32
::CloseHandle(this->handle);
#else /* _WIN32 */
/* Nothing to do. */
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Reset
*/
void vislib::sys::Event::Reset(void) {
#ifdef _WIN32
if (!::ResetEvent(this->handle)) {
throw SystemException(__FILE__, __LINE__);
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Reset\n");
this->semaphore.TryLock();
ASSERT(!this->semaphore.TryLock());
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Set
*/
void vislib::sys::Event::Set(void) {
#ifdef _WIN32
if (!::SetEvent(this->handle)) {
throw SystemException(__FILE__, __LINE__);
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Set\n");
this->semaphore.TryLock();
this->semaphore.Unlock();
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Wait
*/
bool vislib::sys::Event::Wait(const DWORD timeout) {
#ifdef _WIN32
switch (::WaitForSingleObject(this->handle, timeout)) {
case WAIT_OBJECT_0:
/* falls through. */
case WAIT_ABANDONED:
return true;
/* Unreachable. */
case WAIT_TIMEOUT:
return false;
/* Unreachable. */
default:
throw SystemException(__FILE__, __LINE__);
/* Unreachable. */
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait\n");
bool retval = false;
if (timeout == TIMEOUT_INFINITE) {
this->semaphore.Lock();
retval = true;
} else {
retval = this->semaphore.TryLock(timeout);
}
if (retval && this->isManualReset) {
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait signal again\n");
this->semaphore.Unlock();
}
return retval;
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const Event& rhs) {
throw UnsupportedOperationException("vislib::sys::Event::Event", __FILE__, __LINE__);
}
/*
* vislib::sys::Event::operator =
*/
vislib::sys::Event& vislib::sys::Event::operator=(const Event& rhs) {
if (this != &rhs) {
throw IllegalParamException("rhs", __FILE__, __LINE__);
}
return *this;
}
| 22.705607 | 120 | 0.626878 |
32ae75958086bad97657ea28f12aebb3dd3173f2 | 94 | cpp | C++ | uppdev/Centrum/Centrum.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/Centrum/Centrum.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/Centrum/Centrum.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include <Core/Core.h>
VectorMap<int32, Vector<int> > map;
CONSOLE_APP_MAIN
{
}
| 9.4 | 37 | 0.617021 |
32af2514e1ead7564365cb478f275cf7c2ea948a | 2,664 | hpp | C++ | src/FclEx.DataStructuresCpp/Iterator.hpp | huoshan12345/FxUtility.DataStructures | cdad625154407c381ec0b5d1003cc7eabc37e829 | [
"MIT"
] | 1 | 2017-04-30T21:12:55.000Z | 2017-04-30T21:12:55.000Z | src/FclEx.DataStructuresCpp/Iterator.hpp | huoshan12345/FxUtility.DataStructures | cdad625154407c381ec0b5d1003cc7eabc37e829 | [
"MIT"
] | null | null | null | src/FclEx.DataStructuresCpp/Iterator.hpp | huoshan12345/FxUtility.DataStructures | cdad625154407c381ec0b5d1003cc7eabc37e829 | [
"MIT"
] | 1 | 2018-10-04T23:54:26.000Z | 2018-10-04T23:54:26.000Z | #pragma once
#include <iterator>
namespace FclEx
{
namespace Node
{
using namespace std;
template <class Node, class IteratorType>
class Iterator : public iterator<forward_iterator_tag,
typename Node::value_type,
typename Node::difference_type,
typename Node::pointer,
typename Node::reference>
{
public:
typedef Node node_type;
typedef typename node_type::BaseNode BaseNode;
typedef typename BaseNode::allocator_type allocator_type;
typedef typename BaseNode::difference_type difference_type;
typedef typename BaseNode::reference reference;
typedef typename BaseNode::const_reference const_reference;
typedef typename BaseNode::pointer pointer;
typedef typename BaseNode::const_pointer const_pointer;
typedef IteratorType self_type;
explicit Iterator(node_type *node) :_pNode(node) { }
virtual ~Iterator() { }
virtual self_type &operator++() = 0;
virtual self_type operator++(int) = 0;
reference operator*()
{
return _pNode->Item;
}
pointer operator->()
{
return &_pNode->Item;
}
bool operator==(const self_type &other) const
{
return _pNode == other._pNode;
}
bool operator!=(const self_type &other) const
{
return !operator==(other);
}
protected:
node_type *_pNode;
};
template <class Node, class IteratorType>
class ConstIterator : public iterator<forward_iterator_tag,
typename Node::value_type,
typename Node::difference_type,
typename Node::const_pointer,
typename Node::const_reference>
{
public:
typedef Node node_type;
typedef typename node_type::BaseNode BaseNode;
typedef typename BaseNode::allocator_type allocator_type;
typedef typename BaseNode::difference_type difference_type;
typedef typename BaseNode::reference reference;
typedef typename BaseNode::const_reference const_reference;
typedef typename BaseNode::pointer pointer;
typedef typename BaseNode::const_pointer const_pointer;
typedef IteratorType self_type;
explicit ConstIterator(const node_type *node) :_pNode(node) { }
virtual ~ConstIterator() { }
virtual self_type &operator++() const = 0;
virtual self_type operator++(int) const = 0;
const_reference operator*() const
{
return _pNode->Item;
}
const_pointer operator->() const
{
return &_pNode->Item;
}
bool operator==(const self_type &other) const
{
return _pNode == other._pNode;
}
bool operator!=(const self_type &other) const
{
return !operator==(other);
}
protected:
node_type *_pNode;
};
}
}
| 23.368421 | 66 | 0.693318 |
32b2309a290661a0ad89ef638222708b7bd2f6de | 57,976 | cc | C++ | chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 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 "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include <stddef.h>
#include <string>
#include <utility>
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/values.h"
#include "chrome/browser/chromeos/arc/arc_session_manager.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/chromeos/arc/policy/arc_policy_util.h"
#include "chrome/browser/chromeos/login/session/user_session_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs_factory.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/app_list/arc/arc_package_syncable_service.h"
#include "chrome/browser/ui/app_list/arc/arc_pai_starter.h"
#include "chrome/grit/generated_resources.h"
#include "components/arc/arc_prefs.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/arc_util.h"
#include "components/arc/connection_holder.h"
#include "components/crx_file/id_util.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
constexpr char kActivity[] = "activity";
constexpr char kIconResourceId[] = "icon_resource_id";
constexpr char kInstallTime[] = "install_time";
constexpr char kIntentUri[] = "intent_uri";
constexpr char kInvalidatedIcons[] = "invalidated_icons";
constexpr char kLastBackupAndroidId[] = "last_backup_android_id";
constexpr char kLastBackupTime[] = "last_backup_time";
constexpr char kLastLaunchTime[] = "lastlaunchtime";
constexpr char kLaunchable[] = "launchable";
constexpr char kName[] = "name";
constexpr char kNotificationsEnabled[] = "notifications_enabled";
constexpr char kPackageName[] = "package_name";
constexpr char kPackageVersion[] = "package_version";
constexpr char kSticky[] = "sticky";
constexpr char kShortcut[] = "shortcut";
constexpr char kShouldSync[] = "should_sync";
constexpr char kSystem[] = "system";
constexpr char kUninstalled[] = "uninstalled";
constexpr char kVPNProvider[] = "vpnprovider";
constexpr base::TimeDelta kDetectDefaultAppAvailabilityTimeout =
base::TimeDelta::FromMinutes(1);
// Provider of write access to a dictionary storing ARC prefs.
class ScopedArcPrefUpdate : public DictionaryPrefUpdate {
public:
ScopedArcPrefUpdate(PrefService* service,
const std::string& id,
const std::string& path)
: DictionaryPrefUpdate(service, path), id_(id) {}
~ScopedArcPrefUpdate() override {}
// DictionaryPrefUpdate overrides:
base::DictionaryValue* Get() override {
base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
base::Value* dict_item =
dict->FindKeyOfType(id_, base::Value::Type::DICTIONARY);
if (!dict_item) {
dict_item = dict->SetKey(id_, base::Value(base::Value::Type::DICTIONARY));
}
return static_cast<base::DictionaryValue*>(dict_item);
}
private:
const std::string id_;
DISALLOW_COPY_AND_ASSIGN(ScopedArcPrefUpdate);
};
// Accessor for deferred set notifications enabled requests in prefs.
class SetNotificationsEnabledDeferred {
public:
explicit SetNotificationsEnabledDeferred(PrefService* prefs)
: prefs_(prefs) {}
void Put(const std::string& app_id, bool enabled) {
DictionaryPrefUpdate update(
prefs_, arc::prefs::kArcSetNotificationsEnabledDeferred);
base::DictionaryValue* const dict = update.Get();
dict->SetKey(app_id, base::Value(enabled));
}
bool Get(const std::string& app_id, bool* enabled) {
const base::DictionaryValue* dict =
prefs_->GetDictionary(arc::prefs::kArcSetNotificationsEnabledDeferred);
return dict->GetBoolean(app_id, enabled);
}
void Remove(const std::string& app_id) {
DictionaryPrefUpdate update(
prefs_, arc::prefs::kArcSetNotificationsEnabledDeferred);
base::DictionaryValue* const dict = update.Get();
dict->RemoveWithoutPathExpansion(app_id, /* out_value */ nullptr);
}
private:
PrefService* const prefs_;
};
bool InstallIconFromFileThread(const base::FilePath& icon_path,
const std::vector<uint8_t>& content_png) {
DCHECK(!content_png.empty());
base::CreateDirectory(icon_path.DirName());
int wrote =
base::WriteFile(icon_path, reinterpret_cast<const char*>(&content_png[0]),
content_png.size());
if (wrote != static_cast<int>(content_png.size())) {
VLOG(2) << "Failed to write ARC icon file: " << icon_path.MaybeAsASCII()
<< ".";
if (!base::DeleteFile(icon_path, false)) {
VLOG(2) << "Couldn't delete broken icon file" << icon_path.MaybeAsASCII()
<< ".";
}
return false;
}
return true;
}
void DeleteAppFolderFromFileThread(const base::FilePath& path) {
DCHECK(path.DirName().BaseName().MaybeAsASCII() == arc::prefs::kArcApps &&
(!base::PathExists(path) || base::DirectoryExists(path)));
const bool deleted = base::DeleteFile(path, true);
DCHECK(deleted);
}
// TODO(crbug.com/672829): Due to shutdown procedure dependency,
// ArcAppListPrefs may try to touch ArcSessionManager related stuff.
// Specifically, this returns false on shutdown phase.
// Remove this check after the shutdown behavior is fixed.
bool IsArcAlive() {
const auto* arc_session_manager = arc::ArcSessionManager::Get();
return arc_session_manager && arc_session_manager->IsAllowed();
}
// Returns true if ARC Android instance is supposed to be enabled for the
// profile. This can happen for if the user has opted in for the given profile,
// or when ARC always starts after login.
bool IsArcAndroidEnabledForProfile(const Profile* profile) {
return arc::ShouldArcAlwaysStart() ||
arc::IsArcPlayStoreEnabledForProfile(profile);
}
bool GetInt64FromPref(const base::DictionaryValue* dict,
const std::string& key,
int64_t* value) {
DCHECK(dict);
std::string value_str;
if (!dict->GetStringWithoutPathExpansion(key, &value_str)) {
VLOG(2) << "Can't find key in local pref dictionary. Invalid key: " << key
<< ".";
return false;
}
if (!base::StringToInt64(value_str, value)) {
VLOG(2) << "Can't change string to int64_t. Invalid string value: "
<< value_str << ".";
return false;
}
return true;
}
base::FilePath ToIconPath(const base::FilePath& app_path,
ui::ScaleFactor scale_factor) {
DCHECK(!app_path.empty());
switch (scale_factor) {
case ui::SCALE_FACTOR_100P:
return app_path.AppendASCII("icon_100p.png");
case ui::SCALE_FACTOR_125P:
return app_path.AppendASCII("icon_125p.png");
case ui::SCALE_FACTOR_133P:
return app_path.AppendASCII("icon_133p.png");
case ui::SCALE_FACTOR_140P:
return app_path.AppendASCII("icon_140p.png");
case ui::SCALE_FACTOR_150P:
return app_path.AppendASCII("icon_150p.png");
case ui::SCALE_FACTOR_180P:
return app_path.AppendASCII("icon_180p.png");
case ui::SCALE_FACTOR_200P:
return app_path.AppendASCII("icon_200p.png");
case ui::SCALE_FACTOR_250P:
return app_path.AppendASCII("icon_250p.png");
case ui::SCALE_FACTOR_300P:
return app_path.AppendASCII("icon_300p.png");
default:
NOTREACHED();
return base::FilePath();
}
}
} // namespace
// static
ArcAppListPrefs* ArcAppListPrefs::Create(
Profile* profile,
arc::ConnectionHolder<arc::mojom::AppInstance, arc::mojom::AppHost>*
app_connection_holder) {
return new ArcAppListPrefs(profile, app_connection_holder);
}
// static
void ArcAppListPrefs::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterDictionaryPref(arc::prefs::kArcApps);
registry->RegisterDictionaryPref(arc::prefs::kArcPackages);
registry->RegisterDictionaryPref(
arc::prefs::kArcSetNotificationsEnabledDeferred);
}
// static
ArcAppListPrefs* ArcAppListPrefs::Get(content::BrowserContext* context) {
return ArcAppListPrefsFactory::GetInstance()->GetForBrowserContext(context);
}
// static
std::string ArcAppListPrefs::GetAppId(const std::string& package_name,
const std::string& activity) {
if (package_name == arc::kPlayStorePackage &&
activity == arc::kPlayStoreActivity) {
return arc::kPlayStoreAppId;
}
const std::string input = package_name + "#" + activity;
const std::string app_id = crx_file::id_util::GenerateId(input);
return app_id;
}
std::string ArcAppListPrefs::GetAppIdByPackageName(
const std::string& package_name) const {
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
if (!apps)
return std::string();
for (const auto& it : apps->DictItems()) {
const base::Value& value = it.second;
const base::Value* installed_package_name =
value.FindKeyOfType(kPackageName, base::Value::Type::STRING);
if (!installed_package_name ||
installed_package_name->GetString() != package_name)
continue;
const base::Value* activity_name =
value.FindKeyOfType(kActivity, base::Value::Type::STRING);
return activity_name ? GetAppId(package_name, activity_name->GetString())
: std::string();
}
return std::string();
}
ArcAppListPrefs::ArcAppListPrefs(
Profile* profile,
arc::ConnectionHolder<arc::mojom::AppInstance, arc::mojom::AppHost>*
app_connection_holder)
: profile_(profile),
prefs_(profile->GetPrefs()),
app_connection_holder_(app_connection_holder),
default_apps_(this, profile),
weak_ptr_factory_(this) {
DCHECK(profile);
DCHECK(app_connection_holder);
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
const base::FilePath& base_path = profile->GetPath();
base_path_ = base_path.AppendASCII(arc::prefs::kArcApps);
invalidated_icon_scale_factor_mask_ = 0;
for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors())
invalidated_icon_scale_factor_mask_ |= (1U << scale_factor);
arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get();
if (!arc_session_manager)
return;
DCHECK(arc::IsArcAllowedForProfile(profile));
const std::vector<std::string> existing_app_ids = GetAppIds();
tracked_apps_.insert(existing_app_ids.begin(), existing_app_ids.end());
// Once default apps are ready OnDefaultAppsReady is called.
}
ArcAppListPrefs::~ArcAppListPrefs() {
arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get();
if (!arc_session_manager)
return;
DCHECK(arc::ArcServiceManager::Get());
arc_session_manager->RemoveObserver(this);
app_connection_holder_->RemoveObserver(this);
}
void ArcAppListPrefs::StartPrefs() {
// Don't tie ArcAppListPrefs created with sync test profile in sync
// integration test to ArcSessionManager.
if (!ArcAppListPrefsFactory::IsFactorySetForSyncTest()) {
arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get();
CHECK(arc_session_manager);
if (arc_session_manager->profile()) {
// Note: If ArcSessionManager has profile, it should be as same as the one
// this instance has, because ArcAppListPrefsFactory creates an instance
// only if the given Profile meets ARC's requirement.
// Anyway, just in case, check it here.
DCHECK_EQ(profile_, arc_session_manager->profile());
OnArcPlayStoreEnabledChanged(
arc::IsArcPlayStoreEnabledForProfile(profile_));
}
arc_session_manager->AddObserver(this);
}
app_connection_holder_->SetHost(this);
app_connection_holder_->AddObserver(this);
if (!app_connection_holder_->IsConnected())
OnConnectionClosed();
}
base::FilePath ArcAppListPrefs::GetAppPath(const std::string& app_id) const {
return base_path_.AppendASCII(app_id);
}
base::FilePath ArcAppListPrefs::MaybeGetIconPathForDefaultApp(
const std::string& app_id,
ui::ScaleFactor scale_factor) const {
const ArcDefaultAppList::AppInfo* default_app = default_apps_.GetApp(app_id);
if (!default_app || default_app->app_path.empty())
return base::FilePath();
return ToIconPath(default_app->app_path, scale_factor);
}
base::FilePath ArcAppListPrefs::GetIconPath(
const std::string& app_id,
ui::ScaleFactor scale_factor) const {
return ToIconPath(GetAppPath(app_id), scale_factor);
}
bool ArcAppListPrefs::IsIconRequestRecorded(
const std::string& app_id,
ui::ScaleFactor scale_factor) const {
const auto iter = request_icon_recorded_.find(app_id);
if (iter == request_icon_recorded_.end())
return false;
return iter->second & (1 << scale_factor);
}
void ArcAppListPrefs::MaybeRemoveIconRequestRecord(const std::string& app_id) {
request_icon_recorded_.erase(app_id);
}
void ArcAppListPrefs::ClearIconRequestRecord() {
request_icon_recorded_.clear();
}
void ArcAppListPrefs::RequestIcon(const std::string& app_id,
ui::ScaleFactor scale_factor) {
DCHECK_NE(app_id, arc::kPlayStoreAppId);
// ArcSessionManager can be terminated during test tear down, before callback
// into this function.
// TODO(victorhsieh): figure out the best way/place to handle this situation.
if (arc::ArcSessionManager::Get() == nullptr)
return;
if (!IsRegistered(app_id)) {
VLOG(2) << "Request to load icon for non-registered app: " << app_id << ".";
return;
}
// In case app is not ready, recorded request will be send to ARC when app
// becomes ready.
// This record will prevent ArcAppIcon from resending request to ARC for app
// icon when icon file decode failure is suffered in case app sends bad icon.
request_icon_recorded_[app_id] |= (1 << scale_factor);
if (!ready_apps_.count(app_id))
return;
if (!app_connection_holder_->IsConnected()) {
// AppInstance should be ready since we have app_id in ready_apps_. This
// can happen in browser_tests.
return;
}
std::unique_ptr<AppInfo> app_info = GetApp(app_id);
if (!app_info) {
VLOG(2) << "Failed to get app info: " << app_id << ".";
return;
}
if (app_info->icon_resource_id.empty()) {
auto* app_instance =
ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_, RequestAppIcon);
// Version 0 instance should always be available here because IsConnected()
// returned true above.
DCHECK(app_instance);
app_instance->RequestAppIcon(
app_info->package_name, app_info->activity,
static_cast<arc::mojom::ScaleFactor>(scale_factor));
} else {
auto* app_instance =
ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_, RequestIcon);
if (!app_instance)
return; // The instance version on ARC side was too old.
app_instance->RequestIcon(
app_info->icon_resource_id,
static_cast<arc::mojom::ScaleFactor>(scale_factor),
base::Bind(&ArcAppListPrefs::OnIcon, base::Unretained(this), app_id,
static_cast<arc::mojom::ScaleFactor>(scale_factor)));
}
}
void ArcAppListPrefs::MaybeRequestIcon(const std::string& app_id,
ui::ScaleFactor scale_factor) {
if (!IsIconRequestRecorded(app_id, scale_factor))
RequestIcon(app_id, scale_factor);
}
void ArcAppListPrefs::SetNotificationsEnabled(const std::string& app_id,
bool enabled) {
if (!IsRegistered(app_id)) {
VLOG(2) << "Request to set notifications enabled flag for non-registered "
<< "app:" << app_id << ".";
return;
}
std::unique_ptr<AppInfo> app_info = GetApp(app_id);
if (!app_info) {
VLOG(2) << "Failed to get app info: " << app_id << ".";
return;
}
// In case app is not ready, defer this request.
if (!ready_apps_.count(app_id)) {
SetNotificationsEnabledDeferred(prefs_).Put(app_id, enabled);
for (auto& observer : observer_list_)
observer.OnNotificationsEnabledChanged(app_info->package_name, enabled);
return;
}
auto* app_instance = ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_,
SetNotificationsEnabled);
if (!app_instance)
return;
SetNotificationsEnabledDeferred(prefs_).Remove(app_id);
app_instance->SetNotificationsEnabled(app_info->package_name, enabled);
}
void ArcAppListPrefs::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void ArcAppListPrefs::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
bool ArcAppListPrefs::HasObserver(Observer* observer) {
return observer_list_.HasObserver(observer);
}
base::RepeatingCallback<std::string(const std::string&)>
ArcAppListPrefs::GetAppIdByPackageNameCallback() {
return base::BindRepeating(
[](base::WeakPtr<ArcAppListPrefs> self, const std::string& package_name) {
if (!self)
return std::string();
return self->GetAppIdByPackageName(package_name);
},
weak_ptr_factory_.GetWeakPtr());
}
std::unique_ptr<ArcAppListPrefs::PackageInfo> ArcAppListPrefs::GetPackage(
const std::string& package_name) const {
if (!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_))
return nullptr;
const base::DictionaryValue* package = nullptr;
const base::DictionaryValue* packages =
prefs_->GetDictionary(arc::prefs::kArcPackages);
if (!packages ||
!packages->GetDictionaryWithoutPathExpansion(package_name, &package))
return std::unique_ptr<PackageInfo>();
bool uninstalled = false;
if (package->GetBoolean(kUninstalled, &uninstalled) && uninstalled)
return nullptr;
int32_t package_version = 0;
int64_t last_backup_android_id = 0;
int64_t last_backup_time = 0;
bool should_sync = false;
bool system = false;
bool vpn_provider = false;
GetInt64FromPref(package, kLastBackupAndroidId, &last_backup_android_id);
GetInt64FromPref(package, kLastBackupTime, &last_backup_time);
package->GetInteger(kPackageVersion, &package_version);
package->GetBoolean(kShouldSync, &should_sync);
package->GetBoolean(kSystem, &system);
package->GetBoolean(kVPNProvider, &vpn_provider);
return std::make_unique<PackageInfo>(package_name, package_version,
last_backup_android_id, last_backup_time,
should_sync, system, vpn_provider);
}
std::vector<std::string> ArcAppListPrefs::GetAppIds() const {
if (arc::ShouldArcAlwaysStart())
return GetAppIdsNoArcEnabledCheck();
if (!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) {
// Default ARC apps available before OptIn.
std::vector<std::string> ids;
for (const auto& default_app : default_apps_.app_map()) {
if (default_apps_.HasApp(default_app.first))
ids.push_back(default_app.first);
}
return ids;
}
return GetAppIdsNoArcEnabledCheck();
}
std::vector<std::string> ArcAppListPrefs::GetAppIdsNoArcEnabledCheck() const {
std::vector<std::string> ids;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
DCHECK(apps);
// crx_file::id_util is de-facto utility for id generation.
for (base::DictionaryValue::Iterator app_id(*apps); !app_id.IsAtEnd();
app_id.Advance()) {
if (!crx_file::id_util::IdIsValid(app_id.key()))
continue;
ids.push_back(app_id.key());
}
return ids;
}
std::unique_ptr<ArcAppListPrefs::AppInfo> ArcAppListPrefs::GetApp(
const std::string& app_id) const {
// Information for default app is available before ARC enabled.
if ((!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) &&
!default_apps_.HasApp(app_id))
return std::unique_ptr<AppInfo>();
const base::DictionaryValue* app = nullptr;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
if (!apps || !apps->GetDictionaryWithoutPathExpansion(app_id, &app))
return std::unique_ptr<AppInfo>();
std::string name;
std::string package_name;
std::string activity;
std::string intent_uri;
std::string icon_resource_id;
bool sticky = false;
bool notifications_enabled = true;
bool shortcut = false;
bool launchable = true;
app->GetString(kName, &name);
app->GetString(kPackageName, &package_name);
app->GetString(kActivity, &activity);
app->GetString(kIntentUri, &intent_uri);
app->GetString(kIconResourceId, &icon_resource_id);
app->GetBoolean(kSticky, &sticky);
app->GetBoolean(kNotificationsEnabled, ¬ifications_enabled);
app->GetBoolean(kShortcut, &shortcut);
app->GetBoolean(kLaunchable, &launchable);
DCHECK(!name.empty());
DCHECK(!shortcut || activity.empty());
DCHECK(!shortcut || !intent_uri.empty());
int64_t last_launch_time_internal = 0;
base::Time last_launch_time;
if (GetInt64FromPref(app, kLastLaunchTime, &last_launch_time_internal)) {
last_launch_time = base::Time::FromInternalValue(last_launch_time_internal);
}
bool deferred;
if (SetNotificationsEnabledDeferred(prefs_).Get(app_id, &deferred))
notifications_enabled = deferred;
return std::make_unique<AppInfo>(
name, package_name, activity, intent_uri, icon_resource_id,
last_launch_time, GetInstallTime(app_id), sticky, notifications_enabled,
ready_apps_.count(app_id) > 0,
launchable && arc::ShouldShowInLauncher(app_id), shortcut, launchable);
}
bool ArcAppListPrefs::IsRegistered(const std::string& app_id) const {
if ((!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) &&
!default_apps_.HasApp(app_id))
return false;
const base::DictionaryValue* app = nullptr;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
return apps && apps->GetDictionaryWithoutPathExpansion(app_id, &app);
}
bool ArcAppListPrefs::IsDefault(const std::string& app_id) const {
return default_apps_.HasApp(app_id);
}
bool ArcAppListPrefs::IsOem(const std::string& app_id) const {
const ArcDefaultAppList::AppInfo* app_info = default_apps_.GetApp(app_id);
return app_info && app_info->oem;
}
bool ArcAppListPrefs::IsShortcut(const std::string& app_id) const {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = GetApp(app_id);
return app_info && app_info->shortcut;
}
void ArcAppListPrefs::SetLastLaunchTime(const std::string& app_id) {
if (!IsRegistered(app_id)) {
NOTREACHED();
return;
}
// Usage time on hidden should not be tracked.
if (!arc::ShouldShowInLauncher(app_id))
return;
const base::Time time = base::Time::Now();
ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps);
base::DictionaryValue* app_dict = update.Get();
const std::string string_value = base::Int64ToString(time.ToInternalValue());
app_dict->SetString(kLastLaunchTime, string_value);
for (auto& observer : observer_list_)
observer.OnAppLastLaunchTimeUpdated(app_id);
if (first_launch_app_request_) {
first_launch_app_request_ = false;
// UI Shown time may not be set in unit tests.
const user_manager::UserManager* user_manager =
user_manager::UserManager::Get();
if (arc::ArcSessionManager::Get()->is_directly_started() &&
!user_manager->IsLoggedInAsKioskApp() &&
!user_manager->IsLoggedInAsArcKioskApp() &&
!chromeos::UserSessionManager::GetInstance()
->ui_shown_time()
.is_null()) {
UMA_HISTOGRAM_CUSTOM_TIMES(
"Arc.FirstAppLaunchRequest.TimeDelta",
time - chromeos::UserSessionManager::GetInstance()->ui_shown_time(),
base::TimeDelta::FromSeconds(1), base::TimeDelta::FromMinutes(2), 20);
}
}
}
void ArcAppListPrefs::DisableAllApps() {
std::unordered_set<std::string> old_ready_apps;
old_ready_apps.swap(ready_apps_);
for (auto& app_id : old_ready_apps)
NotifyAppReadyChanged(app_id, false);
}
void ArcAppListPrefs::NotifyRegisteredApps() {
if (apps_restored_)
return;
DCHECK(ready_apps_.empty());
std::vector<std::string> app_ids = GetAppIdsNoArcEnabledCheck();
for (const auto& app_id : app_ids) {
std::unique_ptr<AppInfo> app_info = GetApp(app_id);
if (!app_info) {
NOTREACHED();
continue;
}
// Default apps are reported earlier.
if (tracked_apps_.insert(app_id).second) {
for (auto& observer : observer_list_)
observer.OnAppRegistered(app_id, *app_info);
}
}
apps_restored_ = true;
}
void ArcAppListPrefs::RemoveAllAppsAndPackages() {
std::vector<std::string> app_ids = GetAppIdsNoArcEnabledCheck();
for (const auto& app_id : app_ids) {
if (!default_apps_.HasApp(app_id)) {
RemoveApp(app_id);
} else {
if (ready_apps_.count(app_id)) {
ready_apps_.erase(app_id);
NotifyAppReadyChanged(app_id, false);
}
}
}
DCHECK(ready_apps_.empty());
const std::vector<std::string> package_names_to_remove =
GetPackagesFromPrefs(false /* check_arc_alive */, true /* installed */);
for (const auto& package_name : package_names_to_remove) {
if (!default_apps_.HasPackage(package_name))
RemovePackageFromPrefs(prefs_, package_name);
for (auto& observer : observer_list_)
observer.OnPackageRemoved(package_name, false);
}
}
void ArcAppListPrefs::OnArcPlayStoreEnabledChanged(bool enabled) {
SetDefaultAppsFilterLevel();
// TODO(victorhsieh): Implement opt-in and opt-out.
if (arc::ShouldArcAlwaysStart())
return;
if (enabled)
NotifyRegisteredApps();
else
RemoveAllAppsAndPackages();
}
void ArcAppListPrefs::SetDefaultAppsFilterLevel() {
// There is no a blacklisting mechanism for Android apps. Until there is
// one, we have no option but to ban all pre-installed apps on Android side.
// Match this requirement and don't show pre-installed apps for managed users
// in app list.
if (arc::policy_util::IsAccountManaged(profile_)) {
default_apps_.set_filter_level(
arc::IsArcPlayStoreEnabledForProfile(profile_)
? ArcDefaultAppList::FilterLevel::OPTIONAL_APPS
: ArcDefaultAppList::FilterLevel::ALL);
} else {
default_apps_.set_filter_level(ArcDefaultAppList::FilterLevel::NOTHING);
}
// Register default apps if it was not registered before.
RegisterDefaultApps();
}
void ArcAppListPrefs::OnDefaultAppsReady() {
// Apply uninstalled packages now.
const std::vector<std::string> uninstalled_package_names =
GetPackagesFromPrefs(false /* check_arc_alive */, false /* installed */);
for (const auto& uninstalled_package_name : uninstalled_package_names)
default_apps_.MaybeMarkPackageUninstalled(uninstalled_package_name, true);
SetDefaultAppsFilterLevel();
default_apps_ready_ = true;
if (!default_apps_ready_callback_.is_null())
default_apps_ready_callback_.Run();
StartPrefs();
}
void ArcAppListPrefs::RegisterDefaultApps() {
// Report default apps first, note, app_map includes uninstalled and filtered
// out apps as well.
for (const auto& default_app : default_apps_.app_map()) {
const std::string& app_id = default_app.first;
if (!default_apps_.HasApp(app_id))
continue;
// Skip already tracked app.
if (tracked_apps_.count(app_id)) {
// Icon should be already taken from the cache. Play Store icon is loaded
// from internal resources.
if (ready_apps_.count(app_id) || app_id == arc::kPlayStoreAppId)
continue;
// Notify that icon is ready for default app.
for (auto& observer : observer_list_) {
for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors())
observer.OnAppIconUpdated(app_id, scale_factor);
}
continue;
}
const ArcDefaultAppList::AppInfo& app_info = *default_app.second.get();
AddAppAndShortcut(false /* app_ready */, app_info.name,
app_info.package_name, app_info.activity,
std::string() /* intent_uri */,
std::string() /* icon_resource_id */, false /* sticky */,
false /* notifications_enabled */, false /* shortcut */,
true /* launchable */);
}
}
base::Value* ArcAppListPrefs::GetPackagePrefs(const std::string& package_name,
const std::string& key) {
if (!GetPackage(package_name)) {
LOG(ERROR) << package_name << " can not be found.";
return nullptr;
}
ScopedArcPrefUpdate update(prefs_, package_name, arc::prefs::kArcPackages);
return update.Get()->FindKey(key);
}
void ArcAppListPrefs::SetPackagePrefs(const std::string& package_name,
const std::string& key,
base::Value value) {
if (!GetPackage(package_name)) {
LOG(ERROR) << package_name << " can not be found.";
return;
}
ScopedArcPrefUpdate update(prefs_, package_name, arc::prefs::kArcPackages);
update.Get()->SetKey(key, std::move(value));
}
void ArcAppListPrefs::SetDefaltAppsReadyCallback(base::Closure callback) {
DCHECK(!callback.is_null());
DCHECK(default_apps_ready_callback_.is_null());
default_apps_ready_callback_ = callback;
if (default_apps_ready_)
default_apps_ready_callback_.Run();
}
void ArcAppListPrefs::SimulateDefaultAppAvailabilityTimeoutForTesting() {
if (!detect_default_app_availability_timeout_.IsRunning())
return;
detect_default_app_availability_timeout_.Stop();
DetectDefaultAppAvailability();
}
void ArcAppListPrefs::OnConnectionReady() {
// Note, sync_service_ may be nullptr in testing.
sync_service_ = arc::ArcPackageSyncableService::Get(profile_);
is_initialized_ = false;
if (!app_list_refreshed_callback_.is_null())
std::move(app_list_refreshed_callback_).Run();
}
void ArcAppListPrefs::OnConnectionClosed() {
DisableAllApps();
installing_packages_count_ = 0;
default_apps_installations_.clear();
detect_default_app_availability_timeout_.Stop();
ClearIconRequestRecord();
if (sync_service_) {
sync_service_->StopSyncing(syncer::ARC_PACKAGE);
sync_service_ = nullptr;
}
is_initialized_ = false;
package_list_initial_refreshed_ = false;
app_list_refreshed_callback_.Reset();
}
void ArcAppListPrefs::HandleTaskCreated(const base::Optional<std::string>& name,
const std::string& package_name,
const std::string& activity) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
const std::string app_id = GetAppId(package_name, activity);
if (IsRegistered(app_id)) {
SetLastLaunchTime(app_id);
} else {
// Create runtime app entry that is valid for the current user session. This
// entry is not shown in App Launcher and only required for shelf
// integration.
AddAppAndShortcut(true /* app_ready */, name.has_value() ? *name : "",
package_name, activity, std::string() /* intent_uri */,
std::string() /* icon_resource_id */, false /* sticky */,
false /* notifications_enabled */, false /* shortcut */,
false /* launchable */);
}
}
void ArcAppListPrefs::AddAppAndShortcut(bool app_ready,
const std::string& name,
const std::string& package_name,
const std::string& activity,
const std::string& intent_uri,
const std::string& icon_resource_id,
const bool sticky,
const bool notifications_enabled,
const bool shortcut,
const bool launchable) {
const std::string app_id = shortcut ? GetAppId(package_name, intent_uri)
: GetAppId(package_name, activity);
// Do not add Play Store app for Public Session and Kiosk modes.
if (app_id == arc::kPlayStoreAppId && arc::IsRobotAccountMode())
return;
std::string updated_name = name;
// Add "(beta)" string to Play Store. See crbug.com/644576 for details.
if (app_id == arc::kPlayStoreAppId)
updated_name = l10n_util::GetStringUTF8(IDS_ARC_PLAYSTORE_ICON_TITLE_BETA);
const bool was_tracked = tracked_apps_.count(app_id);
if (was_tracked) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_old_info = GetApp(app_id);
DCHECK(app_old_info);
DCHECK(launchable);
if (updated_name != app_old_info->name) {
for (auto& observer : observer_list_)
observer.OnAppNameUpdated(app_id, updated_name);
}
}
ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps);
base::DictionaryValue* app_dict = update.Get();
app_dict->SetString(kName, updated_name);
app_dict->SetString(kPackageName, package_name);
app_dict->SetString(kActivity, activity);
app_dict->SetString(kIntentUri, intent_uri);
app_dict->SetString(kIconResourceId, icon_resource_id);
app_dict->SetBoolean(kSticky, sticky);
app_dict->SetBoolean(kNotificationsEnabled, notifications_enabled);
app_dict->SetBoolean(kShortcut, shortcut);
app_dict->SetBoolean(kLaunchable, launchable);
// Note the install time is the first time the Chrome OS sees the app, not the
// actual install time in Android side.
if (GetInstallTime(app_id).is_null()) {
std::string install_time_str =
base::Int64ToString(base::Time::Now().ToInternalValue());
app_dict->SetString(kInstallTime, install_time_str);
}
const bool was_disabled = ready_apps_.count(app_id) == 0;
DCHECK(!(!was_disabled && !app_ready));
if (was_disabled && app_ready)
ready_apps_.insert(app_id);
if (was_tracked) {
if (was_disabled && app_ready)
NotifyAppReadyChanged(app_id, true);
} else {
AppInfo app_info(updated_name, package_name, activity, intent_uri,
icon_resource_id, base::Time(), GetInstallTime(app_id),
sticky, notifications_enabled, app_ready,
launchable && arc::ShouldShowInLauncher(app_id), shortcut,
launchable);
for (auto& observer : observer_list_)
observer.OnAppRegistered(app_id, app_info);
tracked_apps_.insert(app_id);
}
if (app_ready) {
int icon_update_mask = 0;
app_dict->GetInteger(kInvalidatedIcons, &icon_update_mask);
auto pending_icons = request_icon_recorded_.find(app_id);
if (pending_icons != request_icon_recorded_.end())
icon_update_mask |= pending_icons->second;
for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) {
if (icon_update_mask & (1 << scale_factor))
RequestIcon(app_id, scale_factor);
}
bool deferred_notifications_enabled;
if (SetNotificationsEnabledDeferred(prefs_).Get(
app_id, &deferred_notifications_enabled)) {
SetNotificationsEnabled(app_id, deferred_notifications_enabled);
}
}
}
void ArcAppListPrefs::RemoveApp(const std::string& app_id) {
// Delete cached icon if there is any.
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = GetApp(app_id);
if (app_info && !app_info->icon_resource_id.empty()) {
arc::RemoveCachedIcon(app_info->icon_resource_id);
}
MaybeRemoveIconRequestRecord(app_id);
// From now, app is not available.
ready_apps_.erase(app_id);
// app_id may be released by observers, get the path first. It should be done
// before removing prefs entry in order not to mix with pre-build default apps
// files.
const base::FilePath app_path = GetAppPath(app_id);
// Remove from prefs.
DictionaryPrefUpdate update(prefs_, arc::prefs::kArcApps);
base::DictionaryValue* apps = update.Get();
const bool removed = apps->Remove(app_id, nullptr);
DCHECK(removed);
DCHECK(tracked_apps_.count(app_id));
for (auto& observer : observer_list_)
observer.OnAppRemoved(app_id);
tracked_apps_.erase(app_id);
// Remove local data on file system.
base::PostTaskWithTraits(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::Bind(&DeleteAppFolderFromFileThread, app_path));
}
void ArcAppListPrefs::AddOrUpdatePackagePrefs(
PrefService* prefs, const arc::mojom::ArcPackageInfo& package) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
const std::string& package_name = package.package_name;
default_apps_.MaybeMarkPackageUninstalled(package_name, false);
if (package_name.empty()) {
VLOG(2) << "Package name cannot be empty.";
return;
}
ScopedArcPrefUpdate update(prefs, package_name, arc::prefs::kArcPackages);
base::DictionaryValue* package_dict = update.Get();
const std::string id_str =
base::Int64ToString(package.last_backup_android_id);
const std::string time_str = base::Int64ToString(package.last_backup_time);
int old_package_version = -1;
package_dict->GetInteger(kPackageVersion, &old_package_version);
package_dict->SetBoolean(kShouldSync, package.sync);
package_dict->SetInteger(kPackageVersion, package.package_version);
package_dict->SetString(kLastBackupAndroidId, id_str);
package_dict->SetString(kLastBackupTime, time_str);
package_dict->SetBoolean(kSystem, package.system);
package_dict->SetBoolean(kUninstalled, false);
package_dict->SetBoolean(kVPNProvider, package.vpn_provider);
if (old_package_version == -1 ||
old_package_version == package.package_version) {
return;
}
InvalidatePackageIcons(package_name);
}
void ArcAppListPrefs::RemovePackageFromPrefs(PrefService* prefs,
const std::string& package_name) {
default_apps_.MaybeMarkPackageUninstalled(package_name, true);
if (!default_apps_.HasPackage(package_name)) {
DictionaryPrefUpdate update(prefs, arc::prefs::kArcPackages);
base::DictionaryValue* packages = update.Get();
const bool removed = packages->RemoveWithoutPathExpansion(package_name,
nullptr);
DCHECK(removed);
} else {
ScopedArcPrefUpdate update(prefs, package_name, arc::prefs::kArcPackages);
base::DictionaryValue* package_dict = update.Get();
package_dict->SetBoolean(kUninstalled, true);
}
}
void ArcAppListPrefs::OnAppListRefreshed(
std::vector<arc::mojom::AppInfoPtr> apps) {
DCHECK(app_list_refreshed_callback_.is_null());
if (!app_connection_holder_->IsConnected()) {
LOG(ERROR) << "App instance is not connected. Delaying app list refresh. "
<< "See b/70566216.";
app_list_refreshed_callback_ =
base::BindOnce(&ArcAppListPrefs::OnAppListRefreshed,
weak_ptr_factory_.GetWeakPtr(), std::move(apps));
return;
}
DCHECK(IsArcAndroidEnabledForProfile(profile_));
std::vector<std::string> old_apps = GetAppIds();
ready_apps_.clear();
for (const auto& app : apps) {
AddAppAndShortcut(true /* app_ready */, app->name, app->package_name,
app->activity, std::string() /* intent_uri */,
std::string() /* icon_resource_id */, app->sticky,
app->notifications_enabled, false /* shortcut */,
true /* launchable */);
}
// Detect removed ARC apps after current refresh.
for (const auto& app_id : old_apps) {
if (ready_apps_.count(app_id))
continue;
if (IsShortcut(app_id)) {
// If this is a shortcut, we just mark it as ready.
ready_apps_.insert(app_id);
NotifyAppReadyChanged(app_id, true);
} else {
// Default apps may not be installed yet at this moment.
if (!default_apps_.HasApp(app_id))
RemoveApp(app_id);
}
}
if (!is_initialized_) {
is_initialized_ = true;
UMA_HISTOGRAM_COUNTS_1000("Arc.AppsInstalledAtStartup", ready_apps_.size());
arc::ArcPaiStarter* pai_starter =
arc::ArcSessionManager::Get()->pai_starter();
if (pai_starter) {
pai_starter->AddOnStartCallback(
base::BindOnce(&ArcAppListPrefs::MaybeSetDefaultAppLoadingTimeout,
weak_ptr_factory_.GetWeakPtr()));
} else {
MaybeSetDefaultAppLoadingTimeout();
}
}
}
void ArcAppListPrefs::DetectDefaultAppAvailability() {
for (const auto& package : default_apps_.GetActivePackages()) {
// Check if already installed or installation in progress.
if (!GetPackage(package) && !default_apps_installations_.count(package))
HandlePackageRemoved(package);
}
}
void ArcAppListPrefs::MaybeSetDefaultAppLoadingTimeout() {
// Find at least one not installed default app package.
for (const auto& package : default_apps_.GetActivePackages()) {
if (!GetPackage(package)) {
detect_default_app_availability_timeout_.Start(FROM_HERE,
kDetectDefaultAppAvailabilityTimeout, this,
&ArcAppListPrefs::DetectDefaultAppAvailability);
break;
}
}
}
void ArcAppListPrefs::AddApp(const arc::mojom::AppInfo& app_info) {
if ((app_info.name.empty() || app_info.package_name.empty() ||
app_info.activity.empty())) {
VLOG(2) << "App Name, package name, and activity cannot be empty.";
return;
}
AddAppAndShortcut(true /* app_ready */, app_info.name, app_info.package_name,
app_info.activity, std::string() /* intent_uri */,
std::string() /* icon_resource_id */, app_info.sticky,
app_info.notifications_enabled, false /* shortcut */,
true /* launchable */);
}
void ArcAppListPrefs::OnAppAddedDeprecated(arc::mojom::AppInfoPtr app) {
AddApp(*app);
}
void ArcAppListPrefs::InvalidateAppIcons(const std::string& app_id) {
// Ignore Play Store app since we provide its icon in Chrome resources.
if (app_id == arc::kPlayStoreAppId)
return;
// Clean up previous icon records. They may refer to outdated icons.
MaybeRemoveIconRequestRecord(app_id);
{
ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps);
base::DictionaryValue* app_dict = update.Get();
app_dict->SetInteger(kInvalidatedIcons,
invalidated_icon_scale_factor_mask_);
}
for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors())
MaybeRequestIcon(app_id, scale_factor);
}
void ArcAppListPrefs::InvalidatePackageIcons(const std::string& package_name) {
for (const std::string& app_id : GetAppsForPackage(package_name))
InvalidateAppIcons(app_id);
}
void ArcAppListPrefs::OnPackageAppListRefreshed(
const std::string& package_name,
std::vector<arc::mojom::AppInfoPtr> apps) {
if (package_name.empty()) {
VLOG(2) << "Package name cannot be empty.";
return;
}
std::unordered_set<std::string> apps_to_remove =
GetAppsForPackage(package_name);
default_apps_.MaybeMarkPackageUninstalled(package_name, false);
for (const auto& app : apps) {
const std::string app_id = GetAppId(app->package_name, app->activity);
apps_to_remove.erase(app_id);
AddApp(*app);
}
for (const auto& app_id : apps_to_remove)
RemoveApp(app_id);
}
void ArcAppListPrefs::OnInstallShortcut(arc::mojom::ShortcutInfoPtr shortcut) {
if ((shortcut->name.empty() || shortcut->intent_uri.empty())) {
VLOG(2) << "Shortcut Name, and intent_uri cannot be empty.";
return;
}
AddAppAndShortcut(true /* app_ready */, shortcut->name,
shortcut->package_name, std::string() /* activity */,
shortcut->intent_uri, shortcut->icon_resource_id,
false /* sticky */, false /* notifications_enabled */,
true /* shortcut */, true /* launchable */);
}
void ArcAppListPrefs::OnUninstallShortcut(const std::string& package_name,
const std::string& intent_uri) {
std::vector<std::string> shortcuts_to_remove;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
for (base::DictionaryValue::Iterator app_it(*apps); !app_it.IsAtEnd();
app_it.Advance()) {
const base::Value* value = &app_it.value();
const base::DictionaryValue* app;
bool shortcut;
std::string installed_package_name;
std::string installed_intent_uri;
if (!value->GetAsDictionary(&app) ||
!app->GetBoolean(kShortcut, &shortcut) ||
!app->GetString(kPackageName, &installed_package_name) ||
!app->GetString(kIntentUri, &installed_intent_uri)) {
VLOG(2) << "Failed to extract information for " << app_it.key() << ".";
continue;
}
if (!shortcut || installed_package_name != package_name ||
installed_intent_uri != intent_uri) {
continue;
}
shortcuts_to_remove.push_back(app_it.key());
}
for (const auto& shortcut_id : shortcuts_to_remove)
RemoveApp(shortcut_id);
}
std::unordered_set<std::string> ArcAppListPrefs::GetAppsForPackage(
const std::string& package_name) const {
return GetAppsAndShortcutsForPackage(package_name,
false /* include_shortcuts */);
}
std::unordered_set<std::string> ArcAppListPrefs::GetAppsAndShortcutsForPackage(
const std::string& package_name,
bool include_shortcuts) const {
std::unordered_set<std::string> app_set;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
for (base::DictionaryValue::Iterator app_it(*apps); !app_it.IsAtEnd();
app_it.Advance()) {
const base::Value* value = &app_it.value();
const base::DictionaryValue* app;
if (!value->GetAsDictionary(&app)) {
NOTREACHED();
continue;
}
std::string app_package;
if (!app->GetString(kPackageName, &app_package)) {
NOTREACHED();
continue;
}
if (package_name != app_package)
continue;
if (!include_shortcuts) {
bool shortcut = false;
if (app->GetBoolean(kShortcut, &shortcut) && shortcut)
continue;
}
app_set.insert(app_it.key());
}
return app_set;
}
void ArcAppListPrefs::HandlePackageRemoved(const std::string& package_name) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
const std::unordered_set<std::string> apps_to_remove =
GetAppsAndShortcutsForPackage(package_name, true /* include_shortcuts */);
for (const auto& app_id : apps_to_remove)
RemoveApp(app_id);
RemovePackageFromPrefs(prefs_, package_name);
}
void ArcAppListPrefs::OnPackageRemoved(const std::string& package_name) {
HandlePackageRemoved(package_name);
for (auto& observer : observer_list_)
observer.OnPackageRemoved(package_name, true);
}
void ArcAppListPrefs::OnAppIcon(const std::string& package_name,
const std::string& activity,
arc::mojom::ScaleFactor scale_factor,
const std::vector<uint8_t>& icon_png_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_NE(0u, icon_png_data.size());
std::string app_id = GetAppId(package_name, activity);
if (!IsRegistered(app_id)) {
VLOG(2) << "Request to update icon for non-registered app: " << app_id;
return;
}
InstallIcon(app_id, static_cast<ui::ScaleFactor>(scale_factor),
icon_png_data);
}
void ArcAppListPrefs::OnIcon(const std::string& app_id,
arc::mojom::ScaleFactor scale_factor,
const std::vector<uint8_t>& icon_png_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_NE(0u, icon_png_data.size());
if (!IsRegistered(app_id)) {
VLOG(2) << "Request to update icon for non-registered app: " << app_id;
return;
}
InstallIcon(app_id, static_cast<ui::ScaleFactor>(scale_factor),
icon_png_data);
}
void ArcAppListPrefs::OnTaskCreated(int32_t task_id,
const std::string& package_name,
const std::string& activity,
const base::Optional<std::string>& name,
const base::Optional<std::string>& intent) {
HandleTaskCreated(name, package_name, activity);
for (auto& observer : observer_list_) {
observer.OnTaskCreated(task_id,
package_name,
activity,
intent.value_or(std::string()));
}
}
void ArcAppListPrefs::OnTaskDescriptionUpdated(
int32_t task_id,
const std::string& label,
const std::vector<uint8_t>& icon_png_data) {
for (auto& observer : observer_list_)
observer.OnTaskDescriptionUpdated(task_id, label, icon_png_data);
}
void ArcAppListPrefs::OnTaskDestroyed(int32_t task_id) {
for (auto& observer : observer_list_)
observer.OnTaskDestroyed(task_id);
}
void ArcAppListPrefs::OnTaskSetActive(int32_t task_id) {
for (auto& observer : observer_list_)
observer.OnTaskSetActive(task_id);
}
void ArcAppListPrefs::OnNotificationsEnabledChanged(
const std::string& package_name,
bool enabled) {
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
for (base::DictionaryValue::Iterator app(*apps); !app.IsAtEnd();
app.Advance()) {
const base::DictionaryValue* app_dict;
std::string app_package_name;
if (!app.value().GetAsDictionary(&app_dict) ||
!app_dict->GetString(kPackageName, &app_package_name)) {
NOTREACHED();
continue;
}
if (app_package_name != package_name) {
continue;
}
ScopedArcPrefUpdate update(prefs_, app.key(), arc::prefs::kArcApps);
base::DictionaryValue* updateing_app_dict = update.Get();
updateing_app_dict->SetBoolean(kNotificationsEnabled, enabled);
}
for (auto& observer : observer_list_)
observer.OnNotificationsEnabledChanged(package_name, enabled);
}
bool ArcAppListPrefs::IsUnknownPackage(const std::string& package_name) const {
return !GetPackage(package_name) && sync_service_ &&
!sync_service_->IsPackageSyncing(package_name);
}
void ArcAppListPrefs::OnPackageAdded(
arc::mojom::ArcPackageInfoPtr package_info) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
AddOrUpdatePackagePrefs(prefs_, *package_info);
for (auto& observer : observer_list_)
observer.OnPackageInstalled(*package_info);
}
void ArcAppListPrefs::OnPackageModified(
arc::mojom::ArcPackageInfoPtr package_info) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
AddOrUpdatePackagePrefs(prefs_, *package_info);
for (auto& observer : observer_list_)
observer.OnPackageModified(*package_info);
}
void ArcAppListPrefs::OnPackageListRefreshed(
std::vector<arc::mojom::ArcPackageInfoPtr> packages) {
DCHECK(IsArcAndroidEnabledForProfile(profile_));
const std::vector<std::string> old_packages(GetPackagesFromPrefs());
std::unordered_set<std::string> current_packages;
for (const auto& package : packages) {
AddOrUpdatePackagePrefs(prefs_, *package);
current_packages.insert((*package).package_name);
}
for (const auto& package_name : old_packages) {
if (!current_packages.count(package_name))
RemovePackageFromPrefs(prefs_, package_name);
}
package_list_initial_refreshed_ = true;
for (auto& observer : observer_list_)
observer.OnPackageListInitialRefreshed();
}
std::vector<std::string> ArcAppListPrefs::GetPackagesFromPrefs() const {
return GetPackagesFromPrefs(true /* check_arc_alive */, true /* installed */);
}
std::vector<std::string> ArcAppListPrefs::GetPackagesFromPrefs(
bool check_arc_alive,
bool installed) const {
std::vector<std::string> packages;
if (check_arc_alive &&
(!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_))) {
return packages;
}
const base::DictionaryValue* package_prefs =
prefs_->GetDictionary(arc::prefs::kArcPackages);
for (base::DictionaryValue::Iterator package(*package_prefs);
!package.IsAtEnd(); package.Advance()) {
const base::DictionaryValue* package_info;
if (!package.value().GetAsDictionary(&package_info)) {
NOTREACHED();
continue;
}
bool uninstalled = false;
package_info->GetBoolean(kUninstalled, &uninstalled);
if (installed != !uninstalled)
continue;
packages.push_back(package.key());
}
return packages;
}
base::Time ArcAppListPrefs::GetInstallTime(const std::string& app_id) const {
const base::DictionaryValue* app = nullptr;
const base::DictionaryValue* apps =
prefs_->GetDictionary(arc::prefs::kArcApps);
if (!apps || !apps->GetDictionaryWithoutPathExpansion(app_id, &app))
return base::Time();
std::string install_time_str;
if (!app->GetString(kInstallTime, &install_time_str))
return base::Time();
int64_t install_time_i64;
if (!base::StringToInt64(install_time_str, &install_time_i64))
return base::Time();
return base::Time::FromInternalValue(install_time_i64);
}
void ArcAppListPrefs::InstallIcon(const std::string& app_id,
ui::ScaleFactor scale_factor,
const std::vector<uint8_t>& content_png) {
const base::FilePath icon_path = GetIconPath(app_id, scale_factor);
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::Bind(&InstallIconFromFileThread, icon_path, content_png),
base::Bind(&ArcAppListPrefs::OnIconInstalled,
weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor));
}
void ArcAppListPrefs::OnIconInstalled(const std::string& app_id,
ui::ScaleFactor scale_factor,
bool install_succeed) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!install_succeed)
return;
ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps);
int invalidated_icon_mask = 0;
base::DictionaryValue* app_dict = update.Get();
app_dict->GetInteger(kInvalidatedIcons, &invalidated_icon_mask);
invalidated_icon_mask &= (~(1 << scale_factor));
app_dict->SetInteger(kInvalidatedIcons, invalidated_icon_mask);
for (auto& observer : observer_list_)
observer.OnAppIconUpdated(app_id, scale_factor);
}
void ArcAppListPrefs::OnInstallationStarted(
const base::Optional<std::string>& package_name) {
++installing_packages_count_;
if (!package_name.has_value())
return;
if (default_apps_.HasPackage(*package_name))
default_apps_installations_.insert(*package_name);
for (auto& observer : observer_list_)
observer.OnInstallationStarted(*package_name);
}
void ArcAppListPrefs::OnInstallationFinished(
arc::mojom::InstallationResultPtr result) {
if (result && default_apps_.HasPackage(result->package_name)) {
default_apps_installations_.erase(result->package_name);
if (!result->success && !GetPackage(result->package_name))
HandlePackageRemoved(result->package_name);
}
if (result) {
for (auto& observer : observer_list_)
observer.OnInstallationFinished(result->package_name, result->success);
}
if (!installing_packages_count_) {
VLOG(2) << "Received unexpected installation finished event";
return;
}
--installing_packages_count_;
}
void ArcAppListPrefs::NotifyAppReadyChanged(const std::string& app_id,
bool ready) {
for (auto& observer : observer_list_)
observer.OnAppReadyChanged(app_id, ready);
}
ArcAppListPrefs::AppInfo::AppInfo(const std::string& name,
const std::string& package_name,
const std::string& activity,
const std::string& intent_uri,
const std::string& icon_resource_id,
const base::Time& last_launch_time,
const base::Time& install_time,
bool sticky,
bool notifications_enabled,
bool ready,
bool showInLauncher,
bool shortcut,
bool launchable)
: name(name),
package_name(package_name),
activity(activity),
intent_uri(intent_uri),
icon_resource_id(icon_resource_id),
last_launch_time(last_launch_time),
install_time(install_time),
sticky(sticky),
notifications_enabled(notifications_enabled),
ready(ready),
showInLauncher(showInLauncher),
shortcut(shortcut),
launchable(launchable) {}
// Need to add explicit destructor for chromium style checker error:
// Complex class/struct needs an explicit out-of-line destructor
ArcAppListPrefs::AppInfo::~AppInfo() {}
ArcAppListPrefs::PackageInfo::PackageInfo(const std::string& package_name,
int32_t package_version,
int64_t last_backup_android_id,
int64_t last_backup_time,
bool should_sync,
bool system,
bool vpn_provider)
: package_name(package_name),
package_version(package_version),
last_backup_android_id(last_backup_android_id),
last_backup_time(last_backup_time),
should_sync(should_sync),
system(system),
vpn_provider(vpn_provider) {}
| 35.920694 | 80 | 0.68863 |
32b30c542f6278376aae76f245f8909cb199d7c5 | 8,768 | cpp | C++ | src/Roids.cpp | bhhaskin/roids | a20889b8d7ad64491c21fd6f80920562eecdd70d | [
"MIT"
] | null | null | null | src/Roids.cpp | bhhaskin/roids | a20889b8d7ad64491c21fd6f80920562eecdd70d | [
"MIT"
] | null | null | null | src/Roids.cpp | bhhaskin/roids | a20889b8d7ad64491c21fd6f80920562eecdd70d | [
"MIT"
] | null | null | null | #include "Roids.h"
#include "util/SimpleLogger/simplog.h"
#include "states/MenuState.h"
#include <stdio.h>
#include <string>
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
Roids::Roids() {
targetFPS = 60.0;
screenWidth = 800;
screenHeight = 600;
fontName = "res/fonts/PressStart2P-Regular.ttf";
showFPS = true;
simplog.writeLog( SIMPLOG_VERBOSE, "Target FPS: %.2f", targetFPS );
simplog.writeLog( SIMPLOG_VERBOSE, "Screen Width: %d", screenWidth );
simplog.writeLog( SIMPLOG_VERBOSE, "Screen Height: %d", screenHeight );
simplog.writeLog( SIMPLOG_VERBOSE, "Font Name: %s", fontName );
simplog.writeLog( SIMPLOG_VERBOSE, "Display FPS set to '%s'", showFPS ? "true" : "false" );
display = NULL;
main_queue = NULL;
input_queue = NULL;
timer = NULL;
font12 = NULL;
font18 = NULL;
// Initialize Allegro
if( !al_init() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize Allegro!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Allegro successfully initiallized" );
}
// Create the display
display = al_create_display( screenWidth, screenHeight);
if( !display ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to create display!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Display created successfully" );
}
// Initialize the keyboard
if( !al_install_keyboard() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize the keyboard!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Keyboard initialized successfully" );
}
// Initialize the mouse
if( !al_install_mouse() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize the mouse!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Mouse initialized successfully" );
}
// Create the main event queue
main_queue = al_create_event_queue();
if( !main_queue ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to create main event queue!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Main event Queue created susscessfully" );
}
// Create the input event queue
input_queue = al_create_event_queue();
if( !input_queue ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to create input event queue!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_DEBUG, "Input event Queue created susscessfully" );
}
// Register the display with the event queue
al_register_event_source( main_queue, al_get_display_event_source( display ) );
simplog.writeLog( SIMPLOG_VERBOSE, "Display event registered" );
// Register the keyboard with the event queue
al_register_event_source( input_queue, al_get_keyboard_event_source() );
simplog.writeLog( SIMPLOG_VERBOSE, "Keyboard event registered" );
// Register the mouse with the event queue
al_register_event_source( input_queue, al_get_mouse_event_source() );
simplog.writeLog( SIMPLOG_VERBOSE, "Mouse event registered" );
// Initialize Allegro's image addon for handling images
if( !al_init_image_addon() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize image addon!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_VERBOSE, "Image addon initialized" );
}
// Initialize Allegro's primitives addon for handling images
if( !al_init_primitives_addon() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize primitives addon!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_VERBOSE, "Primitives addon initialized" );
}
// Initialize Allegro's font addon for handling fonts
al_init_font_addon();
simplog.writeLog( SIMPLOG_VERBOSE, "Font addon initialized" );
// Initialize Allegro's TTF addon for handling TTF fonts
if( !al_init_ttf_addon() ) {
simplog.writeLog( SIMPLOG_FATAL, "Failed to initialize TTF addon!" );
throw -1;
} else {
simplog.writeLog( SIMPLOG_VERBOSE, "TTF addon initialized" );
}
// Load a size 18 font
font18 = al_load_font( fontName, 18, 0 );
if( !font18 ) {
// simplog.writeLog( SIMPLOG_FATAL, "Failed to load font '%s' at size %d!", fontName, 18 );
throw -1;
} else {
// simplog.writeLog( SIMPLOG_DEBUG, "Font '%s' loaded at size %d", fontName, 18 );
}
// Load a size 12 font
font12 = al_load_font( fontName, 12, 0 );
if( !font12 ) {
// simplog.writeLog( SIMPLOG_FATAL, "Failed to load font '%s' at size %d!", fontName, 12 );
throw -1;
} else {
// simplog.writeLog( SIMPLOG_DEBUG, "Font '%s' loaded at size %d", fontName, 12 );
}
// Create a timer to cap the game FPS
timer = al_create_timer( 1.0 / targetFPS );
if( !timer ) {
// simplog.writeLog( SIMPLOG_FATAL, "Failed to create timer with resolution of %.2f seconds!", 1.0 / targetFPS );
throw -1;
} else {
// simplog.writeLog( SIMPLOG_VERBOSE, "Timer created with resolution of %.2f seconds", 1.0 / targetFPS );
}
// Register the timer with the event queue
al_register_event_source( main_queue, al_get_timer_event_source( timer ) );
// simplog.writeLog( SIMPLOG_VERBOSE, "Timer event registered" );
// Clear the screen to black
al_clear_to_color( al_map_rgb( 0, 0, 0 ) );
// Push menu state onto the stack
states = new std::stack<BaseState*>();
states->push( new MenuState( display, input_queue, states ) );
}
Roids::~Roids() {
al_destroy_display( display );
simplog.writeLog( SIMPLOG_VERBOSE, "Display destroyed" );
al_destroy_event_queue( main_queue );
simplog.writeLog( SIMPLOG_VERBOSE, "Main event queue destroyed" );
al_destroy_event_queue( input_queue );
simplog.writeLog( SIMPLOG_VERBOSE, "Input event queue destroyed" );
al_destroy_timer( timer );
simplog.writeLog( SIMPLOG_VERBOSE, "Timer destroyed" );
al_destroy_font( font18 );
al_destroy_font( font12 );
simplog.writeLog( SIMPLOG_VERBOSE, "Font destroyed" );
simplog.writeLog( SIMPLOG_DEBUG, "All game objects destroyed" );
}
void Roids::play() {
simplog.writeLog( SIMPLOG_INFO, "Roids started successfully!" );
// Start the timer
al_start_timer( timer );
simplog.writeLog( SIMPLOG_VERBOSE, "Timer started" );
// Run loop variables
bool done = false;
bool redraw = true;
double lastTime = al_get_time();
double currentFPS = 0.0;
int frames_done = 1;
ALLEGRO_EVENT event;
// Run loop
while( !done ) {
// Wait for an event to occur
al_wait_for_event( main_queue, &event );
// Redraw only when the timer event is triggered to cap FPS
if( event.type == ALLEGRO_EVENT_TIMER ) {
redraw = true;
} else if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE ) {
done = true;
}
// Get current time
double currentTime = al_get_time();
// Calculate delta time
double delta = currentTime - lastTime;
// Calculate current FPS
if( delta >= 1.0 ) {
currentFPS = frames_done / delta;
frames_done = 0;
lastTime = currentTime;
}
// Redraw if the timer was triggered, and the event queue is empty
if( redraw && al_is_event_queue_empty( main_queue ) ) {
redraw = false;
// Update and render the current state
bool updateOkay = states->top()->update( delta );
bool renderOkay = states->top()->render();
// Check if update and render completed okay for the current state
if( !updateOkay || !renderOkay ) {
// Delete the current state and pop if off the stack
delete states->top();
states->pop();
// If there are no states left, end the run loop
if( states->empty() ) {
done = true;
}
}
// Print the FPS in the upper left corner
if( showFPS ) {
al_draw_textf( font12, al_map_rgb( 255, 255, 255 ), 0, 0, ALLEGRO_ALIGN_LEFT, "FPS: %.2f", currentFPS );
}
// Flip the display
al_flip_display();
}
// Increment the current frames total
frames_done++;
}
}
| 33.723077 | 122 | 0.615876 |
32b7f262ecdee5430ec11c40f35d8b6da5a9e9b6 | 1,577 | cpp | C++ | asl/audio/DummyPump.cpp | artcom/asl | d47748983678c245ac2da3b5de56245ac41768fe | [
"BSL-1.0"
] | 2 | 2016-01-11T01:06:11.000Z | 2019-07-24T02:27:13.000Z | asl/audio/DummyPump.cpp | artcom/asl | d47748983678c245ac2da3b5de56245ac41768fe | [
"BSL-1.0"
] | null | null | null | asl/audio/DummyPump.cpp | artcom/asl | d47748983678c245ac2da3b5de56245ac41768fe | [
"BSL-1.0"
] | 1 | 2016-01-31T18:14:37.000Z | 2016-01-31T18:14:37.000Z | /* __ ___ ____ _____ ______ _______ ________ _______ ______ _____ ____ ___ __
//
// Copyright (C) 1993-2012, ART+COM AG Berlin, Germany <www.artcom.de>
//
// This file is part of the ART+COM Standard Library (asl).
//
// It is 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 "DummyPump.h"
#include <asl/base/Logger.h>
#include <asl/base/string_functions.h>
#include <asl/math/numeric_functions.h>
#include <asl/base/Assure.h>
//#include <exception>
//#include <sstream>
//#include <string.h>
using namespace std;
namespace asl {
DummyPump::~DummyPump () {
AC_INFO << "DummyPump::~DummyPump";
Pump::stop();
}
Time DummyPump::getCurrentTime () {
return Time();
}
DummyPump::DummyPump ()
: Pump(SF_F32, 0)
{
AC_INFO << "DummyPump::DummyPump";
setDeviceName("Dummy Sound Device");
setCardName("Dummy Sound Card");
_curFrame = 0;
_myOutputBuffer.init(2048, getNumOutputChannels(), getNativeSampleRate());
dumpState();
start();
}
void DummyPump::pump()
{
static Time lastTime;
msleep(unsigned(1000*getLatency()));
Time curTime;
double TimeSinceLastPump = curTime-lastTime;
unsigned numFramesToDeliver = unsigned(TimeSinceLastPump*getNativeSampleRate());
lastTime = curTime;
AC_TRACE << "DummyPump::pump: numFramesToDeliver=" << numFramesToDeliver;
mix(_myOutputBuffer, numFramesToDeliver);
}
}
| 22.855072 | 84 | 0.701332 |
32b8be4744f527e8ea9b3c385237a08e8bfb3967 | 1,140 | hpp | C++ | qtswarmtv/seasonepisodewidget.hpp | annejan/swarmtv | 847d82114d1ee2338d37be314a222e386849aad1 | [
"Unlicense"
] | 1 | 2019-07-10T10:33:23.000Z | 2019-07-10T10:33:23.000Z | qtswarmtv/seasonepisodewidget.hpp | annejan/swarmtv | 847d82114d1ee2338d37be314a222e386849aad1 | [
"Unlicense"
] | null | null | null | qtswarmtv/seasonepisodewidget.hpp | annejan/swarmtv | 847d82114d1ee2338d37be314a222e386849aad1 | [
"Unlicense"
] | null | null | null | #ifndef SEASONEPISODEWIDGET_HPP
#define SEASONEPISODEWIDGET_HPP
#include <QDialog>
extern "C" {
#include <tvdb.h>
}
#include <QTreeWidget>
#include <taskqueue.hpp>
class episodeInfoWidget;
namespace Ui {
class seasonEpisodeWidget;
}
class seasonEpisodeWidget : public QDialog
{
Q_OBJECT
public:
explicit seasonEpisodeWidget(QWidget *parent = 0);
~seasonEpisodeWidget();
void setSeriesTitle(QString &name);
void setSeriesId(int id);
void setrieveEpisodeData();
void fillListView(tvdb_list_front_t *);
void retrieveEpisodeData();
public slots:
// GUI signals
void itemExpanded(QTreeWidgetItem *item);
void itemDoubleClicked(QTreeWidgetItem *item, int column);
// Task signals
void seriesResults(tvdb_buffer_t *series_xml);
void seriesFailed();
private:
void addTask(episodeInfoWidget *widget);
QTreeWidgetItem *addSeasonEntry(int seasonNum);
void addEpisodeEntry(QTreeWidgetItem *season, tvdb_series_info_t *s);
Ui::seasonEpisodeWidget *ui;
QString seriesName;
int seriesId;
taskQueue tc;
htvdb_t tvdb;
};
#endif // SEASONEPISODEWIDGET_HPP
| 21.923077 | 73 | 0.735088 |
32bc74330720c58268f5da7dae316ae1aefe5029 | 17,303 | cpp | C++ | lib/rbm/cpp/rbm.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 134 | 2015-01-06T14:24:18.000Z | 2022-03-13T22:38:56.000Z | lib/rbm/cpp/rbm.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 103 | 2015-01-02T14:01:29.000Z | 2021-11-12T18:45:54.000Z | lib/rbm/cpp/rbm.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 39 | 2015-07-14T20:20:13.000Z | 2021-12-01T00:49:23.000Z |
// Copyright (c) 2014 Quanta Research Cambridge, Inc.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#undef NDEBUG
#include "portalmat.h"
#include "rbm.h"
#include "mnist.h"
float sigmoid(float x)
{
if (x < -8.0)
x = -8.0;
if (x > 8.0)
x = 8.0;
return 1 / (1 + expf(-x));
}
void configureSigmoidTable()
{
sigmoiddevice->tableSize();
sem_wait(&mul_sem);
int num_entries = sigmoidindication->tableSize();
int addrsize = log((double)num_entries) / log(2.0);
float range = 16.0;
float lowest_angle = - range/2.0;
double fincr = (float)num_entries / range;
double fscale = num_entries / range;
fprintf(stderr, "configureSigmoidTable: num_entries=%d addrsize=%d fscale=%f fincr=%f\n", num_entries, addrsize, fscale, fincr);
RbmMat sigmoidTable;
// each entry consists of [-angle, sigmoid(angle), derivative, 0]
sigmoidTable.create(1, 4*num_entries, CV_32F);
// v = (index-num_entries/2) / fscale
// index = v * fscale + num_entries/2
float fxscale = fscale;
float fxllimit = (float)lowest_angle;
float fxulimit = (float)-lowest_angle;
fprintf(stderr, "configureSigmoidTable num_entries=%d rscale=%f %x llimit=%f %x rlimit=%f %x\n",
num_entries, fxscale, *(int*)&fxscale, fxllimit, *(int*)&fxllimit, fxulimit, *(int*)&fxulimit);
sigmoiddevice->setLimits(*(int*)&fxscale, *(int*)&fxllimit, *(int*)&fxulimit);
int incr = 1;
fprintf(stderr, "filling sigmoid table pointer=%x\n", sigmoidTable.reference());
for (int ai = 0; ai < num_entries; ai += incr) {
float angle = (ai - num_entries / 2) / fscale;
//int index = (int)(angle*fscale);
float s = sigmoid(angle);
//fprintf(stderr, "ai=%d angle=%f entry_angle=%f sigmoid=%f\n", ai, angle, angle * fscale + num_entries/2, s);
sigmoidTable.at<float>(0, 4*ai+0) = -angle;
sigmoidTable.at<float>(0, 4*ai+1) = s;
if (ai == num_entries-1) {
sigmoidTable.at<float>(0, 4*ai+2) = 0;
} else if (ai > 0) {
float angle_prev = (ai - 1 - num_entries/2) / fscale;
float s_prev = sigmoidTable.at<float>(0,4*(ai-1)+1);
float dangle = angle - angle_prev;
float ds = s - s_prev;
float slope = ds / dangle;
//fprintf(stderr, "angle=%f angle_prev=%f s=%f s_prev=%f ds=%f dangle=%f slope=%f\n", angle, angle_prev, s, s_prev, ds, dangle, slope);
sigmoidTable.at<float>(0, 4*ai+2) = slope;
}
sigmoidTable.at<float>(0, 4*ai+3) = 0;
}
fprintf(stderr, "updating sigmoid table pointer=%x\n", sigmoidTable.reference());
sigmoiddevice->updateTable(sigmoidTable.reference(), 0, num_entries);
sem_wait(&mul_sem);
fprintf(stderr, "sigmoid table updated\n");
}
void RbmMat::sigmoid(RbmMat &a)
{
create(a.rows, a.cols, CV_32F);
fprintf(stderr, "RbmMat::sigmoid() %d %d\n", a.rows, a.cols);
reference();
cacheFlushInvalidate();
//fprintf(stderr, "sigmoid: a.ref=%d a.rows=%d a.cols=%d\n", a.reference(), a.rows, a.cols);
//fprintf(stderr, "sigmoiddevice->sigmoid\n");
sigmoiddevice->sigmoid(a.reference(), 0, reference(), 0, a.rows*a.cols);
sem_wait(&mul_sem);
}
void RbmMat::hiddenStates(RbmMat &a, RbmMat &rand)
{
create(a.rows, a.cols, CV_32F);
fprintf(stderr, "hiddenStates: a.ref=%d a.rows=%d a.cols=%d\n", a.reference(), a.rows, a.cols);
rand.reference();
reference();
cacheFlushInvalidate();
fprintf(stderr, "rbmdevice->computeStates ptr=%d randPtr=%d\n", a.reference(), rand.reference());
rbmdevice->computeStates(a.reference(), 0, rand.reference(), 0, reference(), 0, a.rows*a.cols);
sem_wait(&mul_sem);
}
// weights += learningRate * (pos_associations - neg_associations) / num_examples;
void RbmMat::updateWeights(RbmMat &posAssociations, RbmMat &negAssociations, float learningRateOverNumExamples)
{
fprintf(stderr, "rbmdevice->updateWeights pa.ref=%d na.ref=%d\n", posAssociations.reference(), negAssociations.reference());
cacheFlushInvalidate();
rbmdevice->updateWeights(posAssociations.reference(), negAssociations.reference(), reference(), rows*cols, *(int*)&learningRateOverNumExamples);
sem_wait(&mul_sem);
}
void RbmMat::sumOfErrorSquared(RbmMat &pred)
{
if (rows != pred.rows || cols != pred.cols) {
fprintf(stderr, "Mismatched data and pred: data.rows=%d data.cols=%d pred.rows=%d pred.cols=%d\n",
rows, cols, pred.rows, pred.cols);
exit(-1);
}
fprintf(stderr, "sumOfErrorSquared called numElts=%d\n", rows*cols);
cacheFlushInvalidate();
rbmdevice->sumOfErrorSquared(reference(), pred.reference(), rows*cols);
sem_wait(&mul_sem);
}
void printDynamicRange(const char *label, cv::Mat m)
{
int min_exp = 0;
int max_exp = 0;
float min_val = 0.0;
float max_val = 0.0;
dynamicRange(m, &min_exp, &max_exp, &min_val, &max_val);
printf("dynamic range: max_exp=%d min_exp=%d max_val=%f min_val=%f %s\n", max_exp, min_exp, max_val, min_val, label);
}
float sumOfErrorSquared(cv::Mat &a, cv::Mat &b)
{
cv::Mat diff = a - b;
float error = diff.dot(diff);
return error;
}
void RBM::train(int numVisible, int numHidden, const cv::Mat &trainingData)
{
bool verify = false;
#ifdef SIMULATION
int numEpochs = 10;
#else
int numEpochs = 100;
#endif
if (verify)
numEpochs = 1;
float sum_of_errors_squareds[numEpochs];
bool verbose = false;
bool dynamicRange = true;
//int numExamples = trainingData.rows;
if (verbose) dumpMat<float>("trainingData", "%5.6f", trainingData);
if (dynamicRange) printDynamicRange("trainingData", trainingData);
cv::Mat weights;
weights.create(numVisible+1, numHidden+1, CV_32F);
for (int i = 0; i < numVisible+1; i++) {
for (int j = 0; j < numHidden+1; j++) {
float w = 0.1 * drand48();
if (w < 0 || w > 1.0)
printf("w out of range %f\n", w);
weights.at<float>(i,j) = w;
}
}
if (dynamicRange) printDynamicRange("weights", weights);
// insert bias units of 1 into first column of data
cv::Mat data;
data.create(trainingData.rows, trainingData.cols+1, CV_32F);
trainingData.copyTo(data.colRange(1, data.cols));
for (int i = 0; i < data.rows; i++)
data.at<float>(i, 0) = 1.0;
RbmMat pmData(data);
RbmMat pmDataT(pmData.t());
RbmMat pmWeights(weights);
RbmMat pmWeightsT;
RbmMat pm_pos_hidden_activations;
RbmMat pm_pos_hidden_probs;
RbmMat pm_rand_mat;
RbmMat pm_pos_hidden_states;
RbmMat pm_pos_hidden_probsT;
RbmMat pm_pos_associations;
RbmMat pm_neg_visible_activations;
RbmMat pm_neg_visible_probs;
RbmMat pm_neg_hidden_activations;
RbmMat pm_neg_hidden_probs;
RbmMat pm_neg_visible_probsT;
RbmMat pm_neg_hidden_probsT;
RbmMat pm_neg_associations;
RbmMat pm_pos_hidden_statesT;
if (verbose) dumpMat<float>("data", "%5.6f", data);
if (verbose) dumpMat<float>("weights", "%5.6f", weights);
portalTimerStart(0);
for (int epoch = 0; epoch < numEpochs; epoch++) {
timerdevice->startTimer();
cv::Mat pos_hidden_activations = data * pmWeights;
if (dynamicRange) printDynamicRange("pos_hidden_activations", pos_hidden_activations);
// fixme transpose
pmWeightsT.transpose(pmWeights);
if (verbose) dumpMat<float>("pmWeightsT", "%5.1f", pmWeightsT);
//RbmMat pm_pos_hidden_activations;
pm_pos_hidden_activations.multf(pmDataT, pmWeights);
if (verbose) dumpMat<float>("pm_pos_hidden_activations", "%5.1f", pm_pos_hidden_activations);
if (verbose) dumpMat<float>(" pos_hidden_activations", "%5.1f", pos_hidden_activations);
if (verify) assert(pm_pos_hidden_activations.compare(pos_hidden_activations, __FILE__, __LINE__));
// RbmMat pm_pos_hidden_probs;
pm_pos_hidden_probs.sigmoid(pm_pos_hidden_activations);
if (dynamicRange) printDynamicRange("pm_pos_hidden_probs", pm_pos_hidden_probs);
cv::Mat pos_hidden_probs(pm_pos_hidden_activations);
for (int i = 0; i < pm_pos_hidden_activations.rows; i++) {
for (int j = 0; j < pm_pos_hidden_activations.cols; j++) {
pos_hidden_probs.at<float>(i,j) = sigmoid(pm_pos_hidden_activations.at<float>(i,j));
}
}
if (verbose) dumpMat<float>("pm_pos_hidden_probs", "%5.1f", pm_pos_hidden_probs);
if (verbose) dumpMat<float>(" pos_hidden_probs", "%5.1f", pos_hidden_probs);
if (verify) assert(pm_pos_hidden_probs.compare(pos_hidden_probs, __FILE__, __LINE__));
// RbmMat pm_rand_mat;
pm_rand_mat.create(pm_pos_hidden_probs.rows, pm_pos_hidden_probs.cols, CV_32F);
for (int i = 0; i < pm_pos_hidden_probs.rows; i++) {
for (int j = 0; j < pm_pos_hidden_probs.cols; j++) {
pm_rand_mat.at<float>(i,j) = (float)drand48();
}
}
if (verbose) dumpMat<float>("pm_rand_mat", "%5.1f", pm_rand_mat);
if (dynamicRange) printDynamicRange("pm_rand_mat", pm_rand_mat);
cv::Mat pos_hidden_states;
pos_hidden_states.create(pm_pos_hidden_probs.rows, pm_pos_hidden_probs.cols, CV_32F);
for (int i = 0; i < pm_pos_hidden_probs.rows; i++) {
for (int j = 0; j < pm_pos_hidden_probs.cols; j++) {
float val = 0.0;
if (pm_pos_hidden_probs.at<float>(i,j) > pm_rand_mat.at<float>(i,j))
val = 1.0;
pos_hidden_states.at<float>(i,j) = val;
}
}
if (dynamicRange) printDynamicRange("pos_hidden_states", pos_hidden_states);
// RbmMat pm_pos_hidden_states;
pm_pos_hidden_states.hiddenStates(pm_pos_hidden_probs, pm_rand_mat);
if (verbose) dumpMat<float>("pm_pos_hidden_states", "%5.1f", pm_pos_hidden_states);
if (verbose) dumpMat<float>(" pos_hidden_states", "%5.1f", pos_hidden_states);
if (verify) assert(pm_pos_hidden_states.compare(pos_hidden_states, __FILE__, __LINE__));
if (verbose) dumpMat<float>("pmDataT", "%5.1f", pmDataT);
//RbmMat pmWeights(weights); // back to non-transposed
//pmWeights.copy(weights);
if (verbose) dumpMat<float>("pmWeights", "%5.1f", pmWeights);
pm_pos_hidden_probsT.transpose(pm_pos_hidden_probs);
if (verbose) dumpMat<float>("pos_hidden_probsT", "%5.1f", pm_pos_hidden_probsT);
cv::Mat pos_associations = pmDataT * pm_pos_hidden_probs;
//RbmMat pm_pos_associations;
pm_pos_associations.multf(pmData, pm_pos_hidden_probs);
if (verbose) dumpMat<float>("pos_associations", "%5.1f", pm_pos_associations);
if (dynamicRange) printDynamicRange("pm_pos_associations", pm_pos_associations);
// check results
if (verify) assert(pm_pos_associations.compare(pos_associations, __FILE__, __LINE__));
// RbmMat pm_neg_visible_activations;
pm_pos_hidden_statesT.transpose(pm_pos_hidden_states);
pm_neg_visible_activations.multf(pm_pos_hidden_statesT, pmWeightsT);
if (verbose) dumpMat<float>("neg_visible_activations", "%5.1f", pm_neg_visible_activations);
if (dynamicRange) printDynamicRange("pm_neg_visible_activations", pm_neg_visible_activations);
cv::Mat neg_visible_probs;
neg_visible_probs.create(pm_neg_visible_activations.rows, pm_neg_visible_activations.cols, CV_32F);
for (int i = 0; i < pm_neg_visible_activations.rows; i++) {
for (int j = 0; j < pm_neg_visible_activations.cols; j++) {
neg_visible_probs.at<float>(i,j) = sigmoid(pm_neg_visible_activations.at<float>(i,j));
}
}
// RbmMat pm_neg_visible_probs;
pm_neg_visible_probs.sigmoid(pm_neg_visible_activations);
pm_neg_visible_probsT.transpose(pm_neg_visible_probs);
if (verbose) dumpMat<float>("neg_visible_probs", "%5.1f", pm_neg_visible_probs);
// pm_neg_visible_probs[:0] = 1;
for (int i = 0; i < pm_neg_visible_probs.rows; i++) {
pm_neg_visible_probs.at<float>(i,0) = 1.0;
neg_visible_probs.at<float>(i,0) = 1.0;
}
if (dynamicRange) printDynamicRange("pm_neg_visible_probs", pm_neg_visible_probs);
if (verify) assert(pm_neg_visible_probs.compare(neg_visible_probs, __FILE__, __LINE__));
// RbmMat pm_neg_hidden_activations;
pm_neg_hidden_activations.multf(pm_neg_visible_probsT, pmWeights);
if (verbose) dumpMat<float>("pm_neg_hidden_activations", "%5.1f", pm_neg_hidden_activations);
if (dynamicRange) printDynamicRange("pm_neg_hidden_activations", pm_neg_hidden_activations);
cv::Mat neg_hidden_activations = pm_neg_visible_probs * pmWeights;
if (verbose) dumpMat<float>(" neg_hidden_activations", "%5.1f", neg_hidden_activations);
if (verify) assert(pm_neg_hidden_activations.compare(neg_hidden_activations, __FILE__, __LINE__, 0.05));
// RbmMat pm_neg_hidden_probs;
pm_neg_hidden_probs.sigmoid(pm_neg_hidden_activations);
if (verbose) dumpMat<float>("pm_neg_hidden_probs", "%5.1f", pm_neg_hidden_probs);
if (dynamicRange) printDynamicRange("pm_neg_hidden_probs", pm_neg_hidden_probs);
pm_neg_visible_probsT.transpose(pm_neg_visible_probs);
if (verbose) dumpMat<float>("pm_neg_visible_probsT", "%5.1f", pm_neg_visible_probsT);
if (dynamicRange) printDynamicRange("pm_neg_visible_probs", pm_neg_visible_probs);
pm_neg_hidden_probsT.transpose(pm_neg_hidden_probs);
//RbmMat pm_neg_associations;
pm_neg_associations.multf(pm_neg_visible_probs, pm_neg_hidden_probs);
if (verbose) dumpMat<float>("pm_neg_associations", "%5.1f", pm_neg_associations);
cv::Mat neg_associations = pm_neg_visible_probsT * pm_neg_hidden_probs;
if (verbose) dumpMat<float>(" neg_associations", "%5.1f", neg_associations);
if (dynamicRange) printDynamicRange("pm_neg_associations", pm_neg_associations);
if (verbose) dumpMat<float>("pmWeights.before", "%5.1f", pmWeights);
// weights += learningRate * (pos_associations - neg_associations) / num_examples;
float learningRate = 1.0;
float num_examples = data.rows;
pmWeights.updateWeights(pm_pos_associations, pm_neg_associations, learningRate / num_examples);
if (verbose) dumpMat<float>("pmWeights.after ", "%5.1f", pmWeights);
if (dynamicRange) printDynamicRange("weights", weights);
fprintf(stderr, "========== %s:%d\n", __FILE__, __LINE__);
// error = np.sum((data - neg_visible_probs) ** 2)
pmData.sumOfErrorSquared(pm_neg_visible_probs);
float error = sumOfErrorSquared(data, pm_neg_visible_probs);
fprintf(stderr, "========== %s:%d\n", __FILE__, __LINE__);
fprintf(stderr, "completed epoch %d sumOfErrorSquared=%f\n", epoch, error);
sum_of_errors_squareds[epoch] = rbmDeviceIndication->sum_of_errors_squared;
timerdevice->stopTimer();
}
//uint64_t total_cycles = portalTimerLap(0);
//uint64_t beats = hostMemServerIndication->getMemoryTraffic(ChannelType_Read);
//fprintf(stderr, "total_cycles=%ld beats=%ld utilization=%f\n", (long)total_cycles, (long)beats, (float)beats / (float)total_cycles);
for(int i = 0; i < numEpochs; i++)
fprintf(stderr, "(%d) %f\n", i, sum_of_errors_squareds[i]);
}
void RBM::run()
{
cv::Mat trainingData = (cv::Mat_<float>(6,6) <<
1,1,1,0,0,0,
1,0,1,0,0,0,
1,1,1,0,0,0,
0,0,1,1,1,0,
0,0,1,1,0,0,
0,0,1,1,1,0);
char name_buff[256];
snprintf(name_buff, 256, "../train-images-idx3-ubyte");
fprintf(stderr, "reading image data from %s\n", name_buff);
MnistImageFile imagefile(name_buff);
imagefile.open();
int numImages = imagefile.numEntries();
int numPixels = imagefile.rows()*imagefile.cols();
numImages = 200;
int cols = 783; // one more column is added below to make the total 784.
#ifdef SIMULATION
numImages = 32;
cols = 31; // one more column is added to make the total 32
#endif
if (!cols || numPixels < cols)
cols = numPixels;
fprintf(stderr, "numImages=%d numPixels=%d imagefile.rows=%d imagefile.cols=%d\n", numImages, numPixels, imagefile.rows(), imagefile.cols());
//numVisible = imagefile.rows()*imagefile.cols();
int numVisible = cols;
int numHidden = numVisible / 2;
trainingData.create(numImages, cols, CV_32F);
for (int i = 0; i < numImages; i++) {
//fprintf(stderr, "Reading mat %d\n", i);
cv::Mat m = imagefile.mat(i);
//dumpMat<unsigned char>("foo", "%02x", m);
for (int j = 0; j < imagefile.rows(); j++) {
for (int k = 0; k < imagefile.cols(); k++) {
int offset = j*imagefile.cols() + k;
if (offset < cols) {
float f = (float)m.at<unsigned char>(k,j);
trainingData.at<float>(i, offset) = f;
}
}
}
}
fprintf(stderr, "RBM::run() invoking train\n");
train(numVisible, numHidden, trainingData);
fprintf(stderr, "trainingData.rows=%d trainingData.cols=%d\n", trainingData.rows, trainingData.cols);
}
| 40.905437 | 148 | 0.701035 |
32c1d7608b90688b8218d44771897257de20408b | 950 | cpp | C++ | module-os/test/performance-monitor.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-os/test/performance-monitor.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-os/test/performance-monitor.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | #include <limits>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "prof.h"
TEST_CASE("prof api test")
{
struct prof_pool_init_data init{0};
prof_pool_init(init);
auto pp = prof_pool_get_data();
REQUIRE(pp.size == 0);
prof_pool_deinit();
}
TEST_CASE("overflow")
{
struct prof_pool_init_data init
{
0
};
prof_pool_init(init);
prof_pool_data_set(0,-1);
REQUIRE(prof_pool_overflow() == 1);
prof_pool_deinit();
}
TEST_CASE("prof api sum")
{
struct prof_pool_init_data init{1};
prof_pool_init(init);
auto pp = prof_pool_get_data();
REQUIRE(pp.size == 1);
const auto switches = 10;
const auto ts = 10;
for (auto i =0; i < switches ; ++i)
{
prof_pool_data_set(0,ts);
}
task_prof_data mem[1];
prof_pool_flush(mem, 1);
REQUIRE(mem->switches == switches);
REQUIRE(mem->exec_time == switches*ts);
prof_pool_deinit();
}
| 19 | 43 | 0.634737 |
32c1f936fb1be70749f4d54d62e912302a2b70d8 | 4,383 | cpp | C++ | libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | 1 | 2021-02-24T13:01:00.000Z | 2021-02-24T13:01:00.000Z | libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp | orynider/php-5.6.3x4VC9 | 47f9765b797279061c364e004153a0919895b23e | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) 2007 Eric Scott Albright
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <UnitTest++.h>
#include <enchant.h>
#include "EnchantDictionaryTestFixture.h"
struct EnchantDictionaryIsAdded_TestFixture : EnchantDictionaryTestFixture
{};
/**
* enchant_dict_is_added
* @dict: A non-null #EnchantDict
* @word: The word you wish to see if it's in your session
* @len: the byte length of @word, or -1 for strlen (@word)
*/
/////////////////////////////////////////////////////////////////////////////
// Test Normal Operation
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_AddedToSession_1)
{
enchant_dict_add_to_session(_dict, "hello", -1);
CHECK_EQUAL(1, enchant_dict_is_added(_dict, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_Added_1)
{
enchant_dict_add(_dict, "hello", -1);
CHECK_EQUAL(1, enchant_dict_is_added(_dict, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_NotAdded_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_OnBrokerPwl_AddedToSession_1)
{
enchant_dict_add_to_session(_pwl, "hello", -1);
CHECK_EQUAL(1, enchant_dict_is_added(_pwl, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_OnBrokerPwl_Added_1)
{
enchant_dict_add(_pwl, "hello", -1);
CHECK_EQUAL(1, enchant_dict_is_added(_pwl, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_OnBrokerPwl_NotAdded_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_pwl, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_HasPreviousError_ErrorCleared)
{
SetErrorOnMockDictionary("something bad happened");
enchant_dict_is_added(_dict, "hello", -1);
CHECK_EQUAL((void*)NULL, (void*)enchant_dict_get_error(_dict));
}
/////////////////////////////////////////////////////////////////////////////
// Test Error Conditions
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_NullDictionary_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(NULL, "hello", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_NullWord_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_dict, NULL, -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_EmptyWord_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_dict, "", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_WordSize0_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", 0));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_InvalidUtf8Word_0)
{
CHECK_EQUAL(0, enchant_dict_is_added(_dict, "\xa5\xf1\x08", -1));
}
TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture,
EnchantDictionaryIsAdded_WordExistsInPwlAndExclude_0)
{
ExternalAddWordToDictionary("hello");
ExternalAddWordToExclude("hello");
ReloadTestDictionary();
CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", -1));
}
| 32.954887 | 80 | 0.726443 |
32c3bdd57aafc5644d1a68828373218e4568c994 | 1,826 | cpp | C++ | binary-trees/Juez215/Source.cpp | albertopastormr/data-structures-eda | 2846e4ba62b5db13788f0c4e6160dc7514070063 | [
"MIT"
] | null | null | null | binary-trees/Juez215/Source.cpp | albertopastormr/data-structures-eda | 2846e4ba62b5db13788f0c4e6160dc7514070063 | [
"MIT"
] | null | null | null | binary-trees/Juez215/Source.cpp | albertopastormr/data-structures-eda | 2846e4ba62b5db13788f0c4e6160dc7514070063 | [
"MIT"
] | null | null | null | // Alberto Pastor Moreno
// E46
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <vector>
#include "bintree_eda.h"
struct tSol{
int numNavegables = 0, caudal = 0;
tSol(int nn, int c) : numNavegables(nn), caudal(c){}
};
// función que resuelve el problema
template <class T>
tSol aguaslimpias(bintree<T> const & tree) {
if (tree.left().empty() && tree.right().empty())
return{ 0, (tree.root() > 0 ? 0 : 1)};
else if (tree.left().empty()){
tSol dr = aguaslimpias(tree.right());
return{ dr.numNavegables + (dr.caudal >= 3 ? 1 : 0), std::max(dr.caudal - tree.root(), 0)};
}
else if (tree.right().empty()){
tSol iz = aguaslimpias(tree.left());
return{ iz.numNavegables + (iz.caudal >= 3 ? 1 : 0), std::max(iz.caudal - tree.root(), 0)};
}
else{
tSol iz = aguaslimpias(tree.left());
tSol dr = aguaslimpias(tree.right());
return{ iz.numNavegables + dr.numNavegables + (iz.caudal >= 3 ? 1 : 0) + (dr.caudal >= 3 ? 1 : 0), std::max(iz.caudal + dr.caudal - tree.root(),0) };
}
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
void resuelveCaso() {
// leer los datos de la entrada
auto tree = leerArbol(-1);
tSol sol = aguaslimpias(tree);
// escribir sol
std::cout << sol.numNavegables << "\n";
}
int main() {
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
int numCasos;
std::cin >> numCasos;
for (int i = 0; i < numCasos; ++i)
resuelveCaso();
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | 26.085714 | 151 | 0.653341 |
32c3cfe9fde5934fbf1e7fe0fb4d14f8c78085aa | 595 | hpp | C++ | paper/config.hpp | williamstarkro/paper | 13266b83b3922fc146cba1eecedac5a9addf6f2a | [
"BSD-2-Clause"
] | null | null | null | paper/config.hpp | williamstarkro/paper | 13266b83b3922fc146cba1eecedac5a9addf6f2a | [
"BSD-2-Clause"
] | null | null | null | paper/config.hpp | williamstarkro/paper | 13266b83b3922fc146cba1eecedac5a9addf6f2a | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <chrono>
#include <cstddef>
namespace paper
{
// Network variants with different genesis blocks and network parameters
enum class paper_networks
{
// Low work parameters, publicly known genesis key, test IP ports
paper_test_network,
// Normal work parameters, secret beta genesis key, beta IP ports
paper_beta_network,
// Normal work parameters, secret live key, live IP ports
paper_live_network
};
paper::paper_networks const paper_network = paper_networks::ACTIVE_NETWORK;
std::chrono::milliseconds const transaction_timeout = std::chrono::milliseconds (1000);
}
| 28.333333 | 87 | 0.789916 |
32c420a5625bb5fe7b614a2677917e7e88ea0cb8 | 1,504 | cpp | C++ | src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp | phs008/PrismSolution | ea2452ef98bdd18216f3947dd0cb5483e2e2a079 | [
"MIT"
] | null | null | null | src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp | phs008/PrismSolution | ea2452ef98bdd18216f3947dd0cb5483e2e2a079 | [
"MIT"
] | null | null | null | src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp | phs008/PrismSolution | ea2452ef98bdd18216f3947dd0cb5483e2e2a079 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "MRigidMeshComponent.h"
#include <Resource/ResourcePath.h>
namespace MVRWrapper
{
MRigidMeshComponent::MRigidMeshComponent()
:MContainerComponent(ComponentEnum::RigidMesh)
{
_pRigidMesh = this->GetNative();
this->setMesh();
}
MRigidMeshComponent::MRigidMeshComponent(Code3::Component::ContainerComponent* _containerComponent)
:MContainerComponent(_containerComponent)
{
_pRigidMesh = this->GetNative();
this->setMesh();
}
Code3::Scene::RigidMesh* MRigidMeshComponent::GetNative()
{
return MContainerComponent::GetNative<Code3::Scene::RigidMesh>();
}
void MRigidMeshComponent::setMaterial(System::String^ matFile)
{
InternString path = MarshalHelper::StringToNativeString(matFile);
Code3::FileIO::Path p;
p.SetAbsolutePath(path);
if (p.MakeRelativePath(&Code3::Resource::GetResourcePath().ResourceFolder))
{
_pRigidMesh->PropRigidMesh.Material.Value = p;
_pRigidMesh->PropRigidMesh.Apply();
//_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile(p);
/*_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile(
_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SourceFile);*/
}
//_pRigidMesh->PropRigidMesh.Apply();
}
void MRigidMeshComponent::setMesh()
{
_pRigidMesh->PropRigidMesh.Mesh.Value.SetRelativePath(Code3::BasicType::InternString("program"), "<sphere>1.0x30x30");
_pRigidMesh->PropRigidMesh.Apply();
}
}
| 32.695652 | 120 | 0.767952 |
32c7df49f8ca191fd2d83eca4e261c3ee1c9a7ae | 1,169 | cpp | C++ | tests/test_geometry.cpp | keisukefukuda/tapas | 341fad9ecd97607771db4c4c966b76d30b5bfc89 | [
"MIT"
] | null | null | null | tests/test_geometry.cpp | keisukefukuda/tapas | 341fad9ecd97607771db4c4c966b76d30b5bfc89 | [
"MIT"
] | 13 | 2015-04-22T10:32:01.000Z | 2016-01-21T10:24:32.000Z | tests/test_geometry.cpp | keisukefukuda/tapas | 341fad9ecd97607771db4c4c966b76d30b5bfc89 | [
"MIT"
] | null | null | null |
#include <cmath>
#include <utility>
#include <set>
#ifndef TAPAS_DEBUG
#define TAPAS_DEBUG 1 // always use TAPAS_DEBUG
#endif
#include <tapas/common.h>
#include <tapas/test.h>
#include <tapas/geometry.h>
SETUP_TEST;
using V1 = tapas::Vec<1, double>;
using V2 = tapas::Vec<2, double>;
using Reg1 = tapas::Region<1, double>;
using Reg2 = tapas::Region<2, double>;
void Test_Join() {
{
const int Dim = 1;
using FP = double;
using Region = tapas::Region<Dim, FP>;
auto A = Region::BB(Region({1}, {2}), Region({-1}, {3}));
ASSERT_EQ(A.min(0), -1);
ASSERT_EQ(A.max(0), 3);
auto B = Region::BB(Region({1}, {2}), Region({3}, {4}));
ASSERT_EQ(B.min(0), 1);
ASSERT_EQ(B.max(0), 4);
}
{
const int Dim = 2;
using FP = double;
using Region = tapas::Region<Dim, FP>;
auto C = Region::BB(Region({1,1}, {2,2}), Region({-1,-1}, {3,3}));
ASSERT_EQ(C.max(0), 3);
ASSERT_EQ(C.max(1), 3);
ASSERT_EQ(C.min(0), -1);
ASSERT_EQ(C.min(1), -1);
}
}
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
Test_Join();
TEST_REPORT_RESULT();
MPI_Finalize();
return (TEST_SUCCESS() ? 0 : 1);
}
| 19.483333 | 70 | 0.586826 |
32c86367a53b92150af27fdf04240e3549386702 | 13,281 | cc | C++ | dfplayer/kinect.cc | gleenn/dfplayer | dd390a6f54b3bd8b2a3397fddd6caacfba01b29d | [
"MIT"
] | null | null | null | dfplayer/kinect.cc | gleenn/dfplayer | dd390a6f54b3bd8b2a3397fddd6caacfba01b29d | [
"MIT"
] | null | null | null | dfplayer/kinect.cc | gleenn/dfplayer | dd390a6f54b3bd8b2a3397fddd6caacfba01b29d | [
"MIT"
] | null | null | null | // Copyright 2015, Igor Chernyshev.
// Licensed under The MIT License
//
#include "kinect.h"
#include <math.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include "util/lock.h"
#include "util/time.h"
#include "utils.h"
#include "../external/kkonnect/include/kk_connection.h"
#include "../external/kkonnect/include/kk_device.h"
using kkonnect::Connection;
using kkonnect::Device;
using kkonnect::DeviceOpenRequest;
using kkonnect::ErrorCode;
using kkonnect::ImageInfo;
// TODO(igorc): Add atexit() to stop this, tcl and visualizer threads,
// and to unblock all waiting Python threads.
// TODO(igorc): Fix crashes on USB disconnect.
class KinectRangeImpl : public KinectRange {
public:
KinectRangeImpl();
~KinectRangeImpl() override;
void EnableVideo() override;
void EnableDepth() override;
void Start(int fps) override;
int GetWidth() const override;
int GetHeight() const override;
int GetDepthDataLength() const override;
void GetDepthData(uint8_t* dst) const override;
void GetVideoData(uint8_t* dst) const override;
Bytes* GetAndClearLastDepthColorImage() override;
Bytes* GetAndClearLastVideoImage() override;
double GetPersonCoordX() const override;
private:
static KinectRangeImpl* GetInstanceImpl();
void ConnectDevices();
static void* RunMergerLoop(void* arg);
void RunMergerLoop();
void MergeImages();
void ContrastDepthLocked();
void ClampDepthDataLocked();
void FindContoursLocked();
int fps_;
bool video_enabled_ = false;
bool depth_enabled_ = false;
Connection* connection_ = nullptr;
pthread_t merger_thread_;
volatile bool should_exit_ = false;
mutable pthread_mutex_t devices_mutex_ = PTHREAD_MUTEX_INITIALIZER;
mutable pthread_mutex_t merger_mutex_ = PTHREAD_MUTEX_INITIALIZER;
std::vector<Device*> devices_;
int width_ = 0;
int height_ = 0;
bool has_started_thread_ = false;
cv::Mat video_data_;
cv::Mat depth_data_orig_;
cv::Mat depth_data_blur_;
cv::Mat depth_data_range_;
cv::Mat depth_data_range_copy_;
cv::Mat depth_data_range_marked_;
cv::Mat erode_element_;
cv::Mat dilate_element_;
cv::vector<cv::Vec3i> circles_;
bool has_new_depth_image_ = false;
bool has_new_video_image_ = false;
};
KinectRange* KinectRange::instance_ = new KinectRangeImpl();
// static
KinectRange* KinectRange::GetInstance() {
return instance_;
}
// static
KinectRangeImpl* KinectRangeImpl::GetInstanceImpl() {
return reinterpret_cast<KinectRangeImpl*>(GetInstance());
}
KinectRangeImpl::KinectRangeImpl() : fps_(15) {
erode_element_ = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));
dilate_element_ = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(8, 8));
}
KinectRangeImpl::~KinectRangeImpl() {
should_exit_ = true;
pthread_join(merger_thread_, NULL);
if (connection_)
connection_->Close();
}
void KinectRangeImpl::EnableVideo() {
CHECK(!has_started_thread_);
video_enabled_ = true;
}
void KinectRangeImpl::EnableDepth() {
CHECK(!has_started_thread_);
depth_enabled_ = true;
}
void KinectRangeImpl::Start(int fps) {
Autolock l1(merger_mutex_);
Autolock l2(devices_mutex_);
if (has_started_thread_)
return;
has_started_thread_ = true;
fps_ = fps;
ConnectDevices();
CHECK(!pthread_create(&merger_thread_, NULL, RunMergerLoop, this));
}
void KinectRangeImpl::ConnectDevices() {
connection_ = Connection::OpenLocal();
int device_count = connection_->GetDeviceCount();
fprintf(stderr, "Found %d Kinect devices\n", device_count);
Device* device = nullptr;
DeviceOpenRequest request(0);
if (video_enabled_)
request.depth_format = kkonnect::kImageFormatVideoRgb;
if (depth_enabled_)
request.depth_format = kkonnect::kImageFormatDepthMm;
ErrorCode err = connection_->OpenDevice(request, &device);
if (err != kkonnect::kErrorSuccess) {
fprintf(stderr, "Failed to open Kinect device, error=%d\n", err);
return;
}
uint64_t start_time = GetCurrentMillis();
while (device->GetStatus() == kkonnect::kErrorInProgress) {
uint64_t elapsed_ms = GetCurrentMillis() - start_time;
if (elapsed_ms > 15 * 1000) {
fprintf(stderr, "Timed out waiting for a Kinect connection\n");
connection_->CloseDevice(device);
return;
}
Sleep(0.1);
}
err = device->GetStatus();
if (err != kkonnect::kErrorSuccess) {
fprintf(stderr, "Failed to connect to Kinect device, error=%d\n", err);
return;
}
ImageInfo video_info = device->GetVideoImageInfo();
ImageInfo depth_info = device->GetDepthImageInfo();
if (!video_info.enabled && !depth_info.enabled) {
fprintf(stderr, "Both video and depth streams are closed\n");
} else if (video_info.enabled && depth_info.enabled) {
CHECK(video_info.width == depth_info.width);
CHECK(video_info.height == depth_info.height);
}
if (video_info.enabled) {
width_ = video_info.width;
height_ = video_info.height;
} else if (depth_info.enabled) {
width_ = depth_info.width;
height_ = depth_info.height;
}
CHECK(width_ > 0);
CHECK(height_ > 0);
devices_.push_back(device);
// TODO(igorc): Get width and height.
video_data_.create(height_, width_ * device_count, CV_8UC3);
video_data_.setTo(cv::Scalar(0, 0, 0));
depth_data_orig_.create(height_, width_ * device_count, CV_16UC1);
depth_data_blur_.create(height_, width_ * device_count, CV_16UC1);
depth_data_orig_.setTo(cv::Scalar(0));
depth_data_blur_.setTo(cv::Scalar(0));
}
// static
void* KinectRangeImpl::RunMergerLoop(void* arg) {
reinterpret_cast<KinectRangeImpl*>(arg)->RunMergerLoop();
return NULL;
}
void KinectRangeImpl::RunMergerLoop() {
uint32_t ms_per_frame = (uint32_t) (1000.0 / (double) fps_);
uint64_t next_render_time = GetCurrentMillis() + ms_per_frame;
while (!should_exit_) {
uint32_t remaining_time = 0;
uint64_t now = GetCurrentMillis();
if (next_render_time > now)
remaining_time = next_render_time - now;
if (remaining_time > 0)
Sleep(((double) remaining_time) / 1000.0);
next_render_time += ms_per_frame;
MergeImages();
}
}
void KinectRangeImpl::MergeImages() {
Autolock l1(merger_mutex_);
bool has_depth_update = false;
bool has_video_update = false;
{
// Merge images from all devices into one.
Autolock l2(devices_mutex_);
for (size_t i = 0; i < devices_.size(); ++i) {
Device* device = devices_[i];
int full_witdh = width_ * devices_.size();
has_depth_update |= device->GetAndClearDepthData(
reinterpret_cast<uint16_t*>(depth_data_orig_.data),
full_witdh * 2);
has_video_update |= device->GetAndClearVideoData(
video_data_.data, full_witdh * 3);
// TODO(igorc): Erase device's part of the image after
// a few missing updates.
}
}
circles_.clear();
if (has_depth_update) {
ContrastDepthLocked();
FindContoursLocked();
has_new_depth_image_ = true;
}
if (has_video_update)
has_new_video_image_ = true;
}
void KinectRangeImpl::ContrastDepthLocked() {
ClampDepthDataLocked();
// Blur the depth image to reduce noise.
// TODO(igorc): Try to reduce CPU usage here (using 10% now?).
const int kKernelSize = 7;
cv::blur(
depth_data_orig_, depth_data_blur_,
cv::Size(kKernelSize, kKernelSize), cv::Point(-1,-1));
// Select trigger pixels.
// The depth range is approximately 3 meters. The height of the car
// is approximately the same. We want to detect objects in the range
// from 1 to 1.5 meters away from the Kinect.
const uint16_t min_threshold = 1500;
const uint16_t max_threshold = 2500;
cv::inRange(depth_data_blur_,
cv::Scalar(min_threshold),
cv::Scalar(max_threshold),
depth_data_range_);
// Further blur range image, using in-place erode-dilate.
cv::erode(depth_data_range_, depth_data_range_, erode_element_);
cv::erode(depth_data_range_, depth_data_range_, erode_element_);
cv::dilate(depth_data_range_, depth_data_range_, dilate_element_);
cv::dilate(depth_data_range_, depth_data_range_, dilate_element_);
}
struct {
bool operator() (cv::Vec3i c1, cv::Vec3i c2) { return (c1[2] > c2[2]); }
} CircleComparator;
void KinectRangeImpl::FindContoursLocked() {
// Find contours of objects in the range image.
// Use depth_data_range_copy_ as the image will be modified.
cv::vector<cv::vector<cv::Point> > all_contours;
cv::vector<cv::Vec4i> hierarchy;
depth_data_range_.copyTo(depth_data_range_copy_);
depth_data_range_.copyTo(depth_data_range_marked_);
cv::findContours(depth_data_range_copy_, all_contours, hierarchy,
CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
int object_count = hierarchy.size();
if (!object_count) {
// fprintf(stderr, "No objects found\n");
return;
}
if (object_count > 100) {
fprintf(stderr, "Too many objects found: %d\n", object_count);
return;
}
// fprintf(stderr, "Found %d objects\n", object_count);
// Assuming that any human will take at least 10% of the image size.
constexpr double kMinObjectRatio = 0.10;
// A human as seen from above should be less than 33% of the image size.
constexpr double kMaxObjectRatio = 0.33;
bool is_first = true;
for (int index = 0; index >= 0; index = hierarchy[index][0]) {
int parent_index = hierarchy[index][3];
if (parent_index != -1) continue; // Top-level contours only.
const cv::vector<cv::Point>& contours = all_contours[index];
cv::Moments moment = cv::moments(contours);
double area = moment.m00;
double radius = sqrt(area / M_PI);
double radius_ratio = radius / 500.0;
if (radius_ratio < kMinObjectRatio) continue;
if (radius_ratio > kMaxObjectRatio) continue;
int x = static_cast<int>(moment.m10 / area);
int y = static_cast<int>(moment.m01 / area);
if (false) {
// cv::Rect rect = cv::boundingRect(contours);
fprintf(stderr, "%sFound object idx=%d contours=%d radius=%d x=%d y=%d\n",
(is_first ? "-> " : " "), index, (int) contours.size(),
static_cast<int>(radius), x, y);
}
is_first = false;
circles_.push_back(cv::Vec3i(x, y, radius));
}
std::sort(circles_.begin(), circles_.end(), CircleComparator);
}
void KinectRangeImpl::ClampDepthDataLocked() {
CHECK(depth_data_orig_.elemSize() == 2);
uint16_t* data = reinterpret_cast<uint16_t*>(depth_data_orig_.data);
for (uint32_t i = 0; i < video_data_.total(); ++i) {
// Clamp to practical limits of 0.5-3m.
uint16_t distance = data[i];
if (distance < 500) {
data[i] = 500;
} else if (distance > 3000) {
data[i]= 3000;
}
}
}
int KinectRangeImpl::GetWidth() const {
return width_ * devices_.size();
}
int KinectRangeImpl::GetHeight() const {
return height_;
}
int KinectRangeImpl::GetDepthDataLength() const {
return depth_data_orig_.total() * depth_data_orig_.elemSize();
}
void KinectRangeImpl::GetDepthData(uint8_t* dst) const {
Autolock l(merger_mutex_);
memcpy(dst, depth_data_blur_.data, GetDepthDataLength());
}
void KinectRangeImpl::GetVideoData(uint8_t* dst) const {
Autolock l(merger_mutex_);
memcpy(dst, video_data_.data,
video_data_.total() * video_data_.elemSize());
}
Bytes* KinectRangeImpl::GetAndClearLastDepthColorImage() {
Autolock l(merger_mutex_);
if (!has_new_depth_image_)
return NULL;
// Expand range to 0..255.
double min = 0;
double max = 0;
cv::minMaxIdx(depth_data_blur_, &min, &max);
cv::Mat adjMap;
double scale = 255.0 / (max - min);
depth_data_blur_.convertTo(adjMap, CV_8UC1, scale, -min * scale);
// depth_data_range_.copyTo(adjMap);
// Color-code the depth map.
cv::Mat coloredMap;
cv::applyColorMap(adjMap, coloredMap, cv::COLORMAP_JET);
// Convert to RGB.
cv::Mat coloredMapRgb;
cv::cvtColor(coloredMap, coloredMapRgb, CV_BGR2RGB);
for (size_t i = 0; i < circles_.size(); ++i) {
const cv::Vec3i& c = circles_[i];
cv::Scalar color = (i == 0 ? cv::Scalar(255, 0, 0) : cv::Scalar(0, 255, 0));
cv::circle(coloredMapRgb, cv::Point(c[0], c[1]), c[2], color, 3);
}
Bytes* result = new Bytes(
coloredMapRgb.data,
coloredMapRgb.total() * coloredMapRgb.elemSize());
has_new_depth_image_ = false;
return result;
}
double KinectRangeImpl::GetPersonCoordX() const {
Autolock l(merger_mutex_);
if (circles_.empty()) return -1;
return static_cast<double>(circles_[0][0]) / width_;
}
Bytes* KinectRangeImpl::GetAndClearLastVideoImage() {
Autolock l(merger_mutex_);
if (!has_new_video_image_)
return NULL;
// Unpack 3-byte RGB into RGBA.
int width = GetWidth();
int height = GetHeight();
const uint8_t* src = reinterpret_cast<const uint8_t*>(video_data_.data);
int dst_size = width * height * 4;
uint8_t* dst = new uint8_t[dst_size];
for (int y = 0; y < height; ++y) {
uint8_t* dst_row = dst + y * width * 4;
const uint8_t* src_row = src + y * width * 3;
for (int x = 0; x < width; ++x) {
memcpy(dst_row + x * 4, src_row + x * 3, 3);
dst_row[3] = 0;
}
}
Bytes* result = new Bytes();
result->MoveOwnership(dst, dst_size);
has_new_video_image_ = false;
return result;
}
| 29.317881 | 80 | 0.701152 |
32ca60aa7761e1341b0036ffae7c4dcf4c6f845d | 1,224 | cpp | C++ | Engine/Source/Runtime/Renderer/Components/Buffers.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | Engine/Source/Runtime/Renderer/Components/Buffers.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | Engine/Source/Runtime/Renderer/Components/Buffers.cpp | 1992please/NullEngine | 8f5f124e9718b8d6627992bb309cf0f0d106d07a | [
"Apache-2.0"
] | null | null | null | #include "NullPCH.h"
#include "Buffers.h"
#include "Platform/OpenGL/OpenGLBuffers.h"
#include "Renderer/Components/RendererAPI.h"
IVertexBuffer* IVertexBuffer::Create(float* InVertices, uint32 InSize)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InVertices, InSize);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
}
IVertexBuffer* IVertexBuffer::Create(uint32 InSize)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InSize);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
}
IIndexBuffer* IIndexBuffer::Create(uint32* InIndices, uint32 InCount)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLIndexBuffer(InIndices, InCount);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
} | 33.081081 | 111 | 0.764706 |
32cdd85e9f1daf620c9ae3cbc82d5360ba12c7b8 | 38,310 | cpp | C++ | main.cpp | stefanosaga/Data-Structures | 4833b90538c3e130e249324765dfa54e9ef1afdc | [
"MIT"
] | null | null | null | main.cpp | stefanosaga/Data-Structures | 4833b90538c3e130e249324765dfa54e9ef1afdc | [
"MIT"
] | null | null | null | main.cpp | stefanosaga/Data-Structures | 4833b90538c3e130e249324765dfa54e9ef1afdc | [
"MIT"
] | null | null | null | #include <iostream>
#include "bubblesort.h"
#include "quicksort.h"
#include "mergesort.h"
#include "general.h"
#include "binary.h"
#include "binIntSearch.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str;
clock_t start, end; // metavlites xronou
double diarkeia; // metavliti diarkeias
int epan=0; // epanaliyi peiramatos
int menu, taxin, anaz, pinakas, arxeio; // int epilogis menu-taxinomisis-anazitisis-xeiristis/mesis-arxeiou
int num, numFile,lines, key, numSearch ,k=0; // voithitikes metavlites gia arxeia
int vimata =0, sigrisi; // vimata anazitisewn,sigrisewn
int * Darray; // dynamic allocation gia times pros taxinomisi
int * Dtemp; // voithitikos gia epanafora timwn
int * Dbinary; // pinakas binary search
int * arrayMerge; // voithitikos gia mergesort
// eisagwgi pros epexergasia twn dosmenwn arxeiwn
ifstream myfile1 ("/home/stefanosaga/Desktop/Link to domes/1/f1.txt");
ifstream myfile2 ("/home/stefanosaga/Desktop/Link to domes/1/f2.txt");
ifstream myfile3 ("/home/stefanosaga/Desktop/Link to domes/1/f3.txt");
ifstream myfile4 ("/home/stefanosaga/Desktop/Link to domes/1/f4.txt");
ifstream myfile5 ("/home/stefanosaga/Desktop/Link to domes/1/f5.txt");
// antikeimena klasewn algorithmwn kai genikwn pliroforiwn
general gen;
quicksort quick;
mergesort merge;
bubblesort bubble;
binary bin;
binIntSearch bis;
cout<<endl;
cout<<"********************************************************************"<<endl;
cout<<"* TAXINOMISI / ANAZITISI *"<<endl;
cout<<"********************************************************************"<<endl<<endl;
do{
cout<<"\n\t------- MENU TAXINOMISIS / ANAZITISIS --------"<<endl;
/* menu vasikwn epilogwn */
gen.printMenu();
cin >> str;
istringstream buffer(str);
buffer >> menu;
//cin>>menu;
// switch gia vasiko menu
switch (menu){
// epilogi 1, ilopihsh algorithmou taxinomisis
case 1:
//mesi h xeiroteri periptwsi???
gen.printMenuPeript();
cin>>pinakas; // epilogi pinaka
// switch periptwsi pinakwn
switch (pinakas){
// epilogi pinaka 1 gia xeiroteri periptwsi, me dosmeno sinolo stoixeiwn apo xristi
case 1:
cout<<"\n\tPosa stoixeia theleis ston pinaka?"<<endl;
cin>>num;
// dimiurgia pinakwn analoga me to dosmeno num tu xristi
Darray= new int [num];
Dtemp= new int [num];
// ekxwrisi stoixeiwn stus pinakes gia xeiristi periptwsi
// XEIRISTI PERIPTWSI = PINAKAS MEGALITERO -> MIKROTERO
for (int j = num-1 ; j > 0; j--){
Darray[k] = j;
Dtemp[k] = Darray[k];
k++;
}
cout<<"\nAlgorithmoi Taxinomisis se pinakes xeiroteris periptwsis! "<<endl;
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
// QUICKSORT !
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k, sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"\n1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis Quicksort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-1]<<"\n(N)sto stoixeio :"<<Darray[k]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
cout<<"\n---------------"<<endl;
break; //break menu gia taxinomisi
break; // break case 1 pinaka
case 2: // ilopihsh taxinomisewn se mesis periptwsis ( dosmena arxeia f1, f2...)
gen.printMenuArxeiou();
cin>>arxeio; // epilogi vasikou menou gia alg taxinom
switch (arxeio){
// epilogi 1, arxeio f1
case 1:
Darray= new int [999]; // orismos megethus analoga to arxeio
Dtemp= new int [999];
k=0; // metrima lines arxeiou
// elenxos gia swsto open arxeiou
if (myfile1.is_open())
{
// diavasma int ana grammi apo to arxeio, kai ekxwrisi tu ston Darray
while ( myfile1 >> numFile)
{
//cout << numFile <<" ";
Darray[k]=numFile;
Dtemp[k]=numFile;
k++;
}
cout<<endl;
cout<<endl<<"LINES :"<<k<<"\n1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
myfile1.close();
}
else cout << "Unable to open f1.txt"<<endl;
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
// case gia quicksort
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis QuickSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k-1];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
break; // break case f1.txt
// epilogi 2, arxeio f2
case 2:
k=0;
Darray= new int [4999];
Dtemp= new int [4999];
if (myfile2.is_open())
{
while ( myfile2 >> numFile)
{
Darray[k]=numFile;
Dtemp[k]=numFile;
k++;
}
cout<<endl<<"LINES :"<<k<<"\n1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
myfile2.close();
}
else {
cout << "Unable to open f2.txt"<<endl;
}
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis QuickSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k-1];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
break; // break case f2.txt
// epilogi 3, arxeio f3
case 3:
k=0;
Darray= new int [9999];
Dtemp= new int [9999];
if (myfile3.is_open())
{
while ( myfile3 >> numFile)
{
//cout << numFile <<" ";
Darray[k]=numFile;
Dtemp[k]=numFile;
k++;
}
cout<<endl<<"LINES :"<<k<<endl;
//for (int j = 0; j < 50; j++){
// cout<<Darray[j]<<endl;
//}
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
myfile3.close();
}
else {
cout << "Unable to open f3.txt"<<endl;
break;
}
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis QuickSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k-1];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
break; // break case f3.txt
// epilogi 4, arxeio f4
case 4:
k=0;
Darray= new int [49999];
Dtemp= new int [49999];
if (myfile4.is_open())
{
while ( myfile4 >> numFile)
{
//cout << numFile <<" ";
Darray[k]=numFile;
Dtemp[k]=numFile;
k++;
}
cout<<endl<<"LINES :"<<k<<endl;
//for (int j = 0; j < 50; j++){
// cout<<Darray[j]<<endl;
//}
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
myfile4.close();
}
else {
cout << "Unable to open f4.txt"<<endl;
break;
}
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis QuickSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k-1];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
break; // break case f4.txt
// epilogi 5, arxeio f5
case 5:
k=0;
Darray= new int [99999];
Dtemp= new int [99999];
if (myfile5.is_open())
{
while ( myfile5 >> numFile)
{
//cout << numFile <<" ";
Darray[k]=numFile;
Dtemp[k]=numFile;
k++;
}
cout<<endl<<"LINES :"<<k<<endl;
//for (int j = 0; j < 50; j++){
// cout<<Darray[j]<<endl;
//}
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
myfile5.close();
}
else {
cout << "Unable to open f5.txt"<<endl;
break;
}
gen.printMenuTaxin();
cin>>taxin; // epilogi vasikou menou gia alg taxinom
switch (taxin){
case 1:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tQUICKSORT! "<<endl;
cout << "\nO pinakas PRIN to QuickSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1 );
start = clock();
quick.quickSort(Darray,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to QuickSort: " << endl;
//gen.print(Darray, k-1);
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis QuickSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 2:
arrayMerge= new int [k-1];
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tMERGESORT! "<<endl;
cout << "\nO pinakas PRIN to MergeSort: " <<endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
start = clock();
merge.mergeSort(Darray, arrayMerge,0, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to MergeSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis MergeSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
case 3:
while(epan!=2)
{
sigrisi=1;
cout<<"\n\tBUBBLESORT ! "<<endl;
cout << "\nO pinakas PRIN to BubbleSort: " <<endl;
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
//gen.print(Darray, k-1);
start = clock();
bubble.bubbleSort(Darray, k-1,sigrisi);
end = clock();
cout << "\nO pinakas META to BubbleSort: " << endl;
//gen.print(Darray, k-1 );
cout<<"1o stoixeio :"<<Darray[0]<<"\n2o stoixeio :"<<Darray[1]<<"\n(N-1)sto stoixeio :"<<Darray[k-2]<<"\n(N)sto stoixeio :"<<Darray[k-1]<<endl;
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout <<"\nXronos ektelesis BubbleSort: "<<fixed<<diarkeia<<"\nSigriseis : "<<sigrisi<<endl;
cout<<"\nEpanaliyi peiramatos ? \nPata 1 gia NAI \nPata 2 gia OXI"<<endl;
cin>>epan;
for (int j = 0; j <= k-1 ; j++){
Darray[j] = Dtemp[j];
}
}// while epanaliyis
epan=0;
break;
default:
cout<<"\nLathos !\n"<<endl;
break;
}//end
break; // break case f5.txt
default:// default break case .txt
cout<<"\nLathos sta arxeia!\n"<<endl;
break; // break case default .txt
} // switch arxeio
break; // break case2 pinakwn
default:// case default pinakwn
cout<<"\nLathos epilogi Pinaka periptwsewn!\n"<<endl;
break; // break case default pinakwn
} // end switch pinakwn
// ===================================================== TELOS pinakwn ==============================================================
menu=3;
break; // break epilogis 1 MENU gia taxinomisi
// ===================================================== ANAZITISIS ==============================================================
//epilogi 2, ilopihsh algorithmu anazitisis
case 2:
gen.printMenuAnaz();
cin>>anaz; // epilogi vasikou menou gia alg anaz
cout<<"\nPosa stoixeia thes na exei o pinakas gia anazitisi ? "<<endl;
cin>>numSearch;
Dbinary= new int [numSearch];
for (int j = 0 ; j < numSearch; j++){
Dbinary[j] = j;
}
switch (anaz){
// epilogi 1, ilopihsh algorithmou taxinomisis
case 1:
cout<<"\n\tBINARY SEARCH! "<<endl;
cout << "\nO pinakas pros anazitisi : " <<endl;
gen.print(Dbinary, numSearch-1);
cout<<"\nPio stoixeio thes na yaxeis ? "<<endl;
cin>>key;
start = clock();
bin.binarySearch(Dbinary, key, 0, numSearch, vimata) ;
end = clock();
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis Binary Search: "<<fixed<<diarkeia<<endl;
break; // break case binary
case 2:
cout<<"\n\tBINARY INTERPOLATION SEARCH! "<<endl;
cout << "\nO pinakas pros anazitisi : " <<endl;
gen.print(Dbinary, numSearch-1);
cout<<"\nPio stoixeio thes na yaxeis ? "<<endl;
cin>>key;
start = clock();
bis.bis(Dbinary, key, 0, numSearch, vimata) ;
end = clock();
diarkeia = ((double) (end-start)) / CLOCKS_PER_SEC ;
cout.precision(15);
cout<<"\nXronos ektelesis Binary Interpolation Search: "<<fixed<<diarkeia<<endl;
break; // break case binary INTERPOLATION
default:// case default anazitisi
cout<<"\nLathos stin anazitisi\n"<<endl;
break; // break case default anazitisi
} // switch anazitisi
menu=3;
cout<<"\n---------------"<<endl;
break; //break menu anazitisi
//epilogi 3, telos programmatos
case 3:
cout<<"\nTelos programmatos! "<<endl;
cout<<"---------------\n"<<endl;
break;//break menu gia 3i epilogi
default:
cout<<"\nLathos epilogi !! Xanaprospathise !\n"<<endl;
break;
}
}while(menu!=3); // telos programmatos otan patisei o xristis to 3
//delete [] Dtemp;
//delete [] Darray;
return 0;
} // end main
| 29.469231 | 214 | 0.429783 |
32ce8492fa335e90ecf599e30210a90e42ff8f14 | 877 | cpp | C++ | src/TestInput.cpp | dublet/KARR | 4b14090b34dab4d8be4e28814cb4d58cd34639ac | [
"BSD-3-Clause"
] | null | null | null | src/TestInput.cpp | dublet/KARR | 4b14090b34dab4d8be4e28814cb4d58cd34639ac | [
"BSD-3-Clause"
] | null | null | null | src/TestInput.cpp | dublet/KARR | 4b14090b34dab4d8be4e28814cb4d58cd34639ac | [
"BSD-3-Clause"
] | null | null | null | #include "TestInput.h"
#include <thread>
#include <time.h>
#include "Status.h"
#include "CarDefinition.h"
using namespace KARR;
void generateTestData() {
Status &s = Status::instance();
struct timespec sleepTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = 20 * 1000 * 1000;
int rpmDirection = 1;
int speedDirection = 1;
for (;;) {
if (s.getRpm() >= StaticCarDefinition::revs.max)
rpmDirection = -1;
if (s.getRpm() == StaticCarDefinition::revs.min)
rpmDirection = 1;
if (s.getSpeed() >= StaticCarDefinition::speed.max)
speedDirection = -1;
if (s.getSpeed() == StaticCarDefinition::speed.min)
speedDirection = 1;
s.setRpm(s.getRpm() + rpmDirection);
s.setSpeed(s.getSpeed() + speedDirection);
nanosleep(&sleepTime, NULL);
}
}
void TestInput::run() {
std::thread tt(generateTestData);
tt.detach();
}
| 19.488889 | 52 | 0.651083 |
32d3084d7c75d5a488629f74a8375ccfd553d2e6 | 940 | cpp | C++ | AtCoder/Archives/BeginnerContest76/C.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2017-10-25T13:33:27.000Z | 2017-10-25T13:33:27.000Z | AtCoder/Archives/BeginnerContest76/C.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | null | null | null | AtCoder/Archives/BeginnerContest76/C.cpp | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2021-05-05T01:16:28.000Z | 2021-05-05T01:16:28.000Z | #include <bits/stdc++.h>
using namespace std;
vector<int> match(const string& t, const string& p) {
vector<int> res;
bool find;
for (int i = 0; i < t.size(); i++) {
find = false;
if (t[i] == '?' || t[i] == p[0]) {
for (int j = 1; j < p.size(); j++) {
if (t[i + j] != '?' && t[i + j] != p[j]) {
find = true;
break;
}
}
if (!find) res.push_back(i);
}
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string t, p, temp, res;
cin >> t >> p;
vector<int> poss = match(t, p);
if (poss.size() != 0) {
res = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
for (auto pos : poss) {
temp = t;
for (int i = 0; i < p.size(); i++) temp[pos + i] = p[i];
for (auto& i : temp)
if (i == '?') i = 'a';
res = min(res, temp);
}
} else
res = "UNRESTORABLE";
cout << res << endl;
return 0;
} | 21.860465 | 63 | 0.469149 |
32db5b8eb721e0710aa9fc88fffde585f73fe707 | 2,925 | cpp | C++ | c++/array2D.cpp | praneethys/cheat-sheets | 1d11b1ffe1332bfd9c8c020bb2768082bdc678a7 | [
"MIT"
] | null | null | null | c++/array2D.cpp | praneethys/cheat-sheets | 1d11b1ffe1332bfd9c8c020bb2768082bdc678a7 | [
"MIT"
] | null | null | null | c++/array2D.cpp | praneethys/cheat-sheets | 1d11b1ffe1332bfd9c8c020bb2768082bdc678a7 | [
"MIT"
] | null | null | null | #include <iostream>
/* ctci_5thEd_13.10
Write a function for allocating a 2D array so as to minimize calls to malloc
and make sure the memory is accessible by the notation arr[i][j]
*/
int** Malloc2DArray(int rows, int cols)
{
std::cout << __func__ << std::endl;
int** rowPtr = (int**) malloc(rows * sizeof(int*));
if (rowPtr == NULL) {
return NULL;
}
std::cout << "Address: " << rowPtr << std::endl;
for (int row = 0; row < rows; row++) {
rowPtr[row] = (int*) malloc(cols * sizeof(int));
if (rowPtr[row] == NULL) {
return NULL;
}
std::cout << "Address: " << rowPtr[row] << std::endl;
}
return rowPtr;
}
void Free2DArray(int** rowPtr, int rows)
{
for (int row = 0; row < rows; row++) {
free(rowPtr[row]);
}
free(rowPtr);
std::cout << __func__ << std::endl;
}
int** Malloc2DArrayContiguous(int rows, int cols)
{
std::cout << __func__ << std::endl;
int header = rows * sizeof(int*);
int data = rows * cols * sizeof(int);
int** rowPtr = (int**) malloc(header + data);
if (rowPtr == NULL) {
return NULL;
}
std::cout << "Address: " << rowPtr << std::endl;
int* buf = (int*) (rowPtr + rows);
for (int row = 0; row < rows; row++) {
rowPtr[row] = buf + row * cols;
std::cout << "Address: " << rowPtr[row] << std::endl;
}
return rowPtr;
}
void Free2DArrayContiguous(int** rowPtr, int rows)
{
free(rowPtr);
std::cout << __func__ << std::endl;
}
int** New2DArray(int rows, int cols)
{
std::cout << __func__ << std::endl;
int** rowPtr = new int*[rows];
if (rowPtr == nullptr) {
return nullptr;
}
std::cout << "Address: " << rowPtr << std::endl;
for (int row = 0; row < rows; row++) {
rowPtr[row] = new int[cols];
if (rowPtr[row] == nullptr) {
return nullptr;
}
std::cout << "Address: " << rowPtr[row] << std::endl;
}
return rowPtr;
}
void Delete2DArray(int** rowPtr, int rows)
{
for (int row = 0; row < rows; row++) {
delete rowPtr[row];
}
delete rowPtr;
std::cout << __func__ << std::endl;
}
void Write2DArray(int** arr, int rows, int cols)
{
static int data;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
arr[row][col] = data++;
}
}
}
void Read2DArray(int** arr, int rows, int cols)
{
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
std::cout << "\t" << arr[row][col];
}
std::cout << std::endl;
}
}
int main()
{
int rows = 2;
int cols = 2;
int **cpp = New2DArray(rows, cols);
Write2DArray(cpp, rows, cols);
Read2DArray(cpp, rows, cols);
int **c = Malloc2DArray(rows, cols);
Write2DArray(c, rows, cols);
Read2DArray(c, rows, cols);
int **cg = Malloc2DArrayContiguous(rows, cols);
Write2DArray(cg, rows, cols);
Read2DArray(cg, rows, cols);
Delete2DArray(cpp, rows);
Free2DArray(c, rows);
Free2DArrayContiguous(cg, rows);
return 0;
} | 21.828358 | 76 | 0.580513 |
77f78d34dea4f79dffd4b2dbf25953ac52db750d | 7,085 | cpp | C++ | Source/ModuleTrails.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 10 | 2019-02-05T07:57:21.000Z | 2021-10-17T13:44:31.000Z | Source/ModuleTrails.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 178 | 2019-02-26T17:29:08.000Z | 2019-06-05T10:55:42.000Z | Source/ModuleTrails.cpp | JellyBitStudios/JellyBitEngine | 4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4 | [
"MIT"
] | 2 | 2020-02-27T18:57:27.000Z | 2020-05-28T01:19:59.000Z | #include "ModuleTrails.h"
#include "ModuleTimeManager.h"
#include "ModuleInput.h"
#include "ModuleResourceManager.h"
#include "ModuleRenderer3D.h"
#include "ModuleInternalResHandler.h"
#include "ResourceMaterial.h"
#include "ResourceShaderObject.h"
#include "ResourceShaderProgram.h"
#include "ResourceMesh.h"
#include "Optick/include/optick.h"
#include <algorithm>
#include "MathGeoLib/include/Math/float4x4.h"
#include "Application.h"
#include "DebugDrawer.h"
#include "ComponentTransform.h"
#include "GLCache.h"
#include "glew/include/GL/glew.h"
ModuleTrails::ModuleTrails(bool start_enabled) : Module(start_enabled)
{}
ModuleTrails::~ModuleTrails()
{
trails.clear();
}
update_status ModuleTrails::PostUpdate()
{
#ifndef GAMEMODE
OPTICK_CATEGORY("ModuleTrails_PostUpdate", Optick::Category::VFX);
#endif // !GAMEMODE
for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail)
{
(*trail)->Update();
}
return UPDATE_CONTINUE;
}
void ModuleTrails::Draw()
{
#ifndef GAMEMODE
OPTICK_CATEGORY("ModuleTrails_Draw", Optick::Category::VFX);
#endif // !GAMEMODE
for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail)
{
if (!(*trail)->trailVertex.empty())
{
if ((*trail)->materialRes == 0) continue;
std::list<TrailNode*>::iterator begin = (*trail)->trailVertex.begin();
TrailNode* end = (*trail)->trailVertex.back();
float i = 0.0f;
float size = (*trail)->trailVertex.size() + 1;
for (std::list<TrailNode*>::iterator curr = (*trail)->trailVertex.begin(); curr != (*trail)->trailVertex.end(); ++curr)
{
i++;
std::list<TrailNode*>::iterator next = curr;
++next;
if (next != (*trail)->trailVertex.end())
{
ResourceMaterial* resourceMaterial = (ResourceMaterial*)App->res->GetResource((*trail)->materialRes);
uint shaderUuid = resourceMaterial->GetShaderUuid();
ResourceShaderProgram* resourceShaderProgram = (ResourceShaderProgram*)App->res->GetResource(shaderUuid);
GLuint shaderProgram = resourceShaderProgram->shaderProgram;
App->glCache->SwitchShader(shaderProgram);
math::float4x4 model_matrix = math::float4x4::identity;// particle matrix
model_matrix = model_matrix.Transposed();
math::float4x4 mvp_matrix = model_matrix * App->renderer3D->viewProj_matrix;
math::float4x4 normal_matrix = model_matrix;
normal_matrix.Inverse();
normal_matrix.Transpose();
uint location = glGetUniformLocation(shaderProgram, "model_matrix");
glUniformMatrix4fv(location, 1, GL_FALSE, model_matrix.ptr());
location = glGetUniformLocation(shaderProgram, "mvp_matrix");
glUniformMatrix4fv(location, 1, GL_FALSE, mvp_matrix.ptr());
location = glGetUniformLocation(shaderProgram, "normal_matrix");
glUniformMatrix3fv(location, 1, GL_FALSE, normal_matrix.Float3x3Part().ptr());
float currUV = (float(i) / size);
float nextUV = (float(i + 1) / size);
math::float3 originHigh = (*curr)->originHigh;
math::float3 originLow = (*curr)->originLow;
math::float3 destinationHigh = (*next)->originHigh;
math::float3 destinationLow = (*next)->originLow;
if ((*trail)->orient)
RearrangeVertex(trail, curr, next, currUV, nextUV, originHigh, originLow, destinationHigh, destinationLow);
location = glGetUniformLocation(shaderProgram, "currUV"); // cUV
glUniform1f(location, currUV);
location = glGetUniformLocation(shaderProgram, "nextUV"); // cUV
glUniform1f(location, nextUV);
location = glGetUniformLocation(shaderProgram, "realColor"); // Color
glUniform4f(location, (*trail)->color.x, (*trail)->color.y, (*trail)->color.z, (*trail)->color.w);
location = glGetUniformLocation(shaderProgram, "vertex1"); // Current High
glUniform3f(location, originHigh.x, originHigh.y, originHigh.z);
location = glGetUniformLocation(shaderProgram, "vertex2"); // Current Low
glUniform3f(location, originLow.x, originLow.y, originLow.z);
location = glGetUniformLocation(shaderProgram, "vertex3"); // Next High
glUniform3f(location, destinationHigh.x, destinationHigh.y, destinationHigh.z);
location = glGetUniformLocation(shaderProgram, "vertex4"); // Next Low
glUniform3f(location, destinationLow.x, destinationLow.y, destinationLow.z);
// Unknown uniforms
uint textureUnit = 0;
std::vector<Uniform> uniforms = resourceMaterial->GetUniforms();
for (uint i = 0; i < uniforms.size(); ++i)
{
Uniform uniform = uniforms[i];
if (strcmp(uniform.common.name, "material.albedo") == 0 || strcmp(uniform.common.name, "material.specular") == 0)
{
if (textureUnit < App->renderer3D->GetMaxTextureUnits())
{
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, uniform.sampler2DU.value.id);
glUniform1i(uniform.common.location, textureUnit);
++textureUnit;
}
}
}
ResourceMesh* plane = (ResourceMesh*)App->res->GetResource(App->resHandler->plane);
glBindVertexArray(plane->GetVAO());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plane->GetIBO());
glDrawElements(GL_TRIANGLES, plane->GetIndicesCount(), GL_UNSIGNED_INT, NULL);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
}
// TODO: THIS IS USELESS I THINK
glEnd();
glPopMatrix();
}
}
}
void ModuleTrails::RearrangeVertex(std::list<ComponentTrail *>::iterator &trail, std::list<TrailNode *>::iterator &curr, std::list<TrailNode *>::iterator &next, float &currUV, float &nextUV, math::float3 &originHigh, math::float3 &originLow, math::float3 &destinationHigh, math::float3 &destinationLow)
{
// Rearrange vertex
float origin = 0;
float dest = 0;
GetOriginAndDest(trail, origin, curr, dest, next);
if (origin < dest)
{
float tmp = currUV;
currUV = nextUV;
nextUV = tmp;
math::float3 tmph = originHigh;
math::float3 tmpl = originLow;
originHigh = destinationHigh;
originLow = destinationLow;
destinationHigh = tmph;
destinationLow = tmpl;
}
}
void ModuleTrails::GetOriginAndDest(std::list<ComponentTrail *>::iterator &trail, float &origin, std::list<TrailNode *>::iterator &curr, float &dest, std::list<TrailNode *>::iterator &next)
{
switch ((*trail)->vector)
{
case X:
origin = (*curr)->originHigh.x;
dest = (*next)->originHigh.x;
break;
case Y:
// This is not right
origin = (*curr)->originHigh.x;
dest = (*next)->originHigh.x;
break;
case Z:
dest = (*curr)->originHigh.z;
origin = (*next)->originHigh.z;
break;
default:
break;
}
}
void ModuleTrails::DebugDraw() const
{
// Todo
}
void ModuleTrails::OnSystemEvent(System_Event event)
{
switch (event.type)
{
case System_Event_Type::Play:
case System_Event_Type::LoadFinished:
// Todo
break;
case System_Event_Type::Stop:
// Todo
break;
}
}
void ModuleTrails::RemoveTrail(ComponentTrail* trail)
{
trails.remove(trail);
}
| 29.894515 | 302 | 0.692449 |
77f9ee909641a70f1d118cd6b3981bf2d3afbb95 | 821 | cpp | C++ | src/main.cpp | Maou-Shimazu/Operation-Cpp | 17398c92b7e64bcabe0d597efc8b01cd724e692b | [
"MIT"
] | null | null | null | src/main.cpp | Maou-Shimazu/Operation-Cpp | 17398c92b7e64bcabe0d597efc8b01cd724e692b | [
"MIT"
] | null | null | null | src/main.cpp | Maou-Shimazu/Operation-Cpp | 17398c92b7e64bcabe0d597efc8b01cd724e692b | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <src/format.cc>
#include <fmt/core.h>
#include <parse_args.h>
#include "../include/prompts.hpp"
#include "loopTerminal.cpp"
#include "../include/argCheck.hpp"
using namespace arguments;
// todo: impliment directory check for program run in directory
void welcomeInfo(){}
int main(int argc, char *argv[]) {
ParseArgs parse = ParseArgs(argc, argv);
if (parse.ParseSelf()){
std::cout << prompt::welcome << std::endl;
prompt::loopInformation();
}
TerminalHandler terminal;
if (parse.DefaultParse("watch")) {
std::cout << "Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here." << std::endl;
terminal.WatchMode();
}
if (parse.DefaultParse("help")) {
fmt::print(prompt::help);
}
return 0;
}
| 24.147059 | 128 | 0.677223 |
77fa96da8b3c3fbb42952b263753b552ef75eb66 | 6,837 | cpp | C++ | src/boost_lagrange.cpp | mugwort-rc/boost_python_lagrange | ae7cc35b1f650e63de91fd7c25996dc6abc550c4 | [
"BSD-3-Clause"
] | null | null | null | src/boost_lagrange.cpp | mugwort-rc/boost_python_lagrange | ae7cc35b1f650e63de91fd7c25996dc6abc550c4 | [
"BSD-3-Clause"
] | null | null | null | src/boost_lagrange.cpp | mugwort-rc/boost_python_lagrange | ae7cc35b1f650e63de91fd7c25996dc6abc550c4 | [
"BSD-3-Clause"
] | null | null | null | // g++ -std=c++11 -I`python -c 'from distutils.sysconfig import *; print(get_python_inc())'` -DPIC -shared -fPIC -o _lagrange.so boost_lagrange.cpp -lboost_python-py35
#include <memory>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include "lagrange.hpp"
template <typename T_>
class boost_multiprecision_to_float {
public:
typedef T_ native_type;
static PyObject* convert(const native_type &value) {
return boost::python::incref(boost::python::object(static_cast<long double>(value)).ptr());
}
};
template <typename T_>
class float_converter {
public:
typedef T_ native_type;
static void * convertible(PyObject *pyo) {
namespace py = boost::python;
if ( ! py::extract<double>(py::object(py::handle<>(py::borrowed(pyo)))).check() ) {
return nullptr;
}
return pyo;
}
static void construct(PyObject *pyo, boost::python::converter::rvalue_from_python_stage1_data *data) {
namespace py = boost::python;
double value = py::extract<double>(py::object(py::handle<>(py::borrowed(pyo))));
native_type *storage = new(reinterpret_cast<py::converter::rvalue_from_python_storage<native_type>*>(data)->storage.bytes) native_type(value);
data->convertible = storage;
}
};
template <typename T_>
class vector_to_pylist_converter {
public:
typedef T_ native_type;
static PyObject * convert(const native_type &v) {
boost::python::list retval;
for (auto i : v) {
retval.append(boost::python::object(i));
}
return boost::python::incref(retval.ptr());
}
};
template <typename T_>
class pylist_to_vector_converter {
public:
typedef T_ native_type;
static void * convertible(PyObject *pyo) {
if ( ! PySequence_Check(pyo) ) {
return nullptr;
}
return pyo;
}
static void construct(PyObject *pyo, boost::python::converter::rvalue_from_python_stage1_data *data)
{
namespace py = boost::python;
native_type *storage = new(reinterpret_cast<py::converter::rvalue_from_python_storage<native_type>*>(data)->storage.bytes) native_type();
for (py::ssize_t i = 0, l = PySequence_Size(pyo); i < l; ++i) {
storage->push_back(
py::extract<typename boost::range_value<native_type>::type>(
PySequence_GetItem(pyo, i)));
}
data->convertible = storage;
}
};
template <typename T>
std::string vector_repr(const std::vector<T> &self) {
boost::python::list pylist;
for (auto item : self) {
pylist.append(boost::python::object(item));
}
return boost::python::extract<std::string>(boost::python::str(pylist));
}
template <typename T>
inline void lagrange_input_assertion(const std::vector<T> &x, const std::vector<T> &w) {
if ( x.size() != w.size() ) {
PyErr_SetString(PyExc_AssertionError, "array must be same langth.");
boost::python::throw_error_already_set();
}
}
template <typename T>
std::shared_ptr<Lagrange<T>> make_Lagrange(const std::vector<T> &x, const std::vector<T> &w) {
lagrange_input_assertion<T>(x, w);
return std::make_shared<Lagrange<T>>(x, w);
}
template<typename T>
boost::python::list tolist(const Lagrange<T> &l) {
boost::python::list r;
for (const auto & c : l.coefficients ) {
r.append(static_cast<long double>(c));
}
return r;
}
template <typename T>
void init_Lagrange(const std::string &name) {
boost::python::class_<Lagrange<T>, std::shared_ptr<Lagrange<T>>>(("Lagrange_" + name).c_str(), boost::python::no_init)
.def("__init__", boost::python::make_constructor(&make_Lagrange<T>))
.def("__call__", &Lagrange<T>::operator())
.def_readonly("c", &Lagrange<T>::coefficients)
.def("coefficients", &tolist<T>)
;
// T to python::float converter
boost::python::to_python_converter<T, boost_multiprecision_to_float<T>>();
// python::float to T converter
boost::python::converter::registry::push_back(
&float_converter<T>::convertible,
&float_converter<T>::construct,
boost::python::type_id<T>())
;
// std::vector<T> to python::list converter
//boost::python::to_python_converter<std::vector<T>, vector_to_pylist_converter<std::vector<T>>>();
boost::python::class_<std::vector<T>>((name + "_vector").c_str())
.def(boost::python::vector_indexing_suite<std::vector<T>>())
.def("__repr__", &vector_repr<T>)
;
// python::list to std::vector<T> converter
boost::python::converter::registry::push_back(
&pylist_to_vector_converter<std::vector<T>>::convertible,
&pylist_to_vector_converter<std::vector<T>>::construct,
boost::python::type_id<std::vector<T>>())
;
}
////////////////////////////////////////////////////////////////////////////////
template <typename T>
std::shared_ptr<DeltaLagrange<T>> make_DeltaLagrange(const std::vector<T> &x, const std::vector<T> &w) {
lagrange_input_assertion<T>(x, w);
return std::make_shared<DeltaLagrange<T>>(x, w);
}
template<typename T>
boost::python::tuple totuple(const DeltaLagrange<T> &l) {
boost::python::list r;
for (const auto & c : l.coefficients ) {
r.append(static_cast<long double>(c));
}
return boost::python::make_tuple(
r,
static_cast<long double>(l.x0),
static_cast<long double>(l.w0)
);
}
template <typename T>
void init_DeltaLagrange(const std::string &name) {
boost::python::class_<DeltaLagrange<T>, std::shared_ptr<DeltaLagrange<T>>>(("DeltaLagrange_" + name).c_str(), boost::python::no_init)
.def("__init__", boost::python::make_constructor(&make_DeltaLagrange<T>))
.def("__call__", &DeltaLagrange<T>::operator())
.def_readonly("c", &DeltaLagrange<T>::coefficients)
.def("coefficients", &totuple<T>)
;
}
double py_fast(double x, const std::vector<double> &xs, const std::vector<double> &ws) {
lagrange_input_assertion<double>(xs, ws);
return Lagrange<double>::fast(x, xs, ws);
}
BOOST_PYTHON_MODULE(_lagrange) {
init_Lagrange<boost::multiprecision::cpp_dec_float_50>("float_50");
init_Lagrange<boost::multiprecision::cpp_dec_float_100>("float_100");
init_DeltaLagrange<boost::multiprecision::cpp_dec_float_50>("float_50");
init_DeltaLagrange<boost::multiprecision::cpp_dec_float_100>("float_100");
boost::python::def("fast", &py_fast);
// python::list to std::vector<T> converter
boost::python::converter::registry::push_back(
&pylist_to_vector_converter<std::vector<double>>::convertible,
&pylist_to_vector_converter<std::vector<double>>::construct,
boost::python::type_id<std::vector<double>>());
}
| 33.18932 | 167 | 0.650578 |
77faa89d81a4b36dab95fe24f37377da962077a4 | 297 | cpp | C++ | Porblems/bear_and_big_brother.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | Porblems/bear_and_big_brother.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | Porblems/bear_and_big_brother.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int limak,bob;
cin>>limak>>bob;
int i=1;
while(1){
limak=limak*3;
bob=bob*2;
if (limak>bob){
cout<<i<<endl;
break;
}
else{
i++;
}
}
} | 14.85 | 26 | 0.40404 |
77fb5c852b5894084a60aee11390464d3b90c236 | 2,921 | hxx | C++ | private/shell/ext/mydocs2/precomp.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/ext/mydocs2/precomp.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/ext/mydocs2/precomp.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | #ifndef _pch_h
#define _pch_h
#include <windows.h>
#include <windowsx.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <ccstock.h>
#include <shsemip.h>
#include <shlwapip.h>
#include <shlapip.h>
#include <shlobjp.h> // for shellp.h
#include <shellp.h> // SHFOLDERCUSTOMSETTINGS
#include <cfdefs.h> // CClassFactory, LPOBJECTINFO
#include <comctrlp.h>
extern const CLSID CLSID_MyDocsDropTarget;
STDAPI_(void) DllAddRef(void);
STDAPI_(void) DllRelease(void);
#ifdef DBG
#define DEBUG 1
#endif
//
// Avoid bringing in C runtime code for NO reason
//
#if defined(__cplusplus)
inline void * __cdecl operator new(size_t size) { return (void *)LocalAlloc(LPTR, size); }
inline void __cdecl operator delete(void *ptr) { LocalFree(ptr); }
extern "C" inline __cdecl _purecall(void) { return 0; }
#endif // __cplusplus
#if defined(DBG) || defined(DEBUG)
#ifndef DEBUG
#define DEBUG
#endif
#else
#undef DEBUG
#endif
#ifdef DEBUG
#define MDTraceSetMask(dwMask) MDDoTraceSetMask(dwMask)
#define MDTraceEnter(dwMask, fn) MDDoTraceEnter(dwMask, TEXT(fn))
#define MDTraceLeave MDDoTraceLeave
#define MDTrace MDDoTrace
#define MDTraceMsg(s) MDDoTrace(TEXT(s))
void MDDoTraceSetMask(DWORD dwMask);
void MDDoTraceEnter(DWORD dwMask, LPCTSTR pName);
void MDDoTraceLeave(void);
void MDDoTrace(LPCTSTR pFormat, ...);
void MDDoTraceAssert(int iLine, LPTSTR pFilename);
#define MDTraceLeaveResult(hr) \
{ HRESULT __hr = hr; if (FAILED(__hr)) MDTrace(TEXT("Failed (%08x)"), hr); MDTraceLeave(); return __hr; }
#else
#define MDTraceSetMask(dwMask)
#define MDTraceEnter(dwMask, fn)
#define MDTraceLeave()
#define MDTrace if (FALSE)
#define MDTraceMsg(s)
#define MDTraceLeaveResult(hr) { return hr; }
#endif
#define TRACE_COMMON_ASSERT 0x40000000
#define ExitGracefully(hr, result, text) \
{ MDTraceMsg(text); hr = result; goto exit_gracefully; }
#define FailGracefully(hr, text) \
{ if ( FAILED(hr) ) { MDTraceMsg(text); goto exit_gracefully; } }
// Magic debug flags
#define TRACE_CORE 0x00000001
#define TRACE_FOLDER 0x00000002
#define TRACE_ENUM 0x00000004
#define TRACE_ICON 0x00000008
#define TRACE_DATAOBJ 0x00000010
#define TRACE_IDLIST 0x00000020
#define TRACE_CALLBACKS 0x00000040
#define TRACE_COMPAREIDS 0x00000080
#define TRACE_DETAILS 0x00000100
#define TRACE_QI 0x00000200
#define TRACE_EXT 0x00000400
#define TRACE_UTIL 0x00000800
#define TRACE_SETUP 0x00001000
#define TRACE_PROPS 0x00002000
#define TRACE_COPYHOOK 0x00004000
#define TRACE_FACTORY 0x00008000
#define TRACE_ALWAYS 0xffffffff // use with caution
#endif
| 26.080357 | 122 | 0.670318 |
77feeab069b3c47765e14808dc6d98b57875f0db | 4,277 | cpp | C++ | AtCoder/typical90/029 - Long Bricks/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | 1 | 2020-05-24T02:27:05.000Z | 2020-05-24T02:27:05.000Z | AtCoder/typical90/029 - Long Bricks/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | null | null | null | AtCoder/typical90/029 - Long Bricks/main.cpp | t-mochizuki/cpp-study | df0409c2e82d154332cb2424c7810370aa9822f9 | [
"MIT"
] | null | null | null | // g++ -std=c++14 -DDEV=1 main.cpp
#include <stdio.h>
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
using std::cin;
using std::cout;
using std::endl;
using std::terminate;
using std::vector;
using std::max;
using std::sort;
using std::map;
using std::make_pair;
// キーワード: 「座標圧縮」で効率化
//
// キーワード: 区間に対する処理は「セグメント木」
#define rep(i, a, n) for (int i = (a); i < (n); ++i)
#define bit(n, k) ((n >> k) & 1)
const long VALUE = 0;
class RangeUpdateQuery {
private:
int M = 1;
int N;
vector<long> value, lazy;
int parent(int i) {
return (i - 1) / 2;
}
int left(int i) {
return 2 * i + 1;
}
int right(int i) {
return 2 * i + 2;
}
void eval(int i) {
if (lazy[i] == VALUE) return ;
if (i < M - 1) {
lazy[left(i)] = lazy[i];
lazy[right(i)] = lazy[i];
}
value[i] = lazy[i];
lazy[i] = VALUE;
}
long find(int lhs, int rhs, int i, int L, int R) {
assert(i < N);
assert(i >= 0);
eval(i);
int ret = VALUE;
if (rhs <= L || R <= lhs) {
ret = VALUE;
} else if (lhs <= L && R <= rhs) {
ret = value[i];
} else {
long lv = find(lhs, rhs, left(i), L, (L + R) / 2);
long rv = find(lhs, rhs, right(i), (L + R) / 2, R);
ret = max(lv, rv);
}
return ret;
}
void update(long x, int lhs, int rhs, int i, int L, int R) {
assert(i < N);
assert(i >= 0);
eval(i);
if (rhs <= L || R <= lhs) {
} else if (lhs <= L && R <= rhs) {
lazy[i] = x;
eval(i);
} else {
update(x, lhs, rhs, left(i), L, (L + R) / 2);
update(x, lhs, rhs, right(i), (L + R) / 2, R);
value[i] = max(value[left(i)], value[right(i)]);
}
}
public:
RangeUpdateQuery(int len) {
while (M < len) {
M *= 2;
}
N = 2 * M - 1;
value.assign(N, VALUE);
lazy.assign(N, VALUE);
}
long find(int lhs, int rhs) {
int root = 0; // 葉の数はM、区間は[0, M)
return find(lhs, rhs, root, 0, M);
}
void update(long x, int lhs, int rhs) {
int root = 0; // 葉の数はM、区間は[0, M)
return update(x, lhs, rhs, root, 0, M);
}
};
class Problem {
private:
int W, N;
vector<int> L, R;
map<int, int> zip;
public:
Problem() {
cin >> W >> N;
assert(2 <= W);
assert(W <= 500000);
assert(1 <= N);
assert(N <= 250000);
L.resize(N);
R.resize(N);
rep(i, 0, N) {
cin >> L[i] >> R[i];
assert(1 <= L[i]);
assert(W >= L[i]);
assert(1 <= R[i]);
assert(W >= R[i]);
assert(L[i] <= R[i]);
}
rep(i, 0, N) {
if (zip.find(L[i]) == zip.end()) {
zip.insert(make_pair(L[i], 1));
}
if (zip.find(R[i]) == zip.end()) {
zip.insert(make_pair(R[i], 1));
}
}
int num = 1;
for (auto it = zip.begin(); it != zip.end(); ++it) {
it->second = num;
num++;
}
}
void fullSearch() {
vector<int> height;
height.assign(W+1, 0);
rep(i, 0, N) {
int maximum = 0;
rep(j, zip[L[i]], zip[R[i]]+1) {
maximum = max(height[j], maximum);
}
maximum++;
cout << maximum << endl;
rep(j, zip[L[i]], zip[R[i]]+1) height[j] = maximum;
}
}
void solve() {
vector<int> height;
height.assign(W+1, 0);
RangeUpdateQuery tree(zip.size()+5);
rep(i, 0, N) {
long x = tree.find(zip[L[i]], zip[R[i]]+1);
x++;
cout << x << endl;
tree.update(x, zip[L[i]], zip[R[i]]+1);
}
}
};
int main() {
#ifdef DEV
std::ifstream in("input");
cin.rdbuf(in.rdbuf());
int t; cin >> t;
for (int x = 1; x <= t; ++x) {
Problem p;
p.solve();
}
#else
Problem p;
p.solve();
#endif
return 0;
}
| 19.619266 | 64 | 0.416647 |
77fef9ca7e9b463b12918ccca0581b7399ccd45d | 1,077 | hpp | C++ | camera/DumpProfile.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | camera/DumpProfile.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | null | null | null | camera/DumpProfile.hpp | flexibity-team/boost-tools | a6c67eacf7374136f9903680308334fc3408ba91 | [
"MIT"
] | 2 | 2019-12-26T13:54:29.000Z | 2020-10-31T10:19:13.000Z | #ifndef DUMBPROFILE_H_
#define DUMBPROFILE_H_
#include <sys/time.h>
#include <stdint.h>
#include <string.h>
#define DPROFILE dumb_profile dprf = dumb_profile(__FUNCTION__, __LINE__); dprf.start();
struct dumb_profile{
struct timeval start_;
struct timeval end_;
const char* fname_;
const uint32_t lnum_;
dumb_profile(const char* fname, const uint32_t lnum): start_(), end_(), fname_(fname), lnum_(lnum){
//start();
}
~dumb_profile(){
stop();
}
void start(){
gettimeofday(&start_, 0);
}
void stop(){
print();
memset(&start_, 0, sizeof(start_));
memset(&end_, 0, sizeof(end_));
}
int64_t started(){
return timeval_to_ms(start_);
}
int64_t timeval_to_ms(struct timeval& tv){
return (tv.tv_sec * 1000000) + tv.tv_usec;
}
void print(){
gettimeofday(&end_, 0);
//uint32_t now_ms = end_.;
int32_t delta = ((end_.tv_sec - start_.tv_sec) * 1000000) + end_.tv_usec - start_.tv_usec;
// printf("profile: %s:%d: now:%03li:04%li elapsed:%d us\n", fname_, lnum_, end_.tv_sec, end_.tv_usec / 1000 , delta);
}
};
#endif //DUMBPROFILE_H_
| 19.944444 | 119 | 0.679666 |
ae023ba1b61d8f539911c840c19059f293e70936 | 980 | cpp | C++ | Codeforces/Solutions/1082B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | Codeforces/Solutions/1082B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | Codeforces/Solutions/1082B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | // Problem Code: 1082B
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int vovaAndTrophies(int n, string S) {
int len, maxLen, g;
vector<int> L(n), R(n);
len = maxLen = 0;
g = count(S.begin(), S.end(), 'G');
if (g == n)
return g;
if (S[0] == 'G')
L[0] = 1;
for (int i = 1 ; i < n ; i++) {
if (S[i] == 'S')
continue;
L[i] = 1;
L[i] += L[i - 1];
}
if (S[n - 1] == 'G')
R[n - 1] = 1;
for (int i = n - 2 ; i >= 0 ; i--) {
if (S[i] == 'S')
continue;
R[i] = 1;
R[i] += R[i + 1];
}
if (n == 1)
maxLen = L[0];
else {
if (S[0] == 'S')
maxLen = max(maxLen, R[1]);
if (S[n - 1] == 'S') {
maxLen = max(maxLen, L[n - 2]);
}
}
for (int i = 1 ; i < n - 1 ; i++) {
if (S[i] == 'G')
continue;
len = L[i - 1] + R[i + 1];
if (len < g)
len++;
if (len > maxLen)
maxLen = len;
}
return maxLen;
}
int main() {
int n;
string S;
cin >> n >> S;
cout << vovaAndTrophies(n, S);
return 0;
} | 15.555556 | 38 | 0.45 |
ae033e4d44777869c7554d7e250a1ce42554f400 | 47,761 | cpp | C++ | source/D2Common/src/DataTbls/SequenceTbls.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:15.000Z | 2022-03-20T12:12:15.000Z | source/D2Common/src/DataTbls/SequenceTbls.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | null | null | null | source/D2Common/src/DataTbls/SequenceTbls.cpp | raumuongluoc/D2MOO | 169de1bd24151cda4c654ef0f8027896a14552ec | [
"MIT"
] | 1 | 2022-03-20T12:12:18.000Z | 2022-03-20T12:12:18.000Z | #include <D2DataTbls.h>
#include <DataTbls/SequenceTbls.h>
#include <D2BitManip.h>
#include <Units/Units.h>
#include <D2Skills.h>
#include <D2Composit.h>
//D2Common.0x6FDDE6A8
D2MonSeqTxt gPlayerSequenceHandToHand1[13] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE6F8
D2MonSeqTxt gPlayerSequenceHandToHand2[14] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE750
D2MonSeqTxt gPlayerSequenceJab_BOW[18] =
{
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE7C0
D2MonSeqTxt gPlayerSequenceJab_1HS[21] =
{
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE840
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceJab =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceJab_BOW, 18, 18,
gPlayerSequenceJab_1HS, 21, 21,
};
//D2Common.0x6FDDE8E8
D2MonSeqTxt gPlayerSequenceSacrifice_1HT[7] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE914
D2MonSeqTxt gPlayerSequenceSacrifice_STF[8] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE948
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceSacrifice =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceSacrifice_1HT, 7, 7,
gPlayerSequenceSacrifice_STF, 8, 8,
};
//D2Common.0x6FDDE9F0
D2MonSeqTxt gPlayerSequenceChastise_1HT[16] =
{
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEA50
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceChastise =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceChastise_1HT, 16, 16,
};
//D2Common.0x6FDDEAF8
D2MonSeqTxt gPlayerSequenceCharge[15] =
{
{ 0, PLRMODE_RUN, 0, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 1, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 3, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEB58
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceCharge =
{
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
0, 0, 0,
0, 0, 0,
gPlayerSequenceCharge, 15, 15,
};
//D2Common.0x6FDDEC00
D2MonSeqTxt gPlayerSequenceDefiance_1HT[6] =
{
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEC28
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDefiance =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDefiance_1HT, 6, 6,
};
//D2Common.0x6FDDECD0
D2MonSeqTxt gPlayerSequenceInferno[15] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDED30
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceInferno =
{
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
};
//D2Common.0x6FDDEDD8
D2MonSeqTxt gPlayerSequenceStrafe_2HS[13] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEE28
D2MonSeqTxt gPlayerSequenceStrafe_2HT[20] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 19, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEEA0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceStrafe =
{
gPlayerSequenceHandToHand1, 13, 13,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceStrafe_2HS, 13, 13,
gPlayerSequenceStrafe_2HT, 20, 20,
};
//D2Common.0x6FDDEF48
D2MonSeqTxt gPlayerSequenceImpale_BOW[21] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEFC8
D2MonSeqTxt gPlayerSequenceImpale_1HS[24] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF058
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceImpale =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceImpale_BOW, 21, 21,
gPlayerSequenceImpale_1HS, 24, 24,
};
//D2Common.0x6FDDF100
D2MonSeqTxt gPlayerSequenceFend_BOW[16] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF160
D2MonSeqTxt gPlayerSequenceFend_1HS[16] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, 0, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF1C0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceFend =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceFend_BOW, 16, 16,
gPlayerSequenceFend_1HS, 16, 16,
};
//D2Common.0x6FDDF268
D2MonSeqTxt gPlayerSequenceWhirlwind[8] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
};
//D2Common.0x6FDDF298
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceWhirlwind =
{
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
0, 0, 0,
0, 0, 0,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
};
//D2Common.0x6FDDF340
D2MonSeqTxt gPlayerSequenceDoubleSwing[17] =
{
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF3A8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleSwing =
{
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
};
//D2Common.0x6FDDF450
D2MonSeqTxt gPlayerSequenceLightning[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF4C8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLightning =
{
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
};
//D2Common.0x6FDDF570
D2MonSeqTxt gPlayerSequenceLeap[15] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_MELEE_ATTACK },
};
//D2Common.0x6FDDF5D0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeap =
{
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
};
//D2Common.0x6FDDF678
D2MonSeqTxt gPlayerSequenceLeapAttack_HTH[22] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF700
D2MonSeqTxt gPlayerSequenceLeapAttack_BOW_1HT[25] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF798
D2MonSeqTxt gPlayerSequenceLeapAttack_1HS_XBW[28] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF840
D2MonSeqTxt gPlayerSequenceLeapAttack_STF[27] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF8E8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeapAttack =
{
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_BOW_1HT, 25, 25,
gPlayerSequenceLeapAttack_1HS_XBW, 28, 28,
gPlayerSequenceLeapAttack_BOW_1HT, 25, 25,
gPlayerSequenceLeapAttack_STF, 27, 27,
0, 0, 0,
0, 0, 0,
gPlayerSequenceLeapAttack_1HS_XBW, 28, 28,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
};
//D2Common.0x6FDDF990
D2MonSeqTxt gPlayerSequenceDoubleThrow[12] =
{
{ 0, PLRMODE_THROW, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF9D8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleThrow =
{
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
};
//D2Common.0x6FDDFA80
D2MonSeqTxt gPlayerSequenceDragonClaw_HTH_HT1[12] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFAC8
D2MonSeqTxt gPlayerSequenceDragonClaw_HT2[16] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL4, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL4, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFB28
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonClaw =
{
gPlayerSequenceDragonClaw_HTH_HT1, 12, 12,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonClaw_HTH_HT1, 12, 12,
gPlayerSequenceDragonClaw_HT2, 16, 16,
};
//D2Common.0x6FDDFBD0
D2MonSeqTxt gPlayerSequenceProjection[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 18, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, 0, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFC48
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceProjection =
{
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
};
//D2Common.0x6FDDFCF0
D2MonSeqTxt gPlayerSequenceDragonTalon[20] =
{
{ 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFD68
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonTalon =
{
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
};
//D2Common.0x6FDDFE10
D2MonSeqTxt gPlayerSequenceArcticBlast[15] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFE70
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceArcticBlast =
{
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
};
//D2Common.0x6FDDFF18
D2MonSeqTxt gPlayerSequenceDragonBreath[17] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFF80
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonBreath =
{
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
};
//D2Common.0x6FDE0028
D2MonSeqTxt gPlayerSequenceDragonFlight[23] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE00B8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonFlight =
{
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
};
//D2Common.0x6FDE0160
D2MonSeqTxt gPlayerSequenceUnmorph[16] =
{
{ 0, PLRMODE_SPECIAL1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE01C0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceUnmorph =
{
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
};
//D2Common.0x6FDE0268
D2MonSeqTxt gPlayerSequenceBladeFury[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE02E0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceBladeFury =
{
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
};
//D2Common.0x6FDE0388
D2PlayerWeaponSequencesStrc* gPlayerWeaponsSequenceTable[24] =
{
NULL,
&gPlayerWeaponsSequenceJab,
&gPlayerWeaponsSequenceSacrifice,
&gPlayerWeaponsSequenceChastise,
&gPlayerWeaponsSequenceCharge,
&gPlayerWeaponsSequenceDefiance,
&gPlayerWeaponsSequenceInferno,
&gPlayerWeaponsSequenceStrafe,
&gPlayerWeaponsSequenceImpale,
&gPlayerWeaponsSequenceFend,
&gPlayerWeaponsSequenceWhirlwind,
&gPlayerWeaponsSequenceDoubleSwing,
&gPlayerWeaponsSequenceLightning,
&gPlayerWeaponsSequenceLeap,
&gPlayerWeaponsSequenceLeapAttack,
&gPlayerWeaponsSequenceDoubleThrow,
&gPlayerWeaponsSequenceDragonClaw,
&gPlayerWeaponsSequenceProjection,
&gPlayerWeaponsSequenceArcticBlast,
&gPlayerWeaponsSequenceDragonTalon,
&gPlayerWeaponsSequenceDragonBreath,
&gPlayerWeaponsSequenceDragonFlight,
&gPlayerWeaponsSequenceUnmorph,
&gPlayerWeaponsSequenceBladeFury,
};
//D2Common.0x6FDE03E8
//Note: This should really just be an array since the indices are ordered anyway...
static const int gWeaponIndexToClassMap[14][2] =
{
{ 0, WEAPONCLASS_HTH },
{ 1, WEAPONCLASS_1HT },
{ 2, WEAPONCLASS_2HT },
{ 3, WEAPONCLASS_1HS },
{ 4, WEAPONCLASS_2HS },
{ 5, WEAPONCLASS_BOW },
{ 6, WEAPONCLASS_XBW },
{ 7, WEAPONCLASS_STF },
{ 8, WEAPONCLASS_1JS },
{ 9, WEAPONCLASS_1JT },
{ 10, WEAPONCLASS_1SS },
{ 11, WEAPONCLASS_1ST },
{ 12, WEAPONCLASS_HT1 },
{ 13, WEAPONCLASS_HT2 }
};
//D2Common.0x6FD727A0 (#10682)
D2MonSeqTxt* __stdcall DATATBLS_GetMonSeqTxtRecordFromUnit(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return pSeqRecord->pMonSeqTxtRecord;
}
return NULL;
}
//D2Common.0x6FD727C0
D2SeqRecordStrc* __fastcall DATATBLS_GetSeqRecordFromUnit(D2UnitStrc* pUnit)
{
if (D2SkillStrc* pSkill = UNITS_GetUsedSkill(pUnit))
{
int nSequenceNum = SKILLS_GetSeqNumFromSkill(pUnit, pSkill);
if (nSequenceNum > 0)
{
int nUnitType = UNIT_TYPES_COUNT;
if (pUnit)
{
nUnitType = pUnit->dwUnitType;
}
if (nUnitType == UNIT_PLAYER)
{
int nWeaponClass = WEAPONCLASS_HTH;
COMPOSIT_GetWeaponClassId(pUnit, pUnit->pInventory, &nWeaponClass, -1, TRUE);
int nWClassIndex = -1;
for (int i = 0; i < 14; i++)
{
if (nWeaponClass == gWeaponIndexToClassMap[i][1])
{
nWClassIndex = gWeaponIndexToClassMap[i][0];
break;
}
}
D2_ASSERT(nWClassIndex != -1);
return &gPlayerWeaponsSequenceTable[nSequenceNum]->weaponRecords[nWClassIndex];
}
else if (nUnitType == UNIT_MONSTER && DATATBLS_GetMonStatsTxtRecord(pUnit->dwClassId))
{
return DATATBLS_GetMonSeqTableRecord(nSequenceNum);
}
}
}
return NULL;
}
//D2Common.0x6FD728A0 (#10683)
int __stdcall DATATBLS_GetSeqFramePointsCount(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return (pSeqRecord->nSeqFramesCount << 8);
}
return 0;
}
//D2Common.0x6FD728C0 (#10684)
int __stdcall DATATBLS_GetSeqFrameCount(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return pSeqRecord->nFramesCount;
}
return 0;
}
//D2Common.0x6FD728E0 (#10685)
void __stdcall DATATBLS_ComputeSequenceAnimation(D2MonSeqTxt* pMonSeqTxt, int nTargetFramePoint, int nCurrentFramePoint, unsigned int* pMode, unsigned int* pFrame, int* pDirection, int* pEvent)
{
if (pMonSeqTxt)
{
const D2MonSeqTxt* pMonSeqTxtRecord = &pMonSeqTxt[nCurrentFramePoint >> 8];
*pMode = pMonSeqTxtRecord->nMode;
*pFrame = pMonSeqTxtRecord->nFrame;
*pDirection = pMonSeqTxtRecord->nDir;
if (nCurrentFramePoint == nTargetFramePoint)
{
*pEvent = pMonSeqTxtRecord->nEvent;
}
else // Retrieve the last event, note that it discard the intermediary events.
{
*pEvent = 0;
const int nNextFrame = (nCurrentFramePoint >> 8) + 1;
const int nTargetFrame = nTargetFramePoint >> 8;
for (int frameIdx = nNextFrame; frameIdx <= nTargetFrame; frameIdx++)
{
const D2MonSeqEvent nEvent = pMonSeqTxt[frameIdx].nEvent;
if (nEvent != MONSEQ_EVENT_NONE)
{
*pEvent = nEvent;
}
}
}
}
else
{
*pMode = 0;
*pFrame = 0;
*pDirection = 0;
*pEvent = MONSEQ_EVENT_NONE;
}
}
//D2Common.0x6FD72990 (#10686)
void __stdcall DATATBLS_GetSequenceEvent(D2MonSeqTxt* pMonSeqTxt, int nSeqFramePoint, int* pEvent)
{
if (pMonSeqTxt)
{
*pEvent = pMonSeqTxt[nSeqFramePoint >> 8].nEvent;
}
else
{
*pEvent = 0;
}
}
//D2Common.0x6FD6F050
void __fastcall DATATBLS_LoadMonSeqTxt(void* pMemPool)
{
D2BinFieldStrc pTbl[] =
{
{ "sequence", TXTFIELD_NAMETOINDEX, 0, 0, &sgptDataTables->pMonSeqLinker },
{ "mode", TXTFIELD_CODETOBYTE, 0, 2, &sgptDataTables->pMonModeLinker },
{ "frame", TXTFIELD_BYTE, 0, 3, NULL },
{ "dir", TXTFIELD_BYTE, 0, 4, NULL },
{ "event", TXTFIELD_BYTE, 0, 5, NULL },
{ "end", TXTFIELD_NONE, 0, 0, NULL },
};
sgptDataTables->pMonSeqLinker = (D2TxtLinkStrc*)FOG_AllocLinker(__FILE__, __LINE__);
sgptDataTables->pMonSeqTxt = (D2MonSeqTxt*)DATATBLS_CompileTxt(pMemPool, "monseq", pTbl, &sgptDataTables->nMonSeqTxtRecordCount, sizeof(D2MonSeqTxt));
if (sgptDataTables->nMonSeqTxtRecordCount > 0)
{
sgptDataTables->nMonSeqTableRecordCount = sgptDataTables->pMonSeqTxt[sgptDataTables->nMonSeqTxtRecordCount - 1].wSequence + 1;
sgptDataTables->pMonSeqTable = (D2SeqRecordStrc*)D2_CALLOC_SERVER(NULL, sizeof(D2SeqRecordStrc) * sgptDataTables->nMonSeqTableRecordCount);
for (int i = 0; i < sgptDataTables->nMonSeqTxtRecordCount; ++i)
{
int nSequence = sgptDataTables->pMonSeqTxt[i].wSequence;
if (!sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord)
{
sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord = &sgptDataTables->pMonSeqTxt[i];
}
++sgptDataTables->pMonSeqTable[nSequence].nSeqFramesCount;
++sgptDataTables->pMonSeqTable[nSequence].nFramesCount;
}
}
}
//D2Common.0x6FD6F200 (#11262)
D2SeqRecordStrc* __stdcall DATATBLS_GetMonSeqTableRecord(int nSequence)
{
if (nSequence >= 0 && nSequence < sgptDataTables->nMonSeqTableRecordCount)
{
return &sgptDataTables->pMonSeqTable[nSequence];
}
return NULL;
} | 35.615958 | 193 | 0.731748 |
ae06620b4145aff4fd7b6004b47eeef88f43cf26 | 1,656 | cpp | C++ | src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.hpp"
#include "coherence/util/ArrayList.hpp" // REVIEW
COH_OPEN_NAMESPACE6(coherence,component,net,extend,protocol,cache)
using coherence::util::ArrayList;
// ----- constructors -------------------------------------------------------
AbstractKeySetRequest::AbstractKeySetRequest()
: f_vCol(self())
{
}
// ----- PortableObject interface -------------------------------------------
void AbstractKeySetRequest::readExternal(PofReader::Handle hIn)
{
AbstractPofRequest::readExternal(hIn);
setKeySet(hIn->readCollection(1, ArrayList::create()));
}
void AbstractKeySetRequest::writeExternal(PofWriter::Handle hOut) const
{
AbstractPofRequest::writeExternal(hOut);
hOut->writeCollection(1, getKeySet());
//release state
// m_vCol = NULL; // c++ optimization uses FinalView and thus can't be released
}
// ----- Describable interface ----------------------------------------------
String::View AbstractKeySetRequest::getDescription() const
{
return COH_TO_STRING(super::getDescription() << ", KeySet=" << getKeySet());
}
// ----- accessors ----------------------------------------------------------
Collection::View AbstractKeySetRequest::getKeySet() const
{
return f_vCol;
}
void AbstractKeySetRequest::setKeySet(Collection::View vCol)
{
initialize(f_vCol, vCol);
}
COH_CLOSE_NAMESPACE6
| 25.476923 | 90 | 0.61715 |
ae08ccd123b4592a416711a9e6da05519e2606fb | 10,499 | cpp | C++ | src/kits/shared/JsonMessageWriter.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/kits/shared/JsonMessageWriter.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/kits/shared/JsonMessageWriter.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>
* Distributed under the terms of the MIT License.
*/
#include "JsonMessageWriter.h"
namespace BPrivate {
/*! The class and sub-classes of it are used as a stack internal to the
BJsonMessageWriter class. As the JSON is parsed, the stack of these
internal listeners follows the stack of the JSON parsing in terms of
containers; arrays and objects.
*/
class BStackedMessageEventListener : public BJsonEventListener {
public:
BStackedMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
uint32 messageWhat);
BStackedMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message);
~BStackedMessageEventListener();
bool Handle(const BJsonEvent& event);
void HandleError(status_t status, int32 line,
const char* message);
void Complete();
void AddMessage(BMessage* value);
status_t ErrorStatus();
virtual const char* NextItemName() = 0;
BStackedMessageEventListener*
Parent();
protected:
void AddBool(bool value);
void AddNull();
void AddDouble(double value);
void AddString(const char* value);
virtual bool WillAdd();
virtual void DidAdd();
void SetStackedListenerOnWriter(
BStackedMessageEventListener*
stackedListener);
BJsonMessageWriter* fWriter;
bool fOwnsMessage;
BStackedMessageEventListener
*fParent;
BMessage* fMessage;
};
class BStackedArrayMessageEventListener : public BStackedMessageEventListener {
public:
BStackedArrayMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent);
BStackedArrayMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message);
~BStackedArrayMessageEventListener();
bool Handle(const BJsonEvent& event);
const char* NextItemName();
protected:
void DidAdd();
private:
uint32 fCount;
BString fNextItemName;
};
class BStackedObjectMessageEventListener : public BStackedMessageEventListener {
public:
BStackedObjectMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent);
BStackedObjectMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message);
~BStackedObjectMessageEventListener();
bool Handle(const BJsonEvent& event);
const char* NextItemName();
protected:
bool WillAdd();
void DidAdd();
private:
BString fNextItemName;
};
} // namespace BPrivate
using BPrivate::BStackedMessageEventListener;
using BPrivate::BStackedArrayMessageEventListener;
using BPrivate::BStackedObjectMessageEventListener;
// #pragma mark - BStackedMessageEventListener
BStackedMessageEventListener::BStackedMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
uint32 messageWhat)
{
fWriter = writer;
fParent = parent;
fOwnsMessage = true;
fMessage = new BMessage(messageWhat);
}
BStackedMessageEventListener::BStackedMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message)
{
fWriter = writer;
fParent = parent;
fOwnsMessage = false;
fMessage = message;
}
BStackedMessageEventListener::~BStackedMessageEventListener()
{
if (fOwnsMessage)
delete fMessage;
}
bool
BStackedMessageEventListener::Handle(const BJsonEvent& event)
{
if (fWriter->ErrorStatus() != B_OK)
return false;
switch (event.EventType()) {
case B_JSON_NUMBER:
AddDouble(event.ContentDouble());
break;
case B_JSON_STRING:
AddString(event.Content());
break;
case B_JSON_TRUE:
AddBool(true);
break;
case B_JSON_FALSE:
AddBool(false);
break;
case B_JSON_NULL:
AddNull();
break;
case B_JSON_OBJECT_START:
{
SetStackedListenerOnWriter(new BStackedObjectMessageEventListener(
fWriter, this));
break;
}
case B_JSON_ARRAY_START:
{
SetStackedListenerOnWriter(new BStackedArrayMessageEventListener(
fWriter, this));
break;
}
default:
{
HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE,
"unexpected type of json item to add to container");
return false;
}
}
return ErrorStatus() == B_OK;
}
void
BStackedMessageEventListener::HandleError(status_t status, int32 line,
const char* message)
{
fWriter->HandleError(status, line, message);
}
void
BStackedMessageEventListener::Complete()
{
// illegal state.
HandleError(JSON_EVENT_LISTENER_ANY_LINE, B_NOT_ALLOWED,
"Complete() called on stacked message listener");
}
void
BStackedMessageEventListener::AddMessage(BMessage* message)
{
if (WillAdd()) {
fMessage->AddMessage(NextItemName(), message);
DidAdd();
}
}
status_t
BStackedMessageEventListener::ErrorStatus()
{
return fWriter->ErrorStatus();
}
BStackedMessageEventListener*
BStackedMessageEventListener::Parent()
{
return fParent;
}
void
BStackedMessageEventListener::AddBool(bool value)
{
if (WillAdd()) {
fMessage->AddBool(NextItemName(), value);
DidAdd();
}
}
void
BStackedMessageEventListener::AddNull()
{
if (WillAdd()) {
fMessage->AddPointer(NextItemName(), (void*)NULL);
DidAdd();
}
}
void
BStackedMessageEventListener::AddDouble(double value)
{
if (WillAdd()) {
fMessage->AddDouble(NextItemName(), value);
DidAdd();
}
}
void
BStackedMessageEventListener::AddString(const char* value)
{
if (WillAdd()) {
fMessage->AddString(NextItemName(), value);
DidAdd();
}
}
bool
BStackedMessageEventListener::WillAdd()
{
return true;
}
void
BStackedMessageEventListener::DidAdd()
{
// noop - present for overriding
}
void
BStackedMessageEventListener::SetStackedListenerOnWriter(
BStackedMessageEventListener* stackedListener)
{
fWriter->SetStackedListener(stackedListener);
}
// #pragma mark - BStackedArrayMessageEventListener
BStackedArrayMessageEventListener::BStackedArrayMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent)
:
BStackedMessageEventListener(writer, parent, B_JSON_MESSAGE_WHAT_ARRAY)
{
fCount = 0;
}
BStackedArrayMessageEventListener::BStackedArrayMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message)
:
BStackedMessageEventListener(writer, parent, message)
{
message->what = B_JSON_MESSAGE_WHAT_ARRAY;
fCount = 0;
}
BStackedArrayMessageEventListener::~BStackedArrayMessageEventListener()
{
}
bool
BStackedArrayMessageEventListener::Handle(const BJsonEvent& event)
{
if (fWriter->ErrorStatus() != B_OK)
return false;
switch (event.EventType()) {
case B_JSON_ARRAY_END:
{
if (fParent != NULL)
fParent->AddMessage(fMessage);
SetStackedListenerOnWriter(fParent);
delete this;
break;
}
default:
return BStackedMessageEventListener::Handle(event);
}
return true;
}
const char*
BStackedArrayMessageEventListener::NextItemName()
{
fNextItemName.SetToFormat("%" B_PRIu32, fCount);
return fNextItemName.String();
}
void
BStackedArrayMessageEventListener::DidAdd()
{
BStackedMessageEventListener::DidAdd();
fCount++;
}
// #pragma mark - BStackedObjectMessageEventListener
BStackedObjectMessageEventListener::BStackedObjectMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent)
:
BStackedMessageEventListener(writer, parent, B_JSON_MESSAGE_WHAT_OBJECT)
{
}
BStackedObjectMessageEventListener::BStackedObjectMessageEventListener(
BJsonMessageWriter* writer,
BStackedMessageEventListener* parent,
BMessage* message)
:
BStackedMessageEventListener(writer, parent, message)
{
message->what = B_JSON_MESSAGE_WHAT_OBJECT;
}
BStackedObjectMessageEventListener::~BStackedObjectMessageEventListener()
{
}
bool
BStackedObjectMessageEventListener::Handle(const BJsonEvent& event)
{
if (fWriter->ErrorStatus() != B_OK)
return false;
switch (event.EventType()) {
case B_JSON_OBJECT_END:
{
if (fParent != NULL)
fParent->AddMessage(fMessage);
SetStackedListenerOnWriter(fParent);
delete this;
break;
}
case B_JSON_OBJECT_NAME:
fNextItemName.SetTo(event.Content());
break;
default:
return BStackedMessageEventListener::Handle(event);
}
return true;
}
const char*
BStackedObjectMessageEventListener::NextItemName()
{
return fNextItemName.String();
}
bool
BStackedObjectMessageEventListener::WillAdd()
{
if (0 == fNextItemName.Length()) {
HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE,
"missing name for adding value into an object");
return false;
}
return true;
}
void
BStackedObjectMessageEventListener::DidAdd()
{
BStackedMessageEventListener::DidAdd();
fNextItemName.SetTo("", 0);
}
// #pragma mark - BJsonMessageWriter
BJsonMessageWriter::BJsonMessageWriter(BMessage& message)
{
fTopLevelMessage = &message;
fStackedListener = NULL;
}
BJsonMessageWriter::~BJsonMessageWriter()
{
BStackedMessageEventListener* listener = fStackedListener;
while (listener != NULL) {
BStackedMessageEventListener* nextListener = listener->Parent();
delete listener;
listener = nextListener;
}
fStackedListener = NULL;
}
bool
BJsonMessageWriter::Handle(const BJsonEvent& event)
{
if (fErrorStatus != B_OK)
return false;
if (fStackedListener != NULL)
return fStackedListener->Handle(event);
else {
switch(event.EventType()) {
case B_JSON_OBJECT_START:
{
SetStackedListener(new BStackedObjectMessageEventListener(
this, NULL, fTopLevelMessage));
break;
}
case B_JSON_ARRAY_START:
{
fTopLevelMessage->what = B_JSON_MESSAGE_WHAT_ARRAY;
SetStackedListener(new BStackedArrayMessageEventListener(
this, NULL, fTopLevelMessage));
break;
}
default:
{
HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE,
"a message object can only handle an object or an array"
"at the top level");
return false;
}
}
}
return true; // keep going
}
void
BJsonMessageWriter::Complete()
{
if (fStackedListener != NULL) {
HandleError(B_BAD_DATA, JSON_EVENT_LISTENER_ANY_LINE,
"unexpected end of input data processing structure");
}
}
void
BJsonMessageWriter::SetStackedListener(
BStackedMessageEventListener* listener)
{
fStackedListener = listener;
} | 19.51487 | 80 | 0.740832 |
ae09b5ccdd4d276517f3989a7ce916f5813cb65a | 74 | cpp | C++ | src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 8 | 2017-06-05T08:56:27.000Z | 2020-04-08T16:50:11.000Z | src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | null | null | null | src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 17 | 2017-06-05T08:54:27.000Z | 2021-08-29T14:19:12.000Z | #include "Attributes.h"
ACEXML_Attributes::~ACEXML_Attributes (void)
{
}
| 12.333333 | 44 | 0.756757 |
ae0b0290fe09ecf6f5ea2fc4f9bf9531d0dc0b63 | 4,759 | cpp | C++ | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "components/ui_toggle_button.h"
#include "common/image.h"
#include "draw/draw_arc.h"
#include "draw/draw_rect.h"
#include "imgdecode/cache_manager.h"
namespace OHOS {
UIToggleButton::UIToggleButton() : width_(DEFAULT_HOT_WIDTH), height_(DEFAULT_HOT_WIDTH),
corner_(DEFAULT_CORNER_RADIUS), radius_(DEFAULT_CORNER_RADIUS - DEAFULT_RADIUS_DIFF),
rectWidth_(DEFAULT_WIDTH)
{
image_[UNSELECTED].SetSrc("");
image_[SELECTED].SetSrc("");
Resize(width_, height_);
}
void UIToggleButton::SetState(bool state)
{
if (state) {
UICheckBox::SetState(SELECTED);
} else {
UICheckBox::SetState(UNSELECTED);
}
Invalidate();
}
void UIToggleButton::CalculateSize()
{
int16_t width = GetWidth();
int16_t height = GetHeight();
if ((width_ == width) && (height_ == height)) {
return;
}
width_ = width;
height_ = height;
int16_t minValue = (width_ > height_) ? height_ : width_;
corner_ = DEFAULT_CORNER_RADIUS * minValue / DEFAULT_HOT_HEIGHT;
int16_t radiusDiff = DEAFULT_RADIUS_DIFF * minValue / DEFAULT_HOT_WIDTH;
radius_ = corner_ - radiusDiff;
rectWidth_ = DEFAULT_WIDTH * minValue / DEFAULT_HOT_WIDTH;
}
void UIToggleButton::OnDraw(const Rect& invalidatedArea)
{
if ((image_[SELECTED].GetSrcType() != IMG_SRC_UNKNOWN) && (image_[UNSELECTED].GetSrcType() != IMG_SRC_UNKNOWN)) {
UICheckBox::OnDraw(invalidatedArea);
} else {
CalculateSize();
DrawRect::Draw(GetRect(), invalidatedArea, *style_, opaScale_);
Rect contentRect = GetContentRect();
int16_t dx = (width_ - rectWidth_) >> 1;
int16_t dy = (height_ >> 1) - corner_;
int16_t x = contentRect.GetX() + dx;
int16_t y = contentRect.GetY() + dy;
Rect rectMid;
rectMid.SetRect(x, y, x + rectWidth_, y + (corner_ << 1) + 1);
Rect trunc = invalidatedArea;
bool isIntersect = trunc.Intersect(trunc, contentRect);
switch (state_) {
case SELECTED: {
Style styleSelect = StyleDefault::GetBackgroundTransparentStyle();
styleSelect.borderRadius_ = corner_;
styleSelect.bgColor_ = Color::GetColorFromRGB(DEFAULT_BG_RED, DEFAULT_BG_GREEN, DEFAULT_BG_BLUE);
styleSelect.bgOpa_ = OPA_OPAQUE;
if (isIntersect) {
DrawRect::Draw(rectMid, trunc, styleSelect, opaScale_);
}
ArcInfo arcInfoRight = {
{ static_cast<int16_t>(x + rectWidth_ - corner_), static_cast<int16_t>(y + corner_) }, { 0 },
radius_, 0, CIRCLE_IN_DEGREE, nullptr
};
styleSelect.bgColor_ = Color::White();
styleSelect.lineWidth_ = radius_;
styleSelect.lineColor_ = Color::White();
if (isIntersect) {
DrawArc::GetInstance()->Draw(arcInfoRight, trunc, styleSelect, OPA_OPAQUE, CapType::CAP_NONE);
}
break;
}
case UNSELECTED: {
Style styleUnSelect = StyleDefault::GetBackgroundTransparentStyle();
styleUnSelect.bgColor_ = Color::White();
styleUnSelect.bgOpa_ = DEFAULT_UNSELECTED_OPA;
styleUnSelect.borderRadius_ = corner_;
if (isIntersect) {
DrawRect::Draw(rectMid, trunc, styleUnSelect, opaScale_);
}
ArcInfo arcInfoLeft = {
{ static_cast<int16_t>(x + corner_), static_cast<int16_t>(y + corner_) }, { 0 }, radius_, 0,
CIRCLE_IN_DEGREE, nullptr
};
styleUnSelect.lineColor_ = Color::White();
styleUnSelect.lineWidth_ = radius_;
if (isIntersect) {
DrawArc::GetInstance()->Draw(arcInfoLeft, trunc, styleUnSelect, OPA_OPAQUE, CapType::CAP_NONE);
}
break;
}
default:
break;
}
}
}
} // namespace OHOS | 39.991597 | 120 | 0.600336 |
ae0bd9b41366661e5c83824971bbd8235099a335 | 1,027 | cpp | C++ | extractor/Utils/DBCReader.cpp | avennstrom/NovusCore-Tools | 03c2bd1ee8e6b865498b4d489ac962b0f168ad59 | [
"MIT"
] | null | null | null | extractor/Utils/DBCReader.cpp | avennstrom/NovusCore-Tools | 03c2bd1ee8e6b865498b4d489ac962b0f168ad59 | [
"MIT"
] | 2 | 2020-01-16T13:58:44.000Z | 2020-07-01T11:37:00.000Z | extractor/Utils/DBCReader.cpp | avennstrom/NovusCore-Tools | 03c2bd1ee8e6b865498b4d489ac962b0f168ad59 | [
"MIT"
] | 5 | 2020-01-16T13:56:44.000Z | 2021-12-20T22:16:08.000Z | #include "DBCReader.h"
/*
1 = Can't open file
2 = Invalid format
3 = Invalid data / string size read
*/
int DBCReader::Load(std::shared_ptr<Bytebuffer> buffer)
{
u32 header = 0;
buffer->GetU32(header);
// Check for WDBC header
if (header != NOVUSDBC_WDBC_TOKEN)
return 2;
try
{
buffer->GetU32(_rowCount);
buffer->GetU32(_fieldCount);
buffer->GetU32(_rowSize);
buffer->GetU32(_stringSize);
}
catch (std::exception)
{
return 2;
}
// Cleanup Memory if we've previously loaded DBC Files
if (_data)
{
delete[] _data;
}
u32 dataSize = _rowSize * _rowCount + _stringSize;
_data = new unsigned char[dataSize];
std::memset(_data, 0, dataSize);
_stringTable = _data + _rowSize * _rowCount;
if (!_data || !_stringTable)
return 3;
buffer->GetBytes(_data, dataSize);
return 0;
}
DBCReader::DBCRow DBCReader::GetRow(u32 id)
{
return DBCRow(*this, _data + id * _rowSize);
} | 20.137255 | 58 | 0.6037 |
ae1126f4317e7224849ef4da6c39a7f628d6738e | 523 | cpp | C++ | exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | #include <iostream>
//Source: https://www.youtube.com/watch?v=6uqU9Y578n4
struct Vector2 {
float x, y;
};
struct Vector4 {
union {
struct {
float x, y, z, w;
};
struct {
Vector2 a, b;
};
};
};
void printVector2(const Vector2& vector) {
std::cout << "( " << vector.x << ", " << vector.y << " )" << std::endl;
}
int main() {
Vector4 vec = { 1.0f, 2.0f, 3.0f, 4.0f };
printVector2(vec.a);
std::cout << "----------------------" << std::endl;
vec.z = 500.0f;
printVector2(vec.b);
return 0;
}
| 14.527778 | 72 | 0.529637 |
ae1a3eda22f78d49e393cd55afd7741c7a2d39b9 | 1,194 | cpp | C++ | BATS/code/BTHAIModule/Source/NexusAgent.cpp | Senth/bats | 51d4ec39f3a118ed0eb90ec27a1864c0ceef3898 | [
"Apache-2.0"
] | null | null | null | BATS/code/BTHAIModule/Source/NexusAgent.cpp | Senth/bats | 51d4ec39f3a118ed0eb90ec27a1864c0ceef3898 | [
"Apache-2.0"
] | null | null | null | BATS/code/BTHAIModule/Source/NexusAgent.cpp | Senth/bats | 51d4ec39f3a118ed0eb90ec27a1864c0ceef3898 | [
"Apache-2.0"
] | null | null | null | #include "NexusAgent.h"
#include "AgentManager.h"
#include "WorkerAgent.h"
#include "PFManager.h"
#include "BatsModule/include/BuildPlanner.h"
#include "ResourceManager.h"
using namespace BWAPI;
using namespace std;
NexusAgent::NexusAgent(Unit* mUnit) : StructureAgent(mUnit)
{
agentType = "NexusAgent";
hasSentWorkers = false;
if (AgentManager::getInstance()->countNoUnits(UnitTypes::Protoss_Nexus) == 0)
{
//We dont do this for the first Nexus.
hasSentWorkers = true;
}
}
void NexusAgent::computeActions()
{
if (!hasSentWorkers)
{
if (!unit->isBeingConstructed())
{
sendWorkers();
hasSentWorkers = true;
bats::BuildPlanner::getInstance()->addRefinery();
if (AgentManager::getInstance()->countNoUnits(UnitTypes::Protoss_Forge) > 0)
{
bats::BuildPlanner::getInstance()->addItemFirst(UnitTypes::Protoss_Pylon);
bats::BuildPlanner::getInstance()->addItemFirst(UnitTypes::Protoss_Photon_Cannon);
}
}
}
if (!unit->isIdle())
{
//Already doing something
return;
}
if (ResourceManager::getInstance()->needWorker())
{
UnitType worker = Broodwar->self()->getRace().getWorker();
if (canBuild(worker))
{
unit->train(worker);
}
}
}
| 20.947368 | 86 | 0.701005 |
ae1c06878dbfac75a332fd6c4f0ac34da9229d79 | 19 | cpp | C++ | src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 387 | 2017-10-14T23:08:59.000Z | 2022-03-28T05:26:44.000Z | src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 246 | 2017-10-09T11:40:20.000Z | 2022-03-22T08:04:08.000Z | src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 113 | 2017-10-18T12:04:53.000Z | 2022-03-28T09:05:27.000Z | #include "tensor.h" | 19 | 19 | 0.736842 |
ae1df20fd6c4d4f350682072ec4175a62b66a344 | 6,242 | cc | C++ | bwidgets/widgets/bwNumberSlider.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 72 | 2018-03-26T20:13:47.000Z | 2022-03-08T15:59:55.000Z | bwidgets/widgets/bwNumberSlider.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 12 | 2018-03-30T12:54:15.000Z | 2021-05-30T23:33:01.000Z | bwidgets/widgets/bwNumberSlider.cc | julianeisel/bWidgets | 35695df104f77b35992013a5602adf2723ab1022 | [
"MIT"
] | 10 | 2018-03-26T23:04:06.000Z | 2021-11-17T21:04:27.000Z | #include <algorithm>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "bwEvent.h"
#include "bwPainter.h"
#include "bwStyle.h"
#include "bwNumberSlider.h"
namespace bWidgets {
bwNumberSlider::bwNumberSlider(std::optional<unsigned int> width_hint,
std::optional<unsigned int> height_hint)
: bwTextBox(width_hint, height_hint), precision(2)
{
}
auto bwNumberSlider::getTypeIdentifier() const -> std::string_view
{
return "bwNumberSlider";
}
void bwNumberSlider::draw(bwStyle& style)
{
bwPainter painter;
bwRectanglePixel inner_rect = rectangle;
const float radius = base_style.corner_radius * style.dpi_fac;
// Inner - "inside" of outline, so scale down
inner_rect.resize(-1);
painter.setContentMask(inner_rect);
painter.enableGradient(
bwGradient(base_style.backgroundColor(), base_style.shadeTop(), base_style.shadeBottom()));
painter.drawRoundbox(inner_rect, base_style.roundbox_corners, radius - 1.0f);
painter.active_drawtype = bwPainter::DrawType::FILLED;
// Text editing
if (is_text_editing) {
// Selection drawing
painter.setActiveColor(base_style.decorationColor());
painter.drawRectangle(selection_rectangle);
}
else {
drawValueIndicator(painter, style);
}
// Outline
painter.setActiveColor(base_style.borderColor());
painter.active_drawtype = bwPainter::DrawType::OUTLINE;
painter.drawRoundbox(rectangle, base_style.roundbox_corners, radius);
painter.setActiveColor(base_style.textColor());
if (!is_text_editing) {
painter.drawText(text, rectangle, base_style.text_alignment);
}
painter.drawText(valueToString(precision),
rectangle,
is_text_editing ? TextAlignment::LEFT : TextAlignment::RIGHT);
}
void bwNumberSlider::drawValueIndicator(bwPainter& painter, bwStyle& style) const
{
bwGradient gradient = bwGradient(base_style.decorationColor(),
// shadeTop/Bottom intentionally inverted
base_style.shadeBottom(),
base_style.shadeTop());
bwRectanglePixel indicator_offset_rect = rectangle;
bwRectanglePixel indicator_rect = rectangle;
unsigned int roundbox_corners = base_style.roundbox_corners;
const float radius = base_style.corner_radius * style.dpi_fac;
float right_side_radius = radius;
indicator_offset_rect.xmax = indicator_offset_rect.xmin + right_side_radius;
indicator_rect.xmin = indicator_offset_rect.xmax;
indicator_rect.xmax = indicator_rect.xmin + calcValueIndicatorWidth(style);
if (indicator_rect.xmax > (rectangle.xmax - right_side_radius)) {
right_side_radius *= (indicator_rect.xmax + right_side_radius - rectangle.xmax) /
right_side_radius;
}
else {
roundbox_corners &= ~(TOP_RIGHT | BOTTOM_RIGHT);
}
painter.enableGradient(gradient);
painter.drawRoundbox(
indicator_offset_rect, roundbox_corners & ~(TOP_RIGHT | BOTTOM_RIGHT), radius);
painter.drawRoundbox(
indicator_rect, roundbox_corners & ~(TOP_LEFT | BOTTOM_LEFT), right_side_radius);
}
auto bwNumberSlider::setValue(float _value) -> bwNumberSlider&
{
const int precision_fac = std::pow(10, precision);
const float unclamped_value = std::max(min, std::min(max, _value));
value = std::roundf(unclamped_value * precision_fac) / precision_fac;
return *this;
}
auto bwNumberSlider::getValue() const -> float
{
return value;
}
auto bwNumberSlider::setMinMax(float _min, float _max) -> bwNumberSlider&
{
min = _min;
max = _max;
return *this;
}
auto bwNumberSlider::valueToString(unsigned int precision) const -> std::string
{
std::stringstream string_stream;
string_stream << std::fixed << std::setprecision(precision) << value;
return string_stream.str();
}
auto bwNumberSlider::calcValueIndicatorWidth(bwStyle& style) const -> float
{
const float range = max - min;
const float radius = base_style.corner_radius * style.dpi_fac;
assert(max > min);
return ((value - min) * (rectangle.width() - radius)) / range;
}
// ------------------ Handling ------------------
class bwNumberSliderHandler : public bwTextBoxHandler {
public:
bwNumberSliderHandler(bwNumberSlider& numberslider);
~bwNumberSliderHandler() = default;
void onMousePress(bwMouseButtonEvent&) override;
void onMouseRelease(bwMouseButtonEvent&) override;
void onMouseClick(bwMouseButtonEvent&) override;
void onMouseDrag(bwMouseButtonDragEvent&) override;
private:
bwNumberSlider& numberslider;
// Initial value before starting to edit.
float initial_value;
};
bwNumberSliderHandler::bwNumberSliderHandler(bwNumberSlider& numberslider)
: bwTextBoxHandler(numberslider), numberslider(numberslider)
{
}
auto bwNumberSlider::createHandler() -> std::unique_ptr<bwScreenGraph::EventHandler>
{
return std::make_unique<bwNumberSliderHandler>(*this);
}
void bwNumberSliderHandler::onMousePress(bwMouseButtonEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
initial_value = numberslider.value;
numberslider.setState(bwWidget::State::SUNKEN);
event.swallow();
}
else if (event.button == bwMouseButtonEvent::Button::RIGHT) {
if (numberslider.is_text_editing) {
endTextEditing();
}
else if (is_dragging) {
numberslider.value = initial_value;
}
event.swallow();
}
}
void bwNumberSliderHandler::onMouseRelease(bwMouseButtonEvent& event)
{
if (is_dragging) {
numberslider.setState(bwWidget::State::NORMAL);
}
is_dragging = false;
event.swallow();
}
void bwNumberSliderHandler::onMouseClick(bwMouseButtonEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
startTextEditing();
}
event.swallow();
}
void bwNumberSliderHandler::onMouseDrag(bwMouseButtonDragEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
numberslider.setValue(initial_value +
(event.drag_distance.x / (float)numberslider.rectangle.width()));
if (numberslider.apply_functor) {
(*numberslider.apply_functor)();
}
is_dragging = true;
event.swallow();
}
}
} // namespace bWidgets
| 28.372727 | 97 | 0.716437 |
ae1f29f88c6f05e3560317369e6deaca5e2fb449 | 324 | cpp | C++ | Sirul_Retardat/Sirul_Retardat.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | Sirul_Retardat/Sirul_Retardat.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | Sirul_Retardat/Sirul_Retardat.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main ()
{
int n, x, y, z, v[10001];
cin >> n >> x >> y >> z;
v[1] = x;
v[2] = y;
v[3] = z;
for (int i = 4; i <= n; ++i)
{
v[i] = v[i - 1] + v[i - 2] - v[i - 3];
}
for (int i = n; i >= 1; --i)
{
cout << v[i] << " ";
}
} | 17.052632 | 46 | 0.330247 |
ae1fcacb9a1c8125da9eda8a38dbe2fb5d748bfa | 95,361 | cpp | C++ | v3d_main/neuron_annotator/gui/NaMainWindow.cpp | hanchuan/vaa3d_external | d6381572dec4079705ac5d3e39c9556b50472403 | [
"MIT"
] | null | null | null | v3d_main/neuron_annotator/gui/NaMainWindow.cpp | hanchuan/vaa3d_external | d6381572dec4079705ac5d3e39c9556b50472403 | [
"MIT"
] | null | null | null | v3d_main/neuron_annotator/gui/NaMainWindow.cpp | hanchuan/vaa3d_external | d6381572dec4079705ac5d3e39c9556b50472403 | [
"MIT"
] | null | null | null | // Fix windows compile problem with windows.h being included too late.
// I wish it wasn't included at all...
#ifdef _MSC_VER
#define NOMINMAX //added by PHC, 2010-05-20 to overcome VC min max macro
#include <windows.h>
#endif
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <iostream>
#include <cmath>
#include <cassert>
#include "NaMainWindow.h"
#include "Na3DWidget.h"
#include "ui_NaMainWindow.h"
#include "../../basic_c_fun/v3d_message.h"
#include "../../v3d/v3d_application.h"
#include "../DataFlowModel.h"
#include "../MultiColorImageStackNode.h"
#include "../NeuronAnnotatorResultNode.h"
#include "../TimebasedIdentifierGenerator.h"
#include "RendererNeuronAnnotator.h"
#include "GalleryButton.h"
#include "../../cell_counter/CellCounter3D.h"
#include "../NeuronSelector.h"
#include "FragmentGalleryWidget.h"
#include "AnnotationWidget.h"
#include "../utility/loadV3dFFMpeg.h"
#include "PreferencesDialog.h"
#include "../utility/FooDebug.h"
#include "../utility/url_tools.h"
#include <cstdlib> // getenv
using namespace std;
using namespace jfrc;
//////////////////
// NutateThread //
//////////////////
NutateThread::NutateThread(qreal cyclesPerSecond, QObject * parentObj /* = NULL */)
: QThread(parentObj)
, speed(cyclesPerSecond)
, interval(0.200) // update every 200 milliseconds
, currentAngle(0.0)
{
deltaAngle = 2.0 * 3.14159 * cyclesPerSecond * interval;
}
void NutateThread::run()
{
while(true) {
if (paused) {
msleep(500);
continue;
}
// qDebug() << "nutation angle = " << currentAngle;
rot = deltaNutation(currentAngle, deltaAngle);
emit nutate(rot);
currentAngle += deltaAngle;
while (currentAngle > 2.0 * 3.14159) currentAngle -= 2.0 * 3.14159;
msleep( (1000.0 * deltaAngle) / (2.0 * 3.14159 * speed) );
}
}
void NutateThread::pause() {paused = true;}
void NutateThread::unpause() {paused = false;}
//////////////////
// NaMainWindow //
//////////////////
inline const char * getConsolePort()
{
const char *port;
port = getenv("WORKSTATION_SERVICE_PORT");
if(NULL == port) port = "30001";
return port;
}
NaMainWindow::NaMainWindow(QWidget * parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
, ui(new Ui::NaMainWindow)
, nutateThread(NULL)
, statusProgressBar(NULL)
, neuronSelector(this)
, undoStack(NULL)
, showAllNeuronsInEmptySpaceAction(NULL)
, hideAllAction(NULL)
, selectNoneAction(NULL)
, neuronContextMenu(NULL)
, viewerContextMenu(NULL)
, recentViewer(VIEWER_3D)
, dynamicRangeTool(NULL)
, isInCustomCutMode(false)
, bShowCrosshair(true) // default to on
, viewMode(VIEW_SINGLE_STACK)
, cutPlanner(NULL)
{
const char* port = getConsolePort();
qDebug() << "Using console port: " << port;
QString qport(port);
QString url = QString("http://localhost:%1/axis2/services/cds").arg(port);
consoleUrl = new char[url.length() + 1];
QByteArray ba = url.toUtf8();
strcpy(consoleUrl, ba.data());
qDebug() << "Using console URL: " << consoleUrl;
// Set up potential 3D stereo modes before creating QGLWidget.
#ifdef ENABLE_STEREO
QGLFormat glFormat = QGLFormat::defaultFormat();
glFormat.setStereo(true);
glFormat.setDoubleBuffer(true);
if (glFormat.stereo()) {
// qDebug() << "Attempting to set 3D stereo format";
}
else {
// qDebug() << "Failed to make stereo 3D default QGLFormat";
}
QGLFormat::setDefaultFormat(glFormat);
#endif
recentFileActions.fill(NULL, NaMainWindow::maxRecentFiles);
ui->setupUi(this);
setAcceptDrops(true);
// Z value comes from camera model
qRegisterMetaType<Vector3D>("Vector3D");
// hide neuron gallery until there are neurons to show
setViewMode(VIEW_SINGLE_STACK);
// ui->mipsFrame->setVisible(false);
// hide compartment map until it works correctly and is not so slow on Mac
ui->compartmentSelectGroupBox->hide();
dataFlowModel=0;
// TODO - neuronSelector should probably be a member of Na3DViewer, not of NaMainWindow
// neuronSelector = new NeuronSelector(this);
// Create stubs for recent file menu
for (int i = 0; i < maxRecentFiles; ++i) {
recentFileActions[i] = new OpenFileAction(this);
ui->menuOpen_Recent->addAction(recentFileActions[i]);
recentFileActions[i]->setVisible(false);
connect(recentFileActions[i], SIGNAL(openFileRequested(QString)),
this, SLOT(openFileOrUrl(QString)));
}
updateRecentFileActions();
// Create an area in the status bar for progress messages.
statusProgressMessage = new QLabel(NULL);
statusBar()->addWidget(statusProgressMessage);
statusProgressBar = new QProgressBar(NULL);
statusProgressBar->setValue(0);
statusProgressBar->setMinimum(0);
statusProgressBar->setMaximum(100);
statusBar()->addWidget(statusProgressBar);
statusProgressBar->hide();
statusProgressMessage->hide();
// hide progress bar for 3d viewer until it is needed
ui->widget_progress3d->hide();
// hide the File->Open 3D Image stack menu item
ui->menuFile->removeAction(ui->actionLoad_Tiff);
ui->menuFile->removeAction(ui->actionCell_Counter_3D_2ch_lsm);
// hide dev-version rotate-X movie maker, until it become more user-friendly
ui->menuExport->removeAction(ui->actionX_Rotation_Movie);
// hide fps option: it's for debugging
ui->menuView->removeAction(ui->actionMeasure_Frame_Rate);
// hide octree test item
ui->menuFile->removeAction(ui->actionOpen_Octree_Volume);
#ifdef USE_FFMPEG
ui->actionLoad_movie_as_texture->setVisible(true);
ui->actionLoad_fast_separation_result->setVisible(true);
#else
ui->actionLoad_movie_as_texture->setVisible(false);
ui->actionLoad_fast_separation_result->setVisible(false);
#endif
// visualize compartment map
//QDockWidget *dock = new QDockWidget(tr("Compartment Map"), this);
//dock->setWidget( ui->compartmentMapWidget);
qRegisterMetaType<QList<LabelSurf> >("QList<LabelSurf>");
ui->compartmentMapWidget->setComboBox(ui->compartmentMapComboBox);
connect(ui->compartmentMapComboBox, SIGNAL(currentIndexChanged(int)), ui->compartmentMapWidget, SLOT(switchCompartment(int)));
//connect(ui->compartmentMapWidget, SIGNAL(viscomp3dview(QList<LabelSurf>)), (Renderer_gl1*)(ui->v3dr_glwidget->getRenderer()), SLOT(setListLabelSurf(QList<LabelSurf>))); // vis compartments in Na3Dviewer
// Wire up MIP viewer
// Status bar message
connect(ui->naLargeMIPWidget, SIGNAL(statusMessage(const QString&)),
statusBar(), SLOT(showMessage(const QString&)));
connect(ui->naZStackWidget, SIGNAL(statusMessage(const QString&)),
statusBar(), SLOT(showMessage(const QString&)));
ui->progressWidgetMip->hide();
connect(ui->naLargeMIPWidget, SIGNAL(showProgress()),
ui->progressWidgetMip, SLOT(show()));
connect(ui->naLargeMIPWidget, SIGNAL(hideProgress()),
ui->progressWidgetMip, SLOT(hide()));
connect(ui->naLargeMIPWidget, SIGNAL(setProgressMax(int)),
ui->progressBarMip, SLOT(setMaximum(int)));
connect(ui->naLargeMIPWidget, SIGNAL(setProgress(int)),
ui->progressBarMip, SLOT(setValue(int)));
ui->progressWidgetZ->hide();
// ui->gammaWidget_Zstack->hide();
// Distinguish the two gamma sliders
ui->sharedGammaWidget->gamma_label->setText("N "); // "neurons"
ui->sharedGammaWidget->setToolTip(tr("Brightness/gamma of data"));
ui->referenceGammaWidget->gamma_label->setText("R "); // "reference"
ui->referenceGammaWidget->setToolTip(tr("Brightness/gamma of reference channel"));
ui->BoxSize_spinBox->setMinimum(NaZStackWidget::minHdrBoxSize);
// Wire up Z-stack / HDR viewer
connect(ui->HDR_checkBox, SIGNAL(toggled(bool)),
ui->naZStackWidget, SLOT(setHDRCheckState(bool)));
connect(ui->naZStackWidget, SIGNAL(changedHDRCheckState(bool)),
ui->HDR_checkBox, SLOT(setChecked(bool)));
connect(ui->HDRRed_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setRedChannel()));
connect(ui->HDRGreen_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setGreenChannel()));
connect(ui->HDRBlue_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setBlueChannel()));
connect(ui->HDRNc82_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setNc82Channel()));
connect(ui->naZStackWidget, SIGNAL(curColorChannelChanged(NaZStackWidget::Color)),
this, SLOT(onHdrChannelChanged(NaZStackWidget::Color)));
ui->naZStackWidget->setHDRCheckState(false);
connect(ui->ZSlice_horizontalScrollBar, SIGNAL(valueChanged(int)),
ui->naZStackWidget, SLOT(setCurrentZSlice(int)));
connect(ui->naZStackWidget, SIGNAL(curZsliceChanged(int)),
ui->ZSlice_horizontalScrollBar, SLOT(setValue(int)));
connect(ui->BoxSize_spinBox, SIGNAL(valueChanged(int)),
ui->naZStackWidget, SLOT(setHdrBoxSize(int)));
connect(ui->naZStackWidget, SIGNAL(hdrBoxSizeChanged(int)),
ui->BoxSize_spinBox, SLOT(setValue(int)));
// 3D viewer
connect(ui->rotationResetButton, SIGNAL(clicked()),
ui->v3dr_glwidget, SLOT(resetRotation()));
connect(ui->nutateButton, SIGNAL(toggled(bool)),
this, SLOT(setNutate(bool)));
connect(this, SIGNAL(nutatingChanged(bool)),
ui->nutateButton, SLOT(setChecked(bool)));
connect(ui->actionAnimate_3D_nutation, SIGNAL(toggled(bool)),
this, SLOT(setNutate(bool)));
connect(this, SIGNAL(nutatingChanged(bool)),
ui->actionAnimate_3D_nutation, SLOT(setChecked(bool)));
connect(ui->v3dr_glwidget, SIGNAL(signalTextureLoaded()),
this, SLOT(onDataLoadFinished()));
/* obsolete. now we toggle channels.
connect(ui->redToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelR(bool)));
connect(ui->greenToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelG(bool)));
connect(ui->blueToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelB(bool)));
*/
// 3D rotation
// synchronize compartment map
connect(&sharedCameraModel, SIGNAL(rotationChanged(const Rotation3D&)),
ui->compartmentMapWidget, SLOT(setRotation(const Rotation3D&)));
// connect(&sharedCameraModel, SIGNAL(focusChanged(const Vector3D&)),
// ui->compartmentMapWidget, SLOT(setFocus(const Vector3D&)));
connect(&(ui->v3dr_glwidget->cameraModel), SIGNAL(rotationChanged(const Rotation3D&)),
this, SLOT(on3DViewerRotationChanged(const Rotation3D&)));
connect(ui->rotXWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->rotYWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->rotZWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->v3dr_glwidget, SIGNAL(progressValueChanged(int)),
this, SLOT(set3DProgress(int)));
connect(ui->v3dr_glwidget, SIGNAL(progressComplete()),
this, SLOT(complete3DProgress()));
connect(ui->v3dr_glwidget, SIGNAL(progressMessageChanged(QString)),
this, SLOT(set3DProgressMessage(QString)));
connect(ui->v3dr_glwidget, SIGNAL(progressAborted(QString)),
this, SLOT(complete3DProgress()));
// 3D volume cut
connect(ui->v3dr_glwidget, SIGNAL(changeXCut0(int)), ui->XcminSlider, SLOT(setValue(int))); // x-cut
connect(ui->XcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeXCut1(int)), ui->XcmaxSlider, SLOT(setValue(int)));
connect(ui->XcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut1(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeYCut0(int)), ui->YcminSlider, SLOT(setValue(int))); // y-cut
connect(ui->YcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeYCut1(int)), ui->YcmaxSlider, SLOT(setValue(int)));
connect(ui->YcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut1(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeZCut0(int)), ui->ZcminSlider, SLOT(setValue(int))); // z-cut
connect(ui->ZcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeZCut1(int)), ui->ZcmaxSlider, SLOT(setValue(int)));
connect(ui->ZcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut1(int)));
connect(ui->XCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setXCutLock(int)));
connect(ui->YCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setYCutLock(int)));
connect(ui->ZCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setZCutLock(int)));
connect(ui->slabThicknessSlider, SIGNAL(valueChanged(int)),
ui->v3dr_glwidget, SLOT(setSlabThickness(int)));
connect(ui->slabPositionSlider, SIGNAL(valueChanged(int)),
ui->v3dr_glwidget, SLOT(setSlabPosition(int)));
connect(ui->v3dr_glwidget, SIGNAL(slabThicknessChanged(int)),
this, SLOT(onSlabThicknessChanged(int)));
// ui->slabThicknessSlider, SLOT(setValue(int)));
connect(ui->v3dr_glwidget, SIGNAL(slabPositionChanged(int)),
ui->slabPositionSlider, SLOT(setValue(int)));
connect(ui->freezeFrontBackButton, SIGNAL(clicked()),
ui->v3dr_glwidget, SLOT(clipSlab()));
// alpha blending
connect(ui->action3D_alpha_blending, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setAlphaBlending(bool)));
connect(ui->v3dr_glwidget, SIGNAL(alphaBlendingChanged(bool)),
ui->action3D_alpha_blending, SLOT(setChecked(bool)));
// show axes
connect(ui->actionShow_Axes, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setShowCornerAxes(bool)));
// Whether to use common zoom and focus in MIP, ZStack and 3D viewers
connect(ui->actionLink_viewers, SIGNAL(toggled(bool)),
this, SLOT(unifyCameras(bool)));
unifyCameras(true); // Start with cameras linked
connect(ui->resetViewButton, SIGNAL(clicked()),
this, SLOT(resetView()));
connect(ui->zoomWidget, SIGNAL(zoomValueChanged(qreal)),
&sharedCameraModel, SLOT(setScale(qreal)));
connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)),
ui->zoomWidget, SLOT(setZoomValue(qreal)));
connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)),
this, SLOT(updateViewers()));
// Colors
connect(ui->redToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelZeroVisibility(bool)));
connect(ui->greenToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelOneVisibility(bool)));
connect(ui->blueToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelTwoVisibility(bool)));
// Crosshair
connect(ui->actionShow_Crosshair, SIGNAL(toggled(bool)),
this, SLOT(setCrosshairVisibility(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->actionShow_Crosshair, SLOT(setChecked(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->naLargeMIPWidget, SLOT(showCrosshair(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->v3dr_glwidget, SLOT(showCrosshair(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->naZStackWidget, SLOT(showCrosshair(bool)));
retrieveCrosshairVisibilitySetting();
// Axes
// TODO I want a small set of axes that sits in the lower left corner. The gigantic axes are less useful.
// connect(ui->actionShow_Axes, SIGNAL(toggled(bool)),
// ui->v3dr_glwidget, SLOT(enableShowAxes(bool)));
// Clear status message when viewer changes
connect(ui->viewerStackedWidget, SIGNAL(currentChanged(int)),
this, SLOT(onViewerChanged(int)));
// Create "Undo" menu options
// TODO - figure out which of these variables to expose once we have a QUndoCommand to work with.
QUndoGroup * undoGroup = new QUndoGroup(this);
QAction * undoAction = undoGroup->createUndoAction(this);
undoAction->setShortcuts(QKeySequence::Undo);
QAction * redoAction = undoGroup->createRedoAction(this);
redoAction->setShortcuts(QKeySequence::Redo);
ui->menuEdit->insertAction(ui->menuEdit->actions().at(0), redoAction);
ui->menuEdit->insertAction(redoAction, undoAction);
// expose undoStack
undoStack = new QUndoStack(undoGroup);
undoGroup->setActiveStack(undoStack);
ui->v3dr_glwidget->setUndoStack(*undoStack);
// Connect sort buttons to gallery widget
connect(ui->gallerySortBySizeButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortBySize()));
connect(ui->gallerySortByColorButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByColor()));
connect(ui->gallerySortByIndexButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByIndex()));
connect(ui->gallerySortByNameButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByName()));
// Allow cross-thread signals/slots that pass QList<int>
qRegisterMetaType< QList<int> >("QList<int>");
// Set up the annotation widget
ui->annotationFrame->setMainWindow(this);
ui->centralwidget->installEventFilter(ui->annotationFrame);
ui->annotationFrame->consoleConnect(3);
// NeuronSelector helper class for selecting neurons
connect(&neuronSelector, SIGNAL(neuronSelected(int)),
ui->annotationFrame, SLOT(selectNeuron(int)));
connect(ui->v3dr_glwidget, SIGNAL(neuronSelected(double,double,double)),
&neuronSelector, SLOT(updateSelectedPosition(double,double,double)));
connect(ui->actionDynamic_range, SIGNAL(triggered(bool)),
this, SLOT(showDynamicRangeTool()));
connect(ui->actionFull_Screen, SIGNAL(toggled(bool)),
this, SLOT(setFullScreen(bool)));
connect(this, SIGNAL(benchmarkTimerResetRequested()),
this, SLOT(resetBenchmarkTimer()));
connect(this, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SLOT(printBenchmarkTimer(QString)));
connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SIGNAL(benchmarkTimerPrintRequested(QString)));
connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerResetRequested()),
this, SIGNAL(benchmarkTimerResetRequested()));
initializeContextMenus();
initializeStereo3DOptions();
connectCustomCut();
}
/* slot */
void NaMainWindow::onSlabThicknessChanged(int t)
{
// qDebug() << "NaMainWindow::onSlabThicknessChanged()" << t << __FILE__ << __LINE__;
if (t > ui->slabThicknessSlider->maximum()) {
ui->slabThicknessSlider->setMaximum(t);
ui->slabPositionSlider->setMaximum(t/2);
ui->slabPositionSlider->setMinimum(-t/2);
}
ui->slabThicknessSlider->setValue(t);
}
/* slot */
void NaMainWindow::resetBenchmarkTimer()
{
mainWindowStopWatch.restart();
}
/* slot */
void NaMainWindow::printBenchmarkTimer(QString message)
{
// qDebug() << "BENCHMARK" << message << "at" << mainWindowStopWatch.elapsed()/1000.0 << "seconds";
}
/* virtual */
void NaMainWindow::keyPressEvent(QKeyEvent *event)
{
// Press <ESC> to exit full screen mode
if (event->key() == Qt::Key_Escape)
{
// qDebug() << "escape pressed in main window";
exitFullScreen();
}
QMainWindow::keyPressEvent(event);
}
/* slot */
void NaMainWindow::setViewMode(ViewMode mode)
{
// if (mode == viewMode)
// return; // no change
viewMode = mode;
if (mode == VIEW_SINGLE_STACK) {
ui->mipsFrame->setVisible(false);
ui->annotationFrame->setVisible(true);
ui->referenceGammaWidget->setVisible(false);
// qDebug() << "Changing to single stack mode" << __FILE__ << __LINE__;
}
if (mode == VIEW_NEURON_SEPARATION) {
ui->mipsFrame->setVisible(true);
ui->annotationFrame->setVisible(true);
ui->referenceGammaWidget->setVisible(true);
// qDebug() << "Changing to separation result mode" << __FILE__ << __LINE__;
}
update();
}
/* slot */
void NaMainWindow::exitFullScreen()
{
if (! isFullScreen())
return;
if (viewMode == VIEW_NEURON_SEPARATION)
{
ui->mipsFrame->show();
}
ui->annotationFrame->show();
ui->viewerSelectorAndControlFrame->show();
statusBar()->show();
showNormal();
}
/* slot */
void NaMainWindow::setFullScreen(bool b)
{
if (isFullScreen() == b)
return;
if (b)
{
ui->annotationFrame->hide();
ui->mipsFrame->hide();
ui->viewerSelectorAndControlFrame->hide();
statusBar()->hide();
showFullScreen();
}
else
{
exitFullScreen();
}
}
QString NaMainWindow::getDataDirectoryPathWithDialog()
{
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString dirName = QFileDialog::getExistingDirectory(
this,
"Select neuron separation directory",
initialDialogPath,
QFileDialog::ShowDirsOnly);
if (dirName.isEmpty())
return "";
QDir dir(dirName);
if (! dir.exists() )
{
QMessageBox::warning(this, tr("No such directory"),
QString("'%1'\n No such directory.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
return "";
}
// Remember parent directory to ease browsing next time
if (dir.cdUp()) {
if (dir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", dir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << dirName;
}
}
return dirName;
}
QString NaMainWindow::getStackPathWithDialog()
{
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString fileName = QFileDialog::getOpenFileName(this,
"Select volume file",
initialDialogPath,
tr("Stacks (*.lsm *.tif *.tiff *.mp4 *.v3draw *.v3dpbd)"));
if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please!
return "";
QFile movieFile(fileName);
if (! movieFile.exists() )
{
QMessageBox::warning(this, tr("No such file"),
QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName));
return "";
}
// Remember parent directory to ease browsing next time
QDir parentDir = QFileInfo(movieFile).dir();
if (parentDir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << fileName;
}
return fileName;
}
/* slot */
void NaMainWindow::on_action1280x720_triggered() {
int w = ui->v3dr_glwidget->width();
int h = ui->v3dr_glwidget->height();
int dw = 1280 - w;
int dh = 720 - h;
resize(width() + dw, height() + dh);
}
/* slot */
void NaMainWindow::on_actionAdd_landmark_at_cursor_triggered() {
// qDebug() << "add landmark";
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
float radius = 20.0;
Vector3D focus = sharedCameraModel.focus();
// Shape comes from type not shape argument. whatever
// 0 - dodecahedron
// 1 - cube
ImageMarker landmark = ImageMarker(2, 0, focus.x(), rna->dim2 - focus.y(), rna->dim3 - focus.z(), radius);
// cycle colors red->green->blue
int c = viewerLandmarks3D.size() % 3;
if (c == 0)
landmark.color.i = 0xff5050ff;
else if (c == 1)
landmark.color.i = 0xff50ff50;
else if (c == 2)
landmark.color.i = 0xffff5050;
viewerLandmarks3D << landmark;
rna->sShowMarkers = true;
rna->markerSize = (int) radius;
rna->setLandmarks(viewerLandmarks3D);
rna->b_showMarkerLabel = false;
rna->b_showMarkerName = false;
// rna->updateLandmark(); // deletes markerList!
}
}
/* slot */
void NaMainWindow::on_actionAppend_key_frame_at_current_view_triggered() {
// qDebug() << "append frame";
KeyFrame newFrame(4.0);
newFrame.storeCameraSettings(sharedCameraModel);
newFrame.storeLandmarkVisibility(viewerLandmarks3D);
if (dataFlowModel != NULL)
{
DataColorModel::Reader reader(dataFlowModel->getDataColorModel());
newFrame.storeChannelColorModel(reader);
}
currentMovie.appendKeyFrame(newFrame);
}
/* slot */
void NaMainWindow::on_actionLoad_movie_as_texture_triggered()
{
#ifdef USE_FFMPEG
QString fileName = getStackPathWithDialog();
if (fileName.isEmpty()) return;
if (! dataFlowModel) return;
dataFlowModel->getFast3DTexture().loadFile(fileName);
#endif
}
void NaMainWindow::on_actionClear_landmarks_triggered() {
viewerLandmarks3D.clear();
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
rna->clearLandmarks();
}
}
void NaMainWindow::on_actionClear_movie_triggered() {
currentMovie.clear();
}
/* slot */
void NaMainWindow::on_actionMeasure_Frame_Rate_triggered()
{
cout << "Measuring frame rate..." << endl;
Rotation3D currentRotation = sharedCameraModel.rotation();
Rotation3D dRot;
const int numSteps = 30;
dRot.setRotationFromAngleAboutUnitVector(
2.0 * 3.14159 / numSteps,
UnitVector3D(0, 1, 0));
QElapsedTimer timer;
timer.start();
for (int deg = 0; deg < numSteps; ++deg)
{
// cout << "step " << deg << endl;
currentRotation = dRot * currentRotation;
sharedCameraModel.setRotation(currentRotation);
QCoreApplication::processEvents();
ui->v3dr_glwidget->updateGL();
QCoreApplication::processEvents();
}
qint64 msTime = timer.elapsed();
double meanFrameTime = msTime / (double)(numSteps);
double frameRate = 1000.0 / meanFrameTime;
cout << meanFrameTime << " ms per frame; " << frameRate << " frames per second" << endl;
// cout << timer.elapsed() << endl;
}
/* slot */
void NaMainWindow::on_actionOpen_Octree_Volume_triggered()
{
QString fileName = getStackPathWithDialog();
if (fileName.isEmpty())
return;
loadSingleStack(fileName, false);
// TODO - actually do something clever
}
/* slot */
void NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered()
{
// qDebug() << "NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered";
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString fileName = QFileDialog::getOpenFileName(this,
"Select MPEG4 format volume data",
initialDialogPath);
// qDebug() << dirName;
// If user presses cancel, QFileDialog::getOpenFileName returns a null string
if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please!
return;
QFile movieFile(fileName);
if (! movieFile.exists() )
{
QMessageBox::warning(this, tr("No such file"),
QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName));
return;
}
// Remember parent directory to ease browsing next time
QDir parentDir = QFileInfo(movieFile).dir();
if (parentDir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << fileName;
}
loadSingleStack(fileName, false);
}
void NaMainWindow::on_actionPlay_movie_triggered() {
// qDebug() << "Play movie";
currentMovie.rewind();
QTime movieTimer;
movieTimer.start();
double movieElapsedTime = 0.0;
AnimationFrame frame;
bool bPlayRealTime = true;
while (currentMovie.hasMoreFrames()) {
frame = currentMovie.getNextFrame();
// Skip frames to catch up, if behind schedule
movieElapsedTime += currentMovie.secondsPerFrame;
if (bPlayRealTime && (movieElapsedTime < movieTimer.elapsed()/1000.0))
continue; // race to next frame
//
animateToFrame(frame);
}
// Alway finish in final frame.
if (bPlayRealTime)
animateToFrame(frame);
}
void NaMainWindow::animateToFrame(const AnimationFrame& frame) {
frame.retrieveCameraSettings(sharedCameraModel);
frame.retrieveLandmarkVisibility(viewerLandmarks3D);
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
rna->clearLandmarks();
rna->setLandmarks(viewerLandmarks3D);
rna->sShowMarkers = true;
}
// One channel visibility at a time
// Test for positive comparisons, to avoid NaN values
if (frame.channelZeroVisibility >= 0.5)
emit setChannelZeroVisibility(true);
else if (frame.channelZeroVisibility < 0.5)
emit setChannelZeroVisibility(false);
//
if (frame.channelOneVisibility >= 0.5)
emit setChannelOneVisibility(true);
else if (frame.channelOneVisibility < 0.5)
emit setChannelOneVisibility(false);
//
if (frame.channelTwoVisibility >= 0.5)
emit setChannelTwoVisibility(true);
else if (frame.channelTwoVisibility < 0.5)
emit setChannelTwoVisibility(false);
//
if (frame.channelThreeVisibility >= 0.5)
emit setChannelThreeVisibility(true);
else if (frame.channelThreeVisibility < 0.5)
emit setChannelThreeVisibility(false);
ui->v3dr_glwidget->update();
QApplication::processEvents();
}
void NaMainWindow::on_actionSave_movie_frames_triggered() {
// Get output folder
static QString startFolder;
QString sf;
if (! startFolder.isEmpty())
sf = startFolder;
QString folderName = QFileDialog::getExistingDirectory(this,
tr("Choose folder to store movie frame images"),
sf);
if (folderName.isEmpty())
return;
QDir folder(folderName);
if (! folder.exists()) {
QMessageBox::warning(this, "No such folder", "Folder " +folderName+ " does not exist");
return;
}
currentMovie.rewind();
double secondsElapsed = 0.0;
int frameIndex = 0;
int savedCount = 0;
while (currentMovie.hasMoreFrames()) {
animateToFrame(currentMovie.getNextFrame());
QImage grabbedFrame = ui->v3dr_glwidget->grabFrameBuffer(true); // true->with alpha
frameIndex += 1;
QString fileName;
fileName.sprintf("frame_%05d.png", frameIndex);
fileName = folder.absoluteFilePath(fileName);
qDebug() << fileName;
if (grabbedFrame.save(fileName)) {
savedCount += 1;
}
else {
// TODO - better error handling
qDebug() << "Failed to save frame" << fileName;
}
}
QMessageBox::information(this, "Finished saving frames", QString("Saved %1 frames").arg(savedCount));
// Remember this folder next time
startFolder = folderName;
}
void NaMainWindow::on_zThicknessDoubleSpinBox_valueChanged(double val) {
ui->v3dr_glwidget->setThickness(val);
}
static bool isFolder(QString path) {
if (path.isEmpty())
return false;
if (path.endsWith("/"))
return true;
if (QFileInfo(path).suffix().isEmpty())
return true;
return false;
}
void NaMainWindow::openFileOrUrl(QString name)
{
// qDebug() << "NaMainWindow::openFileOrUrl" << name << __FILE__ << __LINE__;
if (name.isEmpty())
return;
QUrl url(name);
if (! url.isValid())
url = QUrl::fromLocalFile(name);
bool isDir = true;
if (url.isValid() && (!url.isRelative()) && url.toLocalFile().isEmpty())
isDir = isFolder(url.path()); // non-file URL
else
isDir = QFileInfo(url.toLocalFile()).isDir(); // local file
if (isDir)
openMulticolorImageStack(url);
else
loadSingleStack(url);
}
/* slot */
void NaMainWindow::setCrosshairVisibility(bool b)
{
if (bShowCrosshair == b) return; // no change
bShowCrosshair = b;
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
settings.setValue("NaCrosshairVisibility", bShowCrosshair);
emit crosshairVisibilityChanged(bShowCrosshair);
}
void NaMainWindow::retrieveCrosshairVisibilitySetting()
{
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
bool bVisible = true; // default to "on"
QVariant val = settings.value("NaCrosshairVisibility");
if (! val.isNull())
bVisible = val.toBool();
setCrosshairVisibility(bVisible);
}
/////////////////////////////////////////////////////
// Drop volume files onto main window to view them //
/////////////////////////////////////////////////////
// Return file name if the dragged item can be usefully dropped into the NeuronAnnotator main window
QUrl checkDragEvent(QDropEvent* event)
{
QList<QUrl> urls;
if (event->mimeData()->hasUrls())
urls = event->mimeData()->urls();
// Maybe the user dragged a string with a filename or url
else if (event->mimeData()->hasText()) {
QString text = event->mimeData()->text();
QUrl url(text);
if (url.isValid() && ! url.isEmpty())
urls.append(url);
else {
if (QFileInfo(text).exists())
urls.append(QUrl::fromLocalFile(text));
}
}
if (urls.isEmpty())
return QUrl();
/* Switch to use URLs, not files Jan 2013
QString fileName = urls.first().toLocalFile();
if (fileName.isEmpty())
return "";
*/
QUrl url = urls.first();
if (url.isEmpty())
return QUrl();
QString urlPath = url.path();
if (url.host() == "")
url.setHost("localhost");
// check for recognized file extensions
QString fileExtension = QFileInfo(urlPath).suffix().toLower();
if (fileExtension == "lsm")
return url;
if (fileExtension.startsWith("tif")) // tif or tiff
return url;
if (fileExtension.startsWith("v3d")) // v3draw or v3dpdb
return url;
#ifdef USE_FFMPEG
if (fileExtension.startsWith("mp4")) // v3draw or v3dpdb
return url;
#endif
bool isDir = isFolder(url.path());
if (isDir)
return url; // neuron separation folder
return QUrl();
}
void NaMainWindow::dragEnterEvent(QDragEnterEvent * event)
{
QUrl url = checkDragEvent(event);
if (! url.isEmpty())
event->acceptProposedAction();
// qDebug() << "NaMainWindow::dragEnterEvent" << fileName << __FILE__ << __LINE__;
}
void NaMainWindow::dropEvent(QDropEvent * event)
{
QUrl url = checkDragEvent(event);
if (url.isEmpty()) return;
openFileOrUrl(url.toString());
}
void NaMainWindow::moveEvent ( QMoveEvent * event )
{
// qDebug() << "NaMainWindow::moveEvent()" << __FILE__ << __LINE__;
ui->v3dr_glwidget->updateScreenPosition();
QMainWindow::moveEvent(event);
}
void NaMainWindow::loadSingleStack(QUrl url)
{
// Default to NeuronAnnotator, not Vaa3D classic, when URL is given
loadSingleStack(url, false);
}
/* slot */
void NaMainWindow::loadSingleStack(QString fileName)
{
QUrl url = QUrl::fromLocalFile(fileName);
loadSingleStack(url, true); // default to classic mode
}
/* slot */
void NaMainWindow::loadSingleStack(QUrl url, bool useVaa3dClassic)
{
if (url.isEmpty())
return;
if (! url.isValid())
return;
mainWindowStopWatch.start();
if (useVaa3dClassic) {
// Open in Vaa3D classic mode
ui->actionV3DDefault->trigger(); // switch mode
QString fileName = url.toLocalFile();
if (! fileName.isEmpty())
emit defaultVaa3dFileLoadRequested(fileName);
else
emit defaultVaa3dUrlLoadRequested(url);
}
else
{
setViewMode(VIEW_SINGLE_STACK);
onDataLoadStarted();
createNewDataFlowModel();
VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture();
volumeTexture.queueVolumeData();
QString baseName = QFileInfo(url.path()).fileName();
setTitle(baseName);
emit singleStackLoadRequested(url);
addUrlToRecentFilesList(url);
}
}
///////////////////////////////////
// User clip planes in 3D viewer //
///////////////////////////////////
void NaMainWindow::connectCustomCut()
{
connect(ui->customCutButton, SIGNAL(pressed()),
this, SLOT(applyCustomCut()));
connect(ui->defineClipPlaneButton, SIGNAL(pressed()),
this, SLOT(toggleCustomCutMode()));
}
/* slot */
void NaMainWindow::applyCustomCut()
{
// assert(isInCustomCutMode);
ui->v3dr_glwidget->applyCustomCut();
if (isInCustomCutMode)
toggleCustomCutMode();
}
/* slot */
void NaMainWindow::applyCustomKeepPlane()
{
// qDebug() << "NaMainWindow::applyCustomKeepPlane()" << __FILE__ << __LINE__;
// assert(isInCustomCutMode);
ui->v3dr_glwidget->applyCustomKeepPlane();
if (isInCustomCutMode)
toggleCustomCutMode();
}
/* slot */
void NaMainWindow::setCustomCutMode(bool doCustom)
{
if (doCustom)
{
// Activate custom cut mode
ui->defineClipPlaneButton->setText(tr("Cancel"));
ui->customCutButton->setEnabled(true);
ui->v3dr_glwidget->setCustomCutMode();
}
else
{
// Turn off custom cut mode
ui->defineClipPlaneButton->setText(tr("Custom..."));
ui->customCutButton->setEnabled(false);
ui->v3dr_glwidget->cancelCustomCutMode();
}
isInCustomCutMode = doCustom;
}
/* slot */
void NaMainWindow::toggleCustomCutMode()
{
setCustomCutMode(!isInCustomCutMode);
}
/* slot */
void NaMainWindow::showDynamicRangeTool()
{
// qDebug() << "NaMainWindow::showDynamicRangeTool";
if (! dynamicRangeTool) {
dynamicRangeTool = new DynamicRangeTool(this);
if (dataFlowModel)
dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel());
else
dynamicRangeTool->setColorModel(NULL);
}
dynamicRangeTool->show();
}
void NaMainWindow::onDataLoadStarted()
{
// Give strong indication to user that load is in progress
ui->viewerControlTabWidget->setEnabled(false);
ViewerIndex currentIndex = (ViewerIndex)ui->viewerStackedWidget->currentIndex();
if (currentIndex != VIEWER_WAIT_LOADING_SCREEN)
recentViewer = currentIndex;
ui->viewerStackedWidget->setCurrentIndex(VIEWER_WAIT_LOADING_SCREEN);
update();
}
void NaMainWindow::onDataLoadFinished()
{
if (undoStack)
undoStack->clear();
ui->viewerStackedWidget->setCurrentIndex(recentViewer);
ui->viewerControlTabWidget->setEnabled(true);
// qDebug() << "Data load took" << mainWindowStopWatch.elapsed()/1000.0 << "seconds";
update();
}
void NaMainWindow::initializeStereo3DOptions()
{
// Only check one stereo format at a time
QActionGroup* stereoModeGroup = new QActionGroup(this);
stereoModeGroup->setExclusive(true);
stereoModeGroup->addAction(ui->actionMono_Off);
stereoModeGroup->addAction(ui->actionLeft_eye_view);
stereoModeGroup->addAction(ui->actionRight_eye_view);
stereoModeGroup->addAction(ui->actionQuadro_120_Hz);
stereoModeGroup->addAction(ui->actionAnaglyph_Red_Cyan);
stereoModeGroup->addAction(ui->actionAnaglyph_Green_Magenta);
stereoModeGroup->addAction(ui->actionRow_Interleaved_Zalman);
stereoModeGroup->addAction(ui->actionChecker_Interleaved_3DTV);
stereoModeGroup->addAction(ui->actionColumn_Interleaved);
connect(ui->actionMono_Off, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoOff(bool)));
connect(ui->actionLeft_eye_view, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoLeftEye(bool)));
connect(ui->actionRight_eye_view, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoRightEye(bool)));
connect(ui->actionQuadro_120_Hz, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoQuadBuffered(bool)));
connect(ui->actionAnaglyph_Red_Cyan, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoAnaglyphRedCyan(bool)));
connect(ui->actionAnaglyph_Green_Magenta, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoAnaglyphGreenMagenta(bool)));
connect(ui->actionRow_Interleaved_Zalman, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoRowInterleaved(bool)));
connect(ui->actionChecker_Interleaved_3DTV, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoCheckerInterleaved(bool)));
connect(ui->actionColumn_Interleaved, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoColumnInterleaved(bool)));
connect(ui->v3dr_glwidget, SIGNAL(quadStereoSupported(bool)),
this, SLOT(supportQuadStereo(bool)));
}
/* slot */
void NaMainWindow::supportQuadStereo(bool b)
{
ui->actionQuadro_120_Hz->setEnabled(b);
if ( (!b) && ui->actionQuadro_120_Hz->isChecked() )
ui->actionMono_Off->setChecked(true);
}
void NaMainWindow::connectContextMenus(const NeuronSelectionModel& neuronSelectionModel)
{
connect(showAllNeuronsInEmptySpaceAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(showAllNeuronsInEmptySpace()));
connect(selectNoneAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(clearSelection()));
connect(hideAllAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(showNothing()));
neuronContextMenu->connectActions(neuronSelectionModel);
}
void NaMainWindow::initializeContextMenus()
{
viewerContextMenu = new QMenu(this);
neuronContextMenu = new NeuronContextMenu(this);
// Some QActions were already made in Qt Designer
showAllNeuronsInEmptySpaceAction = ui->actionShow_all_neurons_in_empty_space;
hideAllAction = ui->actionClear_Hide_All;
selectNoneAction = ui->actionSelect_None;
//
viewerContextMenu->addAction(showAllNeuronsInEmptySpaceAction);
viewerContextMenu->addAction(hideAllAction);
viewerContextMenu->addAction(selectNoneAction);
//
neuronContextMenu->addSeparator();
neuronContextMenu->addAction(showAllNeuronsInEmptySpaceAction);
neuronContextMenu->addAction(hideAllAction);
neuronContextMenu->addAction(selectNoneAction);
//
ui->naLargeMIPWidget->setContextMenus(viewerContextMenu, neuronContextMenu);
ui->naZStackWidget->setContextMenus(viewerContextMenu, neuronContextMenu);
ui->v3dr_glwidget->setContextMenus(viewerContextMenu, neuronContextMenu);
}
/* slot */
void NaMainWindow::onHdrChannelChanged(NaZStackWidget::Color channel)
{
switch(channel)
{
// Due to exclusive group, checking one button unchecks the others.
case NaZStackWidget::COLOR_RED:
ui->HDRRed_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_GREEN:
ui->HDRGreen_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_BLUE:
ui->HDRBlue_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_NC82:
ui->HDRNc82_pushButton->setChecked(true);
break;
}
}
/* slot */
void NaMainWindow::onColorModelChanged()
{
// For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel
bool bReferenceColorIsVisible;
bool bReferenceOverlayIsVisible;
{
DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel());
if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return;
ui->redToggleButton->setChecked(colorReader.getChannelVisibility(0));
ui->greenToggleButton->setChecked(colorReader.getChannelVisibility(1));
ui->blueToggleButton->setChecked(colorReader.getChannelVisibility(2));
// Gamma
ui->sharedGammaWidget->setGammaBrightness(colorReader.getSharedGamma());
const int refIndex = 3;
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock() && volumeReader.hasReferenceImage())
ui->referenceGammaWidget->setGammaBrightness(colorReader.getChannelGamma(refIndex));
// Communicate reference channel changes between NeuronSelectionModel and DataColorModel
bReferenceColorIsVisible = colorReader.getChannelVisibility(refIndex);
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (selectionReader.getMaskStatusList().size() < 1)
return; // selection model is not active, single stack being viewed?
bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX];
} // release read locks
// Communicate reference visibility change, if any, to NeuronSelectionModel
if (bReferenceColorIsVisible != bReferenceOverlayIsVisible)
dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, bReferenceColorIsVisible);
}
/* slot */
void NaMainWindow::onSelectionModelVisibilityChanged()
{
// For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel
bool bReferenceColorIsVisible;
bool bReferenceOverlayIsVisible;
{
DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel());
if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return;
bReferenceColorIsVisible = colorReader.getChannelVisibility(3);
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX];
}
if (bReferenceColorIsVisible != bReferenceOverlayIsVisible)
// TODO - this causes a fork of data color model
// dataFlowModel->getDataColorModel().setChannelVisibility(3, bReferenceOverlayIsVisible);
emit channelVisibilityChanged(3, bReferenceOverlayIsVisible);
}
/* slot */
void NaMainWindow::setChannelZeroVisibility(bool v)
{
// qDebug() << "NaMainWindow::setChannelZeroVisibility" << v;
emit channelVisibilityChanged(0, v);
}
/* slot */
void NaMainWindow::setChannelOneVisibility(bool v)
{
emit channelVisibilityChanged(1, v);
}
/* slot */
void NaMainWindow::setChannelTwoVisibility(bool v)
{
emit channelVisibilityChanged(2, v);
}
/* slot */
void NaMainWindow::setChannelThreeVisibility(bool v) // reference channel
{
// For reference channel, update both DataColorModel AND "overlay" of NeuronSelectionModel
if (dataFlowModel)
dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, v);
emit channelVisibilityChanged(3, v);
}
void NaMainWindow::onViewerChanged(int viewerIndex)
{
QString msg(" viewer selected.");
switch(viewerIndex) {
case VIEWER_MIP:
msg = "Maximum intensity projection" + msg;
break;
case VIEWER_ZSTACK:
msg = "Z-stack" + msg;
break;
case VIEWER_3D:
msg = "3D" + msg;
break;
default:
return; // wait window gets no message
break;
}
ui->statusbar->showMessage(msg);
}
void NaMainWindow::setRotation(Rotation3D r) {
sharedCameraModel.setRotation(r);
ui->v3dr_glwidget->update();
}
void NaMainWindow::setNutate(bool bDoNutate)
{
if (bDoNutate) {
// qDebug() << "nutate";
if (! nutateThread) {
nutateThread = new NutateThread(0.2, this);
qRegisterMetaType<Rotation3D>("Rotation3D");
connect(nutateThread, SIGNAL(nutate(const Rotation3D&)),
this, SLOT(nutate(const Rotation3D&)));
}
if (! nutateThread->isRunning())
nutateThread->start(QThread::IdlePriority);
if (nutateThread->isRunning() && nutateThread->isPaused()) {
nutateThread->unpause();
emit nutatingChanged(bDoNutate);
}
}
else {
// qDebug() << "stop nutating";
if (!nutateThread) return;
if (nutateThread->isRunning() && (!nutateThread->isPaused())) {
nutateThread->pause();
emit nutatingChanged(bDoNutate);
}
}
}
void NaMainWindow::nutate(const Rotation3D& R) {
// qDebug() << "nutate!";
// std::cout << R << std::endl;
CameraModel& cam = ui->v3dr_glwidget->cameraModel;
if (!ui->v3dr_glwidget->mouseIsDragging()) {
cam.setRotation(R * cam.rotation());
// TODO - use a signal here instead of processEvents
QCoreApplication::processEvents(); // keep responsive during nutation
ui->v3dr_glwidget->update();
}
}
void NaMainWindow::resetView()
{
// TODO - might not work if cameras are not linked
Vector3D newFocus = ui->v3dr_glwidget->getDefaultFocus();
// cerr << newFocus << __LINE__ << __FILE__;
sharedCameraModel.setFocus(newFocus);
sharedCameraModel.setRotation(Rotation3D()); // identity rotation
sharedCameraModel.setScale(1.0); // fit to window
ui->viewerStackedWidget->update(); // whichever viewer is shown
}
void NaMainWindow::updateViewers()
{
ui->naLargeMIPWidget->update();
ui->naZStackWidget->update();
ui->v3dr_glwidget->update();
}
void NaMainWindow::unifyCameras(bool bDoUnify)
{
// TODO - explicitly copy parameters from active displayed viewer
if (bDoUnify) {
ui->naLargeMIPWidget->synchronizeWithCameraModel(&sharedCameraModel);
ui->naZStackWidget->synchronizeWithCameraModel(&sharedCameraModel);
ui->v3dr_glwidget->synchronizeWithCameraModel(&sharedCameraModel);
// qDebug() << "unify cameras";
}
else {
ui->naLargeMIPWidget->decoupleCameraModel(&sharedCameraModel);
ui->naZStackWidget->decoupleCameraModel(&sharedCameraModel);
ui->v3dr_glwidget->decoupleCameraModel(&sharedCameraModel);
// qDebug() << "disband cameras";
}
}
void NaMainWindow::setZRange(int minZ, int maxZ) {
// qDebug() << "minZ = " << minZ << "; maxZ = " << maxZ;
QString text = QString("of %1").arg(maxZ);
// qDebug() << text;
ui->ZSliceTotal_label->setText(text);
ui->ZSlice_horizontalScrollBar->setMaximum(maxZ);
ui->ZSlice_spinBox->setMaximum(maxZ);
ui->ZSlice_horizontalScrollBar->setMinimum(minZ);
ui->ZSlice_spinBox->setMinimum(minZ);
}
void NaMainWindow::handleCoordinatedCloseEvent(QCloseEvent *e)
{
if (isVisible())
{
// Remember window size for next time.
// These settings affect both NaMainWindow and classic V3D MainWindows. So only use
// NaMainWindow settings if the NaMainWindow is visible.
// qDebug() << "Saving NaMainWindow size and position";
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
settings.setValue("pos", pos());
settings.setValue("size", size());
}
e->accept();
}
void NaMainWindow::closeEvent(QCloseEvent *e)
{
V3dApplication::handleCloseEvent(e);
}
void NaMainWindow::on_actionQuit_triggered() {
close();
}
void NaMainWindow::on_actionV3DDefault_triggered() {
V3dApplication::deactivateNaMainWindow();
V3dApplication::activateMainWindow();
}
void NaMainWindow::on_actionNeuronAnnotator_triggered() {
V3dApplication::activateNaMainWindow();
V3dApplication::deactivateMainWindow();
}
void NaMainWindow::setV3DDefaultModeCheck(bool checkState) {
QAction* ui_actionV3DDefault = this->findChild<QAction*>("actionV3DDefault");
ui_actionV3DDefault->setChecked(checkState);
}
void NaMainWindow::setNeuronAnnotatorModeCheck(bool checkState) {
QAction* ui_actionNeuronAnnotator = this->findChild<QAction*>("actionNeuronAnnotator");
ui_actionNeuronAnnotator->setChecked(checkState);
}
void NaMainWindow::on_actionOpen_microCT_Cut_Planner_triggered()
{
if (cutPlanner == NULL) {
cutPlanner = new CutPlanner(sharedCameraModel, *ui->v3dr_glwidget, this);
connect(cutPlanner, SIGNAL(rotationAdjusted(Rotation3D)),
this, SLOT(setRotation(Rotation3D)));
connect(cutPlanner, SIGNAL(clipPlaneRequested()),
this, SLOT(applyCustomCut()));
connect(cutPlanner, SIGNAL(keepPlaneRequested()),
this, SLOT(applyCustomKeepPlane()));
connect(cutPlanner, SIGNAL(cutGuideRequested(bool)),
this, SLOT(setCustomCutMode(bool)));
connect(cutPlanner, SIGNAL(compartmentNamingRequested()),
this, SLOT(labelNeuronsAsFlyBrainCompartments()));
}
setCustomCutMode(true);
cutPlanner->show();
}
void NaMainWindow::on_actionOpen_triggered()
{
QString dirName = getDataDirectoryPathWithDialog();
openMulticolorImageStack(dirName);
}
bool NaMainWindow::openMulticolorImageStack(QString dirName)
{
// qDebug() << "NaMainWindow::openMulticolorImageStack" << dirName << __FILE__ << __LINE__;
// string could be a folder name or a URL string
// Try for folder name
QDir imageDir(dirName);
if (imageDir.exists()) {
QUrl url = QUrl::fromLocalFile(imageDir.absolutePath());
return openMulticolorImageStack(url);
}
// Path is always a folder, so make it explicit
if (! dirName.endsWith("/"))
dirName = dirName + "/";
// That didn't work: try for a URL
QUrl url(dirName);
if (! url.isValid()) {
QMessageBox::warning(this, tr("No such directory or URL"),
QString("'%1'\n No such directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
return false;
}
// qDebug() << url;
bool result = openMulticolorImageStack(url);
if (! result) {
QMessageBox::warning(this, tr("Error opening directory or URL"),
QString("'%1'\n Could not open directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
}
return result;
}
bool NaMainWindow::openMulticolorImageStack(QUrl url)
{
// qDebug() << "NaMainWindow::openMulticolorImageStack" << url << __FILE__ << __LINE__;
mainWindowStopWatch.start();
// std::cout << "Selected directory=" << imageDir.absolutePath().toStdString() << endl;
emit benchmarkTimerResetRequested();
emit benchmarkTimerPrintRequested("openMulticolorImageStack called");
if (! tearDownOldDataFlowModel()) {
QMessageBox::warning(this, tr("Could not close previous Annotation Session"),
"Error saving previous session and/or clearing memory - please exit application");
return false;
}
// Try to avoid Dec 2013 crash
ui->v3dr_glwidget->clearImage();
createNewDataFlowModel();
// reset front/back clip slab
ui->v3dr_glwidget->resetSlabThickness();
emit initializeColorModelRequested();
VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture();
// Queue up the various volumes to load, using StageFileLoaders
// delegated to VolumeTexture (3D viewer) and NaVolumeTexture (all viewers)
onDataLoadStarted();
if (! volumeTexture.queueSeparationFolder(url))
{
onDataLoadFinished();
return false;
}
// Make sure 3D viewer is showing if fast loading is enabled
if(volumeTexture.hasFastVolumesQueued()) {
// Fast loading is only interesting if 3D viewer is selected.
// So show the 3D viewer
ui->viewerControlTabWidget->setCurrentIndex(2);
setViewMode(VIEW_SINGLE_STACK); // no gallery yet.
}
// MulticolorImageStackNode setup is required for loadLsmMetadata call to succeed.
MultiColorImageStackNode* multiColorImageStackNode =
new MultiColorImageStackNode(url.toString());
QUrl fileUrl = url;
QString path = fileUrl.path();
if (! path.endsWith("/"))
path = path + "/";
// These file names will be overridden by Staged loader
fileUrl.setPath(path + "ConsolidatedSignal");
multiColorImageStackNode->setPathToOriginalImageStackFile(fileUrl.toString());
fileUrl.setPath(path + "Reference");
multiColorImageStackNode->setPathToReferenceStackFile(fileUrl.toString());
fileUrl.setPath(path + "ConsolidatedLabel");
multiColorImageStackNode->setPathToMulticolorLabelMaskFile(fileUrl.toString());
dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode);
if (! dataFlowModel->getVolumeData().queueSeparationFolder(url)) {
onDataLoadFinished();
return false;
}
// Correct Z-thickness
dataFlowModel->loadLsmMetadata();
// Kick off loading sequence
emit stagedLoadRequested();
// volumeTexture.loadNextVolume();
addUrlToRecentFilesList(url);
return true;
}
bool NaMainWindow::loadSeparationDirectoryV1Pbd(QUrl imageInputDirectory)
{
onDataLoadStarted();
// Need to construct (temporary until backend implemented) MultiColorImageStackNode from this directory
// This code will be redone when the node/filestore is implemented.
QUrl originalImageStackFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_STACK_BASE_FILENAME);
QUrl maskLabelFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_MASK_BASE_FILENAME);
QUrl referenceStackFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_REFERENCE_BASE_FILENAME);
// Create input nodes
MultiColorImageStackNode* multiColorImageStackNode = new MultiColorImageStackNode(imageInputDirectory);
multiColorImageStackNode->setPathToMulticolorLabelMaskFile(maskLabelFilePath);
multiColorImageStackNode->setPathToOriginalImageStackFile(originalImageStackFilePath);
multiColorImageStackNode->setPathToReferenceStackFile(referenceStackFilePath);
dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode);
// Create result node
long resultNodeId=TimebasedIdentifierGenerator::getSingleId();
NeuronAnnotatorResultNode* resultNode = new NeuronAnnotatorResultNode(resultNodeId);
if (!resultNode->ensureDirectoryExists()) {
QMessageBox::warning(this, tr("Could not create NeuronAnnotationResultNode"),
"Error creating directory="+resultNode->getDirectoryPath());
return false;
}
dataFlowModel->setNeuronAnnotatorResultNode(resultNode);
// Opposite of fast loading behavior
dataFlowModel->getVolumeData().doFlipY = true;
dataFlowModel->getVolumeData().bDoUpdateSignalTexture = true;
// fooDebug() << __FILE__ << __LINE__;
// Load session
setViewMode(VIEW_NEURON_SEPARATION);
if (! dataFlowModel->loadVolumeData()) return false;
// dataChanged() signal will be emitted if load succeeds
return true;
}
// Recent files list
void NaMainWindow::addDirToRecentFilesList(QDir imageDir)
{
QString fileName = imageDir.absolutePath();
addFileNameToRecentFilesList(QUrl::fromLocalFile(fileName).toString());
}
void NaMainWindow::addUrlToRecentFilesList(QUrl url)
{
addFileNameToRecentFilesList(url.toString());
}
void NaMainWindow::addFileNameToRecentFilesList(QString fileName)
{
// fooDebug() << fileName << __FILE__ << __LINE__;
if (fileName.isEmpty()) return;
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QVariant filesVariant = settings.value("NeuronAnnotatorRecentFileList");
QStringList files = filesVariant.toStringList();
if ( (files.size() > 0) && (files[0] == fileName) )
return; // this dir is already the top entry as is
files.removeAll(fileName);
files.removeAll(QString());
files.prepend(fileName);
while (files.size() > maxRecentFiles)
files.removeLast();
settings.setValue("NeuronAnnotatorRecentFileList", files);
updateRecentFileActions();
}
void NaMainWindow::updateRecentFileActions()
{
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QStringList files = settings.value("NeuronAnnotatorRecentFileList").toStringList();
ui->menuOpen_Recent->setEnabled(files.size() > 0);
for (int i = 0; i < maxRecentFiles; ++i)
{
if ( (i < files.size() && (! files[i].isEmpty())) ) { // active
recentFileActions[i]->setFileName(files[i]);
recentFileActions[i]->setVisible(true);
}
else { // inactive
recentFileActions[i]->setFileName(QString());
recentFileActions[i]->setVisible(false);
}
}
}
QString NaMainWindow::suggestedExportFilenameFromCurrentState(const NeuronSelectionModel::Reader& selectionReader)
{
MultiColorImageStackNode* multiColorImageStackNode=this->dataFlowModel->getMultiColorImageStackNode();
QStringList lsmFilePathsList=multiColorImageStackNode->getLsmFilePathList();
if (lsmFilePathsList.size()>0) {
// First get filename prefix
QString firstFilePath=lsmFilePathsList.at(0);
QStringList components=firstFilePath.split(QRegExp("/"));
QString name=components.at(components.size()-1);
QStringList extComponents=name.split(QRegExp("\\."));
QString filenamePrefix=extComponents.at(0);
// Next, add current state
if(selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) {
filenamePrefix.append("_R");
}
if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) {
filenamePrefix.append("_B");
}
const QList<bool> neuronStatusList = selectionReader.getMaskStatusList();
int activeCount=0;
QString neuronStatusString;
for (int i=0;i<neuronStatusList.size();i++) {
if (neuronStatusList.at(i)) {
neuronStatusString.append("_");
QString number=QString("%1").arg(i);
neuronStatusString.append(number);
activeCount++;
}
}
if (activeCount==neuronStatusList.size()) {
filenamePrefix.append("_all");
} else if (activeCount<6) {
filenamePrefix.append(neuronStatusString);
} else {
filenamePrefix.append("_multiple");
}
return filenamePrefix;
} else {
return QString("");
}
}
void expressRegretsAboutVolumeWriting(QString message) {
QMessageBox::warning(NULL, "Volume export failed",
message);
}
void NaMainWindow::on_action3D_Volume_triggered()
{
if (! dataFlowModel) {
expressRegretsAboutVolumeWriting("No data available to save");
return;
}
QString suggestedFile;
{
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) {
expressRegretsAboutVolumeWriting("Could not access selection data");
return;
}
suggestedFile=suggestedExportFilenameFromCurrentState(selectionReader);
}
QString fileTypes = "*.v3dpbd *.v3draw *.tif";
#ifdef USE_FFMPEG
fileTypes += " *.mp4";
#endif
fileTypes = "3D Volumes ("+fileTypes+")";
QString filename = QFileDialog::getSaveFileName(
0,
QObject::tr("Save 3D Volume to a file"),
suggestedFile,
QObject::tr(fileTypes.toStdString().c_str()));
if (filename.isEmpty())
return; // user pressed "Cancel"
QFileInfo fi(filename);
if (fi.suffix().isEmpty())
filename = filename + ".v3dpbd";
fooDebug() << filename;
ExportFile *pExport = new ExportFile(
filename,
dataFlowModel->getVolumeData(),
dataFlowModel->getNeuronSelectionModel(),
dataFlowModel->getDataColorModel(),
sharedCameraModel);
connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater()));
connect(pExport, SIGNAL(exportFinished(QString)),
this, SLOT(onExportFinished(QString)));
connect(pExport, SIGNAL(exportFailed(QString, QString)),
this, SLOT(onExportFinished(QString, QString)));
pExport->start();
}
/* slot */
void NaMainWindow::onExportFinished(QString fileName) {
QMessageBox::information(this, "Volume export succeeded",
"Saved file " + fileName);
}
/* slot */
void NaMainWindow::onExportFailed(QString fileName, QString message) {
QMessageBox::warning(this, "Volume export failed",
message + ": " + fileName);
}
void NaMainWindow::on_action2D_MIP_triggered() {
QString filename = QFileDialog::getSaveFileName(0, QObject::tr("Save 2D MIP to an .tif file"), ".", QObject::tr("2D MIP (*.tif)"));
if (!(filename.isEmpty())){
// bool saved = ui->naLargeMIPWidget->saveImage(filename); // REPLACING WITH 3D MIP USING ROTATION and CUT PLANES
ExportFile *pExport = new ExportFile(
filename,
dataFlowModel->getVolumeData(),
dataFlowModel->getNeuronSelectionModel(),
dataFlowModel->getDataColorModel(),
sharedCameraModel,
true /* is2D */);
connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater()));
connect(pExport, SIGNAL(exportFinished(QString)),
this, SLOT(onExportFinished(QString)));
connect(pExport, SIGNAL(exportFailed(QString, QString)),
this, SLOT(onExportFinished(QString, QString)));
pExport->start();
}
}
void NaMainWindow::on_actionScreenShot_triggered() {
static QString dirname = ".";
QString filename = QFileDialog::getSaveFileName(
ui->v3dr_glwidget,
QObject::tr("Save 3D View to an image file"),
dirname,
QObject::tr("Images (*.tif *.png *.jpg *.ppm *.xpm)"));
if (filename.isEmpty())
return; // User cancelled
bool saved = ui->v3dr_glwidget->screenShot(filename);
if (saved) {
QMessageBox::information(ui->v3dr_glwidget,
"Successfully saved screen shot",
"Successfully saved screen shot to file " + filename);
// Remember this directory next time
// TODO - use QSettings for more persistent memory
dirname = filename;
}
else {
QMessageBox::critical(this,
"Failed to save screen shot",
"Failed to save screen shot to file " + filename
+ " \nDo you have write permission in that folder?"
+ " \nMaybe a different image format would work better?");
}
}
void NaMainWindow::on_actionPreferences_triggered()
{
PreferencesDialog dlg(this);
dlg.loadPreferences();
int result = dlg.exec();
if (result == QDialog::Accepted) {
dlg.savePreferences();
}
}
void NaMainWindow::on_actionX_Rotation_Movie_triggered()
{
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save movie frame images"),
"",
tr("Images (*.png *.jpg *.ppm)"));
if (fileName.isEmpty())
return;
QFileInfo fi(fileName);
QDir dir = fi.absoluteDir();
QString base = fi.completeBaseName();
QString suffix = fi.suffix();
int frameCount = 540;
Rotation3D dRot;
dRot.setRotationFromAngleAboutUnitVector(
2.0 * 3.14159 / frameCount,
UnitVector3D(1, 0, 0));
Rotation3D currentRotation = sharedCameraModel.rotation();
ui->v3dr_glwidget->resize(1280, 720);
for (int f = 0; f < frameCount; ++f)
{
QString fnum = QString("_%1.").arg(f, 5, 10, QChar('0'));
QString fName = dir.absoluteFilePath(base + fnum + suffix);
fooDebug() << fName;
currentRotation = dRot * currentRotation;
sharedCameraModel.setRotation(currentRotation);
ui->v3dr_glwidget->repaint();
QCoreApplication::processEvents();
QImage frameImage = ui->v3dr_glwidget->grabFrameBuffer();
frameImage.save(fName, NULL, 95);
}
}
// June 27, 2012 modify to accept "NULL" during data flow replacement
void NaMainWindow::setDataFlowModel(DataFlowModel* dataFlowModelParam)
{
if (dataFlowModel == dataFlowModelParam)
return; // no change
if ( (dataFlowModelParam != NULL) // we are not currently tearing down
&& (dataFlowModel != NULL) ) // there is another different model in existence
{
qDebug() << "WARNING: setDataFlowModel() should not be tearing down old models" << __FILE__ << __LINE__;
tearDownOldDataFlowModel();
}
dataFlowModel = dataFlowModelParam;
ui->v3dr_glwidget->setDataFlowModel(dataFlowModel);
ui->naLargeMIPWidget->setDataFlowModel(dataFlowModel);
ui->naZStackWidget->setDataFlowModel(dataFlowModel);
ui->fragmentGalleryWidget->setDataFlowModel(dataFlowModel);
neuronSelector.setDataFlowModel(dataFlowModel);
// was in loadAnnotationSessionFromDirectory June 27, 2012
if (dynamicRangeTool) {
if (NULL == dataFlowModel)
dynamicRangeTool->setColorModel(NULL);
else
dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel());
}
// No connecting if the model is NULL
if (NULL == dataFlowModel)
{
ui->naLargeMIPWidget->setMipMergedData(NULL);
return;
}
connect(this, SIGNAL(subsampleLabelPbdFileNamed(QUrl)),
&dataFlowModel->getVolumeTexture(), SLOT(setLabelPbdFileUrl(QUrl)));
connect(dataFlowModel, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SIGNAL(benchmarkTimerPrintRequested(QString)));
connect(dataFlowModel, SIGNAL(benchmarkTimerResetRequested()),
this, SIGNAL(benchmarkTimerResetRequested()));
// Connect mip viewer to data flow model
ui->naLargeMIPWidget->setMipMergedData(&dataFlowModel->getMipMergedData());
connectContextMenus(dataFlowModel->getNeuronSelectionModel());
connect(dataFlowModel, SIGNAL(scrollBarFocus(NeuronSelectionModel::NeuronIndex)),
ui->fragmentGalleryWidget, SLOT(scrollToFragment(NeuronSelectionModel::NeuronIndex)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)),
this, SLOT(processUpdatedVolumeData()));
// Both mip images and selection model need to be in place to update gallery
connect(&dataFlowModel->getGalleryMipImages(), SIGNAL(dataChanged()),
this, SLOT(updateGalleries()));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(initialized()),
this, SLOT(initializeGalleries()));
// Z value comes from camera model
connect(&sharedCameraModel, SIGNAL(focusChanged(Vector3D)),
&dataFlowModel->getZSliceColors(), SLOT(onCameraFocusChanged(Vector3D)));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(selectionCleared()),
ui->annotationFrame, SLOT(deselectNeurons()));
connect(ui->annotationFrame, SIGNAL(neuronSelected(int)),
&dataFlowModel->getNeuronSelectionModel(), SLOT(selectExactlyOneNeuron(int)));
connect(ui->annotationFrame, SIGNAL(neuronsDeselected()),
&dataFlowModel->getNeuronSelectionModel(), SLOT(clearSelection()));
connect(this, SIGNAL(initializeSelectionModelRequested()),
&dataFlowModel->getNeuronSelectionModel(), SLOT(initializeSelectionModel()));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(visibilityChanged()),
this, SLOT(onSelectionModelVisibilityChanged()));
// Progress if NaVolumeData file load
// TODO - this is a lot of connection boilerplate code. This should be abstracted into a single call or specialized ProgressManager class.
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressMessageChanged(QString)),
this, SLOT(setProgressMessage(QString)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressValueChanged(int)),
this, SLOT(setProgressValue(int)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressCompleted()),
this, SLOT(completeProgress()));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressAborted(QString)),
this, SLOT(abortProgress(QString)));
// Loading single stack
connect(this, SIGNAL(singleStackLoadRequested(QUrl)),
&dataFlowModel->getVolumeData(), SLOT(loadChannels(QUrl)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)),
this, SLOT(onDataLoadFinished()));
// Loading a series of separation result stacks
connect(this, SIGNAL(stagedLoadRequested()),
&dataFlowModel->getVolumeTexture(), SLOT(loadStagedVolumes()));
// Color toggling
connect(this, SIGNAL(channelVisibilityChanged(int,bool)),
&dataFlowModel->getDataColorModel(), SLOT(setChannelVisibility(int,bool)));
connect(ui->resetColorsButton, SIGNAL(clicked()),
&dataFlowModel->getDataColorModel(), SLOT(resetColors()));
connect(ui->sharedGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setSharedGamma(qreal)));
connect(ui->referenceGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setReferenceGamma(qreal)));
connect(&dataFlowModel->getDataColorModel(), SIGNAL(dataChanged()),
this, SLOT(onColorModelChanged()));
connect(ui->naZStackWidget, SIGNAL(hdrRangeChanged(int,qreal,qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setChannelHdrRange(int,qreal,qreal)));
connect(this, SIGNAL(initializeColorModelRequested()),
&dataFlowModel->getDataColorModel(), SLOT(resetColors()));
}
bool NaMainWindow::tearDownOldDataFlowModel()
{
ui->v3dr_glwidget->clearImage();
if (NULL == dataFlowModel)
return true;
// TODO - orderly shut down of old data flow model
DataFlowModel* dfm = dataFlowModel; // save pointer
// TODO - make sure clients respect setting to null
// TODO - make sure this does not yet delete dataFlowModel
setDataFlowModel(NULL);
delete dfm;
return true;
}
bool NaMainWindow::createNewDataFlowModel()
{
if (NULL != dataFlowModel) {
bool result = tearDownOldDataFlowModel();
if (!result)
return false;
}
DataFlowModel* dfm = new DataFlowModel();
setDataFlowModel(dfm);
ui->v3dr_glwidget->invalidate();
ui->naZStackWidget->invalidate();
ui->naLargeMIPWidget->invalidate();
ui->v3dr_glwidget->clearImage();
ui->v3dr_glwidget->initializeDefaultTextures(); // <- this is how to reset the label texture
return true;
}
void NaMainWindow::setTitle(QString title) {
setWindowTitle(QString("%1 - V3D Neuron Annotator").arg(title));
}
/* slot */
void NaMainWindow::processUpdatedVolumeData() // activated by volumeData::dataChanged() signal
{
onDataLoadFinished();
// TODO -- install separate listeners for dataChanged() in the various display widgets
dataFlowModel->loadLsmMetadata();
int img_sc, img_sz, ref_sc;
{
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (! volumeReader.hasReadLock()) return;
const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy();
const Image4DProxy<My4DImage>& refProxy = volumeReader.getReferenceImageProxy();
img_sc = imgProxy.sc;
img_sz = imgProxy.sz;
ref_sc = refProxy.sc;
} // release read locks
setZRange(0, img_sz - 1);
// Ensure z-stack viewer gets enabled
dataFlowModel->getZSliceColors().onCameraFocusChanged(sharedCameraModel.focus());
// Start in middle of volume
// No, initial position should be set in 3D viewer
// ui->naZStackWidget->setCurrentZSlice(img_sz / 2 + 1);
// Need at least two colors for use of the color buttons to make sense
ui->HDRRed_pushButton->setEnabled(img_sc > 1);
ui->HDRGreen_pushButton->setEnabled(img_sc > 1);
ui->HDRBlue_pushButton->setEnabled(img_sc > 2);
ui->HDRNc82_pushButton->setEnabled(ref_sc > 0);
resetVolumeCutRange();
}
/* slot */
void NaMainWindow::resetVolumeCutRange()
{
int mx, my, mz;
mx = my = mz = 0;
// first try VolumeTexture to get dimensions
{
VolumeTexture::Reader textureReader(dataFlowModel->getVolumeTexture());
if (! dataFlowModel->getVolumeTexture().readerIsStale(textureReader))
{
Dimension size = textureReader.originalImageSize();
mx = (int)size.x() - 1;
my = (int)size.y() - 1;
mz = (int)size.z() - 1;
}
}
// if that fails, try VolumeData
if (mx <= 0)
{
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock())
{
const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy();
mx = imgProxy.sx - 1;
my = imgProxy.sy - 1;
mz = imgProxy.sz - 1;
}
}
if (mx <= 0)
return;
// volume cut update
ui->XcminSlider->setRange(0, mx);
ui->XcminSlider->setValue(0);
ui->XcmaxSlider->setRange(0, mx);
ui->XcmaxSlider->setValue(mx);
ui->YcminSlider->setRange(0, my);
ui->YcminSlider->setValue(0);
ui->YcmaxSlider->setRange(0, my);
ui->YcmaxSlider->setValue(my);
ui->ZcminSlider->setRange(0, my);
ui->ZcminSlider->setValue(0);
ui->ZcmaxSlider->setRange(0, my);
ui->ZcmaxSlider->setValue(my);
} // release lock
DataFlowModel* NaMainWindow::getDataFlowModel() const {
return dataFlowModel;
}
void NaMainWindow::initializeGalleries()
{
initializeOverlayGallery();
initializeNeuronGallery();
}
void NaMainWindow::updateGalleries()
{
updateOverlayGallery();
updateNeuronGallery();
// Show or hide galleries depending on data structures
// In particular, hide galleries when there is no reference, nor any neurons.
bool bShowGalleries = false;
if (NULL == dataFlowModel)
; // bShowGalleries = false;
else {
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock()) {
if ( (volumeReader.getNumberOfNeurons() > 0)
|| (volumeReader.hasReferenceImage()) )
{
bShowGalleries = true;
}
}
}
// ui->mipsFrame->setVisible(bShowGalleries);
if (bShowGalleries)
setViewMode(VIEW_NEURON_SEPARATION);
}
void NaMainWindow::initializeOverlayGallery()
{
// qDebug() << "NaMainWindow::initializeOverlayGallery()" << __FILE__ << __LINE__;
// Create layout, only if needed.
QFrame* ui_maskFrame = this->findChild<QFrame*>("maskFrame");
if (! ui_maskFrame->layout()) {
ui_maskFrame->setLayout(new QHBoxLayout());
assert(ui_maskFrame->layout());
}
QLayout *managementLayout = ui_maskFrame->layout();
// Create new buttons, only if needed.
if (overlayGalleryButtonList.size() != 2) {
// Delete any old contents from the layout, such as previous thumbnails
QLayoutItem * item;
while ( ( item = managementLayout->takeAt(0)) != NULL )
{
delete item->widget();
delete item;
}
QImage initialImage(100, 140, QImage::Format_ARGB32);
initialImage.fill(Qt::gray);
GalleryButton* referenceButton = new GalleryButton(
initialImage,
"Reference",
DataFlowModel::REFERENCE_MIP_INDEX,
GalleryButton::OVERLAY_BUTTON);
managementLayout->addWidget(referenceButton);
overlayGalleryButtonList.append(referenceButton);
GalleryButton* backgroundButton = new GalleryButton(
initialImage,
"Background",
DataFlowModel::BACKGROUND_MIP_INDEX,
GalleryButton::OVERLAY_BUTTON);
managementLayout->addWidget(backgroundButton);
overlayGalleryButtonList.append(backgroundButton);
}
// Initialize signals whether the buttons were already there or not
for (int i = 0; i < 2; ++i)
{
overlayGalleryButtonList[i]->setNeuronSelectionModel(dataFlowModel->getNeuronSelectionModel());
}
updateOverlayGallery();
}
void NaMainWindow::updateOverlayGallery()
{
if (overlayGalleryButtonList.size() != 2) return; // not initialized
if (NULL == dataFlowModel) return;
{
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (selectionReader.getOverlayStatusList().size() < 2) return;
if (selectionReader.hasReadLock())
{
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->setChecked(selectionReader.getOverlayStatusList().at(i));
}
}
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (mipReader.hasReadLock() && (mipReader.getNumberOfOverlays() == 2))
{
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->setThumbnailIcon(*mipReader.getOverlayMip(i));
}
}
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->update();
}
void NaMainWindow::initializeNeuronGallery()
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (! mipReader.hasReadLock()) return;
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons())
{
neuronGalleryButtonList.clear();
ui->fragmentGalleryWidget->clear(); // deletes buttons
// qDebug() << "Number of neuron masks = " << mipReader.getNumberOfNeurons();
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
GalleryButton* button = new GalleryButton(
*mipReader.getNeuronMip(i),
QString("Neuron fragment %1").arg(i),
i,
GalleryButton::NEURON_BUTTON);
button->setContextMenu(neuronContextMenu);
neuronGalleryButtonList.append(button);
ui->fragmentGalleryWidget->appendFragment(button);
}
// qDebug() << "createMaskGallery() end size=" << mipReader.getNumberOfNeurons();
}
// Update signals whether the buttons were already there or not
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i));
neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i));
neuronGalleryButtonList[i]->update();
neuronGalleryButtonList[i]->setNeuronSelectionModel(
dataFlowModel->getNeuronSelectionModel());
}
ui->fragmentGalleryWidget->updateButtonsGeometry();
}
// For microCT mode
/* slot */
void NaMainWindow::labelNeuronsAsFlyBrainCompartments() {
// If a second renaming scheme is ever needed, refactor this to load names from an
// external data source.
QList<QString> compartmentNames;
compartmentNames << "FB (Fan-shaped Body)";
compartmentNames << "EB (Ellipsoid Body)";
compartmentNames << "SAD (Saddle)";
compartmentNames << "NO (Noduli)";
compartmentNames << "SOG (Suboesophageal Ganglion)";
compartmentNames << "PB (Protocerebral Bridge)";
compartmentNames << "CRE_R (Crepine)";
compartmentNames << "EPA_R (Epaulette)";
compartmentNames << "VES_R (Vesta)";
compartmentNames << "ATL_R (Antler)";
compartmentNames << "PLP_R (Posterior Lateral Protocerebrum)";
compartmentNames << "AVLP_R (Anterior Ventro-lateral protocerebrum)";
compartmentNames << "AL_R (Antennal Lobe)";
compartmentNames << "GOR_R (Gorget)";
compartmentNames << "SCL_R (Superior Clamp)";
compartmentNames << "FLA (Flange)";
compartmentNames << "ICL_R (Inferior Clamp)";
compartmentNames << "ME_R (Medulla)";
compartmentNames << "LOP_R (Lobula Plate)";
compartmentNames << "LO_R (Lobula)";
compartmentNames << "MB_R (Mushroom Body)";
compartmentNames << "PVLP_R (Posterior Ventro-lateral Protocerebrum)";
compartmentNames << "OTU_R (Optic Tubercle)";
compartmentNames << "WED_R (Wedge)";
compartmentNames << "SMP_R (Superior Medial Protocerebrum)";
compartmentNames << "LH_R (Lateral Horn)";
compartmentNames << "SLP_R (Superior Lateral Protocerebrum)";
compartmentNames << "LB_R (Lateral Bulb)";
compartmentNames << "SIP_R (Superior Intermediate Protocerebrum)";
compartmentNames << "IB_R (Inferior Bridge)";
compartmentNames << "IVLP_R (Inferior Ventro-lateral Protocerebrum)";
compartmentNames << "IPS_R (Inferior Posterior Slope)";
compartmentNames << "SPS_R (Superior Posterior Slope)";
compartmentNames << "LAL_R (Lateral Accessory Lobe)";
compartmentNames << "PRW (Prow)";
compartmentNames << "AME_R (Accessory Medulla)";
compartmentNames << "GA_R (Gall)";
compartmentNames << "CRE_L (Crepine)";
compartmentNames << "EPA_L (Epaulette)";
compartmentNames << "VES_L (Vesta)";
compartmentNames << "ATL_L (Antler)";
compartmentNames << "PLP_L (Posterior Lateral Protocerebrum)";
compartmentNames << "AVLP_L (Anterior Ventro-lateral protocerebrum)";
compartmentNames << "AL_L (Antennal Lobe)";
compartmentNames << "GOR_L (Gorget)";
compartmentNames << "SCL_L (Superior Clamp)";
compartmentNames << "ICL_L (Inferior Clamp)";
compartmentNames << "ME_L (Medulla)";
compartmentNames << "LOP_L (Lobula Plate)";
compartmentNames << "LO_L (Lobula)";
compartmentNames << "MB_L (Mushroom Body)";
compartmentNames << "PVLP_L (Posterior Ventro-lateral Protocerebrum)";
compartmentNames << "OTU_L (Optic Tubercle)";
compartmentNames << "WED_L (Wedge)";
compartmentNames << "SMP_L (Superior Medial Protocerebrum)";
compartmentNames << "LH_L (Lateral Horn)";
compartmentNames << "SLP_L (Superior Lateral Protocerebrum)";
compartmentNames << "LB_L (Lateral Bulb)";
compartmentNames << "SIP_L (Superior Intermediate Protocerebrum)";
compartmentNames << "IB_L (Inferior Bridge)";
compartmentNames << "IVLP_L (Inferior Ventro-lateral Protocerebrum)";
compartmentNames << "IPS_L (Inferior Posterior Slope)";
compartmentNames << "SPS_L (Superior Posterior Slope)";
compartmentNames << "LAL_L (Lateral Accessory Lobe)";
compartmentNames << "AME_L (Accessory Medulla)";
compartmentNames << "GA_L (Gall)";
compartmentNames << "AMMC_L (Antennal Mechanosensory and Motor Centre)";
compartmentNames << "AMMC_R (Antennal Mechanosensory and Motor Centre)";
for (int i = 0; i < neuronGalleryButtonList.size(); ++ i) {
if (i >= compartmentNames.size())
break;
neuronGalleryButtonList[i]->setLabelText(compartmentNames[i]);
}
ui->fragmentGalleryWidget->updateNameSortTable();
}
void NaMainWindow::updateNeuronGallery()
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (! mipReader.hasReadLock()) return;
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons())
initializeNeuronGallery();
else {
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i));
neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i));
neuronGalleryButtonList[i]->update();
}
ui->fragmentGalleryWidget->updateButtonsGeometry();
}
}
void NaMainWindow::on3DViewerRotationChanged(const Rotation3D& rot)
{
Vector3D angles = rot.convertBodyFixedXYZRotationToThreeAngles();
int rotX = Na3DWidget::radToDeg(angles.x());
int rotY = Na3DWidget::radToDeg(angles.y());
int rotZ = Na3DWidget::radToDeg(angles.z());
int oldRotX = ui->rotXWidget->spinBox->value();
int oldRotY = ui->rotYWidget->spinBox->value();
int oldRotZ = ui->rotZWidget->spinBox->value();
if (Na3DWidget::eulerAnglesAreEquivalent(rotX, rotY, rotZ, oldRotX, oldRotY, oldRotZ))
return;
// Block signals from individual rot widgets until we update them all
ui->rotXWidget->blockSignals(true);
ui->rotYWidget->blockSignals(true);
ui->rotZWidget->blockSignals(true);
ui->rotXWidget->setAngle(rotX);
ui->rotYWidget->setAngle(rotY);
ui->rotZWidget->setAngle(rotZ);
ui->rotXWidget->blockSignals(false);
ui->rotYWidget->blockSignals(false);
ui->rotZWidget->blockSignals(false);
}
void NaMainWindow::update3DViewerXYZBodyRotation()
{
int rotX = ui->rotXWidget->spinBox->value();
int rotY = ui->rotYWidget->spinBox->value();
int rotZ = ui->rotZWidget->spinBox->value();
// qDebug() << rotX << ", " << rotY << ", " << rotZ;
ui->v3dr_glwidget->setXYZBodyRotationInt(rotX, rotY, rotZ);
}
// update neuron selected status
void NaMainWindow::synchronizeGalleryButtonsToAnnotationSession(QString updateString)
{
NeuronSelectionModel::Reader selectionReader(
dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
// We are not using the update string in this case, which is from the modelUpdated() signal,
// because we are doing a total update.
int maskStatusListSize=selectionReader.getMaskStatusList().size();
int neuronGalleryButtonSize=neuronGalleryButtonList.size();
assert(neuronGalleryButtonSize == maskStatusListSize);
for (int i = 0; i < maskStatusListSize; i++) {
neuronGalleryButtonList.at(i)->setChecked(
selectionReader.neuronMaskIsChecked(i));
}
// Reference toggle
if (selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) {
overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(true);
} else {
overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(false);
}
// Background toggle
if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) {
overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(true);
} else {
overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(false);
}
}
/* slot */
void NaMainWindow::setProgressValue(int progressValueParam)
{
if (progressValueParam >= 100) {
completeProgress();
return;
}
statusProgressBar->setValue(progressValueParam);
statusProgressBar->show();
}
/* slot */
void NaMainWindow::setProgressMessage(QString msg)
{
statusBar()->showMessage(""); // avoid overlap of temporary messages with progress message
statusProgressMessage->setText(msg);
statusProgressMessage->show();
}
/* slot */
void NaMainWindow::completeProgress()
{
statusProgressBar->hide();
statusProgressMessage->hide();
statusBar()->showMessage("", 500);
}
/* slot */
void NaMainWindow::abortProgress(QString msg)
{
statusProgressBar->hide();
statusProgressMessage->hide();
statusBar()->showMessage(msg, 1000);
}
static const bool use3DProgress = false;
void NaMainWindow::set3DProgress(int prog)
{
if (prog >= 100) {
complete3DProgress();
return;
}
if (use3DProgress) {
ui->progressBar3d->setValue(prog);
// ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior
ui->widget_progress3d->show();
}
else
setProgressValue(prog);
}
void NaMainWindow::complete3DProgress()
{
if (use3DProgress) {
ui->widget_progress3d->hide();
// avoid jerky resize to accomodated progress widget
QCoreApplication::processEvents(); // flush pending resize events
ui->v3dr_glwidget->resizeEvent(NULL);
ui->v3dr_glwidget->setResizeEnabled(true);
//
ui->v3dr_glwidget->update();
}
else completeProgress();
}
void NaMainWindow::set3DProgressMessage(QString msg)
{
if (use3DProgress) {
ui->progressLabel3d->setText(msg);
ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior
ui->widget_progress3d->show();
}
else
setProgressMessage(msg);
}
char* NaMainWindow::getConsoleURL()
{
return consoleUrl;
}
// NutateThread
| 37.425824 | 208 | 0.672696 |
ae20dffff4f5bece759d6338968d318650d624ea | 33,119 | cpp | C++ | SwaySensorA/SwaySensorA.cpp | SMH-MRD/SwaySensorA | 0e75ce6589c4a5c5bbec0349209e941ae54bd360 | [
"MIT"
] | null | null | null | SwaySensorA/SwaySensorA.cpp | SMH-MRD/SwaySensorA | 0e75ce6589c4a5c5bbec0349209e941ae54bd360 | [
"MIT"
] | 4 | 2020-06-11T08:26:50.000Z | 2020-08-24T00:45:13.000Z | SwaySensorA/SwaySensorA.cpp | SMH-MRD/SwaySensorA | 0e75ce6589c4a5c5bbec0349209e941ae54bd360 | [
"MIT"
] | null | null | null | // SwaySensorA.cpp : アプリケーションのエントリ ポイントを定義します。
//
#include "framework.h"
#include "SwaySensorA.h"
#include "inifile.h"
#include "CHelper.h"
#include "CTaskObj.h" /タスククラス
#include <windowsx.h> //コモンコントロール用
#include <commctrl.h> //コモンコントロール用
#include <shlwapi.h> //Win32 APIでパスを扱うには shlwapi.h に定義されている関数群(Path Routines)を使用
using namespace std;
#define MAX_LOADSTRING 100
// グローバル変数:
HINSTANCE hInst; // 現在のインターフェイス
WCHAR szTitle[MAX_LOADSTRING]; // タイトル バーのテキスト
WCHAR szWindowClass[MAX_LOADSTRING]; // メイン ウィンドウ クラス名
vector<void*> VectpCTaskObj; //タスクオブジェクトのポインタ
CSharedObject* g_pSharedObject; //タスク間共有データのポインタ
ST_iTask g_itask; //タスクID参照用グローバル変数
SYSTEMTIME gAppStartTime; //アプリケーション開始時間
LPWSTR pszInifile; // iniファイルのパス
wstring wstrPathExe; // 実行ファイルのパス
// スタティック変数:
// マルチタスク管理用
static ST_KNL_MANAGE_SET knl_manage_set; //マルチスレッド管理用構造体
static vector<HANDLE> VectHevent; //マルチスレッド用イベントのハンドル
static CSharedObject* cSharedData; // 共有オブジェクトインスタンス
// メインウィンドウパネル用
static vector<HWND> VectTweetHandle; //メインウィンドウのスレッドツイートメッセージ表示Staticハンドル
static HIMAGELIST hImgListTaskIcon; //タスクアイコン用イメージリスト
static HWND hTabWnd; //操作パネル用タブコントロールウィンドウのハンドル
static HWND hWnd_status_bar; //ステータスバーのウィンドウのハンドル
// このコード モジュールに含まれる関数の宣言を転送します:
// # アプリケーション専用関数: ************************************
// コア関数
VOID CALLBACK alarmHandlar(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2); //マルチメディアタイマ処理関数 スレッドのイベントオブジェクト処理
int Init_tasks(HWND hWnd, HINSTANCE hInstance); //アプリケーション毎のタスクオブジェクトの初期設定
DWORD knlTaskStartUp(); //実行させるタスクの起動処理
INT setIniParameter(ST_INI_INF* pInf, LPCWSTR pFileName); //iniファイルパラメータ設定処理
void CreateSharedData(void); //共有メモリCreate処理
static unsigned __stdcall thread_gate_func(void * pObj) { //スレッド実行のためのゲート関数
CTaskObj * pthread_obj = (CTaskObj *)pObj;
return pthread_obj->run(pObj);
}
// メインウィンドウパネル用
LRESULT CALLBACK TaskTabDlgProc(HWND, UINT, WPARAM, LPARAM); //個別タスク設定タブウィンドウ用メッセージハンドリング関数
HWND CreateStatusbarMain(HWND); //メインウィンドウステータスバー作成関数
HWND CreateTaskSettingWnd(HWND hWnd);
// # Wizard Default関数: ************************************
ATOM MyRegisterClass(HINSTANCE hInstance); // ウィンドウ クラスを登録します。
BOOL InitInstance(HINSTANCE, int); // メインウィンドウクリエイト
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // ウィンドウプロシージャ
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
// # 関数: wWinMain ************************************
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: ここにコードを挿入してください。
// グローバル文字列を初期化する
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_SWAYSENSORA, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// アプリケーション初期化の実行:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SWAYSENSORA));
MSG msg;
// メイン メッセージ ループ:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
for (unsigned i = 0; i < knl_manage_set.num_of_task; i++) {
CTaskObj * pobj = (CTaskObj *)VectpCTaskObj[i];
delete pobj;
}
return (int) msg.wParam;
}
///# 関数: MyRegisterClass() ************************************************************************
//
// 目的: ウィンドウ クラスを登録します。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SWAYSENSORA));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_SWAYSENSORA);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
///# 関数: InitInstance(HINSTANCE, int) *************************************************************
//
// 目的 : インスタンス ハンドルを保存して、メイン ウィンドウを作成します
// コメント : この関数で、グローバル変数でインスタンス ハンドルを保存し、メイン プログラム ウィンドウを作成および表示します。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // グローバル変数にインスタンス ハンドルを格納する
GetSystemTime(&gAppStartTime); //アプリケーション開始時刻取得
HWND hWnd = CreateWindowW(
szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, //lpClassName, lpWindowName, dwStyle,
MAIN_WND_INIT_POS_X, MAIN_WND_INIT_POS_Y, // x, y,
TAB_DIALOG_W + 40, (MSG_WND_H + MSG_WND_Y_SPACE)*TASK_NUM + TAB_DIALOG_H + 110, // Width, nHeight,
nullptr, nullptr, hInstance, nullptr); // hWndParent, hMenu, hInstance, lpParam
if (!hWnd) return FALSE;
g_pSharedObject = new CSharedObject();
/// -タスク設定
Init_tasks(hWnd,hInst);//タスク個別設定
///WM_PAINTを発生させてアイコンを描画させる
InvalidateRect(hWnd, NULL, FALSE);
///実行させる各オブジェクトのスレッドを起動 マルチメディアタイマー起動
knlTaskStartUp();
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
///# 関数: WndProc(HWND, UINT, WPARAM, LPARAM) ******************************************************
//
// 目的: メイン ウィンドウのメッセージを処理します。
// WM_COMMAND - アプリケーション メニューの処理
// WM_PAINT - メイン ウィンドウを描画する
// WM_DESTROY - 中止メッセージを表示して戻る
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
///メインウィンドウにステータスバー付加
hWnd_status_bar = CreateStatusbarMain(hWnd);
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// 選択されたメニューの解析:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_NOTIFY: {
int tab_index = TabCtrl_GetCurSel(((NMHDR *)lParam)->hwndFrom);//選択タブID取得
for (unsigned i = 0; i < VectpCTaskObj.size(); i++) {
CTaskObj * pObj = (CTaskObj *)VectpCTaskObj[i];
//MoveWindow(pObj->inf.hWnd_opepane, TAB_POS_X, TAB_POS_Y + TAB_SIZE_H, TAB_DIALOG_W, TAB_DIALOG_H - TAB_SIZE_H, TRUE);
if ((VectpCTaskObj.size() - 1 - pObj->inf.index) == tab_index) {
//タブ選択されたパネルウィンドウ表示
ShowWindow(pObj->inf.hWnd_opepane, SW_SHOW);
//パネルウィンドウにタブ選択されたパネルウィンドウ表示
HWND hname_static = GetDlgItem(pObj->inf.hWnd_opepane, IDC_TAB_TASKNAME);
SetWindowText(hname_static, pObj->inf.name);
pObj->set_panel_pb_txt();
#if 0
//実行関数の設定状況に応じてOption Checkボタンセット
if (pObj->inf.work_select == THREAD_WORK_OPTION1) {
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK1), BM_SETCHECK, BST_CHECKED, 0L);
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK2), BM_SETCHECK, BST_UNCHECKED, 0L);
}
else if (pObj->inf.work_select == THREAD_WORK_OPTION2) {
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK1), BM_SETCHECK, BST_UNCHECKED, 0L);
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK2), BM_SETCHECK, BST_CHECKED, 0L);
}
else {
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK1), BM_SETCHECK, BST_UNCHECKED, 0L);
SendMessage(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TASK_OPTION_CHECK2), BM_SETCHECK, BST_UNCHECKED, 0L);
}
#endif
// ウィンドウをフォアグラウンドに持ってくる
SetForegroundWindow(pObj->inf.hWnd_opepane);
}
else {
ShowWindow(pObj->inf.hWnd_opepane, SW_HIDE);
}
}
}break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: HDC を使用する描画コードをここに追加してください...
//タスクツィートメッセージアイコン描画
for (unsigned i = 0; i < knl_manage_set.num_of_task; i++) ImageList_Draw(hImgListTaskIcon, i, hdc, 0, i*(MSG_WND_H + MSG_WND_Y_SPACE), ILD_NORMAL);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
//各タスクスレッド停止
for (unsigned i = 0; i < knl_manage_set.num_of_task; i++) {
CTaskObj * pobj = (CTaskObj *)VectpCTaskObj[i];
pobj->inf.thread_com = TERMINATE_THREAD;
}
Sleep(100);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
///# 関数: スレッドタスクの登録、設定 ***
int Init_tasks(HWND hWnd, HINSTANCE hInstance) {
HBITMAP hBmp;
CTaskObj *ptempobj;
int task_index = 0;
//コモンコントロール初期化
InitCommonControls();
//タスクアイコン用イメージリストクリエイト
hImgListTaskIcon = ImageList_Create(32, 32, //int cx, int cy
ILC_COLOR | ILC_MASK, //UINT flags
2, 0); //int cInitial, int cGrow
CreateSharedData();//共有メモリクリエイト
//###Task1 設定 MANAGER
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CManager;
VectpCTaskObj.push_back((void*)ptempobj); //オブジェクトのポインタセット
g_itask.mng = task_index; //タスクIDセット
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト
//定周期タイマーイベント
VectHevent.push_back( //マルチメディアタイマー定周期起動用 Event Handle登録
ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL)//自動リセット,初期値非シグナル
);
//オプションイベント
//ptempobj->inf.hevents[ID_OPT1_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL)//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 1000;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_MANAGER");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, MANAGER_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, MANAGER_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task2 設定 PLAYER
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CPlayer;
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.ply = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(
ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL) //自動リセット,初期値非シグナル
);
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 50;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_PLAYER");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, PLAYER_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, PLAYER_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task3 設定 COMCLIENT
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CComClient;
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.comc = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 1000;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_COMCLIENT");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, CLIENT_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, CLIENT_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task4 設定 COMRIO
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CComRIO;
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.comd1 = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 50;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_RIOCOM");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, RIO_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, RIO_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task5 設定 COMCCAMERA
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CComCamera;
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.comd2 = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 50;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_CAMERACOM");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, CAMERA_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, CAMERA_COM_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task6 設定 CLERK
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CClerk();
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.clerk = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 1000;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_CLERK");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, CLERK_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, CLERK_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task7 設定 ANALYST
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CAnalyst;
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.ana = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 50;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_ANALYST");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, ANALYST_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, ANALYST_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
//###Task8 設定 PUBLICRELATION
{
/// -タスクインスタンス作成->リスト登録
ptempobj = new CPublicRelation();
VectpCTaskObj.push_back((void*)ptempobj);
g_itask.pr = task_index;
/// -タスクインデクスセット
ptempobj->inf.index = task_index++;
/// -イベントオブジェクトクリエイト->リスト登録
VectHevent.push_back(ptempobj->inf.hevents[ID_TIMER_EVENT] = CreateEvent(NULL, FALSE, FALSE, NULL));//自動リセット,初期値非シグナル
/// -スレッド起動周期セット
ptempobj->inf.cycle_ms = 50;
/// -ツイートメッセージ用iconセット
hBmp = (HBITMAP)LoadBitmap(hInst, L"IDB_PR");//ビットマップ割り当て
ImageList_AddMasked(hImgListTaskIcon, hBmp, RGB(255, 255, 255));
DeleteObject(hBmp);
///オブジェクト名セット
DWORD str_num = GetPrivateProfileString(OBJ_NAME_SECT_OF_INIFILE, PR_KEY_OF_INIFILE, L"No Name", ptempobj->inf.name, sizeof(ptempobj->inf.name) / 2, PATH_OF_INIFILE);
str_num = GetPrivateProfileString(OBJ_SNAME_SECT_OF_INIFILE, PR_KEY_OF_INIFILE, L"No Name", ptempobj->inf.sname, sizeof(ptempobj->inf.sname) / 2, PATH_OF_INIFILE);
///実行関数選択
ptempobj->inf.work_select = THREAD_WORK_ROUTINE;
///スレッド起動に使うイベント数(定周期タイマーのみの場合1)
ptempobj->inf.n_active_events = 1;
}
hTabWnd = CreateTaskSettingWnd(hWnd);//タブウィンドウ作成
//設定タスク数登録
knl_manage_set.num_of_task = (unsigned int)VectpCTaskObj.size();
//各タスク用残初期設定
for (unsigned i = 0; i < knl_manage_set.num_of_task; i++) {
CTaskObj * pobj = (CTaskObj *)VectpCTaskObj[i];
pobj->inf.index = i; //設定順でタスクインデックスセット
pobj->inf.hWnd_parent = hWnd; //親ウィンドウのハンドルセット
pobj->inf.hInstance = hInstance; //アプリケーションのハンドル
// -ツイートメッセージ用Static window作成->リスト登録
pobj->inf.hWnd_msgStatics = CreateWindow(L"STATIC", L"...", WS_CHILD | WS_VISIBLE, MSG_WND_ORG_X, MSG_WND_ORG_Y + MSG_WND_H * i + i * MSG_WND_Y_SPACE, MSG_WND_W, MSG_WND_H, hWnd, (HMENU)ID_STATIC_MAIN, hInst, NULL);
VectTweetHandle.push_back(pobj->inf.hWnd_msgStatics);
//その他設定
pobj->inf.psys_counter = &knl_manage_set.sys_counter; //システムカウンタ(基本周期でカウント)参照アドレスセット
pobj->inf.act_count = 0; //起動チェック用カウンタリセット
if (pobj->inf.cycle_ms >= SYSTEM_TICK_ms) //タスクスレッド起動を掛けるカウント値設定
pobj->inf.cycle_count = pobj->inf.cycle_ms / SYSTEM_TICK_ms;
else pobj->inf.cycle_count = 1;
pobj->init_task(pobj); //最後にタスク固有初期化関数呼び出し
}
return 1;
}
///# 関数: マルチタスクスタートアップ処理関数 ***
DWORD knlTaskStartUp() //実行させるオブジェクトのリストのスレッドを起動 マルチメディアタイマー起動
{
//機能 :[KNL]システム/ユーザタスクスタートアップ関数
//処理 :自プロセスのプライオリティ設定,カーネルの初期設定,タスク生成,基本周期設定
//戻り値:Win32APIエラーコード
HANDLE myPrcsHndl; /* 本プログラムのプロセスハンドル */
///# 自プロセスプライオリティ設定処理
//-プロセスハンドル取得
if ((myPrcsHndl = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION, FALSE, _getpid())) == NULL) return(GetLastError());
_RPT1(_CRT_WARN, "KNL Priority For Windows(before) = %d \n", GetPriorityClass(myPrcsHndl));//VisualStudio 出力
//-自プロセスのプライオリティを最優先ランクに設定
if (SetPriorityClass(myPrcsHndl, REALTIME_PRIORITY_CLASS) == 0) return(GetLastError());//VisualStudio 出力
_RPT1(_CRT_WARN, "KNL Priority For NT(after) = %d \n", GetPriorityClass(myPrcsHndl));
///# アプリケーションタスク数が最大数を超えた場合は終了
if (VectpCTaskObj.size() >= MAX_APL_TASK) return((DWORD)ERROR_BAD_ENVIRONMENT);
///# アプリケーションスレッド生成処理
for (unsigned i = 0; i < VectpCTaskObj.size(); i++) {
CTaskObj * pobj = (CTaskObj *)VectpCTaskObj[i];
// タスクスレッド生成
pobj->inf.hndl = (HANDLE)_beginthreadex(
(void *)NULL, // 他プロセスとの共有なし
0, // スタック初期サイズ デフォルト
thread_gate_func, // スレッド実行関数 引数で渡すオブジェクトで対象切り替え
VectpCTaskObj[i], // スレッド関数に渡すの引数(対象のオブジェクトのポインタ)
(unsigned)0, // 即実行Createflags
(unsigned *)&(pobj->inf.ID) // スレッドID取り込み
);
// タスクプライオリティ設定
if (SetThreadPriority(pobj->inf.hndl, pobj->inf.priority) == 0)
return(GetLastError());
_RPT2(_CRT_WARN, "Task[%d]_priority = %d\n", i, GetThreadPriority(pobj->inf.hndl));
pobj->inf.act_count = 0; // 基本ティックのカウンタ変数クリア
pobj->inf.time_over_count = 0; // 予定周期オーバーカウントクリア
}
/// -マルチメディアタイマ起動
{
/// > マルチメディアタイマ精度設定
TIMECAPS wTc;//マルチメディアタイマ精度構造体
//ハードウェアのタイマー能力チェック
if (timeGetDevCaps(&wTc, sizeof(TIMECAPS)) != TIMERR_NOERROR) return((DWORD)FALSE);
knl_manage_set.mmt_resolution = MIN(MAX(wTc.wPeriodMin, TARGET_RESOLUTION), wTc.wPeriodMax);
if (timeBeginPeriod(knl_manage_set.mmt_resolution) != TIMERR_NOERROR) return((DWORD)FALSE);
_RPT1(_CRT_WARN, "MMTimer Resolution = %d\n", knl_manage_set.mmt_resolution);
/// > マルチメディアタイマセット
knl_manage_set.KnlTick_TimerID = timeSetEvent(
knl_manage_set.cycle_base, // uDelay
knl_manage_set.mmt_resolution, // uResolution
(LPTIMECALLBACK)alarmHandlar, // lpTimeProc コールバック関数のアドレス
0, // dwUser ユーザー変数。このパラメータはコールバック関数に伝えられる
TIME_PERIODIC // タイマーの動作モード
);
/// >マルチメディアタイマー起動失敗判定 メッセージBOX出してFALSE returen
if (knl_manage_set.KnlTick_TimerID == 0) { //失敗確認表示
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
0, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language*/(LPTSTR)&lpMsgBuf, 0, NULL);
MessageBox(NULL, (LPCWSTR)lpMsgBuf, L"MMT Failed!!", MB_OK | MB_ICONINFORMATION);// Display the string.
LocalFree(lpMsgBuf);// Free the buffer.
return((DWORD)FALSE);
}
}
return 1;
}
///# バージョン情報ボックスのメッセージ ハンドラーです。 *********************************************
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
///# 関数: マルチメディアタイマーイベント処理関数 **********************************************
VOID CALLBACK alarmHandlar(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) {
LONG64 tmttl;
knl_manage_set.sys_counter++; //システムカウンタ更新
//スレッド再開イベントセット処理
for (unsigned i = 0; i < knl_manage_set.num_of_task; i++) { //登録した各タスクチェック
CTaskObj * pobj = (CTaskObj *)VectpCTaskObj[i];
pobj->inf.act_count++;
if (pobj->inf.act_count >= pobj->inf.cycle_count) { //登録したタスクの周期カウンタチェック
PulseEvent(VectHevent[i]); //イベント送信してタスクスレッドのループを回す
pobj->inf.act_count = 0; //タスクの周期カウンタリセット
pobj->inf.total_act++; //タスクスレッド起動回数カウンタ更新
}
}
//Statusバーに経過時間表示
if (knl_manage_set.sys_counter % 40 == 0) {// 1sec毎
//起動後経過時間計算
tmttl = knl_manage_set.sys_counter * knl_manage_set.cycle_base;//アプリケーション起動後の経過時間msec
knl_manage_set.Knl_Time.wMilliseconds = (WORD)(tmttl % 1000); tmttl /= 1000;
knl_manage_set.Knl_Time.wSecond = (WORD)(tmttl % 60); tmttl /= 60;
knl_manage_set.Knl_Time.wMinute = (WORD)(tmttl % 60); tmttl /= 60;
knl_manage_set.Knl_Time.wHour = (WORD)(tmttl % 60); tmttl /= 24;
knl_manage_set.Knl_Time.wDay = (WORD)(tmttl % 24);
TCHAR tbuf[32];
wsprintf(tbuf, L"%3dD %02d:%02d:%02d", knl_manage_set.Knl_Time.wDay, knl_manage_set.Knl_Time.wHour, knl_manage_set.Knl_Time.wMinute, knl_manage_set.Knl_Time.wSecond);
SendMessage(hWnd_status_bar, SB_SETTEXT, 5, (LPARAM)tbuf);
}
}
///# 関数: ini file読み込みパラメータ設定 *********************************************
INT setIniParameter(ST_INI_INF* pInf, LPCWSTR pFileName)
{
//--------------------------------------------------------------------------
// 設定ファイル存在チェック
if (!(PathFileExists(pFileName)) || PathIsDirectory(pFileName))
{
return RESULT_NG_INVALID;
}
//--------------------------------------------------------------------------
// 共通設定パラメータ
CHelper::GetIniInf(pFileName, INI_SCT_CAMERA, INI_KEY_CAM_EXPOSURE,
L"10000", INITYPE_INT, &(pInf->exposureTime)); // 露光時間
CHelper::GetIniInf(pFileName, INI_SCT_CAMERA, INI_KEY_CAM_WIDTH,
L"640", INITYPE_INT, &(pInf->camWidth)); // カメラ撮影横幅
CHelper::GetIniInf(pFileName, INI_SCT_CAMERA, INI_KEY_CAM_HEIGHT,
L"480", INITYPE_INT, &(pInf->camHeight)); // カメラ撮影高さ
CHelper::GetIniInf(pFileName, INI_SCT_CAMERA, INI_KEY_CAM_FRAMERATE,
L"30", INITYPE_INT, &(pInf->frameRate)); // フレームレート
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK1_EN,
L"1", INITYPE_INT, &(pInf->mask1En)); // マスク1有効無効
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK1_MIN,
L"0", INITYPE_INT, &(pInf->mask1Min)); // マスク1最小
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK1_MAX,
L"10", INITYPE_INT, &(pInf->mask1Max)); // マスク1最大
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK2_EN,
L"1", INITYPE_INT, &(pInf->mask2En)); // マスク2有効無効
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK2_MIN,
L"170", INITYPE_INT, &(pInf->mask2Min)); // マスク2最小
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK2_MAX,
L"180", INITYPE_INT, &(pInf->mask2Max)); // マスク2最大
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK3_EN,
L"1", INITYPE_INT, &(pInf->mask3En)); // マスク3有効無効
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK3_MIN,
L"80", INITYPE_INT, &(pInf->mask3Min)); // マスク3最小
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_MASK3_MAX,
L"100", INITYPE_INT, &(pInf->mask3Max)); // マスク3最大
CHelper::GetIniInf(pFileName, INI_SCT_OPENCV, INI_KEY_OPENCV_PROC_ALGO,
L"100", INITYPE_INT, &(pInf->procAlgo)); // 画像処理アルゴリズム
CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_IPADDR,
L"192.168.0.1", INITYPE_CHAR, &(pInf->rioIpAddr)); // RIO IPアドレス
CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_TCPPORTNUM,
L"502", INITYPE_INT, &(pInf->rioTcpPortNum)); // RIO TCPポート番号
CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_SLAVEADDR,
L"1", INITYPE_INT, &(pInf->rioSlaveAddr)); // RIOスレーブアドレス
CHelper::CHelper::CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_TIMEOUT,
L"2000", INITYPE_INT, &(pInf->rioTimeOut)); // RIOタイムアウト
CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_XPORTNUM,
L"1", INITYPE_INT, &(pInf->rioXPortNum)); // RIO傾斜計Xデータ接続ポート番号
CHelper::GetIniInf(pFileName, INI_SCT_RIO, INI_KEY_RIO_YPORTNUM,
L"2", INITYPE_INT, &(pInf->rioYPortNum)); // RIO傾斜計Yデータ接続ポート番号
return S_OK;
}
///# 関数: 共有オブジェクト初期化 ********************************************************************
void CreateSharedData(void) {
// ini file path
static WCHAR dstpath[_MAX_PATH], szDrive[_MAX_DRIVE], szPath[_MAX_PATH], szFName[_MAX_FNAME], szExt[_MAX_EXT];
//実行ファイルのパス取得
GetModuleFileName(NULL, dstpath, (sizeof(TCHAR) * _MAX_PATH) / 2);
//実行ファイルのパスを分割
_wsplitpath_s(dstpath, szDrive, sizeof(szDrive) / 2, szPath, sizeof(szPath) / 2, szFName, sizeof(szFName) / 2, szExt, sizeof(szExt) / 2);
// ini file path構成
wstrPathExe = szDrive; wstrPathExe += szPath;
_wmakepath_s(dstpath, sizeof(dstpath) / 2, szDrive, szPath, NAME_OF_INIFILE, EXT_OF_INIFILE);
pszInifile = dstpath;
ST_INI_INF ini;
setIniParameter(&ini, dstpath);
// cSharedData = new CSharedObject();
g_pSharedObject->InitSharedObject();
g_pSharedObject->SetParam(PARAM_ID_CAM_EXPOSURE_TIME, (UINT32)ini.exposureTime);
g_pSharedObject->SetParam(PARAM_ID_CAM_FRAMERATE, (UINT32)ini.frameRate);
g_pSharedObject->SetParam(PARAM_ID_CAM_WIDTH, (UINT32)ini.camWidth);
g_pSharedObject->SetParam(PARAM_ID_CAM_HEIGHT, (UINT32)ini.camHeight);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE1_EN, (UINT32)ini.mask1En);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE1_MIN, (UINT32)ini.mask1Min);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE1_MAX, (UINT32)ini.mask1Max);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE2_EN, (UINT32)ini.mask2En);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE2_MIN, (UINT32)ini.mask2Min);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE2_MAX, (UINT32)ini.mask2Max);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE3_EN, (UINT32)ini.mask3En);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE3_MIN, (UINT32)ini.mask3Min);
g_pSharedObject->SetParam(PARAM_ID_PIC_HUE3_MAX, (UINT32)ini.mask3Max);
g_pSharedObject->SetParam(PARAM_ID_PIC_COG_ALGO, (UINT32)ini.procAlgo);
char* cstr = (char*)malloc(sizeof(ini.rioIpAddr));
if (cstr != NULL) {
size_t size;
wcstombs_s(&size, cstr, sizeof(ini.rioIpAddr), ini.rioIpAddr, sizeof(ini.rioIpAddr));
string str = cstr;
g_pSharedObject->SetParam(PARAM_ID_STR_RIO_IPADDR, str);
free(cstr);
}
g_pSharedObject->SetParam(PARAM_ID_RIO_TCPPORT, (UINT32)ini.rioTcpPortNum);
g_pSharedObject->SetParam(PARAM_ID_RIO_SLAVEADDR, (UINT32)ini.rioSlaveAddr);
g_pSharedObject->SetParam(PARAM_ID_RIO_TIMEOUT, (UINT32)ini.rioTimeOut);
g_pSharedObject->SetParam(PARAM_ID_RIO_XPORT, (UINT32)ini.rioXPortNum);
g_pSharedObject->SetParam(PARAM_ID_RIO_YPORT, (UINT32)ini.rioYPortNum);
}
///# 関数: ステータスバー作成 *****************************************************************
HWND CreateStatusbarMain(HWND hWnd)
{
HWND hSBWnd;
int sb_size[] = { 100,200,300,400,525,615 };//ステータス区切り位置
InitCommonControls();
hSBWnd = CreateWindowEx(
0, //拡張スタイル
STATUSCLASSNAME, //ウィンドウクラス
NULL, //タイトル
WS_CHILD | SBS_SIZEGRIP, //ウィンドウスタイル
0, 0, //位置
0, 0, //幅、高さ
hWnd, //親ウィンドウ
(HMENU)ID_STATUS, //ウィンドウのID
hInst, //インスタンスハンドル
NULL);
SendMessage(hSBWnd, SB_SETPARTS, (WPARAM)6, (LPARAM)(LPINT)sb_size);//6枠で各枠の仕切り位置をパラーメータ指定
ShowWindow(hSBWnd, SW_SHOW);
return hSBWnd;
}
///# 関数: タブ付タスクウィンドウ作成 *******
HWND CreateTaskSettingWnd(HWND hWnd) {
RECT rc;
TC_ITEM tc[TASK_NUM];
GetClientRect(hWnd, &rc);
HWND hTab = CreateWindowEx(
0, WC_TABCONTROL, NULL, WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | TCS_BUTTONS,
rc.left + TAB_POS_X, rc.top + TAB_POS_Y, TAB_DIALOG_W, TAB_DIALOG_H,
hWnd, (HMENU)ID_TASK_SET_TAB, hInst, NULL
);
for (unsigned i = 0; i < VectpCTaskObj.size(); i++) {//Task Setting用タブ作成
CTaskObj* pObj = (CTaskObj *)VectpCTaskObj[i];
tc[i].mask = (TCIF_TEXT | TCIF_IMAGE);
tc[i].pszText = pObj->inf.sname;
tc[i].iImage = pObj->inf.index;
SendMessage(hTab, TCM_INSERTITEM, (WPARAM)0, (LPARAM)&tc[i]);
pObj->inf.hWnd_opepane = CreateDialog(hInst, L"IDD_DIALOG_TASKSET", hWnd, (DLGPROC)TaskTabDlgProc);
pObj->set_panel_pb_txt();
MoveWindow(pObj->inf.hWnd_opepane, TAB_POS_X, TAB_POS_Y + TAB_SIZE_H, TAB_DIALOG_W, TAB_DIALOG_H - TAB_SIZE_H, TRUE);
//初期値はindex 最後のウィンドウを表示
if (i == VectpCTaskObj.size()-1) {
ShowWindow(pObj->inf.hWnd_opepane, SW_SHOW);
SetWindowText(GetDlgItem(pObj->inf.hWnd_opepane, IDC_TAB_TASKNAME), pObj->inf.name);//タスク名をスタティックテキストに表示
}
else ShowWindow(pObj->inf.hWnd_opepane, SW_HIDE);
}
//タブコントロールにイメージリストセット
SendMessage(hTab, TCM_SETIMAGELIST, (WPARAM)0, (LPARAM)hImgListTaskIcon);
return hTab;
}
static LVCOLUMNA lvcol;
LRESULT CALLBACK TaskTabDlgProc(HWND hDlg, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg) {
case WM_INITDIALOG: {
InitCommonControls();
//メッセージ用リスト
LVCOLUMN lvcol;
LPTSTR strItem0[] = { (LPTSTR)(L"time"), (LPTSTR)(L"message") };//列ラベル
int CX[] = { 60, 600 };//列幅
//リストコントロール設定
HWND hList = GetDlgItem(hDlg, IDC_LIST1);
lvcol.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvcol.fmt = LVCFMT_LEFT;
for (int i = 0; i < 2; i++) {
lvcol.cx = CX[i]; // 表示位置
lvcol.pszText = strItem0[i]; // 見出し
lvcol.iSubItem = i; // サブアイテムの番号
ListView_InsertColumn(hList, i, &lvcol);
}
//リスト行追加
LVITEM item;
item.mask = LVIF_TEXT;
for (int i = 0; i < MSG_LIST_MAX; i++) {
item.pszText = (LPWSTR)L"."; // テキスト
item.iItem = i; // 番号
item.iSubItem = 0; // サブアイテムの番号
ListView_InsertItem(hList, &item);
}
return TRUE;
}break;
case WM_COMMAND: {
CTaskObj * pObj = (CTaskObj *)VectpCTaskObj[VectpCTaskObj.size() - TabCtrl_GetCurSel(hTabWnd) - 1];
pObj->PanelProc(hDlg, msg, wp, lp);
}break;
}
return FALSE;
}
| 35.345784 | 217 | 0.69202 |
ae21813026e4767736b777c70f4cdb75a5f38fd7 | 37,937 | cpp | C++ | src/test/requestmanager_tests.cpp | an4s/bitcoinunlimited_shortidresolver | fef28f6371a9de454dfc8406351bb88ab8ea311e | [
"MIT"
] | null | null | null | src/test/requestmanager_tests.cpp | an4s/bitcoinunlimited_shortidresolver | fef28f6371a9de454dfc8406351bb88ab8ea311e | [
"MIT"
] | null | null | null | src/test/requestmanager_tests.cpp | an4s/bitcoinunlimited_shortidresolver | fef28f6371a9de454dfc8406351bb88ab8ea311e | [
"MIT"
] | null | null | null | // Copyright (c) 2016-2019 The Bitcoin Unlimited Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blockrelay/blockrelay_common.h"
#include "blockrelay/graphene.h"
#include "blockrelay/thinblock.h"
#include "bloom.h"
#include "chainparams.h"
#include "dosman.h"
#include "main.h"
#include "net.h"
#include "primitives/block.h"
#include "protocol.h"
#include "random.h"
#include "requestManager.h"
#include "serialize.h"
#include "streams.h"
#include "streams.h"
#include "txmempool.h"
#include "uint256.h"
#include "unlimited.h"
#include "util.h"
#include "utilstrencodings.h"
#include "validation/validation.h"
#include "version.h"
#include "test/test_bitcoin.h"
#include <algorithm>
#include <atomic>
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <string>
extern CTweak<uint64_t> grapheneMaxVersionSupported;
class CRequestManagerTest
{
private:
CRequestManager *_rman;
public:
CRequestManagerTest(CRequestManager *r) { _rman = r; }
std::map<uint256, CUnknownObj> GetMapTxnInfo() { return _rman->mapTxnInfo; }
std::map<uint256, CUnknownObj> GetMapBlkInfo() { return _rman->mapBlkInfo; }
};
// Cleanup all maps
static void CleanupAll(std::vector<CNode *> &vPeers)
{
for (auto pnode : vPeers)
{
thinrelay.ClearAllBlocksToReconstruct(pnode->GetId());
thinrelay.ClearAllBlocksInFlight(pnode->GetId());
thinrelay.RemovePeers(pnode);
{
LOCK(pnode->cs_vSend);
pnode->vSendMsg.clear();
pnode->vLowPrioritySendMsg.clear();
}
}
requester.MapBlocksInFlightClear();
}
// Return the netmessage string for a block/xthin/graphene request
static std::string NetMessage(std::deque<CSerializeData> &_vSendMsg)
{
if (_vSendMsg.size() == 0)
return "none";
CInv inv_result;
CSerializeData data = _vSendMsg.front();
std::string ssData(data.begin(), data.end());
std::string ss(ssData.begin() + 4, ssData.begin() + 16);
_vSendMsg.pop_front();
// Remove whitespace
ss.erase(std::remove(ss.begin(), ss.end(), '\000'), ss.end());
// if it's a getdata then we need to find out what type
if (ss == "getdata")
{
CDataStream ssInv(SER_NETWORK, PROTOCOL_VERSION);
ssInv.insert(ssInv.begin(), ssData.begin() + 25, ssData.begin() + 61);
CInv inv;
ssInv >> inv;
if (inv.type == MSG_BLOCK)
return "getdata";
else if (inv.type == MSG_CMPCT_BLOCK)
return "cmpctblock";
else
return "nothing";
}
return ss;
}
static void ClearThinBlocksInFlight(CNode &node, CInv &inv) { thinrelay.ClearBlockInFlight(node.GetId(), inv.hash); }
BOOST_FIXTURE_TEST_SUITE(requestmanager_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(blockrequest_tests)
{
// Test the requesting of blocks/graphenblocks/thinblocks with varying node configurations.
// This tests all the code paths within RequestBlock() in the request manager.
// create dummy test addrs
CAddress addr_xthin(ipaddress(0xa0b0c001, 10000));
CAddress addr_graphene(ipaddress(0xa0b0c002, 10001));
CAddress addr_cmpct(ipaddress(0xa0b0c003, 10002));
CAddress addr_none(ipaddress(0xa0b0c004, 10003));
// create nodes
CNode dummyNodeXthin(INVALID_SOCKET, addr_xthin, "", true);
CNode dummyNodeGraphene(INVALID_SOCKET, addr_graphene, "", true);
CNode dummyNodeCmpct(INVALID_SOCKET, addr_cmpct, "", true);
CNode dummyNodeNone(INVALID_SOCKET, addr_none, "", true);
dummyNodeXthin.nVersion = MIN_PEER_PROTO_VERSION;
SetConnected(dummyNodeXthin);
dummyNodeXthin.nServices |= NODE_XTHIN;
dummyNodeXthin.nServices &= ~NODE_GRAPHENE;
dummyNodeXthin.fSupportsCompactBlocks = false;
dummyNodeXthin.id = 1;
dummyNodeGraphene.nVersion = MIN_PEER_PROTO_VERSION;
SetConnected(dummyNodeGraphene);
dummyNodeGraphene.nServices |= NODE_GRAPHENE;
dummyNodeGraphene.nServices &= ~NODE_XTHIN;
dummyNodeGraphene.fSupportsCompactBlocks = false;
dummyNodeGraphene.id = 2;
// This dummy node does not exchange a simulated xversion so jam in graphene supported version.
dummyNodeGraphene.negotiatedGrapheneVersion = grapheneMaxVersionSupported.Value();
dummyNodeCmpct.nVersion = MIN_PEER_PROTO_VERSION;
SetConnected(dummyNodeCmpct);
dummyNodeCmpct.nServices &= ~NODE_GRAPHENE;
dummyNodeCmpct.nServices &= ~NODE_XTHIN;
dummyNodeCmpct.fSupportsCompactBlocks = true;
dummyNodeCmpct.id = 3;
dummyNodeNone.nVersion = MIN_PEER_PROTO_VERSION;
SetConnected(dummyNodeNone);
dummyNodeNone.nServices &= ~NODE_GRAPHENE;
dummyNodeNone.nServices &= ~NODE_XTHIN;
dummyNodeNone.fSupportsCompactBlocks = false;
dummyNodeNone.id = 4;
// Add to vNodes
vNodes.push_back(&dummyNodeXthin);
vNodes.push_back(&dummyNodeGraphene);
vNodes.push_back(&dummyNodeCmpct);
vNodes.push_back(&dummyNodeNone);
// Initialize Nodes
GetNodeSignals().InitializeNode(&dummyNodeXthin);
GetNodeSignals().InitializeNode(&dummyNodeGraphene);
GetNodeSignals().InitializeNode(&dummyNodeCmpct);
GetNodeSignals().InitializeNode(&dummyNodeNone);
// Create basic Inv for requesting blocks. This simulates an entry in the request manager for a block
// download.
uint256 hash = InsecureRand256();
uint256 randhash = InsecureRand256();
CInv inv(MSG_BLOCK, hash);
CInv inv_cmpct(MSG_CMPCT_BLOCK, hash);
uint64_t nTime = GetTime();
dosMan.ClearBanned();
/** Block in flight tests */
// Try to add the same block twice which will fail the second attempt.
// We should only be allowed one unique thintype block in flight
thinrelay.AddBlockInFlight(&dummyNodeGraphene, hash, NetMsgType::GRAPHENEBLOCK);
BOOST_CHECK(!thinrelay.AreTooManyBlocksInFlight());
BOOST_CHECK(!thinrelay.AddBlockInFlight(&dummyNodeGraphene, hash, NetMsgType::GRAPHENEBLOCK));
// Add 4 more blocks in flight
thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK);
thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK);
thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK);
thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK);
BOOST_CHECK(!thinrelay.AreTooManyBlocksInFlight());
// Add one more which is the max blocks in flight. A call to TooManyBlocksInFlight() will now
// return false.
BOOST_CHECK(thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK));
BOOST_CHECK(thinrelay.AreTooManyBlocksInFlight());
// Try to add one beyond the maximum which should fail
BOOST_CHECK(!thinrelay.AddBlockInFlight(&dummyNodeGraphene, GetRandHash(), NetMsgType::GRAPHENEBLOCK));
CleanupAll(vNodes);
// Test the General Case: Chain synced, graphene ON, Thinblocks ON, Cmpct ON
// This should return a Graphene block.
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "get_xthin");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv_cmpct) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "cmpctblock");
thinrelay.ClearBlockRelayTimer(inv_cmpct.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Test the General Case: Chain synced, graphene ON, Thinblocks ON, Cmpct ON
// This should return a Graphene block.
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "get_xthin");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv_cmpct) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "cmpctblock");
thinrelay.ClearBlockRelayTimer(inv_cmpct.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Thin timer disabled: Chain synced, graphene ON, Thinblocks OFF, Cmpct ON
// Although the timer would have been on because one relay type was off, here we explicity turn off
// the timer. We should still be able to request a Graphene, or Cmpct or regular block
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
SetArg("-preferential-timer", "0");
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
// This test would generally cause a request for a "get_xthin", however xthins is not on and
// the timer is off which results in a full block request.
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv_cmpct) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "cmpctblock");
thinrelay.ClearBlockRelayTimer(inv_cmpct.hash);
CleanupAll(vNodes);
inv.type = MSG_BLOCK;
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
SetArg("-preferential-timer", "10000"); // reset from 0
// Chain NOT synced with any nodes, graphene ON, Thinblocks ON, Cmpct ON
IsChainNearlySyncdSet(false);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "getdata");
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "getdata");
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd: No graphene nodes, No Thinblock nodes, No Cmpct nodes, Thinblocks OFF, Graphene OFF, CMPCT OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
ClearThinBlocksInFlight(dummyNodeNone, inv);
requester.MapBlocksInFlightClear();
thinrelay.RemovePeers(&dummyNodeNone);
CleanupAll(vNodes);
// Chains IS sync'd: HAVE graphene nodes, NO Thinblock nodes, No Cmpt nodes, Graphene OFF, Thinblocks OFF,
// Compactblocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpt nodes, Graphene OFF, Thinblocks ON, Cmpctblocks
// OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpt nodes, Graphene OFF, Thinblocks OFF,
// Cmpctblocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Graphene OFF, Thinblocks ON,
// Cmpctblocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Graphene OFF, Thinblocks ON,
// Cmpctblocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Graphene OFF, Thinblocks OFF,
// Cmpctblocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks OFF, Graphene ON, Cmpct
// blocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks OFF, Graphene ON, Cmpct
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks OFF, Graphene OFF, Cmpct
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks OFF, Graphene OFF, Cmpct
// blocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpctblock nodes, Thinblocks OFF, Graphene ON, Cmpt
// blocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpctblock nodes, Thinblocks OFF, Graphene ON, Cmpt
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpctblock nodes, Thinblocks ON, Graphene ON, Cmpt
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, NO Thinblock nodes, No Cmpctblock nodes, Thinblocks ON, Graphene ON, Cmpt
// blocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Thinblocks ON, Graphene ON, Cmpct
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Thinblocks OFF, Graphene ON, Cmpct
// blocks ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, NO Thinblock nodes, No Cmpct nodes, Thinblocks OFF, Graphene ON, Cmpct
// blocks OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Thinblocks ON, Graphene ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "get_grblk");
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks ON, Graphene OFF, Cmpct
// OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "get_xthin");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, HAVE Thinblock nodes, No Cmpct Nodes, Thinblocks ON, Graphene ON, Cmpct ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "get_xthin");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, No Thinblock nodes, Have Cmpct Nodes, Thinblocks OFF, Graphene OFF, Cmpct
// ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", false);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv_cmpct) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "cmpctblock");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Chains IS sync'd, NO graphene nodes, No Thinblock nodes, Have Cmpct Nodes, Thinblocks ON, Graphene ON, Cmpct ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv_cmpct) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "cmpctblock");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check full blocks are downloaded when no block announcements come from a graphene, thinblock or cmpct peer.
* The timers in this case will be disabled so we will immediately download a full block.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Have Cmpct node, Thinblocks ON, Graphene ON, Cmpct
// ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check full blocks are downloaded when graphene is off but thin type timer is exceeded
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Have Cmpct nodes, Graphene OFF, Thinblocks ON,
// Cmpct ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should fail but the xthin timer should be triggered
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == false);
// Now move the clock ahead so that the timer is exceeded and we should now
// download a full block
SetMockTime(nTime + 20);
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeNone.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check a full block is downloaded when Graphene timer is exceeded but then we get an announcement
* from a graphene peer (thinblocks is OFF), and then request from that graphene peer before we
* request from any others.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Thinblocks OFF, Graphene ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", false);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should fail but the timers should be triggered for graphene
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == false);
// Now move the clock ahead so that the timer is exceeded and we should now
// download a full block
SetMockTime(nTime + 20);
randhash = InsecureRand256();
thinrelay.AddBlockInFlight(&dummyNodeGraphene, randhash, NetMsgType::GRAPHENEBLOCK);
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeGraphene.vSendMsg) == "getdata");
CleanupAll(vNodes);
/******************************
* Check another graphene block is downloaded when Graphene timer is exceeded and then we get an announcement
* from a graphene peer (thinblocks is ON), and then request from that graphene peer before we
* request from any others.
* However this time we already have a grapheneblock in flight but we end up downloading another graphene block
* because we haven't exceeded the limit on number of thintype blocks in flight.
* Then proceed to request more thintype blocks until the limit is exceeded.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Thinblocks ON, Graphene ON, Cmpct OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", true);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", false);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should suceed as should successive requests up until the limit of thintype requests in flight
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 1);
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 2);
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 3);
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 4);
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == true);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 5);
// Now move the clock ahead so that the timers are exceeded and we should now
// download an xthin
SetMockTime(nTime + 20);
{
LOCK(dummyNodeXthin.cs_vSend);
dummyNodeXthin.vSendMsg.clear();
}
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(dummyNodeXthin.GetSendMsgSize() == 1);
// Try to send a 7th block. It should fail to send as it's above the limit of thintype blocks in flight.
inv.hash = InsecureRand256();
BOOST_CHECK(requester.RequestBlock(&dummyNodeGraphene, inv) == false);
BOOST_CHECK(dummyNodeGraphene.GetSendMsgSize() == 5);
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check a Xthin is is downloaded when thinblock timer is exceeded but then we get an announcement
* from a thinblock peer, and then request from that thinblock peer before we request from any others.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Thinblocks ON, Graphene OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should fail but the timers should be triggered for xthin
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == false);
// Now move the clock ahead so that the timer is exceeded and we should now
// download a full block
SetMockTime(nTime + 20);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check a Xthin is is downloaded when thinblock timer is exceeded but then we get an announcement
* from a thinblock peer, and then request from that thinblock peer before we request from any others.
* However this time we already have an xthin in flight for this peer so we end up downloading a full block.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Thinblocks ON, Graphene OFF
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should fail but the timers should be triggered for xthin
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == false);
// Now move the clock ahead so that the timer is exceeded and we should now
// download a full block
SetMockTime(nTime + 20);
randhash = InsecureRand256();
thinrelay.AddBlockInFlight(&dummyNodeXthin, randhash, NetMsgType::XTHINBLOCK);
BOOST_CHECK(requester.RequestBlock(&dummyNodeXthin, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeXthin.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
/******************************
* Check a full block is is downloaded when thinblock timer is exceeded but then we get an announcement
* from a cmpctblock peer, and then request from that cmpctnblock peer before we request from any others.
* However this time we already have an cmpctblk in flight for this peer so we end up downloading a full block.
*/
// Chains IS sync'd, HAVE graphene nodes, HAVE Thinblock nodes, Have Cmpct nodes, Thinblocks OFF, Graphene OFF,
// Cmpct ON
IsChainNearlySyncdSet(true);
SetBoolArg("-use-grapheneblocks", false);
SetBoolArg("-use-thinblocks", true);
SetBoolArg("-use-compactblocks", true);
thinrelay.AddPeers(&dummyNodeGraphene);
thinrelay.AddPeers(&dummyNodeXthin);
thinrelay.AddCompactBlockPeer(&dummyNodeCmpct);
thinrelay.AddPeers(&dummyNodeNone);
// Set mocktime
nTime = GetTime();
SetMockTime(nTime);
// The first request should fail but the timers should be triggered for cmpctblock
BOOST_CHECK(requester.RequestBlock(&dummyNodeNone, inv) == false);
// Now move the clock ahead so that the timer is exceeded and we should now
// download a full block
SetMockTime(nTime + 20);
randhash = InsecureRand256();
thinrelay.AddBlockInFlight(&dummyNodeCmpct, randhash, NetMsgType::CMPCTBLOCK);
BOOST_CHECK(requester.RequestBlock(&dummyNodeCmpct, inv) == true);
BOOST_CHECK(NetMessage(dummyNodeCmpct.vSendMsg) == "getdata");
thinrelay.ClearBlockRelayTimer(inv.hash);
CleanupAll(vNodes);
// Final cleanup: Unset mocktime
SetMockTime(0);
requester.MapBlocksInFlightClear();
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), &dummyNodeGraphene), vNodes.end());
vNodes.erase(remove(vNodes.begin(), vNodes.end(), &dummyNodeNone), vNodes.end());
vNodes.erase(remove(vNodes.begin(), vNodes.end(), &dummyNodeCmpct), vNodes.end());
vNodes.erase(remove(vNodes.begin(), vNodes.end(), &dummyNodeXthin), vNodes.end());
}
BOOST_AUTO_TEST_CASE(askfor_tests)
{
CAddress addr1(ipaddress(0xa0b0c001, 10000));
CAddress addr2(ipaddress(0xa0b0c002, 10001));
// create nodes
CNode dummyNode1(INVALID_SOCKET, addr1, "", true);
CNode dummyNode2(INVALID_SOCKET, addr2, "", true);
CRequestManager rman;
CRequestManagerTest rman_access(&rman);
std::map<uint256, CUnknownObj> mapTxn;
std::map<uint256, CUnknownObj> mapBlk;
/*** tests for transactions ***/
uint256 hash_txn = GetRandHash();
CInv inv_txn(MSG_TX, hash_txn);
rman.AskFor(inv_txn, &dummyNode1);
mapTxn = rman_access.GetMapTxnInfo();
BOOST_CHECK(mapTxn[inv_txn.hash].availableFrom.size() == 1);
// all sources should be removed and no new ones added.
rman.ProcessingTxn(inv_txn.hash, &dummyNode1);
rman.AskFor(inv_txn, &dummyNode2);
mapTxn = rman_access.GetMapTxnInfo();
BOOST_CHECK(mapTxn[inv_txn.hash].availableFrom.size() == 0);
/*** tests for blocks ***/
uint256 hash_block = GetRandHash();
CInv inv_block(MSG_BLOCK, hash_block);
rman.AskFor(inv_block, &dummyNode1);
mapBlk = rman_access.GetMapBlkInfo();
BOOST_CHECK(mapBlk[inv_block.hash].availableFrom.size() == 1);
// blocks are handled differently than transactions. A new source should have been added.
rman.ProcessingBlock(inv_block.hash, &dummyNode1);
rman.AskFor(inv_block, &dummyNode2);
mapBlk = rman_access.GetMapBlkInfo();
BOOST_CHECK(mapBlk[inv_block.hash].availableFrom.size() == 2); // should add another source
}
BOOST_AUTO_TEST_SUITE_END()
| 39.807975 | 120 | 0.71798 |
ae223da69d12a8042f518d725fe23972111e156a | 580 | cpp | C++ | contest/AOJ/0035.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AOJ/0035.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AOJ/0035.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "geometry/polygon.hpp"
#include "string.hpp"
int main() {
setBoolName("YES", "NO");
for (String line; line = in, !in.eof;) {
auto v = line.split(',').transform(cast<String, long double>());
Polygon polygon(4);
for (int i = 0; i < 4; ++i) {
polygon[i] = Point(v[2 * i], v[2 * i + 1]);
}
if (polygon.area() < 0) {
polygon.reverse();
}
auto is_convex = [](const Vector<Point> &corner) {
return ccw(Segment(corner[0], corner[1]), corner[2]) != RIGHT;
};
cout << polygon.getCorners().all_of(is_convex) << endl;
}
}
| 27.619048 | 68 | 0.555172 |
ae264600552d13c8335eae879cf3250abfc1074d | 5,203 | cpp | C++ | ass2/Ass2_3.cpp | krishna-akula/OSLab | 09ea00eb9b346a2a51b39a0948d05b4f3b414342 | [
"MIT"
] | null | null | null | ass2/Ass2_3.cpp | krishna-akula/OSLab | 09ea00eb9b346a2a51b39a0948d05b4f3b414342 | [
"MIT"
] | null | null | null | ass2/Ass2_3.cpp | krishna-akula/OSLab | 09ea00eb9b346a2a51b39a0948d05b4f3b414342 | [
"MIT"
] | null | null | null | #include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<string>
#include<cstring>
#include<sstream>
#include<vector>
#include<iostream>
using namespace std;
struct cmd_info{
int type;
string infilename,outfilename,filename;
string cmd;
string fcmd;
string path;
char *argv[1024];
int size;
cmd_info()
{
size=0;
}
};
void run_internal_cmd(cmd_info &rd)
{
int status=-1;
if(rd.fcmd=="mkdir")
{
status=mkdir((rd.path).c_str(),0777);
}
else if(rd.fcmd=="rm")
{
status=rmdir((rd.path).c_str());
}
else if(rd.fcmd=="cd")
{
char cwd[256];
getcwd(cwd,sizeof(cwd));
cout<<"Original directory:\t"<<cwd<<"\n";
status=chdir((rd.path).c_str());
getcwd(cwd,sizeof(cwd));
cout<<"Changed directory:\t"<<cwd<<"\n";
}
if(status==-1)
cout<<"enter correct command\n";
else
cout<<"command executed successfully\n";
}
void run_exec(cmd_info &rd)
{
pid_t id_child;
int cstatus=0;
pid_t c;
int in,out;
id_child=fork();
if(id_child==0)
{
if(rd.type==3)
{
in = open(rd.filename.c_str(), O_RDONLY);
dup2(in,0);
}
else if(rd.type==4)
{
out = open(rd.filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
dup2(out,1);
}
// execlp("/bin/sh",argc);
// if(rd.type==5)
// {
// //setpgid(0,0);
// fclose(stdin);
// }
// setpgid(0,0);
execvp((rd.cmd).c_str(),rd.argv);
cout<<"Child process could not do execlp.\n";//error if the child process is not executed
exit(2);
}
else if(id_child==-1)
{
//if forking is failed
cout<<"Fork failed\n";
}
else
{
if(rd.type==5)
waitpid(id_child,&cstatus,WNOHANG);
else
waitpid(id_child,&cstatus,0);
}
}
void get_tokens(cmd_info &rd,string command_line)
{
istringstream iss(command_line);
string word;
iss>>rd.cmd;
if((rd.cmd).size()>0){
rd.argv[rd.size]=new char[(rd.cmd).length()+1];
strcpy(rd.argv[rd.size],(rd.cmd).c_str());
rd.size++;
}
else rd.cmd=" ";
while(iss >> word) {
if(word==">" or word=="<")
{
iss>>rd.filename;
rd.type=word==">"?4:3;
break;
}
else if(word=="&")
{
break;
}
rd.argv[rd.size]=new char[word.length()+1];
strcpy(rd.argv[rd.size],word.c_str());
rd.size++;
}
if(rd.size==0)
{
rd.argv[0]=" ";
rd.size++;
}
rd.argv[rd.size]='\0';
}
void connect_cmds(int in,int out,cmd_info & rd,int last)
{
pid_t id_child;
pid_t c;
int cstatus;
id_child=fork();
if(id_child==0)
{
if(in!=0)
{
dup2(in,0);
close(in);
}
if(out!=1 and !last)
{
// close(in);
dup2(out,1);
close(out);
}
execvp((rd.cmd).c_str(),rd.argv);
cout<<" chld process could not be constructed\n";
exit(1);
}
else
{
c=wait(&cstatus);
close(in);
close(out);
return;
}
}
void run_pipe_cmds(vector<cmd_info> &rds)
{
int n=rds.size();
int pipes[n-1][2];
int in=0;
// pipe(pipes);
int stdo,stdi;
stdi=dup(0);
stdo=dup(1);
for(int i=0;i<n-1;i++)
{
pipe(pipes[i]);
}
for(int i=0;i<n;i++)
{
if(i==n-1)
{
connect_cmds(in,1,rds[i],1);
dup2(stdi,0);
dup2(stdo,1);
}
else
{
dup2(in,0);
connect_cmds(in,pipes[i][1],rds[i],0);
in = pipes[i][0];
}
}
}
int main()
{
cout<<"----------------------------------------------------------------------------------------------\n";
cout<<"select the option for excecution\n";
cout<<"1.\tInternal command\n";
cout<<"2:\tExternal command\n";
cout<<"3:\tExternal command by redirectting standard input\n";
cout<<"4:\tExternal command by redirectting standard output\n";
cout<<"5:\tExternal command in the background\n";
cout<<"6:\tExternal command by for pipelining execution\n";
cout<<"7:\tQuit the program\n";
while(1)
{
int choice;
pid_t par;
par=getpid();
cmd_info rd;
cout<<">option\t\t:";
cin>>choice;
cout<<"\n";
if(choice<1 or choice>=7)
break;
string command_line,word;
cin.ignore(256, '\n');
cout<<">command\t:";
getline(cin,command_line);
cout<<"\n";
rd.type=choice;
if(choice==1)
{
istringstream iss(command_line);
iss>>rd.fcmd;
iss>>rd.path;
run_internal_cmd(rd);
}
else if( (choice>=2 and choice <=4) or choice==5)
{
get_tokens(rd,command_line);
run_exec(rd);
}
else if(choice==6)
{
vector<string>pipe_cmds;
string delim="|";
size_t pos = 0;
string token;
while ((pos = command_line.find(delim)) != string::npos) {
token = command_line.substr(0, pos);
pipe_cmds.push_back(token);
command_line.erase(0, pos + delim.length());
}
if(command_line.size()!=0)
{
pipe_cmds.push_back(command_line);
}
vector< cmd_info >rds(pipe_cmds.size());
for(int i=0;i<pipe_cmds.size();i++)
{
rds[i].type=2;
get_tokens(rds[i],pipe_cmds[i]);
}
// cout<<rds.size()<<endl;
run_pipe_cmds(rds);
}
if(getpid()!=par)
{
exit(1);
}
}
} | 17.171617 | 106 | 0.55641 |
ae26a8066b1380a0d36c6e3d5e87ca7977f0762f | 506 | cpp | C++ | 6.ExceptionHandling/i-Assess/HallBookingBO.cpp | Concept-Team/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 26 | 2021-03-17T03:15:22.000Z | 2021-06-09T13:29:41.000Z | 6.ExceptionHandling/i-Assess/HallBookingBO.cpp | Servatom/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 6 | 2021-03-16T19:04:05.000Z | 2021-06-03T13:41:04.000Z | 6.ExceptionHandling/i-Assess/HallBookingBO.cpp | Concept-Team/e-box-UTA018 | a6caf487c9f27a5ca30a00847ed49a163049f67e | [
"MIT"
] | 42 | 2021-03-17T03:16:22.000Z | 2021-06-14T21:11:20.000Z | #include<iostream>
#include<list>
#include"HallBooking.cpp"
#include<iterator>
using namespace std;
class HallBookingBO{
public:
bool validateHallBooking(list<HallBooking> lst,HallBooking hallObj){
try{
for(HallBooking h: lst){
if(h.getHall()==hallObj.getHall()&&h.getDateOfBooking()==hallObj.getDateOfBooking()){
throw 1;
}
}
}catch(...){
return false;
}
return true;
}
}; | 24.095238 | 101 | 0.551383 |
ae2a6ab82e3b1a653467db1256731298173dee6a | 268 | cpp | C++ | LastHope Engine/Component.cpp | rohomedesrius/LastHopeEngine | 5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0 | [
"MIT"
] | 1 | 2018-10-03T14:01:40.000Z | 2018-10-03T14:01:40.000Z | LastHope Engine/Component.cpp | rohomedesrius/LastHopeEngine | 5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0 | [
"MIT"
] | null | null | null | LastHope Engine/Component.cpp | rohomedesrius/LastHopeEngine | 5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0 | [
"MIT"
] | null | null | null | #include "Component.h"
GameObject* Component::GetGameObject() const
{
return game_object;
}
bool Component::IsActive() const
{
return active;
}
void Component::SetActive(bool value)
{
active = value;
}
ComponentType Component::GetType() const
{
return type;
}
| 12.181818 | 44 | 0.727612 |
ae2c515406c9ae9c65d4a3b150e08c2c989fafc9 | 2,598 | hpp | C++ | include/multi_sync_replayer.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | 9 | 2021-09-04T15:14:57.000Z | 2022-03-29T04:34:13.000Z | include/multi_sync_replayer.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | null | null | null | include/multi_sync_replayer.hpp | dabinkim-LGOM/lsc_planner | 88dcb1de59bac810d1b1fd194fe2b8d24d1860c9 | [
"MIT"
] | 4 | 2021-09-29T11:32:54.000Z | 2022-03-06T05:24:33.000Z | #pragma once
#include <ros/ros.h>
#include <param.hpp>
#include <mission.hpp>
#include <obstacle_generator.hpp>
#include <visualization_msgs/MarkerArray.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Float64MultiArray.h>
#include <util.hpp>
namespace DynamicPlanning {
class MultiSyncReplayer {
public:
MultiSyncReplayer(const ros::NodeHandle& _nh, Param _param, Mission _mission);
void initializeReplay();
void replay(double t);
void readCSVFile(const std::string& file_name);
void setOctomap(std::string file_name);
private:
ros::NodeHandle nh;
ros::Publisher pub_agent_trajectories;
ros::Publisher pub_obstacle_trajectories;
ros::Publisher pub_collision_model;
ros::Publisher pub_start_goal_points;
// ros::Publisher pub_safety_margin_to_agents;
// ros::Publisher pub_safety_margin_to_obstacles;
ros::Publisher pub_agent_velocities_x;
ros::Publisher pub_agent_velocities_y;
ros::Publisher pub_agent_velocities_z;
ros::Publisher pub_agent_accelerations_x;
ros::Publisher pub_agent_accelerations_y;
ros::Publisher pub_agent_accelerations_z;
ros::Publisher pub_agent_vel_limits;
ros::Publisher pub_agent_acc_limits;
ros::Publisher pub_world_boundary;
ros::Publisher pub_collision_alert;
Param param;
Mission mission;
std::shared_ptr<DynamicEDTOctomap> distmap_obj;
ObstacleGenerator obstacle_generator;
visualization_msgs::MarkerArray msg_agent_trajectories_replay;
visualization_msgs::MarkerArray msg_obstacle_trajectories_replay;
std::vector<std::vector<State>> agent_state_history;
std::vector<std::vector<State>> obstacle_state_history;
// std_msgs::Float64MultiArray safety_margin_to_agents_replay;
// std_msgs::Float64MultiArray safety_margin_to_obstacles_replay;
// std::vector<std::vector<double>> safety_margin_to_agents_history;
// std::vector<std::vector<double>> safety_margin_to_obstacles_history;
double timeStep, makeSpan;
void doReplay(double t);
void publish_agent_trajectories(double t);
void publish_obstacle_trajectories(double t);
void publish_collision_model();
void publish_start_goal_points();
// void publish_safety_margin(double t);
void publish_collision_alert();
void publish_agent_vel_acc(double t);
static std::vector<std::string> csv_read_row(std::istream& in, char delimiter);
};
}
| 33.307692 | 87 | 0.711316 |
ae2d3ee25a6ac1b5bde055317dabe97eabc70e44 | 1,764 | cpp | C++ | CF R405/B.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | CF R405/B.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | CF R405/B.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define forall(i,a,b) for(int i=a;i<b;i++)
#define ll long long int
#define llu long long unsigned
#define vll vector<ll>
#define vllu vector<llu>
#define sll set<ll>
#define sllu set<llu>
#define pb push_back
#define mll map<ll,ll>
#define mllu map<llu,llu>
#define miN(a,b) ( (a) < (b) ? (a) : (b))
#define maX(a,b) ( (a) > (b) ? (a) : (b))
#define mod 1000000007
int main()
{
#ifndef ONLINE_JUDGE
freopen("B_in.txt","r",stdin);
#endif
int n,m;
cin>>n>>m;
int a[n][n];
forall(i,0,n)
forall(j,0,n)
a[i][j]=0;
forall(i,0,m)
{
ll p, q;
cin>>p>>q;
a[p-1][q-1]=1;
}
int c[n][n];
forall(i,0,n)
{
forall(j,0,n)
{
c[i][j]=0;
forall(k,0,n){
c[i][j]=c[i][j]+(a[i][k]*a[k][j]);
if(c[i][j]>0)
break;
}
}
}
int ans=1;
int i,j;
// for(i=0;i<n;++i)
// {
// for(j=0;j<n;++j)
// {
// cout<<a[i][j]<<" ";
// }
// cout<<"\n";
// }
// for(i=0;i<n;++i)
// {
// for(j=0;j<n;++j)
// {
// cout<<c[i][j]<<" ";
// }
// cout<<"\n";
// }
forall(i,0,n)
{
forall(j,0,n)
{
if(c[i][j]>0 && a[i][j]!=1)
{
ans=0;
break;
}
}
if(!ans)break;
}
if(ans)
cout<<"YES";
else
cout<<"NO";
return 0;
}
| 19.173913 | 61 | 0.3322 |
ae2d8775f8329e8e9c17bff4ec195a3d69b6d59f | 32,224 | cpp | C++ | DRE2008OS_plugins/DRE2008_OS_Callback.cpp | GreatCong/GUI_EC_PluginSrc | 9194e67b76f3707f782f1fc17ba6e6dcb712c2a5 | [
"MIT"
] | 1 | 2019-12-25T13:36:01.000Z | 2019-12-25T13:36:01.000Z | DRE2008OS_plugins/DRE2008_OS_Callback.cpp | GreatCong/GUI_EC_PluginSrc | 9194e67b76f3707f782f1fc17ba6e6dcb712c2a5 | [
"MIT"
] | null | null | null | DRE2008OS_plugins/DRE2008_OS_Callback.cpp | GreatCong/GUI_EC_PluginSrc | 9194e67b76f3707f782f1fc17ba6e6dcb712c2a5 | [
"MIT"
] | 1 | 2020-08-05T14:05:15.000Z | 2020-08-05T14:05:15.000Z | #include "DRE2008_OS_Callback.h"
#include <QDebug>
//int slave_num = 1;
//int16_t Normal_AD_Input[8] = { 0,0,0,0,0,0,0,0 };
char file[500]; //需要保存数据的文件
DRE2008_OS_Callback::DRE2008_OS_Callback(QObject *parent) : QObject(parent),Ethercat_Callback()
{
m_isOS_Reset = false;//超采样初始化
m_isOS_Run = false;
pre_OverSampling_CycleCount = 0;
output_ptr = nullptr;
input_ptr = nullptr;
m_measure_Q = new QQueue<int16_t>();
m_OS_Channel = OS_CH1; //超采样通道设置
m_SamplingRate = 20; //采样率设置(最大40Khz)
m_AD_Channel = AD_CH1;
m_ErrState = Error_None;
memset(m_Normal_AD_Input,0,sizeof(m_Normal_AD_Input));
}
void DRE2008_OS_Callback::Master_AppLoop_callback()
{
static int reset_num = 0;
if(m_isOS_Run){
if(!m_isOS_Reset){//这里貌似是需要按顺序执行,稍后再改
//超采样设置
if(reset_num < 3){//先Reset,再进行其他操作
reset_num++;
// DRE2008_OS_Reset(slave_num); //DRE2008-OS复位(禁止超采样)
// pre_OverSampling_CycleCount = 0;
DRE2008_OS_Reset(output_ptr); //DRE2008-OS复位(禁止超采样)
pre_OverSampling_CycleCount = 0;
}
else{
DRE2008_OS_SamplingRateSet(output_ptr, m_SamplingRate); //设置采样率
DRE2008_OS_Enable(output_ptr, m_OS_Channel); //设置超采样通道并使能超采样
m_isOS_Reset = true;
reset_num = 0;
}
}
else{
DRE2008_OS_NormalInputRead(input_ptr, m_Normal_AD_Input); //普通模式数据采集
// qDebug() << Normal_AD_Input[0];
m_ErrState = DRE2008_OS_OverSamplingInputLog(input_ptr, m_OS_Channel, 0, file, m_AD_Channel); //超采样数据log
// if(m_ErrState != Error_None){
// qDebug() << m_ErrState;
// }
}
}
else{
pre_OverSampling_CycleCount = 0;
DRE2008_OS_SamplingRateSet(output_ptr, 50);
DRE2008_OS_Disable(output_ptr);
// printf("required %d data log complete!\n", num_of_samples);
// TestKillTimer(1);
}
}
void DRE2008_OS_Callback::Master_AppStart_callback()
{
// qDebug() << "Index1:" << this->Master_getSlaveChooseIndex();
output_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).outputs_offset);//这里需要根据扫描到的地址替换
input_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).inputs_offset);
m_isOS_Reset = false;//超采样初始化
pre_OverSampling_CycleCount = 0;//超采样获取中的参数
m_isOS_Run = false;
// initQueue(&my_ecQueue.my_ecQueue_ch1);
m_measure_Q->clear();
emit Master_RunStateChanged(true);
}
void DRE2008_OS_Callback::Master_AppStop_callback()
{
m_isOS_Reset = false;//超采样初始化
m_isOS_Run = false;
// clearQueue(&my_ecQueue.my_ecQueue_ch1);
m_measure_Q->clear();
emit Master_RunStateChanged(false);
}
void DRE2008_OS_Callback::Master_AppScan_callback()
{
emit Sig_MasterScanChanged();
}
void DRE2008_OS_Callback::Master_ReleaseAddress()
{
m_Master_addressBase = NULL;
output_ptr = NULL;
input_ptr = NULL;
}
int DRE2008_OS_Callback::Master_setAdressBase(char *address)
{
m_Master_addressBase = address;
return 0;
}
void DRE2008_OS_Callback::Set_OverSampling_run(bool isRun)
{
m_isOS_Run = isRun;
}
void DRE2008_OS_Callback::Set_OverSampling_Reset(bool isReset)
{
m_isOS_Reset = isReset;
}
const QString DRE2008_OS_Callback::ErrorState_ToString()
{
QString str;
switch(m_ErrState){
case Error_None:
str = "Error_None";
break;
case Error_NoFile:
str = "Error_NoFile";
break;
case Error_File_WriteOver:
str = "Error_File_WriteOver";
break;
case Error_TimeOut:
str = "Error_TimeOut";
break;
case Error_Channel_Invalid:
str = "Error_Channel_Invalid";
break;
default:
str = "ErrorCode:"+QString::number(m_ErrState);
break;
}
return str;
}
/* DRE2008 */
void DRE2008_OS_Callback::DRE2008_OS_Reset(uint8_t *data_OutPtr)
{
// int i = 0;
DRE2008_OS_SamplingRateSet(data_OutPtr, 50);
DRE2008_OS_Disable(data_OutPtr);
// while(i < 50)
// {
// ec_send_processdata();
// ec_receive_processdata(EC_TIMEOUTRET);
// osal_usleep(2000);
// i++;
// }
// printf("RESET OVER......\n");
// qDebug() << "RESET OVER......";
}
void DRE2008_OS_Callback::DRE2008_OS_SamplingRateSet(uint8_t *data_Outptr, int SamplingRate)
{
uint8_t *data_out;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++ = SamplingRate & 0xFF;
*data_out++ = SamplingRate >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_Enable(uint8_t *data_Outptr, int channel)
{
uint8_t *data_out;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++;
*data_out++;
*data_out++ = channel & 0xFF;
*data_out++ = channel >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_Disable(uint8_t *data_Outptr)
{
uint8_t *data_out;
int channel = OS_NONE;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++;
*data_out++;
*data_out++ = channel & 0xFF;
*data_out++ = channel >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_NormalInputRead(uint8_t *data_Inptr, int16_t *NormalInput)
{
uint8_t *data_in;
int16_t temp1, temp2;
// data_in = ec_slave[slave_num].inputs;
data_in = data_Inptr;
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[0] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[1] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[2] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[3] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[4] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[5] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[6] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[7] = temp1 + (temp2 << 8);
}
void DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputRead(uint8_t *data_Inptr, int32_t *CycleCount, int16_t *OverSamplingInput)
{
uint8_t *data_in;
int16_t temp1, temp2, temp3, temp4;
// data_in = ec_slave[slave_num].inputs;
data_in = data_Inptr;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
temp1 = *data_in++;
temp2 = *data_in++;
temp3 = *data_in++;
temp4 = *data_in++;
*CycleCount = temp1 + (temp2 << 8) + (temp3 << 16) + (temp4 << 24);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[0] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[1] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[2] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[3] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[4] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[5] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[6] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[7] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[8] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[9] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[10] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[11] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[12] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[13] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[14] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[15] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[16] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[17] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[18] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[19] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[20] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[21] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[22] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[23] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[24] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[25] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[26] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[27] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[28] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[29] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[30] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[31] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[32] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[33] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[34] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[35] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[36] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[37] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[38] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[39] = temp1 + (temp2 << 8);
}
int DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputLog(uint8_t *data_Inptr, int channel, int num_of_samples, char *file, int dis_channel)
{
// FILE *fpWrite;
(void*)(&num_of_samples);
(void*)file;
int32_t OverSampling_CycleCount = 0;
int16_t OverSampling_AD_Input[40] = { 0 };
// static int32_t pre_OverSampling_CycleCount = 0;
int circlecount_error = 3;//当前周期读取到的circlrcount与上一周期的差值,理论为1,将该值设置大于1可提高容错率但会造成部分数据丢失
int ret = Error_None;
// int channelDis_temp = 0;
// channelDis_temp = dis_channel -1;//C语言数组从0开始,而参数是从1开始
int channelDis_temp = dis_channel;//dis_channel本身从0开始
DRE2008_OS_OverSamplingInputRead(data_Inptr, &OverSampling_CycleCount, OverSampling_AD_Input);//读取40个数据
switch (channel)
{
case OS_CH1://CH1超采样
{
if((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 1, OverSampling_AD_Input[0]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 2, OverSampling_AD_Input[1]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 3, OverSampling_AD_Input[2]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 4, OverSampling_AD_Input[3]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 5, OverSampling_AD_Input[4]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 6, OverSampling_AD_Input[5]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 7, OverSampling_AD_Input[6]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 8, OverSampling_AD_Input[7]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 9, OverSampling_AD_Input[8]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 10, OverSampling_AD_Input[9]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 11, OverSampling_AD_Input[10]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 12, OverSampling_AD_Input[11]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 13, OverSampling_AD_Input[12]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 14, OverSampling_AD_Input[13]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 15, OverSampling_AD_Input[14]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 16, OverSampling_AD_Input[15]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 17, OverSampling_AD_Input[16]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 18, OverSampling_AD_Input[17]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 19, OverSampling_AD_Input[18]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 20, OverSampling_AD_Input[19]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 21, OverSampling_AD_Input[20]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 22, OverSampling_AD_Input[21]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 23, OverSampling_AD_Input[22]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 24, OverSampling_AD_Input[23]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 25, OverSampling_AD_Input[24]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 26, OverSampling_AD_Input[25]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 27, OverSampling_AD_Input[26]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 28, OverSampling_AD_Input[27]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 29, OverSampling_AD_Input[28]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 30, OverSampling_AD_Input[29]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 31, OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 32, OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 33, OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 34, OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 35, OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 36, OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 37, OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 38, OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 39, OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 40, OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 1){
for(int index=0,loop_num = 0;loop_num < 40;index++,loop_num++){
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
// qDebug() << OverSampling_AD_Input[index];
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else {
ret = Error_Channel_Invalid;//通道不匹配
}
// if (((OverSampling_CycleCount - 1) * 40 + 40) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;//表示满了
// }
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH2://CH1-CH2超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[20]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[21]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[22]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[23]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[24]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[25]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[26]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[27]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[28]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[29]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 11, OverSampling_AD_Input[10], OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 12, OverSampling_AD_Input[11], OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 13, OverSampling_AD_Input[12], OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 14, OverSampling_AD_Input[13], OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 15, OverSampling_AD_Input[14], OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 16, OverSampling_AD_Input[15], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 17, OverSampling_AD_Input[16], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 18, OverSampling_AD_Input[17], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 19, OverSampling_AD_Input[18], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 20, OverSampling_AD_Input[19], OverSampling_AD_Input[39]);
// fclose(fpWrite);
// if (((OverSampling_CycleCount - 1) * 20 + 20) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
if(channelDis_temp < 2){
for(int index = channelDis_temp*20,loop_num = 0;loop_num < 20;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else {
ret = Error_Channel_Invalid;
}
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH4://CH1-CH4超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return -1;
// }
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[10], \
// OverSampling_AD_Input[20], OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[11], \
// OverSampling_AD_Input[21], OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[12], \
// OverSampling_AD_Input[22], OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[13], \
// OverSampling_AD_Input[23], OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[14], \
// OverSampling_AD_Input[24], OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[15], \
// OverSampling_AD_Input[25], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[16], \
// OverSampling_AD_Input[26], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[17], \
// OverSampling_AD_Input[27], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[18], \
// OverSampling_AD_Input[28], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[19], \
// OverSampling_AD_Input[29], OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 4){
for(int index = channelDis_temp*10,loop_num = 0;loop_num < 10;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else{
ret = Error_Channel_Invalid;
}
// if (((OverSampling_CycleCount - 1) * 10 + 10) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH8://CH1-CH8超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[5], \
// OverSampling_AD_Input[10], OverSampling_AD_Input[15], \
// OverSampling_AD_Input[20], OverSampling_AD_Input[25], \
// OverSampling_AD_Input[30], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[6], \
// OverSampling_AD_Input[11], OverSampling_AD_Input[16], \
// OverSampling_AD_Input[21], OverSampling_AD_Input[26], \
// OverSampling_AD_Input[31], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[7], \
// OverSampling_AD_Input[12], OverSampling_AD_Input[17], \
// OverSampling_AD_Input[22], OverSampling_AD_Input[27], \
// OverSampling_AD_Input[32], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[8], \
// OverSampling_AD_Input[13], OverSampling_AD_Input[18], \
// OverSampling_AD_Input[23], OverSampling_AD_Input[28], \
// OverSampling_AD_Input[33], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[9], \
// OverSampling_AD_Input[14], OverSampling_AD_Input[19], \
// OverSampling_AD_Input[24], OverSampling_AD_Input[29], \
// OverSampling_AD_Input[34], OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 8){
for(int index = channelDis_temp*5,loop_num = 0;loop_num < 5;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else{
ret = Error_Channel_Invalid;
}
// if (((OverSampling_CycleCount - 1) * 5 + 5) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("The required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
}
else{
ret = Error_TimeOut;
}
break;
}
default:
break;
}
return ret;
}
| 43.961801 | 172 | 0.543105 |
ae2d8c0a1f4465bf6b72f7b7cc39561f4ef0ad19 | 1,798 | hpp | C++ | include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp | mgorshkov/np | 75c7adff38e7260371135839b547d5340f3ca367 | [
"MIT"
] | null | null | null | /*
C++ numpy-like template-based array implementation
Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <np/ndarray/dynamic/NDArrayDynamicDecl.hpp>
namespace np::ndarray::array_dynamic {
// Sort an array
template<typename DType, typename Storage>
inline void NDArrayDynamic<DType, Storage>::sort() {
m_ArrayImpl.sort();
auto shape = m_ArrayImpl.shape();
shape.flatten();
m_ArrayImpl.setShape(shape);
}
// Sort the elements of an array's axis
// TODO
// template<typename DType, typename Storage>
// template<std::size_t N>
// inline void NDArrayDynamic<DType, Storage>::sort(std::optional<Axis<N>> axis) {
// }
} // namespace np::ndarray::array_dynamic
| 36.693878 | 86 | 0.74861 |
ae3120a1f2b602611be0945168db439e9cd8076f | 35 | cpp | C++ | NotifyServer/SQLThreadConPool.cpp | lijialong1234/TeachNotice | 27ec630d1a8e669bd30df406ea6618d8fbce8c3b | [
"MIT"
] | 2 | 2019-05-25T13:25:33.000Z | 2019-06-03T06:48:24.000Z | NotifyServer/SQLThreadConPool.cpp | lijialong1234/TeachNotice | 27ec630d1a8e669bd30df406ea6618d8fbce8c3b | [
"MIT"
] | null | null | null | NotifyServer/SQLThreadConPool.cpp | lijialong1234/TeachNotice | 27ec630d1a8e669bd30df406ea6618d8fbce8c3b | [
"MIT"
] | null | null | null | #include "SQLThreadConPool.h"
| 8.75 | 30 | 0.685714 |
ae38f72c78ef42f31273498ba0aa14853c32c46e | 8,622 | cpp | C++ | Cpp/Docker/OBJ.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 5 | 2019-08-19T18:18:08.000Z | 2019-12-13T19:26:03.000Z | Cpp/Docker/OBJ.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 3 | 2019-04-15T19:24:36.000Z | 2020-02-29T13:09:07.000Z | Cpp/Docker/OBJ.cpp | Gabidal/GAC | f36b76bceb6a39a87b50c393eb3540f4085bd879 | [
"MIT"
] | 2 | 2019-10-08T23:16:05.000Z | 2019-12-18T22:58:04.000Z | #include "../../H/Docker/OBJ.h"
#include "../../H/BackEnd/Selector.h"
#include "../../H/Nodes/Node.h"
#include "../../H/Assembler/Assembler_Types.h"
#include "../../H/UI/Usr.h"
#include "../../H/UI/Safe.h"
#include "../../H/Assembler/Assembler.h"
#include "../../H/Docker/Docker.h"
extern Selector* selector;
extern Node* Global_Scope;
extern Usr* sys;
extern Assembler* assembler;
vector<OBJ::Section> OBJ::Gather_All_Sections(vector<char> buffer, int Section_Count)
{
vector<Section> Result;
for (int i = sizeof(Header); i < Section_Count; i += sizeof(Section)) {
Result.push_back(*(Section*)&(buffer[i]));
}
return Result;
}
vector<string> OBJ::Get_Symbol_Table_Content(Header h, vector<char> buffer)
{
vector<string> Result;
vector<Symbol> Symbols;
for (int i = *(int*)h.Pointer_To_Symbol_Table; i < buffer.size(); i++) {
Symbols.push_back(*(Symbol*)&(buffer[i]));
}
for (auto& S : Symbols) {
if (S.Name.Header == 0) {
string Name = "";
for (int i = *(int*)S.Name.Offset; i < buffer.size(); i++) {
if (buffer[i] == '\0')
break;
Name += buffer[i];
}
Result.push_back(Name);
}
else
Result.push_back(string(S.Full_Name, 8));
}
return Result;
}
void OBJ::OBJ_Analyser(vector<string>& Output) {
//get the header and then start up the section suckup syste 2000 :D
//read the file
vector<uint8_t> tmp = DOCKER::Get_Char_Buffer_From_File(DOCKER::Working_Dir.back().second + DOCKER::FileName.back(), "");
vector<char> Buffer = vector<char>(*(char*)tmp.data(), tmp.size());
//read the header of this obj file
Header header = *(Header*)&Buffer;
DOCKER::Append(Output, Get_Symbol_Table_Content(header, Buffer));
}
vector<unsigned char> OBJ::Create_Obj(vector<Byte_Map_Section*> Input){
OBJ::Header header;
header.Machine = selector->OBJ_Machine_ID;
header.Number_OF_Sections = Input.size();
header.Date_Time = time_t(time(NULL));
header.Pointer_To_Symbol_Table = offsetof(OBJ::Header, Characteristics) + sizeof(Header::Characteristics) + sizeof(OBJ::Section) * Input.size();
//calculate the exports and import functions from global scope
for (auto s : Global_Scope->Defined){
if (s->Has(vector<string>{"export", "import"}) > 0){
header.Number_Of_Symbols++;
}
}
header.Size_Of_Optional_Header = 0;
header.Characteristics = _IMAGE_FILE_LARGE_ADDRESS_AWARE;
// header.Magic = _MAGIC_PE32_PlUS;
// header.Linker_Version = 0x0000;
// for (auto i : Input){
// header.Size_Of_Code += i->Calculated_Size;
// }
// for (auto i : Input){
// if (i->Is_Data_Section)
// header.Size_Of_Initialized_Data += i->Calculated_Size;
// }
// header.Size_Of_Uninitialized_Data = 0;
// if (sys->Info.Format == "lib"){
// header.Address_Of_Entry_Point = 0;
// }
// else{
// string Unmangled_Starting_Function_Name = sys->Info.Start_Function_Name;
// Node* Function = Global_Scope->Find(Unmangled_Starting_Function_Name, Global_Scope, FUNCTION_NODE);
// if (Function == nullptr){
// Report(Observation(ERROR, "Function " + Unmangled_Starting_Function_Name + " not found in the global scope", LINKER_MISSING_STARTING_FUNCTION));
// return vector<unsigned char>();
// }
// string Mangled_Starting_Function_Name = Function->Mangled_Name;
// header.Address_Of_Entry_Point = assembler->Symbol_Table.at(Mangled_Starting_Function_Name);
// }
// header.Base_Of_Code = Input.size() * sizeof(Section) + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header);
// header.Base_Of_Data = header.Base_Of_Code + header.Size_Of_Code;
// if (sys->Info.OS == "win"){
// if (sys->Info.Format == "exe"){
// header.Image_Base = _WINDOWS_PE_EXE_BASE_IMAGE;
// }
// else if (sys->Info.Format == "dll"){
// header.Image_Base = _WINDOWS_PE_DLL_BASE_IMAGE;
// }
// }
// header.Section_Alignment = _FILE_ALIGNMENT;
// header.File_Alignment = _FILE_ALIGNMENT;
// header.Operating_System_Version = 0x0006;
// header.Image_Version = 0;
// header.Subsystem_Version = 0;
// header.Win32_Version_Value = 0;
// header.Size_Of_Image = header.Size_Of_Code + header.Size_Of_Initialized_Data + header.Size_Of_Uninitialized_Data + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header);
// header.Size_Of_Headers = sizeof(Header) + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol);
// header.Check_Sum = 0;
// header.Subsystem = 0;
// header.Dll_Characteristics = 0;
// header.Size_Of_Stack_Reserve = 0x100000;
// header.Size_Of_Stack_Commit = 0x1000;
// //Allocate for one bucket + bucket buffer for the Evie allocator.
// header.Size_Of_Heap_Reserve = _BUCKET_SIZE;
// header.Size_Of_Heap_Commit = _ALLOCATOR_BUCKET_COUNT + _BUCKET_SIZE;
// header.Loader_Flags = 0;
// header.Number_Of_Rva_And_Sizes = 0;
vector<OBJ::Symbol> Symbols = Generate_Symbol_Table();
vector<string> Symbol_Names = Generate_Name_Section_For_Symbol_Table();
unsigned long long Symbol_Name_Size = 0;
for (auto i : Symbol_Names){
//add the null terminator
Symbol_Name_Size += i.size() + 1;
}
vector<OBJ::Section> Sections = Generate_Section_Table(Input, header.Pointer_To_Symbol_Table + sizeof(header.Pointer_To_Symbol_Table) + sizeof(OBJ::Symbol) * Symbols.size() + Symbol_Name_Size);
//Now inline all the data into one humongus buffer
vector<unsigned char> Buffer;
//Remove the optional headers from the buffer
unsigned char* Header_Start_Address = (unsigned char*)&header;
unsigned char* Header_End_Address = (unsigned char*)&header.Characteristics + sizeof(header.Characteristics);
Buffer.insert(Buffer.end(), (unsigned char*)&header, Header_End_Address);
Buffer.insert(Buffer.end(), (unsigned char*)Sections.data(), (unsigned char*)Sections.data() + sizeof(OBJ::Section) * Input.size());
Buffer.insert(Buffer.end(), (unsigned char*)Symbols.data(), (unsigned char*)Symbols.data() + sizeof(OBJ::Symbol) * Symbols.size());
int s = sizeof(OBJ::Symbol);
unsigned int String_Table_Size = 0;
vector<unsigned char> String_Table_Buffer;
for (auto i : Symbol_Names){
String_Table_Buffer.insert(String_Table_Buffer.end(), i.begin(), i.end());
String_Table_Buffer.push_back(0);
}
String_Table_Size = String_Table_Buffer.size() + sizeof(String_Table_Size);
Buffer.insert(Buffer.end(), (unsigned char*)&String_Table_Size, (unsigned char*)&String_Table_Size + sizeof(String_Table_Size));
Buffer.insert(Buffer.end(), String_Table_Buffer.begin(), String_Table_Buffer.end());
for (auto i : Input){
for (auto& j : i->Byte_Maps){
vector<unsigned char> Data = selector->Assemble(j);
Buffer.insert(Buffer.end(), Data.begin(), Data.end());
}
}
//transform the
return Buffer;
}
vector<OBJ::Section> OBJ::Generate_Section_Table(vector<Byte_Map_Section*> Input, unsigned long long Origo){
vector<OBJ::Section> Result;
for (auto i : Input){
Section tmp;
memcpy(&tmp.Name, i->Name.data(), i->Name.size());
tmp.Virtual_Size = i->Calculated_Size;
tmp.Virtual_Address = i->Calculated_Address;
tmp.Size_Of_Raw_Data = i->Calculated_Size;
tmp.Pointer_To_Raw_Data = i->Calculated_Address + Origo;
tmp.Pointer_To_Relocations = 0;
tmp.Pointer_To_Line_Numbers = 0;
tmp.Number_Of_Relocations = 0;
tmp.Number_Of_Line_Numbers = 0;
if (i->Is_Data_Section){
tmp.Characteristics = _IMAGE_SCN_CNT_INITIALIZED_DATA | _IMAGE_SCN_MEM_READ | _IMAGE_SCN_MEM_WRITE;
}
else{
tmp.Characteristics = _IMAGE_SCN_CNT_CODE | _IMAGE_SCN_MEM_EXECUTE | _IMAGE_SCN_MEM_READ;
}
Result.push_back(tmp);
}
return Result;
}
vector<OBJ::Symbol> OBJ::Generate_Symbol_Table(){
vector<OBJ::Symbol> Result;
//Skip the String_Table_Size identifier
long long Current_Symbol_Offset = sizeof(unsigned int);
for (auto i : assembler->Symbol_Table){
OBJ::Symbol Current;
//Generate the offset for the name redies in, transform it to text
Current.Full_Name = Current_Symbol_Offset << 32;
Current.Value = i.second;
Current.Section_Number = 0;
Current.Type = 0;
Current.Storage_Class = _IMAGE_SYM_CLASS_LABEL;
Current.Number_Of_Aux_Symbols = 0;
Result.push_back(Current);
Current_Symbol_Offset += i.first.size() + 1;
}
return Result;
}
vector<string> OBJ::Generate_Name_Section_For_Symbol_Table(){
vector<string> Result;
for (auto symbol : assembler->Symbol_Table){
Result.push_back(symbol.first);
}
return Result;
} | 31.933333 | 212 | 0.694734 |
ae38f7dc7a43cd38e41341504420dbacb7158e09 | 9,567 | cc | C++ | chrome/browser/autofill/form_structure_browsertest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/autofill/form_structure_browsertest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/autofill/form_structure_browsertest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 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 <vector>
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/autofill/form_structure.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
namespace {
FilePath GetInputFileDirectory() {
FilePath test_data_dir_;
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
test_data_dir_ = test_data_dir_.AppendASCII("autofill_heuristics")
.AppendASCII("input");
return test_data_dir_;
}
FilePath GetOutputFileDirectory() {
FilePath test_data_dir_;
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
test_data_dir_ = test_data_dir_.AppendASCII("autofill_heuristics")
.AppendASCII("output");
return test_data_dir_;
}
// Write |content| to |file|. Returns true on success.
bool WriteFile(const FilePath& file, const std::string& content) {
int write_size = file_util::WriteFile(file, content.c_str(),
content.length());
return write_size == static_cast<int>(content.length());
}
// Convert |html| to URL format, and return the converted string.
const std::string ConvertToURLFormat(const std::string& html) {
return std::string("data:text/html;charset=utf-8,") + html;
}
// Compare |output_file_source| with |form_string|. Returns true when they are
// identical.
bool CompareText(const std::string& output_file_source,
const std::string& form_string) {
std::string output_file = output_file_source;
std::string form = form_string;
ReplaceSubstringsAfterOffset(&output_file, 0, "\r\n", " ");
ReplaceSubstringsAfterOffset(&output_file, 0, "\r", " ");
ReplaceSubstringsAfterOffset(&output_file, 0, "\n", " ");
ReplaceSubstringsAfterOffset(&form, 0, "\n", " ");
return (output_file == form);
}
} // namespace
// Test class for verifying proper form structure as determined by AutoFill
// heuristics. A test inputs each form file(e.g. form_[language_code].html),
// loads its HTML content with a call to |NavigateToURL|, the |AutoFillManager|
// associated with the tab contents is queried for the form structures that
// were loaded and parsed. These form structures are serialized to string form.
// If this is the first time test is run, a gold test result file is generated
// in output directory, else the form structures are compared against the
// existing result file.
class FormStructureBrowserTest : public InProcessBrowserTest {
public:
FormStructureBrowserTest() {}
virtual ~FormStructureBrowserTest() {}
protected:
// Returns a vector of form structure objects associated with the given
// |autofill_manager|.
const std::vector<FormStructure*>& GetFormStructures(
const AutoFillManager& autofill_manager);
// Serializes the given form structures in |forms| to string form.
const std::string FormStructuresToString(
const std::vector<FormStructure*>& forms);
private:
// A helper utility for converting an |AutoFillFieldType| to string form.
const std::string AutoFillFieldTypeToString(AutoFillFieldType type);
DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest);
};
const std::vector<FormStructure*>& FormStructureBrowserTest::GetFormStructures(
const AutoFillManager& autofill_manager) {
return autofill_manager.form_structures_.get();
}
const std::string FormStructureBrowserTest::FormStructuresToString(
const std::vector<FormStructure*>& forms) {
std::string forms_string;
for (std::vector<FormStructure*>::const_iterator iter = forms.begin();
iter != forms.end();
++iter) {
for (std::vector<AutoFillField*>::const_iterator field_iter =
(*iter)->begin();
field_iter != (*iter)->end();
++field_iter) {
// The field list is NULL-terminated. Exit loop when at the end.
if (!*field_iter)
break;
forms_string += AutoFillFieldTypeToString((*field_iter)->type());
forms_string += "\n";
}
}
return forms_string;
}
const std::string FormStructureBrowserTest::AutoFillFieldTypeToString(
AutoFillFieldType type) {
switch (type) {
case NO_SERVER_DATA:
return "NO_SERVER_DATA";
case UNKNOWN_TYPE:
return "UNKNOWN_TYPE";
case EMPTY_TYPE:
return "EMPTY_TYPE";
case NAME_FIRST:
return "NAME_FIRST";
case NAME_MIDDLE:
return "NAME_MIDDLE";
case NAME_LAST:
return "NAME_LAST";
case NAME_MIDDLE_INITIAL:
return "NAME_MIDDLE_INITIAL";
case NAME_FULL:
return "NAME_FULL";
case NAME_SUFFIX:
return "NAME_SUFFIX";
case EMAIL_ADDRESS:
return "EMAIL_ADDRESS";
case PHONE_HOME_NUMBER:
return "PHONE_HOME_NUMBER";
case PHONE_HOME_CITY_CODE:
return "PHONE_HOME_CITY_CODE";
case PHONE_HOME_COUNTRY_CODE:
return "PHONE_HOME_COUNTRY_CODE";
case PHONE_HOME_CITY_AND_NUMBER:
return "PHONE_HOME_CITY_AND_NUMBER";
case PHONE_HOME_WHOLE_NUMBER:
return "PHONE_HOME_WHOLE_NUMBER";
case PHONE_FAX_NUMBER:
return "PHONE_FAX_NUMBER";
case PHONE_FAX_CITY_CODE:
return "PHONE_FAX_CITY_CODE";
case PHONE_FAX_COUNTRY_CODE:
return "PHONE_FAX_COUNTRY_CODE";
case PHONE_FAX_CITY_AND_NUMBER:
return "PHONE_FAX_CITY_AND_NUMBER";
case PHONE_FAX_WHOLE_NUMBER:
return "PHONE_FAX_WHOLE_NUMBER";
case ADDRESS_HOME_LINE1:
return "ADDRESS_HOME_LINE1";
case ADDRESS_HOME_LINE2:
return "ADDRESS_HOME_LINE2";
case ADDRESS_HOME_APT_NUM:
return "ADDRESS_HOME_APT_NUM";
case ADDRESS_HOME_CITY:
return "ADDRESS_HOME_CITY";
case ADDRESS_HOME_STATE:
return "ADDRESS_HOME_STATE";
case ADDRESS_HOME_ZIP:
return "ADDRESS_HOME_ZIP";
case ADDRESS_HOME_COUNTRY:
return "ADDRESS_HOME_COUNTRY";
case ADDRESS_BILLING_LINE1:
return "ADDRESS_BILLING_LINE1";
case ADDRESS_BILLING_LINE2:
return "ADDRESS_BILLING_LINE2";
case ADDRESS_BILLING_APT_NUM:
return "ADDRESS_BILLING_APT_NUM";
case ADDRESS_BILLING_CITY:
return "ADDRESS_BILLING_CITY";
case ADDRESS_BILLING_STATE:
return "ADDRESS_BILLING_STATE";
case ADDRESS_BILLING_ZIP:
return "ADDRESS_BILLING_ZIP";
case ADDRESS_BILLING_COUNTRY:
return "ADDRESS_BILLING_COUNTRY";
case CREDIT_CARD_NAME:
return "CREDIT_CARD_NAME";
case CREDIT_CARD_NUMBER:
return "CREDIT_CARD_NUMBER";
case CREDIT_CARD_EXP_MONTH:
return "CREDIT_CARD_EXP_MONTH";
case CREDIT_CARD_EXP_2_DIGIT_YEAR:
return "CREDIT_CARD_EXP_2_DIGIT_YEAR";
case CREDIT_CARD_EXP_4_DIGIT_YEAR:
return "CREDIT_CARD_EXP_4_DIGIT_YEAR";
case CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
return "CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR";
case CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
return "CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR";
case CREDIT_CARD_TYPE:
return "CREDIT_CARD_TYPE";
case CREDIT_CARD_VERIFICATION_CODE:
return "CREDIT_CARD_VERIFICATION_CODE";
case COMPANY_NAME:
return "COMPANY_NAME";
default:
NOTREACHED() << "Invalid AutoFillFieldType value.";
}
return std::string();
}
IN_PROC_BROWSER_TEST_F(FormStructureBrowserTest, HTMLFiles) {
FilePath input_file_path = GetInputFileDirectory();
file_util::FileEnumerator input_file_enumerator(input_file_path,
false, file_util::FileEnumerator::FILES, FILE_PATH_LITERAL("*.html"));
for (input_file_path = input_file_enumerator.Next();
!input_file_path.empty();
input_file_path = input_file_enumerator.Next()) {
std::string input_file_source;
ASSERT_TRUE(file_util::ReadFileToString(input_file_path,
&input_file_source));
input_file_source = ConvertToURLFormat(input_file_source);
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
browser(), GURL(input_file_source)));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(ui_test_utils::IsViewFocused(
browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
AutoFillManager* autofill_manager =
browser()->GetSelectedTabContents()->GetAutoFillManager();
ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager);
std::vector<FormStructure*> forms = GetFormStructures(*autofill_manager);
FilePath output_file_directory = GetOutputFileDirectory();
FilePath output_file_path = output_file_directory.Append(
input_file_path.BaseName().StripTrailingSeparators().ReplaceExtension(
FILE_PATH_LITERAL(".out")));
std::string output_file_source;
if (file_util::ReadFileToString(output_file_path, &output_file_source)) {
ASSERT_TRUE(CompareText(
output_file_source,
FormStructureBrowserTest::FormStructuresToString(forms)));
} else {
ASSERT_TRUE(WriteFile(
output_file_path,
FormStructureBrowserTest::FormStructuresToString(forms)));
}
}
}
| 35.831461 | 79 | 0.720184 |
ae3ab6bc4f88c37f0fa5090dce0cf138c035c01c | 308 | hpp | C++ | pythran/pythonic/include/cmath/log.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/cmath/log.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/cmath/log.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_INCLUDE_CMATH_LOG_HPP
#define PYTHONIC_INCLUDE_CMATH_LOG_HPP
#include "pythonic/include/utils/proxy.hpp"
#include <cmath>
namespace pythonic
{
namespace cmath
{
ALIAS_DECL(log, std::log);
double log(double x, double base);
PROXY_DECL(pythonic::cmath, log);
}
}
#endif
| 15.4 | 43 | 0.733766 |
ae3b50e593a3c8dd1c8b912c6cbdc593f6ebe381 | 883 | cc | C++ | remoting/signaling/signaling_tracker_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | remoting/signaling/signaling_tracker_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | remoting/signaling/signaling_tracker_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 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 "remoting/signaling/signaling_tracker_impl.h"
namespace remoting {
SignalingTrackerImpl::SignalingTrackerImpl() = default;
SignalingTrackerImpl::~SignalingTrackerImpl() = default;
void SignalingTrackerImpl::OnChannelActive() {
channel_last_active_time_ = base::TimeTicks::Now();
}
bool SignalingTrackerImpl::IsChannelActive() const {
return GetLastReportedChannelActiveDuration() <
SignalingTracker::kChannelInactiveTimeout;
}
base::TimeDelta SignalingTrackerImpl::GetLastReportedChannelActiveDuration()
const {
if (channel_last_active_time_.is_null()) {
return base::TimeDelta::Max();
}
return base::TimeTicks::Now() - channel_last_active_time_;
}
} // namespace remoting
| 28.483871 | 76 | 0.772367 |
ae3ca7324c166c72a93c09bd7aa727976348a3cf | 9,203 | hpp | C++ | stm32-jl/include/common/uart.hpp | serjzimmerman/mipt-rt-stm32-f0-labs | 561f363ec5c4dece92b2a14c36343aaa9d713785 | [
"MIT"
] | null | null | null | stm32-jl/include/common/uart.hpp | serjzimmerman/mipt-rt-stm32-f0-labs | 561f363ec5c4dece92b2a14c36343aaa9d713785 | [
"MIT"
] | null | null | null | stm32-jl/include/common/uart.hpp | serjzimmerman/mipt-rt-stm32-f0-labs | 561f363ec5c4dece92b2a14c36343aaa9d713785 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdarg>
#include <cstring>
#include "gpio.hpp"
#include "stm32f051/rcc.hpp"
namespace JL {
enum StopBits {
stopBit1 = 0b00,
stopBit05 = 0b01,
stopBit2 = 0b10,
stopBit15 = 0b11,
};
enum WordLength {
wordLength8 = 0b00,
wordLength9 = 0b01,
wordLength7 = 0b10,
};
template <uint32_t addr, typename tx, typename rx, PinAlternateFunction txaf, PinAlternateFunction rxaf, typename clock>
struct UartBase {
static constexpr uint32_t addr_ = addr;
using Tx = tx;
using Rx = rx;
struct CR1 : RegisterBase<addr_ + 0x00, RegisterReadWriteMode> {
using UE = RegisterField<UartBase::CR1, 0, 1, RegisterReadWriteMode>;
using UESM = RegisterField<UartBase::CR1, 1, 1, RegisterReadWriteMode>;
using RE = RegisterField<UartBase::CR1, 2, 1, RegisterReadWriteMode>;
using TE = RegisterField<UartBase::CR1, 3, 1, RegisterReadWriteMode>;
using IDLEIE = RegisterField<UartBase::CR1, 4, 1, RegisterReadWriteMode>;
using EXNEIE = RegisterField<UartBase::CR1, 5, 1, RegisterReadWriteMode>;
using TCIE = RegisterField<UartBase::CR1, 6, 1, RegisterReadWriteMode>;
using TXEIE = RegisterField<UartBase::CR1, 7, 1, RegisterReadWriteMode>;
using PEIE = RegisterField<UartBase::CR1, 8, 1, RegisterReadWriteMode>;
using PS = RegisterField<UartBase::CR1, 9, 1, RegisterReadWriteMode>;
using PCE = RegisterField<UartBase::CR1, 10, 1, RegisterReadWriteMode>;
using WAKE = RegisterField<UartBase::CR1, 11, 1, RegisterReadWriteMode>;
using M0 = RegisterField<UartBase::CR1, 12, 1, RegisterReadWriteMode>;
using MME = RegisterField<UartBase::CR1, 13, 1, RegisterReadWriteMode>;
using CMIE = RegisterField<UartBase::CR1, 14, 1, RegisterReadWriteMode>;
using OVER8 = RegisterField<UartBase::CR1, 15, 1, RegisterReadWriteMode>;
using DEDT = RegisterField<UartBase::CR1, 16, 4, RegisterReadWriteMode>;
using DEAT = RegisterField<UartBase::CR1, 21, 4, RegisterReadWriteMode>;
using RTOIE = RegisterField<UartBase::CR1, 26, 1, RegisterReadWriteMode>;
using EOBIE = RegisterField<UartBase::CR1, 27, 1, RegisterReadWriteMode>;
using M1 = RegisterField<UartBase::CR1, 28, 1, RegisterReadWriteMode>;
};
struct CR2 : RegisterBase<addr_ + 0x04, RegisterReadWriteMode> {
using ADDM7 = RegisterField<UartBase::CR2, 4, 1, RegisterReadWriteMode>;
using LBDL = RegisterField<UartBase::CR2, 5, 1, RegisterReadWriteMode>;
using LBDIE = RegisterField<UartBase::CR2, 6, 1, RegisterReadWriteMode>;
using LBCL = RegisterField<UartBase::CR2, 8, 1, RegisterReadWriteMode>;
using CPHA = RegisterField<UartBase::CR2, 9, 1, RegisterReadWriteMode>;
using CPOL = RegisterField<UartBase::CR2, 10, 1, RegisterReadWriteMode>;
using CLKEN = RegisterField<UartBase::CR2, 11, 1, RegisterReadWriteMode>;
using STOP = RegisterField<UartBase::CR2, 12, 2, RegisterReadWriteMode>;
using LINEN = RegisterField<UartBase::CR2, 14, 1, RegisterReadWriteMode>;
using SWAP = RegisterField<UartBase::CR2, 15, 1, RegisterReadWriteMode>;
using RXINV = RegisterField<UartBase::CR2, 16, 1, RegisterReadWriteMode>;
using TXINV = RegisterField<UartBase::CR2, 17, 1, RegisterReadWriteMode>;
using DATAINV = RegisterField<UartBase::CR2, 18, 1, RegisterReadWriteMode>;
using MSBFIRST = RegisterField<UartBase::CR2, 19, 1, RegisterReadWriteMode>;
using ABREN = RegisterField<UartBase::CR2, 20, 1, RegisterReadWriteMode>;
using ABRMOD = RegisterField<UartBase::CR2, 21, 2, RegisterReadWriteMode>;
using RTOEN = RegisterField<UartBase::CR2, 23, 1, RegisterReadWriteMode>;
using ADD = RegisterField<UartBase::CR2, 24, 8, RegisterReadWriteMode>;
};
struct CR3 : RegisterBase<addr_ + 0x08, RegisterReadWriteMode> {
using EIE = RegisterField<UartBase::CR3, 0, 1, RegisterReadWriteMode>;
using IREN = RegisterField<UartBase::CR3, 1, 1, RegisterReadWriteMode>;
using IRLP = RegisterField<UartBase::CR3, 2, 1, RegisterReadWriteMode>;
using HDSEL = RegisterField<UartBase::CR3, 3, 1, RegisterReadWriteMode>;
using NACK = RegisterField<UartBase::CR3, 4, 1, RegisterReadWriteMode>;
using SCEN = RegisterField<UartBase::CR3, 5, 1, RegisterReadWriteMode>;
using DMAR = RegisterField<UartBase::CR3, 6, 1, RegisterReadWriteMode>;
using DMAT = RegisterField<UartBase::CR3, 7, 2, RegisterReadWriteMode>;
using RTSE = RegisterField<UartBase::CR3, 8, 1, RegisterReadWriteMode>;
using CTSE = RegisterField<UartBase::CR3, 9, 1, RegisterReadWriteMode>;
using CTSIE = RegisterField<UartBase::CR3, 10, 1, RegisterReadWriteMode>;
using ONEBIT = RegisterField<UartBase::CR3, 11, 1, RegisterReadWriteMode>;
using OVRDIS = RegisterField<UartBase::CR3, 12, 1, RegisterReadWriteMode>;
using DDRE = RegisterField<UartBase::CR3, 13, 1, RegisterReadWriteMode>;
using DEM = RegisterField<UartBase::CR3, 14, 1, RegisterReadWriteMode>;
using DEP = RegisterField<UartBase::CR3, 15, 1, RegisterReadWriteMode>;
using SCARCNT = RegisterField<UartBase::CR3, 17, 3, RegisterReadWriteMode>;
using WUS = RegisterField<UartBase::CR3, 20, 2, RegisterReadWriteMode>;
using WUFIE = RegisterField<UartBase::CR3, 22, 1, RegisterReadWriteMode>;
};
struct BRR : RegisterBase<addr_ + 0x0c, RegisterReadWriteMode> {
using BRR16 = RegisterField<UartBase::BRR, 0, 16, RegisterReadWriteMode>;
using FRAC8 = RegisterField<UartBase::BRR, 0, 3, RegisterReadWriteMode>;
using BRR8 = RegisterField<UartBase::BRR, 4, 12, RegisterReadWriteMode>;
};
struct RDRREG : RegisterBase<addr_ + 0x24, RegisterReadMode> {
using RDR = RegisterField<UartBase::RDRREG, 0, 9, RegisterReadMode>;
};
struct TDRREG : RegisterBase<addr_ + 0x28, RegisterReadWriteMode> {
using TDR = RegisterField<UartBase::TDRREG, 0, 9, RegisterReadWriteMode>;
};
struct ISR : RegisterBase<addr_ + 0x1c, RegisterReadMode> {
using PE = RegisterField<UartBase::ISR, 0, 1, RegisterReadMode>;
using FE = RegisterField<UartBase::ISR, 1, 1, RegisterReadMode>;
using NF = RegisterField<UartBase::ISR, 2, 1, RegisterReadMode>;
using ORE = RegisterField<UartBase::ISR, 3, 1, RegisterReadMode>;
using IDLE = RegisterField<UartBase::ISR, 4, 1, RegisterReadMode>;
using RXNE = RegisterField<UartBase::ISR, 5, 1, RegisterReadMode>;
using TC = RegisterField<UartBase::ISR, 6, 1, RegisterReadMode>;
using TXE = RegisterField<UartBase::ISR, 7, 1, RegisterReadMode>;
using LBDF = RegisterField<UartBase::ISR, 8, 1, RegisterReadMode>;
using CTSIF = RegisterField<UartBase::ISR, 9, 1, RegisterReadMode>;
using CTS = RegisterField<UartBase::ISR, 10, 1, RegisterReadMode>;
using RTOF = RegisterField<UartBase::ISR, 11, 1, RegisterReadMode>;
using EOBF = RegisterField<UartBase::ISR, 12, 1, RegisterReadMode>;
using ABRE = RegisterField<UartBase::ISR, 14, 1, RegisterReadMode>;
using ABRF = RegisterField<UartBase::ISR, 15, 1, RegisterReadMode>;
using BUSY = RegisterField<UartBase::ISR, 16, 1, RegisterReadMode>;
using CMF = RegisterField<UartBase::ISR, 17, 1, RegisterReadMode>;
using SBKF = RegisterField<UartBase::ISR, 18, 1, RegisterReadMode>;
using RWU = RegisterField<UartBase::ISR, 19, 1, RegisterReadMode>;
using WUF = RegisterField<UartBase::ISR, 20, 1, RegisterReadMode>;
using TEACK = RegisterField<UartBase::ISR, 21, 1, RegisterReadMode>;
using REACK = RegisterField<UartBase::ISR, 22, 1, RegisterReadMode>;
};
/* Only for oversampling 16 */
static inline void SetFrequency(uint32_t baudrate) {
BRR::BRR16::Set(APBClock / baudrate);
}
static inline void Config(uint32_t baudrate, StopBits stop, WordLength length, PinType type) {
/* Enable clock for USART and tx and rx PORT */
ClockPack<typename rx::PinPort::Clock, typename tx::PinPort::Clock>::Enable();
ClockPack<clock>::Enable();
PinPack<rx, tx>::Config(modeAlternate, speedMid);
rx::SetAlternateFunction(rxaf);
tx::SetAlternateFunction(txaf);
CR1::Set(0);
CR2::Set(0);
CR3::Set(0);
PinPack<rx, tx>::SetOutputType(type);
/* If type and open-drain, then USART is configured in half-duplex mode */
if (type == typeOpdr) {
CR3::HDSEL::Set(1);
}
SetFrequency(baudrate);
CR1::UE::Set(1);
/* Configure word length and number of stop bits */
RegisterFieldPack<typename CR1::M0, typename CR1::M1>::Set(CR1::M0::GetIndividualValue(length & 1) |
CR1::M1::GetIndividualValue((length >> 1) & 1));
RegisterFieldPack<typename CR2::STOP>::Set(CR2::STOP::GetIndividualValue(stop));
/* Enable USART, transmitter and receiver */
}
static void PutChar(char tosend) {
TDRREG::TDR::Set(tosend);
/* Todo: implement timeout */
while (ISR::TC::Get() != 1)
;
}
static char GetChar() {
while (ISR::RXNE::Get() != 1)
;
return RDRREG::RDR::Get();
}
static void Print(const char *s) {
while (*s) {
PutChar(*s++);
}
}
};
} // namespace JL | 48.183246 | 120 | 0.693144 |
ae3cec7f20f8fdb8d588ff4460e5e882697b33d1 | 9,676 | cpp | C++ | src/modules/hip/kernel/median_filter.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 26 | 2019-09-04T17:48:41.000Z | 2022-02-23T17:04:24.000Z | src/modules/hip/kernel/median_filter.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 57 | 2019-09-06T21:37:34.000Z | 2022-03-09T02:13:46.000Z | src/modules/hip/kernel/median_filter.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 24 | 2019-09-04T23:12:07.000Z | 2022-03-30T02:06:22.000Z | #include <hip/hip_runtime.h>
#include "rpp_hip_host_decls.hpp"
#define saturate_8u(value) ((value) > 255 ? 255 : ((value) < 0 ? 0 : (value)))
#define SIZE 7*7
extern "C" __global__ void median_filter_pkd(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned int kernelSize)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int c[SIZE];
int counter = 0;
int pixIdx = id_y * channel * width + id_x * channel + id_z;
int bound = (kernelSize - 1) / 2;
for(int i = -bound ; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1)
{
unsigned int index = pixIdx + (j * channel) + (i * width * channel);
c[counter] = input[index];
}
else
{
c[counter] = 0;
counter++;
}
}
}
int pos;
int max = 0;
for (int i = 0; i < counter; i++)
{
for (int j = i; j < counter; j++)
{
if (max < c[j])
{
max = c[j];
pos = j;
}
}
max = 0;
int temp = c[pos];
c[pos] = c[i];
c[i] = temp;
}
counter = kernelSize * bound + bound + 1;
output[pixIdx] = c[counter];
}
extern "C" __global__ void median_filter_pln(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned int kernelSize)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int c[SIZE];
int counter = 0;
int pixIdx = id_y * width + id_x + id_z * width * height;
int bound = (kernelSize - 1) / 2;
unsigned char pixel = input[pixIdx];
for(int i = -bound; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1)
{
unsigned int index = pixIdx + j + (i * width);
c[counter] = input[index];
}
else
{
c[counter] = 0;
counter++;
}
}
}
int pos;
int max = 0;
for (int i = 0; i < counter; i++)
{
for (int j = i; j < counter; j++)
{
if (max < c[j])
{
max = c[j];
pos = j;
}
}
max = 0;
int temp = c[pos];
c[pos] = c[i];
c[i] = temp;
}
counter = kernelSize * bound + bound + 1;
output[pixIdx] = c[counter];
}
extern "C" __global__ void median_filter_batch(unsigned char *input,
unsigned char *output,
unsigned int *kernelSize,
unsigned int *xroi_begin,
unsigned int *xroi_end,
unsigned int *yroi_begin,
unsigned int *yroi_end,
unsigned int *height,
unsigned int *width,
unsigned int *max_width,
unsigned long long *batch_index,
const unsigned int channel,
unsigned int *inc, // use width * height for pln and 1 for pkd
const int plnpkdindex) // use 1 pln 3 for pkd
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
unsigned char valuer, valuer1, valueg, valueg1, valueb, valueb1;
int kernelSizeTemp = kernelSize[id_z];
int indextmp = 0;
long pixIdx = 0;
int temp;
// printf("%d", id_x);
int value = 0;
int value1 = 0;
int counter = 0;
int r[SIZE], g[SIZE], b[SIZE], maxR = 0, maxG = 0, maxB = 0, posR, posG, posB;
int bound = (kernelSizeTemp - 1) / 2;
pixIdx = batch_index[id_z] + (id_x + id_y * max_width[id_z]) * plnpkdindex;
if((id_y >= yroi_begin[id_z]) && (id_y <= yroi_end[id_z]) && (id_x >= xroi_begin[id_z]) && (id_x <= xroi_end[id_z]))
{
for(int i = -bound; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width[id_z] - 1 && id_y + i >= 0 && id_y + i <= height[id_z] - 1)
{
unsigned int index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex;
r[counter] = input[index];
if(channel == 3)
{
index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z];
g[counter] = input[index];
index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z] * 2;
b[counter] = input[index];
}
}
else
{
r[counter] = 0;
if(channel == 3)
{
g[counter] = 0;
b[counter] = 0;
}
}
counter++;
}
}
for (int i = 0; i < counter; i++)
{
posB = i;
posG = i;
posR = i;
for (int j = i; j < counter; j++)
{
if (maxR < r[j])
{
maxR = r[j];
posR = j;
}
if (maxG < g[j])
{
maxG = g[j];
posG = j;
}
if (maxB < b[j])
{
maxB = b[j];
posB = j;
}
}
maxR = 0;
maxG = 0;
maxB = 0;
int temp;
temp = r[posR];
r[posR] = r[i];
r[i] = temp;
temp = g[posG];
g[posG] = g[i];
g[i] = temp;
temp = b[posB];
b[posB] = b[i];
b[i] = temp;
}
counter = kernelSizeTemp * bound + bound + 1;
output[pixIdx] = r[counter];
if(channel == 3)
{
output[pixIdx + inc[id_z]] = g[counter];
output[pixIdx + inc[id_z] * 2] = b[counter];
}
}
else if((id_x < width[id_z]) && (id_y < height[id_z]))
{
for(indextmp = 0; indextmp < channel; indextmp++)
{
output[pixIdx] = input[pixIdx];
pixIdx += inc[id_z];
}
}
}
RppStatus hip_exec_median_filter_batch(Rpp8u *srcPtr, Rpp8u *dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, Rpp32u channel, Rpp32s plnpkdind, Rpp32u max_height, Rpp32u max_width)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = (max_width + 31) & ~31;
int globalThreads_y = (max_height + 31) & ~31;
int globalThreads_z = handle.GetBatchSize();
hipLaunchKernelGGL(median_filter_batch,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
dstPtr,
handle.GetInitHandle()->mem.mgpu.uintArr[0].uintmem,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
plnpkdind);
return RPP_SUCCESS;
} | 35.185455 | 185 | 0.423625 |
ae3d5347e2294cddba00ceea4f9349c14fcfe64f | 2,859 | cc | C++ | src/swganh/object/group/group.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | 1 | 2015-03-25T16:02:17.000Z | 2015-03-25T16:02:17.000Z | src/swganh/object/group/group.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | null | null | null | src/swganh/object/group/group.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | null | null | null | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "swganh/object/group/group.h"
#include "swganh/object/tangible/tangible.h"
using namespace std;
using namespace swganh::messages;
using namespace swganh::object;
using namespace swganh::object::group;
using namespace swganh::object::tangible;
Group::Group()
: member_list_(5)
, difficulty_(0)
, loot_master_(0)
, loot_mode_(FREE_LOOT)
{
}
Group::Group(uint32_t max_member_size)
: member_list_(max_member_size)
, difficulty_(0)
, loot_master_(0)
, loot_mode_(FREE_LOOT)
{
}
Group::~Group()
{
}
void Group::AddGroupMember(uint64_t member, std::string name)
{
boost::lock_guard<boost::mutex> lock(group_mutex_);
member_list_.Add(Member(member, name));
GetEventDispatcher()->Dispatch(make_shared<GroupEvent>
("Group::Member",static_pointer_cast<Group>(shared_from_this())));
}
void Group::RemoveGroupMember(uint64_t member)
{
boost::lock_guard<boost::mutex> lock(group_mutex_);
auto iter = std::find_if(begin(member_list_), end(member_list_), [=](const Member& x)->bool {
return member == x.object_id;
});
if(iter == end(member_list_))
{
return;
}
member_list_.Remove(iter);
GetEventDispatcher()->Dispatch(make_shared<GroupEvent>
("Group::Member",static_pointer_cast<Group>(shared_from_this())));
}
swganh::messages::containers::NetworkSortedVector<Member> Group::GetGroupMembers()
{
boost::lock_guard<boost::mutex> lock(group_mutex_);
return member_list_;
}
void Group::SetLootMode(LootMode loot_mode)
{
loot_mode_ = loot_mode;
GetEventDispatcher()->Dispatch(make_shared<GroupEvent>
("Group::LootMode",static_pointer_cast<Group>(shared_from_this())));
}
LootMode Group::GetLootMode(void)
{
uint32_t loot_mode = loot_mode_;
return (LootMode)loot_mode;
}
void Group::SetDifficulty(uint16_t difficulty)
{
difficulty_ = difficulty;
GetEventDispatcher()->Dispatch(make_shared<GroupEvent>
("Group::Difficulty",static_pointer_cast<Group>(shared_from_this())));
}
uint16_t Group::GetDifficulty(void)
{
return difficulty_;
}
void Group::SetLootMaster(uint64_t loot_master)
{
loot_master_ = loot_master;
GetEventDispatcher()->Dispatch(make_shared<GroupEvent>
("Group::LootMaster",static_pointer_cast<Group>(shared_from_this())));
}
uint64_t Group::GetLootMaster(void)
{
return loot_master_;
}
uint16_t Group::GetCapacity(void)
{
boost::lock_guard<boost::mutex> lock(group_mutex_);
return member_list_.Capacity();
}
uint16_t Group::GetSize(void)
{
boost::lock_guard<boost::mutex> lock(group_mutex_);
return member_list_.Size();
}
void Group::GetBaseline3()
{
}
void Group::GetBaseline6()
{
} | 22.872 | 97 | 0.70794 |
ae3dc01e1073dba6d10405d3e51257864cf466be | 3,743 | hpp | C++ | src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2013 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of Caelus.
Caelus 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.
Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>.
Class
CML::bladeModel
Description
Blade model class
SourceFiles
bladeModel.cpp
\*---------------------------------------------------------------------------*/
#ifndef bladeModel_HPP
#define bladeModel_HPP
#include "List.hpp"
#include "dictionary.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class bladeModel Declaration
\*---------------------------------------------------------------------------*/
class bladeModel
{
protected:
// Protected data
//- Corresponding profile name per section
List<word> profileName_;
//- Corresponding profile ID per section
List<label> profileID_;
//- Radius [m]
List<scalar> radius_;
//- Twist [deg] on input, converted to [rad]
List<scalar> twist_;
//- Chord [m]
List<scalar> chord_;
//- File name (optional)
fileName fName_;
// Protected Member Functions
//- Return ture if file name is set
bool readFromFile() const;
//- Return the interpolation indices and gradient
void interpolateWeights
(
const scalar& xIn,
const List<scalar>& values,
label& i1,
label& i2,
scalar& ddx
) const;
public:
//- Constructor
bladeModel(const dictionary& dict);
//- Destructor
virtual ~bladeModel();
// Member functions
// Access
//- Return const access to the profile name list
const List<word>& profileName() const;
//- Return const access to the profile ID list
const List<label>& profileID() const;
//- Return const access to the radius list
const List<scalar>& radius() const;
//- Return const access to the twist list
const List<scalar>& twist() const;
//- Return const access to the chord list
const List<scalar>& chord() const;
// Edit
//- Return non-const access to the profile ID list
List<label>& profileID();
// Evaluation
//- Return the twist and chord for a given radius
virtual void interpolate
(
const scalar radius,
scalar& twist,
scalar& chord,
label& i1,
label& i2,
scalar& invDr
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 25.290541 | 79 | 0.47689 |
ae41976ffdc4f430861d25c818f7ef3d17a23a23 | 2,092 | cpp | C++ | Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | /*
https://practice.geeksforgeeks.org/problems/stickler-theif-1587115621/1
Stickler Thief
Easy Accuracy: 50.32% Submissions: 43113 Points: 2
Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i] amount of money present in it.
Example 1:
Input:
n = 6
a[] = {5,5,10,100,10,5}
Output: 110
Explanation: 5+100+5=110
Example 2:
Input:
n = 3
a[] = {1,2,3}
Output: 4
Explanation: 1+3=4
Your Task:
Complete the function FindMaxSum() which takes an array arr[] and n as input which returns the maximum money he can get following the rules
Expected Time Complexity: O(N).
Expected Space Complexity: O(N).
Constraints:
1 ≤ n ≤ 104
1 ≤ a[i] ≤ 104
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
// } Driver Code Ends
class Solution
{
public:
//Function to find the maximum money the thief can get.
int FindMaxSum(int arr[], int n)
{
// Your code here
{
int dp[n];
dp[0] = arr[0];
dp[1] = max(arr[1], arr[0]);
for (int i = 2; i < n; i++)
dp[i] = max(dp[i - 1], arr[i] + dp[i - 2]);
return dp[n - 1];
}
}
};
// { Driver Code Starts.
int main()
{
//taking total testcases
int t;
cin >> t;
while (t--)
{
//taking number of houses
int n;
cin >> n;
int a[n];
//inserting money of each house in the array
for (int i = 0; i < n; ++i)
cin >> a[i];
Solution ob;
//calling function FindMaxSum()
cout << ob.FindMaxSum(a, n) << endl;
}
return 0;
}
// } Driver Code Ends | 25.82716 | 541 | 0.616635 |
ae41cb5076286b79fd7b17737b07b0d2febfd7f3 | 1,687 | hpp | C++ | thirdparty/libgenerator/inc/generator/utils.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | thirdparty/libgenerator/inc/generator/utils.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | thirdparty/libgenerator/inc/generator/utils.hpp | ppiecuch/godot | ff2098b324b814a0d1bd9d5722aa871fc5214fab | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null |
// Copyright 2015 Markus Ilmola
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
#ifndef GENERATOR_UTILS_HPP
#define GENERATOR_UTILS_HPP
namespace generator {
/// Will have a type named "Type" that has same type as value returned by method
/// generate() of type Generator.
template <typename Generator>
class GeneratedType {
public:
using Type = decltype(static_cast<const Generator *>(nullptr)->generate());
};
/// Will have a type named "Type" that has same type as value returned by method
/// edges() for type Primitive.
template <typename Primitive>
class EdgeGeneratorType {
public:
using Type = decltype(static_cast<const Primitive *>(nullptr)->edges());
};
/// Will have a type named "Type" that has same type as value returned by method
/// triangles() for type Primitive.
template <typename Primitive>
class TriangleGeneratorType {
public:
using Type = decltype(static_cast<const Primitive *>(nullptr)->triangles());
};
/// Will have a type named "Type" that has same type as value returned by method
/// vertices() for type Primitive.
template <typename Primitive>
class VertexGeneratorType {
public:
using Type = decltype(static_cast<const Primitive *>(nullptr)->vertices());
};
/// Counts the number of steps left in the generator.
template <typename Generator>
int count(const Generator &generator) noexcept {
Generator temp{ generator };
int c = 0;
while (!temp.done()) {
++c;
temp.next();
}
return c;
}
} // namespace generator
#endif
| 28.116667 | 80 | 0.739775 |
ae441a8c950165c356976067cadacc904641a35c | 1,526 | cpp | C++ | lib/CMakeTargetMachine.cpp | akemimadoka/LLVMCMakeBackend | 64513885876ad81d932eeb06464aa7caa5f5843b | [
"MIT"
] | 40 | 2020-04-04T09:16:28.000Z | 2021-12-10T14:03:40.000Z | lib/CMakeTargetMachine.cpp | akemimadoka/LLVMCMakeBackend | 64513885876ad81d932eeb06464aa7caa5f5843b | [
"MIT"
] | 1 | 2020-04-07T10:44:48.000Z | 2020-04-16T17:02:48.000Z | lib/CMakeTargetMachine.cpp | akemimadoka/LLVMCMakeBackend | 64513885876ad81d932eeb06464aa7caa5f5843b | [
"MIT"
] | null | null | null | #include "CMakeTargetMachine.h"
#include "CMakeBackend.h"
#include "CheckNeedGotoPass.h"
#include <llvm/CodeGen/TargetPassConfig.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Transforms/Utils.h>
using namespace llvm;
Target CMakeBackendTarget{};
extern "C" void LLVMInitializeCMakeBackendTarget()
{
RegisterTargetMachine<LLVMCMakeBackend::CMakeTargetMachine> X(CMakeBackendTarget);
}
extern "C" void LLVMInitializeCMakeBackendTargetInfo()
{
RegisterTarget<> X(CMakeBackendTarget, "cmake", "CMake backend", "CMake");
}
extern "C" void LLVMInitializeCMakeBackendTargetMC()
{
}
bool LLVMCMakeBackend::CMakeTargetSubtargetInfo::enableAtomicExpand() const
{
return true;
}
const llvm::TargetLowering* LLVMCMakeBackend::CMakeTargetSubtargetInfo::getTargetLowering() const
{
return &Lowering;
}
bool LLVMCMakeBackend::CMakeTargetMachine::addPassesToEmitFile(
llvm::PassManagerBase& PM, llvm::raw_pwrite_stream& Out, llvm::raw_pwrite_stream* DwoOut,
llvm::CodeGenFileType FileType, bool DisableVerify, llvm::MachineModuleInfoWrapperPass* MMIWP)
{
if (FileType != CodeGenFileType::CGFT_AssemblyFile)
{
return true;
}
const auto reg = PassRegistry::getPassRegistry();
const auto passConfig = createPassConfig(PM);
PM.add(passConfig);
PM.add(createLowerSwitchPass());
PM.add(new CheckNeedGotoPass());
PM.add(new CMakeBackend(Out));
return false;
}
const llvm::TargetSubtargetInfo*
LLVMCMakeBackend::CMakeTargetMachine::getSubtargetImpl(const Function&) const
{
return &SubtargetInfo;
}
| 24.612903 | 98 | 0.787025 |
ae4e5b3ae84f0a27adcc7442fc4f8cd1a6f576eb | 3,660 | cpp | C++ | Haru/hpdf/hpdf_image.cpp | miyako/4d-plugin-haru | 749599d7ec9f21a2071ebef3859eb3fce8c59754 | [
"MIT"
] | null | null | null | Haru/hpdf/hpdf_image.cpp | miyako/4d-plugin-haru | 749599d7ec9f21a2071ebef3859eb3fce8c59754 | [
"MIT"
] | 1 | 2020-02-13T03:34:38.000Z | 2020-06-01T21:08:11.000Z | Haru/hpdf/hpdf_image.cpp | miyako/4d-plugin-haru | 749599d7ec9f21a2071ebef3859eb3fce8c59754 | [
"MIT"
] | 2 | 2016-06-07T08:28:17.000Z | 2016-08-03T10:53:05.000Z | #include "hpdf_image.h"
// ------------------------------------- Image ------------------------------------
void PDF_Image_AddSMask(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT Param2;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Image smask = (HPDF_Image)_fromHex(Param2);
returnValue.setIntValue(HPDF_Image_AddSMask(image, smask));
returnValue.setReturn(pResult);
}
void PDF_Image_GetSize(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_REAL Param2;
C_REAL Param3;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Point size;
returnValue.setIntValue(HPDF_Image_GetSize2(image, &size));
Param2.setDoubleValue(size.x);
Param3.setDoubleValue(size.y);
Param2.toParamAtIndex(pParams, 2);
Param3.toParamAtIndex(pParams, 3);
returnValue.setReturn(pResult);
}
void PDF_Image_GetWidth(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetWidth(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetHeight(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetHeight(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetBitsPerComponent(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetBitsPerComponent(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetColorSpace(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
CUTF8String u = CUTF8String((const uint8_t *)HPDF_Image_GetColorSpace(image));
returnValue.setUTF8String(&u);
returnValue.setReturn(pResult);
}
void PDF_Image_SetColorMask(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT Param2;
C_LONGINT Param3;
C_LONGINT Param4;
C_LONGINT Param5;
C_LONGINT Param6;
C_LONGINT Param7;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
Param3.fromParamAtIndex(pParams, 3);
Param4.fromParamAtIndex(pParams, 4);
Param5.fromParamAtIndex(pParams, 5);
Param6.fromParamAtIndex(pParams, 6);
Param7.fromParamAtIndex(pParams, 7);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_UINT rmin = (HPDF_UINT)Param2.getIntValue();
HPDF_UINT rmax = (HPDF_UINT)Param3.getIntValue();
HPDF_UINT gmin = (HPDF_UINT)Param4.getIntValue();
HPDF_UINT gmax = (HPDF_UINT)Param5.getIntValue();
HPDF_UINT bmin = (HPDF_UINT)Param6.getIntValue();
HPDF_UINT bmax = (HPDF_UINT)Param7.getIntValue();
returnValue.setIntValue(HPDF_Image_SetColorMask(image, rmin, rmax, gmin, gmax, bmin, bmax));
returnValue.setReturn(pResult);
}
void PDF_Image_SetMaskImage(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT Param2;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Image mask_image = (HPDF_Image)_fromHex(Param2);
returnValue.setIntValue(HPDF_Image_SetMaskImage(image, mask_image));
returnValue.setReturn(pResult);
}
| 24.4 | 93 | 0.764208 |
ae4f4b4e979772284c486e8ee37fad05527ab9d8 | 3,071 | cxx | C++ | osf-to-esf/dborl/dborl_image_description.cxx | wenhanshi/lemsvxl-shock-computation | 1208e5f6a0c9fddbdffcc20f2c1d914e07015b45 | [
"MIT"
] | 1 | 2022-01-01T20:43:47.000Z | 2022-01-01T20:43:47.000Z | osf-to-esf/dborl/dborl_image_description.cxx | wenhanshi/lemsvxl-shock-computation | 1208e5f6a0c9fddbdffcc20f2c1d914e07015b45 | [
"MIT"
] | null | null | null | osf-to-esf/dborl/dborl_image_description.cxx | wenhanshi/lemsvxl-shock-computation | 1208e5f6a0c9fddbdffcc20f2c1d914e07015b45 | [
"MIT"
] | null | null | null | //:
// \file
// \brief
// \author Ozge Can Ozcanli (ozge@lems.brown.edu)
// \date 010/03/07
#include "dborl_image_description.h"
#include "dborl_image_data_description_base.h"
#include "dborl_image_bbox_description.h"
#include "dborl_image_polygon_description.h"
#include "dborl_image_mask_description.h"
#include <vcl_iostream.h>
dborl_image_description::dborl_image_description(dborl_image_bbox_description_sptr box_data)
{
vcl_map<vcl_string, vcl_vector<vsol_box_2d_sptr> >& map = box_data->get_category_map();
//: add each category and counts one by one
for (vcl_map<vcl_string, vcl_vector<vsol_box_2d_sptr> >::iterator i = map.begin(); i != map.end(); i++)
category_list_[i->first] = (i->second).size();
category_data_ = box_data->cast_to_image_data_description_base();
}
dborl_image_description::dborl_image_description(dborl_image_polygon_description_sptr poly_data)
{
vcl_map<vcl_string, vcl_vector<vsol_polygon_2d_sptr> >& map = poly_data->get_category_map();
//: add each category and counts one by one
for (vcl_map<vcl_string, vcl_vector<vsol_polygon_2d_sptr> >::iterator i = map.begin(); i != map.end(); i++)
category_list_[i->first] = (i->second).size();
category_data_ = poly_data->cast_to_image_data_description_base();
}
//: assuming the names in the vector are names of categories for corresponding indices
// (the vector may contain way more cats than that exists in the mask)
dborl_image_description::dborl_image_description(dborl_image_mask_description_sptr mask_data, vcl_vector<vcl_string>& cats)
{
category_data_ = mask_data->cast_to_image_data_description_base();
for (unsigned i = 0; i < cats.size(); i++) {
if (category_exists(cats[i]))
add_to_category_cnt(cats[i], 1); // increments the count by 1
else
add_category(cats[i]); // sets the count to 1
}
}
unsigned dborl_image_description::version()
{
return 0;
}
void dborl_image_description::b_read()
{
vcl_cout << "IMPLEMENT: dborl_image_description::b_read()\n";
}
void dborl_image_description::b_write()
{
vcl_cout << "IMPLEMENT: dborl_image_description::b_write()\n";
}
unsigned dborl_image_description::get_object_type()
{
return dborl_object_type::image;
}
void dborl_image_description::write_xml(vcl_ostream& os)
{
os << "<type name = \"image\">\n";
os << "\t<description>\n";
if (category_data_->cast_to_image_polygon_description()) {
category_data_->cast_to_image_polygon_description()->write_xml(os);
} else if (category_data_->cast_to_image_bbox_description()) {
category_data_->cast_to_image_bbox_description()->write_xml(os);
} else if (category_data_->cast_to_image_mask_description()) {
for (vcl_map<vcl_string, int>::iterator iter = category_list_.begin(); iter != category_list_.end(); iter++) {
for (int i = 0; i < iter->second; i++) {
os << "\t\t<instance>\n";
os << "\t\t\t<category>" << iter->first << "</category>\n";
os << "\t\t</instance>\n";
}
}
}
os << "\t</description>\n";
os << "</type>\n";
}
| 34.122222 | 123 | 0.713123 |
ae52889679352218af67833e2b1ae882b3353939 | 2,650 | cpp | C++ | src/sol_scip_kbest.cpp | aurtg/david | 26922b8b9f35ee749f44e56a599aa5e7136024e2 | [
"MIT"
] | null | null | null | src/sol_scip_kbest.cpp | aurtg/david | 26922b8b9f35ee749f44e56a599aa5e7136024e2 | [
"MIT"
] | null | null | null | src/sol_scip_kbest.cpp | aurtg/david | 26922b8b9f35ee749f44e56a599aa5e7136024e2 | [
"MIT"
] | null | null | null | #include <mutex>
#include <algorithm>
#include "./kernel.h"
#include "./lhs.h"
#include "./cnv.h"
#include "./sol.h"
#include "./json.h"
namespace dav
{
namespace sol
{
#ifdef USE_SCIP
string_t code2str(SCIP_RETCODE c);
#endif
scip_k_best_t::scip_k_best_t(const kernel_t *m, bool cpi)
: scip_t(m, cpi),
m_max_num(param()->geti("max-solution-num", 5)),
m_max_delta(param()->getf("max-eval-delta", 5.0)),
m_margin(param()->geti("eval-margin", 3))
{}
void scip_k_best_t::validate() const
{
scip_t::validate();
if (not m_max_num.valid())
throw exception_t("The value \"max-solution-num\" must not be a minus value.");
if (m_margin < 0)
throw exception_t("The valud \"margin\" must not be a minus value.");
}
void scip_k_best_t::solve(std::shared_ptr<ilp::problem_t> prob)
{
#ifdef USE_SCIP
model_t m(this, prob);
auto exe = [](SCIP_RETCODE c)
{
if (c <= 0)
throw exception_t(format(
"SCIP error-code: \"%s\"", code2str(c).c_str()));
};
exe(m.initialize());
while (m_max_num.do_accept(out.size() + 1))
{
console_t::auto_indent_t ai;
if (console()->is(verboseness_e::ROUGH))
{
console()->print_fmt("Optimization #%d", out.size() + 1);
console()->add_indent();
}
if (out.empty())
exe(m.solve(&out));
else
{
ilp::constraint_t c = prohibit(out.back(), m_margin);
exe(m.free_transform());
exe(m.add_constraint(c));
exe(m.solve(&out));
if (out.empty()) break;
else if (out.back()->type() == ilp::SOL_NOT_AVAILABLE)
{
out.pop_back();
break;
}
else if (m_max_delta.valid())
{
// IF DELTA IS BIGGER THAN THRESHOLD, THIS SOLUTION IS NOT ACCEPTABLE.
double delta = out.back()->objective_value() - out.front()->objective_value();
if (!m_max_delta.do_accept(std::abs(delta)))
{
out.pop_back();
break;
}
}
}
if (has_timed_out()) break;
}
#endif
}
void scip_k_best_t::write_json(json::object_writer_t &wr) const
{
scip_t::write_json(wr);
wr.write_field<int>("max-num", m_max_num.get());
wr.write_field<double>("max-delta", m_max_delta.get());
wr.write_field<int>("margin", m_margin);
}
ilp_solver_t* scip_k_best_t::generator_t::operator()(const kernel_t *m) const
{
return new sol::scip_k_best_t(m, do_use_cpi);
}
}
}
| 22.457627 | 94 | 0.551698 |
ae5289e95ee89e9358178fefeafc955aca22fb10 | 11,663 | cpp | C++ | Computer Graphics/src/scene_texture.cpp | sergio5405/Computer-Graphics-Project | 829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc | [
"MIT"
] | null | null | null | Computer Graphics/src/scene_texture.cpp | sergio5405/Computer-Graphics-Project | 829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc | [
"MIT"
] | null | null | null | Computer Graphics/src/scene_texture.cpp | sergio5405/Computer-Graphics-Project | 829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc | [
"MIT"
] | null | null | null | #include "scene_texture.h"
#include "ifile.h"
#include "time.h"
#include "cgmath.h"
#include "vec2.h"
#include "vec3.h"
#include "mat3.h"
#include "mat4.h"
#include <string>
#include <vector>
scene_texture::~scene_texture() {
glDeleteProgram(shader_program);
}
void scene_texture::init() {
std::vector<cgmath::vec3> positions;
//Front
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
//Top
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
//Right
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
//Left
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
//Down
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
//Back
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
std::vector<unsigned int> indices{ 0, 1, 2, //front
1, 3, 2,
4, 5, 6, //top
5, 7, 6,
8, 9, 10, //right
9, 11, 10,
12, 13, 14, //left
13, 15, 14,
16, 17, 18, //down
17, 19, 18,
20, 21, 22, //back
21, 23, 22
};
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &positionsVBO);
glBindBuffer(GL_ARRAY_BUFFER, positionsVBO);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * positions.size(),
positions.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &positionsIndicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, positionsIndicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(unsigned int) * indices.size(),
indices.data(),
GL_STATIC_DRAW);
std::vector<cgmath::vec3> colors;
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//red
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//green
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//blue
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 0.0f, 1.0f));//pink
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 1.0f, 0.0f));//yellow
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 1.0f, 1.0f));//cyan
//std::vector<unsigned int> indicesColors{ 0, 0, 0, 0, 0, 0, //front
// 1, 1, 1, 1, 1, 1, //top
// 2, 2, 2, 2, 2, 2, //right
// 3, 3, 3, 3, 3, 3, //left
// 4, 4, 4, 4, 4, 4, //down
// 5, 5, 5, 5, 5, 5, //back
//};
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * colors.size(),
colors.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/*glGenBuffers(1, &indicesColorBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesColorBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(unsigned int) * indicesColors.size(),
indicesColors.data(),
GL_STATIC_DRAW);
glBindVertexArray(0);*/
std::vector<cgmath::vec3> normals;
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//front
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//top
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//right
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(-1.0f, 0.0f, 0.0f));//left
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, -1.0f, 0.0f));//down
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 0.0f, -1.0f));//back
glGenBuffers(1, &normalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * normals.size(),
normals.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
std::vector<cgmath::vec2> texCoords;
for (int i = 0; i < 6; i++) {
texCoords.push_back(cgmath::vec2(1.0f, 0.0f));
texCoords.push_back(cgmath::vec2(1.0f, 1.0f));
texCoords.push_back(cgmath::vec2(0.0f, 0.0f));
texCoords.push_back(cgmath::vec2(0.0f, 1.0f));
}
glGenBuffers(1, &texCoordsBuffer);
glBindBuffer(GL_ARRAY_BUFFER, texCoordsBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec2) * texCoords.size(),
texCoords.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
ilGenImages(1, &pigImageId);
ilBindImage(pigImageId);
ilLoadImage("images/pig.png");
glGenTextures(2, textureId);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_WIDTH),
ilGetInteger(IL_IMAGE_HEIGHT),
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_TYPE),
ilGetData());
glGenerateMipmap(GL_TEXTURE_2D);
ilDeleteImages(1, &pigImageId);
ILenum Error;
while ((Error = ilGetError()) != IL_NO_ERROR) {
printf("%d: /n", Error);
}
ilGenImages(1, &crateImageId);
ilBindImage(crateImageId);
ilLoadImage("images/crate.png");
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureId[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_WIDTH),
ilGetInteger(IL_IMAGE_HEIGHT),
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_TYPE),
ilGetData());
glGenerateMipmap(GL_TEXTURE_2D);
ilDeleteImages(1, &crateImageId);
while ((Error = ilGetError()) != IL_NO_ERROR) {
printf("%d: /n", Error);
}
glBindTexture(GL_TEXTURE_2D, 0);
ifile shader_file;
shader_file.read("shaders/cubeTex.vert");
std::string vertex_source = shader_file.get_contents();
const GLchar* vertex_source_c = (const GLchar*)vertex_source.c_str();
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_source_c, nullptr);
glCompileShader(vertex_shader);
GLint Result = GL_FALSE;
int InfoLogLength;
// Check Vertex Shader
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &Result);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(vertex_shader, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
printf("%s\n", &VertexShaderErrorMessage[0]);
}
shader_file.read("shaders/cubeColorsTex.frag");
std::string fragment_source = shader_file.get_contents();
const GLchar* fragment_source_c = (const GLchar*)fragment_source.c_str();
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_source_c, nullptr);
glCompileShader(fragment_shader);
Result = GL_FALSE;
InfoLogLength;
// Check Frag Shader
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &Result);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> FragShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(fragment_shader, InfoLogLength, NULL, &FragShaderErrorMessage[0]);
printf("%s\n", &FragShaderErrorMessage[0]);
}
shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glBindAttribLocation(shader_program, 0, "VertexPosition");
glBindAttribLocation(shader_program, 1, "Color");
glBindAttribLocation(shader_program, 2, "VertexNormal");
glBindAttribLocation(shader_program, 3, "TexC");
glLinkProgram(shader_program);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glUseProgram(0);
}
void scene_texture::awake() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_PROGRAM_POINT_SIZE);
}
void scene_texture::sleep() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_PROGRAM_POINT_SIZE);
}
void scene_texture::mainLoop() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shader_program);
float t = time::elapsed_time().count();
////Vmath library from http://www.openglsuperbible.com/example-code/
//Model matrix
cgmath::mat4 rotationMatrix = cgmath::mat4::rotateMatrix(t*30.0f, t*60.0f, t*30.0f);
cgmath::mat4 modelMatrix = rotationMatrix;
// View Matrix
cgmath::mat4 viewMatrix(1.0f);
viewMatrix[3][2] = 20.0f;
viewMatrix = cgmath::mat4::inverse(viewMatrix);
// Projection Matrix
float far = 1000.0f;
float near = 1.0f;
float half_fov = cgmath::radians(30.0f);
cgmath::mat4 projectionMatrix;
projectionMatrix[0][0] = 1.0f / (1.0f * tan(half_fov));
projectionMatrix[1][1] = 1.0f / tan(half_fov);
projectionMatrix[2][2] = -((far + near) / (far - near));
projectionMatrix[2][3] = -1.0f;
projectionMatrix[3][2] = -((2 * far * near) / (far - near));
cgmath::mat4 mvpMatrix = projectionMatrix * viewMatrix * modelMatrix;
cgmath::mat3 esqSupIzq = cgmath::mat3();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
esqSupIzq[i][j] = modelMatrix[i][j];
cgmath::mat3 normalMatrix = cgmath::mat3::transpose(cgmath::mat3::inverse(esqSupIzq));
GLuint mvp_location = glGetUniformLocation(shader_program, "MVPMatrix");
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, &mvpMatrix[0][0]);
GLuint normal_location = glGetUniformLocation(shader_program, "NormalMatrix");
glUniformMatrix3fv(normal_location, 1, GL_FALSE, &normalMatrix[0][0]);
GLuint model_location = glGetUniformLocation(shader_program, "ModelMatrix");
glUniformMatrix4fv(model_location, 1, GL_FALSE, &modelMatrix[0][0]);
cgmath::vec3 lightVector = cgmath::vec3(-3, 6, 10);
GLuint light_location = glGetUniformLocation(shader_program, "LightPosition");
glUniform3fv(light_location, 1, &lightVector[0]);
cgmath::vec3 cameraPos = cgmath::vec3(0, 0, 10);
GLuint camera_loc = glGetUniformLocation(shader_program, "CameraPosition");
glUniform3fv(camera_loc, 1, &cameraPos[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId[0]);
GLint pig_tex_location = glGetUniformLocation(shader_program, "PigTex");
glUniform1i(pig_tex_location, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureId[1]);
GLint crate_tex_location = glGetUniformLocation(shader_program, "CrateTex");
glUniform1i(crate_tex_location, 1);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glUseProgram(0);
}
void scene_texture::resize(int width, int height) {
glViewport(0, 0, width, height);
}
| 32.307479 | 87 | 0.717311 |
ae551ceeabbd4f32ea97ede9162edf49c11e9545 | 2,054 | cpp | C++ | bazaar/PixRaster/UppLept.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | bazaar/PixRaster/UppLept.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | bazaar/PixRaster/UppLept.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "PixRaster.h"
#include <Draw/Draw.h>
NAMESPACE_UPP
///////////////////////////////////////////////////////////////////////////////
// All Leptonica routines operates on Pix data structures; here 2 conversion
// routines are provided to go to/from Upp Images
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Creation of Pix image from an Upp Image
// As Upp Image is in RGBA format, it's simply converted
// to an RGB Leptonica Pix; alpha channel is discarded
PIX *Image2Pix(const Image &img)
{
PIX *pix;
// Get image sizes
int width = img.GetWidth();
int height = img.GetHeight();
// Get image sizes in dots
int sizeX = img.GetDots().cx;
int sizeY = img.GetDots().cy;
// Allocates the Pix structure
pix = pixCreateNoInit(width, height, 32);
if(!pix)
return NULL;
// sets image resolution (if any)
// don't know if it's correct, yet....
pixSetResolution(pix, sizeX / width, sizeY / height);
// transfer the image bytes
memcpy(pixGetData(pix), ~img, 4*width*height);
return pix;
} // END Image2Pix()
///////////////////////////////////////////////////////////////////////////////
// Creation of Upp Image from Pix
// Pix is first converted to an RGB format, then to Upp Image
Image Pix2Image(PIX * pix)
{
bool destroyCopy = false;
// colormapped and non-32 bit depth pixs need conversion before
if(pixGetColormap(pix) || pixGetDepth(pix) != 32)
{
// we need to destroy converted pix on exit
destroyCopy = true;
// convert pix to 32 bit format
pix = pixConvertTo32(pix);
if(!pix)
return Image();
}
// just copy data buffer to a new imagebuffer
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
ImageBuffer img(width, height);
memcpy(~img, pixGetData(pix), 4*width*height);
// sets image type to opaque
// not sure if we must set alpha bit to 255......
img.SetKind(IMAGE_OPAQUE);
if(destroyCopy)
pixDestroy(&pix);
return img;
}
END_UPP_NAMESPACE
| 25.675 | 79 | 0.588121 |
ae5542944f061d0fc74cb545b84b0d4b3d8b6986 | 448 | cpp | C++ | src/get_texture_colour.cpp | jackys-95/computer-graphics-final-image-competition | 65e7c041530f319d10faba177ef03963aad16e56 | [
"MIT"
] | null | null | null | src/get_texture_colour.cpp | jackys-95/computer-graphics-final-image-competition | 65e7c041530f319d10faba177ef03963aad16e56 | [
"MIT"
] | null | null | null | src/get_texture_colour.cpp | jackys-95/computer-graphics-final-image-competition | 65e7c041530f319d10faba177ef03963aad16e56 | [
"MIT"
] | null | null | null | #include "get_texture_colour.h"
#include <iostream>
Eigen::Vector3d get_texture_colour(const std::vector<unsigned char> &rgb, const int height,
const int width, const int offset)
{
int new_height = 0;
if (offset == 247)
{
new_height = 360 - height;
}
else
{
new_height = height;
}
int start_index = 3 * (width + 640 * new_height);
return Eigen::Vector3d(rgb[0 + start_index],rgb[1 +start_index], rgb[2+start_index]);
} | 24.888889 | 92 | 0.676339 |
ae558cbe13ad230e54864517dfea11f3775d4f37 | 7,772 | cpp | C++ | src/particle_filter.cpp | kpilkk/CarND-Kidnapped-Vehicle-Project | ba21c14b6b2b66194fcafefd42bd41768c3d222d | [
"MIT"
] | null | null | null | src/particle_filter.cpp | kpilkk/CarND-Kidnapped-Vehicle-Project | ba21c14b6b2b66194fcafefd42bd41768c3d222d | [
"MIT"
] | null | null | null | src/particle_filter.cpp | kpilkk/CarND-Kidnapped-Vehicle-Project | ba21c14b6b2b66194fcafefd42bd41768c3d222d | [
"MIT"
] | null | null | null | /**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
// using std::string;
// using std::vector;
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
normal_distribution<double> norm_x(x, std[0]);
normal_distribution<double> norm_y(y, std[1]);
normal_distribution<double> norm_theta(theta, std[2]);
default_random_engine generator;
num_particles = 100; // TODO: Set the number of particles
particles.resize(num_particles);
for (auto& p : particles) {
p.x = norm_x(generator);
p.y = norm_y(generator);
p.theta = norm_theta(generator);
p.weight = 1.0;
weights.push_back(1.0);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
default_random_engine generator;
normal_distribution<double> norm_x(0, std_pos[0]);
normal_distribution<double> norm_y(0, std_pos[1]);
normal_distribution<double> norm_theta(0, std_pos[2]);
for (auto & p : particles) {
if (fabs(yaw_rate) > 0.001) {
p.x += velocity / yaw_rate * (sin(p.theta + yaw_rate * delta_t) - sin(p.theta));
p.y += velocity / yaw_rate * (cos(p.theta) - cos(p.theta + yaw_rate * delta_t));
p.theta += yaw_rate * delta_t;
} else {
p.x += velocity * delta_t * cos(p.theta);
p.y += velocity * delta_t * sin(p.theta);
}
p.x += norm_x(generator);
p.y += norm_y(generator);
p.theta += norm_theta(generator);
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
for (auto & obs : observations) {
double mindist = std::numeric_limits<float>::max();
for (auto & pre : predicted) {
double result = dist(obs.x, obs.y, pre.x, pre.y);
if (result < mindist) {
mindist = result;
obs.id = pre.id;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
for (auto & p : particles) {
std::vector<LandmarkObs> predicted;
for (const auto& lm : map_landmarks.landmark_list) {
double result = dist(p.x, p.y, lm.x_f, lm.y_f);
if (result < sensor_range) {
LandmarkObs markObs = LandmarkObs { lm.id_i, lm.x_f, lm.y_f };
predicted.push_back(markObs);
}
}
std::vector<LandmarkObs> observationsmap;
for (const auto & obs : observations) {
LandmarkObs tmp;
tmp.x = p.x + cos(p.theta) * obs.x - sin(p.theta) * obs.y;
tmp.y = p.y + sin(p.theta) * obs.x + cos(p.theta) * obs.y;
observationsmap.push_back(tmp);
}
dataAssociation(predicted, observationsmap);
p.weight = 1.0;
for (const auto &obs_m : observationsmap) {
LandmarkObs landmark;
for (auto & pre : predicted) {
if (pre.id == obs_m.id) {
landmark = pre;
}
}
double gauss_norm = 1 / (2 * M_PI * std_landmark[0] * std_landmark[1]);
double exponent = pow(obs_m.x - landmark.x, 2) / (2 * pow(std_landmark[0], 2))
+ pow(obs_m.y - landmark.y, 2) / (2 * pow(std_landmark[1], 2));
p.weight *= gauss_norm * exp(-exponent);
}
weights.push_back(p.weight);
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
int particles_size = particles.size();
vector<double> weights;
for (int i = 0; i < particles_size; i++) {
Particle particle = particles[i];
weights.push_back(particle.weight);
}
discrete_distribution<> d(weights.begin(), weights.end());
default_random_engine generator;
std::vector<Particle> new_particles;
for (int i = 0; i < particles_size; i++) {
int index = d(generator);
new_particles.push_back(particles[index]);
}
particles = new_particles;
weights.clear();
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
} | 35.327273 | 91 | 0.650798 |
ae5b4d125742c200e4661b8418e7cdd46ff338a4 | 958 | hpp | C++ | fsc/include/fsx/sim_event.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | fsc/include/fsx/sim_event.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | fsc/include/fsx/sim_event.hpp | gbucknell/fsc-sdk | 11b7cda4eea35ec53effbe37382f4b28020cd59d | [
"MIT"
] | null | null | null | // (c) Copyright 2008 Samuel Debionne.
//
// Distributed under the MIT Software License. (See accompanying file
// license.txt) or copy at http://www.opensource.org/licenses/mit-license.php)
//
// See http://code.google.com/p/fsc-sdk/ for the library home page.
//
// $Revision: $
// $History: $
/// \file sim_event.hpp
/// Events of the Sim Connect API
#if !defined(__FSX_SIM_EVENT_HPP__)
#define __FSX_SIM_EVENT_HPP__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <cassert>
#include <windows.h>
#include <SimConnect.h>
namespace fsx {
/// Sim connect event.
class sim_event
{
public:
sim_event(SIMCONNECT_CLIENT_EVENT_ID _id, const DWORD& _data) : id_(_id), data_(_data) {}
private:
SIMCONNECT_CLIENT_EVENT_ID id_;
DWORD data_;
};
//template <class T>
//struct sim_data_traits
//{
// int
//};
} //namespace fsx
#endif //__FSX_SIM_EVENT_HPP__ | 17.418182 | 94 | 0.656576 |
ae609a38d49a1719bae957c603e67db286fac184 | 20,403 | cpp | C++ | hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp | MoritzNegwer/vaa3d_tools | bdb2dc95bc13e9a31e1d416cc341c00d97153968 | [
"MIT"
] | null | null | null | hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp | MoritzNegwer/vaa3d_tools | bdb2dc95bc13e9a31e1d416cc341c00d97153968 | [
"MIT"
] | null | null | null | hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp | MoritzNegwer/vaa3d_tools | bdb2dc95bc13e9a31e1d416cc341c00d97153968 | [
"MIT"
] | null | null | null | #include "branchtree.h"
#include <queue>
void adjustRalationForSplitBranches(Branch *origin, vector<Branch *> target) {
target.front()->parent = origin->parent;
if (origin->parent) {
auto it = origin->parent->children.begin();
for (; it != origin->parent->children.end(); ++it) {
if (*it == origin) {
origin->parent->children.erase(it);
break;
}
}
origin->parent->children.push_back(target.front());
}
for (int k = 1; k < target.size(); ++k) {
target[k]->parent = target[k - 1];
target[k - 1]->children.push_back(target[k]);
}
target.back()->children = origin->children;
for (Branch* child : origin->children) {
child->parent = target.back();
}
}
void adjustRalationForRemoveBranch(Branch *origin) {
if (origin->parent) {
auto it = origin->parent->children.begin();
for (; it != origin->parent->children.end(); ++it) {
if (*it == origin) {
origin->parent->children.erase(it);
break;
}
}
}
for (Branch* child : origin->children) {
if (origin->parent) {
origin->parent->children.push_back(child);
}
child->parent = origin->parent;
}
}
void PointFeature::getFeature(unsigned char *pdata, long long *sz, float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
double *vec1 = new double[3];
double *vec2 = new double[3];
double *vec3 = new double[3];
double pc1, pc2, pc3;
int xx = x + 0.5, yy = y + 0.5, zz = z + 0.5;
xx = xx >= sz[0] ? sz[0] - 1 : xx;
xx = xx < 0 ? 0 : xx;
yy = yy >= sz[1] ? sz[1] - 1 : yy;
yy = yy < 0 ? 0 : yy;
zz = zz >= sz[2] ? sz[2] - 1 : zz;
zz = zz < 0 ? 0 : zz;
this->intensity = pdata[zz * sz[0]* sz[1] + yy * sz[0] + xx];
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_3 = pc2 == 0 ? 0 : pc1 / pc2;
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_5 = pc2 == 0 ? 0 : pc1 / pc2;
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_8 = pc2 == 0 ? 0 : pc1 / pc2;
if (x < 5 || x > sz[0] -5 ||
y < 5 || y > sz[1] - 5 ||
z < 5 || z > sz[2] - 5) {
this->nearEdge = 1;
} else {
this->nearEdge = 0;
}
if(vec1){
delete[] vec1; vec1 = 0;
}
if(vec2){
delete[] vec2; vec2 = 0;
}
if(vec3){
delete[] vec3; vec3 = 0;
}
}
void LineFeature::intial() {
this->pointsFeature.clear();
this->pointsFeature = vector<PointFeature>(5);
this->directions.clear();
this->directions = vector<XYZ>(5, XYZ());
this->intensity_mean = this->intensity_std = 0;
this->intensity_mean_r5 = this->intensity_std_r5 = 0;
this->linearity_3_mean = this->linearity_5_mean = this->linearity_8_mean = 0;
}
vector<Branch*> Branch::splitByInflectionPoint(float d, float cosAngleThres) {
vector<Branch*> results;
int pointSize = this->points.size();
float* path = new float[pointSize];
memset(path, 0, sizeof(float) * pointSize);
if (pointSize < 2) {
results.push_back(this);
return results;
}
for (int i = 1; i < pointSize; ++i) {
float tmpD = zx_dist(this->points[i], this->points[i - 1]);
path[i] = path[i-1] + tmpD;
}
XYZ v1,v2;
XYZ p1,p2;
p1 = XYZ(this->points[0].x, this->points[0].y, this->points[0].z);
float cosAngle;
int startPoint = 0;
int i,j,k;
int ppIndex,ccIndex,curIndex;
XYZ pp1,pp2;
float inflectionPointCosAngle;
int inflectionPointIndex = -1;
for (i = 0; i < pointSize;) {
for (j = i+1; j < pointSize; ++j) {
if (path[j] - path[i] > d) {
p2 = XYZ(this->points[j].x, this->points[j].y, this->points[j].z);
if (i == startPoint) {
v1 = p2 - p1;
} else {
v2 = p2 - p1;
cosAngle = dot(normalize(v1), normalize(v2));
if (cosAngle < cosAngleThres) {
inflectionPointCosAngle = 1;
inflectionPointIndex = -1;
for (k = startPoint + 1; k < j; ++k) {
if ((path[k] - path[startPoint]) < d || (path[j] - path[k]) < d) {
continue;
}
curIndex = k;
ppIndex = startPoint;
ccIndex = j;
for (int ki = k - 1; ki >= startPoint; --ki) {
if (path[k] - path[ki] > d) {
ppIndex = ki;
break;
}
}
for (int ki = k + 1; ki <= j; ++ki) {
if (path[ki] - path[k] > d) {
ccIndex = ki;
break;
}
}
pp1 = XYZ(this->points[ppIndex].x, this->points[ppIndex].y, this->points[ppIndex].z);
pp2 = XYZ(this->points[ccIndex].x, this->points[ccIndex].y, this->points[ccIndex].z);
double tmpCosAngle = dot(normalize(pp1), normalize(pp2));
if (tmpCosAngle < inflectionPointCosAngle) {
inflectionPointCosAngle = tmpCosAngle;
inflectionPointIndex = k;
}
}
if(cosAngle > (sqrt(2.0)/2) || inflectionPointIndex == -1){
inflectionPointIndex = (j + startPoint) / 2;
}
Branch* line = new Branch();
for (k = startPoint; k <= inflectionPointIndex; ++k) {
line->points.push_back(this->points[k]);
}
results.push_back(line);
startPoint = j;
}
}
p1 = p2;
break;
}
}
i = j;
}
if (startPoint == 0) {
results.push_back(this);
return results;
} else {
Branch* line = new Branch();
for (k = inflectionPointIndex; k < pointSize; ++k) {
line->points.push_back(this->points[k]);
}
results.push_back(line);
}
adjustRalationForSplitBranches(this, results);
return results;
}
vector<Branch*> Branch::splitByLength(float l_thres) {
vector<Branch*> results;
this->calLength();
if (this->length < l_thres) {
results.push_back(this);
return results;
}
int length_mean = this->length / ceil(this->length / l_thres);
int count_i = 1;
float path_length = 0;
int start_index = 0;
for (int i = 1; i<this->points.size() - 1; ++i) {
path_length += zx_dist(this->points[i], this->points[i - 1]);
if (path_length > length_mean * count_i) {
Branch* branch = new Branch();
branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.begin() + i + 1);
results.push_back(branch);
start_index = i;
count_i++;
}
}
Branch* branch = new Branch();
branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.end());
results.push_back(branch);
adjustRalationForSplitBranches(this, results);
return results;
}
void Branch::removePointsNearSoma(const NeuronSWC &soma, float ratio) {
if (this->level > 2) {
return;
}
auto it = this->points.begin();
for (; it != this->points.end(); ) {
if (zx_dist(*it, soma) < soma.r * ratio) {
this->points.erase(it);
} else {
break;
}
}
}
void Branch::removeTerminalPoints(float d) {
auto it = this->points.begin();
float length = 0;
for (; it != this->points.end() - 1; ) {
if (length < d) {
length += zx_dist(*it, *(it + 1));
this->points.erase(it);
} else {
break;
}
}
it = this->points.end() - 1;
length = 0;
for (; it != this->points.begin(); ) {
if (length < d) {
length += zx_dist(*it, *(it - 1));
this->points.erase(it);
--it;
} else {
break;
}
}
}
float Branch::calLength() {
this->length = 0;
auto it = this->points.begin();
for(; it != this->points.end() - 1; ++it) {
this->length += zx_dist(*it, *(it + 1));
}
return this->length;
}
float Branch::calDistance() {
this->distance = this->points.size() ? zx_dist(this->points.front(), this->points.back()) : 0;
return this->distance;
}
void Branch::getFeature(unsigned char *pdata, long long *sz) {
this->line_feature.intial();
this->calLength();
this->calDistance();
int pointSize = this->points.size();
double *vec1 = new double[3];
double *vec2 = new double[3];
double *vec3 = new double[3];
int x,y,z;
double pc1,pc2,pc3;
vector<unsigned char> intensities;
this->line_feature.pointsFeature[0].getFeature(pdata, sz, this->points.front().x, this->points.front().y, this->points.front().z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature.front().intensity;
intensities.push_back(this->line_feature.pointsFeature.front().intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.front().linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.front().linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.front().linearity_8;
int point_i = 1;
float cur_length = 0;
for (int i = 1; i < pointSize - 1; ++i) {
cur_length += zx_dist(this->points[i], this->points[i - 1]);
if (cur_length > this->length / 5 * point_i) {
this->line_feature.pointsFeature[point_i].getFeature(pdata, sz, this->points[i].x, this->points[i].y, this->points[i].z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature[point_i].intensity;
intensities.push_back(this->line_feature.pointsFeature[point_i].intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature[point_i].linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature[point_i].linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature[point_i].linearity_8;
point_i++;
} else {
x = this->points[i].x + 0.5;
y = this->points[i].y + 0.5;
z = this->points[i].z + 0.5;
x = x >= sz[0] ? sz[0] - 1 : x;
x = x < 0 ? 0 : x;
y = y >= sz[1] ? sz[1] - 1 : y;
y = y < 0 ? 0 : y;
z = z >= sz[2] ? sz[2] - 1 : z;
z = z < 0 ? 0 : z;
this->line_feature.intensity_mean += pdata[z * sz[0] * sz[1] + y * sz[0] + x];
intensities.push_back(pdata[z * sz[0] * sz[1] + y * sz[0] + x]);
computeCubePcaEigVec(pdata, sz, x, y, z, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_3_mean += (pc2 == 0 ? 0 : pc1 / pc2);
computeCubePcaEigVec(pdata, sz, x, y, z, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_5_mean += (pc2 == 0 ? 0 : pc1 / pc2);
computeCubePcaEigVec(pdata, sz, x, y, z, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_8_mean += (pc2 == 0 ? 0 : pc1 / pc2);
}
}
this->line_feature.pointsFeature[4].getFeature(pdata, sz, this->points.back().x, this->points.back().y, this->points.back().z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature.back().intensity;
intensities.push_back(this->line_feature.pointsFeature.front().intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.back().linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.back().linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.back().linearity_8;
this->line_feature.intensity_mean /= pointSize;
this->line_feature.linearity_3_mean /= pointSize;
this->line_feature.linearity_5_mean /= pointSize;
this->line_feature.linearity_8_mean /= pointSize;
for (auto intensity : intensities) {
this->line_feature.intensity_std += pow((intensity - this->line_feature.intensity_mean), 2);
}
this->line_feature.intensity_std = sqrt(this->line_feature.intensity_std / pointSize);
NeuronTree nt_r5;
for (NeuronSWC s : this->points) {
s.radius = 5;
nt_r5.listNeuron.push_back(s);
}
setNeuronTreeHash(nt_r5);
vector<MyMarker*> markers_r5 = swc_convert(nt_r5);
unsigned char* mask_r5 = 0;
swcTomask(mask_r5, markers_r5, sz[0], sz[1], sz[2]);
V3DLONG total_sz = sz[0] * sz[1] * sz[2];
intensities.clear();
// qDebug()<<"origin: "<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5;
// qDebug()<<"intensity size: "<<intensities.size();
for (int i = 0; i < total_sz; ++i) {
if (mask_r5[i] > 0) {
this->line_feature.intensity_mean_r5 += pdata[i];
intensities.push_back(pdata[i]);
}
}
// qDebug()<<"after intensity size: "<<intensities.size();
if (intensities.size() > 0) {
this->line_feature.intensity_mean_r5 /= intensities.size();
}
for (auto intensity : intensities) {
this->line_feature.intensity_std_r5 += pow((intensity - this->line_feature.intensity_mean_r5), 2);
}
if (intensities.size() > 0) {
this->line_feature.intensity_std_r5 = sqrt(this->line_feature.intensity_std_r5 / intensities.size());
}
// qDebug()<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5;
if (this->line_feature.pointsFeature.front().x > this->line_feature.pointsFeature.back().x) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
} else if (this->line_feature.pointsFeature.front().x == this->line_feature.pointsFeature.back().x) {
if (this->line_feature.pointsFeature.front().y > this->line_feature.pointsFeature.back().y) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
} else if (this->line_feature.pointsFeature.front().y == this->line_feature.pointsFeature.back().y){
if (this->line_feature.pointsFeature.front().z > this->line_feature.pointsFeature.back().z) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
}
}
}
this->line_feature.directions[0] = XYZ(this->line_feature.pointsFeature.back().x - this->line_feature.pointsFeature.front().x,
this->line_feature.pointsFeature.back().y - this->line_feature.pointsFeature.front().y,
this->line_feature.pointsFeature.back().z - this->line_feature.pointsFeature.front().z);
for (int i = 1; i < this->line_feature.pointsFeature.size(); ++i) {
this->line_feature.directions[i] = XYZ(this->line_feature.pointsFeature[i].x - this->line_feature.pointsFeature[i - 1].x,
this->line_feature.pointsFeature[i].y - this->line_feature.pointsFeature[i - 1].y,
this->line_feature.pointsFeature[i].z - this->line_feature.pointsFeature[i - 1].z);
}
for (int i = 0; i < 5; ++i) {
normalize(this->line_feature.directions[i]);
}
}
bool BranchTree::initialize(NeuronTree &nt) {
this->branches.clear();
vector<V3DLONG> rootIndex = vector<V3DLONG>();
V3DLONG size = nt.listNeuron.size();
vector<vector<V3DLONG> > children = vector<vector<V3DLONG> >(size,vector<V3DLONG>());
for (V3DLONG i = 0; i < size; ++i) {
V3DLONG prt = nt.listNeuron[i].parent;
if (nt.hashNeuron.contains(prt)) {
V3DLONG prtIndex = nt.hashNeuron.value(prt);
children[prtIndex].push_back(i);
} else {
rootIndex.push_back(i);
}
}
queue<V3DLONG> q;
if (rootIndex.size() != 1) {
return false;
} else {
this->soma = nt.listNeuron[rootIndex.front()];
q.push(rootIndex.front());
if (soma.parent == -1) {
this->hasSoma = true;
} else {
this->hasSoma = false;
}
}
while (!q.empty()) {
V3DLONG tmp = q.front();
q.pop();
vector<V3DLONG>& child = children[tmp];
for(int i = 0; i < child.size(); ++i)
{
Branch* branch = new Branch();
int cIndex = child[i];
branch->points.push_back(nt.listNeuron[tmp]);
while(children[cIndex].size() == 1)
{
branch->points.push_back(nt.listNeuron[cIndex]);
cIndex = children[cIndex][0];
}
if(children.at(cIndex).size() >= 1)
{
q.push(cIndex);
}
branch->points.push_back(nt.listNeuron[cIndex]);
this->branches.push_back(branch);
}
}
//initial parent
for(int i = 0; i < this->branches.size(); ++i)
{
if(this->branches[i]->points.front().parent == this->soma.parent)
{
this->branches[i]->parent = nullptr;
}
else
{
for(int j = 0; j < this->branches.size(); ++j)
{
if(this->branches[i]->points.front().n == this->branches[j]->points.back().n)
{
this->branches[i]->parent = this->branches[j];
break;
}
}
}
}
//initial level
for(int i = 0; i < this->branches.size(); ++i)
{
Branch* branch = this->branches[i];
int level=0;
while(branch->parent != nullptr)
{
level++;
branch = branch->parent;
}
this->branches[i]->level = level;
}
//initial children
for(int i = 0; i < this->branches.size(); ++i){
if (this->branches[i]->parent) {
this->branches[i]->parent->children.push_back(this->branches[i]);
}
}
}
void BranchTree::preProcess(float inflection_d, float cosAngleThres,
float l_thres_max, float l_thres_min,
float t_length, float soma_ratio) {
vector<Branch*> tmp_results;
for (Branch* branch : this->branches) {
vector<Branch*> s_results = branch->splitByInflectionPoint(inflection_d, cosAngleThres);
tmp_results.insert(tmp_results.end(), s_results.begin(), s_results.end());
}
this->branches.clear();
for (Branch* branch : tmp_results) {
vector<Branch*> s_results = branch->splitByLength(l_thres_max);
this->branches.insert(this->branches.end(), s_results.begin(), s_results.end());
}
if (this->hasSoma) {
for (Branch* branch : this->branches) {
branch->removePointsNearSoma(this->soma, soma_ratio);
}
}
for (Branch* branch : this->branches) {
branch->removeTerminalPoints(t_length);
}
auto it = this->branches.begin();
for (; it != this->branches.end();) {
if ((*it)->calLength() < l_thres_min) {
adjustRalationForRemoveBranch(*it);
this->branches.erase(it);
} else {
++it;
}
}
}
void BranchTree::getFeature(unsigned char *pdata, long long *sz) {
for (Branch* branch : this->branches) {
branch->getFeature(pdata, sz);
}
}
| 36.82852 | 134 | 0.538646 |
ae615bac2d2f06e2f0a8f5674d924c2d6e7c1292 | 546 | hh | C++ | cs252/LABS/shell/command.hh | fshafi1997/PurdueComputerScience | 673c56daf80f059f5064c3e096a9e27d9c84a7a5 | [
"MIT"
] | null | null | null | cs252/LABS/shell/command.hh | fshafi1997/PurdueComputerScience | 673c56daf80f059f5064c3e096a9e27d9c84a7a5 | [
"MIT"
] | null | null | null | cs252/LABS/shell/command.hh | fshafi1997/PurdueComputerScience | 673c56daf80f059f5064c3e096a9e27d9c84a7a5 | [
"MIT"
] | null | null | null | #ifndef command_hh
#define command_hh
#include "simpleCommand.hh"
// Command Data Structure
struct Command {
std::vector<SimpleCommand *> _simpleCommands;
std::string * _outFile;
std::string * _inFile;
std::string * _errFile;
bool _background;
int _counterOut;
int _counterIn;
int appendFlag;
Command();
void insertSimpleCommand( SimpleCommand * simpleCommand );
void expanding();
void clear();
void print();
void execute();
int checkForBuiltIn(int i);
static SimpleCommand *_currentSimpleCommand;
};
#endif
| 18.2 | 60 | 0.721612 |
ae62f1acdcbd3b242c2ab531e9039846d26c5ebe | 2,994 | cpp | C++ | src/Eos/SurfaceGroup/eossurfacegroupclient.cpp | sparkleholic/qml-webos-framework | dbf1f8608ae88b189dedd358acc97d9504425996 | [
"Apache-2.0"
] | 12 | 2018-03-17T12:35:32.000Z | 2021-10-15T09:04:56.000Z | src/Eos/SurfaceGroup/eossurfacegroupclient.cpp | sparkleholic/qml-webos-framework | dbf1f8608ae88b189dedd358acc97d9504425996 | [
"Apache-2.0"
] | 2 | 2020-05-28T14:58:01.000Z | 2022-02-04T04:03:07.000Z | src/Eos/SurfaceGroup/eossurfacegroupclient.cpp | sparkleholic/qml-webos-framework | dbf1f8608ae88b189dedd358acc97d9504425996 | [
"Apache-2.0"
] | 5 | 2018-03-22T18:54:18.000Z | 2020-03-04T19:20:01.000Z | // Copyright (c) 2015-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "eossurfacegroupclient.h"
EosSurfaceGroupClient::EosSurfaceGroupClient(QObject *parent)
: QObject (parent)
, m_webOSWindow (0)
, m_SurfaceGroup (0)
{
}
EosSurfaceGroupClient::~EosSurfaceGroupClient()
{
if (m_SurfaceGroup) {
delete m_SurfaceGroup;
m_SurfaceGroup = 0;
}
}
void EosSurfaceGroupClient::classBegin()
{
}
void EosSurfaceGroupClient::componentComplete()
{
if (!m_webOSWindow) {
qCritical("Need valid value for \"webOSWindow\" ");
return;
}
if (m_groupName.isEmpty()) {
qCritical("Need valid value for \"groupName\" ");
return;
}
handleWindowVisibility();
}
void EosSurfaceGroupClient::handleWindowVisibility()
{
if (m_SurfaceGroup) {
return;
}
if (m_webOSWindow && m_webOSWindow->isVisible()) {
WebOSSurfaceGroupCompositor* compositor = WebOSPlatform::instance()->surfaceGroupCompositor();
if (compositor) {
if (!m_groupName.isEmpty()) {
m_SurfaceGroup = compositor->getGroup(m_groupName);
if (m_SurfaceGroup) {
if (m_layerName.isEmpty()) {
m_SurfaceGroup->attachAnonymousSurface(m_webOSWindow);
} else {
m_SurfaceGroup->attachSurface(m_webOSWindow, m_layerName);
}
}
}
}
}
}
void EosSurfaceGroupClient::setGroupName(const QString& groupName)
{
if (m_groupName.isEmpty() && !groupName.isEmpty()) {
m_groupName = groupName;
}
}
void EosSurfaceGroupClient::setWebOSWindow(WebOSQuickWindow* webOSWindow)
{
if (!m_webOSWindow && webOSWindow) {
m_webOSWindow = webOSWindow;
QObject::connect(m_webOSWindow, SIGNAL(visibleChanged(bool)),
this, SLOT(handleWindowVisibility()));
}
}
void EosSurfaceGroupClient::setLayerName(const QString& layerName)
{
if (m_layerName.isEmpty() && !layerName.isEmpty()) {
m_layerName = layerName;
}
}
void EosSurfaceGroupClient::focusOwner()
{
if (m_SurfaceGroup) {
m_SurfaceGroup->focusOwner();
}
}
void EosSurfaceGroupClient::focusLayer()
{
if (m_SurfaceGroup) {
if (!m_layerName.isEmpty()) {
m_SurfaceGroup->focusLayer(m_layerName);
}
}
}
| 25.810345 | 102 | 0.642285 |
ae6907210038d0f445acfc2d470f884aadd55ec4 | 802 | hpp | C++ | ql/experimental/templatemodels/hybrid/hybridmodels.hpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | null | null | null | ql/experimental/templatemodels/hybrid/hybridmodels.hpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | null | null | null | ql/experimental/templatemodels/hybrid/hybridmodels.hpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | null | null | null | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2019 Sebastian Schlenkrich
*/
/*! \file hybridmodels.hpp
\brief bind template types to double
*/
#ifndef quantlib_hybridmodels_hpp
#define quantlib_hybridmodels_hpp
#include <ql/experimental/templatemodels/hybrid/assetmodelT.hpp>
#include <ql/experimental/templatemodels/hybrid/hybridmodelT.hpp>
#include <ql/experimental/templatemodels/hybrid/spreadmodelT.hpp>
namespace QuantLib {
typedef AssetModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> AssetModel;
typedef HybridModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> HybridModel;
typedef SpreadModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> SpreadModel;
}
#endif /* ifndef quantlib_hybridmodelshpp */
| 25.0625 | 85 | 0.753117 |
ae6a31d9655395ef70277c4e533cd2fd26227972 | 671 | cpp | C++ | src/ProjectileGraphicsComponent.cpp | filipecaixeta/NeonEdgeGame | 7dbc825507d731d60a96b4a82975a70e6aa68d7e | [
"MIT"
] | 6 | 2017-05-10T19:25:23.000Z | 2021-04-08T23:55:17.000Z | src/ProjectileGraphicsComponent.cpp | filipecaixeta/NeonEdgeGame | 7dbc825507d731d60a96b4a82975a70e6aa68d7e | [
"MIT"
] | 1 | 2017-11-10T12:17:26.000Z | 2017-11-10T12:17:26.000Z | src/ProjectileGraphicsComponent.cpp | filipecaixeta/NeonEdgeGame | 7dbc825507d731d60a96b4a82975a70e6aa68d7e | [
"MIT"
] | 5 | 2017-05-30T01:07:46.000Z | 2021-04-08T23:55:19.000Z | // Copyright (c) 2017 Neon Edge Game.
#include "ProjectileGraphicsComponent.h"
#include "Projectile.h"
#include "Rect.h"
ProjectileGraphicsComponent::ProjectileGraphicsComponent(std::string baseNameParam):
GraphicsComponent(baseNameParam) {
AddSprite(baseName, "Projectile", 4, 80);
sprite = sprites["Projectile"];
surface = surfaces["Projectile"];
}
ProjectileGraphicsComponent::~ProjectileGraphicsComponent() {
}
void ProjectileGraphicsComponent::Update(GameObject *gameObject, float deltaTime) {
characterLeftDirection = (gameObject->facing == GameObject::LEFT);
sprite->Mirror(characterLeftDirection);
sprite->Update(deltaTime);
}
| 29.173913 | 84 | 0.755589 |
ae6b36b615553c52c30538243fca26525e741ce4 | 323 | hxx | C++ | inc/html5xx.d/Article.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | inc/html5xx.d/Article.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | inc/html5xx.d/Article.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | /*
*
*/
#ifndef _HTML5XX_ARTICLE_HXX_
#define _HTML5XX_ARTICLE_HXX_
#include "Element.hxx"
using namespace std;
namespace html
{
class Article: public Element
{
public:
Article():
Element(Block, "article")
{}
};
} // end namespace html
#endif // _HTML5XX_ARTICLE_HXX_
// vi: set ai et sw=2 sts=2 ts=2 :
| 10.766667 | 34 | 0.678019 |
ae6e20ab813074a83619a655aae7ccdca6126795 | 4,408 | hpp | C++ | common/array.hpp | ChaosGroup/cg2_2014_demo | fd7a70399321e9cdbc205ff1c74dd04ed7b922f0 | [
"MIT"
] | 1 | 2016-03-01T16:44:06.000Z | 2016-03-01T16:44:06.000Z | common/array.hpp | ChaosGroup/cg2_2014_demo | fd7a70399321e9cdbc205ff1c74dd04ed7b922f0 | [
"MIT"
] | null | null | null | common/array.hpp | ChaosGroup/cg2_2014_demo | fd7a70399321e9cdbc205ff1c74dd04ed7b922f0 | [
"MIT"
] | null | null | null | #ifndef array_H__
#define array_H__
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include "aligned_ptr.hpp"
template < typename ELEMENT_T, size_t ALIGNMENT = 64 >
class Array
{
enum { alignment = ALIGNMENT };
protected:
uint32_t m_capacity;
uint32_t m_count;
aligned_ptr< ELEMENT_T, alignment > m_elem;
// call only from copy ctors
template < size_t SRC_ALIGNMENT >
void actual_copy_ctor(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src);
// call only from assignment operators
template < size_t SRC_ALIGNMENT >
Array& actual_assignment(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src);
public:
Array()
: m_capacity(0)
, m_count(0) {
}
Array(
const Array& src) {
actual_copy_ctor(src);
}
template < size_t SRC_ALIGNMENT >
Array(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src) {
actual_copy_ctor(src);
}
~Array();
Array& operator =(
const Array& src) {
return actual_assignment(src);
}
template < size_t SRC_ALIGNMENT >
Array& operator =(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src) {
return actual_assignment(src);
}
bool
setCapacity(
const size_t n);
size_t
getCapacity() const {
return m_capacity;
}
size_t
getCount() const {
return m_count;
}
void
resetCount() {
setCapacity(m_capacity);
}
bool
addElement();
bool
addElement(
const ELEMENT_T &e);
bool
addMultiElement(
const size_t count);
const ELEMENT_T&
getElement(
const size_t i) const;
ELEMENT_T&
getMutable(
const size_t i);
};
template < typename ELEMENT_T, size_t ALIGNMENT >
template < size_t SRC_ALIGNMENT >
inline void Array< ELEMENT_T, ALIGNMENT >::actual_copy_ctor(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src) {
m_capacity = 0;
m_count = 0;
if (0 == src.m_capacity)
return;
assert(!src.m_elem.is_null());
m_elem.malloc(src.m_capacity);
if (m_elem.is_null())
return;
for (size_t i = 0; i < src.m_count; ++i)
new (m_elem + i) ELEMENT_T(src.m_elem[i]);
m_capacity = src.m_capacity;
m_count = src.m_count;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline Array< ELEMENT_T, ALIGNMENT >::~Array() {
assert(0 == m_capacity || !m_elem.is_null());
for (size_t i = 0; i < m_count; ++i)
m_elem[i].~ELEMENT_T();
#if !defined(NDEBUG)
m_capacity = 0;
m_count = 0;
#endif
}
template < typename ELEMENT_T, size_t ALIGNMENT >
template < size_t SRC_ALIGNMENT >
inline Array< ELEMENT_T, ALIGNMENT >&
Array< ELEMENT_T, ALIGNMENT >::actual_assignment(
const Array< ELEMENT_T, SRC_ALIGNMENT >& src) {
if (setCapacity(src.m_capacity)) {
for (size_t i = 0; i < src.m_count; ++i)
new (m_elem + i) ELEMENT_T(src.m_elem[i]);
m_count = src.m_count;
}
return *this;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline bool
Array< ELEMENT_T, ALIGNMENT >::setCapacity(
const size_t n) {
// setting the capacity resets the content
for (size_t i = 0; i < m_count; ++i)
m_elem[i].~ELEMENT_T();
m_count = 0;
if (m_capacity == n)
return true;
m_capacity = 0;
if (0 == n) {
m_elem.free();
return true;
}
m_elem.malloc(n);
if (m_elem.is_null())
return false;
m_capacity = n;
return true;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline bool
Array< ELEMENT_T, ALIGNMENT >::addElement() {
if (m_count == m_capacity)
return false;
assert(!m_elem.is_null());
new (m_elem + m_count++) ELEMENT_T();
return true;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline bool
Array< ELEMENT_T, ALIGNMENT >::addElement(
const ELEMENT_T& e) {
if (m_count == m_capacity)
return false;
assert(!m_elem.is_null());
new (m_elem + m_count++) ELEMENT_T(e);
return true;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline bool
Array< ELEMENT_T, ALIGNMENT >::addMultiElement(
const size_t count) {
if (m_count + count > m_capacity)
return false;
assert(!m_elem.is_null());
for (size_t i = 0; i < count; ++i)
new (m_elem + m_count + i) ELEMENT_T();
m_count += count;
return true;
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline const ELEMENT_T&
Array< ELEMENT_T, ALIGNMENT >::getElement(
const size_t i) const {
assert(i < m_count);
assert(!m_elem.is_null());
return m_elem[i];
}
template < typename ELEMENT_T, size_t ALIGNMENT >
inline ELEMENT_T&
Array< ELEMENT_T, ALIGNMENT >::getMutable(
const size_t i) {
assert(i < m_count);
assert(!m_elem.is_null());
return m_elem[i];
}
#endif // array_H__
| 17.151751 | 60 | 0.690563 |
ae6e79bfa2356803e033cc0b24673eaff495daca | 4,352 | cpp | C++ | conui/examples/Test5ValEdit.cpp | amalk/GUI-CLI | a08f3eed8d65c1cfef259397990f9e218a77d594 | [
"MIT"
] | 3 | 2016-08-17T09:35:16.000Z | 2019-02-07T21:27:58.000Z | conui/examples/Test5ValEdit.cpp | amalk/GUI-CLI | a08f3eed8d65c1cfef259397990f9e218a77d594 | [
"MIT"
] | null | null | null | conui/examples/Test5ValEdit.cpp | amalk/GUI-CLI | a08f3eed8d65c1cfef259397990f9e218a77d594 | [
"MIT"
] | 3 | 2016-08-17T09:35:21.000Z | 2018-02-14T08:14:35.000Z | // Console Input Output Library Tester program for CValEdit
// Test5ValEdit.cpp
//
// Fardad Soleimanloo, Chris Szalwinski
// Oct 10 2012
// Version 0.9
#include "cuigh.h"
#include "console.h"
#include "cframe.h"
#include "cdialog.h"
#include "clabel.h"
#include "cveditline.h"
#include "cbutton.h"
#include <cstring>
#include <cctype>
using namespace std;
using namespace cui;
bool Yes(const char* message, CDialog* owner);
void Help(CDialog* owner, CDialog* helping);
void PhoneHelp(MessageStatus st, CDialog& owner);
void LastNameHelp(MessageStatus st, CDialog& owner);
bool ValidPhone(const char* ph , CDialog& owner);
int main()
{
int key = 0;
int i = 1;
bool done = false;
bool insert = true;
char str[81] = "I want to edit this thing!";
for(int k = 0; k < console.getRows(); k += 2)
{
for(int m = 0; m < console.getCols() - 10; m += 10)
{
console.strdsp((i = !i) ? "Hello" : "Hi", k, m);
}
}
CDialog Screen;
CDialog FD(&Screen, 5, 5, 70, 15, true);
CLabel PhHelp(8, 34, 30);
CLabel LnHelp(5, 37, 30);
CLabel ErrMes(10, 2, 67);
Screen << new CLabel("F1: HELP ", 0, 0);
FD << new CLabel("Name:", 2, 2)
<< new CLineEdit(1, 10, 20, 40, &insert, true)
<< new CLabel("Lastname:", 5, 2)
<< new CValEdit(4, 13, 20, 40, &insert, NO_VALDFUNC, LastNameHelp, true)
<< new CLabel("Phone Number", 8, 2)
<< new CValEdit(7, 16, 15, 12, &insert, ValidPhone, PhoneHelp, true)
<< PhHelp
<< LnHelp
<< ErrMes
<< new CLabel("F1: help, ESCAPE: exit", 11, 2);
FD.draw();
while(!done)
{
key = FD.edit();
switch(key)
{
case F(1):
Help(&Screen, &FD);
break;
case ESCAPE:
if(Yes("Do you really want to quit?", &Screen))
{
done = true;
}
break;
case F(6):
FD.move();
break;
}
}
return 0;
}
bool Yes(const char* message, CDialog* owner)
{
int key;
bool res = false;
bool done = false;
CButton bt_yes("Yes", 4, 4 , true, " _ ");
CButton bt_no("No", 4, 15 , true, " _ ");
CDialog YesNo(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true);
YesNo << new CLabel(2, 2, 36) << bt_yes << bt_no;
YesNo[0].set(message);
YesNo.draw(C_FULL_FRAME);
while(!done)
{
key = YesNo.edit();
if(key == C_BUTTON_HIT)
{
res = &YesNo.curField() == &bt_yes;
done = true;
}
else if(key == F(6))
{
YesNo.move();
}
}
YesNo.hide();
return res;
}
void Help(CDialog* owner, CDialog* helping)
{
CDialog help(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true);
help << new CLabel(2, 3, 36)
<< new CLabel("Escape Key: Exit the test program.", 4, 3)
<< new CLabel("F1 Key: Open this window.", 6, 3);
switch(helping->curIndex())
{
case 1:
help[0].set("Enter the name here!");
break;
case 3:
help[0].set("Enter the Last name here!");
break;
case 5:
help[0].set("Enter Phone number: 999-999-9999");
}
while(help.edit(C_FULL_FRAME) == F(6))
{
help.move();
}
help.hide();
}
void PhoneHelp(MessageStatus st, CDialog& owner)
{
if(st == ClearMessage)
{
owner[6].set("");
}
else
{
owner[6].set("Phone Format: 999-999-9999");
}
owner.draw(7);
}
void LastNameHelp(MessageStatus st, CDialog& owner)
{
if(st == ClearMessage)
{
owner[7].set("");
}
else
{
owner[7].set("i.e. Middle name and Surname");
}
owner.draw(8);
}
bool ValidPhone(const char* ph , CDialog& owner)
{
bool ok = true;
int i;
for(i = 0; ok && i < 3; ok = (bool)isdigit(ph[i]), i++);
ok = ph[i++] == '-';
for(; ok && i < 7; ok = (bool)isdigit(ph[i]), i++);
ok = ph[i++] == '-';
for(; ok && i < 12; ok = (bool)isdigit(ph[i]), i++);
if(ok)
{
owner[8].set("");
}
else
{
owner[8].set("Invlid phone number, please use the specified phone number format!");
}
owner.draw(9);
return ok;
}
| 21.544554 | 99 | 0.516774 |
ae6e8aa318c8889f6cca7de9f3eeb46bc5c3eb03 | 2,182 | cpp | C++ | test/libwebsocket-mock/mock_lws_minimal.cpp | costanic/mbed-edge | 4900e950ff67f8974b7aeef955289ef56606c964 | [
"Apache-2.0"
] | 24 | 2018-03-27T16:44:18.000Z | 2020-04-28T15:28:34.000Z | test/libwebsocket-mock/mock_lws_minimal.cpp | costanic/mbed-edge | 4900e950ff67f8974b7aeef955289ef56606c964 | [
"Apache-2.0"
] | 19 | 2021-01-28T20:14:45.000Z | 2021-11-23T13:08:59.000Z | test/libwebsocket-mock/mock_lws_minimal.cpp | costanic/mbed-edge | 4900e950ff67f8974b7aeef955289ef56606c964 | [
"Apache-2.0"
] | 28 | 2018-04-02T02:36:48.000Z | 2020-10-13T05:37:16.000Z | #include "CppUTestExt/MockSupport.h"
#include "cpputest-custom-types/value_pointer.h"
extern "C" {
#include "libwebsockets.h"
}
int lws_callback_on_writable(struct lws *wsi)
{
return mock().actualCall("lws_callback_on_writable")
.returnIntValueOrDefault(0);
}
size_t lws_remaining_packet_payload(struct lws *wsi)
{
return mock().actualCall("lws_remaining_packet_payload").returnUnsignedLongIntValue();
}
int lws_is_final_fragment(struct lws *wsi)
{
return mock().actualCall("lws_is_final_fragment").returnIntValue();
}
int lws_is_first_fragment(struct lws *wsi)
{
return mock().actualCall("lws_is_first_fragment").returnIntValue();
}
void lws_close_reason(struct lws *wsi, enum lws_close_status status, unsigned char *buf, size_t len)
{
mock().actualCall("lws_close_reason");
}
int lws_write(struct lws *wsi, unsigned char *buf, size_t len, enum lws_write_protocol protocol)
{
ValuePointer msg_param = ValuePointer(buf, len);
return mock().actualCall("lws_write")
.withParameterOfType("ValuePointer", "buf", &msg_param)
.returnIntValue();
}
struct lws_context *lws_create_context(const struct lws_context_creation_info *info)
{
return (struct lws_context*) mock().actualCall("lws_create_context").returnPointerValue();
}
void lws_context_destroy(struct lws_context *ctx)
{
mock().actualCall("lws_context_destroy");
free(ctx);
}
LWS_VISIBLE LWS_EXTERN struct lws *lws_client_connect_via_info(const struct lws_client_connect_info *ccinfo)
{
return (struct lws*) mock().actualCall("lws_client_connect_via_info")
.withStringParameter("path", ccinfo->path)
.returnPointerValue();
}
int lws_extension_callback_pm_deflate(struct lws_context *context,
const struct lws_extension *ext,
struct lws *wsi,
enum lws_extension_callback_reasons reason,
void *user,
void *in,
size_t len)
{
return mock().actualCall("lws_extension_callback_pm_deflate").returnIntValue();
}
| 31.623188 | 108 | 0.681027 |
ae6ed21530c39a8428342f0b94e687f912f25877 | 22,053 | cpp | C++ | tests/constraint/test_RnBoxConstraint.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 181 | 2016-04-22T15:11:23.000Z | 2022-03-26T12:51:08.000Z | tests/constraint/test_RnBoxConstraint.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 514 | 2016-04-20T04:29:51.000Z | 2022-02-10T19:46:21.000Z | tests/constraint/test_RnBoxConstraint.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 31 | 2017-03-17T09:53:02.000Z | 2022-03-23T10:35:05.000Z | #include <dart/common/Memory.hpp>
#include <gtest/gtest.h>
#include <aikido/common/memory.hpp>
#include <aikido/constraint/uniform/RnBoxConstraint.hpp>
#include <aikido/distance/RnEuclidean.hpp>
#include "SampleGeneratorCoverage.hpp"
using aikido::common::RNG;
using aikido::common::RNGWrapper;
using aikido::constraint::ConstraintType;
using aikido::constraint::SampleGenerator;
using aikido::constraint::uniform::R2BoxConstraint;
using aikido::constraint::uniform::RnBoxConstraint;
using aikido::distance::R2Euclidean;
using aikido::distance::RnEuclidean;
using aikido::statespace::R2;
using aikido::statespace::Rn;
using Eigen::Matrix2d;
using Eigen::Vector2d;
class RnBoxConstraintTests : public ::testing::Test
{
protected:
static constexpr std::size_t NUM_X_TARGETS{10};
static constexpr std::size_t NUM_Y_TARGETS{10};
static constexpr std::size_t NUM_SAMPLES{10000};
static constexpr double DISTANCE_THRESHOLD{0.15};
void SetUp() override
{
mR2StateSpace = std::make_shared<R2>();
mRxStateSpace = std::make_shared<Rn>(2);
mR2Distance = std::make_shared<R2Euclidean>(mR2StateSpace);
mRxDistance = std::make_shared<RnEuclidean>(mRxStateSpace);
mRng
= ::aikido::common::make_unique<RNGWrapper<std::default_random_engine>>(
0);
mLowerLimits = Vector2d(-1., 1.);
mUpperLimits = Vector2d(1., 2.);
mGoodValues.resize(3);
mGoodValues[0] = Vector2d(-0.9, 1.1);
mGoodValues[1] = Vector2d(0.0, 1.5);
mGoodValues[2] = Vector2d(0.9, 1.9);
mBadValues.resize(8);
mBadValues[0] = Vector2d(-1.1, 1.5);
mBadValues[1] = Vector2d(1.1, 1.5);
mBadValues[2] = Vector2d(0.0, 0.9);
mBadValues[3] = Vector2d(0.0, 2.1);
mBadValues[4] = Vector2d(-1.1, 0.9);
mBadValues[5] = Vector2d(-1.1, 2.1);
mBadValues[6] = Vector2d(1.1, 0.9);
mBadValues[7] = Vector2d(1.1, 2.1);
mTargets.clear();
mTargets.reserve(NUM_X_TARGETS * NUM_Y_TARGETS);
for (std::size_t ix = 0; ix < NUM_X_TARGETS; ++ix)
{
auto xRatio = static_cast<double>(ix) / (NUM_X_TARGETS - 1);
auto x = (1 - xRatio) * mLowerLimits[0] + xRatio * mUpperLimits[0];
for (std::size_t iy = 0; iy < NUM_Y_TARGETS; ++iy)
{
auto yRatio = static_cast<double>(iy) / (NUM_Y_TARGETS - 1);
auto y = (1 - yRatio) * mLowerLimits[1] + yRatio * mUpperLimits[1];
auto state = mR2StateSpace->createState();
state.setValue(Vector2d(x, y));
mTargets.emplace_back(std::move(state));
}
}
}
std::unique_ptr<RNG> mRng;
std::shared_ptr<R2> mR2StateSpace;
std::shared_ptr<Rn> mRxStateSpace;
std::shared_ptr<R2Euclidean> mR2Distance;
std::shared_ptr<RnEuclidean> mRxDistance;
Eigen::Vector2d mLowerLimits;
Eigen::Vector2d mUpperLimits;
std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>>
mGoodValues;
std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>>
mBadValues;
std::vector<R2::ScopedState> mTargets;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_constructor_StateSpaceIsNull_Throws)
{
EXPECT_THROW(
{ R2BoxConstraint(nullptr, mRng->clone(), mLowerLimits, mUpperLimits); },
std::invalid_argument);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_constructor_StateSpaceIsNull_Throws)
{
EXPECT_THROW(
{ RnBoxConstraint(nullptr, mRng->clone(), mLowerLimits, mUpperLimits); },
std::invalid_argument);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_constructor_RNGIsNull_DoesNotThrow)
{
EXPECT_NO_THROW(
{ R2BoxConstraint(mR2StateSpace, nullptr, mLowerLimits, mUpperLimits); });
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_constructor_RNGIsNull_DoesNotThrow)
{
EXPECT_NO_THROW(
{ RnBoxConstraint(mRxStateSpace, nullptr, mLowerLimits, mUpperLimits); });
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, R2_constructor_LowersLimitExceedsUpperLimits_Throws)
{
Eigen::Vector2d badLowerLimits(1., 0.);
Eigen::Vector2d badUpperLimits(0., 1.);
EXPECT_THROW(
{
R2BoxConstraint(
mR2StateSpace, mRng->clone(), badLowerLimits, badUpperLimits);
},
std::invalid_argument);
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, Rx_constructor_LowersLimitExceedsUpperLimits_Throws)
{
Eigen::Vector2d badLowerLimits(1., 0.);
Eigen::Vector2d badUpperLimits(0., 1.);
EXPECT_THROW(
{
RnBoxConstraint(
mRxStateSpace, mRng->clone(), badLowerLimits, badUpperLimits);
},
std::invalid_argument);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_getStateSpace)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
EXPECT_EQ(mR2StateSpace, constraint.getStateSpace());
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_getStateSpace)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
EXPECT_EQ(mRxStateSpace, constraint.getStateSpace());
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_getConstraintDimension)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
EXPECT_EQ(2, constraint.getConstraintDimension());
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_getConstraintDimension)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
EXPECT_EQ(2, constraint.getConstraintDimension());
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_getConstraintTypes)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto constraintTypes = constraint.getConstraintTypes();
ASSERT_EQ(2, constraintTypes.size());
EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[0]);
EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[1]);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_getConstraintTypes)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto constraintTypes = constraint.getConstraintTypes();
ASSERT_EQ(2, constraintTypes.size());
EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[0]);
EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[1]);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_isSatisfied_SatisfiesConstraint_ReturnsTrue)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
EXPECT_TRUE(constraint.isSatisfied(state));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_isSatisfied_SatisfiesConstraint_ReturnsTrue)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
EXPECT_TRUE(constraint.isSatisfied(state));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, R2_isSatisfied_DoesNotSatisfyConstraint_ReturnsFalse)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
EXPECT_FALSE(constraint.isSatisfied(state));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, Rx_isSatisfied_DoesNotSatisfyConstraint_ReturnsFalse)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
EXPECT_FALSE(constraint.isSatisfied(state));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_project_SatisfiesConstraint_DoesNothing)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto inState = mR2StateSpace->createState();
auto outState = mR2StateSpace->createState();
for (const auto& value : mGoodValues)
{
inState.setValue(value);
EXPECT_TRUE(constraint.project(inState, outState));
EXPECT_TRUE(value.isApprox(outState.getValue()));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_project_SatisfiesConstraint_DoesNothing)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto inState = mRxStateSpace->createState();
auto outState = mRxStateSpace->createState();
for (const auto& value : mGoodValues)
{
inState.setValue(value);
EXPECT_TRUE(constraint.project(inState, outState));
EXPECT_TRUE(value.isApprox(outState.getValue()));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_project_DoesNotSatisfyConstraint_Projects)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto inState = mR2StateSpace->createState();
auto outState = mR2StateSpace->createState();
for (const auto& value : mBadValues)
{
inState.setValue(value);
EXPECT_TRUE(constraint.project(inState, outState));
EXPECT_TRUE(constraint.isSatisfied(outState));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_project_DoesNotSatisfyConstraint_Projects)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto inState = mRxStateSpace->createState();
auto outState = mRxStateSpace->createState();
for (const auto& value : mBadValues)
{
inState.setValue(value);
EXPECT_TRUE(constraint.project(inState, outState));
EXPECT_TRUE(constraint.isSatisfied(outState));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_getValue_SatisfiesConstraint_ReturnsZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
constraint.getValue(state, constraintValue);
EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_getValue_SatisfiesConstraint_ReturnsZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
constraint.getValue(state, constraintValue);
EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, R2_getValue_DoesNotSatisfyConstraint_ReturnsNonZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
// TODO: Check the sign.
// TODO: Check which elements are non-zero.
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
constraint.getValue(state, constraintValue);
EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests, Rx_getValue_DoesNotSatisfyConstraint_ReturnsNonZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
// TODO: Check the sign.
// TODO: Check which elements are non-zero.
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
constraint.getValue(state, constraintValue);
EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_getJacobian_SatisfiesConstraint_ReturnsZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::MatrixXd jacobian;
constraint.getJacobian(state, jacobian);
EXPECT_TRUE(Matrix2d::Zero().isApprox(jacobian));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_getJacobian_SatisfiesConstraint_ReturnsZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::MatrixXd jacobian;
constraint.getJacobian(state, jacobian);
EXPECT_TRUE(Matrix2d::Zero().isApprox(jacobian));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
R2_getJacobian_DoesNotSatisfyConstraint_ReturnsNonZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
// TODO: Check the sign.
// TODO: Check which elements are non-zero.
auto state = mR2StateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::MatrixXd jacobian;
constraint.getJacobian(state, jacobian);
EXPECT_FALSE(Matrix2d::Zero().isApprox(jacobian));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
Rx_getJacobian_DoesNotSatisfyConstraint_ReturnsNonZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
// TODO: Check the sign.
// TODO: Check which elements are non-zero.
auto state = mRxStateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::MatrixXd jacobian;
constraint.getJacobian(state, jacobian);
EXPECT_FALSE(Matrix2d::Zero().isApprox(jacobian));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
R2_getValueAndJacobian_SatisfiesConstraint_ReturnsZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
Eigen::MatrixXd constraintJac;
constraint.getValueAndJacobian(state, constraintValue, constraintJac);
EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue));
EXPECT_TRUE(Matrix2d::Zero().isApprox(constraintJac));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
Rx_getValueAndJacobian_SatisfiesConstraint_ReturnsZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mGoodValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
Eigen::MatrixXd constraintJac;
constraint.getValueAndJacobian(state, constraintValue, constraintJac);
EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue));
EXPECT_TRUE(Matrix2d::Zero().isApprox(constraintJac));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
R2_getValueAndJacobian_DoesNotSatisfyConstraint_ReturnsNonZero)
{
R2BoxConstraint constraint(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mR2StateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
Eigen::MatrixXd constraintJac;
constraint.getValueAndJacobian(state, constraintValue, constraintJac);
EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue));
EXPECT_FALSE(Matrix2d::Zero().isApprox(constraintJac));
}
}
//==============================================================================
TEST_F(
RnBoxConstraintTests,
Rx_getValueAndJacobian_DoesNotSatisfyConstraint_ReturnsNonZero)
{
RnBoxConstraint constraint(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto state = mRxStateSpace->createState();
for (const auto& value : mBadValues)
{
state.setValue(value);
Eigen::VectorXd constraintValue;
Eigen::MatrixXd constraintJac;
constraint.getValueAndJacobian(state, constraintValue, constraintJac);
EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue));
EXPECT_FALSE(Matrix2d::Zero().isApprox(constraintJac));
}
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_createSampleGenerator)
{
auto constraint = dart::common::make_aligned_shared<R2BoxConstraint>(
mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto generator = constraint->createSampleGenerator();
EXPECT_EQ(mR2StateSpace, generator->getStateSpace());
auto result = SampleGeneratorCoverage(
*generator,
*mR2Distance,
std::begin(mTargets),
std::end(mTargets),
DISTANCE_THRESHOLD,
NUM_SAMPLES);
ASSERT_TRUE(result);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator)
{
auto constraint = std::make_shared<RnBoxConstraint>(
mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits);
auto generator = constraint->createSampleGenerator();
EXPECT_EQ(mRxStateSpace, generator->getStateSpace());
auto result = SampleGeneratorCoverage(
*generator,
*mRxDistance,
std::begin(mTargets),
std::end(mTargets),
DISTANCE_THRESHOLD,
NUM_SAMPLES);
ASSERT_TRUE(result);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_createSampleGenerator_RNGIsNull_Throws)
{
// We need to use make_shared here because createSampleGenerator calls
// shared_from_this, provided by enable_shared_from_this.
auto constraint = dart::common::make_aligned_shared<R2BoxConstraint>(
mR2StateSpace, nullptr, mLowerLimits, mUpperLimits);
EXPECT_THROW({ constraint->createSampleGenerator(); }, std::invalid_argument);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator_RNGIsNull_Throws)
{
// We need to use make_shared here because createSampleGenerator calls
// shared_from_this, provided by enable_shared_from_this.
auto constraint = std::make_shared<RnBoxConstraint>(
mRxStateSpace, nullptr, mLowerLimits, mUpperLimits);
EXPECT_THROW({ constraint->createSampleGenerator(); }, std::invalid_argument);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, R2_createSampleGenerator_Unbounded_Throws)
{
Vector2d noLowerBound = mLowerLimits;
noLowerBound[0] = -std::numeric_limits<double>::infinity();
Vector2d noUpperBound = mUpperLimits;
noUpperBound[1] = std::numeric_limits<double>::infinity();
// We need to use make_shared here because createSampleGenerator calls
// shared_from_this, provided by enable_shared_from_this.
auto unbounded1 = dart::common::make_aligned_shared<R2BoxConstraint>(
mR2StateSpace, mRng->clone(), noLowerBound, mUpperLimits);
EXPECT_THROW({ unbounded1->createSampleGenerator(); }, std::runtime_error);
auto unbounded2 = dart::common::make_aligned_shared<R2BoxConstraint>(
mR2StateSpace, mRng->clone(), mLowerLimits, noUpperBound);
EXPECT_THROW({ unbounded2->createSampleGenerator(); }, std::runtime_error);
}
//==============================================================================
TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator_Unbounded_Throws)
{
Vector2d noLowerBound = mLowerLimits;
noLowerBound[0] = -std::numeric_limits<double>::infinity();
Vector2d noUpperBound = mUpperLimits;
noUpperBound[1] = std::numeric_limits<double>::infinity();
// We need to use make_shared here because createSampleGenerator calls
// shared_from_this, provided by enable_shared_from_this.
auto unbounded1 = std::make_shared<RnBoxConstraint>(
mRxStateSpace, mRng->clone(), noLowerBound, mUpperLimits);
EXPECT_THROW({ unbounded1->createSampleGenerator(); }, std::runtime_error);
auto unbounded2 = std::make_shared<RnBoxConstraint>(
mRxStateSpace, mRng->clone(), mLowerLimits, noUpperBound);
EXPECT_THROW({ unbounded2->createSampleGenerator(); }, std::runtime_error);
}
| 31.730935 | 80 | 0.635378 |
ae706494abacc4054ca1c640a0e4f4f245f031c0 | 17,359 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include <Elastos.CoreLibrary.Utility.h>
#include "Elastos.Droid.Accounts.h"
#include "Elastos.Droid.App.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.Droid.Location.h"
#include "Elastos.Droid.Widget.h"
#include "elastos/droid/os/NullVibrator.h"
#include "elastos/droid/view/InputDevice.h"
#include "elastos/droid/view/CKeyCharacterMap.h"
#include "elastos/droid/view/MotionEvent.h"
#include "elastos/droid/hardware/input/CInputManager.h"
#include "elastos/droid/hardware/input/CInputDeviceIdentifier.h"
#include "elastos/droid/hardware/input/CInputManagerHelper.h"
#include <elastos/core/AutoLock.h>
using Elastos::Core::AutoLock;
using Elastos::Utility::CArrayList;
using Elastos::Droid::Os::NullVibrator;
using Elastos::Droid::Hardware::Input::CInputManager;
using Elastos::Droid::Hardware::Input::CInputDeviceIdentifier;
using Elastos::Droid::Hardware::Input::IInputManagerHelper;
using Elastos::Droid::Hardware::Input::CInputManagerHelper;
using Elastos::Droid::Hardware::Input::IInputManager;
namespace Elastos {
namespace Droid {
namespace View {
CAR_INTERFACE_IMPL(InputDevice::MotionRange, Object, IMotionRange)
CAR_INTERFACE_IMPL_2(InputDevice, Object, IInputDevice, IParcelable)
InputDevice::MotionRange::MotionRange(
/* [in] */ Int32 axis,
/* [in] */ Int32 source,
/* [in] */ Float min,
/* [in] */ Float max,
/* [in] */ Float flat,
/* [in] */ Float fuzz,
/* [in] */ Float resolution)
: mAxis(axis)
, mSource(source)
, mMin(min)
, mMax(max)
, mFlat(flat)
, mFuzz(fuzz)
, mResolution(resolution)
{
}
ECode InputDevice::MotionRange::GetAxis(
/* [out] */ Int32* axis)
{
VALIDATE_NOT_NULL(axis)
*axis = mAxis;
return NOERROR;
}
ECode InputDevice::MotionRange::GetSource(
/* [out] */ Int32* source)
{
VALIDATE_NOT_NULL(source)
*source = mSource;
return NOERROR;
}
ECode InputDevice::MotionRange::IsFromSource(
/* [in] */ Int32 source,
/* [out] */ Boolean* rst)
{
VALIDATE_NOT_NULL(rst)
*rst = (mSource & source) == source;
return NOERROR;
}
ECode InputDevice::MotionRange::GetMin(
/* [out] */ Float* minimum)
{
VALIDATE_NOT_NULL(minimum);
*minimum = mMin;
return NOERROR;
}
ECode InputDevice::MotionRange::GetMax(
/* [out] */ Float* maximum)
{
VALIDATE_NOT_NULL(maximum);
*maximum = mMax;
return NOERROR;
}
ECode InputDevice::MotionRange::GetRange(
/* [out] */ Float* range)
{
VALIDATE_NOT_NULL(range);
*range = mMax - mMin;
return NOERROR;
}
ECode InputDevice::MotionRange::GetFlat(
/* [out] */ Float* flat)
{
VALIDATE_NOT_NULL(flat);
*flat = mFlat;
return NOERROR;
}
ECode InputDevice::MotionRange::GetFuzz(
/* [out] */ Float* fuzz)
{
VALIDATE_NOT_NULL(fuzz);
*fuzz = mFuzz;
return NOERROR;
}
ECode InputDevice::MotionRange::GetResolution(
/* [out] */ Float* resolution)
{
VALIDATE_NOT_NULL(resolution);
*resolution = mResolution;
return NOERROR;
}
InputDevice::InputDevice()
: mId(0)
, mGeneration(0)
, mControllerNumber(0)
, mVendorId(0)
, mProductId(0)
, mIsExternal(FALSE)
, mSources(0)
, mKeyboardType(0)
, mHasVibrator(FALSE)
, mHasButtonUnderPad(FALSE)
{
}
InputDevice::~InputDevice()
{
}
ECode InputDevice::constructor()
{
CArrayList::New((IArrayList**)&mMotionRanges);
return NOERROR;
}
ECode InputDevice::constructor(
/* [in] */ Int32 id,
/* [in] */ Int32 generation,
/* [in] */ Int32 controllerNumber,
/* [in] */ const String& name,
/* [in] */ Int32 vendorId,
/* [in] */ Int32 productId,
/* [in] */ const String& descriptor,
/* [in] */ Boolean isExternal,
/* [in] */ Int32 sources,
/* [in] */ Int32 keyboardType,
/* [in] */ IKeyCharacterMap* keyCharacterMap,
/* [in] */ Boolean hasVibrator,
/* [in] */ Boolean hasButtonUnderPad)
{
CArrayList::New((IArrayList**)&mMotionRanges);
mId = id;
mGeneration = generation;
mControllerNumber = controllerNumber;
mName = name;
mVendorId = vendorId;
mProductId = productId;
mDescriptor = descriptor;
mIsExternal = isExternal;
mSources = sources;
mKeyboardType = keyboardType;
mKeyCharacterMap = keyCharacterMap;
mHasVibrator = hasVibrator;
mHasButtonUnderPad = hasButtonUnderPad;
CInputDeviceIdentifier::New(descriptor, vendorId, productId, (IInputDeviceIdentifier**)&mIdentifier);
return NOERROR;
}
ECode InputDevice::GetDevice(
/* [in] */ Int32 id,
/* [out] */ IInputDevice** device)
{
return CInputManager::GetInstance()->GetInputDevice(id, device);
}
ECode InputDevice::GetDeviceIds(
/* [out, callee] */ ArrayOf<Int32>** deviceIds)
{
return CInputManager::GetInstance()->GetInputDeviceIds(deviceIds);
}
ECode InputDevice::GetId(
/* [out] */ Int32* id)
{
VALIDATE_NOT_NULL(id);
*id = mId;
return NOERROR;
}
ECode InputDevice::GetControllerNumber(
/* [out] */ Int32* number)
{
VALIDATE_NOT_NULL(number)
*number = mControllerNumber;
return NOERROR;
}
ECode InputDevice::GetIdentifier(
/* [out] */ IInputDeviceIdentifier** identifier)
{
VALIDATE_NOT_NULL(identifier)
*identifier = mIdentifier;
REFCOUNT_ADD(*identifier)
return NOERROR;
}
ECode InputDevice::GetGeneration(
/* [out] */ Int32* generation)
{
VALIDATE_NOT_NULL(generation);
*generation = mGeneration;
return NOERROR;
}
ECode InputDevice::GetVendorId(
/* [out] */ Int32* id)
{
VALIDATE_NOT_NULL(id)
*id = mVendorId;
return NOERROR;
}
ECode InputDevice::GetProductId(
/* [out] */ Int32* id)
{
VALIDATE_NOT_NULL(id)
*id = mProductId;
return NOERROR;
}
ECode InputDevice::GetDescriptor(
/* [out] */ String* descriptor)
{
VALIDATE_NOT_NULL(descriptor);
*descriptor = mDescriptor;
return NOERROR;
}
ECode InputDevice::IsVirtual(
/* [out] */ Boolean* isVirtual)
{
VALIDATE_NOT_NULL(isVirtual);
*isVirtual = mId < 0;
return NOERROR;
}
ECode InputDevice::IsExternal(
/* [out] */ Boolean* isExternal)
{
VALIDATE_NOT_NULL(isExternal);
*isExternal = mIsExternal;
return NOERROR;
}
ECode InputDevice::IsFullKeyboard(
/* [out] */ Boolean* isFullKeyboard)
{
VALIDATE_NOT_NULL(isFullKeyboard);
*isFullKeyboard = (mSources & SOURCE_KEYBOARD) == SOURCE_KEYBOARD
&& mKeyboardType == KEYBOARD_TYPE_ALPHABETIC;
return NOERROR;
}
ECode InputDevice::GetName(
/* [out] */ String* name)
{
VALIDATE_NOT_NULL(name);
*name = mName;
return NOERROR;
}
ECode InputDevice::GetSources(
/* [out] */ Int32* sources)
{
VALIDATE_NOT_NULL(sources);
*sources = mSources;
return NOERROR;
}
ECode InputDevice::SupportsSource(
/* [in] */ Int32 source,
/* [out] */ Boolean* rst)
{
VALIDATE_NOT_NULL(rst);
*rst = (mSources & source) == source;
return NOERROR;
}
ECode InputDevice::GetKeyboardType(
/* [out] */ Int32* type)
{
VALIDATE_NOT_NULL(type);
*type = mKeyboardType;
return NOERROR;
}
ECode InputDevice::GetKeyCharacterMap(
/* [out] */ IKeyCharacterMap** keyCharacterMap)
{
VALIDATE_NOT_NULL(keyCharacterMap);
*keyCharacterMap = mKeyCharacterMap;
REFCOUNT_ADD(*keyCharacterMap);
return NOERROR;
}
ECode InputDevice::GetHasVibrator(
/* [out] */ Boolean* hasVibrator)
{
VALIDATE_NOT_NULL(hasVibrator)
*hasVibrator = mHasVibrator;
return NOERROR;
}
ECode InputDevice::GetHasButtonUnderPad(
/* [out] */ Boolean* hasButtonUnderPad)
{
VALIDATE_NOT_NULL(hasButtonUnderPad)
*hasButtonUnderPad = mHasButtonUnderPad;
return NOERROR;
}
ECode InputDevice::HasKeys(
/* [in] */ ArrayOf<Int32>* keys,
/* [out, calleee] */ ArrayOf<Boolean>** rsts)
{
VALIDATE_NOT_NULL(rsts)
AutoPtr<IInputManagerHelper> helper;
CInputManagerHelper::AcquireSingleton((IInputManagerHelper**)&helper);
AutoPtr<IInputManager> manager;
helper->GetInstance((IInputManager**)&manager);
AutoPtr<ArrayOf<Int32> > param = ArrayOf<Int32>::Alloc(keys->GetLength() + 1);
param->Set(0, mId);
param->Copy(1, keys);
return manager->DeviceHasKeys(*param, rsts);
}
ECode InputDevice::GetMotionRange(
/* [in] */ Int32 axis,
/* [out] */ IMotionRange** montionRange)
{
VALIDATE_NOT_NULL(montionRange);
Int32 size;
mMotionRanges->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> tmp;
mMotionRanges->Get(i, (IInterface**)&tmp);
AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp);
MotionRange* range = (MotionRange*)(rangeItf.Get());
if (range->mAxis == axis) {
*montionRange = range;
REFCOUNT_ADD(*montionRange);
return NOERROR;
}
}
*montionRange = NULL;
return NOERROR;
}
ECode InputDevice::GetMotionRange(
/* [in] */ Int32 axis,
/* [in] */ Int32 source,
/* [out] */ IMotionRange** montionRange)
{
VALIDATE_NOT_NULL(montionRange);
Int32 size;
mMotionRanges->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> tmp;
mMotionRanges->Get(i, (IInterface**)&tmp);
AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp);
MotionRange* range = (MotionRange*)(rangeItf.Get());
if (range->mAxis == axis && range->mSource == source) {
*montionRange = range;
REFCOUNT_ADD(*montionRange);
return NOERROR;
}
}
*montionRange = NULL;
return NOERROR;
}
ECode InputDevice::GetMotionRanges(
/* [out] */ IList** motionRanges)
{
VALIDATE_NOT_NULL(motionRanges);
*motionRanges = IList::Probe(mMotionRanges);
REFCOUNT_ADD(*motionRanges)
return NOERROR;
}
ECode InputDevice::AddMotionRange(
/* [in] */ Int32 axis,
/* [in] */ Int32 source,
/* [in] */ Float min,
/* [in] */ Float max,
/* [in] */ Float flat,
/* [in] */ Float fuzz,
/* [in] */ Float resolution)
{
AutoPtr<MotionRange> range = new MotionRange(axis, source, min, max, flat, fuzz, resolution);
mMotionRanges->Add((IMotionRange*)range.Get());
return NOERROR;
}
ECode InputDevice::GetVibrator(
/* [out] */ IVibrator** vibrator)
{
VALIDATE_NOT_NULL(vibrator);
ISynchronize* sync = ISynchronize::Probe(mMotionRanges);
AutoLock lock(sync);
if (mVibrator == NULL) {
if (mHasVibrator) {
CInputManager::GetInstance()->GetInputDeviceVibrator(
mId, (IVibrator**)&mVibrator);
}
else {
mVibrator = (IVibrator*)NullVibrator::GetInstance().Get();
}
}
*vibrator = mVibrator;
REFCOUNT_ADD(*vibrator);
return NOERROR;
}
ECode InputDevice::HasButtonUnderPad(
/* [in] */ Boolean* rst)
{
VALIDATE_NOT_NULL(rst)
*rst = mHasButtonUnderPad;
return NOERROR;
}
ECode InputDevice::ReadFromParcel(
/* [in] */ IParcel* in)
{
in->ReadInt32(&mId);
in->ReadInt32(&mGeneration);
in->ReadInt32(&mControllerNumber);
in->ReadString(&mName);
in->ReadInt32(&mVendorId);
in->ReadInt32(&mProductId);
in->ReadString(&mDescriptor);
in->ReadBoolean(&mIsExternal);
in->ReadInt32(&mSources);
in->ReadInt32(&mKeyboardType);
CKeyCharacterMap::New((IKeyCharacterMap**)&mKeyCharacterMap);
IParcelable::Probe(mKeyCharacterMap)->ReadFromParcel(in);
in->ReadBoolean(&mHasVibrator);
in->ReadBoolean(&mHasButtonUnderPad);
CInputDeviceIdentifier::New(mDescriptor, mVendorId, mProductId, (IInputDeviceIdentifier**)&mIdentifier);
Int32 size;
in->ReadInt32(&size);
for (Int32 i = 0; i < size; ++i) {
Int32 axis, source;
Float min, max, flat, fuzz, resolution;
in->ReadInt32(&axis);
in->ReadInt32(&source);
in->ReadFloat(&min);
in->ReadFloat(&max);
in->ReadFloat(&flat);
in->ReadFloat(&fuzz);
in->ReadFloat(&resolution);
AddMotionRange(axis, source, min, max, flat, fuzz, resolution);
}
return NOERROR;
}
ECode InputDevice::WriteToParcel(
/* [in] */ IParcel* out)
{
out->WriteInt32(mId);
out->WriteInt32(mGeneration);
out->WriteInt32(mControllerNumber);
out->WriteString(mName);
out->WriteInt32(mVendorId);
out->WriteInt32(mProductId);
out->WriteString(mDescriptor);
out->WriteBoolean(mIsExternal);
out->WriteInt32(mSources);
out->WriteInt32(mKeyboardType);
IParcelable::Probe(mKeyCharacterMap)->WriteToParcel(out);
out->WriteBoolean(mHasVibrator);
out->WriteBoolean(mHasButtonUnderPad);
Int32 size;
mMotionRanges->GetSize(&size);
out->WriteInt32(size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> tmp;
mMotionRanges->Get(i, (IInterface**)&tmp);
AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp);
MotionRange* range = (MotionRange*)(rangeItf.Get());
assert(range != NULL);
out->WriteInt32(range->mAxis);
out->WriteInt32(range->mSource);
out->WriteFloat(range->mMin);
out->WriteFloat(range->mMax);
out->WriteFloat(range->mFlat);
out->WriteFloat(range->mFuzz);
out->WriteFloat(range->mResolution);
}
return NOERROR;
}
ECode InputDevice::ToString(
/* [out] */ String* str)
{
VALIDATE_NOT_NULL(str)
StringBuilder description;
((((description += "Input Device ") += mId) += ": ") += mName) += "\n";
((description += " Descriptor: ") += mDescriptor) += "\n";
((description += " Generation: ") += " Generation: ") += "\n";
((description += " Generation: ") += mGeneration) += "\n";
((description += " Location: ") += mIsExternal ? "external" : "built-in") += "\n";
description += " Keyboard Type: ";
switch (mKeyboardType) {
case IInputDevice::KEYBOARD_TYPE_NONE:
description += "none";
break;
case IInputDevice::KEYBOARD_TYPE_NON_ALPHABETIC:
description += "non-alphabetic";
break;
case IInputDevice::KEYBOARD_TYPE_ALPHABETIC:
description += "alphabetic";
break;
}
description += "\n";
((description += " Has Vibrator: ") += " Has Vibrator: ") += "\n";
((description += " Sources: 0x") += StringUtils::ToString(mSources, 16)) += " (";
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_KEYBOARD, String("keyboard"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_DPAD, String("dpad"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TOUCHSCREEN, String("touchscreen"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_MOUSE, String("mouse"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_STYLUS, String("stylus"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TRACKBALL, String("trackball"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TOUCHPAD, String("touchpad"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_JOYSTICK, String("joystick"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_GAMEPAD, String("gamepad"));
AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_GESTURE_SENSOR, String("gesture"));
description += " )\n";
Int32 size;
mMotionRanges->GetSize(&size);
for (Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> tmp;
mMotionRanges->Get(i, (IInterface**)&tmp);
AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp);
MotionRange* range = (MotionRange*)(rangeItf.Get());
(description += " ") += MotionEvent::AxisToString(range->mAxis);
(description += ": source=0x") += StringUtils::ToString(range->mSource, 16);
(description += " min=") += range->mMin;
(description += " max=") += range->mMax;
(description += " flat=") += range->mFlat;
(description += " fuzz=") += range->mFuzz;
(description += " resolution=") += range->mResolution;
description += "\n";
}
*str = description.ToString();
return NOERROR;
}
ECode InputDevice::AppendSourceDescriptionIfApplicable(
/* [in] */ StringBuilder& description,
/* [in] */ Int32 source,
/* [in] */ const String& sourceName)
{
if ((mSources & source) == source) {
description += " ";
description += sourceName;
}
return NOERROR;
}
} //namespace View
} //namespace Droid
} //namespace Elastos
| 27.953301 | 110 | 0.645832 |
ae71a4ef975ed4a1f28cc8068cf32da4b32e4d2b | 3,722 | hpp | C++ | src/mge/core/GameObject.hpp | mtesseracttech/CustomEngine | 1a9ed564408ae29fe49681a810b851403d71f486 | [
"Apache-2.0"
] | null | null | null | src/mge/core/GameObject.hpp | mtesseracttech/CustomEngine | 1a9ed564408ae29fe49681a810b851403d71f486 | [
"Apache-2.0"
] | null | null | null | src/mge/core/GameObject.hpp | mtesseracttech/CustomEngine | 1a9ed564408ae29fe49681a810b851403d71f486 | [
"Apache-2.0"
] | null | null | null | #ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <vector>
#include <string>
#include <iostream>
#include <glm/glm.hpp>
#include "LinearMath/btDefaultMotionState.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletDynamics/Vehicle/btRaycastVehicle.h"
class RigidBody;
class AbstractBehaviour;
class AbstractMaterial;
class World;
class Mesh;
/**
* A GameObject wraps all data required to display an (interactive / dynamic) object, but knows nothing about OpenGL or rendering.
* You will need to alter this class to add colliders etc.
*/
class GameObject
{
public:
GameObject(std::string pName = NULL, glm::vec3 pPosition = glm::vec3(0.0f, 0.0f, 0.0f));
virtual ~GameObject();
void setName(std::string pName);
std::string getName() const;
//contains local rotation, scale, position
const glm::mat4& getTransform() const;
void setTransform(const glm::mat4& pTransform);
//access just the local position
glm::vec3 getLocalPosition() const;
glm::quat getLocalRotation() const;
glm::quat getLocalRotationSlow() const;
void setLocalPosition(const glm::vec3 pPosition);
void setLocalRotation(const glm::quat rotation);
glm::vec3 getTransformRight() const;
glm::vec3 getTransformUp() const;
glm::vec3 getTransformForward() const;
void setTransformForward(glm::vec3 fwd);
//get the objects world position by combining transforms
//expensive operations!! Improvement would be to cache these transforms!
glm::vec3 getWorldPosition() const;
glm::quat getWorldRotation() const;
glm::mat4 getWorldTransform() const;
glm::vec3 getWorldTransformRight() const;
glm::vec3 getWorldTransformUp() const;
glm::vec3 getWorldTransformForward() const;
//change local position, rotation, scaling
void translate(glm::vec3 pTranslation);
void rotate(float pAngle, glm::vec3 pAxis);
//DO NOT USE IN FINAL GAME, ROTATION FUNCTIONS MAKE GAMEOBJECT LOSE SCALE!
void scale(glm::vec3 pScale);
//mesh and material should be shared as much as possible
void setMesh(Mesh* pMesh);
Mesh* getMesh() const;
void setMaterial(AbstractMaterial* pMaterial);
AbstractMaterial* getMaterial() const;
btDefaultMotionState* getDefaultMotionState() const;
void setRigidBody(btCollisionShape* shape, float mass, btDynamicsWorld* world);
void setMeshRigidBody(btDynamicsWorld* world);
RigidBody* getRigidBody() const;
void removeRigidBody() const;
virtual void update(float pStep);
void AddBehaviour(AbstractBehaviour* behaviour);
void RemoveBehaviour(AbstractBehaviour* behaviour);
void ClearBehaviours();
void DeleteBehaviours();
//child management
//shortcut to set the parent of pChild to ourselves
void add(GameObject* pChild);
//shortcut to set the parent of pChild to NULL
void remove(GameObject* pChild);
virtual void setParent(GameObject* pGameObject);
GameObject* getParent();
int getChildCount();
GameObject* getChildAt(int pIndex);
void enableDebugging();
void printDebug();
void deleteObject(const GameObject* pObject);
//light
void AdjustPosition();
virtual void OnCollision(const btCollisionObject* other);
protected:
std::string _name;
glm::mat4 _transform;
GameObject* _parent;
std::vector<GameObject*> _children;
Mesh* _mesh;
AbstractMaterial* _material;
RigidBody* _rigidBody;
btDefaultMotionState* _defaultMotionState;
std::vector<AbstractBehaviour*> _behaviours;
//update children list administration
void _innerAdd(GameObject* pChild);
void _innerRemove(GameObject* pChild);
private:
GameObject(const GameObject&);
GameObject& operator=(const GameObject&);
bool _debug;
glm::mat4 floatToMat4(float* Pmatrix);
};
#endif // GAMEOBJECT_H
| 29.776 | 129 | 0.754164 |
ae72d619789f6f135889a6b73e3309bce505c65c | 783 | cc | C++ | examples/cli-subcommands/greetings.cc | jfjlaros/userIO | 21e32a80ed3c652fb983780de0936a1aaec67b0c | [
"MIT"
] | 2 | 2021-11-09T11:25:55.000Z | 2021-12-08T18:47:53.000Z | examples/cli-subcommands/greetings.cc | jfjlaros/commandIO | 21e32a80ed3c652fb983780de0936a1aaec67b0c | [
"MIT"
] | null | null | null | examples/cli-subcommands/greetings.cc | jfjlaros/commandIO | 21e32a80ed3c652fb983780de0936a1aaec67b0c | [
"MIT"
] | null | null | null | /*
* Example CLI interface for multiple functions.
*/
#include <commandIO.h>
string hi(bool shout) {
if (shout) {
return "HELLO WORLD!";
}
return "Hello world.";
}
string greet(string name) {
return "Hello " + name + ".";
}
string flood(string name, int times) {
string greeting = "";
int i;
for (i = 0; i < times; i++) {
greeting += "Hi " + name + ".\n";
}
return greeting;
}
int main(int argc, char** argv) {
CliIO io(argc, argv);
interface(
io,
func(hi, "hi", "simple greeting",
param("-s", false, "shout")),
func(greet, "greet", "personal greeting",
param("name", "name")),
func(flood, "flood", "multiple personal greetings",
param("name", "name"),
param("-n", 1, "multiplier")));
return 0;
}
| 17.021739 | 55 | 0.563218 |
ae74218f8cb2aabee96af40c71347623f1a9343e | 945 | cpp | C++ | C++/Maximum Element/Solution.cpp | chessmastersan/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 2 | 2019-08-07T19:58:20.000Z | 2019-08-27T00:06:09.000Z | C++/Maximum Element/Solution.cpp | chessmastersan/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 1 | 2020-06-11T19:09:48.000Z | 2020-06-11T19:09:48.000Z | C++/Maximum Element/Solution.cpp | chessmastersan/HackerRank | 850319e6f79e7473afbb847d28edde7b2cdfc37d | [
"MIT"
] | 7 | 2019-08-27T00:06:11.000Z | 2021-12-11T10:01:45.000Z | /**
* @author SANKALP SAXENA
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
long int n, i=1, ch, item, top=-1;
scanf("%ld",&n);
long int stack[n];
for(i=1; i<=n; i++)
{
scanf("%ld",&ch);
switch(ch)
{
case 1: scanf("%ld",&item);
stack[++(top)] = item;
break;
case 2:
stack[(top)--];
break;
case 3: long int i=0, max=stack[0];
for( ; i<=top ; i++)
{
if(stack[i] > max)
max = stack[i];
}
printf("%ld\n", max);
}
}
return 0;
}
| 21 | 80 | 0.373545 |
ae7ad77f8d25919d3349cddc6fd908c972de005b | 13,697 | cpp | C++ | sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | null | null | null | sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | null | null | null | sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp | Sasha7b9Work/S8-53M2 | fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Program: wxWidgets Widgets Sample
// Name: gauge.cpp
// Purpose: Part of the widgets sample showing wxGauge
// Author: Vadim Zeitlin
// Created: 27.03.01
// Copyright: (c) 2001 Vadim Zeitlin
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/timer.h"
#include "wx/bitmap.h"
#include "wx/button.h"
#include "wx/checkbox.h"
#include "wx/combobox.h"
#include "wx/gauge.h"
#include "wx/radiobox.h"
#include "wx/statbox.h"
#include "wx/textctrl.h"
#endif
#include "wx/sizer.h"
#include "widgets.h"
#if wxUSE_GAUGE
#include "icons/gauge.xpm"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// control ids
enum
{
GaugePage_Reset = wxID_HIGHEST,
GaugePage_Progress,
GaugePage_IndeterminateProgress,
GaugePage_Clear,
GaugePage_SetValue,
GaugePage_SetRange,
GaugePage_CurValueText,
GaugePage_ValueText,
GaugePage_RangeText,
GaugePage_Timer,
GaugePage_IndeterminateTimer,
GaugePage_Gauge
};
// ----------------------------------------------------------------------------
// GaugeWidgetsPage
// ----------------------------------------------------------------------------
class GaugeWidgetsPage : public WidgetsPage
{
public:
GaugeWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist);
virtual ~GaugeWidgetsPage();
virtual wxWindow *GetWidget() const wxOVERRIDE { return m_gauge; }
virtual void RecreateWidget() wxOVERRIDE { CreateGauge(); }
// lazy creation of the content
virtual void CreateContent() wxOVERRIDE;
protected:
// event handlers
void OnButtonReset(wxCommandEvent& event);
void OnButtonProgress(wxCommandEvent& event);
void OnButtonIndeterminateProgress(wxCommandEvent& event);
void OnButtonClear(wxCommandEvent& event);
void OnButtonSetValue(wxCommandEvent& event);
void OnButtonSetRange(wxCommandEvent& event);
void OnCheckOrRadioBox(wxCommandEvent& event);
void OnUpdateUIValueButton(wxUpdateUIEvent& event);
void OnUpdateUIRangeButton(wxUpdateUIEvent& event);
void OnUpdateUIResetButton(wxUpdateUIEvent& event);
void OnUpdateUICurValueText(wxUpdateUIEvent& event);
void OnProgressTimer(wxTimerEvent& event);
void OnIndeterminateProgressTimer(wxTimerEvent& event);
// reset the gauge parameters
void Reset();
// (re)create the gauge
void CreateGauge();
// start progress timer
void StartTimer(wxButton*);
// stop the progress timer
void StopTimer(wxButton*);
// the gauge range
unsigned long m_range;
// the controls
// ------------
// the checkboxes for styles
wxCheckBox *m_chkVert,
*m_chkSmooth,
*m_chkProgress;
// the gauge itself and the sizer it is in
wxGauge *m_gauge;
wxSizer *m_sizerGauge;
// the text entries for set value/range
wxTextCtrl *m_textValue,
*m_textRange;
// the timer for simulating gauge progress
wxTimer *m_timer;
private:
wxDECLARE_EVENT_TABLE();
DECLARE_WIDGETS_PAGE(GaugeWidgetsPage)
};
// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(GaugeWidgetsPage, WidgetsPage)
EVT_BUTTON(GaugePage_Reset, GaugeWidgetsPage::OnButtonReset)
EVT_BUTTON(GaugePage_Progress, GaugeWidgetsPage::OnButtonProgress)
EVT_BUTTON(GaugePage_IndeterminateProgress, GaugeWidgetsPage::OnButtonIndeterminateProgress)
EVT_BUTTON(GaugePage_Clear, GaugeWidgetsPage::OnButtonClear)
EVT_BUTTON(GaugePage_SetValue, GaugeWidgetsPage::OnButtonSetValue)
EVT_BUTTON(GaugePage_SetRange, GaugeWidgetsPage::OnButtonSetRange)
EVT_UPDATE_UI(GaugePage_SetValue, GaugeWidgetsPage::OnUpdateUIValueButton)
EVT_UPDATE_UI(GaugePage_SetRange, GaugeWidgetsPage::OnUpdateUIRangeButton)
EVT_UPDATE_UI(GaugePage_Reset, GaugeWidgetsPage::OnUpdateUIResetButton)
EVT_UPDATE_UI(GaugePage_CurValueText, GaugeWidgetsPage::OnUpdateUICurValueText)
EVT_CHECKBOX(wxID_ANY, GaugeWidgetsPage::OnCheckOrRadioBox)
EVT_RADIOBOX(wxID_ANY, GaugeWidgetsPage::OnCheckOrRadioBox)
EVT_TIMER(GaugePage_Timer, GaugeWidgetsPage::OnProgressTimer)
EVT_TIMER(GaugePage_IndeterminateTimer, GaugeWidgetsPage::OnIndeterminateProgressTimer)
wxEND_EVENT_TABLE()
// ============================================================================
// implementation
// ============================================================================
#if defined(__WXUNIVERSAL__)
#define FAMILY_CTRLS UNIVERSAL_CTRLS
#else
#define FAMILY_CTRLS NATIVE_CTRLS
#endif
IMPLEMENT_WIDGETS_PAGE(GaugeWidgetsPage, "Gauge", FAMILY_CTRLS );
GaugeWidgetsPage::GaugeWidgetsPage(WidgetsBookCtrl *book,
wxImageList *imaglist)
:WidgetsPage(book, imaglist, gauge_xpm)
{
// init everything
m_range = 100;
m_timer = (wxTimer *)NULL;
m_chkVert =
m_chkSmooth =
m_chkProgress = (wxCheckBox *)NULL;
m_gauge = (wxGauge *)NULL;
m_sizerGauge = (wxSizer *)NULL;
}
void GaugeWidgetsPage::CreateContent()
{
wxSizer *sizerTop = new wxBoxSizer(wxHORIZONTAL);
// left pane
wxStaticBox *box = new wxStaticBox(this, wxID_ANY, "&Set style");
wxSizer *sizerLeft = new wxStaticBoxSizer(box, wxVERTICAL);
m_chkVert = CreateCheckBoxAndAddToSizer(sizerLeft, "&Vertical");
m_chkSmooth = CreateCheckBoxAndAddToSizer(sizerLeft, "&Smooth");
m_chkProgress = CreateCheckBoxAndAddToSizer(sizerLeft, "&Progress");
sizerLeft->Add(5, 5, 0, wxGROW | wxALL, 5); // spacer
wxButton *btn = new wxButton(this, GaugePage_Reset, "&Reset");
sizerLeft->Add(btn, 0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 15);
// middle pane
wxStaticBox *box2 = new wxStaticBox(this, wxID_ANY, "&Change gauge value");
wxSizer *sizerMiddle = new wxStaticBoxSizer(box2, wxVERTICAL);
wxTextCtrl *text;
wxSizer *sizerRow = CreateSizerWithTextAndLabel("Current value",
GaugePage_CurValueText,
&text);
text->SetEditable(false);
sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5);
sizerRow = CreateSizerWithTextAndButton(GaugePage_SetValue,
"Set &value",
GaugePage_ValueText,
&m_textValue);
sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5);
sizerRow = CreateSizerWithTextAndButton(GaugePage_SetRange,
"Set &range",
GaugePage_RangeText,
&m_textRange);
m_textRange->SetValue( wxString::Format("%lu", m_range) );
sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5);
btn = new wxButton(this, GaugePage_Progress, "Simulate &progress");
sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5);
btn = new wxButton(this, GaugePage_IndeterminateProgress,
"Simulate &indeterminate job");
sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5);
btn = new wxButton(this, GaugePage_Clear, "&Clear");
sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5);
// right pane
wxSizer *sizerRight = new wxBoxSizer(wxHORIZONTAL);
m_gauge = new wxGauge(this, GaugePage_Gauge, m_range);
sizerRight->Add(m_gauge, 1, wxCENTRE | wxALL, 5);
sizerRight->SetMinSize(150, 0);
m_sizerGauge = sizerRight; // save it to modify it later
// the 3 panes panes compose the window
sizerTop->Add(sizerLeft, 0, wxGROW | (wxALL & ~wxLEFT), 10);
sizerTop->Add(sizerMiddle, 1, wxGROW | wxALL, 10);
sizerTop->Add(sizerRight, 1, wxGROW | (wxALL & ~wxRIGHT), 10);
// final initializations
Reset();
SetSizer(sizerTop);
}
GaugeWidgetsPage::~GaugeWidgetsPage()
{
delete m_timer;
}
// ----------------------------------------------------------------------------
// operations
// ----------------------------------------------------------------------------
void GaugeWidgetsPage::Reset()
{
m_chkVert->SetValue(false);
m_chkSmooth->SetValue(false);
m_chkProgress->SetValue(false);
}
void GaugeWidgetsPage::CreateGauge()
{
int flags = GetAttrs().m_defaultFlags;
if ( m_chkVert->GetValue() )
flags |= wxGA_VERTICAL;
else
flags |= wxGA_HORIZONTAL;
if ( m_chkSmooth->GetValue() )
flags |= wxGA_SMOOTH;
if ( m_chkProgress->GetValue() )
flags |= wxGA_PROGRESS;
int val = 0;
if ( m_gauge )
{
val = m_gauge->GetValue();
m_sizerGauge->Detach( m_gauge );
delete m_gauge;
}
m_gauge = new wxGauge(this, GaugePage_Gauge, m_range,
wxDefaultPosition, wxDefaultSize,
flags);
m_gauge->SetValue(val);
if ( flags & wxGA_VERTICAL )
m_sizerGauge->Add(m_gauge, 0, wxGROW | wxALL, 5);
else
m_sizerGauge->Add(m_gauge, 1, wxCENTRE | wxALL, 5);
m_sizerGauge->Layout();
}
void GaugeWidgetsPage::StartTimer(wxButton *clicked)
{
static const int INTERVAL = 300;
wxLogMessage("Launched progress timer (interval = %d ms)", INTERVAL);
m_timer = new wxTimer(this,
clicked->GetId() == GaugePage_Progress ? GaugePage_Timer : GaugePage_IndeterminateTimer);
m_timer->Start(INTERVAL);
clicked->SetLabel("&Stop timer");
if (clicked->GetId() == GaugePage_Progress)
FindWindow(GaugePage_IndeterminateProgress)->Disable();
else
FindWindow(GaugePage_Progress)->Disable();
}
void GaugeWidgetsPage::StopTimer(wxButton *clicked)
{
wxCHECK_RET( m_timer, "shouldn't be called" );
m_timer->Stop();
wxDELETE(m_timer);
if (clicked->GetId() == GaugePage_Progress)
{
clicked->SetLabel("Simulate &progress");
FindWindow(GaugePage_IndeterminateProgress)->Enable();
}
else
{
clicked->SetLabel("Simulate indeterminate job");
FindWindow(GaugePage_Progress)->Enable();
}
wxLogMessage("Progress finished.");
}
// ----------------------------------------------------------------------------
// event handlers
// ----------------------------------------------------------------------------
void GaugeWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event))
{
Reset();
CreateGauge();
}
void GaugeWidgetsPage::OnButtonProgress(wxCommandEvent& event)
{
wxButton *b = (wxButton *)event.GetEventObject();
if ( !m_timer )
{
StartTimer(b);
}
else // stop the running timer
{
StopTimer(b);
wxLogMessage("Stopped the timer.");
}
}
void GaugeWidgetsPage::OnButtonIndeterminateProgress(wxCommandEvent& event)
{
wxButton *b = (wxButton *)event.GetEventObject();
if ( !m_timer )
{
StartTimer(b);
}
else // stop the running timer
{
StopTimer(b);
m_gauge->SetValue(0);
wxLogMessage("Stopped the timer.");
}
}
void GaugeWidgetsPage::OnButtonClear(wxCommandEvent& WXUNUSED(event))
{
m_gauge->SetValue(0);
}
void GaugeWidgetsPage::OnButtonSetRange(wxCommandEvent& WXUNUSED(event))
{
unsigned long val;
if ( !m_textRange->GetValue().ToULong(&val) )
return;
m_range = val;
m_gauge->SetRange(val);
}
void GaugeWidgetsPage::OnButtonSetValue(wxCommandEvent& WXUNUSED(event))
{
unsigned long val;
if ( !m_textValue->GetValue().ToULong(&val) )
return;
m_gauge->SetValue(val);
}
void GaugeWidgetsPage::OnUpdateUIValueButton(wxUpdateUIEvent& event)
{
unsigned long val;
event.Enable( m_textValue->GetValue().ToULong(&val) && (val <= m_range) );
}
void GaugeWidgetsPage::OnUpdateUIRangeButton(wxUpdateUIEvent& event)
{
unsigned long val;
event.Enable( m_textRange->GetValue().ToULong(&val) );
}
void GaugeWidgetsPage::OnUpdateUIResetButton(wxUpdateUIEvent& event)
{
event.Enable( m_chkVert->GetValue() || m_chkSmooth->GetValue() ||
m_chkProgress->GetValue() );
}
void GaugeWidgetsPage::OnCheckOrRadioBox(wxCommandEvent& WXUNUSED(event))
{
CreateGauge();
}
void GaugeWidgetsPage::OnProgressTimer(wxTimerEvent& WXUNUSED(event))
{
int val = m_gauge->GetValue();
if ( (unsigned)val < m_range )
{
m_gauge->SetValue(val + 1);
}
else // reached the end
{
wxButton *btn = (wxButton *)FindWindow(GaugePage_Progress);
wxCHECK_RET( btn, "no progress button?" );
StopTimer(btn);
}
}
void GaugeWidgetsPage::OnIndeterminateProgressTimer(wxTimerEvent& WXUNUSED(event))
{
m_gauge->Pulse();
}
void GaugeWidgetsPage::OnUpdateUICurValueText(wxUpdateUIEvent& event)
{
event.SetText( wxString::Format("%d", m_gauge->GetValue()));
}
#endif
// wxUSE_GAUGE
| 28.835789 | 97 | 0.599036 |
ae814fd9c69ec00895489e21e847958a7a75a14d | 410 | cc | C++ | poj/2/2591.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/2/2591.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/2/2591.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main(void)
{
static const int N = 10000000;
vector<int> v(N);
int a = 0, b = 0;
v[0] = 1;
for (int i = 1; i < N; i++) {
int x = min(2*v[a]+1, 3*v[b]+1);
if (x == 2*v[a]+1) {
a++;
}
if (x == 3*v[b]+1) {
b++;
}
v[i] = x;
}
int n;
while (cin >> n) {
cout << v[n-1] << endl;
}
return 0;
}
| 14.642857 | 36 | 0.429268 |
ae81c922341310210d05bf5ccbe9a368b12e9ce0 | 1,086 | hpp | C++ | function/codeFunction.hpp | TaylorP/TML | e4c0c7ce69645a1cf30df005af786a15f85b54a2 | [
"MIT"
] | 4 | 2015-12-17T21:58:27.000Z | 2019-10-31T16:50:41.000Z | function/codeFunction.hpp | TaylorP/TML | e4c0c7ce69645a1cf30df005af786a15f85b54a2 | [
"MIT"
] | null | null | null | function/codeFunction.hpp | TaylorP/TML | e4c0c7ce69645a1cf30df005af786a15f85b54a2 | [
"MIT"
] | 1 | 2019-05-07T18:51:00.000Z | 2019-05-07T18:51:00.000Z | #ifndef CODE_FUNCTION_HPP
#define CODE_FUNCTION_HPP
#include "function/function.hpp"
#include "exception/functionException.hpp"
/// Function for full width code blocks
class CodeFunction : public Function
{
public:
/// Constructs a new code function
CodeFunction(const bool pFilter)
: Function(pFilter)
{
}
/// Emits a full width code block to the stream
virtual void emit(std::ostream& pStream,
const std::vector<std::string>& pInput) const
{
// Validate parameter count
if (pInput.size() != 2)
{
throw(FunctionException("@code",
"Function expects exactly 2 parameters"));
}
// Print the pre tag, including the linenums and language class
pStream << "<pre class='prettyprint linenums " << pInput[0] << "'>";
newline(pStream);
// Print the code
pStream << pInput[1];
newline(pStream);
// Close the pre tag
pStream << "</pre>";
newline(pStream);
}
};
#endif
| 25.255814 | 78 | 0.577348 |
ae857cf2e59e794dc8dcefaa309ac2c647a69b70 | 840 | cpp | C++ | Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp | MrWpGg/Durna | 62c8ca2d69623e70e2dac49a5560cd3ac2c304ed | [
"Apache-2.0"
] | null | null | null | Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp | MrWpGg/Durna | 62c8ca2d69623e70e2dac49a5560cd3ac2c304ed | [
"Apache-2.0"
] | null | null | null | Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp | MrWpGg/Durna | 62c8ca2d69623e70e2dac49a5560cd3ac2c304ed | [
"Apache-2.0"
] | null | null | null | #include "DurnaPCH.h"
#include "OpenGLContext.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <gl/GL.h>
namespace Durna
{
OpenGLContext::OpenGLContext(GLFWwindow* InWindowHandle)
: WindowHandle(InWindowHandle)
{
DRN_ASSERT(WindowHandle, "WindowHandle is null!")
}
void OpenGLContext::Init()
{
DRN_PROFILE_FUNCTION();
glfwMakeContextCurrent(WindowHandle);
int Status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
DRN_ASSERT(Status, "Failed to init glad!");
LOG_TRACE(LOGCAT_GL, "initialized");
LOG_TRACE(LOGCAT_GL, "Vendor: {0}", glGetString(GL_VENDOR));
LOG_TRACE(LOGCAT_GL, "Renderer: {0}", glGetString(GL_RENDERER));
LOG_TRACE(LOGCAT_GL, "Version: {0}", glGetString(GL_VERSION));
}
void OpenGLContext::SwapBuffers()
{
DRN_PROFILE_FUNCTION();
glfwSwapBuffers(WindowHandle);
}
}
| 21.538462 | 66 | 0.736905 |
ae8a84f1881c8f25d27c1cb296519ae738c84b22 | 2,627 | cpp | C++ | src/network/vector_write.cpp | mpbarnwell/lightstep-tracer-cpp | 4f8f110e7b69d1b8d24c9ea130cd560295e479b6 | [
"MIT"
] | 47 | 2016-05-23T10:39:50.000Z | 2022-03-08T08:46:25.000Z | src/network/vector_write.cpp | mpbarnwell/lightstep-tracer-cpp | 4f8f110e7b69d1b8d24c9ea130cd560295e479b6 | [
"MIT"
] | 63 | 2016-07-26T00:02:09.000Z | 2022-03-11T07:20:44.000Z | src/network/vector_write.cpp | mpbarnwell/lightstep-tracer-cpp | 4f8f110e7b69d1b8d24c9ea130cd560295e479b6 | [
"MIT"
] | 19 | 2016-09-21T17:59:03.000Z | 2021-09-16T06:42:40.000Z | #include "network/vector_write.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <climits>
#include <cstring>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include "common/platform/error.h"
#include "common/platform/memory.h"
#include "common/platform/network.h"
namespace lightstep {
//--------------------------------------------------------------------------------------------------
// Write
//--------------------------------------------------------------------------------------------------
bool Write(int socket,
std::initializer_list<FragmentInputStream*> fragment_input_streams) {
int num_fragments = 0;
for (auto fragment_input_stream : fragment_input_streams) {
num_fragments += fragment_input_stream->num_fragments();
}
if (num_fragments == 0) {
return true;
}
const auto max_batch_size =
std::min(static_cast<int>(IoVecMax), num_fragments);
auto fragments = static_cast<IoVec*>(alloca(sizeof(IoVec) * max_batch_size));
auto fragment_iter = fragments;
const auto fragment_last = fragments + max_batch_size;
int num_bytes_written = 0;
int batch_num_bytes = 0;
bool error = false;
bool blocked = false;
ErrorCode error_code;
auto do_write = [&]() noexcept {
auto rcode =
WriteV(socket, fragments,
static_cast<int>(std::distance(fragments, fragment_iter)));
if (rcode < 0) {
error_code = GetLastErrorCode();
if (IsBlockingErrorCode(error_code)) {
blocked = true;
} else {
error = true;
}
return;
}
auto num_batch_bytes_written = static_cast<int>(rcode);
assert(num_batch_bytes_written <= batch_num_bytes);
num_bytes_written += num_batch_bytes_written;
if (num_batch_bytes_written < batch_num_bytes) {
blocked = true;
}
};
auto do_fragment = [&](void* data, int size) noexcept {
*fragment_iter++ = MakeIoVec(data, static_cast<size_t>(size));
batch_num_bytes += size;
if (fragment_iter != fragment_last) {
return true;
}
do_write();
fragment_iter = fragments;
batch_num_bytes = 0;
return !(error || blocked);
};
for (auto fragment_input_stream : fragment_input_streams) {
if (!fragment_input_stream->ForEachFragment(do_fragment)) {
break;
}
}
if (batch_num_bytes > 0) {
do_write();
}
auto result = Consume(fragment_input_streams, num_bytes_written);
if (error) {
std::ostringstream oss;
oss << "writev failed: " << GetErrorCodeMessage(error_code);
throw std::runtime_error{oss.str()};
}
return result;
}
} // namespace lightstep
| 29.852273 | 100 | 0.625809 |
ae8d05d82a6f88cc465c3192a18107f3ee98669a | 1,326 | cpp | C++ | aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.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/cognito-idp/model/SetUserMFAPreferenceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CognitoIdentityProvider::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
SetUserMFAPreferenceRequest::SetUserMFAPreferenceRequest() :
m_sMSMfaSettingsHasBeenSet(false),
m_softwareTokenMfaSettingsHasBeenSet(false),
m_accessTokenHasBeenSet(false)
{
}
Aws::String SetUserMFAPreferenceRequest::SerializePayload() const
{
JsonValue payload;
if(m_sMSMfaSettingsHasBeenSet)
{
payload.WithObject("SMSMfaSettings", m_sMSMfaSettings.Jsonize());
}
if(m_softwareTokenMfaSettingsHasBeenSet)
{
payload.WithObject("SoftwareTokenMfaSettings", m_softwareTokenMfaSettings.Jsonize());
}
if(m_accessTokenHasBeenSet)
{
payload.WithString("AccessToken", m_accessToken);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection SetUserMFAPreferenceRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.SetUserMFAPreference"));
return headers;
}
| 22.862069 | 119 | 0.775264 |