blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2c1bc68157902874007fe7c6e4d07a0dde433d4e | 2c6a29560e7012032fbb81ab717fa04f2905caaf | /proyecto/compiler/src/main.cpp | c99e300fdbec774701fb149c8fd5743a955bfec6 | [] | no_license | Erick-ECE/ArquitecturaDeComputadoras | aeac77745d0bba7fe5b617101fb81e109329a1af | de2de9d473a14f0ccc1b80a64aca8fc2da749381 | refs/heads/master | 2020-03-22T04:04:37.890519 | 2018-07-02T17:15:13 | 2018-07-02T17:15:13 | 139,471,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | int main(int argc, char *argv[]) {
++argv; --argc;
if(argc != 2){
cout << "Invalid parameters. Usage\nsasm <filename> <output>" << endl;
return 127;
} else {
yyin = fopen(argv[0], "r");
if(yyin == NULL){
cerr << "Error, assembly file not found" << endl;
return 126;
}
}
yylex();
if(lexer_stop){
cerr << "Compilation halted due to lexical analysis errors" << endl;
return 1;
} else {
AsmParser parser(tokens);
parser.start();
if(parser.parseErrors()){
cerr << "Compilation halted due to syntax analysis errors" << endl;
return 2;
}
if(parser.semantErrors()){
cerr << "Compilation halted due to semantic analysis errors" << endl;
return 3;
}
deque<StrEntry> strings = parser.stringTable();
deque<ProcEntry> procedures = parser.procTable();
deque<Instr> code = parser.codeGenerated();
deque<int> deferred = parser.deferredInstructions();
deque<char*> deferredid = parser.deferredIds();
AsmCodeGen cg(code, deferred, deferredid,
procedures, strings,
parser.codeSize());
cg.compile(argv[1]);
if(cg.codeGenErrors()){
cerr << "Compilation halted due to code generation errors" << endl;
return 4;
} else {
cerr << "File succesfully compiled to: " << argv[1] << endl;
return 0;
}
}
}
| [
"ericken15@ciencias.unam.mx"
] | ericken15@ciencias.unam.mx |
312b9ffb447a0825c761764bbfe1fc060d74537a | 454497aab9fb97d44477565476f9de7374ca16f7 | /Prob4_1/Prob4_1/method.cpp | 49057da8df3f86964ff2aecd87f7e9d4466f1305 | [] | no_license | duddn14758/SummerAlg | ea08f91c6de12c7fb5a594cb26cc01a43bc03559 | 08df19b88c75037a5812942cee6502c75a7f3218 | refs/heads/master | 2020-03-22T09:13:40.733338 | 2018-07-31T17:39:30 | 2018-07-31T17:39:30 | 139,823,974 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 3,340 | cpp | #include <stdlib.h>
#include <stdio.h>
#include "method.h"
int *MakeArry(int N) {
int *arr;
arr = (int*)malloc(sizeof(int)*N);
for (int i = 0; i < N; i++)
arr[i] = rand() % N;
return arr;
}
int *MakeReverse(int N) {
int *arr;
arr = (int*)malloc(sizeof(int)*N);
for (int i = 0; i < N; i++)
arr[i] = N - i;
return arr;
}
int *Bubble(int *arr, int N) {
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
return arr;
}
int *Selection(int *arr, int N) {
int M_index = 0;
while (N > 0) {
M_index = 0;
for (int i = 0; i < N; i++) {
if (arr[i] > arr[M_index])
M_index = i;
}
swap(arr[--N], arr[M_index]);
}
return arr;
}
int *Insertion(int *arr, int N) {
int tmp;
for (int i = 1; i < N; i++) {
if (arr[i - 1] > arr[i]) {
tmp = arr[i];
int j = i;
while (--j >= 0) {
if (arr[j] > tmp)
swap(arr[j], arr[j + 1]);
}
}
}
return arr;
}
int *Merge(int *arr, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
Merge(arr, p, q);
Merge(arr, q + 1, r);
return merging(arr, p, q, r);
}
return arr;
}
int* merging(int *arr, int p, int q, int r) {
int origin = p;
int i = 0, j = 0;
int* arr1 = (int*)malloc(sizeof(int)*(q - p + 1));
int *arr2 = (int*)malloc(sizeof(int)*(r - q));
arr1 = copying(arr, arr1, p, q);
arr2 = copying(arr, arr2, q + 1, r);
while (i<=q-p&&j<= r-q-1) {
if (arr1[i] < arr2[j]) {
arr[origin++] = arr1[i++];
}
else if (arr1[i] >= arr2[j]) {
arr[origin++] = arr2[j++];
}
}
while (i <= q-p) {
arr[origin++] = arr1[i++];
}
while (j <= r-q-1) {
arr[origin++] = arr2[j++];
}
free(arr1);
free(arr2);
return arr;
}
int *copyarr(int *arr, int h, int t) {
int *cpyarr;
int point = 0;
cpyarr = (int*)malloc(sizeof(int)*(h - t + 1));
printf("%d부터 %d까지 복사된배열\n", h,t);
while (h <= t) {
printf("%d\n", arr[h]);
cpyarr[point++] = arr[h++];
}
return cpyarr;
}
int *copying(int *arr, int *cpyarr, int h, int t) {
int point = 0;
while (h <= t) {
cpyarr[point++] = arr[h++];
}
return cpyarr;
}
int *Quick1(int *arr, int p, int r) {
if (p < r) {
int q = partition(arr, p, r);
Quick1(arr, p, q-1);
Quick1(arr, q + 1, r);
return arr;
}
return arr;
}
int partition(int *arr, int p, int r) {
int pivot = arr[r];
int i = r, j = r;
while (--j >= p) {
if (arr[j] > pivot) {
int tmp = arr[j];
for (int k = j; k < i; k++) {
arr[k] = arr[k + 1];
}
arr[i--] = tmp;
}
}
return i;
}
int *Quick2(int *arr, int p, int r) {
if (p < r) {
partition2(arr, p, r);
int q = partition(arr, p, r-1);
Quick2(arr, p, q-1);
Quick2(arr, q + 1, r);
return arr;
}
return arr;
}
void partition2(int *arr, int p, int r) {
int q = (p + r) / 2;
if (arr[p] > arr[q]) {
swap(arr[p], arr[q]);
}
if (arr[q] > arr[r]) {
swap(arr[q], arr[r]);
}
if (arr[p] > arr[r]) {
swap(arr[q], arr[r]);
}
swap(arr[q], arr[r-1]);
}
int *Quick3(int *arr, int p, int r) {
if (p < r) {
partition3(arr, p, r);
int q = partition(arr, p, r);
Quick3(arr, p, q - 1);
Quick3(arr, q + 1, r);
return arr;
}
return arr;
}
void partition3(int *arr, int p, int r) {
int random = rand()%(r-p);
swap(arr[p + random], arr[r]);
}
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
| [
"duddn14758@naver.com"
] | duddn14758@naver.com |
737b1d14d8b0b865477678d70e07716adbfa8534 | d124275f227ee6fa02a9340f4adfb546d54bd88d | /week-2-rational/tests.cpp | 9dfcef7d19ae062c621a5e6c45c7d6df4b903931 | [] | no_license | nicoverduin/v1oopc-examples | 96070ae5f5a8bc820bf92280d3dee7d637d62626 | 44e944acc409ea9d4d5a13dad58fbf435fddd7e9 | refs/heads/master | 2023-04-13T19:36:17.604146 | 2021-04-21T07:59:15 | 2021-04-21T07:59:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,361 | cpp | #include "catch.hpp"
#include "ostream"
#include "sstream"
#include "rational.hpp"
TEST_CASE( "constructor, two_parameters" ){
rational v( 3, 4 );
std::stringstream s;
s << v;
REQUIRE( s.str() == "[3/4]" );
}
TEST_CASE( "equality, equal" ){
rational v( 1, 2 );
REQUIRE( v == rational( 1, 2 ) );
}
TEST_CASE( "equality, unequal" ){
rational v( 1, 2 );
REQUIRE( ! ( v == rational( 1, 3 )) );
}
TEST_CASE( "constructor, two_parameters; reduction" ){
rational v( 10, 2 );
REQUIRE( v == rational( 5, 1 ) );
}
TEST_CASE( "constructor, one parameter" ){
rational v( 6 );
REQUIRE( v == rational( 6, 1 ) );
}
TEST_CASE( "multiply by integer" ){
rational v( 3, 4 );
rational x = v * 7;
REQUIRE( v == rational( 3, 4 ) );
REQUIRE( x == rational( 21, 4 ) );
}
TEST_CASE( "multiply by integer; reduction" ){
rational v( 3, 10 );
rational x = v * 5;
REQUIRE( v == rational( 3, 10 ) );
REQUIRE( x == rational( 3, 2 ) );
}
TEST_CASE( "multiply by rational" ){
rational v( 3, 4 );
rational x = v * rational( 9, 7 );
REQUIRE( v == rational( 3, 4 ) );
REQUIRE( x == rational( 27, 28 ) );
}
TEST_CASE( "multiply by rational; reduction" ){
rational v( 3, 10 );
rational x = v * rational( 4, 6 );
REQUIRE( v == rational( 3, 10 ) );
REQUIRE( x == rational( 1, 5 ) );
}
TEST_CASE( "add rational into rational" ){
rational v( 3, 10 );
v += rational( 6, 7 );
REQUIRE( v == rational( 81, 70 ) );
}
TEST_CASE( "add rational into rational; reduction" ){
rational v( 23, 147 );
v += rational( 5, 91 );
REQUIRE( v == rational( 404, 1911 ) );
}
TEST_CASE( "add rational into rational; return value" ){
rational v( 1, 2 );
rational x = ( v += rational( 1, 4 ));
REQUIRE( v == rational( 3, 4 ) );
REQUIRE( x == rational( 3, 4 ) );
}
TEST_CASE( "multiply rational into rational" ){
rational v( 3, 10 );
v *= rational( 1, 2 );
REQUIRE( v == rational( 3, 20 ) );
}
TEST_CASE( "multiply rational into rational; reduction" ){
rational v( 2, 3 );
v *= rational( 3, 2 );
REQUIRE( v == rational( 1, 1 ) );
}
TEST_CASE( "multiply rational into rational; return value" ){
rational v( 3, 10 );
rational x = ( v *= rational( 1, 2 ));
REQUIRE( x == rational( 3, 20 ) );
}
| [
"wouter@voti.nl"
] | wouter@voti.nl |
706165bc84c690ac70e6343598f5ceeb346bcf01 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/ds/adsi/nwnds/ndsufree.cxx | ba567167a3b0c765acedcca44740281c8a6d21ab | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,661 | cxx | /+---------------------------------------------------------------------------
//
// Microsoft Windows
// Freeright (C) Microsoft Corporation, 1992 - 1995.
//
// File: ndsufree.cxx
//
// Contents:
//
// Functions:
//
// FreeABC1ToNDSSynId1
// FreeABC2ToNDSSynId2
// FreeABC3ToNDSSynId3
// FreeABC4ToNDSSynId4
// FreeABC5ToNDSSynId5
// FreeABC6ToNDSSynId6
// FreeABC7ToNDSSynId7
// FreeABC8ToNDSSynId8
// FreeABC9ToNDSSynId9
// FreeABC10ToNDSSynId10
// FreeABC11ToNDSSynId11
// FreeABC12ToNDSSynId12
// FreeABC13ToNDSSynId13
// FreeABC14ToNDSSynId14
// FreeABC15ToNDSSynId15
// FreeABC16ToNDSSynId16
// FreeABC17ToNDSSynId17
// FreeABC18ToNDSSynId18
// FreeABC19ToNDSSynId19
// FreeABC20ToNDSSynId20
// FreeABC21ToNDSSynId21
// FreeABC22ToNDSSynId22
// FreeABC23ToNDSSynId23
// FreeABC24ToNDSSynId24
// FreeABC25ToNDSSynId25
// FreeABC26ToNDSSynId26
// FreeABC27ToNDSSynId27
//
// History: 15-Jul-97 FelixW Created.
//
//----------------------------------------------------------------------------
#include "nds.hxx"
LPBYTE
FreeNDSSynId1ToNDS1(
LPBYTE lpByte
)
{
LPASN1_TYPE_1 lpASN1_1 = (LPASN1_TYPE_1) lpByte;
if (lpASN1_1->DNString) {
FreeADsStr(lpASN1_1->DNString);
}
lpByte = (LPBYTE ) lpASN1_1 + sizeof(ASN1_TYPE_1);
return(lpByte);
}
LPBYTE
FreeNDSSynId2ToNDS2(
LPBYTE lpByte
)
{
LPASN1_TYPE_2 lpASN1_2 = (LPASN1_TYPE_2) lpByte;
if (lpASN1_2->CaseExactString) {
FreeADsStr(lpASN1_2->CaseExactString);
}
lpByte = (LPBYTE ) lpASN1_2 + sizeof(ASN1_TYPE_2);
return(lpByte);
}
LPBYTE
FreeNDSSynId3ToNDS3(
LPBYTE lpByte
)
{
LPASN1_TYPE_3 lpASN1_3 = (LPASN1_TYPE_3) lpByte;
if (lpASN1_3->CaseIgnoreString) {
FreeADsStr(lpASN1_3->CaseIgnoreString);
}
lpByte = (LPBYTE ) lpASN1_3 + sizeof(ASN1_TYPE_3);
return(lpByte);
}
LPBYTE
FreeNDSSynId4ToNDS4(
LPBYTE lpByte
)
{
LPASN1_TYPE_4 lpASN1_4 = (LPASN1_TYPE_4) lpByte;
if (lpASN1_4->PrintableString) {
FreeADsStr(lpASN1_4->PrintableString);
}
lpByte = (LPBYTE ) lpASN1_4 + sizeof(ASN1_TYPE_4);
return(lpByte);
}
LPBYTE
FreeNDSSynId5ToNDS5(
LPBYTE lpByte
)
{
LPASN1_TYPE_5 lpASN1_5 = (LPASN1_TYPE_5) lpByte;
if (lpASN1_5->NumericString) {
FreeADsStr(lpASN1_5->NumericString);
}
lpByte = (LPBYTE ) lpASN1_5 + sizeof(ASN1_TYPE_5);
return(lpByte);
}
LPBYTE
FreeNDSSynId6ToNDS6(
LPBYTE lpByte
)
{
LPASN1_TYPE_6 lpASN1_6 = (LPASN1_TYPE_6) lpByte;
if (lpASN1_6->String) {
FreeADsStr(lpASN1_6->String);
}
while (lpASN1_6->Next)
{
if (lpASN1_6->String) {
FreeADsStr(lpASN1_6->String);
}
lpASN1_6 = (LPASN1_TYPE_6)lpASN1_6->Next;
}
lpByte = (LPBYTE ) lpASN1_6 + sizeof(ASN1_TYPE_6);
return(lpByte);
}
LPBYTE
FreeNDSSynId7ToNDS7(
LPBYTE lpByte
)
{
LPASN1_TYPE_8 lpASN1_8 = (LPASN1_TYPE_8) lpByte;
lpByte = (LPBYTE ) lpASN1_8 + sizeof(ASN1_TYPE_8);
return(lpByte);
}
LPBYTE
FreeNDSSynId8ToNDS8(
LPBYTE lpByte
)
{
LPASN1_TYPE_8 lpASN1_8 = (LPASN1_TYPE_8) lpByte;
lpByte = (LPBYTE ) lpASN1_8 + sizeof(ASN1_TYPE_8);
return(lpByte);
}
LPBYTE
FreeNDSSynId9ToNDS9(
LPBYTE lpByte
)
{
LPASN1_TYPE_9 lpASN1_9 = (LPASN1_TYPE_9) lpByte;
if (lpASN1_9->OctetString) {
FreeADsMem((LPBYTE)lpASN1_9->OctetString);
}
lpByte = (LPBYTE ) lpASN1_9 + sizeof(ASN1_TYPE_9);
return(lpByte);
}
LPBYTE
FreeNDSSynId10ToNDS10(
LPBYTE lpByte
)
{
LPASN1_TYPE_10 lpASN1_10 = (LPASN1_TYPE_10) lpByte;
if (lpASN1_10->TelephoneNumber) {
FreeADsStr(lpASN1_10->TelephoneNumber);
}
lpByte = (LPBYTE ) lpASN1_10 + sizeof(ASN1_TYPE_10);
return(lpByte);
}
LPBYTE
FreeNDSSynId11ToNDS11(
LPBYTE lpByte
)
{
LPASN1_TYPE_11 lpASN1_11 = (LPASN1_TYPE_11) lpByte;
if (lpASN1_11->TelephoneNumber) {
FreeADsStr(lpASN1_11->TelephoneNumber);
}
lpByte = (LPBYTE ) lpASN1_11 + sizeof(ASN1_TYPE_11);
return(lpByte);
}
LPBYTE
FreeNDSSynId12ToNDS12(
LPBYTE lpByte
)
{
LPASN1_TYPE_12 lpASN1_12 = (LPASN1_TYPE_12) lpByte;
if (lpASN1_12->Address) {
FreeADsMem((LPBYTE)lpASN1_12->Address);
}
lpByte = (LPBYTE ) lpASN1_12 + sizeof(ASN1_TYPE_12);
return(lpByte);
}
LPBYTE
FreeNDSSynId13ToNDS13(
LPBYTE lpByte
)
{
//
// BugBug: KrishnaG not supported!
//
return(lpByte);
}
LPBYTE
FreeNDSSynId14ToNDS14(
LPBYTE lpByte
)
{
LPASN1_TYPE_14 lpASN1_14 = (LPASN1_TYPE_14) lpByte;
if (lpASN1_14->Address) {
FreeADsStr(lpASN1_14->Address);
}
lpByte = (LPBYTE ) lpASN1_14 + sizeof(ASN1_TYPE_14);
return(lpByte);
}
LPBYTE
FreeNDSSynId15ToNDS15(
LPBYTE lpByte
)
{
LPASN1_TYPE_15 lpASN1_15 = (LPASN1_TYPE_15) lpByte;
if (lpASN1_15->VolumeName) {
FreeADsStr(lpASN1_15->VolumeName);
}
if (lpASN1_15->Path) {
FreeADsStr(lpASN1_15->Path);
}
lpByte = (LPBYTE ) lpASN1_15 + sizeof(ASN1_TYPE_15);
return(lpByte);
}
LPBYTE
FreeNDSSynId16ToNDS16(
LPBYTE lpByte
)
{
//
// BugBug: KrishnaG not supported!
//
return(lpByte);
}
LPBYTE
FreeNDSSynId17ToNDS17(
LPBYTE lpByte
)
{
LPASN1_TYPE_17 lpASN1_17 = (LPASN1_TYPE_17) lpByte;
if (lpASN1_17->ProtectedAttrName) {
FreeADsStr(lpASN1_17->ProtectedAttrName);
}
if (lpASN1_17->SubjectName) {
FreeADsStr(lpASN1_17->SubjectName);
}
lpByte = (LPBYTE ) lpASN1_17 + sizeof(ASN1_TYPE_17);
return(lpByte);
}
LPBYTE
FreeNDSSynId18ToNDS18(
LPBYTE lpByte
)
{
LPASN1_TYPE_18 lpASN1_18 = (LPASN1_TYPE_18) lpByte;
if (lpASN1_18->PostalAddress[0]) {
FreeADsStr(lpASN1_18->PostalAddress[0]);
}
if (lpASN1_18->PostalAddress[1]) {
FreeADsStr(lpASN1_18->PostalAddress[1]);
}
if (lpASN1_18->PostalAddress[2]) {
FreeADsStr(lpASN1_18->PostalAddress[2]);
}
if (lpASN1_18->PostalAddress[3]) {
FreeADsStr(lpASN1_18->PostalAddress[3]);
}
if (lpASN1_18->PostalAddress[4]) {
FreeADsStr(lpASN1_18->PostalAddress[4]);
}
if (lpASN1_18->PostalAddress[5]) {
FreeADsStr(lpASN1_18->PostalAddress[5]);
}
lpByte = (LPBYTE ) lpASN1_18 + sizeof(ASN1_TYPE_18);
return(lpByte);
}
LPBYTE
FreeNDSSynId19ToNDS19(
LPBYTE lpByte
)
{
//
// BugBug: KrishnaG not supported!
//
return(lpByte);
LPASN1_TYPE_19 lpASN1_19 = (LPASN1_TYPE_19) lpByte;
lpByte = (LPBYTE ) lpASN1_19 + sizeof(ASN1_TYPE_19);
return(lpByte);
}
LPBYTE
FreeNDSSynId20ToNDS20(
LPBYTE lpByte
)
{
LPASN1_TYPE_20 lpASN1_20 = (LPASN1_TYPE_20) lpByte;
if (lpASN1_20->ClassName) {
FreeADsStr(lpASN1_20->ClassName);
}
lpByte = (LPBYTE ) lpASN1_20 + sizeof(ASN1_TYPE_20);
return(lpByte);
}
LPBYTE
FreeNDSSynId21ToNDS21(
LPBYTE lpByte
)
{
LPASN1_TYPE_21 lpASN1_21 = (LPASN1_TYPE_21) lpByte;
//
// The Length value is supposedly always zero!!
//
lpByte = (LPBYTE ) lpASN1_21 + sizeof(ASN1_TYPE_21);
return(lpByte);
}
LPBYTE
FreeNDSSynId22ToNDS22(
LPBYTE lpByte
)
{
LPASN1_TYPE_22 lpASN1_22 = (LPASN1_TYPE_22) lpByte;
lpByte = (LPBYTE ) lpASN1_22 + sizeof(ASN1_TYPE_22);
return(lpByte);
}
LPBYTE
FreeNDSSynId23ToNDS23(
LPBYTE lpByte
)
{
LPASN1_TYPE_23 lpASN1_23 = (LPASN1_TYPE_23) lpByte;
if (lpASN1_23->ObjectName) {
FreeADsStr(lpASN1_23->ObjectName);
}
lpByte = (LPBYTE ) lpASN1_23 + sizeof(ASN1_TYPE_23);
return(lpByte);
}
LPBYTE
FreeNDSSynId24ToNDS24(
LPBYTE lpByte
)
{
LPASN1_TYPE_24 lpASN1_24 = (LPASN1_TYPE_24) lpByte;
lpByte = (LPBYTE ) lpASN1_24 + sizeof(ASN1_TYPE_24);
return(lpByte);
}
LPBYTE
FreeNDSSynId25ToNDS25(
LPBYTE lpByte
)
{
LPASN1_TYPE_25 lpASN1_25 = (LPASN1_TYPE_25) lpByte;
if (lpASN1_25->ObjectName) {
FreeADsStr(lpASN1_25->ObjectName);
}
lpByte = (LPBYTE ) lpASN1_25 + sizeof(ASN1_TYPE_25);
return(lpByte);
}
LPBYTE
FreeNDSSynId26ToNDS26(
LPBYTE lpByte
)
{
LPASN1_TYPE_26 lpASN1_26 = (LPASN1_TYPE_26) lpByte;
if (lpASN1_26->ObjectName) {
FreeADsStr(lpASN1_26->ObjectName);
}
lpByte = (LPBYTE ) lpASN1_26 + sizeof(ASN1_TYPE_26);
return(lpByte);
}
LPBYTE
FreeNDSSynId27ToNDS27(
LPBYTE lpByte
)
{
LPASN1_TYPE_27 lpASN1_27 = (LPASN1_TYPE_27) lpByte;
lpByte = (LPBYTE ) lpASN1_27 + sizeof(ASN1_TYPE_27);
return(lpByte);
}
LPBYTE
FreeNDSSynIdToNDS(
DWORD dwSyntaxId,
LPBYTE lpByte
)
{
switch (dwSyntaxId) {
case 1:
lpByte = FreeNDSSynId1ToNDS1(
lpByte
);
break;
case 2:
lpByte = FreeNDSSynId2ToNDS2(
lpByte
);
break;
case 3:
lpByte = FreeNDSSynId3ToNDS3(
lpByte
);
break;
case 4:
lpByte = FreeNDSSynId4ToNDS4(
lpByte
);
break;
case 5:
lpByte = FreeNDSSynId5ToNDS5(
lpByte
);
break;
case 6:
lpByte = FreeNDSSynId6ToNDS6(
lpByte
);
break;
case 7:
lpByte = FreeNDSSynId7ToNDS7(
lpByte
);
break;
case 8:
lpByte = FreeNDSSynId8ToNDS8(
lpByte
);
break;
case 9:
lpByte = FreeNDSSynId9ToNDS9(
lpByte
);
break;
case 10:
lpByte = FreeNDSSynId10ToNDS10(
lpByte
);
break;
case 11:
lpByte = FreeNDSSynId11ToNDS11(
lpByte
);
break;
case 12:
lpByte = FreeNDSSynId12ToNDS12(
lpByte
);
break;
case 13:
lpByte = FreeNDSSynId13ToNDS13(
lpByte
);
break;
case 14:
lpByte = FreeNDSSynId14ToNDS14(
lpByte
);
break;
case 15:
lpByte = FreeNDSSynId15ToNDS15(
lpByte
);
break;
case 16:
lpByte = FreeNDSSynId16ToNDS16(
lpByte
);
break;
case 17:
lpByte = FreeNDSSynId17ToNDS17(
lpByte
);
break;
case 18:
lpByte = FreeNDSSynId18ToNDS18(
lpByte
);
break;
case 19:
lpByte = FreeNDSSynId19ToNDS19(
lpByte
);
break;
case 20:
lpByte = FreeNDSSynId20ToNDS20(
lpByte
);
break;
case 21:
lpByte = FreeNDSSynId21ToNDS21(
lpByte
);
break;
case 22:
lpByte = FreeNDSSynId22ToNDS22(
lpByte
);
break;
case 23:
lpByte = FreeNDSSynId23ToNDS23(
lpByte
);
break;
case 24:
lpByte = FreeNDSSynId24ToNDS24(
lpByte
);
break;
case 25:
lpByte = FreeNDSSynId25ToNDS25(
lpByte
);
break;
case 26:
lpByte = FreeNDSSynId26ToNDS26(
lpByte
);
break;
case 27:
lpByte = FreeNDSSynId27ToNDS27(
lpByte
);
break;
default:
break;
}
return(lpByte);
}
HRESULT
FreeMarshallMemory(
DWORD dwSyntaxId,
DWORD dwNumValues,
LPBYTE lpValue
)
{
DWORD i = 0;
for (i = 0; i < dwNumValues; i++) {
lpValue = FreeNDSSynIdToNDS(
dwSyntaxId,
lpValue
);
}
RRETURN(S_OK);
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
3cea15aa6174b036afe10e1886e4b040560b1e2c | 8760ace452bd3428ee202794085070d3423e1403 | /physics/perlinvf/type1.cpp | 0bc90a054706f9f2ad0ecc32eb94a515901d75bf | [] | no_license | dan98/cluster | 9dd798426df4688b42762ef4e99024d0e0892df3 | 83322f784042c95201cf6600228524f277c844ba | refs/heads/master | 2020-12-25T22:28:57.607021 | 2016-09-20T08:56:27 | 2016-09-20T08:56:27 | 68,688,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,248 | cpp | #include <bits/stdc++.h>
#include <GLFW/glfw3.h>
#include <GL/freeglut.h>
using namespace std;
#include "simplex.cpp"
#define x first
#define lsb(x) (x&-x)
#define pb push_back
#define y second
const int NMAX=300666; //LOL
const int MOD=1000000007;
typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<LD,LD> PLD;
typedef vector<int> VI;
GLFWwindow* window;
void init_frame()
{ if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(700, 700, "main", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
}
struct Vector{
double x, y, z;
Vector(double _x, double _y, double _z)
{
x=_x;
y=_y;
z=_z;
}
};
struct Mat3
{
double m[3][3];
Mat3(double a11, double a12, double a13, double a21, double a22, double a23, double a31, double a32, double a33)
{
m[0][0]=a11;
m[0][1]=a12;
m[0][2]=a13;
m[1][0]=a21;
m[1][1]=a22;
m[1][2]=a23;
m[2][0]=a31;
m[2][1]=a32;
m[2][2]=a33;
}
};
Vector multMat3Vector(Mat3 A, Vector v)
{
Vector n(0,0,0);
n.x=v.x*A.m[0][0]+v.y*A.m[0][1]+v.z*A.m[0][2];
n.y=v.x*A.m[1][0]+v.y*A.m[1][1]+v.z*A.m[1][2];
n.z=v.x*A.m[2][0]+v.y*A.m[2][1]+v.z*A.m[2][2];
return n;
}
Vector addVector(Vector a, Vector b)
{
Vector n(0,0,0);
n.x=a.x+b.x;
n.y=a.y+b.y;
n.z=a.z+b.z;
}
Mat3 Qx(double a)
{
return Mat3(1, 0, 0, 0, cos(a), sin(a), 0, -sin(a), cos(a));
}
Mat3 Qy(double a)
{
return Mat3(cos(a), 0, sin(a), 0, 1, 0, -sin(a), 0, cos(a));
}
Mat3 Qz(double a)
{
return Mat3(cos(a), sin(a), 0, -sin(a), cos(a), 0, 0, 0, 1);
}
Vector poz(0, 0, 0);
int main(int argc, char **argv)
{
glutInit(&argc, argv);
init_frame();
int simplexseed1, simplexseed2, simplexseed3;
SimplexNoiseStruct SimplexOne;
SimplexNoiseStruct SimplexTwo;
SimplexNoiseStruct SimplexThree;
SimplexOne.setNoiseSeed(simplexseed1);
SimplexTwo.setNoiseSeed(simplexseed2);
SimplexThree.setNoiseSeed(simplexseed3);
double t=0;
while(!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat lightpos[] = {.5, 1., 1., 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat cyan[] = {0.f, .8f, .8f, 1.f};
glMaterialfv(GL_FRONT, GL_AMBIENT, cyan);
glRotatef(0.1, 0, 1, 1);
for(double i=-0.5; i<=0.5; i+=0.05)
for(double j=-0.5; j<=0.5; j+=0.05)
for(double k=-0.5; k<=0.5; k+=0.05)
{
glPointSize(1);
glLineWidth(2);
glBegin(GL_LINES);
glVertex3f(i, j, k);
glEnd();
glBegin(GL_POINTS);
glVertex3f(i, j, k);
glEnd();
}
double a1=SimplexOne.SimplexNoiseInRange4D(poz.x, poz.y, poz.z, t, 0, 0.5*acos(-1));
double a2=SimplexTwo.SimplexNoiseInRange4D(poz.x, poz.y, poz.z, t, 0, 0.5*acos(-1));
double a3=SimplexThree.SimplexNoiseInRange4D(poz.x, poz.y, poz.z, t, 0, 0.5*acos(-1));
Vector vel(0.1, 0, 0);
vel=multMat3Vector(Qz(a1), vel);
vel=multMat3Vector(Qy(a2), vel);
vel=multMat3Vector(Qx(a3), vel);
poz=addVector(poz, vel);
glPointSize(8);
glBegin(GL_POINTS);
glVertex3f(poz.x, poz.y, poz.z);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
t+=0.001;
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| [
"Daniel Grosu"
] | Daniel Grosu |
caa9688bf633b53e490576590f250f3848fd05a0 | e65e6b345e98633cccc501ad0d6df9918b2aa25e | /Codeforces/Regular/864/D.cpp | 2561fbb91c9a27cddc224c94f873f824a526fdb2 | [] | no_license | wcysai/CodeLibrary | 6eb99df0232066cf06a9267bdcc39dc07f5aab29 | 6517cef736f1799b77646fe04fb280c9503d7238 | refs/heads/master | 2023-08-10T08:31:58.057363 | 2023-07-29T11:56:38 | 2023-07-29T11:56:38 | 134,228,833 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | cpp | #pragma GCC optimize(3)
#include<bits/stdc++.h>
#define MAXN 100005
#define INF 1000000000
#define MOD 1000000007
#define F first
#define S second
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int n,m,a[MAXN];
int sz[MAXN],fa[MAXN];
ll sum[MAXN];
set<P> son[MAXN];
vector<int> G[MAXN];
void dfs(int v,int p){
sz[v]=1; sum[v]=a[v]; fa[v]=p;
for(auto to:G[v]){
if(to==p) continue;
dfs(to,v);
son[v].insert(P(-sz[to],to));
sz[v]+=sz[to]; sum[v]+=sum[to];
}
}
void solve(int v){
P p=*son[v].begin();
assert(fa[v]);
son[fa[v]].erase(son[fa[v]].find(P(-sz[v],v)));
int s=p.S; son[v].erase(son[v].begin());
sum[v]-=sum[s]; sz[v]-=sz[s];
sum[s]+=sum[v]; sz[s]+=sz[v];
fa[s]=fa[v]; fa[v]=s;
son[s].insert(P(-sz[v],v));
son[fa[s]].insert(P(-sz[s],s));
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=0;i<n-1;i++){
int u,v; scanf("%d%d",&u,&v);
G[u].push_back(v); G[v].push_back(u);
}
dfs(1,0);
for(int i=0;i<m;i++){
int t,x;
scanf("%d%d",&t,&x);
if(t==1) printf("%lld\n",sum[x]);
else{
if(sz[x]>1) solve(x);
}
}
return 0;
}
| [
"wcysai@foxmail.com"
] | wcysai@foxmail.com |
4298438af1b702eaa2b543eca0598b32986d1a01 | 5454ae0fe9b4713afff524d67f18a5cafa792fb3 | /Cellulut/ui/views/forms/LoadModelFormView.cpp | 63a4e25ad067626febddea73de83c6235ee245c2 | [] | no_license | liujiaqi-corrine/projet_LO21 | b82781e7eb156c82a7ec9607abfe60b0d94a7b27 | 6d7668d4e91a3a3183d81df463977fb2be36d629 | refs/heads/main | 2023-06-09T04:03:01.105235 | 2021-06-13T22:58:35 | 2021-06-13T22:58:35 | 354,117,911 | 0 | 0 | null | 2021-05-13T15:20:05 | 2021-04-02T19:46:55 | C++ | UTF-8 | C++ | false | false | 2,742 | cpp | #include "LoadModelFormView.h"
LoadModelFormView::LoadModelFormView(QWidget *parent, UIEngine *_uiEngine) : QWidget(parent), uiEngine(_uiEngine)
{
this->instructionMessageLabel = UIUtils::createLabel(tr("Choose a model to use for the simulation"), 20, true, false);
this->backButton = new QPushButton("Return to main menu");
this->backButton->setFixedHeight(150);
this->backButton->setFont(UIUtils::getFont(15,true,false,QFont::Capitalization::AllUppercase));
this->backButton->setStyleSheet("background-color : crimson; color: white;");
this->nextButton = new QPushButton("Start simulation\n on this model");
this->nextButton->setFixedHeight(150);
this->nextButton->setFont(UIUtils::getFont(15,true,false,QFont::Capitalization::AllUppercase));
this->nextButton->setStyleSheet("background-color : crimson; color: white;");
this->modelComboLabel = UIUtils::createLabel(tr("Model :"), 20, false, false);
QStringList modelComboStringList;
vector<Model*> *listOfModels = Library::getLibrary()->getListModels();
for(unsigned int i = 0; i < listOfModels->size(); i++){
modelComboStringList << listOfModels->at(i)->getTitleAsQString();
}
this->modelComboModel = new QStringListModel();
this->modelComboModel->setStringList(modelComboStringList);
this->modelCombo = new QComboBox();
this->modelCombo->setModel(modelComboModel);
this->gridLayout = new QGridLayout();
this->gridLayout->addWidget(this->instructionMessageLabel, 0, 0, 1, 2);
this->gridLayout->addWidget(this->modelComboLabel, 1, 0, 1, 1);
this->gridLayout->addWidget(this->modelCombo, 1, 1, 1, 1);
this->gridLayout->addWidget(this->backButton, 2, 0, 1, 1);
this->gridLayout->addWidget(this->nextButton, 2, 1, 1, 1);
this->setLayout(this->gridLayout);
connect(this->backButton, &QPushButton::clicked, this->uiEngine, &UIEngine::changeToMainMenuView);
connect(this->nextButton, &QPushButton::clicked, this, &LoadModelFormView::onNextButtonClick);
qInfo() << "LoadModelFormView::LoadModelFormView - constructor";
}
LoadModelFormView::~LoadModelFormView()
{
delete this->gridLayout;
delete this->instructionMessageLabel;
delete this->modelComboModel;
delete this->modelCombo;
delete this->modelComboLabel;
delete this->nextButton;
delete this->backButton;
qInfo() << "LoadModelFormView::LoadModelFormView - destructor";
}
void LoadModelFormView::onNextButtonClick(){
int selectedModel = this->modelCombo->currentIndex();
Automate::getAutomate()->setModel(Library::getLibrary()->getListModels()->at(selectedModel));
Automate::getAutomate()->init_Grid(MIN_GRID_SIZE);
this->uiEngine->changeToSimulationView();
}
| [
"3clement3@gmail.com"
] | 3clement3@gmail.com |
ba0f058e3399b5081513725ffcb46ef95b6c0179 | 7b126b5d40d33c8f395e96ab97b0a9df6cba4bb9 | /tetreesh/swordfeesh/engine.hpp | d2dcd940de46128c7dab1540f8800ef165819a0d | [] | no_license | ElFeesho/OldCProjects | 244cced8c158a9c0cbb4a6ff66decbb164b6050e | 3c44ccc79bc4982340cdf6816e70845e5bc334ba | refs/heads/master | 2016-09-08T01:57:21.337382 | 2014-10-29T22:55:27 | 2014-10-29T22:55:27 | 7,738,615 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 880 | hpp | #ifndef __ENGINE_HPP__
#define __ENGINE_HPP__
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <vector>
#ifndef SDLWINDOW
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#endif
#include "scene.hpp"
using std::vector;
namespace SwordFeesh
{
class Engine
{
public:
Engine(int w, int h);
~Engine();
bool update();
void set_scene(Scene *scene);
static Engine *get_inst();
static Uint32 get_ticks();
void get_viewport(int *w, int *h);
void shutdown();
void clear_screen(int r = 0, int g = 0, int b = 0);
private:
#ifndef SDLWINDOW
Display *dpy;
Window glwin;
#endif
static Engine *inst;
static Uint32 ticks;
int w;
int h;
Scene *nscene; // New scene
Scene *scene; // The actual scene
bool quit; // Shutdown sets this to true
};
}
#endif
| [
"gummybassist@gmail.com"
] | gummybassist@gmail.com |
9e354b9ef01679a6ce7f51017bbdfbd286e3624d | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/ea/b536fe00fdc94f/main.cpp | 6c7bd6059ba4237937881cce0d7b299956194e6c | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,643 | cpp | #include <cstddef>
#include <memory>
#include <numeric>
#include <array>
#include <initializer_list>
namespace detail {
template <typename T>
auto get_data( std::initializer_list<T>& cont ) -> decltype( cont.begin( ) ) {
return cont.begin( );
}
template <typename T>
auto get_data( std::initializer_list<T>&& cont ) -> decltype( cont.begin( ) ) {
return cont.begin( );
}
template <typename T>
auto get_data( std::initializer_list<T> cont ) -> decltype( cont.begin( ) ) {
return cont.begin( );
}
template <typename T>
auto get_data( std::false_type, T* cont ) -> decltype( cont ) {
return cont;
}
template <typename T>
auto get_data( std::false_type, T&& cont ) -> decltype( cont.data( ) ) {
return cont.data( );
}
template <typename T, std::size_t n>
T* get_data( std::true_type, T( &cont )[ n ] ) {
return std::addressof( cont[ 0 ] );
}
inline std::nullptr_t get_data( std::false_type, std::nullptr_t ) {
return nullptr;
}
inline std::size_t get_size( std::false_type, std::nullptr_t ) {
return 0;
}
template <typename T>
auto get_size( std::false_type, T&& cont ) -> decltype( cont.size( ) ) {
return cont.size( );
}
template <typename T, std::size_t n>
std::size_t get_size( std::true_type, T( &cont )[ n ] ) {
return n;
}
}
template <typename T>
auto get_data( T& cont ) -> decltype( detail::get_data( std::is_array<T>( ), cont ) ) {
return detail::get_data( std::is_array<T>( ), cont );
}
template <typename T>
auto get_size( T& cont ) -> decltype( detail::get_size( std::is_array<T>( ), cont ) ) {
return detail::get_size( std::is_array<T>( ), cont );
}
template <std::size_t nrank = 1>
struct index {
private:
std::array<std::size_t, nrank> idxs;
public:
index ( ) : idxs() {
}
index( std::initializer_list<std::size_t> values ) {
std::copy( values.begin(), values.end(), idxs.begin() );
}
std::size_t& operator[]( std::size_t i ) {
return idxs[i];
}
const std::size_t& operator[]( std::size_t i ) const {
return idxs[i];
}
};
template <>
struct index<1> {
private:
std::array<std::size_t, 1> idxs;
public:
index ( ) : idxs() {
}
index( std::size_t dim ) {
idxs[0] = dim;
}
index( std::initializer_list<std::size_t> values ) {
std::copy( values.begin(), values.end(), idxs.begin() );
}
std::size_t size () const {
return idxs.size();
}
std::size_t& operator[]( std::size_t i ) {
return idxs[i];
}
const std::size_t& operator[]( std::size_t i ) const {
return idxs[i];
}
};
template <typename TRange, std::size_t nrank>
std::size_t access_index ( const index<nrank>& i, TRange&& dimensions ) {
std::size_t dataidx = 0;
for ( std::size_t c = 0; c < dimensions.size() -1; ++c ) {
dataidx += i[c] * dimensions[c];
}
return i[ dimensions.size() - 1 ] + dataidx;
}
template <typename T, std::size_t d = 1>
class buffer_view {
public:
typedef index<d> index_type;
typedef T value_type;
typedef typename std::conditional<std::is_same<void, typename std::remove_cv<T>::type>::value, unsigned char, T>::type& reference;
typedef const typename std::conditional<std::is_same<void, typename std::remove_cv<T>::type>::value, unsigned char, T>::type& const_reference;
typedef T* pointer_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef pointer_type iterator;
typedef const pointer_type const_iterator;
private:
T* res;
std::array<std::size_t, d> dims;
public:
buffer_view( std::nullptr_t nptr = nullptr ) : res( nullptr ), dims{ } {
}
buffer_view( T* buffer, const std::array<std::size_t, d>& dims )
: res( buffer ), dims( dims ) {
}
template <typename TContainer, typename... Tn>
buffer_view( TContainer&& container, Tn&&... sizen )
: buffer_view( get_data( container ), { static_cast<std::size_t>( std::forward<Tn>( sizen ) )... } ) {
}
template <typename TContainer>
buffer_view( TContainer&& container )
: buffer_view( get_data( container ), { get_size( container ) } ) {
static_assert( d == 1, "Cannot use single-argument constructor with a multi-dimensional array: specify sizes" );
}
const std::array<std::size_t, d>& dimensions ( ) const {
return dims;
}
bool is_null( ) const {
return res == nullptr;
}
bool empty( ) const {
return size( ) < 1;
}
bool not_empty( ) const {
return size( ) > 0;
}
iterator begin( ) {
return res;
}
iterator end( ) {
return res + size( );
}
const_iterator begin( ) const {
return res;
}
const_iterator end( ) const {
return res + size( );
}
const_iterator cbegin( ) {
return res;
}
const_iterator cend( ) {
return res + size( );
}
const_iterator cbegin( ) const {
return res;
}
const_iterator cend( ) const {
return res + size( );
}
reference operator[] ( index_type i ) {
return res[ access_index( i, dims ) ];
}
const_reference operator[] ( index_type i ) const {
return res[ access_index( i, dims ) ];
}
T* data( ) {
return res;
}
T* data_end( ) {
return res + size( );
}
const T* data( ) const {
return res;
}
const T* data_end( ) const {
return res + size();
}
reference front( ) {
return *res;
}
reference back( ) {
return *( res + size( ) );
}
const_reference front( ) const {
return *res;
}
const_reference back( ) const {
return *( res + size( ) );
}
std::size_t size( ) const {
return std::accumulate( dims.begin( ), dims.end( ), 1, [ ] ( std::size_t a, std::size_t b ) { return a * b; } );
}
};
#include <vector>
#include <iostream>
template <typename TRange>
void array_print ( TRange&& range ) {
for ( auto i : range ) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << std::endl;
}
int main() {
std::vector<double> dataz( 8, 0.0f );
buffer_view<double> view8x1( dataz );
buffer_view<double, 2> view2x4( dataz, 2, 4 );
array_print( dataz );
view8x1[0] = 2.0f;
view8x1[1] = 2.0f;
array_print( dataz );
view2x4[{1, 1}] = 3.0f;
view2x4[{1, 0}] = 3.0f;
array_print( dataz );
// calls will fail
//buffer_view<double, 2> view2x4fail( dataz );
//view2x4[ 1 ] = 50.0f;
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
a6eea53dff365aa0a9f1a55907952bde1675bff0 | ceec3f1ea495e9673b8ef3198657c485f927380f | /cocaIrrlicht/vendor/irrlicht/source/Irrlicht/CIrrDeviceConsole.cpp | 951be8d7e887304b6c7b4a6bbe3515a90425b879 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | harmboschloo/CocaProject | 251b138fb2e29d9d7a2f0e07fb24e85299ccb7e4 | 530476db6db41158beab47810e56c9d1820640e4 | refs/heads/master | 2020-04-05T22:51:53.812675 | 2014-07-03T09:15:53 | 2014-07-03T09:15:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,123 | cpp | // Copyright (C) 2009 Gaz Davidson
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CIrrDeviceConsole.h"
#ifdef _IRR_USE_CONSOLE_DEVICE_
#include "os.h"
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
// to close the device on terminate signal
irr::CIrrDeviceConsole *DeviceToClose;
#ifdef _IRR_WINDOWS_NT_CONSOLE_
// Callback for Windows
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
switch(CEvent)
{
case CTRL_C_EVENT:
irr::os::Printer::log("Closing console device", "CTRL+C");
break;
case CTRL_BREAK_EVENT:
irr::os::Printer::log("Closing console device", "CTRL+Break");
break;
case CTRL_CLOSE_EVENT:
irr::os::Printer::log("Closing console device", "User closed console");
break;
case CTRL_LOGOFF_EVENT:
irr::os::Printer::log("Closing console device", "User is logging off");
break;
case CTRL_SHUTDOWN_EVENT:
irr::os::Printer::log("Closing console device", "Computer shutting down");
break;
}
DeviceToClose->closeDevice();
return TRUE;
}
#else
// sigterm handler
#include <signal.h>
void sighandler(int sig)
{
irr::core::stringc code = "Signal ";
code += sig;
code += " received";
irr::os::Printer::log("Closing console device", code.c_str());
DeviceToClose->closeDevice();
}
#endif
namespace irr
{
const c8 ASCIIArtChars[] = " .,'~:;!+>=icopjtJY56SB8XDQKHNWM"; //MWNHKQDX8BS65YJtjpoci=+>!;:~',. ";
const u16 ASCIIArtCharsCount = 32;
//const c8 ASCIIArtChars[] = " \xb0\xb1\xf9\xb2\xdb";
//const u16 ASCIIArtCharsCount = 5;
//! constructor
CIrrDeviceConsole::CIrrDeviceConsole(const SIrrlichtCreationParameters& params)
: CIrrDeviceStub(params), IsDeviceRunning(true), IsWindowFocused(true), ConsoleFont(0)
{
DeviceToClose = this;
#ifdef _IRR_WINDOWS_NT_CONSOLE_
MouseButtonStates = 0;
WindowsSTDIn = GetStdHandle(STD_INPUT_HANDLE);
WindowsSTDOut = GetStdHandle(STD_OUTPUT_HANDLE);
PCOORD Dimensions = 0;
if (CreationParams.Fullscreen)
{
if (SetConsoleDisplayMode(WindowsSTDOut, CONSOLE_FULLSCREEN_MODE, Dimensions))
{
CreationParams.WindowSize.Width = Dimensions->X;
CreationParams.WindowSize.Width = Dimensions->Y;
}
}
else
{
COORD ConsoleSize;
ConsoleSize.X = CreationParams.WindowSize.Width;
ConsoleSize.X = CreationParams.WindowSize.Height;
SetConsoleScreenBufferSize(WindowsSTDOut, ConsoleSize);
}
// catch windows close/break signals
SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE);
#else
// catch other signals
signal(SIGABRT, &sighandler);
signal(SIGTERM, &sighandler);
signal(SIGINT, &sighandler);
#endif
#ifdef _IRR_VT100_CONSOLE_
// reset terminal
printf("%cc", 27);
// disable line wrapping
printf("%c[7l", 27);
#endif
switch (params.DriverType)
{
case video::EDT_SOFTWARE:
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Software driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_BURNINGSVIDEO:
#ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_
VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this);
#else
os::Printer::log("Burning's Video driver was not compiled in.", ELL_ERROR);
#endif
break;
case video::EDT_DIRECT3D8:
case video::EDT_DIRECT3D9:
case video::EDT_OPENGL:
os::Printer::log("The console device cannot use hardware drivers", ELL_ERROR);
break;
case video::EDT_NULL:
VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize);
break;
default:
break;
}
// set up output buffer
for (u32 y=0; y<CreationParams.WindowSize.Height; ++y)
{
core::stringc str;
str.reserve(CreationParams.WindowSize.Width);
for (u32 x=0; x<CreationParams.WindowSize.Width; ++x)
str += " ";
OutputBuffer.push_back(str);
}
#ifdef _IRR_WINDOWS_NT_CONSOLE_
CursorControl = new CCursorControl(CreationParams.WindowSize);
#endif
if (VideoDriver)
{
createGUIAndScene();
#ifdef _IRR_USE_CONSOLE_FONT_
if (GUIEnvironment)
{
ConsoleFont = new gui::CGUIConsoleFont(this);
gui::IGUISkin *skin = GUIEnvironment->getSkin();
if (skin)
{
for (u32 i=0; i < gui::EGDF_COUNT; ++i)
skin->setFont(ConsoleFont, gui::EGUI_DEFAULT_FONT(i));
}
}
#endif
}
}
//! destructor
CIrrDeviceConsole::~CIrrDeviceConsole()
{
// GUI and scene are dropped in the stub
if (CursorControl)
{
CursorControl->drop();
CursorControl = 0;
}
if (ConsoleFont)
{
ConsoleFont->drop();
ConsoleFont = 0;
}
#ifdef _IRR_VT100_CONSOLE_
// reset terminal
printf("%cc", 27);
#endif
}
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceConsole::run()
{
// increment timer
os::Timer::tick();
// process Windows console input
#ifdef _IRR_WINDOWS_NT_CONSOLE_
INPUT_RECORD in;
DWORD oldMode;
DWORD count, waste;
// get old input mode
GetConsoleMode(WindowsSTDIn, &oldMode);
SetConsoleMode(WindowsSTDIn, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
GetNumberOfConsoleInputEvents(WindowsSTDIn, &count);
// read keyboard and mouse input
while (count)
{
ReadConsoleInput(WindowsSTDIn, &in, 1, &waste );
switch(in.EventType)
{
case KEY_EVENT:
{
SEvent e;
e.EventType = EET_KEY_INPUT_EVENT;
e.KeyInput.PressedDown = (in.Event.KeyEvent.bKeyDown == TRUE);
e.KeyInput.Control = (in.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
e.KeyInput.Shift = (in.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED) != 0;
e.KeyInput.Key = EKEY_CODE(in.Event.KeyEvent.wVirtualKeyCode);
e.KeyInput.Char = in.Event.KeyEvent.uChar.UnicodeChar;
postEventFromUser(e);
break;
}
case MOUSE_EVENT:
{
SEvent e;
e.EventType = EET_MOUSE_INPUT_EVENT;
e.MouseInput.X = in.Event.MouseEvent.dwMousePosition.X;
e.MouseInput.Y = in.Event.MouseEvent.dwMousePosition.Y;
e.MouseInput.Wheel = 0.f;
e.MouseInput.ButtonStates =
( (in.Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) ? EMBSM_LEFT : 0 ) |
( (in.Event.MouseEvent.dwButtonState & RIGHTMOST_BUTTON_PRESSED) ? EMBSM_RIGHT : 0 ) |
( (in.Event.MouseEvent.dwButtonState & FROM_LEFT_2ND_BUTTON_PRESSED) ? EMBSM_MIDDLE : 0 ) |
( (in.Event.MouseEvent.dwButtonState & FROM_LEFT_3RD_BUTTON_PRESSED) ? EMBSM_EXTRA1 : 0 ) |
( (in.Event.MouseEvent.dwButtonState & FROM_LEFT_4TH_BUTTON_PRESSED) ? EMBSM_EXTRA2 : 0 );
if (in.Event.MouseEvent.dwEventFlags & MOUSE_MOVED)
{
CursorControl->setPosition(core::position2di(e.MouseInput.X, e.MouseInput.Y));
// create mouse moved event
e.MouseInput.Event = EMIE_MOUSE_MOVED;
postEventFromUser(e);
}
if (in.Event.MouseEvent.dwEventFlags & MOUSE_WHEELED)
{
e.MouseInput.Event = EMIE_MOUSE_WHEEL;
e.MouseInput.Wheel = (in.Event.MouseEvent.dwButtonState & 0xFF000000) ? -1.0f : 1.0f;
postEventFromUser(e);
}
if ( (MouseButtonStates & EMBSM_LEFT) != (e.MouseInput.ButtonStates & EMBSM_LEFT) )
{
e.MouseInput.Event = (e.MouseInput.ButtonStates & EMBSM_LEFT) ? EMIE_LMOUSE_PRESSED_DOWN : EMIE_LMOUSE_LEFT_UP;
postEventFromUser(e);
}
if ( (MouseButtonStates & EMBSM_RIGHT) != (e.MouseInput.ButtonStates & EMBSM_RIGHT) )
{
e.MouseInput.Event = (e.MouseInput.ButtonStates & EMBSM_RIGHT) ? EMIE_RMOUSE_PRESSED_DOWN : EMIE_RMOUSE_LEFT_UP;
postEventFromUser(e);
}
if ( (MouseButtonStates & EMBSM_MIDDLE) != (e.MouseInput.ButtonStates & EMBSM_MIDDLE) )
{
e.MouseInput.Event = (e.MouseInput.ButtonStates & EMBSM_MIDDLE) ? EMIE_MMOUSE_PRESSED_DOWN : EMIE_MMOUSE_LEFT_UP;
postEventFromUser(e);
}
// save current button states
MouseButtonStates = e.MouseInput.ButtonStates;
break;
}
case WINDOW_BUFFER_SIZE_EVENT:
VideoDriver->OnResize(
core::dimension2d<u32>(in.Event.WindowBufferSizeEvent.dwSize.X,
in.Event.WindowBufferSizeEvent.dwSize.Y));
break;
case FOCUS_EVENT:
IsWindowFocused = (in.Event.FocusEvent.bSetFocus == TRUE);
break;
default:
break;
}
GetNumberOfConsoleInputEvents(WindowsSTDIn, &count);
}
// set input mode
SetConsoleMode(WindowsSTDIn, oldMode);
#else
// todo: keyboard input from terminal in raw mode
#endif
return IsDeviceRunning;
}
//! Cause the device to temporarily pause execution and let other processes to run
// This should bring down processor usage without major performance loss for Irrlicht
void CIrrDeviceConsole::yield()
{
#ifdef _IRR_WINDOWS_API_
Sleep(1);
#else
struct timespec ts = {0,0};
nanosleep(&ts, NULL);
#endif
}
//! Pause execution and let other processes to run for a specified amount of time.
void CIrrDeviceConsole::sleep(u32 timeMs, bool pauseTimer)
{
const bool wasStopped = Timer ? Timer->isStopped() : true;
#ifdef _IRR_WINDOWS_API_
Sleep(timeMs);
#else
struct timespec ts;
ts.tv_sec = (time_t) (timeMs / 1000);
ts.tv_nsec = (long) (timeMs % 1000) * 1000000;
if (pauseTimer && !wasStopped)
Timer->stop();
nanosleep(&ts, NULL);
#endif
if (pauseTimer && !wasStopped)
Timer->start();
}
//! sets the caption of the window
void CIrrDeviceConsole::setWindowCaption(const wchar_t* text)
{
#ifdef _IRR_WINDOWS_NT_CONSOLE_
core::stringc txt(text);
SetConsoleTitle(txt.c_str());
#endif
}
//! returns if window is active. if not, nothing need to be drawn
bool CIrrDeviceConsole::isWindowActive() const
{
// there is no window, but we always assume it is active
return true;
}
//! returns if window has focus
bool CIrrDeviceConsole::isWindowFocused() const
{
return IsWindowFocused;
}
//! returns if window is minimized
bool CIrrDeviceConsole::isWindowMinimized() const
{
return false;
}
//! presents a surface in the client area
bool CIrrDeviceConsole::present(video::IImage* surface, void* windowId, core::rect<s32>* src)
{
if (surface)
{
for (u32 y=0; y < surface->getDimension().Height; ++y)
{
for (u32 x=0; x< surface->getDimension().Width; ++x)
{
// get average pixel
u32 avg = surface->getPixel(x,y).getAverage() * (ASCIIArtCharsCount-1);
avg /= 255;
OutputBuffer[y] [x] = ASCIIArtChars[avg];
}
}
}
#ifdef _IRR_USE_CONSOLE_FONT_
for (u32 i=0; i< Text.size(); ++i)
{
s32 y = Text[i].Pos.Y;
if ( y < (s32)OutputBuffer.size() && y > 0)
for (u32 c=0; c < Text[i].Text.size() && c + Text[i].Pos.X < OutputBuffer[y].size(); ++c)
//if (Text[i].Text[c] != ' ')
OutputBuffer[y] [c+Text[i].Pos.X] = Text[i].Text[c];
}
Text.clear();
#endif
// draw output
for (u32 y=0; y<OutputBuffer.size(); ++y)
{
setTextCursorPos(0,y);
printf("%s", OutputBuffer[y].c_str());
}
return surface != 0;
}
//! notifies the device that it should close itself
void CIrrDeviceConsole::closeDevice()
{
// return false next time we run()
IsDeviceRunning = false;
}
//! Sets if the window should be resizable in windowed mode.
void CIrrDeviceConsole::setResizable(bool resize)
{
// do nothing
}
//! Minimize the window.
void CIrrDeviceConsole::minimizeWindow()
{
// do nothing
}
void CIrrDeviceConsole::setTextCursorPos(s16 x, s16 y)
{
#ifdef _IRR_WINDOWS_NT_CONSOLE_
// move WinNT cursor
COORD Position;
Position.X = x;
Position.Y = y;
SetConsoleCursorPosition(WindowsSTDOut, Position);
#elif defined(_IRR_VT100_CONSOLE_)
// send escape code
printf("%c[%d;%dH", 27, y, x);
#else
// not implemented
#endif
}
void CIrrDeviceConsole::addPostPresentText(s16 X, s16 Y, const wchar_t *text)
{
SPostPresentText p;
p.Text = text;
p.Pos.X = X;
p.Pos.Y = Y;
Text.push_back(p);
}
extern "C" IRRLICHT_API IrrlichtDevice* IRRCALLCONV createDeviceEx(
const SIrrlichtCreationParameters& parameters)
{
CIrrDeviceConsole* dev = new CIrrDeviceConsole(parameters);
if (dev && !dev->getVideoDriver() && parameters.DriverType != video::EDT_NULL)
{
dev->closeDevice(); // close device
dev->run(); // consume quit message
dev->drop();
dev = 0;
}
return dev;
}
} // end namespace irr
#endif // _IRR_USE_CONSOLE_DEVICE_
| [
"harm@boschloo.net"
] | harm@boschloo.net |
d839e66c72090da01bed9d5262395c1459a4352d | dc10aaa23f2c3772caed6ede025525f8a40147f4 | /include/Network/SmartPacket.h | 34245685b1cd5de82408d02049e6237d411bd2aa | [] | no_license | Bomberman3D/BomberClient | 3516a410ae0f2aa4654a55143786d5f447902fee | 209c196ff9c2adaff4abbeabb0fb7d824d3f509b | refs/heads/master | 2020-05-30T03:45:24.366103 | 2013-04-26T09:29:13 | 2013-04-26T09:30:13 | 2,949,128 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | h | /* *
* Bomberman Server *
* *
* Developed by: Cmaranec (Kennny) *
* *
* Copyright (c) 2011 *
* */
#ifndef __SMARTPACKET_H_
#define __SMARTPACKET_H_
#include <iostream>
#include <vector>
#ifndef _WIN32
#include <string.h>
#endif
#include "Opcodes.h"
class SmartPacket
{
public:
SmartPacket(unsigned int opcode = MSG_NONE)
{
opcodeId = opcode;
storage.clear();
size = 0;
pos = 0;
}
void SetOpcode(unsigned int opcode) { opcodeId = opcode; }
unsigned int GetOpcode() { return opcodeId; }
void SetPos(size_t newpos) { pos = newpos; }
unsigned int GetPos() { return pos; }
size_t GetSize() { return size; }
SmartPacket &operator<<(unsigned char value)
{
storage.resize(size + sizeof(unsigned char));
memcpy(&storage[size],&value,sizeof(unsigned char));
size += sizeof(unsigned char);
return *this;
}
SmartPacket &operator<<(unsigned short value)
{
storage.resize(size + sizeof(unsigned short));
memcpy(&storage[size],&value,sizeof(unsigned short));
size += sizeof(unsigned short);
return *this;
}
SmartPacket &operator<<(unsigned int value)
{
storage.resize(size + sizeof(unsigned int));
memcpy(&storage[size],&value,sizeof(unsigned int));
size += sizeof(unsigned int);
return *this;
}
SmartPacket &operator<<(float value)
{
storage.resize(size + sizeof(float));
memcpy(&storage[size],&value,sizeof(float));
size += sizeof(float);
return *this;
}
SmartPacket &operator<<(const char* value)
{
for(size_t i = 0; i < strlen(value); i++)
{
storage.resize(size + sizeof(unsigned char));
storage[size] = value[i];
size += sizeof(unsigned char);
}
// String must be null terminated
storage.resize(size + sizeof(unsigned char));
storage[size] = 0;
size += sizeof(unsigned char);
return *this;
}
SmartPacket &operator>>(char &value)
{
value = storage[pos];
pos += sizeof(char);
return *this;
}
SmartPacket &operator>>(unsigned char &value)
{
value = storage[pos];
pos += sizeof(unsigned char);
return *this;
}
SmartPacket &operator>>(unsigned short &value)
{
memcpy(&value,&storage[pos],sizeof(unsigned short));
pos += sizeof(unsigned short);
return *this;
}
SmartPacket &operator>>(unsigned int &value)
{
memcpy(&value,&storage[pos],sizeof(unsigned int));
pos += sizeof(unsigned int);
return *this;
}
SmartPacket &operator>>(float &value)
{
memcpy(&value,&storage[pos],sizeof(float));
pos += sizeof(float);
return *this;
}
const char* readstr(size_t size)
{
char* temp = new char[size+sizeof(unsigned char)];
for(size_t i = 0; i < size; i++)
{
temp[i] = storage[pos];
pos += sizeof(unsigned char);
}
temp[size] = '\0';
return temp;
}
const char* readstr()
{
char* temp = new char[size+sizeof(unsigned char)];
for(size_t i = 0; i < storage.size(); i++)
{
temp[i] = storage[pos];
pos += sizeof(unsigned char);
if (storage[pos-1] == '\0')
return temp;
}
temp[size] = '\0';
return temp;
}
private:
unsigned int opcodeId;
std::vector<unsigned char> storage;
size_t size, pos;
};
#endif
| [
"cmaranec@seznam.cz"
] | cmaranec@seznam.cz |
efa882965ca4dbd4be17b4b62f8941403992bff5 | dc8701db40badf2076e22d604505cc6221a51b35 | /skyrim32_ckt/skyrim32_ckt.cpp | c15ac5a3c90c77a048571a2bc7a84f608dbd8897 | [] | no_license | ap-Di0/SkyrimSETest | c8ceb84ffd053d79aa0ab867a6c2da2778af039f | 328916305165a46c4e4b527735bbcfd46b09a0ca | refs/heads/master | 2023-07-02T21:01:54.243797 | 2021-08-11T18:02:24 | 2021-08-11T18:03:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,999 | cpp | #include <windows.h>
#include <stdio.h>
#include <thread>
#include <atomic>
#include "Loader.h"
#include "CreationKit.h"
#include "LipSynchAnim.h"
std::atomic_uint32_t g_CreationKitPID;
bool RunLipGeneration(const char *Language, const char *FonixDataPath, const char *WavPath, const char *ResampledWavPath, const char *LipPath, const char *Text, bool Resample)
{
CreationKit::SetFaceFXDataPath(FonixDataPath);
CreationKit::SetFaceFXLanguage(Language);
CreationKit::SetFaceFXAutoResampling(Resample);
auto lipAnim = LipSynchAnim::Generate(WavPath, ResampledWavPath, Text, nullptr);
if (!lipAnim)
return false;
bool result = lipAnim->SaveToFile(LipPath, true, 16, true);
lipAnim->Free();
return result;
}
void IPCExitNotificationThread()
{
// Grab a handle to the parent process and check for termination
HANDLE parentProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, g_CreationKitPID);
if (!parentProcess)
{
printf("A CreationKit parent process ID (0x%X) was supplied, but wasn't able to be queried (%d).\n", g_CreationKitPID.load(), GetLastError());
return;
}
for (DWORD exitCode = 0;; Sleep(2000))
{
if (g_CreationKitPID == 0)
break;
if (GetExitCodeProcess(parentProcess, &exitCode) && exitCode == STILL_ACTIVE)
continue;
g_CreationKitPID = 0;
break;
}
CloseHandle(parentProcess);
}
bool StartCreationKitIPC(uint32_t ProcessID)
{
// Disable any kind of buffering when using printf or related functions
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Establish tunnel
char temp[128];
sprintf_s(temp, "CkSharedMem%d", ProcessID);
HANDLE mapping = OpenFileMappingA(FILE_MAP_ALL_ACCESS, TRUE, temp);
if (!mapping)
{
printf("Could not create file mapping object (%d).\n", GetLastError());
return false;
}
auto tunnel = reinterpret_cast<CreationKit::LipGenTunnel *>(MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0x40000));
if (!tunnel)
{
printf("Could not map view of file (%d).\n", GetLastError());
CloseHandle(mapping);
return false;
}
sprintf_s(temp, "CkNotifyEvent%d", ProcessID);
HANDLE notifyEvent = OpenEventA(EVENT_ALL_ACCESS, TRUE, temp);
sprintf_s(temp, "CkWaitEvent%d", ProcessID);
HANDLE waitEvent = OpenEventA(EVENT_ALL_ACCESS, TRUE, temp);
if (!notifyEvent || !waitEvent)
{
printf("Could not open event handle(s) (%d).\n", GetLastError());
UnmapViewOfFile(tunnel);
CloseHandle(mapping);
return false;
}
// Thread to check for parent process exit
std::thread exitThread(IPCExitNotificationThread);
exitThread.detach();
// Wait until the creation kit asks to do something, then lazy initialize the loader
printf("FaceFXWrapper IPC established\n");
g_CreationKitPID = ProcessID;
bool loaderInitialized = false;
while (true)
{
DWORD waitStatus = WaitForSingleObject(notifyEvent, 2500);
if (waitStatus == WAIT_FAILED)
{
printf("Failed waiting for CK64 notification (%d).\n", GetLastError());
break;
}
// If the parent process exited, bail
if ((waitStatus == WAIT_OBJECT_0 && strlen(tunnel->InputWAVPath) <= 0) || g_CreationKitPID == 0)
break;
if (waitStatus == WAIT_TIMEOUT)
continue;
if (!std::exchange(loaderInitialized, true))
{
if (!Loader::Initialize())
break;
}
printf("Attempting to create LIP file:\n");
printf(" Input WAV: '%s'\n", tunnel->InputWAVPath);
printf(" Resampled input WAV: '%s'\n", tunnel->ResampleTempWAVPath);
printf(" Text: '%s'\n", tunnel->DialogueText);
printf(" Fonix data: '%s'\n", tunnel->FonixDataPath);
printf(" Language: '%s'\n", tunnel->Language);
const char *lipPath = "Data\\Sound\\Voice\\Processing\\Temp.lip";
printf("Writing temporary LIP file to '%s'\n", lipPath);
if (!RunLipGeneration(tunnel->Language, tunnel->FonixDataPath, tunnel->InputWAVPath, tunnel->ResampleTempWAVPath, lipPath, tunnel->DialogueText, true))
printf("Unable to generate LIP data or unable to save to '%s'!\n", lipPath);
memset(tunnel->InputWAVPath, 0, sizeof(tunnel->InputWAVPath));
tunnel->UnknownStatus = true;
// Done
SetEvent(waitEvent);
WaitForSingleObject(notifyEvent, INFINITE);
SetEvent(waitEvent);
}
printf("FaceFXWrapper IPC shutdown\n");
CloseHandle(notifyEvent);
CloseHandle(waitEvent);
UnmapViewOfFile(tunnel);
CloseHandle(mapping);
g_CreationKitPID = 0;
return true;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Create the IPC tunnel if this was launched from CreationKit.exe
if (const char *pid = getenv("Ckpid"); pid && strlen(pid) > 0)
{
if (!StartCreationKitIPC(atoi(pid)))
return 1;
return 0;
}
// Use command line processing instead
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
switch (__argc)
{
case 6:
if (!Loader::Initialize())
return 1;
// Resampling disabled - use same path for WavPath and ResampledWavPath
if (!RunLipGeneration(__argv[1], __argv[2], __argv[3], __argv[3], __argv[4], __argv[5], false))
{
printf("LIP generation failed\n");
return 1;
}
return 0;
case 7:
if (!Loader::Initialize())
return 1;
if (!RunLipGeneration(__argv[1], __argv[2], __argv[3], __argv[4], __argv[5], __argv[6], true))
{
printf("LIP generation failed\n");
return 1;
}
return 0;
default:
printf("\n\nUsage:\n");
printf("\tFaceFXWrapper [Lang] [FonixDataPath] [WavPath] [ResampledWavPath] [LipPath] [Text]\n");
printf("\tFaceFXWrapper [Lang] [FonixDataPath] [ResampledWavPath] [LipPath] [Text]\n");
printf("\n");
printf("Examples:\n");
printf("\tFaceFXWrapper \"USEnglish\" \"C:\\FonixData.cdf\" \"C:\\input.wav\" \"C:\\input_resampled.wav\" \"C:\\output.lip\" \"Blah Blah Blah\"\n");
printf("\tFaceFXWrapper \"USEnglish\" \"C:\\FonixData.cdf\" \"C:\\input_resampled.wav\" \"C:\\output.lip\" \"Blah Blah Blah\"\n");
printf("\n");
return 1;
}
return 0;
} | [
"Nukem@outlook.com"
] | Nukem@outlook.com |
15213cf287e66064d71380fdb3583bb52983e0c7 | 0ce69de361c56ffd82a213a782ad0604ca787141 | /CSE329 Prelude to competitive coding/after mid/multiply with recursion.cpp | b02749ddf10476d214d0e93961151d31ab049b8a | [] | no_license | Sandipghosh98/My_Programs | 842ac20134d1d0e6e9adb7d1613f8c82d0daa72a | a1a5041628b7d1a47223832c103c83c2a864af34 | refs/heads/master | 2020-06-13T02:33:18.381343 | 2019-06-30T10:26:16 | 2019-06-30T10:26:16 | 194,502,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | #include<bits/stdc++.h>
using namespace std;
//int t=1;
int recu(int x, int n){
int t=1;
//int n;
// n=e/2;
if(n==1){
return x;
}
if(n%2==0){
t=recu(x,n/2)*recu(x,n/2);
}
else{
t=recu(x,n/2)*recu(x,n/2)*x;
// t=t*t;
}
}
int main()
{
int x,n,re;
cin>>n;
cin>>x;
re=recu(x,n);
cout<<re;
}
| [
"sandipghosh8888@gmail"
] | sandipghosh8888@gmail |
cf7222a407783f61c3551fbc48cd4c31f19645cd | e604a604adead7e0684ef2fb1525bd79eccfd804 | /ApprocheFin2/Particule.h | 2e00ae233d659f6055eaa1cc84ef04adbe06b8de | [] | no_license | Deastan/Brownian_movement | 0f6fded7cc633ae740ab6874ae3093342353e03a | 8b96cf293f573f6262340c16f40e93a38c243ee4 | refs/heads/master | 2020-03-12T05:45:15.813801 | 2018-04-21T12:20:49 | 2018-04-21T12:20:49 | 130,470,276 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,873 | h | /**
* \file Particule.h
* \brief Prototype de la classe mère Particule
* \author Emma Geoffray et Jonathan Burkhard
* \version 1.0
* \date avril 2014
*/
#ifndef PRJ_PARTICULE_H
#define PRJ_PARTICULE_H
#include "Vecteur.h"
#include "Dessinable.h"
#include "Enceinte.h"
#include "GenerateurAleatoire.h"
/** \class Particule
* \brief Classe mère dont hérite toutes les classes de type : TXTNom et GLNom
* Représentation d'une particule (ici version graphique)
*
* C'est une classe virtuelle pure, on ne peut donc pas créer d'instances
* de cette classe car il n'est pas logique de créer l'objet générale mais
* plutôt des classes spécialisées. Elle permet d'avoir une structure générale
* et des méthodes que chacunes des particules devra redéfinir.
*/
class Particule : public Dessinable
{
/*================================================================================
* Definition des attributs
*================================================================================*/
protected :
/** Vecteur représentant la position de la particule dans l'enceinte */
Vecteur position;
/** Vecteur représentant la vitesse de la particule */
Vecteur vitesse;
/** Nombre réel représentant la masse de la particule (nécessaire pour le calcul des nouvelles vitesses lors d'une collision) */
double const masse;
/** Nombre réel représentant le rayon de la particule (nécessaire pour déterminer si des particules entrent en collision) */
double const rayon;
/*================================================================================
* Prototypage des constructeurs
*================================================================================*/
public :
/// Constructeur par défaut
Particule();
/// Constructeur
Particule(Vecteur position, Vecteur vitesse, double masse, double rayon);
/// Constructeur
Particule(Enceinte const& enceinte, GenerateurAleatoire& tirage, double temperature, double masse, double rayon);
/*================================================================================
* Prototypage des methodes
*================================================================================*/
/// Permet d'afficher les différents attributs de la particule
std::ostream& afficher(std::ostream& sortie) const;
/// S'occupe de faire évoluer la particule d'un temps dt
virtual void evolue(double dt);
/// Gére les sorties de l'enceinte
void gere_sorties(Enceinte const& enceinte);
/// Calcul le pavage cubique autour d'une particule
Vecteur pavageCubique(double espsilon) const;
/// Effectue la collision de deux particules
void collision(Particule& p, GenerateurAleatoire& tirage);
/// Getter
double get_rayon();
};
/// Surcharge de l'opérateur d'affichage
std::ostream& operator<<(std::ostream& sortie, Particule const& p);
#endif // PRJ_PARTICULE_H
| [
"jonathanburkhard@gmail.com"
] | jonathanburkhard@gmail.com |
9b05b034f3a88abbf13e8de3e116369c61e6bdfc | ac7f34e27f33db5001574104607ebc25a7c9b615 | /problems/12356.cc | cf49db450184aaeffaa07b1062a6a67011f3e0a5 | [] | no_license | albertnez/uva-online-judge | b13c7ebaeffb9ce1345f730c4397b28bc61b65f7 | 7449037f0ca5d297ae5d419d2cc8d9223e171b4b | refs/heads/master | 2016-09-09T22:53:03.178917 | 2015-02-18T01:49:08 | 2015-02-18T01:49:08 | 24,539,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 640 | cc | #include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
typedef pair<int,int> ii;
typedef vector<ii> vii;
int main () {
int s, l;
int left[100002];
int right[100002];
while (scanf("%d %d", &s, &l) and (s|l)) {
//vii v(s+2);
for (int i = 1; i < s+1; ++i) {
left[i] = i-1;
right[i] = i+1;
}
right[0] = 0;
left[s+1] = s+1;
while (l--) {
int x,y;
scanf("%d %d", &x, &y);
right[left[x]] = right[y];
left[right[y]] = left[x];
if (left[x] > 0) printf("%d ", left[x]);
else printf("* ");
if (right[y] < s+1) printf("%d\n", right[y]);
else printf("*\n");
}
printf("-\n");
}
} | [
"albertmg7@gmail.com"
] | albertmg7@gmail.com |
621cdd443744758d23bbfbbf5a1449b3e0072b6b | b0dd7779c225971e71ae12c1093dc75ed9889921 | /boost/spirit/home/support/detail/endian/endian.hpp | c7ecfdbaa7a18c33beeee77cd26688f3d691690a | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 21,123 | hpp | // Boost endian.hpp header file -------------------------------------------------------//
// (C) Copyright Darin Adler 2000
// (C) Copyright Beman Dawes 2006, 2009
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See library home page at http://www.boost.org/libs/endian
//--------------------------------------------------------------------------------------//
// Original design developed by Darin Adler based on classes developed by Mark
// Borgerding. Four original class templates were combined into a single endian
// class template by Beman Dawes, who also added the unrolled_byte_loops sign
// partial specialization to correctly extend the sign when cover integer size
// differs from endian representation size.
// TODO: When a compiler supporting constexpr becomes available, try possible uses.
#ifndef BOOST_SPIRIT_ENDIAN_HPP
#define BOOST_SPIRIT_ENDIAN_HPP
#if defined(_MSC_VER)
#pragma once
#endif
#ifdef BOOST_ENDIAN_LOG
# include <iostream>
#endif
#if defined(__BORLANDC__) || defined( __CODEGEARC__)
# pragma pack(push, 1)
#endif
#include <boost/config.hpp>
#include <boost/detail/endian.hpp>
#define BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#define BOOST_NO_IO_COVER_OPERATORS
#include <boost/spirit/home/support/detail/endian/cover_operators.hpp>
#undef BOOST_NO_IO_COVER_OPERATORS
#undef BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#include <boost/type_traits/is_signed.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>
#include <boost/spirit/home/support/detail/scoped_enum_emulation.hpp>
#include <iosfwd>
#include <climits>
# if CHAR_BIT != 8
# error Platforms with CHAR_BIT != 8 are not supported
# endif
# define BOOST_ENDIAN_DEFAULT_CONSTRUCT {} // C++03
# if defined(BOOST_ENDIAN_FORCE_PODNESS)
# define BOOST_ENDIAN_NO_CTORS
# endif
namespace boost { namespace spirit
{
namespace detail
{
// Unrolled loops for loading and storing streams of bytes.
template <typename T, std::size_t n_bytes,
bool sign=boost::is_signed<T>::value >
struct unrolled_byte_loops
{
typedef unrolled_byte_loops<T, n_bytes - 1, sign> next;
static T load_big(const unsigned char* bytes)
{ return *(bytes - 1) | (next::load_big(bytes - 1) << 8); }
static T load_little(const unsigned char* bytes)
{ return *bytes | (next::load_little(bytes + 1) << 8); }
static void store_big(char* bytes, T value)
{
*(bytes - 1) = static_cast<char>(value);
next::store_big(bytes - 1, value >> 8);
}
static void store_little(char* bytes, T value)
{
*bytes = static_cast<char>(value);
next::store_little(bytes + 1, value >> 8);
}
};
template <typename T>
struct unrolled_byte_loops<T, 1, false>
{
static T load_big(const unsigned char* bytes)
{ return *(bytes - 1); }
static T load_little(const unsigned char* bytes)
{ return *bytes; }
static void store_big(char* bytes, T value)
{ *(bytes - 1) = static_cast<char>(value); }
static void store_little(char* bytes, T value)
{ *bytes = static_cast<char>(value); }
};
template <typename T>
struct unrolled_byte_loops<T, 1, true>
{
static T load_big(const unsigned char* bytes)
{ return *reinterpret_cast<const signed char*>(bytes - 1); }
static T load_little(const unsigned char* bytes)
{ return *reinterpret_cast<const signed char*>(bytes); }
static void store_big(char* bytes, T value)
{ *(bytes - 1) = static_cast<char>(value); }
static void store_little(char* bytes, T value)
{ *bytes = static_cast<char>(value); }
};
template <typename T, std::size_t n_bytes>
inline
T load_big_endian(const void* bytes)
{
return unrolled_byte_loops<T, n_bytes>::load_big
(static_cast<const unsigned char*>(bytes) + n_bytes);
}
template <>
inline
float load_big_endian<float, 4>(const void* bytes)
{
const unsigned char *b = reinterpret_cast<const unsigned char *>(
bytes);
b += 3;
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for(std::size_t i = 0; i < 4; ++i)
{
*v++ = *b--;
}
return value;
}
template <>
inline
double load_big_endian<double, 8>(const void* bytes)
{
const unsigned char *b = reinterpret_cast<const unsigned char *>(
bytes);
b += 7;
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for(std::size_t i = 0; i < 8; ++i)
{
*v++ = *b--;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline
T load_little_endian(const void* bytes)
{
return unrolled_byte_loops<T, n_bytes>::load_little
(static_cast<const unsigned char*>(bytes));
}
template <>
inline
float load_little_endian<float, 4>(const void* bytes)
{
const unsigned char *b = reinterpret_cast<const unsigned char *>(
bytes);
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for(std::size_t i = 0; i < 4; ++i)
{
*v++ = *b++;
}
return value;
}
template <>
inline
double load_little_endian<double, 8>(const void* bytes)
{
const unsigned char *b = reinterpret_cast<const unsigned char *>(
bytes);
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for(std::size_t i = 0; i < 8; ++i)
{
*v++ = *b++;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline
void store_big_endian(void* bytes, T value)
{
unrolled_byte_loops<T, n_bytes>::store_big
(static_cast<char*>(bytes) + n_bytes, value);
}
template <>
inline
void store_big_endian<float, 4>(void* bytes, float value)
{
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 3;
const unsigned char *v = reinterpret_cast<const unsigned char *>(
&value);
for(std::size_t i = 0; i < 4; ++i)
{
*b-- = *v++;
}
}
template <>
inline
void store_big_endian<double, 8>(void* bytes, double value)
{
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 7;
const unsigned char *v = reinterpret_cast<const unsigned char *>(
&value);
for(std::size_t i = 0; i < 8; ++i)
{
*b-- = *v++;
}
}
template <typename T, std::size_t n_bytes>
inline
void store_little_endian(void* bytes, T value)
{
unrolled_byte_loops<T, n_bytes>::store_little
(static_cast<char*>(bytes), value);
}
template <>
inline
void store_little_endian<float, 4>(void* bytes, float value)
{
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(
&value);
for(std::size_t i = 0; i < 4; ++i)
{
*b++ = *v++;
}
}
template <>
inline
void store_little_endian<double, 8>(void* bytes, double value)
{
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(
&value);
for(std::size_t i = 0; i < 8; ++i)
{
*b++ = *v++;
}
}
} // namespace detail
namespace endian
{
# ifdef BOOST_ENDIAN_LOG
bool endian_log(true);
# endif
// endian class template and specializations ---------------------------------------//
BOOST_SCOPED_ENUM_START(endianness) { big, little, native }; BOOST_SCOPED_ENUM_END
BOOST_SCOPED_ENUM_START(alignment) { unaligned, aligned }; BOOST_SCOPED_ENUM_END
template <BOOST_SCOPED_ENUM(endianness) E, typename T, std::size_t n_bits,
BOOST_SCOPED_ENUM(alignment) A = alignment::unaligned>
class endian;
// Specializations that represent unaligned bytes.
// Taking an integer type as a parameter provides a nice way to pass both
// the size and signedness of the desired integer and get the appropriate
// corresponding integer type for the interface.
// unaligned big endian specialization
template <typename T, std::size_t n_bits>
class endian< endianness::big, T, n_bits, alignment::unaligned >
: cover_operators< endian< endianness::big, T, n_bits >, T >
{
BOOST_STATIC_ASSERT( (n_bits/8)*8 == n_bits );
public:
typedef T value_type;
# ifndef BOOST_ENDIAN_NO_CTORS
endian() BOOST_ENDIAN_DEFAULT_CONSTRUCT
explicit endian(T val)
{
# ifdef BOOST_ENDIAN_LOG
if ( endian_log )
std::clog << "big, unaligned, " << n_bits << "-bits, construct(" << val << ")\n";
# endif
detail::store_big_endian<T, n_bits/8>(m_value, val);
}
# endif
endian & operator=(T val) { detail::store_big_endian<T, n_bits/8>(m_value, val); return *this; }
operator T() const
{
# ifdef BOOST_ENDIAN_LOG
if ( endian_log )
std::clog << "big, unaligned, " << n_bits << "-bits, convert(" << detail::load_big_endian<T, n_bits/8>(m_value) << ")\n";
# endif
return detail::load_big_endian<T, n_bits/8>(m_value);
}
private:
char m_value[n_bits/8];
};
// unaligned little endian specialization
template <typename T, std::size_t n_bits>
class endian< endianness::little, T, n_bits, alignment::unaligned >
: cover_operators< endian< endianness::little, T, n_bits >, T >
{
BOOST_STATIC_ASSERT( (n_bits/8)*8 == n_bits );
public:
typedef T value_type;
# ifndef BOOST_ENDIAN_NO_CTORS
endian() BOOST_ENDIAN_DEFAULT_CONSTRUCT
explicit endian(T val)
{
# ifdef BOOST_ENDIAN_LOG
if ( endian_log )
std::clog << "little, unaligned, " << n_bits << "-bits, construct(" << val << ")\n";
# endif
detail::store_little_endian<T, n_bits/8>(m_value, val);
}
# endif
endian & operator=(T val) { detail::store_little_endian<T, n_bits/8>(m_value, val); return *this; }
operator T() const
{
# ifdef BOOST_ENDIAN_LOG
if ( endian_log )
std::clog << "little, unaligned, " << n_bits << "-bits, convert(" << detail::load_little_endian<T, n_bits/8>(m_value) << ")\n";
# endif
return detail::load_little_endian<T, n_bits/8>(m_value);
}
private:
char m_value[n_bits/8];
};
// unaligned native endian specialization
template <typename T, std::size_t n_bits>
class endian< endianness::native, T, n_bits, alignment::unaligned >
: cover_operators< endian< endianness::native, T, n_bits >, T >
{
BOOST_STATIC_ASSERT( (n_bits/8)*8 == n_bits );
public:
typedef T value_type;
# ifndef BOOST_ENDIAN_NO_CTORS
endian() BOOST_ENDIAN_DEFAULT_CONSTRUCT
# ifdef BOOST_BIG_ENDIAN
explicit endian(T val) { detail::store_big_endian<T, n_bits/8>(m_value, val); }
# else
explicit endian(T val) { detail::store_little_endian<T, n_bits/8>(m_value, val); }
# endif
# endif
# ifdef BOOST_BIG_ENDIAN
endian & operator=(T val) { detail::store_big_endian<T, n_bits/8>(m_value, val); return *this; }
operator T() const { return detail::load_big_endian<T, n_bits/8>(m_value); }
# else
endian & operator=(T val) { detail::store_little_endian<T, n_bits/8>(m_value, val); return *this; }
operator T() const { return detail::load_little_endian<T, n_bits/8>(m_value); }
# endif
private:
char m_value[n_bits/8];
};
// Specializations that mimic built-in integer types.
// These typically have the same alignment as the underlying types.
// aligned big endian specialization
template <typename T, std::size_t n_bits>
class endian< endianness::big, T, n_bits, alignment::aligned >
: cover_operators< endian< endianness::big, T, n_bits, alignment::aligned >, T >
{
BOOST_STATIC_ASSERT( (n_bits/8)*8 == n_bits );
BOOST_STATIC_ASSERT( sizeof(T) == n_bits/8 );
public:
typedef T value_type;
# ifndef BOOST_ENDIAN_NO_CTORS
endian() BOOST_ENDIAN_DEFAULT_CONSTRUCT
# ifdef BOOST_BIG_ENDIAN
endian(T val) : m_value(val) { }
# else
explicit endian(T val) { detail::store_big_endian<T, sizeof(T)>(&m_value, val); }
# endif
# endif
# ifdef BOOST_BIG_ENDIAN
endian & operator=(T val) { m_value = val; return *this; }
operator T() const { return m_value; }
# else
endian & operator=(T val) { detail::store_big_endian<T, sizeof(T)>(&m_value, val); return *this; }
operator T() const { return detail::load_big_endian<T, sizeof(T)>(&m_value); }
# endif
private:
T m_value;
};
// aligned little endian specialization
template <typename T, std::size_t n_bits>
class endian< endianness::little, T, n_bits, alignment::aligned >
: cover_operators< endian< endianness::little, T, n_bits, alignment::aligned >, T >
{
BOOST_STATIC_ASSERT( (n_bits/8)*8 == n_bits );
BOOST_STATIC_ASSERT( sizeof(T) == n_bits/8 );
public:
typedef T value_type;
# ifndef BOOST_ENDIAN_NO_CTORS
endian() BOOST_ENDIAN_DEFAULT_CONSTRUCT
# ifdef BOOST_LITTLE_ENDIAN
endian(T val) : m_value(val) { }
# else
explicit endian(T val) { detail::store_little_endian<T, sizeof(T)>(&m_value, val); }
# endif
# endif
# ifdef BOOST_LITTLE_ENDIAN
endian & operator=(T val) { m_value = val; return *this; }
operator T() const { return m_value; }
#else
endian & operator=(T val) { detail::store_little_endian<T, sizeof(T)>(&m_value, val); return *this; }
operator T() const { return detail::load_little_endian<T, sizeof(T)>(&m_value); }
#endif
private:
T m_value;
};
// naming convention typedefs ------------------------------------------------------//
// unaligned big endian signed integer types
typedef endian< endianness::big, int_least8_t, 8 > big8_t;
typedef endian< endianness::big, int_least16_t, 16 > big16_t;
typedef endian< endianness::big, int_least32_t, 24 > big24_t;
typedef endian< endianness::big, int_least32_t, 32 > big32_t;
typedef endian< endianness::big, int_least64_t, 40 > big40_t;
typedef endian< endianness::big, int_least64_t, 48 > big48_t;
typedef endian< endianness::big, int_least64_t, 56 > big56_t;
typedef endian< endianness::big, int_least64_t, 64 > big64_t;
// unaligned big endian unsigned integer types
typedef endian< endianness::big, uint_least8_t, 8 > ubig8_t;
typedef endian< endianness::big, uint_least16_t, 16 > ubig16_t;
typedef endian< endianness::big, uint_least32_t, 24 > ubig24_t;
typedef endian< endianness::big, uint_least32_t, 32 > ubig32_t;
typedef endian< endianness::big, uint_least64_t, 40 > ubig40_t;
typedef endian< endianness::big, uint_least64_t, 48 > ubig48_t;
typedef endian< endianness::big, uint_least64_t, 56 > ubig56_t;
typedef endian< endianness::big, uint_least64_t, 64 > ubig64_t;
// unaligned little endian signed integer types
typedef endian< endianness::little, int_least8_t, 8 > little8_t;
typedef endian< endianness::little, int_least16_t, 16 > little16_t;
typedef endian< endianness::little, int_least32_t, 24 > little24_t;
typedef endian< endianness::little, int_least32_t, 32 > little32_t;
typedef endian< endianness::little, int_least64_t, 40 > little40_t;
typedef endian< endianness::little, int_least64_t, 48 > little48_t;
typedef endian< endianness::little, int_least64_t, 56 > little56_t;
typedef endian< endianness::little, int_least64_t, 64 > little64_t;
// unaligned little endian unsigned integer types
typedef endian< endianness::little, uint_least8_t, 8 > ulittle8_t;
typedef endian< endianness::little, uint_least16_t, 16 > ulittle16_t;
typedef endian< endianness::little, uint_least32_t, 24 > ulittle24_t;
typedef endian< endianness::little, uint_least32_t, 32 > ulittle32_t;
typedef endian< endianness::little, uint_least64_t, 40 > ulittle40_t;
typedef endian< endianness::little, uint_least64_t, 48 > ulittle48_t;
typedef endian< endianness::little, uint_least64_t, 56 > ulittle56_t;
typedef endian< endianness::little, uint_least64_t, 64 > ulittle64_t;
// unaligned native endian signed integer types
typedef endian< endianness::native, int_least8_t, 8 > native8_t;
typedef endian< endianness::native, int_least16_t, 16 > native16_t;
typedef endian< endianness::native, int_least32_t, 24 > native24_t;
typedef endian< endianness::native, int_least32_t, 32 > native32_t;
typedef endian< endianness::native, int_least64_t, 40 > native40_t;
typedef endian< endianness::native, int_least64_t, 48 > native48_t;
typedef endian< endianness::native, int_least64_t, 56 > native56_t;
typedef endian< endianness::native, int_least64_t, 64 > native64_t;
// unaligned native endian unsigned integer types
typedef endian< endianness::native, uint_least8_t, 8 > unative8_t;
typedef endian< endianness::native, uint_least16_t, 16 > unative16_t;
typedef endian< endianness::native, uint_least32_t, 24 > unative24_t;
typedef endian< endianness::native, uint_least32_t, 32 > unative32_t;
typedef endian< endianness::native, uint_least64_t, 40 > unative40_t;
typedef endian< endianness::native, uint_least64_t, 48 > unative48_t;
typedef endian< endianness::native, uint_least64_t, 56 > unative56_t;
typedef endian< endianness::native, uint_least64_t, 64 > unative64_t;
#define BOOST_HAS_INT16_T
#define BOOST_HAS_INT32_T
#define BOOST_HAS_INT64_T
// These types only present if platform has exact size integers:
// aligned big endian signed integer types
// aligned big endian unsigned integer types
// aligned little endian signed integer types
// aligned little endian unsigned integer types
// aligned native endian typedefs are not provided because
// <cstdint> types are superior for this use case
# if defined(BOOST_HAS_INT16_T)
typedef endian< endianness::big, int16_t, 16, alignment::aligned > aligned_big16_t;
typedef endian< endianness::big, uint16_t, 16, alignment::aligned > aligned_ubig16_t;
typedef endian< endianness::little, int16_t, 16, alignment::aligned > aligned_little16_t;
typedef endian< endianness::little, uint16_t, 16, alignment::aligned > aligned_ulittle16_t;
# endif
# if defined(BOOST_HAS_INT32_T)
typedef endian< endianness::big, int32_t, 32, alignment::aligned > aligned_big32_t;
typedef endian< endianness::big, uint32_t, 32, alignment::aligned > aligned_ubig32_t;
typedef endian< endianness::little, int32_t, 32, alignment::aligned > aligned_little32_t;
typedef endian< endianness::little, uint32_t, 32, alignment::aligned > aligned_ulittle32_t;
# endif
# if defined(BOOST_HAS_INT64_T)
typedef endian< endianness::big, int64_t, 64, alignment::aligned > aligned_big64_t;
typedef endian< endianness::big, uint64_t, 64, alignment::aligned > aligned_ubig64_t;
typedef endian< endianness::little, int64_t, 64, alignment::aligned > aligned_little64_t;
typedef endian< endianness::little, uint64_t, 64, alignment::aligned > aligned_ulittle64_t;
# endif
} // namespace endian
}} // namespace boost::spirit
// import the namespace above into boost::endian
namespace boost { namespace endian
{
using namespace boost::spirit::endian;
}}
#if defined(__BORLANDC__) || defined( __CODEGEARC__)
# pragma pack(pop)
#endif
#endif // BOOST_SPIRIT_ENDIAN_HPP
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
58c45423e9a1552ec0234b87e5e85ea97ffdd256 | f6a06e69f756ca8b7c3c692fdb88432e00113893 | /ExchangeChannelsDlg.cpp | f1c26263d81c0702f2c9faaee6ec583f506ac956 | [
"MIT"
] | permissive | HeikoPlate/psruti | 0aea193e8856b19e0003407e2151f67edb43a09b | ccc96780bc0f47594184f7a051fac419d41d25ed | refs/heads/main | 2023-01-19T02:13:23.555002 | 2020-11-21T14:30:07 | 2020-11-21T14:30:07 | 314,814,594 | 3 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 14,821 | cpp | // ExchangeChannelsDlg.cpp: Implementierungsdatei
//
#include "stdafx.h"
#include "psruti.h"
#include "ExchangeChannelsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// Dialogfeld ExchangeChannelsDlg
ExchangeChannelsDlg::ExchangeChannelsDlg(CWnd* pParent /*=NULL*/)
: CDialog(ExchangeChannelsDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(ExchangeChannelsDlg)
// HINWEIS: Der Klassen-Assistent fügt hier Elementinitialisierung ein
//}}AFX_DATA_INIT
int i;
source_check[0] = &m_source_1;
source_check[1] = &m_source_2;
source_check[2] = &m_source_3;
source_check[3] = &m_source_4;
source_check[4] = &m_source_5;
source_check[5] = &m_source_6;
source_check[6] = &m_source_7;
source_check[7] = &m_source_8;
source_check[8] = &m_source_9;
source_check[9] = &m_source_10;
source_check[10] = &m_source_11;
source_check[11] = &m_source_12;
source_check[12] = &m_source_13;
source_check[13] = &m_source_14;
source_check[14] = &m_source_15;
source_check[15] = &m_source_16;
dest_check[0] = &m_dest_1;
dest_check[1] = &m_dest_2;
dest_check[2] = &m_dest_3;
dest_check[3] = &m_dest_4;
dest_check[4] = &m_dest_5;
dest_check[5] = &m_dest_6;
dest_check[6] = &m_dest_7;
dest_check[7] = &m_dest_8;
dest_check[8] = &m_dest_9;
dest_check[9] = &m_dest_10;
dest_check[10]= &m_dest_11;
dest_check[11]= &m_dest_12;
dest_check[12]= &m_dest_13;
dest_check[13]= &m_dest_14;
dest_check[14]= &m_dest_15;
dest_check[15]= &m_dest_16;
// inializes membervariable list m_voice_type
m_voice_type[0] = &m_channel_patch1;
m_voice_type[1] = &m_channel_patch2;
m_voice_type[2] = &m_channel_patch3;
m_voice_type[3] = &m_channel_patch4;
m_voice_type[4] = &m_channel_patch5;
m_voice_type[5] = &m_channel_patch6;
m_voice_type[6] = &m_channel_patch7;
m_voice_type[7] = &m_channel_patch8;
m_voice_type[8] = &m_channel_patch9;
m_voice_type[9] = &m_channel_patch10;
m_voice_type[10] = &m_channel_patch11;
m_voice_type[11] = &m_channel_patch12;
m_voice_type[12] = &m_channel_patch13;
m_voice_type[13] = &m_channel_patch14;
m_voice_type[14] = &m_channel_patch15;
m_voice_type[15] = &m_channel_patch16;
m_pToolTip = NULL;
idc_voice_name[0] = IDC_CHANNEL_PATCH_1;
idc_voice_name[1] = IDC_CHANNEL_PATCH_2;
idc_voice_name[2] = IDC_CHANNEL_PATCH_3;
idc_voice_name[3] = IDC_CHANNEL_PATCH_4;
idc_voice_name[4] = IDC_CHANNEL_PATCH_5;
idc_voice_name[5] = IDC_CHANNEL_PATCH_6;
idc_voice_name[6] = IDC_CHANNEL_PATCH_7;
idc_voice_name[7] = IDC_CHANNEL_PATCH_8;
idc_voice_name[8] = IDC_CHANNEL_PATCH_9;
idc_voice_name[9] = IDC_CHANNEL_PATCH_10;
idc_voice_name[10] = IDC_CHANNEL_PATCH_11;
idc_voice_name[11] = IDC_CHANNEL_PATCH_12;
idc_voice_name[12] = IDC_CHANNEL_PATCH_13;
idc_voice_name[13] = IDC_CHANNEL_PATCH_14;
idc_voice_name[14] = IDC_CHANNEL_PATCH_15;
idc_voice_name[15] = IDC_CHANNEL_PATCH_16;
selection = NONE_SELECTED;
for (i=0; i<16; i++)
{
source_channels[i] = false;
}
dest_channel = -1;
}
void ExchangeChannelsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(ExchangeChannelsDlg)
DDX_Control(pDX, IDC_CHANNEL_PATCH_1, m_channel_patch1);
DDX_Control(pDX, IDC_CHANNEL_PATCH_2, m_channel_patch2);
DDX_Control(pDX, IDC_CHANNEL_PATCH_3, m_channel_patch3);
DDX_Control(pDX, IDC_CHANNEL_PATCH_4, m_channel_patch4);
DDX_Control(pDX, IDC_CHANNEL_PATCH_5, m_channel_patch5);
DDX_Control(pDX, IDC_CHANNEL_PATCH_6, m_channel_patch6);
DDX_Control(pDX, IDC_CHANNEL_PATCH_7, m_channel_patch7);
DDX_Control(pDX, IDC_CHANNEL_PATCH_8, m_channel_patch8);
DDX_Control(pDX, IDC_CHANNEL_PATCH_9, m_channel_patch9);
DDX_Control(pDX, IDC_CHANNEL_PATCH_10, m_channel_patch10);
DDX_Control(pDX, IDC_CHANNEL_PATCH_11, m_channel_patch11);
DDX_Control(pDX, IDC_CHANNEL_PATCH_12, m_channel_patch12);
DDX_Control(pDX, IDC_CHANNEL_PATCH_13, m_channel_patch13);
DDX_Control(pDX, IDC_CHANNEL_PATCH_14, m_channel_patch14);
DDX_Control(pDX, IDC_CHANNEL_PATCH_15, m_channel_patch15);
DDX_Control(pDX, IDC_CHANNEL_PATCH_16, m_channel_patch16);
DDX_Control(pDX, IDC_SOURCE_1, m_source_1);
DDX_Control(pDX, IDC_SOURCE_2, m_source_2);
DDX_Control(pDX, IDC_SOURCE_3, m_source_3);
DDX_Control(pDX, IDC_SOURCE_4, m_source_4);
DDX_Control(pDX, IDC_SOURCE_5, m_source_5);
DDX_Control(pDX, IDC_SOURCE_6, m_source_6);
DDX_Control(pDX, IDC_SOURCE_7, m_source_7);
DDX_Control(pDX, IDC_SOURCE_8, m_source_8);
DDX_Control(pDX, IDC_SOURCE_9, m_source_9);
DDX_Control(pDX, IDC_SOURCE_10, m_source_10);
DDX_Control(pDX, IDC_SOURCE_11, m_source_11);
DDX_Control(pDX, IDC_SOURCE_12, m_source_12);
DDX_Control(pDX, IDC_SOURCE_13, m_source_13);
DDX_Control(pDX, IDC_SOURCE_14, m_source_14);
DDX_Control(pDX, IDC_SOURCE_15, m_source_15);
DDX_Control(pDX, IDC_SOURCE_16, m_source_16);
DDX_Control(pDX, IDC_DEST_1, m_dest_1);
DDX_Control(pDX, IDC_DEST_2, m_dest_2);
DDX_Control(pDX, IDC_DEST_3, m_dest_3);
DDX_Control(pDX, IDC_DEST_4, m_dest_4);
DDX_Control(pDX, IDC_DEST_5, m_dest_5);
DDX_Control(pDX, IDC_DEST_6, m_dest_6);
DDX_Control(pDX, IDC_DEST_7, m_dest_7);
DDX_Control(pDX, IDC_DEST_8, m_dest_8);
DDX_Control(pDX, IDC_DEST_9, m_dest_9);
DDX_Control(pDX, IDC_DEST_10, m_dest_10);
DDX_Control(pDX, IDC_DEST_11, m_dest_11);
DDX_Control(pDX, IDC_DEST_12, m_dest_12);
DDX_Control(pDX, IDC_DEST_13, m_dest_13);
DDX_Control(pDX, IDC_DEST_14, m_dest_14);
DDX_Control(pDX, IDC_DEST_15, m_dest_15);
DDX_Control(pDX, IDC_DEST_16, m_dest_16);
DDX_Control(pDX, IDC_LIST_COPY_EXCHANGE, m_list_copy_exchange);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(ExchangeChannelsDlg, CDialog)
//{{AFX_MSG_MAP(ExchangeChannelsDlg)
ON_LBN_SELCHANGE(IDC_LIST_COPY_EXCHANGE, OnSelchangeListCopyExchange)
ON_BN_CLICKED(IDC_SOURCE_1, OnSource1)
ON_BN_CLICKED(IDC_SOURCE_2, OnSource2)
ON_BN_CLICKED(IDC_SOURCE_3, OnSource3)
ON_BN_CLICKED(IDC_SOURCE_4, OnSource4)
ON_BN_CLICKED(IDC_SOURCE_5, OnSource5)
ON_BN_CLICKED(IDC_SOURCE_6, OnSource6)
ON_BN_CLICKED(IDC_SOURCE_7, OnSource7)
ON_BN_CLICKED(IDC_SOURCE_8, OnSource8)
ON_BN_CLICKED(IDC_SOURCE_9, OnSource9)
ON_BN_CLICKED(IDC_SOURCE_10, OnSource10)
ON_BN_CLICKED(IDC_SOURCE_11, OnSource11)
ON_BN_CLICKED(IDC_SOURCE_12, OnSource12)
ON_BN_CLICKED(IDC_SOURCE_13, OnSource13)
ON_BN_CLICKED(IDC_SOURCE_14, OnSource14)
ON_BN_CLICKED(IDC_SOURCE_15, OnSource15)
ON_BN_CLICKED(IDC_SOURCE_16, OnSource16)
ON_BN_CLICKED(IDC_DEST_1, OnDest1)
ON_BN_CLICKED(IDC_DEST_2, OnDest2)
ON_BN_CLICKED(IDC_DEST_3, OnDest3)
ON_BN_CLICKED(IDC_DEST_4, OnDest4)
ON_BN_CLICKED(IDC_DEST_5, OnDest5)
ON_BN_CLICKED(IDC_DEST_6, OnDest6)
ON_BN_CLICKED(IDC_DEST_7, OnDest7)
ON_BN_CLICKED(IDC_DEST_8, OnDest8)
ON_BN_CLICKED(IDC_DEST_9, OnDest9)
ON_BN_CLICKED(IDC_DEST_10, OnDest10)
ON_BN_CLICKED(IDC_DEST_11, OnDest11)
ON_BN_CLICKED(IDC_DEST_12, OnDest12)
ON_BN_CLICKED(IDC_DEST_13, OnDest13)
ON_BN_CLICKED(IDC_DEST_14, OnDest14)
ON_BN_CLICKED(IDC_DEST_15, OnDest15)
ON_BN_CLICKED(IDC_DEST_16, OnDest16)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Behandlungsroutinen für Nachrichten ExchangeChannelsDlg
void ExchangeChannelsDlg::OnOK()
{
bool is_source_selected = false;
int i;
for (i=0; i<16;i++)
{
if (source_channels[i])
{
is_source_selected = true;
break;
}
}
if (selection==NONE_SELECTED)
{
::MessageBox(AfxGetMainWnd()->m_hWnd,GlobalUtilities::get_resource_string(IDS_SELECT_FUNCTION),NULL,MB_OK|MB_TASKMODAL);
return;
}
if (!is_source_selected)
{
::MessageBox(AfxGetMainWnd()->m_hWnd,GlobalUtilities::get_resource_string(IDS_SELECT_SOURCE_CHANNEL),NULL,MB_OK|MB_TASKMODAL);
return;
}
if (((selection==CUT_COPY_SELECTED) ||
(selection==EXCHANGE_SELECTED)||
(selection==COPY_SELECTED)) &&
dest_channel==-1)
{
::MessageBox(AfxGetMainWnd()->m_hWnd,GlobalUtilities::get_resource_string(IDS_SELECT_DESTINATION_CHANNEL),NULL,MB_OK|MB_TASKMODAL);
return;
}
if (((selection==CUT_COPY_SELECTED)||(selection==COPY_SELECTED))&&
(!(hpmfi->mute)[dest_channel]))
{
if (IDYES != AfxMessageBox(GlobalUtilities::get_resource_string(IDS_OVERWRITE_DESTINATION_CHANNEL),MB_YESNO,0))
{
return;
}
}
if (m_pToolTip != NULL)
{
delete m_pToolTip;
m_pToolTip = NULL;
}
EndDialog(1);
}
void ExchangeChannelsDlg::OnCancel()
{
if (m_pToolTip != NULL)
{
delete m_pToolTip;
m_pToolTip = NULL;
}
EndDialog(0);
}
BOOL ExchangeChannelsDlg::PreTranslateMessage(MSG* pMsg)
{
if (NULL != m_pToolTip)
{
m_pToolTip->RelayEvent(pMsg);
}
return CDialog::PreTranslateMessage(pMsg);
}
BOOL ExchangeChannelsDlg::OnInitDialog()
{
int chan;
CDialog::OnInitDialog();
CString delete_channel = GlobalUtilities::get_resource_string(IDS_DELETE_CHANNEL);
CString exchange_channels = GlobalUtilities::get_resource_string(IDS_EXCHANGE_CHANNELS);
CString cut_copy_channel = GlobalUtilities::get_resource_string(IDS_CUT_COPY_CHANNEL);
CString double_channel = GlobalUtilities::get_resource_string(IDS_DOUBLE_CHANNEL);
m_list_copy_exchange.AddString(delete_channel);
m_list_copy_exchange.AddString(exchange_channels);
m_list_copy_exchange.AddString(cut_copy_channel);
m_list_copy_exchange.AddString(double_channel);
int i;
for (i=0; i<16; i++)
{
if (!(hpmfi->mute)[i])
{
SetDlgItemText(idc_voice_name[i],(hpmfi->patchname)[i]);
}
else
{
SetDlgItemText(idc_voice_name[i],"");
}
source_check[i]->EnableWindow(FALSE);
dest_check[i]->EnableWindow(FALSE);
}
// Tool Tips
if (hpmfi->with_insdef)
{
m_pToolTip = new CToolTipCtrl;
m_pToolTip->Create(this);
m_pToolTip->SetDelayTime(TTDT_AUTOPOP,4000);
m_pToolTip->SetMaxTipWidth(200);
for (chan=0; chan<16; chan++)
{
if ((hpmfi->mlv_list[chan]).voicename == "") continue;
m_pToolTip->AddTool(m_voice_type[chan],(hpmfi->mlv_list[chan]).voicename);
}
m_pToolTip->Activate(true);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX-Eigenschaftenseiten sollten FALSE zurückgeben
}
void ExchangeChannelsDlg::OnSelchangeListCopyExchange()
{
int i;
for (i=0; i<16; i++)
{
source_check[i]->SetCheck(0);
dest_check[i]->SetCheck(0);
if (!(hpmfi->mute)[i])
{
source_check[i]->EnableWindow(TRUE);
}
}
selection = m_list_copy_exchange.GetCurSel();
if (selection == EXCHANGE_SELECTED)
{
for (i=0; i<16; i++)
{
dest_check[i]->SetCheck(0);
if (!(hpmfi->mute)[i] && ((i!=9)||hpmfi->with_xg_on))
{
dest_check[i]->EnableWindow(TRUE);
}
}
}
else
if ((selection == CUT_COPY_SELECTED) ||
(selection == COPY_SELECTED))
{
for (i=0; i<16; i++)
{
dest_check[i]->EnableWindow(((i==9)&&!hpmfi->with_xg_on)?FALSE:TRUE);
}
}
else
if (selection == DELETE_SELECTED)
{
for (i=0; i<16; i++)
{
dest_check[i]->EnableWindow(FALSE);
source_channels[i] = false;
}
}
}
void ExchangeChannelsDlg::SourceClicked(int chan, int checked)
{
int i;
if (selection !=DELETE_SELECTED)
{
if (checked==1)
{
for (i=0; i<16; i++)
{
if (i==chan) continue;
source_check[i]->SetCheck(0);
source_channels[i] = false;
}
source_channels[chan] = true;
}
else
{
for (i=0; i<16; i++)
{
source_check[i]->SetCheck(0);
}
source_channels[chan] = false;
}
if ((source_channels[chan]) && (dest_channel==chan))
{
source_check[chan]->SetCheck(0);
source_channels[chan] = false;
}
}
else
{ // DELETE_SELECTED
source_channels[chan] = (checked==1);
}
}
void ExchangeChannelsDlg::OnSource1()
{
SourceClicked(0,source_check[0]->GetCheck());
}
void ExchangeChannelsDlg::OnSource2()
{
SourceClicked(1,source_check[1]->GetCheck());
}
void ExchangeChannelsDlg::OnSource3()
{
SourceClicked(2,source_check[2]->GetCheck());
}
void ExchangeChannelsDlg::OnSource4()
{
SourceClicked(3,source_check[3]->GetCheck());
}
void ExchangeChannelsDlg::OnSource5()
{
SourceClicked(4,source_check[4]->GetCheck());
}
void ExchangeChannelsDlg::OnSource6()
{
SourceClicked(5,source_check[5]->GetCheck());
}
void ExchangeChannelsDlg::OnSource7()
{
SourceClicked(6,source_check[6]->GetCheck());
}
void ExchangeChannelsDlg::OnSource8()
{
SourceClicked(7,source_check[7]->GetCheck());
}
void ExchangeChannelsDlg::OnSource9()
{
SourceClicked(8,source_check[8]->GetCheck());
}
void ExchangeChannelsDlg::OnSource10()
{
SourceClicked(9,source_check[9]->GetCheck());
}
void ExchangeChannelsDlg::OnSource11()
{
SourceClicked(10,source_check[10]->GetCheck());
}
void ExchangeChannelsDlg::OnSource12()
{
SourceClicked(11,source_check[11]->GetCheck());
}
void ExchangeChannelsDlg::OnSource13()
{
SourceClicked(12,source_check[12]->GetCheck());
}
void ExchangeChannelsDlg::OnSource14()
{
SourceClicked(13,source_check[13]->GetCheck());
}
void ExchangeChannelsDlg::OnSource15()
{
SourceClicked(14,source_check[14]->GetCheck());
}
void ExchangeChannelsDlg::OnSource16()
{
SourceClicked(15,source_check[15]->GetCheck());
}
void ExchangeChannelsDlg::DestClicked(int chan, int checked)
{
int i;
if (checked==1)
{
for (i=0; i<16; i++)
{
if (i==chan) continue;
dest_check[i]->SetCheck(0);
}
dest_channel = chan;
}
else
{
dest_channel = -1;
}
if ((dest_channel==chan) && (source_channels[chan]))
{
dest_check[chan]->SetCheck(0);
dest_channel = -1;
}
}
void ExchangeChannelsDlg::OnDest1()
{
DestClicked(0,dest_check[0]->GetCheck());
}
void ExchangeChannelsDlg::OnDest2()
{
DestClicked(1,dest_check[1]->GetCheck());
}
void ExchangeChannelsDlg::OnDest3()
{
DestClicked(2,dest_check[2]->GetCheck());
}
void ExchangeChannelsDlg::OnDest4()
{
DestClicked(3,dest_check[3]->GetCheck());
}
void ExchangeChannelsDlg::OnDest5()
{
DestClicked(4,dest_check[4]->GetCheck());
}
void ExchangeChannelsDlg::OnDest6()
{
DestClicked(5,dest_check[5]->GetCheck());
}
void ExchangeChannelsDlg::OnDest7()
{
DestClicked(6,dest_check[6]->GetCheck());
}
void ExchangeChannelsDlg::OnDest8()
{
DestClicked(7,dest_check[7]->GetCheck());
}
void ExchangeChannelsDlg::OnDest9()
{
DestClicked(8,dest_check[8]->GetCheck());
}
void ExchangeChannelsDlg::OnDest10()
{
DestClicked(9,dest_check[9]->GetCheck());
}
void ExchangeChannelsDlg::OnDest11()
{
DestClicked(10,dest_check[10]->GetCheck());
}
void ExchangeChannelsDlg::OnDest12()
{
DestClicked(11,dest_check[11]->GetCheck());
}
void ExchangeChannelsDlg::OnDest13()
{
DestClicked(12,dest_check[12]->GetCheck());
}
void ExchangeChannelsDlg::OnDest14()
{
DestClicked(13,dest_check[13]->GetCheck());
}
void ExchangeChannelsDlg::OnDest15()
{
DestClicked(14,dest_check[14]->GetCheck());
}
void ExchangeChannelsDlg::OnDest16()
{
DestClicked(15,dest_check[15]->GetCheck());
}
| [
"email@dplate.de"
] | email@dplate.de |
93303398fc921d4699bff0511ea1003967568f4e | 1fd49a602e2ad2d1d7d858bfab434c0118990b6d | /62_timing_in_cpp/main.cpp | 37dac8fc272741dd4da746a428f033f0a1cd3e3b | [] | no_license | czhherry/cpp_tutorial | 4b3dc4ce44a741e2666a8aa4a66de4e4b12a363a | 682cb5e22c17573c7014a54e29bc940e597f6a0d | refs/heads/master | 2020-11-24T21:36:58.776140 | 2019-12-25T13:44:00 | 2019-12-25T13:44:00 | 228,350,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | cpp | #include <iostream>
#include <chrono>
#include <thread>
struct Timer
{
// std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
std::chrono::duration<float> duration;
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
float ms = duration.count() * 1000.0f;
std::cout << "Timer took " << ms << "ms\n";// << std::endl;
}
};
void Function()
{
using namespace std::literals::chrono_literals;
Timer t;
for(int i = 0; i < 100; i++)
std::cout << "Hello" << std::endl;
std::this_thread::sleep_for(1s);
}
int main()
{
Function();
std::cin.get();
}
// int main()
// {
// using namespace std::literals::chrono_literals;
// auto start = std::chrono::high_resolution_clock::now();
// std::this_thread::sleep_for(1s);
// auto end = std::chrono::high_resolution_clock::now();
// std::chrono::duration<float> duration = end - start;
// std::cout << duration.count() << std::endl;
// std::cin.get();
// } | [
"czhherry@gmail.com"
] | czhherry@gmail.com |
3fa57d71bd4dc67db9eb1f7d8a944ebcc16197de | b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1 | /C++ code/NTU Online Judge/2636.cpp | 4f58472a7aad8b2a47a5a55433d62b71de71e53e | [] | no_license | fsps60312/old-C-code | 5d0ffa0796dde5ab04c839e1dc786267b67de902 | b4be562c873afe9eacb45ab14f61c15b7115fc07 | refs/heads/master | 2022-11-30T10:55:25.587197 | 2017-06-03T16:23:03 | 2017-06-03T16:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,810 | cpp | #include<cstdio>
#include<cassert>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
typedef long long LL;
struct Point
{
int X,Y,Z;
Point(){}
Point(const int _X,const int _Y,const int _Z):X(_X),Y(_Y),Z(_Z){}
};
bool operator<(const Point &a,const Point &b)
{
if(a.Z!=b.Z)return a.Z<b.Z;
if(a.X!=b.X)return a.X<b.X;
if(a.Y!=b.Y)return a.Y<b.Y;
return false;
}
struct Vector
{
int X,Y;
Vector(){}
Vector(const int _X,const int _Y):X(_X),Y(_Y){}
};
Vector operator-(const Point &a,const Point &b){return Vector(a.X-b.X,a.Y-b.Y);}
bool Direction(const Vector &a,const Vector &b)
{
return ((LL)a.X*b.Y-(LL)b.X*a.Y)>0;
}
struct Triangle
{
Point A,B,C;
Triangle(){}
Triangle(const Point &_A,const Point &_B,const Point &_C):A(_A),B(_B),C(_C){}
bool Contains(const Point &p)const
{
return Direction(B-A,p-A)==Direction(p-A,C-A)&&Direction(A-B,p-B)==Direction(p-B,C-B);
}
};
Point ReadPoint()
{
Point p;
scanf("%d%d%d",&p.X,&p.Y,&p.Z);
return p;
}
Triangle ReadTriangle(){return Triangle(ReadPoint(),ReadPoint(),ReadPoint());}
int N,M,H[6000];
Point RI[6000];
vector<Triangle>S;
Point A0,B0;
int A,B;
vector<int>ET[6000];
map<Point,int>ID;
vector<Point>ANS;
bool Dfs(const int u,bool *vis,const int bound)
{
if(vis[u]||H[u]>bound)return false;
vis[u]=true;
ANS.push_back(RI[u]);
if(u==B){ANS.push_back(B0);return true;}
for(const int nxt:ET[u])if(Dfs(nxt,vis,bound))return true;
ANS.pop_back();
return false;
}
bool Solve(const int bound)
{
static bool vis[6000];
for(int i=0;i<N;i++)vis[i]=false;
ANS.clear();ANS.push_back(A0);
return Dfs(A,vis,bound);
}
int main()
{
// freopen("in.txt","r",stdin);
while(scanf("%d",&N)==1)
{
S.clear();
for(int i=0;i<N;i++)S.push_back(ReadTriangle());
A0=ReadPoint(),B0=ReadPoint();
ID.clear();
for(const Triangle &t:S)ID[t.A]=ID[t.B]=ID[t.C]=-1;
{M=0;for(auto &it:ID)H[it.second=M++]=it.first.Z,RI[it.second]=it.first;}
for(int i=0;i<M;i++)ET[i].clear();
for(const Triangle &t:S)
{
ET[ID[t.A]].push_back(ID[t.B]);
ET[ID[t.A]].push_back(ID[t.C]);
ET[ID[t.B]].push_back(ID[t.A]);
ET[ID[t.B]].push_back(ID[t.C]);
ET[ID[t.C]].push_back(ID[t.A]);
ET[ID[t.C]].push_back(ID[t.B]);
}
for(const Triangle &t:S)if(t.Contains(A0)){A=ID[min(min(t.A,t.B),t.C)];goto index_foundA;}
assert(0);index_foundA:;
for(const Triangle &t:S)if(t.Contains(B0)){B=ID[min(min(t.A,t.B),t.C)];goto index_foundB;}
assert(0);index_foundB:;
// printf("A=(%d,%d,%d)\n",RI[A].X,RI[A].Y,RI[A].Z);
// printf("B=(%d,%d,%d)\n",RI[B].X,RI[B].Y,RI[B].Z);
int l=0,r=1000000;
while(l<r)
{
const int mid=(l+r)/2;
if(Solve(mid))r=mid;
else l=mid+1;
}
// printf("r=%d\n",r);
assert(Solve(r));
printf("%d\n",(int)ANS.size());
for(const Point &p:ANS)printf("%d %d %d\n",p.X,p.Y,p.Z);
}
return 0;
}
| [
"fsps60312@yahoo.com.tw"
] | fsps60312@yahoo.com.tw |
40a39639711a7e77081198df6adadf9291724051 | 564d6b08c438acfa59875025c4191c67918d891c | /Robocup/BehaviorTree/InverterNode.h | 27524875653e579dfb125b2d23698a782c96c514 | [
"MIT"
] | permissive | MaximV88/RoboCup | 83c835f980cadb1fc0e705d501cca00fa39167d0 | 7066f3f1370145cf0a7bad06a7774716cb0b4573 | refs/heads/master | 2021-01-19T17:17:49.788296 | 2015-11-15T00:17:58 | 2015-11-15T00:17:58 | 38,407,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | h | /************************************************************
* Student Name: TreeBots *
* Exercise Name: Ex6 *
* File description: Declaration of Vector Class *
***********************************************************/
#ifndef __Robocup__InverterNode__
#define __Robocup__InverterNode__
#include "DecoratorNode.h"
namespace behavior {
class InverterNode : public DecoratorNode {
public:
InverterNode(BehaviorTreeNode* cChild);
~InverterNode();
virtual StatusType process();
};
}
#endif
| [
"maximv88@gmail.com"
] | maximv88@gmail.com |
87fd3f303f6535e64ae1abcb8b9d0be5aadfa8bf | 4f54fb00cfb3bed4e8132ce2e783c6d93fc9c7ca | /mlir/test/lib/Analysis/DataFlow/TestDeadCodeAnalysis.cpp | 8106c94d57368ab1fd4dca9b428512f7f662ec0f | [
"Apache-2.0",
"LLVM-exception"
] | permissive | koparasy/HPAC | 357101325a32ba5e27bf211400d9501e9fc37e7b | 207b5b570375b9835d79c949b6efe33e7146fec2 | refs/heads/develop | 2023-04-14T04:36:50.098763 | 2022-08-24T17:48:58 | 2022-08-24T17:48:58 | 356,543,963 | 1 | 0 | null | 2022-08-26T02:09:59 | 2021-04-10T10:13:27 | C++ | UTF-8 | C++ | false | false | 3,881 | cpp | //===- TestDeadCodeAnalysis.cpp - Test dead code analysis -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Analysis/DataFlow/ConstantPropagationAnalysis.h"
#include "mlir/Analysis/DataFlow/DeadCodeAnalysis.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
using namespace mlir::dataflow;
/// Print the liveness of every block, control-flow edge, and the predecessors
/// of all regions, callables, and calls.
static void printAnalysisResults(DataFlowSolver &solver, Operation *op,
raw_ostream &os) {
op->walk([&](Operation *op) {
auto tag = op->getAttrOfType<StringAttr>("tag");
if (!tag)
return;
os << tag.getValue() << ":\n";
for (Region ®ion : op->getRegions()) {
os << " region #" << region.getRegionNumber() << "\n";
for (Block &block : region) {
os << " ";
block.printAsOperand(os);
os << " = ";
auto *live = solver.lookupState<Executable>(&block);
if (live)
os << *live;
else
os << "dead";
os << "\n";
for (Block *pred : block.getPredecessors()) {
os << " from ";
pred->printAsOperand(os);
os << " = ";
auto *live = solver.lookupState<Executable>(
solver.getProgramPoint<CFGEdge>(pred, &block));
if (live)
os << *live;
else
os << "dead";
os << "\n";
}
}
if (!region.empty()) {
auto *preds = solver.lookupState<PredecessorState>(®ion.front());
if (preds)
os << "region_preds: " << *preds << "\n";
}
}
auto *preds = solver.lookupState<PredecessorState>(op);
if (preds)
os << "op_preds: " << *preds << "\n";
});
}
namespace {
/// This is a simple analysis that implements a transfer function for constant
/// operations.
struct ConstantAnalysis : public DataFlowAnalysis {
using DataFlowAnalysis::DataFlowAnalysis;
LogicalResult initialize(Operation *top) override {
WalkResult result = top->walk([&](Operation *op) {
if (op->hasTrait<OpTrait::ConstantLike>())
if (failed(visit(op)))
return WalkResult::interrupt();
return WalkResult::advance();
});
return success(!result.wasInterrupted());
}
LogicalResult visit(ProgramPoint point) override {
Operation *op = point.get<Operation *>();
Attribute value;
if (matchPattern(op, m_Constant(&value))) {
auto *constant = getOrCreate<Lattice<ConstantValue>>(op->getResult(0));
propagateIfChanged(
constant, constant->join(ConstantValue(value, op->getDialect())));
}
return success();
}
};
/// This is a simple pass that runs dead code analysis with no constant value
/// provider. It marks everything as live.
struct TestDeadCodeAnalysisPass
: public PassWrapper<TestDeadCodeAnalysisPass, OperationPass<>> {
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestDeadCodeAnalysisPass)
StringRef getArgument() const override { return "test-dead-code-analysis"; }
void runOnOperation() override {
Operation *op = getOperation();
DataFlowSolver solver;
solver.load<DeadCodeAnalysis>();
solver.load<ConstantAnalysis>();
if (failed(solver.initializeAndRun(op)))
return signalPassFailure();
printAnalysisResults(solver, op, llvm::errs());
}
};
} // end anonymous namespace
namespace mlir {
namespace test {
void registerTestDeadCodeAnalysisPass() {
PassRegistration<TestDeadCodeAnalysisPass>();
}
} // end namespace test
} // end namespace mlir
| [
"jeffniu22@gmail.com"
] | jeffniu22@gmail.com |
ecc1444ac857ddcdb8331c57e432f2f94b2c0076 | 156884c5005fc0be626159030f41319ee801bc8b | /Source/Resources/DDSImage.cpp | 0d22e00d2c26a21e30d2aacb02260d8cbb828366 | [
"MIT"
] | permissive | aaronmjacobs/Forge | 1ddd0c9f088b728dea3316d5c64b2c0184d3d438 | d9c4b0282926b77edb0633489b9b12a10351c1a1 | refs/heads/master | 2023-08-03T12:33:32.246365 | 2023-07-21T01:06:54 | 2023-07-21T01:06:54 | 236,388,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,965 | cpp | #include "Resources/DDSImage.h"
#include "Resources/Image.h"
#include <utility>
namespace
{
enum DXGIFormat
{
DXGI_FORMAT_UNKNOWN = 0,
DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
DXGI_FORMAT_R32G32B32A32_UINT = 3,
DXGI_FORMAT_R32G32B32A32_SINT = 4,
DXGI_FORMAT_R32G32B32_TYPELESS = 5,
DXGI_FORMAT_R32G32B32_FLOAT = 6,
DXGI_FORMAT_R32G32B32_UINT = 7,
DXGI_FORMAT_R32G32B32_SINT = 8,
DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
DXGI_FORMAT_R16G16B16A16_UNORM = 11,
DXGI_FORMAT_R16G16B16A16_UINT = 12,
DXGI_FORMAT_R16G16B16A16_SNORM = 13,
DXGI_FORMAT_R16G16B16A16_SINT = 14,
DXGI_FORMAT_R32G32_TYPELESS = 15,
DXGI_FORMAT_R32G32_FLOAT = 16,
DXGI_FORMAT_R32G32_UINT = 17,
DXGI_FORMAT_R32G32_SINT = 18,
DXGI_FORMAT_R32G8X24_TYPELESS = 19,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
DXGI_FORMAT_R10G10B10A2_UNORM = 24,
DXGI_FORMAT_R10G10B10A2_UINT = 25,
DXGI_FORMAT_R11G11B10_FLOAT = 26,
DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
DXGI_FORMAT_R8G8B8A8_UNORM = 28,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
DXGI_FORMAT_R8G8B8A8_UINT = 30,
DXGI_FORMAT_R8G8B8A8_SNORM = 31,
DXGI_FORMAT_R8G8B8A8_SINT = 32,
DXGI_FORMAT_R16G16_TYPELESS = 33,
DXGI_FORMAT_R16G16_FLOAT = 34,
DXGI_FORMAT_R16G16_UNORM = 35,
DXGI_FORMAT_R16G16_UINT = 36,
DXGI_FORMAT_R16G16_SNORM = 37,
DXGI_FORMAT_R16G16_SINT = 38,
DXGI_FORMAT_R32_TYPELESS = 39,
DXGI_FORMAT_D32_FLOAT = 40,
DXGI_FORMAT_R32_FLOAT = 41,
DXGI_FORMAT_R32_UINT = 42,
DXGI_FORMAT_R32_SINT = 43,
DXGI_FORMAT_R24G8_TYPELESS = 44,
DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
DXGI_FORMAT_R8G8_TYPELESS = 48,
DXGI_FORMAT_R8G8_UNORM = 49,
DXGI_FORMAT_R8G8_UINT = 50,
DXGI_FORMAT_R8G8_SNORM = 51,
DXGI_FORMAT_R8G8_SINT = 52,
DXGI_FORMAT_R16_TYPELESS = 53,
DXGI_FORMAT_R16_FLOAT = 54,
DXGI_FORMAT_D16_UNORM = 55,
DXGI_FORMAT_R16_UNORM = 56,
DXGI_FORMAT_R16_UINT = 57,
DXGI_FORMAT_R16_SNORM = 58,
DXGI_FORMAT_R16_SINT = 59,
DXGI_FORMAT_R8_TYPELESS = 60,
DXGI_FORMAT_R8_UNORM = 61,
DXGI_FORMAT_R8_UINT = 62,
DXGI_FORMAT_R8_SNORM = 63,
DXGI_FORMAT_R8_SINT = 64,
DXGI_FORMAT_A8_UNORM = 65,
DXGI_FORMAT_R1_UNORM = 66,
DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
DXGI_FORMAT_BC1_TYPELESS = 70,
DXGI_FORMAT_BC1_UNORM = 71,
DXGI_FORMAT_BC1_UNORM_SRGB = 72,
DXGI_FORMAT_BC2_TYPELESS = 73,
DXGI_FORMAT_BC2_UNORM = 74,
DXGI_FORMAT_BC2_UNORM_SRGB = 75,
DXGI_FORMAT_BC3_TYPELESS = 76,
DXGI_FORMAT_BC3_UNORM = 77,
DXGI_FORMAT_BC3_UNORM_SRGB = 78,
DXGI_FORMAT_BC4_TYPELESS = 79,
DXGI_FORMAT_BC4_UNORM = 80,
DXGI_FORMAT_BC4_SNORM = 81,
DXGI_FORMAT_BC5_TYPELESS = 82,
DXGI_FORMAT_BC5_UNORM = 83,
DXGI_FORMAT_BC5_SNORM = 84,
DXGI_FORMAT_B5G6R5_UNORM = 85,
DXGI_FORMAT_B5G5R5A1_UNORM = 86,
DXGI_FORMAT_B8G8R8A8_UNORM = 87,
DXGI_FORMAT_B8G8R8X8_UNORM = 88,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89,
DXGI_FORMAT_B8G8R8A8_TYPELESS = 90,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91,
DXGI_FORMAT_B8G8R8X8_TYPELESS = 92,
DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93,
DXGI_FORMAT_BC6H_TYPELESS = 94,
DXGI_FORMAT_BC6H_UF16 = 95,
DXGI_FORMAT_BC6H_SF16 = 96,
DXGI_FORMAT_BC7_TYPELESS = 97,
DXGI_FORMAT_BC7_UNORM = 98,
DXGI_FORMAT_BC7_UNORM_SRGB = 99,
DXGI_FORMAT_AYUV = 100,
DXGI_FORMAT_Y410 = 101,
DXGI_FORMAT_Y416 = 102,
DXGI_FORMAT_NV12 = 103,
DXGI_FORMAT_P010 = 104,
DXGI_FORMAT_P016 = 105,
DXGI_FORMAT_420_OPAQUE = 106,
DXGI_FORMAT_YUY2 = 107,
DXGI_FORMAT_Y210 = 108,
DXGI_FORMAT_Y216 = 109,
DXGI_FORMAT_NV11 = 110,
DXGI_FORMAT_AI44 = 111,
DXGI_FORMAT_IA44 = 112,
DXGI_FORMAT_P8 = 113,
DXGI_FORMAT_A8P8 = 114,
DXGI_FORMAT_B4G4R4A4_UNORM = 115,
DXGI_FORMAT_P208 = 130,
DXGI_FORMAT_V208 = 131,
DXGI_FORMAT_V408 = 132,
DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189,
DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190,
DXGI_FORMAT_FORCE_UINT = 0xffffffff
};
enum D3D10ResourceDimension
{
D3D10_RESOURCE_DIMENSION_UNKNOWN = 0,
D3D10_RESOURCE_DIMENSION_BUFFER = 1,
D3D10_RESOURCE_DIMENSION_TEXTURE1D = 2,
D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3,
D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4
};
namespace DDSFlags
{
enum Enum : uint32_t
{
None = 0x0,
Caps = 0x1,
Height = 0x2,
Width = 0x4,
Pitch = 0x8,
PixelFormat = 0x1000,
MipMapCount = 0x20000,
LinearSize = 0x80000,
Depth = 0x800000
};
}
namespace DDSCaps
{
enum Enum : uint32_t
{
None = 0x0,
Complex = 0x8,
MipMap = 0x400000,
Texture = 0x1000
};
}
namespace DDSCaps2
{
enum Enum : uint32_t
{
None = 0x0,
Cubemap = 0x200,
CubemapPositiveX = 0x400,
CubemapNegativeX = 0x800,
CubemapPositiveY = 0x1000,
CubemapNegativeY = 0x2000,
CubemapPositiveZ = 0x4000,
CubemapNegativeZ = 0x8000,
Volume = 0x200000
};
}
namespace DDSPixelFormatFlags
{
enum Enum : uint32_t
{
None = 0x0,
AlphaPixels = 0x1,
Alpha = 0x2,
FourCC = 0x4,
RGB = 0x40,
YUV = 0x200,
Luminance = 0x20000
};
}
constexpr uint32_t fourCC(const char chars[5])
{
return static_cast<uint32_t>((chars[0] << 0) | (chars[1] << 8) | (chars[2] << 16) | (chars[3] << 24));
}
namespace DDSFourCC
{
enum Enum : uint32_t
{
Invalid = 0,
DXT1 = fourCC("DXT1"),
DXT2 = fourCC("DXT2"),
DXT3 = fourCC("DXT3"),
DXT4 = fourCC("DXT4"),
DXT5 = fourCC("DXT5"),
ATI1 = fourCC("ATI1"),
ATI2 = fourCC("ATI2"),
BC4U = fourCC("BC4U"),
BC4S = fourCC("BC4S"),
BC5U = fourCC("BC5U"),
BC5S = fourCC("BC5S"),
RGBG = fourCC("RGBG"),
GRGB = fourCC("GRGB"),
DX10 = fourCC("DX10")
};
}
namespace DDSDX10MiscFlag
{
enum Enum : uint32_t
{
None = 0x0,
TextureCube = 0x4
};
}
namespace DDSDX10AlphaMode
{
enum Enum : uint32_t
{
Unknown = 0x0,
Straight = 0x1,
Premultiplied = 0x2,
Opaque = 0x3,
Custom = 0x4
};
}
struct DDSPixelFormat
{
uint32_t size = 0;
DDSPixelFormatFlags::Enum flags = DDSPixelFormatFlags::None;
DDSFourCC::Enum fourCC = DDSFourCC::Invalid;
uint32_t rgbBitCount = 0;
uint32_t rBitMask = 0;
uint32_t gBitMask = 0;
uint32_t bBitMask = 0;
uint32_t aBitMask = 0;
};
struct DDSHeader
{
uint32_t size = 0;
DDSFlags::Enum flags = DDSFlags::None;
uint32_t height = 0;
uint32_t width = 0;
uint32_t pitchOrLinearSize = 0;
uint32_t depth = 0;
uint32_t mipMapCount = 0;
std::array<uint32_t, 11> reserved1{};
DDSPixelFormat pixelFormat;
DDSCaps::Enum caps = DDSCaps::None;
DDSCaps2::Enum caps2 = DDSCaps2::None;
uint32_t caps3 = 0;
uint32_t caps4 = 0;
uint32_t reserved2 = 0;
};
struct DDSHeaderDX10
{
DXGIFormat dxgiFormat = DXGI_FORMAT_UNKNOWN;
D3D10ResourceDimension resourceDimension = D3D10_RESOURCE_DIMENSION_UNKNOWN;
DDSDX10MiscFlag::Enum miscFlag = DDSDX10MiscFlag::None;
uint32_t arraySize = 0;
DDSDX10AlphaMode::Enum miscFlags2 = DDSDX10AlphaMode::Unknown;
};
vk::Format dxgiToVk(DXGIFormat dxgiFormat)
{
switch (dxgiFormat)
{
case DXGI_FORMAT_UNKNOWN:
return vk::Format::eUndefined;
case DXGI_FORMAT_R32G32B32A32_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
return vk::Format::eR32G32B32A32Sfloat;
case DXGI_FORMAT_R32G32B32A32_UINT:
return vk::Format::eR32G32B32A32Uint;
case DXGI_FORMAT_R32G32B32A32_SINT:
return vk::Format::eR32G32B32A32Sint;
case DXGI_FORMAT_R32G32B32_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R32G32B32_FLOAT:
return vk::Format::eR32G32B32Sfloat;
case DXGI_FORMAT_R32G32B32_UINT:
return vk::Format::eR32G32B32Uint;
case DXGI_FORMAT_R32G32B32_SINT:
return vk::Format::eR32G32B32Sint;
case DXGI_FORMAT_R16G16B16A16_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
return vk::Format::eR16G16B16A16Sfloat;
case DXGI_FORMAT_R16G16B16A16_UNORM:
return vk::Format::eR16G16B16A16Unorm;
case DXGI_FORMAT_R16G16B16A16_UINT:
return vk::Format::eR16G16B16A16Uint;
case DXGI_FORMAT_R16G16B16A16_SNORM:
return vk::Format::eR16G16B16A16Snorm;
case DXGI_FORMAT_R16G16B16A16_SINT:
return vk::Format::eR16G16B16A16Sint;
case DXGI_FORMAT_R32G32_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R32G32_FLOAT:
return vk::Format::eR32G32Sfloat;
case DXGI_FORMAT_R32G32_UINT:
return vk::Format::eR32G32Uint;
case DXGI_FORMAT_R32G32_SINT:
return vk::Format::eR32G32Sint;
case DXGI_FORMAT_R32G8X24_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
return vk::Format::eD32SfloatS8Uint;
case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
return vk::Format::eUndefined;
case DXGI_FORMAT_R10G10B10A2_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R10G10B10A2_UNORM:
return vk::Format::eA2R10G10B10UnormPack32;
case DXGI_FORMAT_R10G10B10A2_UINT:
return vk::Format::eA2R10G10B10UintPack32;
case DXGI_FORMAT_R11G11B10_FLOAT:
return vk::Format::eB10G11R11UfloatPack32;
case DXGI_FORMAT_R8G8B8A8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R8G8B8A8_UNORM:
return vk::Format::eR8G8B8A8Unorm;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
return vk::Format::eR8G8B8A8Srgb;
case DXGI_FORMAT_R8G8B8A8_UINT:
return vk::Format::eR8G8B8A8Uint;
case DXGI_FORMAT_R8G8B8A8_SNORM:
return vk::Format::eR8G8B8A8Snorm;
case DXGI_FORMAT_R8G8B8A8_SINT:
return vk::Format::eR8G8B8A8Sint;
case DXGI_FORMAT_R16G16_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R16G16_FLOAT:
return vk::Format::eR16G16Sfloat;
case DXGI_FORMAT_R16G16_UNORM:
return vk::Format::eR16G16Unorm;
case DXGI_FORMAT_R16G16_UINT:
return vk::Format::eR16G16Uint;
case DXGI_FORMAT_R16G16_SNORM:
return vk::Format::eR16G16Snorm;
case DXGI_FORMAT_R16G16_SINT:
return vk::Format::eR16G16Sint;
case DXGI_FORMAT_R32_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_D32_FLOAT:
return vk::Format::eD32Sfloat;
case DXGI_FORMAT_R32_FLOAT:
return vk::Format::eR32Sfloat;
case DXGI_FORMAT_R32_UINT:
return vk::Format::eR32Uint;
case DXGI_FORMAT_R32_SINT:
return vk::Format::eR32Sint;
case DXGI_FORMAT_R24G8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_D24_UNORM_S8_UINT:
return vk::Format::eD24UnormS8Uint;
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
return vk::Format::eUndefined;
case DXGI_FORMAT_R8G8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R8G8_UNORM:
return vk::Format::eR8G8Unorm;
case DXGI_FORMAT_R8G8_UINT:
return vk::Format::eR8G8Uint;
case DXGI_FORMAT_R8G8_SNORM:
return vk::Format::eR8G8Snorm;
case DXGI_FORMAT_R8G8_SINT:
return vk::Format::eR8G8Sint;
case DXGI_FORMAT_R16_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R16_FLOAT:
return vk::Format::eR16Sfloat;
case DXGI_FORMAT_D16_UNORM:
return vk::Format::eD16Unorm;
case DXGI_FORMAT_R16_UNORM:
return vk::Format::eR16Unorm;
case DXGI_FORMAT_R16_UINT:
return vk::Format::eR16Uint;
case DXGI_FORMAT_R16_SNORM:
return vk::Format::eR16Snorm;
case DXGI_FORMAT_R16_SINT:
return vk::Format::eR16Sint;
case DXGI_FORMAT_R8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_R8_UNORM:
return vk::Format::eR8Unorm;
case DXGI_FORMAT_R8_UINT:
return vk::Format::eR8Uint;
case DXGI_FORMAT_R8_SNORM:
return vk::Format::eR8Snorm;
case DXGI_FORMAT_R8_SINT:
return vk::Format::eR8Sint;
case DXGI_FORMAT_A8_UNORM:
return vk::Format::eUndefined;
case DXGI_FORMAT_R1_UNORM:
return vk::Format::eUndefined;
case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
return vk::Format::eE5B9G9R9UfloatPack32;
case DXGI_FORMAT_R8G8_B8G8_UNORM:
return vk::Format::eB8G8R8G8422Unorm;
case DXGI_FORMAT_G8R8_G8B8_UNORM:
return vk::Format::eG8B8G8R8422Unorm;
case DXGI_FORMAT_BC1_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC1_UNORM:
return vk::Format::eBc1RgbaUnormBlock;
case DXGI_FORMAT_BC1_UNORM_SRGB:
return vk::Format::eBc1RgbaSrgbBlock;
case DXGI_FORMAT_BC2_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC2_UNORM:
return vk::Format::eBc2UnormBlock;
case DXGI_FORMAT_BC2_UNORM_SRGB:
return vk::Format::eBc2SrgbBlock;
case DXGI_FORMAT_BC3_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC3_UNORM:
return vk::Format::eBc3UnormBlock;
case DXGI_FORMAT_BC3_UNORM_SRGB:
return vk::Format::eBc3SrgbBlock;
case DXGI_FORMAT_BC4_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC4_UNORM:
return vk::Format::eBc4UnormBlock;
case DXGI_FORMAT_BC4_SNORM:
return vk::Format::eBc4SnormBlock;
case DXGI_FORMAT_BC5_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC5_UNORM:
return vk::Format::eBc5UnormBlock;
case DXGI_FORMAT_BC5_SNORM:
return vk::Format::eBc5SnormBlock;
case DXGI_FORMAT_B5G6R5_UNORM:
return vk::Format::eB5G6R5UnormPack16;
case DXGI_FORMAT_B5G5R5A1_UNORM:
return vk::Format::eB5G5R5A1UnormPack16;
case DXGI_FORMAT_B8G8R8A8_UNORM:
return vk::Format::eB8G8R8A8Unorm;
case DXGI_FORMAT_B8G8R8X8_UNORM:
return vk::Format::eUndefined;
case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
return vk::Format::eUndefined;
case DXGI_FORMAT_B8G8R8A8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
return vk::Format::eB8G8R8A8Srgb;
case DXGI_FORMAT_B8G8R8X8_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC6H_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC6H_UF16:
return vk::Format::eBc6HUfloatBlock;
case DXGI_FORMAT_BC6H_SF16:
return vk::Format::eBc6HSfloatBlock;
case DXGI_FORMAT_BC7_TYPELESS:
return vk::Format::eUndefined;
case DXGI_FORMAT_BC7_UNORM:
return vk::Format::eBc7UnormBlock;
case DXGI_FORMAT_BC7_UNORM_SRGB:
return vk::Format::eBc7SrgbBlock;
case DXGI_FORMAT_AYUV:
return vk::Format::eUndefined;
case DXGI_FORMAT_Y410:
return vk::Format::eUndefined;
case DXGI_FORMAT_Y416:
return vk::Format::eUndefined;
case DXGI_FORMAT_NV12:
return vk::Format::eUndefined;
case DXGI_FORMAT_P010:
return vk::Format::eUndefined;
case DXGI_FORMAT_P016:
return vk::Format::eUndefined;
case DXGI_FORMAT_420_OPAQUE:
return vk::Format::eUndefined;
case DXGI_FORMAT_YUY2:
return vk::Format::eUndefined;
case DXGI_FORMAT_Y210:
return vk::Format::eUndefined;
case DXGI_FORMAT_Y216:
return vk::Format::eUndefined;
case DXGI_FORMAT_NV11:
return vk::Format::eUndefined;
case DXGI_FORMAT_AI44:
return vk::Format::eUndefined;
case DXGI_FORMAT_IA44:
return vk::Format::eUndefined;
case DXGI_FORMAT_P8:
return vk::Format::eUndefined;
case DXGI_FORMAT_A8P8:
return vk::Format::eUndefined;
case DXGI_FORMAT_B4G4R4A4_UNORM:
return vk::Format::eB4G4R4A4UnormPack16;
case DXGI_FORMAT_P208:
return vk::Format::eUndefined;
case DXGI_FORMAT_V208:
return vk::Format::eUndefined;
case DXGI_FORMAT_V408:
return vk::Format::eUndefined;
case DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE:
return vk::Format::eUndefined;
case DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE:
return vk::Format::eUndefined;
case DXGI_FORMAT_FORCE_UINT:
return vk::Format::eUndefined;
default:
return vk::Format::eUndefined;
}
}
bool matchesBitmask(const DDSPixelFormat& ddsFormat, uint32_t r, uint32_t g, uint32_t b, uint32_t a)
{
return ddsFormat.rBitMask == r && ddsFormat.gBitMask == g && ddsFormat.bBitMask == b && ddsFormat.aBitMask == a;
}
vk::Format ddsToVkFormat(const DDSPixelFormat& ddsFormat, const DDSHeaderDX10& headerDX10, bool sRGBHint)
{
if (ddsFormat.flags & DDSPixelFormatFlags::RGB)
{
switch (ddsFormat.rgbBitCount)
{
case 16:
if (matchesBitmask(ddsFormat, 0x7c00, 0x03e0, 0x001f, 0x8000))
{
return vk::Format::eB5G5R5A1UnormPack16;
}
if (matchesBitmask(ddsFormat, 0xf800, 0x07e0, 0x001f, 0x0000))
{
return vk::Format::eB5G6R5UnormPack16;
}
if (matchesBitmask(ddsFormat, 0x0f00, 0x00f0, 0x000f, 0xf000))
{
return vk::Format::eB4G4R4A4UnormPack16;
}
break;
case 32:
if (matchesBitmask(ddsFormat, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
{
return vk::Format::eR8G8B8A8Unorm;
}
if (matchesBitmask(ddsFormat, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
{
return vk::Format::eB8G8R8A8Unorm;
}
if (matchesBitmask(ddsFormat, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000))
{
return vk::Format::eA2R10G10B10UnormPack32;
}
if (matchesBitmask(ddsFormat, 0xffffffff, 0x00000000, 0x00000000, 0x00000000))
{
return vk::Format::eR32Sfloat;
}
break;
default:
break;
}
}
else if (ddsFormat.flags & DDSPixelFormatFlags::Luminance)
{
switch (ddsFormat.rgbBitCount)
{
case 8:
if (matchesBitmask(ddsFormat, 0x000000ff, 0x00000000, 0x00000000, 0x00000000))
{
return vk::Format::eR8Unorm;
}
break;
case 16:
if (matchesBitmask(ddsFormat, 0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
{
return vk::Format::eR16Unorm;
}
if (matchesBitmask(ddsFormat, 0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
{
return vk::Format::eR8G8Unorm;
}
break;
default:
break;
}
}
else if (ddsFormat.flags & DDSPixelFormatFlags::Alpha)
{
return vk::Format::eUndefined;
}
else if (ddsFormat.flags & DDSPixelFormatFlags::FourCC)
{
switch (ddsFormat.fourCC)
{
case DDSFourCC::DXT1:
return sRGBHint ? vk::Format::eBc1RgbSrgbBlock : vk::Format::eBc1RgbUnormBlock;
case DDSFourCC::DXT2:
case DDSFourCC::DXT3:
return sRGBHint ? vk::Format::eBc2SrgbBlock : vk::Format::eBc2UnormBlock;
case DDSFourCC::DXT4:
case DDSFourCC::DXT5:
return sRGBHint ? vk::Format::eBc3SrgbBlock : vk::Format::eBc3UnormBlock;
case DDSFourCC::ATI1:
return vk::Format::eBc4UnormBlock;
case DDSFourCC::ATI2:
return vk::Format::eBc5UnormBlock;
case DDSFourCC::BC4U:
return vk::Format::eBc4UnormBlock;
case DDSFourCC::BC4S:
return vk::Format::eBc4SnormBlock;
case DDSFourCC::BC5U:
return vk::Format::eBc5UnormBlock;
case DDSFourCC::BC5S:
return vk::Format::eBc5SnormBlock;
case DDSFourCC::RGBG:
return vk::Format::eB8G8R8G8422Unorm;
case DDSFourCC::GRGB:
return vk::Format::eG8B8G8R8422Unorm;
case DDSFourCC::DX10:
return dxgiToVk(headerDX10.dxgiFormat);
default:
return vk::Format::eUndefined;
}
}
return vk::Format::eUndefined;
}
vk::ImageType determineImageType(const DDSHeader& header, const DDSHeaderDX10& headerDX10)
{
switch (headerDX10.resourceDimension)
{
case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
return vk::ImageType::e1D;
case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
return vk::ImageType::e2D;
case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
return vk::ImageType::e3D;
default:
if (header.flags & DDSFlags::Depth)
{
return vk::ImageType::e3D;
}
return vk::ImageType::e2D;
}
}
uint32_t determineLayerCount(const DDSHeader& header, const DDSHeaderDX10& headerDX10)
{
if (headerDX10.arraySize > 0)
{
uint32_t arraySize = headerDX10.arraySize;
// https://forums.developer.nvidia.com/t/texture-tools-exporter-cubemap-has-incorrect-arraysize/244753/3
if (header.reserved1[9] == fourCC("NVT3") && header.reserved1[10] == 0 && (header.caps2 & DDSCaps2::Cubemap))
{
arraySize /= 6;
}
return arraySize * ((headerDX10.miscFlag & DDSDX10MiscFlag::TextureCube) ? 6 : 1);
}
uint32_t allCubemapFaces = DDSCaps2::CubemapPositiveX | DDSCaps2::CubemapNegativeX | DDSCaps2::CubemapPositiveY | DDSCaps2::CubemapNegativeY | DDSCaps2::CubemapPositiveZ | DDSCaps2::CubemapNegativeZ;
if ((header.caps2 & DDSCaps2::Cubemap) && (header.caps2 & allCubemapFaces) == allCubemapFaces)
{
return 6;
}
return 1;
}
uint32_t computeImageDataSize(vk::Format format, uint32_t width, uint32_t height, uint32_t depth)
{
uint32_t bytesPerBlock = FormatHelpers::bytesPerBlock(format);
if (bytesPerBlock > 0)
{
uint32_t numBlocksWide = std::max(1u, (width + 3) / 4);
uint32_t numBlocksHigh = std::max(1u, (height + 3) / 4);
uint32_t numBlocksDeep = std::max(1u, (depth + 3) / 4);
uint32_t numBlocks = numBlocksWide * numBlocksHigh * numBlocksDeep;
return numBlocks * bytesPerBlock;
}
if (format == vk::Format::eB8G8R8G8422Unorm || format == vk::Format::eG8B8G8R8422Unorm)
{
uint32_t bytesPerRow = ((width + 1) / 2) * 4;
uint32_t numRows = height * depth;
return numRows * bytesPerRow;
}
uint32_t bitsPerPixel = FormatHelpers::bitsPerPixel(format);
uint32_t bytesPerRow = (width * bitsPerPixel + 7) / 8;
uint32_t numRows = height * depth;
return numRows * bytesPerRow;
}
class DDSImage : public Image
{
public:
DDSImage(const ImageProperties& imageProperties, std::vector<uint8_t> fileData, std::size_t textureDataOffset, std::size_t textureDataSize, std::vector<MipInfo> mipInfo, uint32_t mipMapCount)
: Image(imageProperties)
, data(std::move(fileData))
, textureOffset(textureDataOffset)
, textureSize(textureDataSize)
, mips(std::move(mipInfo))
, mipsPerLayer(mipMapCount)
{
}
TextureData getTextureData() const final
{
TextureData textureData;
textureData.bytes = std::span<const uint8_t>(data.data() + textureOffset, textureSize);
textureData.mips = std::span<const MipInfo>(mips);
textureData.mipsPerLayer = mipsPerLayer;
return textureData;
}
private:
std::vector<uint8_t> data;
std::size_t textureOffset = 0;
std::size_t textureSize = 0;
std::vector<MipInfo> mips;
uint32_t mipsPerLayer = 0;
};
}
namespace DDS
{
std::unique_ptr<Image> loadImage(std::vector<uint8_t> fileData, bool sRGBHint)
{
if (fileData.size() < sizeof(uint32_t) + sizeof(DDSHeader))
{
return nullptr;
}
std::size_t offset = 0;
uint32_t magic = 0;
std::memcpy(&magic, fileData.data() + offset, sizeof(uint32_t));
offset += sizeof(uint32_t);
DDSHeader header;
std::memcpy(&header, fileData.data() + offset, sizeof(DDSHeader));
offset += sizeof(DDSHeader);
constexpr uint32_t kDDSMagic = fourCC("DDS ");
if (magic != kDDSMagic || header.size != sizeof(DDSHeader))
{
return nullptr;
}
DDSHeaderDX10 headerDX10;
if ((header.pixelFormat.flags & DDSPixelFormatFlags::FourCC) && header.pixelFormat.fourCC == DDSFourCC::DX10 && fileData.size() >= offset + sizeof(DDSHeaderDX10))
{
std::memcpy(&headerDX10, fileData.data() + offset, sizeof(DDSHeaderDX10));
offset += sizeof(DDSHeaderDX10);
}
ImageProperties properties;
properties.format = ddsToVkFormat(header.pixelFormat, headerDX10, sRGBHint);
if (properties.format == vk::Format::eUndefined)
{
return nullptr;
}
properties.type = determineImageType(header, headerDX10);
if (header.flags & DDSFlags::Width)
{
properties.width = header.width;
}
if (header.flags & DDSFlags::Height)
{
properties.height = header.height;
}
if (header.flags & DDSFlags::Depth)
{
properties.depth = header.depth;
}
properties.layers = determineLayerCount(header, headerDX10);
properties.hasAlpha = FormatHelpers::hasAlpha(properties.format);
properties.cubeCompatible = (header.caps2 & DDSCaps2::Cubemap) || (headerDX10.miscFlag & DDSDX10MiscFlag::TextureCube);
uint32_t mipMapCount = 1;
if (header.flags & DDSFlags::MipMapCount)
{
mipMapCount = header.mipMapCount;
}
std::size_t textureDataOffset = offset;
std::size_t textureDataSize = 0;
std::vector<MipInfo> mips;
mips.reserve(mipMapCount * properties.layers);
for (uint32_t layer = 0; layer < properties.layers; ++layer)
{
uint32_t mipWidth = properties.width;
uint32_t mipHeight = properties.height;
uint32_t mipDepth = properties.depth;
for (uint32_t i = 0; i < mipMapCount; ++i)
{
uint32_t dataSize = computeImageDataSize(properties.format, mipWidth, mipHeight, mipDepth);
textureDataSize += dataSize;
if (fileData.size() < offset + dataSize)
{
return nullptr;
}
MipInfo mipInfo;
mipInfo.extent = vk::Extent3D(mipWidth, mipHeight, mipDepth);
mipInfo.bufferOffset = static_cast<uint32_t>(offset - textureDataOffset);
mips.push_back(mipInfo);
offset += dataSize;
mipWidth = std::max(1u, mipWidth / 2);
mipHeight = std::max(1u, mipHeight / 2);
mipDepth = std::max(1u, mipDepth / 2);
}
}
return std::make_unique<DDSImage>(properties, std::move(fileData), textureDataOffset, textureDataSize, std::move(mips), mipMapCount);
}
}
| [
"aaron@aaronmjacobs.com"
] | aaron@aaronmjacobs.com |
2e16f22b303d9717aebedbad8b1a25893e733428 | 327c359022428e4ef92962b31ad58ccf7707072e | /Core/src/BitPacker.cpp | 227e7f53f005ea0867727eb560af9675e7b3e184 | [] | no_license | brendan-kellam/UDP-Protocol | 9371015d13c35e5cb8e54f456ffbb1a204bcf553 | 841503daf5adfc86951a87d55dbd1d7682812ddb | refs/heads/master | 2021-06-03T01:20:09.158243 | 2019-12-04T01:57:24 | 2019-12-04T01:57:24 | 112,244,101 | 0 | 0 | null | 2018-06-08T07:36:25 | 2017-11-27T20:19:47 | C++ | UTF-8 | C++ | false | false | 818 | cpp | #include "BitPacker.h"
#include "Platform.h"
#include <string>
CBitPacker::CBitPacker(uint32_t* buffer, size_t bufferLen)
: m_scratch(0),
m_scratchBits(0),
m_wordIndex(0),
m_buffer(buffer),
m_bufferLen(bufferLen)
{
UDP_TRAP(bufferLen % 4 == 0)
}
std::string CBitPacker::getBits(uint64_t val)
{
if (val == 0)
{
return std::string("0");
}
std::string g;
while (val != 0)
{
g += std::to_string((val % 2 != 0));
val /= 2;
}
std::reverse(g.begin(), g.end());
return g;
}
std::string CBitPacker::getBits(uint64_t val, int bits)
{
int remainingBits = bits;
std::string g;
while (val != 0)
{
g += std::to_string((val % 2 != 0));
val /= 2;
remainingBits--;
}
for (int i = 0; i < remainingBits; i++)
{
g += std::string("0");
}
std::reverse(g.begin(), g.end());
return g;
}
| [
"bshizzle1234@gmail.com"
] | bshizzle1234@gmail.com |
fa91d3109d97a21515019c9f7d0a1e565154ac00 | 1db0c736999607a522e4d3e2cf6eea40fcf45d43 | /Projet2A/modesinter.cpp | dc9b3c008e255fbbe090035de095edf46c6a6bad | [] | no_license | naouelboughattas/Smart_parental_Monitoring_2A17 | 82aeb1abc5d634768d04c8b40954fa8f3a6082f6 | 708bfdda4a58824dadf4fca5f75d61e7b3b87aad | refs/heads/master | 2023-04-18T15:59:37.180824 | 2021-05-07T06:02:30 | 2021-05-07T06:02:30 | 345,682,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,533 | cpp | #include "modesinter.h"
#include "ui_modesinter.h"
#include <QMessageBox>
#include <QtPrintSupport/QPrintDialog>
#include "tableprinter.h"
#include <QPrinter>
#include <QPrintPreviewDialog>
modesinter::modesinter(QWidget *parent) :
QDialog(parent),
ui(new Ui::modesinter)
{
ui->setupUi(this);
setWindowTitle("Gestion de mode");
//Column size
ui->tablemodifier->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
refresh();
ui->comboBox_etat->setModel(tmpetat.requestnom());
QStringList list;
list << "" << "NOM" << "ETAT" << "DATE_DEBUT" << "DATE_FIN"<< "DESCRIPTION";
ui->comboBox_Tri->addItems(list);
}
modesinter::~modesinter()
{
delete ui;
}
void modesinter::refresh(){
ui->tablemodifier->setModel(tmpmodes.afficher());
//Combo
ui->comboBox_modif->setModel(tmpmodes.remplircombomodes());
ui->comboBox->setModel(tmpmodes.remplircombomodes());
}
void modesinter::on_AjouterBouton_clicked()
{
modes mod(ui->Nom->toPlainText(),ui->comboBox_etat->currentText(),ui->datedebut->dateTime(),ui->datefin->dateTime(),ui->decription->toPlainText());
bool test = mod.ajouter();
if(test)
{
//NOTIFICATION
trayIcon = new QSystemTrayIcon(this);
trayIcon->setVisible(true);
trayIcon->setIcon(this->style()->standardIcon(QStyle::SP_DesktopIcon));
trayIcon->setToolTip("Ajouter" "\n"
"Ajouter avec sucées");
trayIcon->showMessage("Ajouter","Ajouter avec sucées",QSystemTrayIcon::Information,1500);
trayIcon->show();
}
else
{
QMessageBox::critical(nullptr, QObject::tr("Ajouter un Mode"),
QObject::tr("Erreur !.\n"
"Click Cancel to exit."), QMessageBox::Cancel);
}
//refresh combobox + tableau
refresh();
}
void modesinter::on_comboBox_modif_currentIndexChanged(const QString &arg1)
{
QSqlQuery query;
QString id = ui->comboBox_modif->currentText();
query =tmpmodes.request(id);
if(query.exec())
{
while(query.next())
{
ui->Nom_mod->setText(query.value(1).toString());
ui->etat_mod->setText(query.value(2).toString());
ui->datedebut->setDateTime(query.value(3).toDateTime());
ui->datefin->setDateTime(query.value(4).toDateTime());
ui->decription_mod->setText(query.value(5).toString());
}
}
}
void modesinter::on_comboBox_currentIndexChanged(const QString &arg1)
{
QSqlQuery query;
QString id = ui->comboBox->currentText();
query =tmpmodes.request(id);
if(query.exec())
{
while(query.next())
{
ui->Nomval->setText(query.value(1).toString());
ui->etatval->setText(query.value(2).toString());
ui->datedebutval->setText(query.value(3).toString());
ui->datefinval_2->setText(query.value(4).toString());
ui->descriptionval->setText(query.value(5).toString());
}
}
}
void modesinter::on_comboBox_Tri_currentIndexChanged(const QString &arg1)
{
if(!(ui->comboBox_Tri->currentText()==""))
{
ui->tablemodifier->setModel(tmpmodes.triafficher(ui->comboBox_Tri->currentText()));
}
}
void modesinter::on_recherche_cursorPositionChanged(int arg1, int arg2)
{
ui->tablemodifier->setModel(tmpmodes.afficherecherche(ui->recherche->text()));
QString test =ui->recherche->text();
if(test=="")
{
ui->tablemodifier->setModel(tmpmodes.afficher());//refresh
}
}
void modesinter::on_PDF_clicked()
{
QString strStream;
QTextStream out(&strStream);
const int rowCount = ui->tablemodifier->model()->rowCount();
const int columnCount =ui->tablemodifier->model()->columnCount();
out << "<html>\n"
"<head>\n"
"<meta Content=\"Text/html; charset=Windows-1251\">\n"
<< QString("<title>%1</title>\n").arg("eleve")
<< "</head>\n"
"<body bgcolor=#F4B8B8 link=#5000A0>\n"
// "<img src='C:/Users/ksemt/Desktop/final/icon/logo.webp' width='20' height='20'>\n"
"<img src='C:/Users/DeLL/Desktop/logooo.png' width='100' height='100'>\n"
"<h1> Liste des Session </h1>"
"<h1> </h1>"
"<table border=1 cellspacing=0 cellpadding=2>\n";
// headers
out << "<thead><tr bgcolor=#f0f0f0>";
for (int column = 0; column < columnCount; column++)
if (!ui->tablemodifier->isColumnHidden(column))
out << QString("<th>%1</th>").arg(ui->tablemodifier->model()->headerData(column, Qt::Horizontal).toString());
out << "</tr></thead>\n";
// data table
for (int row = 0; row < rowCount; row++) {
out << "<tr>";
for (int column = 0; column < columnCount; column++) {
if (!ui->tablemodifier->isColumnHidden(column)) {
QString data = ui->tablemodifier->model()->data(ui->tablemodifier->model()->index(row, column)).toString().simplified();
out << QString("<td bkcolor=0>%1</td>").arg((!data.isEmpty()) ? data : QString(" "));
}
}
out << "</tr>\n";
}
out << "</table>\n"
"</body>\n"
"</html>\n";
QTextDocument *document = new QTextDocument();
document->setHtml(strStream);
QPrinter printer;
QPrintDialog *dialog = new QPrintDialog(&printer, NULL);
if (dialog->exec() == QDialog::Accepted) {
document->print(&printer);
}
}
void modesinter::on_ModifierBouton_clicked()
{
if((ui->Nom_mod->toPlainText() != "") &&(ui->etat_mod->toPlainText() != "")&&(ui->decription_mod->toPlainText() != ""))
{
if(tmpmodes.modifier(ui->Nom_mod->toPlainText(),ui->etat_mod->toPlainText(),ui->datedebut_mod->dateTime(),ui->datefin_mod->dateTime(),ui->decription_mod->toPlainText(),ui->comboBox_modif->currentText()))
{
//refresh combobox + tableau
refresh();
//NOTIFICATION
trayIcon = new QSystemTrayIcon(this);
trayIcon->setVisible(true);
trayIcon->setIcon(this->style()->standardIcon(QStyle::SP_DesktopIcon));
trayIcon->setToolTip("Modifier" "\n"
"Modifier avec sucées");
trayIcon->showMessage("Modifier","Modifier avec sucées",QSystemTrayIcon::Warning,1500);
trayIcon->show();
}
else
{
QMessageBox::critical(this, QObject::tr("Modifier un mode"),
QObject::tr("Erreur !.\n"
"Click Cancel to exit."), QMessageBox::Cancel);
}
}
}
void modesinter::on_SupprimerBouton_clicked()
{
QMessageBox::StandardButton reply =QMessageBox::question(this,
"Supprimer","Voulez-vous vraiment supprimer ?",
QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes)
{
bool test=tmpmodes.supprimer(ui->comboBox->currentText().toInt());
if(test)
{
//refresh combobox + tableau
refresh();
//NOTIFICATION
trayIcon = new QSystemTrayIcon(this);
trayIcon->setVisible(true);
trayIcon->setIcon(this->style()->standardIcon(QStyle::SP_DesktopIcon));
trayIcon->setToolTip("Supprimer" "\n"
"Supprimer avec sucées");
trayIcon->showMessage("Supprimer","Supprimer avec sucées",QSystemTrayIcon::Warning,1500);
trayIcon->show();
}
else
{
QMessageBox::critical(this, QObject::tr("Supprimer un mode"),
QObject::tr("Erreur !.\n"
"Click Cancel to exit."), QMessageBox::Cancel);
}
}
}
| [
"mindsmatter@isae.edu.ib"
] | mindsmatter@isae.edu.ib |
d5bbff1cc24d4fdd77d46954ffa6898256594b21 | 6e4aa50e275048cdedef07b79f5d51bd29a7bef1 | /IPST_2016/o59_mar_c2_wormholes.cpp | 2f2350256dfffa236c1beae1ca11054d701f5a6e | [] | no_license | KorlaMarch/competitive-programming | 4b0790b8aed4286cdd65cf6e4584e61376a2615e | fa8d650938ad5f158c8299199a3d3c370f298a32 | refs/heads/master | 2021-03-27T12:31:10.145264 | 2019-03-03T02:30:51 | 2019-03-03T02:30:51 | 34,978,427 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | #include "stdio.h"
#include "stdlib.h"
#include "algorithm"
int k,m,xi1,yi1,xi2,yi2;
int hx1[40],hy1[40],hx2[40],hy2[40];
int wdis[40][40];
int distance(int x1, int y1, int x2, int y2){
return abs(x1-x2)+abs(y1-y2);
}
int main(){
scanf("%d%d",&k,&m);
for(int i = 0; i < k; i++){
scanf("%d%d%d%d",&hx1[i],&hy1[i],&hx2[i],&hy2[i]);
}
for(int i = 0; i < k; i++){
for(int j = 0; j < k; j++){
wdis[i][j] = std::min( std::min(distance(hx1[i],hy1[i],hx1[j],hy1[j]),distance(hx1[i],hy1[i],hx2[j],hy2[j])) ,
std::min(distance(hx2[i],hy2[i],hx1[j],hy1[j]),distance(hx2[i],hy2[i],hx2[j],hy2[j])) );
}
}
//all pair shortest path
for(int x = 0; x < k; x++){
for(int i = 0; i < k; i++){
for(int j = 0; j < k; j++){
wdis[i][j] = std::min(wdis[i][j],wdis[i][x]+wdis[x][j]);
}
}
}
for(int x = 0; x < m; x++){
scanf("%d%d%d%d",&xi1,&yi1,&xi2,&yi2);
int ans = distance(xi1,yi1,xi2,yi2);
for(int i = 0; i < k; i++){
for(int j = 0; j < k; j++){
const int nwDis = std::min(distance(xi1,yi1,hx1[i],hy1[i]),distance(xi1,yi1,hx2[i],hy2[i])) +
wdis[i][j] +
std::min(distance(hx1[j],hy1[j],xi2,yi2),distance(hx2[j],hy2[j],xi2,yi2));
if(nwDis<ans){
ans = nwDis;
}
}
}
printf("%d\n", ans);
}
} | [
"korla.march@gmail.com"
] | korla.march@gmail.com |
99f5017b4192780114362a5b381c50d9624dc9ae | 8b0aa0a3143f7f57da837dff6a7bb31f65005b9c | /export/linux/obj/include/flixel/util/FlxSort.h | 5c92e85307c4b16dbc3f524a75d6d9a73ecc37d6 | [] | no_license | HedgehogFog/HaxePolygon | 124f58641ecf09f7cd5b13b612d01e843c4b7d45 | 0812c7d663985148e142611da197016b59492ad9 | refs/heads/master | 2020-04-26T02:26:59.219400 | 2019-03-01T07:38:25 | 2019-03-01T07:38:25 | 173,235,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 2,066 | h | // Generated by Haxe 3.4.7
#ifndef INCLUDED_flixel_util_FlxSort
#define INCLUDED_flixel_util_FlxSort
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(flixel,FlxBasic)
HX_DECLARE_CLASS1(flixel,FlxObject)
HX_DECLARE_CLASS2(flixel,util,FlxSort)
HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable)
namespace flixel{
namespace util{
class HXCPP_CLASS_ATTRIBUTES FlxSort_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef FlxSort_obj OBJ_;
FlxSort_obj();
public:
enum { _hx_ClassId = 0x7feb7832 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="flixel.util.FlxSort")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"flixel.util.FlxSort"); }
hx::ObjectPtr< FlxSort_obj > __new() {
hx::ObjectPtr< FlxSort_obj > __this = new FlxSort_obj();
__this->__construct();
return __this;
}
static hx::ObjectPtr< FlxSort_obj > __alloc(hx::Ctx *_hx_ctx) {
FlxSort_obj *__this = (FlxSort_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(FlxSort_obj), false, "flixel.util.FlxSort"));
*(void **)__this = FlxSort_obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~FlxSort_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_HCSTRING("FlxSort","\xd0","\x60","\xb0","\xdc"); }
static void __boot();
static int ASCENDING;
static int DESCENDING;
static int byY(int Order, ::flixel::FlxObject Obj1, ::flixel::FlxObject Obj2);
static ::Dynamic byY_dyn();
static int byValues(int Order,Float Value1,Float Value2);
static ::Dynamic byValues_dyn();
};
} // end namespace flixel
} // end namespace util
#endif /* INCLUDED_flixel_util_FlxSort */
| [
"hedgehog_fogs@mail.ru"
] | hedgehog_fogs@mail.ru |
5224d037d7bb6694ebfa19a8e0f88cb03b022b29 | 368a2407c6b559bcca85ce20bbabf98fab4c095b | /BackGround.cpp | c07b3cc635bf4010326a3523e27a7f32a85e71f6 | [] | no_license | OkonomiSource/OkonomiGame | c45f7ee9fd1b06fa3ba9cf20f01038d6906b2649 | 12ef740429c64446ce1d7957fb99c261f6caaf77 | refs/heads/master | 2022-05-27T19:56:00.593763 | 2020-05-04T15:04:06 | 2020-05-04T15:04:06 | 260,480,577 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,162 | cpp | #include"BackGround.h"
// コンストラクタ
CBackGround::CBackGround()
{
}
CBackGround::CBackGround(unsigned int uiBG)
{
SetMapChips(uiBG);
}
// デストラクタ
CBackGround::~CBackGround()
{
for (int i = 0; i < BG_Y_MAX; i++)
{
for (int j = 0; j < BG_X_MAX; j++) {
DeleteGraph(iMapchips_Bottom[i][j]);
}
}
}
void CBackGround::SetMapChips(unsigned int uiBG)
{
switch (uiBG)
{
case GROUND:
// 縦一列を設定
for (int i = 0; i < BG_Y_MAX; i++)
{
// 横一列を設定
for (int j = 0; j < BG_X_MAX; j++) {
this->iMapchips_Bottom[i][j] = LoadGraph("image/Mapchip/640x480/pipo-map001_at-sabaku/04.png");
}
}
break;
case RIVER:
// 縦一列を設定
for (int i = 0; i < BG_Y_MAX; i++)
{
// 横一列を設定
for (int j = 0; j < BG_X_MAX; j++) {
this->iMapchips_Bottom[i][j] = LoadGraph("image/Mapchip/640x480/pipo-map001_at-umi/04.png");
}
}
break;
default:
break;
}
}
void CBackGround::DrawBackGround()
{
for (int i = 0; i < BG_Y_MAX; i++)
{
// 横一列を設定
for (int j = 0; j < BG_X_MAX; j++) {
DrawGraph(j * 32, i * 32, this->iMapchips_Bottom[i][j], TRUE);
}
}
}
| [
"username@example.com"
] | username@example.com |
c6e9436f503d4526567ea489d866d2c70e7be138 | df782bd7edc183c0c0446631c1a588364d738889 | /A4/Image.h | e4977c64be9699b4be2512a77def813b23b20043 | [] | no_license | bpospeck/CSU-CS410 | a025a105d74736c71eec0444ab868fdfb702e922 | fda686c088de02865c5e0ed71a9519c0d66e16ad | refs/heads/master | 2020-03-27T09:23:27.007226 | 2018-08-27T18:53:11 | 2018-08-27T18:53:11 | 146,336,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,366 | h | // Bradley Pospeck
// Image class declaration
#ifndef IMAGE_H
#define IMAGE_H
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <Eigen/Dense>
#include <Models.h>
#include <Model.h>
#include <Sphere.h>
#include <Light.h>
using std::ifstream;
using std::string;
using std::cout;
using std::cerr;
using std::stringstream;
using std::max;
using Eigen::Vector3d;
using Eigen::Vector3i;
using Eigen::Matrix3d;
class Image
{
private:
// Class collections
Models* mods;
Sphere* sphereCollect;
Light* lightCollect;
// Camera vars
Vector3d eye; // Camera location
Vector3d look; // Direction camera is looking
Vector3d up; // Vector defining which direction is 'up'
Vector3d camW; // Camera's Z-axis, W
Vector3d camU, camV;
// Counting objs, spheres and lights
string models;
string spheres;
string lights;
int numModels = 0;
int numSpheres = 0;
int numLights = 0;
// near clipping plane vars
double focalLength; // distance from eye/focal point to near clipping plane
double left, bottom, right, top; // near clipping plane bounds
int resWidth, resHeight; // Image resolution
// recursion depth for reflection: 0 means no reflection
int recursion=0;
// ambient light
double ambR;
double ambG;
double ambB;
// Intersection vars
vector<Eigen::Vector3d> pixels;
vector<Eigen::Vector3d> rays;
vector<Eigen::Vector3i> rgbPix;
vector<double> tVals;
Matrix3d M,M1,M2,M3;
double beta,gamma;
double tmin = 1000000.0;
double tmax = 0.0;
// Pixel Methods
double getPx(const int& i);
double getPy(const int& j);
// Coloring pixels and rayTracing recursion
bool isShadowFromSphere(Vector3d lightLoc, Vector3d point, Sphere sphere);
Vector3d calcSphCol(Sphere& sphere,const Eigen::Vector3d& ray,const double t, Vector3d& point);
Vector3d calcObjCol(Object3d& object,const Eigen::Vector3d& ray,const double t, Vector3d& point, const int& faceInd);
Vector3d rayTrace(Vector3d& point,Vector3d& ray,Vector3d accum,Vector3d refatt,int depth);
public:
~Image(); // destructor
bool isComment(const string& s);
void readDriver(ifstream& sceneInfo);
void setCamera();
void setSpheres();
void setLights();
void setModels(const string& dName);
void setPixels();
void setRays();
void findIntersection();
void writePpm(const string& ppm);
};
#endif | [
"bpospeck@gmail.com"
] | bpospeck@gmail.com |
1d017d40202e3802418a6b80ade0563bb4db1ce7 | 1a93a3b56dc2d54ffe3ee344716654888b0af777 | /env/Library/include/qt/Qt3DExtras/5.12.9/Qt3DExtras/private/qspritesheetitem_p.h | f23d71cd7dd6657f56215856c9f82475be912b06 | [
"BSD-3-Clause",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-only",
"GPL-2.0-only"
] | permissive | h4vlik/TF2_OD_BRE | ecdf6b49b0016407007a1a049f0fdb952d58cbac | 54643b6e8e9d76847329b1dbda69efa1c7ae3e72 | refs/heads/master | 2023-04-09T16:05:27.658169 | 2021-02-22T14:59:07 | 2021-02-22T14:59:07 | 327,001,911 | 0 | 0 | BSD-3-Clause | 2021-02-22T14:59:08 | 2021-01-05T13:08:03 | null | UTF-8 | C++ | false | false | 2,678 | h | /****************************************************************************
**
** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QT3DEXTRAS_QSPRITESHEET_P_H
#define QT3DEXTRAS_QSPRITESHEET_P_H
#include <QRect>
#include <QVector>
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of other Qt classes. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <Qt3DCore/private/qnode_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DExtras {
class QSpriteSheetItem;
class QSpriteSheetItemPrivate: public Qt3DCore::QNodePrivate
{
QSpriteSheetItemPrivate();
int m_x;
int m_y;
int m_width;
int m_height;
Q_DECLARE_PUBLIC(QSpriteSheetItem)
};
} // Qt3DExtras
QT_END_NAMESPACE
#endif // QT3DEXTRAS_QSPRITESHEET_P_H
| [
"martin.cernil@ysoft.com"
] | martin.cernil@ysoft.com |
5174a14fb58128516066cfc88adb42b119441daf | c5fb6d1f24bd75f5e35d267739ea8f7cdcd4e26c | /linked_list/find_merge_point_of_two_list.cpp | 34020fe842d4bf978aab65f66e5fe3e492201172 | [] | no_license | ankishb/Algorithm-DS-Problems | 48c48be61d0c96365b7bbc97ec6f4f2de998eb2b | 76487e72b86d0038cc996e2ac416cc0673d1f6d6 | refs/heads/master | 2020-06-30T08:19:29.129966 | 2020-01-12T17:12:49 | 2020-01-12T17:12:49 | 200,775,653 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,921 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void collect_nodes(ListNode* root, stack<ListNode*> &s){
while(root != NULL){
s.push(root);
// cout<<root->val<<" ";
root = root->next;
}
// cout<<endl;
}
ListNode* naive_memory(ListNode *headA, ListNode *headB){
if(headA==NULL || headB==NULL) return NULL;
stack<ListNode*> s1;
stack<ListNode*> s2;
collect_nodes(headA, s1);
collect_nodes(headB, s2);
if(s1.top() != s2.top()) return NULL;
ListNode* temp;
while(!s1.empty() && !s2.empty()){
temp = s1.top();
s1.pop(); s2.pop();
if(s1.empty() || s2.empty()) return temp;
if(s1.top() != s2.top()) return temp;
}
return NULL;
}
ListNode* efficient(ListNode *headA, ListNode *headB){
if(headA==NULL || headB==NULL) return NULL;
int n1=0, n2=0;
ListNode* temp = headA;
while(temp != NULL){
n1++;
temp = temp->next;
}
temp = headB;
while(temp != NULL){
n2++;
temp = temp->next;
}
if(n1 > n2){
for(int i=0; i<n1-n2; i++){
headA = headA->next;
}
}
else if(n1 < n2){
for(int i=0; i<n2-n1; i++){
headB = headB->next;
}
}
while(headA != NULL){
if(headA == headB){
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
ListNode* two_pointer(ListNode *headA, ListNode *headB) {
ListNode *p1 = headA;
ListNode *p2 = headB;
if (p1 == NULL || p2 == NULL) return NULL;
while (p1 != NULL && p2 != NULL && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
//
// Any time they collide or reach end together without colliding
// then return any one of the pointers.
//
if (p1 == p2) return p1;
//
// If one of them reaches the end earlier then reuse it
// by moving it to the beginning of other list.
// Once both of them go through reassigning,
// they will be equidistant from the collision point.
//
if (p1 == NULL) p1 = headB;
if (p2 == NULL) p2 = headA;
}
return p1;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// return naive_memory(headA, headB);
// return efficient(headA, headB);
return two_pointer(headA, headB);
}
};
// not working
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return head;
if(head->next == NULL) return head;
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next = head->next;
while(cur != NULL){
if(next == NULL){
// make head connection and return
cur->next = prev;
head = cur;
return head;
}
cur->next = prev;
prev = cur;
cur = next;
next = next->next;
}
return head;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
headA = reverseList(headA);
headB = reverseList(headB);
while(headA != NULL && headB != NULL){
if((headA->val == headB->val) && (headA->next->val != headB->next->val)){
ListNode* new_node = new ListNode(headA->val);
return new_node;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};
int findMergeNode(SinglyLinkedListNode* headA, SinglyLinkedListNode* headB) {
if(headA==NULL || headB==NULL) return -1;
int n1=0, n2=0;
SinglyLinkedListNode* temp = headA;
while(temp != NULL){
n1++;
temp = temp->next;
}
temp = headB;
while(temp != NULL){
n2++;
temp = temp->next;
}
if(n1 > n2){
for(int i=0; i<n1-n2; i++){
headA = headA->next;
}
}
else if(n1 < n2){
for(int i=0; i<n2-n1; i++){
headB = headB->next;
}
}
while(headA != NULL){
if(headA == headB){
return headA->data;
}
headA = headA->next;
headB = headB->next;
}
return -1;
}
| [
"bansal.ankish1@gmail.com"
] | bansal.ankish1@gmail.com |
6de20ffaf4baccc2cbe28cd67924a69f94fc5f18 | 79d0f0fc29ae8521beb289bf79be27b8c2c4f898 | /simple_shape.h | 3c506d9934fbaf9bc92fc111b3fc193ea0ea88b9 | [] | no_license | eladtzemach/openglstar | c2fefa604840a78cbea0da513453357505f81201 | afed9f32fd67e81fe11325f5749d2181cdef50cf | refs/heads/master | 2021-07-08T14:03:30.659433 | 2017-10-04T19:02:04 | 2017-10-04T19:02:04 | 105,553,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,874 | h |
#ifndef CSI4130_SIMPLE_SHAPE_H_
#define CSI4130_SIMPLE_SHAPE_H_
#include <cassert>
#include <math.h>
#include <GL/glew.h>
#if WIN32
#include <gl/wglew.h>
#else
#include <GL/glext.h>
#endif
#include <iostream>
using namespace std;
class SimpleShape {
private:
const static int g_nPoints;
const static GLuint g_primitives[];
bool d_animated;
int d_index;
public:
GLfloat g_xVal[26];
GLfloat g_yVal[26];
GLfloat d_xPos;
GLfloat d_yPos;
GLfloat d_scale;
GLfloat d_angle;
public:
inline SimpleShape();
inline void zoom( GLfloat _scale );
inline void rotate( GLfloat _theta );
inline void moveHorizontal( GLfloat _xShift );
inline void moveVertical( GLfloat _yShift );
inline int getNPoints() const;
inline GLfloat getX( int _num );
inline GLfloat getY( int _num );
inline void nextPrimitive();
inline GLuint getPrimitive();
inline bool toggleAnimate();
};
SimpleShape::SimpleShape()
: d_xPos(0.0f), d_yPos(0.0f),
d_scale(1.0), d_angle(0.0f)
{
const float kfPi = 3.1415926535897932384626433832795;
const float kfRadius = 0.0616/2.0;
const float kfInnerRadius = kfRadius*(1.0/(sin((2.0*kfPi)/5.0)*2.0*cos(kfPi/10.0) + sin((3.0*kfPi)/10.0)));
int index = 1;
g_xVal[0] = 0.0;
g_yVal[0] = 0.0;
for (int iVertIndex = 0; iVertIndex < 20; ++iVertIndex) {
float fAngleStart = kfPi/2.0 + (iVertIndex*2.0*kfPi)/20.0;
float fAngleEnd = fAngleStart + kfPi/10.0;
if (iVertIndex % 2 == 0) {
g_xVal[index] = kfRadius*cos(fAngleStart)/1.9;
g_yVal[index] = kfRadius*sin(fAngleStart);
g_xVal[index+1] = kfInnerRadius*cos(fAngleEnd)/1.9;
g_yVal[index+1] = kfInnerRadius*sin(fAngleEnd);
index++;
} else {
g_xVal[index] = kfInnerRadius*cos(fAngleStart)/1.9;
g_yVal[index] = kfInnerRadius*sin(fAngleStart);
g_xVal[index+1] = kfRadius*cos(fAngleEnd)/1.9;
g_yVal[index+1] = kfRadius*sin(fAngleEnd);
index++;
}}
}
void SimpleShape::zoom( GLfloat _scale ) {
// scale in x and y
d_scale *= _scale;
return;
}
void SimpleShape::moveHorizontal( GLfloat _xShift ) {
d_xPos += _xShift;
return;
}
void SimpleShape::moveVertical( GLfloat _yShift ) {
d_yPos += _yShift;
return;
}
void SimpleShape::rotate( GLfloat _theta ) {
d_angle += _theta;
if ( d_angle > 360.0 ) d_angle -= 360.0;
return;
}
int SimpleShape::getNPoints() const {
return g_nPoints;
}
GLfloat SimpleShape::getX( int _num ) {
assert( _num < g_nPoints );
return g_xVal[_num];
}
GLfloat SimpleShape::getY( int _num ) {
assert( _num < g_nPoints );
return g_yVal[_num];
}
void SimpleShape::nextPrimitive() {
d_index = (++d_index)%8;
return;
}
GLuint SimpleShape::getPrimitive() {
return g_primitives[d_index];
}
bool SimpleShape::toggleAnimate() {
d_animated = !d_animated;
return d_animated;
}
#endif
| [
"eladtzemach@gmail.com"
] | eladtzemach@gmail.com |
eca2c0f623b1df42988d0404b7766fd5a5965606 | 768371d8c4db95ad629da1bf2023b89f05f53953 | /applayerprotocols/httpexamples/TestWebBrowser/src/Main.cpp | f93b9f46cb9477e9f18be963dcf719fa7d15f0dc | [] | no_license | SymbianSource/oss.FCL.sf.mw.netprotocols | 5eae982437f5b25dcf3d7a21aae917f5c7c0a5bd | cc43765893d358f20903b5635a2a125134a2ede8 | refs/heads/master | 2021-01-13T08:23:16.214294 | 2010-10-03T21:53:08 | 2010-10-03T21:53:08 | 71,899,655 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | cpp | // Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//
#include <e32base.h>
#include <http.h>
#include <chttpformencoder.h>
#include "httpexampleutils.h"
#include "testwebbrowser.h"
// Create a test object, invoke the tests using it and remove
LOCAL_D void TestL()
{
// Start C32 and initalize some device drivers. This is necessary when running a test console as these won't
// have been started
CHttpExampleUtils::InitCommsL();
CHttpExampleUtils* httpUtils = CHttpExampleUtils::NewL ( _L ( "Test web browser" ) );
CleanupStack::PushL ( httpUtils );
// create an active scheduler to use
CActiveScheduler* scheduler = new(ELeave) CActiveScheduler();
CleanupStack::PushL( scheduler );
CActiveScheduler::Install( scheduler );
// Create and start the web browser
CTestWebBrowser* webBrowser = CTestWebBrowser::NewLC ( *httpUtils );
CActiveScheduler::Start ();
CleanupStack::Pop ( webBrowser ); // Pop and destroy webBrowser
delete webBrowser;
CleanupStack::Pop ( scheduler ); // Pop and destroy scheduler
delete scheduler;
CleanupStack::Pop ( httpUtils ); // pop and destroy httpUtils
delete httpUtils;
}
// Main program - run the tests within a TRAP harness, reporting any errors that
// occur via the panic mechanism. Test for memory leaks using heap marking.
GLDEF_C TInt E32Main()
{
__UHEAP_MARK;
CTrapCleanup* tc = CTrapCleanup::New();
TRAPD( err,TestL() );
if ( err != KErrNone )
User::Panic( _L( "Test failed with error code: %i" ), err );
delete tc;
__UHEAP_MARKEND;
return KErrNone;
}
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
8ce4203ac903ce8264ea41a616933fd43ae6d311 | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /lib/Target/RISCV/RISCVRegisterInfo.cpp | 35363bf37c0dbf8e590548ba81abf11270d14a89 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 13,425 | cpp | //===-- RISCVRegisterInfo.cpp - RISCV Register Information ------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the RISCV implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "RISCVRegisterInfo.h"
#include "RISCV.h"
#include "RISCVMachineFunctionInfo.h"
#include "RISCVSubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/Support/ErrorHandling.h"
#define GET_REGINFO_TARGET_DESC
#include "RISCVGenRegisterInfo.inc"
using namespace llvm;
static_assert(RISCV::X1 == RISCV::X0 + 1, "Register list not consecutive");
static_assert(RISCV::X31 == RISCV::X0 + 31, "Register list not consecutive");
static_assert(RISCV::F1_H == RISCV::F0_H + 1, "Register list not consecutive");
static_assert(RISCV::F31_H == RISCV::F0_H + 31,
"Register list not consecutive");
static_assert(RISCV::F1_F == RISCV::F0_F + 1, "Register list not consecutive");
static_assert(RISCV::F31_F == RISCV::F0_F + 31,
"Register list not consecutive");
static_assert(RISCV::F1_D == RISCV::F0_D + 1, "Register list not consecutive");
static_assert(RISCV::F31_D == RISCV::F0_D + 31,
"Register list not consecutive");
static_assert(RISCV::V1 == RISCV::V0 + 1, "Register list not consecutive");
static_assert(RISCV::V31 == RISCV::V0 + 31, "Register list not consecutive");
RISCVRegisterInfo::RISCVRegisterInfo(unsigned HwMode)
: RISCVGenRegisterInfo(RISCV::X1, /*DwarfFlavour*/0, /*EHFlavor*/0,
/*PC*/0, HwMode) {}
const MCPhysReg *
RISCVRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
auto &Subtarget = MF->getSubtarget<RISCVSubtarget>();
if (MF->getFunction().getCallingConv() == CallingConv::GHC)
return CSR_NoRegs_SaveList;
if (MF->getFunction().hasFnAttribute("interrupt")) {
if (Subtarget.hasStdExtD())
return CSR_XLEN_F64_Interrupt_SaveList;
if (Subtarget.hasStdExtF())
return CSR_XLEN_F32_Interrupt_SaveList;
return CSR_Interrupt_SaveList;
}
switch (Subtarget.getTargetABI()) {
default:
llvm_unreachable("Unrecognized ABI");
case RISCVABI::ABI_ILP32:
case RISCVABI::ABI_LP64:
return CSR_ILP32_LP64_SaveList;
case RISCVABI::ABI_ILP32F:
case RISCVABI::ABI_LP64F:
return CSR_ILP32F_LP64F_SaveList;
case RISCVABI::ABI_ILP32D:
case RISCVABI::ABI_LP64D:
return CSR_ILP32D_LP64D_SaveList;
}
}
BitVector RISCVRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
const RISCVFrameLowering *TFI = getFrameLowering(MF);
BitVector Reserved(getNumRegs());
// Mark any registers requested to be reserved as such
for (size_t Reg = 0; Reg < getNumRegs(); Reg++) {
if (MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(Reg))
markSuperRegs(Reserved, Reg);
}
// Use markSuperRegs to ensure any register aliases are also reserved
markSuperRegs(Reserved, RISCV::X0); // zero
markSuperRegs(Reserved, RISCV::X2); // sp
markSuperRegs(Reserved, RISCV::X3); // gp
markSuperRegs(Reserved, RISCV::X4); // tp
if (TFI->hasFP(MF))
markSuperRegs(Reserved, RISCV::X8); // fp
// Reserve the base register if we need to realign the stack and allocate
// variable-sized objects at runtime.
if (TFI->hasBP(MF))
markSuperRegs(Reserved, RISCVABI::getBPReg()); // bp
// V registers for code generation. We handle them manually.
markSuperRegs(Reserved, RISCV::VL);
markSuperRegs(Reserved, RISCV::VTYPE);
markSuperRegs(Reserved, RISCV::VXSAT);
markSuperRegs(Reserved, RISCV::VXRM);
// Floating point environment registers.
markSuperRegs(Reserved, RISCV::FRM);
markSuperRegs(Reserved, RISCV::FFLAGS);
assert(checkAllSuperRegsMarked(Reserved));
return Reserved;
}
bool RISCVRegisterInfo::isAsmClobberable(const MachineFunction &MF,
MCRegister PhysReg) const {
return !MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(PhysReg);
}
bool RISCVRegisterInfo::isConstantPhysReg(MCRegister PhysReg) const {
return PhysReg == RISCV::X0;
}
const uint32_t *RISCVRegisterInfo::getNoPreservedMask() const {
return CSR_NoRegs_RegMask;
}
// Frame indexes representing locations of CSRs which are given a fixed location
// by save/restore libcalls.
static const std::map<unsigned, int> FixedCSRFIMap = {
{/*ra*/ RISCV::X1, -1},
{/*s0*/ RISCV::X8, -2},
{/*s1*/ RISCV::X9, -3},
{/*s2*/ RISCV::X18, -4},
{/*s3*/ RISCV::X19, -5},
{/*s4*/ RISCV::X20, -6},
{/*s5*/ RISCV::X21, -7},
{/*s6*/ RISCV::X22, -8},
{/*s7*/ RISCV::X23, -9},
{/*s8*/ RISCV::X24, -10},
{/*s9*/ RISCV::X25, -11},
{/*s10*/ RISCV::X26, -12},
{/*s11*/ RISCV::X27, -13}
};
bool RISCVRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
Register Reg,
int &FrameIdx) const {
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
if (!RVFI->useSaveRestoreLibCalls(MF))
return false;
auto FII = FixedCSRFIMap.find(Reg);
if (FII == FixedCSRFIMap.end())
return false;
FrameIdx = FII->second;
return true;
}
void RISCVRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS) const {
assert(SPAdj == 0 && "Unexpected non-zero SPAdj value");
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
MachineRegisterInfo &MRI = MF.getRegInfo();
const RISCVInstrInfo *TII = MF.getSubtarget<RISCVSubtarget>().getInstrInfo();
DebugLoc DL = MI.getDebugLoc();
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
Register FrameReg;
StackOffset Offset =
getFrameLowering(MF)->getFrameIndexReference(MF, FrameIndex, FrameReg);
bool IsRVVSpill = TII->isRVVSpill(MI, /*CheckFIs*/ false);
if (!IsRVVSpill)
Offset += StackOffset::getFixed(MI.getOperand(FIOperandNum + 1).getImm());
if (!isInt<32>(Offset.getFixed())) {
report_fatal_error(
"Frame offsets outside of the signed 32-bit range not supported");
}
MachineBasicBlock &MBB = *MI.getParent();
bool FrameRegIsKill = false;
// If required, pre-compute the scalable factor amount which will be used in
// later offset computation. Since this sequence requires up to two scratch
// registers -- after which one is made free -- this grants us better
// scavenging of scratch registers as only up to two are live at one time,
// rather than three.
Register ScalableFactorRegister;
unsigned ScalableAdjOpc = RISCV::ADD;
if (Offset.getScalable()) {
int64_t ScalableValue = Offset.getScalable();
if (ScalableValue < 0) {
ScalableValue = -ScalableValue;
ScalableAdjOpc = RISCV::SUB;
}
// 1. Get vlenb && multiply vlen with the number of vector registers.
ScalableFactorRegister =
TII->getVLENFactoredAmount(MF, MBB, II, DL, ScalableValue);
}
if (!isInt<12>(Offset.getFixed())) {
// The offset won't fit in an immediate, so use a scratch register instead
// Modify Offset and FrameReg appropriately
Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
TII->movImm(MBB, II, DL, ScratchReg, Offset.getFixed());
if (MI.getOpcode() == RISCV::ADDI && !Offset.getScalable()) {
BuildMI(MBB, II, DL, TII->get(RISCV::ADD), MI.getOperand(0).getReg())
.addReg(FrameReg)
.addReg(ScratchReg, RegState::Kill);
MI.eraseFromParent();
return;
}
BuildMI(MBB, II, DL, TII->get(RISCV::ADD), ScratchReg)
.addReg(FrameReg)
.addReg(ScratchReg, RegState::Kill);
Offset = StackOffset::get(0, Offset.getScalable());
FrameReg = ScratchReg;
FrameRegIsKill = true;
}
if (!Offset.getScalable()) {
// Offset = (fixed offset, 0)
MI.getOperand(FIOperandNum)
.ChangeToRegister(FrameReg, false, false, FrameRegIsKill);
if (!IsRVVSpill)
MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
else {
if (Offset.getFixed()) {
Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), ScratchReg)
.addReg(FrameReg, getKillRegState(FrameRegIsKill))
.addImm(Offset.getFixed());
MI.getOperand(FIOperandNum)
.ChangeToRegister(ScratchReg, false, false, true);
}
}
} else {
// Offset = (fixed offset, scalable offset)
// Step 1, the scalable offset, has already been computed.
assert(ScalableFactorRegister &&
"Expected pre-computation of scalable factor in earlier step");
// 2. Calculate address: FrameReg + result of multiply
if (MI.getOpcode() == RISCV::ADDI && !Offset.getFixed()) {
BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), MI.getOperand(0).getReg())
.addReg(FrameReg, getKillRegState(FrameRegIsKill))
.addReg(ScalableFactorRegister, RegState::Kill);
MI.eraseFromParent();
return;
}
Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
BuildMI(MBB, II, DL, TII->get(ScalableAdjOpc), VL)
.addReg(FrameReg, getKillRegState(FrameRegIsKill))
.addReg(ScalableFactorRegister, RegState::Kill);
if (IsRVVSpill && Offset.getFixed()) {
// Scalable load/store has no immediate argument. We need to add the
// fixed part into the load/store base address.
BuildMI(MBB, II, DL, TII->get(RISCV::ADDI), VL)
.addReg(VL)
.addImm(Offset.getFixed());
}
// 3. Replace address register with calculated address register
MI.getOperand(FIOperandNum).ChangeToRegister(VL, false, false, true);
if (!IsRVVSpill)
MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getFixed());
}
auto ZvlssegInfo = TII->isRVVSpillForZvlsseg(MI.getOpcode());
if (ZvlssegInfo) {
Register VL = MRI.createVirtualRegister(&RISCV::GPRRegClass);
BuildMI(MBB, II, DL, TII->get(RISCV::PseudoReadVLENB), VL);
uint32_t ShiftAmount = Log2_32(ZvlssegInfo->second);
if (ShiftAmount != 0)
BuildMI(MBB, II, DL, TII->get(RISCV::SLLI), VL)
.addReg(VL)
.addImm(ShiftAmount);
// The last argument of pseudo spilling opcode for zvlsseg is the length of
// one element of zvlsseg types. For example, for vint32m2x2_t, it will be
// the length of vint32m2_t.
MI.getOperand(FIOperandNum + 1).ChangeToRegister(VL, /*isDef=*/false);
}
}
Register RISCVRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
const TargetFrameLowering *TFI = getFrameLowering(MF);
return TFI->hasFP(MF) ? RISCV::X8 : RISCV::X2;
}
const uint32_t *
RISCVRegisterInfo::getCallPreservedMask(const MachineFunction & MF,
CallingConv::ID CC) const {
auto &Subtarget = MF.getSubtarget<RISCVSubtarget>();
if (CC == CallingConv::GHC)
return CSR_NoRegs_RegMask;
switch (Subtarget.getTargetABI()) {
default:
llvm_unreachable("Unrecognized ABI");
case RISCVABI::ABI_ILP32:
case RISCVABI::ABI_LP64:
return CSR_ILP32_LP64_RegMask;
case RISCVABI::ABI_ILP32F:
case RISCVABI::ABI_LP64F:
return CSR_ILP32F_LP64F_RegMask;
case RISCVABI::ABI_ILP32D:
case RISCVABI::ABI_LP64D:
return CSR_ILP32D_LP64D_RegMask;
}
}
const TargetRegisterClass *
RISCVRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
const MachineFunction &) const {
if (RC == &RISCV::VMV0RegClass)
return &RISCV::VRRegClass;
return RC;
}
void RISCVRegisterInfo::getOffsetOpcodes(const StackOffset &Offset,
SmallVectorImpl<uint64_t> &Ops) const {
// VLENB is the length of a vector register in bytes. We use <vscale x 8 x i8>
// to represent one vector register. The dwarf offset is
// VLENB * scalable_offset / 8.
assert(Offset.getScalable() % 8 == 0 && "Invalid frame offset");
// Add fixed-sized offset using existing DIExpression interface.
DIExpression::appendOffset(Ops, Offset.getFixed());
unsigned VLENB = getDwarfRegNum(RISCV::VLENB, true);
int64_t VLENBSized = Offset.getScalable() / 8;
if (VLENBSized > 0) {
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(VLENBSized);
Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
Ops.push_back(dwarf::DW_OP_mul);
Ops.push_back(dwarf::DW_OP_plus);
} else if (VLENBSized < 0) {
Ops.push_back(dwarf::DW_OP_constu);
Ops.push_back(-VLENBSized);
Ops.append({dwarf::DW_OP_bregx, VLENB, 0ULL});
Ops.push_back(dwarf::DW_OP_mul);
Ops.push_back(dwarf::DW_OP_minus);
}
}
unsigned
RISCVRegisterInfo::getRegisterCostTableIndex(const MachineFunction &MF) const {
return MF.getSubtarget<RISCVSubtarget>().hasStdExtC() ? 1 : 0;
}
| [
"agarny@hellix.com"
] | agarny@hellix.com |
d13341e460344da015dc0448908df982ff567c51 | e45fd4b2772b9553fc52f02e428016c8299115f1 | /Temp_13092019/AEPS_IMPS_Bill_Reversal_11092019_DEBUG_ON/src/makerequest.cpp | 7ff71f48df918e2a23b8ceb884b7a96c7e8c8c94 | [] | no_license | adarshaa08/gitexample | 0b5ddfd067bed5c7699e9129ae1df36812fae287 | 770230155380c1dd38a60cb7004119cce8f85d75 | refs/heads/master | 2021-01-07T20:06:44.769636 | 2020-02-20T12:14:56 | 2020-02-20T12:14:56 | 241,807,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,610 | cpp | #include "FPB.h"
#include "ui_FPB.h"
#include "displaymessage.h"
#include "Login.h"
//#include "CHeader.h"
#include"getprofile.h"
//extern GProfile GETProfile;
extern Login_leg1 configLoginLeg1;
extern Login_leg2 configLoginLeg2;
//unsigned char BM_Recvdata[1024*45];
int FPB::iMakeRequest(int TYPE)
{
FILE *fp=NULL;
int iRet = -1;
char cTagId[5];
int iTagId = 0;
char cFileBuuf[2];
int index = 0;
//unsigned char *tempBuff1=NULL;
memset(Recvdata,0,sizeof(Recvdata));
memset(cFileBuuf,0,sizeof(cFileBuuf));
//tempBuff1=Recvdata;
qDebug()<<"TYPE = "<<TYPE;
switch (TYPE)
{
case 0:
fp=fopen("/usr/FINO/FPB/REQ_Dollar/Leg1.txt","r");//Log in Leg1
break;
case 1:
fp=fopen("/usr/FINO/FPB/REQ_Dollar/Leg2N.txt","r");//Log in Leg1
break;
case 2:
fp=fopen("/usr/FINO/FPB/REQ_Dollar/Leg2.txt","r"); //Login Leg2
break;
case 3:
fp=fopen("/usr/FINO/FPB/REQ_Dollar/AEPSWITH.txt","r");// AEPS Withdrawal
break;
case 4:
fp=fopen("/usr/FINO/FPB/REQ_Dollar/AEPS_BALENQ.txt","r");
break;
case 5:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/LTS.txt","r"); // Last Transaction Status
break;
case 6:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/GETPROF.txt","r");
break;
case 7:
// fp = fopen("/usr/FINO/FPB/REQ_Dollar/BANKMAST.txt","r");
fp = fopen("/usr/FINO/FPB/REQ_Dollar/IMPS_BANKMAST.txt","r");
break;
case 8:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/AEPSMINI.txt","r");
break;
case 9:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/AEPSLTS.txt","r"); // LTTS-Last Ten Transaction Status
break;
case 10:
qDebug()<<"Inside the make request";
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTGSQ.txt","r");
break;
case 11:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTGenOTP.txt","r");
break;
case 12:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTOTPVAL.txt","r");
break;
case 13:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTGSK.txt","r");
break;
case 14:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTFEL.txt","r");
break;
case 15:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTSWC.txt","r");
break;
case 19:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTOIN.txt","r");
break;
case 21:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTCP.txt","r");
break;
case 22:
fp = fopen("/usr/FINO/FPB/REQ_Dollar/VTFC.txt","r");
break;
case 23:
qDebug()<<"23";
fp = fopen("/usr/FINO/FPB/REQ_Dollar/REFIRE.txt","r");
break;
case 24:
qDebug()<<"24";
fp = fopen("/usr/FINO/FPB/REQ_Dollar/REFUND.txt","r");
break;
case 25:
qDebug()<<"25";
fp = fopen("/usr/FINO/FPB/REQ_Dollar/BILLREFIRE.txt","r");
break;
default:
break;
}
if (fp==NULL)
{
qDebug()<<"fp == NULL";
//GL_Dialog_Message(graphicLib,"ERROR","Please load Request Files",GL_ICON_NONE,GL_BUTTON_NONE,3000);
return FUNC_ERROR;
}
do
{
while(*cFileBuuf != '$')
{
memset(cFileBuuf,0,sizeof(cFileBuuf));
iRet=fread(cFileBuuf,1,1,fp);
if(iRet != 1 )
{
fclose(fp);
if(strlen((char*)Recvdata) <=0)
{
qDebug()<<"fread failed";
return FUNC_ERROR;
}
else
return FUNC_OK;
}
if(*cFileBuuf != '$')
Recvdata[index++] = *cFileBuuf;
}
memset(cTagId,0,sizeof(cTagId));
fread(cTagId,3,1,fp);
iTagId = atoi(cTagId);
// call the db fuction
switch (TYPE) {
case 0:
iLogInLeg1(iTagId,&Recvdata[index]); // Log in LEG1
break;
case 1:
iLogInLeg2(iTagId,&Recvdata[index]); // Log in LEG2
break;
case 2:
// iLogInLeg2(iTagId,&Recvdata[index]); //Log in LEG2
break;
case 3:
iSetAEPS_With(iTagId,&Recvdata[index]); //AEPS Withdrawal
break;
case 4:
iSetAEPS_BalEnq(iTagId,&Recvdata[index]);//AEPS Balance Enquiry
break;
case 5:
iSetLTS(iTagId,&Recvdata[index]);//AEPS LTS last one transaction
break;
case 6:
iSetGet_Profile(iTagId,&Recvdata[index]);//Get Profile Enquiry
break;
case 7:
//iSetAEPSBANKMAST(iTagId,&Recvdata[index]);//Get AEPS Bank master // Temp BM
iSetIMPSBANKMAST(iTagId,&Recvdata[index]);//Get AEPS Bank master // Temp BM
break;
case 8:
iSetAEPSMiniState(iTagId,&Recvdata[index]);//Get AEPS Ministatement
break;
case 9:
iSetAEPSLTS(iTagId,&Recvdata[index]);//AEPS Last 10 Transactions
break;
case 10:
iSetFORGET(iTagId,&Recvdata[index]);
break;
case 11:
iSetOTP(iTagId,&Recvdata[index]);
break;
case 12:
iSetNEWPASS(iTagId,&Recvdata[index]);
break;
case 13:
iSetOTP(iTagId,&Recvdata[index]);
break;
// case 14:
// iSetFETCH(iTagId,&Recvdata[index]);
// break;
case 15:
iSetSEARCHWALK(iTagId,&Recvdata[index]);
break;
case 19:
// qDebug()<<"isetCustlimit";
iSetOTPIMPS(iTagId,&Recvdata[index]);
break;
case 21:
// qDebug()<<"isetCustlimit";
iSetCHANGE(iTagId,&Recvdata[index]);
break;
case 22:
iSetFINDCUSTOMER(iTagId,&Recvdata[index]);
break;
case 23:
iSetREFIRE(iTagId,&Recvdata[index]);
break;
case 24:
iSetREFUND(iTagId,&Recvdata[index]);
break;
case 25:
iSetBILLREFIRE(iTagId,&Recvdata[index]);
break;
default:
break;
}
// if(TYPE == 7) // Temp BM
// {
// printf("index : %d\n",index);
// index += strlen((char *)&BMRecvdata[index]); // Temp BM
// }
// else // Temp BM
index += strlen((char *)&Recvdata[index]);
memset(cFileBuuf,0,sizeof(cFileBuuf));
} while (iRet==1);
fclose(fp);
/*//consolprint(gSendData);
//S_FS_FILE *fp=NULL;
FS_unlink("/HOST/WITHF.TXT");
fp =FS_open("/HOST/WITHF.TXT","a");
FS_write(gSendData,strlen(gSendData),1,fp);
ttestall(0,100);
FS_close(fp);*/
return FUNC_OK;
}
//int FPB::iLogInLeg1(int tagID, unsigned char *value)
//{
// switch(tagID)
// {
// case 1:
// strcpy((char *)value,(char *)configLoginLeg2.ucRequestID_req);
// break;
// case 2:
// strcpy((char *)value,(char *)configLoginLeg2.ucMethodID_req);//Method id
// break;
// case 3:
// strcpy((char *)value,(char *)configLoginLeg2.ucTellerID_req);//teller id
// break;
// case 4:
// strcpy((char *)value,(char *)configLoginLeg2.ucIsEncrypt_req);//Is encrypt
// break;
// case 5:
// strcpy((char *)value,(char *)configLoginLeg2.ucUser_id_req);//User ID
// break;
// case 6:
// strcpy((char *)value,(char *)configLoginLeg2.ucPassword_req);//Password
// break;
// case 7:
// strcpy((char *)value,(char *)configLoginLeg2.ucClient_id_req);//Client Id
// break;
// case 8:
// strcpy((char *)value,(char *)configLoginLeg2.ucChannelID_req);//Channel ID //18012019 Dhiral
// break;
// case 9:
// strcpy((char *)value,(char *)configLoginLeg2.ucServiceID_req);//Service Id
// break;
// case 10:
// strcpy((char *)value,(char *)configLoginLeg2.ucChannel_req);//Service Id
// break;
// default:
// return FUNC_ERROR;
// }
// return FUNC_OK;
//}
int FPB::iLogInLeg1(int tagID, unsigned char *value)
{
switch(tagID)
{
case 1:
strcpy((char *)value,(char *)configLoginLeg1.ucRequestID_req);
break;
case 2:
strcpy((char *)value,(char *)configLoginLeg1.ucMethodID_req);//Method id
break;
case 3:
strcpy((char *)value,(char *)configLoginLeg1.ucTellerID_req);//teller id
break;
case 4:
strcpy((char *)value,(char *)configLoginLeg1.ucIsEncrypt_req);//Is encrypt
break;
case 5:
strcpy((char *)value,(char *)configLoginLeg1.ucUser_id_req);//User ID
break;
case 6:
strcpy((char *)value,(char *)configLoginLeg1.ucold_user_id);//Password
break;
case 7:
strcpy((char *)value,(char *)configLoginLeg1.ucClient_id_req);//Password
break;
return FUNC_ERROR;
}
return FUNC_OK;
}
int FPB::iLogInLeg2(int tagID, unsigned char *value)
{
switch(tagID)
{
case 1:
strcpy((char *)value,(char *)configLoginLeg2.ucRequestID_req);
break;
case 2:
strcpy((char *)value,(char *)configLoginLeg2.ucMethodID_req);//Method id
break;
case 3:
strcpy((char *)value,(char *)configLoginLeg2.ucTellerID_req);//teller id
break;
case 4:
strcpy((char *)value,(char *)configLoginLeg2.ucIsEncrypt_req);//Is encrypt
break;
case 5:
strcpy((char *)value,(char *)configLoginLeg2.ucUser_id_req);//User ID
break;
case 6:
strcpy((char *)value,(char *)configLoginLeg2.ucPassword_req);//Password
break;
case 7:
strcpy((char *)value,(char *)configLoginLeg2.ucClient_id_req);//Client Id
break;
case 8:
strcpy((char *)value,(char *)configLoginLeg2.ucChannelID_req);//Channel ID //18012019 Dhiral
break;
case 9:
strcpy((char *)value,(char *)configLoginLeg2.ucServiceID_req);//Service Id
break;
case 10:
strcpy((char *)value,(char *)configLoginLeg2.ucChannel_req);//Service Id
break;
case 11:
strcpy((char *)value,(char *)configLoginLeg2.ucGeoLattitude_req);
// printf("configLoginLeg2.ucGeoLattitude_req = %s\n",configLoginLeg2.ucGeoLattitude_req);
break;
case 12:
strcpy((char *)value,(char *)configLoginLeg2.ucGeoLongitude_req);//Method id
// printf("configLoginLeg2.ucGeoLongitude_req = %s\n",configLoginLeg2.ucGeoLongitude_req);
break;
case 13:
strcpy((char *)value,(char *)configLoginLeg2.ucVersion_req);//teller id
// printf("configLoginLeg2.ucVersion_req = %s\n",configLoginLeg2.ucVersion_req);
break;
case 14:
strcpy((char *)value,(char *)configLoginLeg2.ucMAC_DeviceID_req);//Is encrypt
// printf("configLoginLeg2.ucMAC_DeviceID_req = %s\n",configLoginLeg2.ucMAC_DeviceID_req);
break;
case 15:
strcpy((char *)value,(char *)configLoginLeg2.ucCellID_req);//User ID
// printf("configLoginLeg2.ucCellID_req = %s\n",configLoginLeg2.ucCellID_req);
break;
case 16:
strcpy((char *)value,(char *)configLoginLeg2.ucDeviceModel_req);//Password
// printf("configLoginLeg2.ucDeviceModel_req = %s\n",configLoginLeg2.ucDeviceModel_req);
break;
case 17:
strcpy((char *)value,(char *)configLoginLeg2.ucDeviceOS_req);//Client Id
// printf("configLoginLeg2.ucDeviceOS_req = %s\n",configLoginLeg2.ucDeviceOS_req);////
break;
case 18:
strcpy((char *)value,(char *)configLoginLeg2.ucMCC_req);//Channel ID //18012019 Dhiral
// printf("configLoginLeg2.ucMCC_req = %s\n",configLoginLeg2.ucMCC_req);
break;
case 19:
strcpy((char *)value,(char *)configLoginLeg2.ucMNC_req);//Service Id
// printf("configLoginLeg2.ucMNC_req = %s\n",configLoginLeg2.ucMNC_req);
break;
case 20:
strcpy((char *)value,(char *)configLoginLeg2.ucipAddress_req);//Service Id
// printf("configLoginLeg2.ucipAddress_req = %s\n",configLoginLeg2.ucipAddress_req);
break;
case 21:
strcpy((char *)value,(char *)configLoginLeg2.ucClient_id_req);//Service Id
// printf("configLoginLeg2.ucClient_id_req = %s\n",configLoginLeg2.ucClient_id_req);
break;
default:
return FUNC_ERROR;
}
return FUNC_OK;
}
| [
"adarshaa08@gmail.com"
] | adarshaa08@gmail.com |
954e98f85368274c003a101d63b33d9d54dfc417 | 7e68e284171cbd07acafdef379ae608fe930330a | /include/SAMCoupe.h | c97f25eeb36859659d7fab16e8af8868a6ea7287 | [
"MIT"
] | permissive | shattered/samdisk | c73f583068a6878f75fb08aef7a3d561fe677227 | 290ce465158360080120c5dcbcf307abc15896e7 | refs/heads/master | 2021-01-09T05:26:45.417748 | 2019-04-10T19:00:05 | 2019-04-10T19:00:09 | 80,769,442 | 1 | 0 | null | 2017-02-02T21:15:38 | 2017-02-02T21:15:38 | null | UTF-8 | C++ | false | false | 5,584 | h | #ifndef SAM_H
#define SAM_H
const int MGT_TRACKS = 80;
const int MGT_SIDES = 2;
const int MGT_SECTORS = 10;
const int MGT_TRACK_SIZE = MGT_SECTORS * SECTOR_SIZE;
const int MGT_DISK_SIZE = NORMAL_SIDES * NORMAL_TRACKS * MGT_TRACK_SIZE;
const int MGT_DISK_SECTORS = MGT_DISK_SIZE / SECTOR_SIZE;
const int MGT_DIR_TRACKS = 4;
// From SAM Technical Manual (bType, wSize, wOffset, wUnused, bPages, bStartPage)
const int MGT_FILE_HEADER_SIZE = 9;
// Maximum size of a file that will fit on a SAM disk
const int MAX_SAM_FILE_SIZE = (MGT_TRACKS * MGT_SIDES - MGT_DIR_TRACKS) * MGT_SECTORS * (SECTOR_SIZE - 2) - MGT_FILE_HEADER_SIZE;
typedef struct
{
uint8_t abUnk1; // +210
uint8_t abTypeZX; // +211 ZX type byte
uint8_t abZXLength[2]; // +212 ZX length
uint8_t abZXStart[2]; // +214 ZX start address
uint8_t abZXUnk2[2]; // +216 ?
uint8_t abZXExec[2]; // +218 ZX autostart line number (BASIC) or address (code):
// BASIC line active if b15+b14 are clear
// CODE address active if not &0000 or &ffff
} DIR_ZX;
typedef struct
{
uint8_t bDirTag; // +250 Directory tag for directory entry; BDOS uses next 6 chars for disk name (fi$
uint8_t bReserved; // +251 Reserved
uint8_t abSerial[2]; // +252 Random word for serial number (first entry only)
uint8_t bDirCode; // +254 Directory tag number for non-directory entries
uint8_t bExtraDirTracks; // +255 Number of directory tracks minus 4 (first entry only)
} DIR_EXTRA;
typedef struct
{
uint8_t bType; // +0 File type (b7=hidden, b6=protected)
uint8_t abName[10]; // +1 Filename padded with spaces; first char is zero for unused
uint8_t bSectorsHigh; // +11 MSB of number of sectors used
uint8_t bSectorsLow; // +12 LSB of number of sectors used
uint8_t bStartTrack; // +13 Track number for start of file
uint8_t bStartSector; // +14 Sector number for start of file
uint8_t abSectorMap[195]; // +15 Sector Address Map for file
union
{
uint8_t abLabel[10]; // +210 +D/Disciple data, or disk label when in first entry (0|255 for none (SAMDOS/BDOS))
DIR_ZX zx;
};
uint8_t bFlags; // +220 Flags (MGT use only) ; start of snapshot registers (22 bytes)
// iy, ix, de', bc', hl', af', de, bc, hl, iff1+I, sp, (af from stack)
uint8_t abFileInfo[11]; // +221 File type information; first byte is mode-1 for screen$
uint8_t abBDOS[4]; // +232 Spare; holds "BDOS" for first entry on BDOS disks
uint8_t bStartPage; // +236 Start page number in b4-b0 (b7-b5 are undefined)
uint8_t bPageOffsetLow; // +237 Start offset in range 32768-49151
uint8_t bPageOffsetHigh;
uint8_t bLengthInPages; // +239 Number of pages in length
uint8_t bLengthOffsetLow; // +240 Length MOD 16384 (b15 and b14 are undefined)
uint8_t bLengthOffsetHigh;
uint8_t bExecutePage; // +242 Execution page for CODE files, or 255 if no autorun
uint8_t bExecAddrLow; // +243 Execution offset (32768-49151) or BASIC autorun line (or 65535)
uint8_t bExecAddrHigh;
uint8_t bDay; // +245 Day of save (1-31), or 255 for invalid/none
uint8_t bMonth; // +246 Month (1-12); bit 7 set for BDOS 1.7a+ format: b6-b3 month, b2-b0 day-of-week (0=Sun)
uint8_t bYear; // +247 Year (year-1900); invalid if 255; MasterDOS has Y2K problem and uses (year%100)
uint8_t bHour; // +248 Hour; new BDOS: b7-b3 hour, b2-b0 low 3 bits of minute
uint8_t bMinute; // +249 Minute; new BDOS: b7-b5 upper 3 bits of minute, b4-b0 seconds/2
union
{
DIR_EXTRA extra;
char szLabelExtra[6];
};
} MGT_DIR;
static_assert(sizeof(MGT_DIR) == 256, "MGT_DIR size is wrong");
const int BDOS_LABEL_SIZE = 16; // Many things expect this to be 16
const int BDOS_SECTOR_SIZE = 512;
const int BDOS_RECORD_SECTORS = MGT_DISK_SECTORS;
typedef struct
{
int list_sectors = 0; // Sectors reserved for the record list
int base_sectors = 0; // Sectors used by boot sector plus record list
int records = 0; // Number of records, including possible partial last record
int extra_sectors = 0; // Extra sectors: >= 40 will form a small final record)
bool need_byteswap = false; // True if this is an ATOM disk that needs byte-swapping
bool bootable = false; // True if the boot sector suggests the disk is bootable
bool lba = false; // True if disk needs LBA sector count instead of CHS
} BDOS_CAPS;
const int PRODOS_SECTOR_SIZE = 512;
const int PRODOS_BASE_SECTORS = 68;
const int PRODOS_RECORD_SECTORS = 2048;
typedef struct
{
int base_sectors; // Sectors used by boot sector plus record list
int records; // Number of records, including possible partial last record
bool bootable; // True if the boot sector suggests the disk is bootable
} PRODOS_CAPS;
enum class SamDosType { SAMDOS, MasterDOS, BDOS };
typedef struct
{
SamDosType dos_type = SamDosType::SAMDOS; // SAMDOS, MasterDOS or BDOS
int dir_tracks = MGT_DIR_TRACKS; // Number of tracks in directory listing (min=4, max=39)
std::string disk_label {}; // Up to BDOS_LABEL_SIZE (16) characters
int serial_number = 0; // Serial number (MasterDOS only)
} MGT_DISK_INFO;
MGT_DISK_INFO *GetDiskInfo (const uint8_t *p, MGT_DISK_INFO &di);
bool SetDiskInfo (uint8_t *pb_, MGT_DISK_INFO &di);
bool GetFileTime (const MGT_DIR *p, struct tm* ptm_);
bool IsSDIDEDisk (const HDD &hdd);
bool IsProDOSDisk (const HDD &hdd, PRODOS_CAPS &pdc);
bool IsBDOSDisk (const HDD &hdd, BDOS_CAPS &bdc);
bool UpdateBDOSBootSector(uint8_t *pb_, const HDD &hdd);
void GetBDOSCaps (int64_t sectors, BDOS_CAPS &bdc);
int FindBDOSRecord (const HDD &hdd, const std::string &path, BDOS_CAPS &bdc);
#endif // SAM_H
| [
"simon@simonowen.com"
] | simon@simonowen.com |
abd60f7856f94077bc1e678c76735b70486cee88 | 42595340ebc8a03cabbcd389453ed62fba57bfc6 | /src/Entities/Scene.cpp | d77d0244290e65adb218a96137732714cb118b5a | [] | no_license | TO19/tetris-sfml2 | d0c8fa313a76a37c8f620ae5093dfad71dd6e238 | edb3624285354be46a01d24bca97713be3fa17e1 | refs/heads/main | 2023-03-28T04:20:01.731691 | 2021-04-02T00:08:30 | 2021-04-02T00:08:30 | 353,850,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,405 | cpp | #include "Scene.hh"
#include "env.hh"
Scene::Scene(sf::RenderWindow *window)
{
AssetsManager::loadFont("main", MAIN_FONT_PATH);
AssetsManager::loadTexture("tiles", TILES_PNG);
AssetsManager::loadTexture("windowBg", WINDOW_BG);
sf::Font *main = AssetsManager::getFont("main");
_fpsCounter.setFont(*main);
_fpsCounter.setCharacterSize(framerate_font_size);
_fpsCounter.setFillColor(sf::Color::Red);
_fpsCounter.setStyle(sf::Text::Bold);
_scoreText.setFont(*main);
_scoreText.setCharacterSize(score_font_size);
_scoreText.setPosition(100, 100);
_scoreText.setFillColor(sf::Color::Green);
this->_window = window;
};
Scene::~Scene(){};
std::list<AbstractEntity *> Scene::GetEntities() const
{
return this->_entityList;
}
void Scene::UpdateLevel()
{
if (this->_playableArea->GetScore() >= (this->_level * LEVEL_MULTIPLIER))
{
this->_level += 1;
}
}
sf::RenderWindow *Scene::GetWindow()
{
return this->_window;
}
void Scene::CleanEntities()
{
this->_entityList.clear();
}
void Scene::AddEntity(AbstractEntity *entity)
{
this->_entityList.push_front(entity);
}
void Scene::UpdateScoreText()
{
this->_scoreText.setString(std::to_string(this->_playableArea->GetScore()));
this->_window->draw(this->_scoreText);
}
void Scene::UpdateFPS()
{
int fps = 1000 / (int)TimeManager::GetInstance()->GetElapsedTime();
int maxFramerate = max_framerate - WINDOW_FPS_SFML_BUG; // SFML set max fps unreliable so we make a fake cap.
if (fps > maxFramerate)
{
fps = maxFramerate;
}
this->_fpsCounter.setString(std::to_string(fps));
this->_window->draw(this->_fpsCounter);
}
void Scene::UpdateBackground()
{
sf::Texture *backgroundTexture = AssetsManager::getTexture("windowBg");
sf::Vector2u textureSize = backgroundTexture->getSize();
sf::Vector2u windowSize = this->_window->getSize();
float scaleX = (float)windowSize.x / (float)textureSize.x;
float scaleY = (float)windowSize.y / (float)textureSize.y;
sf::Sprite background;
background.setTexture(*backgroundTexture);
background.setScale(scaleX, scaleY);
this->_window->draw(background);
}
void Scene::UpdatePlayableArea()
{
this->_window->draw(this->_playableArea->GetArea());
}
void Scene::RemoveEntity(AbstractEntity *entity)
{
this->_entityList.remove(entity);
}
AbstractEntity *Scene::GetEntity(int index)
{
std::list<AbstractEntity *>::iterator it = this->_entityList.begin();
std::advance(it, index);
return *it;
}
void Scene::
Update()
{
this->_window->clear();
TimeManager::GetInstance()->Update();
UpdateBackground();
UpdateFPS();
UpdateScoreText();
UpdatePlayableArea();
UpdateLeaderBoard();
UpdateLevel();
std::list<AbstractEntity *>::iterator it;
for (it = this->_entityList.begin(); it != this->_entityList.end(); ++it)
{
ShapeEntity *shape = dynamic_cast<ShapeEntity *>(*it);
if (shape != NULL && !CheckPlayableAreaCollision(shape, false))
{
(*it)->Update();
}
(*it)->Draw(this->_window);
}
if (!this->_gameRunning)
{
UpdateGameOverText();
}
this->_window->display();
}
PlayableArea *Scene::GetPlayableArea() const
{
return this->_playableArea;
}
void Scene::SetPlayableArea(PlayableArea *playableArea)
{
this->_playableArea = playableArea;
}
bool Scene::CheckBlockCollision(
ShapeEntity *movingEntity,
BlockEntity *movingBlock,
std::list<AbstractEntity *> entityList,
bool isXTranslation)
{
sf::RectangleShape movingRect = movingBlock->GetBlock();
auto currentBounds = movingRect.getGlobalBounds();
if (entityList.size() > 1)
{
for (auto shape : entityList)
{
auto shapeEntity = dynamic_cast<ShapeEntity *>(shape);
if (shapeEntity != movingEntity)
{
for (auto staticBlock : shapeEntity->GetBlockList())
{
sf::RectangleShape staticRect = staticBlock->GetBlock();
auto staticRectBounds = staticRect.getGlobalBounds();
if (currentBounds.intersects(staticRectBounds))
{
if (!isXTranslation)
{
double snapPos = GetPlayableArea()->GetClosestSnap(-movingRect.getPosition().y);
movingEntity->TranslateY(movingRect.getPosition().y + snapPos);
movingEntity->Freeze();
if (this->_gameRunning)
{
GenerateShape();
}
}
return true;
}
}
}
}
}
return false;
}
bool Scene::CheckPlayableAreaCollision(ShapeEntity *shape, bool isXTranslation)
{
if (shape->GetMoving())
{
sf::RectangleShape area = GetPlayableArea()->GetArea();
auto playableAreaBounds = area.getGlobalBounds();
for (auto movingBlock : shape->GetBlockList())
{
sf::RectangleShape movingRect = movingBlock->GetBlock();
auto movingRectBounds = movingRect.getGlobalBounds();
if (CheckBlockCollision(shape, movingBlock, this->_entityList, isXTranslation))
{
if (GetPlayableArea()->GetGridSize() <= shape->GetY() && this->_gameRunning)
{
auto sounds = new SoundManager();
sounds->playGameOver();
TxtFileManager::writeToFile("./Assets/score.txt", "LocalPlayer " + std::to_string(GetPlayableArea()->GetScore()));
this->_gameRunning = false;
}
return true;
}
/* If bounds in playable area we don't have a problem we do have one */
if (!playableAreaBounds.intersects(movingRectBounds) ||
movingRectBounds.top + movingRectBounds.height > playableAreaBounds.height + area.getPosition().y)
{
if (movingRectBounds.top > playableAreaBounds.height)
{
double snapPos = GetPlayableArea()->GetClosestSnap(-movingRect.getPosition().y);
shape->TranslateY(movingRect.getPosition().y + snapPos);
shape->Freeze();
if (this->_gameRunning)
{
GenerateShape();
}
}
return true;
}
}
}
return false;
}
void Scene::PlaceInGame(ShapeEntity *shape)
{
shape->SetMoving(true);
shape->SetPreview(false);
/* TODO Temporary thing, setPosition must be bugged, and shapes don't have the same origin */
shape->SetPosition(sf::Vector2f(GetPlayableArea()->GetBasePos().x, GetPlayableArea()->GetGridSize()));
}
void Scene::GenerateShape()
{
ShapeFactory *factory = new ShapeFactory();
int size = GetPlayableArea()->GetGridSize();
sf::Vector2f playablePos = GetPlayableArea()->GetArea().getPosition();
auto *shapeAsAbstractEntity = factory->Create(rand() % 7, size, playablePos, this->_level);
auto shape = dynamic_cast<ShapeEntity *>(shapeAsAbstractEntity);
if (NULL != shape)
{
if (GetEntities().size() == 0)
{
/* Generate Next Shape */
AddEntity(shape);
GenerateShape(); // Playable one
return;
}
AddEntity(shape);
/* Add Observers here */
shape->AddObserver(new RowObserver(GetPlayableArea(), this->_entityList));
PlaceInGame(dynamic_cast<ShapeEntity *>(GetEntity(1)));
}
}
void Scene::UpdateGameOverText()
{
sf::Text gameOverText;
gameOverText.setFont(*AssetsManager::getFont("main"));
gameOverText.setCharacterSize(40);
gameOverText.setFillColor(sf::Color::White);
gameOverText.setStyle(sf::Text::Bold);
gameOverText.setString("Game over - Press R to restart");
gameOverText.setPosition(
GetWindow()->getSize().x / 5,
GetWindow()->getSize().y / 2);
this->_window->draw(gameOverText);
}
void Scene::UpdateLeaderBoard()
{
const int LEFT_MARGIN = 25;
const int TOP_MARGIN = 419;
auto list = TxtFileManager::readScoreboardFile();
int counter = 1;
sf::Text leaderBoard;
leaderBoard.setFont(*AssetsManager::getFont("main"));
leaderBoard.setCharacterSize(40);
leaderBoard.setStyle(sf::Text::Underlined | sf::Text::Bold);
leaderBoard.setFillColor(sf::Color::White);
leaderBoard.setString("Leaderboard: ");
leaderBoard.setPosition(LEFT_MARGIN, TOP_MARGIN - 20);
for (auto score : list)
{
std::string name = score.first += " ";
std::string nameAndScore = name += std::to_string(score.second);
sf::Text text;
text.setFont(*AssetsManager::getFont("main"));
text.setCharacterSize(25);
text.setFillColor(sf::Color::White);
text.setString(nameAndScore);
text.setPosition(LEFT_MARGIN, (counter * 25) + TOP_MARGIN);
this->_window->draw(text);
counter++;
}
this->_window->draw(leaderBoard);
}
void Scene::SetGameRunning(bool isRunning)
{
this->_gameRunning = isRunning;
} | [
"tx19@github.com"
] | tx19@github.com |
46884d12e51e00197d24ae24a18a47332cd828c4 | f178d109847c102cdbae6bd38e651b15d4b103df | /f3d-core/c/include/file-image.h | 5778c647f2d8949c6ab78477e8dd3f23886cda58 | [] | no_license | Tubbz-alt/f3d | 6d6d5b34e4c605d1eb17935d8b9aa5fe46665a8c | 93285f582198bfbab33ca96ff71efda539b1bec7 | refs/heads/master | 2021-08-15T17:34:23.379470 | 2017-11-18T00:52:55 | 2017-11-18T00:52:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,873 | h | #ifndef __file_image_h
#define __file_image_h
#ifdef __GNUG__
#pragma interface
#endif
#include "image.h"
#include "paged-image.h"
#include "cme-error.h"
#include "namespace.h"
BEGIN_NAMESPACE_FREEDIUS
#define READ_OK 1
#define WRITE_OK 2
typedef char *string;
/* Also defined in image-io.h - bad news! */
#ifndef OFF_T
#if defined(_WIN32)
typedef __int64 OFF_T;
#else
typedef off_t OFF_T;
#endif
#endif
class file_image_page_handler: public image_page_handler
{public:
int stream;
char *pathname;
int first_tile_offset; // FIXME: should be of type off_t
//IMAGE_ELEMENT_TYPE element_type_code; // not used
// int endian; // 0=big_endian, 1=little_endian UNUSED ?
// virtual IMAGE_CLASS class_code() {return FILE_IMAGE_CLASS;}
file_image_page_handler(image_page_pool* page_pool, int npages);
page_queue_entry* probe_page_fault (int blknum);
void read_page(int blknum);
void write_page(int blknum);
virtual OFF_T page_filepos(int page_number);
void force_page_initialization();
void unmap_file(int closep = 1); // closep: 1=yes, 2=yes-abort, 0=no
virtual int save_image (paged_image_base *img, char *path);
virtual int map_image_to_file (paged_image_base *img, int iomode, string pathname,
int header_length);
};
paged_image_base *iu_testbed_load_file_image (string path);
// paged_image_base *iu_testbed_load_file_image (file_image_base *img, string path);
int init_iu_testbed_file_image_header();
int init_image_choose_image_class_fn();
paged_image_base *
make_file_image (int xdim, int ydim,
IMAGE_ELEMENT_TYPE element_type = IMG_UNSIGNED_8BIT,
int samples_per_pixel = 1,
int block_xdim = 0, int block_ydim = 0,int padded_block_xdim = 0,
char *pathname = (char *) 0);
extern int init_make_file_image_fn ();
int init_make_file_image_fn();
END_NAMESPACE_FREEDIUS
#endif /* ! __file_image_h */
| [
"e23393@MacBook-Pro-2.local"
] | e23393@MacBook-Pro-2.local |
5b9734b794e97f6766a75f80ac3936dfe8da9f0f | e3b28dd830ef7f0c9f7d20d2c1448923f38351be | /RobotControls/src/Commands/IntakeControls.h~ | 49ab187bd07ae6dee280f6f06dc6de82b60c873a | [] | no_license | Giodood/RobotControls2018 | 5c09021cfa2e3a6dc11ee57020a45e98899e505b | 535530900270d93b1e54dafb5b78e3c925b436ac | refs/heads/master | 2021-05-03T21:02:15.443744 | 2018-02-06T01:19:49 | 2018-02-06T01:19:49 | 120,374,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// C++ from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
#ifndef INTAKECONTROLS_H
#define INTAKECONTROLS_H
#include "Commands/Subsystem.h"
#include "../Robot.h"
/**
*
*
* @author ExampleAuthor
*/
class IntakeControls: public frc::Command {
public:
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
IntakeControls();
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
void Initialize() override;
void Execute() override;
bool IsFinished() override;
void End() override;
void Interrupted() override;
private:
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES
};
#endif
| [
"35720975+Giodood@users.noreply.github.com"
] | 35720975+Giodood@users.noreply.github.com | |
ce4c17ccce3b783b23b79cf02f42d6fa71ae3599 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/Source/bindings/core/v8/V8BindingForTesting.h | 3815348d85c251a8f29371542cc5d6e91b484849 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 1,515 | h | // Copyright (c) 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.
#ifndef V8BindingForTesting_h
#define V8BindingForTesting_h
#include "bindings/core/v8/ExceptionState.h"
#include "platform/bindings/ScriptState.h"
#include "platform/wtf/Allocator.h"
#include "platform/wtf/Forward.h"
#include "v8/include/v8.h"
namespace blink {
class Document;
class DOMWrapperWorld;
class DummyPageHolder;
class ExecutionContext;
class LocalFrame;
class Page;
class ScriptStateForTesting : public ScriptState {
public:
static RefPtr<ScriptStateForTesting> Create(v8::Local<v8::Context>,
RefPtr<DOMWrapperWorld>);
private:
ScriptStateForTesting(v8::Local<v8::Context>, RefPtr<DOMWrapperWorld>);
};
class V8TestingScope {
STACK_ALLOCATED();
public:
V8TestingScope();
ScriptState* GetScriptState() const;
ExecutionContext* GetExecutionContext() const;
v8::Isolate* GetIsolate() const;
v8::Local<v8::Context> GetContext() const;
ExceptionState& GetExceptionState();
Page& GetPage();
LocalFrame& GetFrame();
Document& GetDocument();
~V8TestingScope();
private:
std::unique_ptr<DummyPageHolder> holder_;
v8::HandleScope handle_scope_;
v8::Local<v8::Context> context_;
v8::Context::Scope context_scope_;
v8::TryCatch try_catch_;
DummyExceptionStateForTesting exception_state_;
};
} // namespace blink
#endif // V8BindingForTesting_h
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
1536d5d7692a75c4dbe6f5861d6920167f547734 | ca79f4e1655df123bde091a102825b2845764a1d | /include/steam/steamnetworkingcustomsignaling.h | 00ff8f3c4d5470a938eab5b0ddb7bc81a3a22e25 | [
"BSD-3-Clause"
] | permissive | ValveSoftware/GameNetworkingSockets | d288783e8ff9ab9830d7880264557434b0818062 | af2aff89038ccd8e960e4be77da4fe35c6882f14 | refs/heads/master | 2023-08-29T06:50:08.485869 | 2023-08-05T12:08:33 | 2023-08-05T12:08:33 | 126,225,160 | 7,656 | 651 | BSD-3-Clause | 2023-08-16T22:04:02 | 2018-03-21T18:43:20 | C++ | UTF-8 | C++ | false | false | 5,472 | h | //====== Copyright Valve Corporation, All rights reserved. ====================
//
// Interfaces needed to implement your own P2P signaling service. If you
// aren't using P2P connections, or you can use the default service provided
// by the platform (e.g. a typical Steam game), then you don't need anything
// in this file.
//
//=============================================================================
#ifndef STEAMNETWORKINGCUSTOMSIGNALING
#define STEAMNETWORKINGCUSTOMSIGNALING
#pragma once
#include "steamnetworkingtypes.h"
class ISteamNetworkingSockets;
/// Interface used to send signaling messages for a particular connection.
///
/// - For connections initiated locally, you will construct it and pass
/// it to ISteamNetworkingSockets::ConnectP2PCustomSignaling.
/// - For connections initiated remotely and "accepted" locally, you
/// will return it from ISteamNetworkingSignalingRecvContext::OnConnectRequest
class ISteamNetworkingConnectionSignaling
{
public:
/// Called to send a rendezvous message to the remote peer. This may be called
/// from any thread, at any time, so you need to be thread-safe! Don't take
/// any locks that might hold while calling into SteamNetworkingSockets functions,
/// because this could lead to deadlocks.
///
/// Note that when initiating a connection, we may not know the identity
/// of the peer, if you did not specify it in ConnectP2PCustomSignaling.
///
/// Return true if a best-effort attempt was made to deliver the message.
/// If you return false, it is assumed that the situation is fatal;
/// the connection will be closed, and Release() will be called
/// eventually.
///
/// Signaling objects will not be shared between connections.
/// You can assume that the same value of hConn will be used
/// every time.
virtual bool SendSignal( HSteamNetConnection hConn, const SteamNetConnectionInfo_t &info, const void *pMsg, int cbMsg ) = 0;
/// Called when the connection no longer needs to send signals.
/// Note that this happens eventually (but not immediately) after
/// the connection is closed. Signals may need to be sent for a brief
/// time after the connection is closed, to clean up the connection.
///
/// If you do not need to save any additional per-connection information
/// and can handle SendSignal() using only the arguments supplied, you do
/// not need to actually create different objects per connection. In that
/// case, it is valid for all connections to use the same global object, and
/// for this function to do nothing.
virtual void Release() = 0;
};
/// Interface used when a custom signal is received.
/// See ISteamNetworkingSockets::ReceivedP2PCustomSignal
class ISteamNetworkingSignalingRecvContext
{
public:
/// Called when the signal represents a request for a new connection.
///
/// If you want to ignore the request, just return NULL. In this case,
/// the peer will NOT receive any reply. You should consider ignoring
/// requests rather than actively rejecting them, as a security measure.
/// If you actively reject requests, then this makes it possible to detect
/// if a user is online or not, just by sending them a request.
///
/// If you wish to send back a rejection, then use
/// ISteamNetworkingSockets::CloseConnection() and then return NULL.
/// We will marshal a properly formatted rejection signal and
/// call SendRejectionSignal() so you can send it to them.
///
/// If you return a signaling object, the connection is NOT immediately
/// accepted by default. Instead, it stays in the "connecting" state,
/// and the usual callback is posted, and your app can accept the
/// connection using ISteamNetworkingSockets::AcceptConnection. This
/// may be useful so that these sorts of connections can be more similar
/// to your application code as other types of connections accepted on
/// a listen socket. If this is not useful and you want to skip this
/// callback process and immediately accept the connection, call
/// ISteamNetworkingSockets::AcceptConnection before returning the
/// signaling object.
///
/// After accepting a connection (through either means), the connection
/// will transition into the "finding route" state.
virtual ISteamNetworkingConnectionSignaling *OnConnectRequest( HSteamNetConnection hConn, const SteamNetworkingIdentity &identityPeer, int nLocalVirtualPort ) = 0;
/// This is called to actively communicate rejection or failure
/// to the incoming message. If you intend to ignore all incoming requests
/// that you do not wish to accept, then it's not strictly necessary to
/// implement this.
virtual void SendRejectionSignal( const SteamNetworkingIdentity &identityPeer, const void *pMsg, int cbMsg ) = 0;
};
/// The function signature of the callback used to obtain a signaling object
/// for connections initiated locally. These are used for
/// ISteamNetworkingSockets::ConnectP2P, and when using the
/// ISteamNetworkingMessages interface. To install the callback for all
/// interfaces, do something like this:
/// SteamNetworkingUtils()->SetGlobalConfigValuePtr( k_ESteamNetworkingConfig_Callback_CreateConnectionSignaling, (void*)fnCallback );
typedef ISteamNetworkingConnectionSignaling * (*FnSteamNetworkingSocketsCreateConnectionSignaling)( ISteamNetworkingSockets *pLocalInterface, const SteamNetworkingIdentity &identityPeer, int nLocalVirtualPort, int nRemoteVirtualPort );
#endif // STEAMNETWORKINGCUSTOMSIGNALING
| [
"fletcherd@valvesoftware.com"
] | fletcherd@valvesoftware.com |
34e378bf369cff2e78b7fcdbdc5a332a475170ad | 46c7c4c6a504005fa62f0ede53d265d064368e10 | /psol/include/third_party/chromium/src/base/string_util.h | f731c34a7e0354d6c2fdf28462cc9e71112ce3de | [
"Apache-2.0"
] | permissive | speed-optimization/ngx_pagespeed | 017df31f0274299298a528b8c5f79699722d5da7 | 4f6f1559209a27d6dd12a434d09bf8bf814a8a6e | refs/heads/master | 2021-01-23T20:17:55.979282 | 2013-02-13T16:26:20 | 2013-02-13T16:26:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,613 | h | // Copyright (c) 2011 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.
//
// This file defines utility functions for working with strings.
#ifndef BASE_STRING_UTIL_H_
#define BASE_STRING_UTIL_H_
#pragma once
#include <stdarg.h> // va_list
#include <string>
#include <vector>
#include "base/base_api.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/string16.h"
#include "base/string_piece.h" // For implicit conversions.
// TODO(brettw) remove this dependency. Previously StringPrintf lived in this
// file. We need to convert the callers over to using stringprintf.h instead
// and then remove this.
#include "base/stringprintf.h"
// Safe standard library wrappers for all platforms.
namespace base {
// C standard-library functions like "strncasecmp" and "snprintf" that aren't
// cross-platform are provided as "base::strncasecmp", and their prototypes
// are listed below. These functions are then implemented as inline calls
// to the platform-specific equivalents in the platform-specific headers.
// Compares the two strings s1 and s2 without regard to case using
// the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
// s2 > s1 according to a lexicographic comparison.
int strcasecmp(const char* s1, const char* s2);
// Compares up to count characters of s1 and s2 without regard to case using
// the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
// s2 > s1 according to a lexicographic comparison.
int strncasecmp(const char* s1, const char* s2, size_t count);
// Same as strncmp but for char16 strings.
int strncmp16(const char16* s1, const char16* s2, size_t count);
// Wrapper for vsnprintf that always null-terminates and always returns the
// number of characters that would be in an untruncated formatted
// string, even when truncation occurs.
int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments)
PRINTF_FORMAT(3, 0);
// vswprintf always null-terminates, but when truncation occurs, it will either
// return -1 or the number of characters that would be in an untruncated
// formatted string. The actual return value depends on the underlying
// C library's vswprintf implementation.
int vswprintf(wchar_t* buffer, size_t size,
const wchar_t* format, va_list arguments)
WPRINTF_FORMAT(3, 0);
// Some of these implementations need to be inlined.
// We separate the declaration from the implementation of this inline
// function just so the PRINTF_FORMAT works.
inline int snprintf(char* buffer, size_t size, const char* format, ...)
PRINTF_FORMAT(3, 4);
inline int snprintf(char* buffer, size_t size, const char* format, ...) {
va_list arguments;
va_start(arguments, format);
int result = vsnprintf(buffer, size, format, arguments);
va_end(arguments);
return result;
}
// We separate the declaration from the implementation of this inline
// function just so the WPRINTF_FORMAT works.
inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...)
WPRINTF_FORMAT(3, 4);
inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...) {
va_list arguments;
va_start(arguments, format);
int result = vswprintf(buffer, size, format, arguments);
va_end(arguments);
return result;
}
// BSD-style safe and consistent string copy functions.
// Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
// Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
// long as |dst_size| is not 0. Returns the length of |src| in characters.
// If the return value is >= dst_size, then the output was truncated.
// NOTE: All sizes are in number of characters, NOT in bytes.
BASE_API size_t strlcpy(char* dst, const char* src, size_t dst_size);
BASE_API size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size);
// Scan a wprintf format string to determine whether it's portable across a
// variety of systems. This function only checks that the conversion
// specifiers used by the format string are supported and have the same meaning
// on a variety of systems. It doesn't check for other errors that might occur
// within a format string.
//
// Nonportable conversion specifiers for wprintf are:
// - 's' and 'c' without an 'l' length modifier. %s and %c operate on char
// data on all systems except Windows, which treat them as wchar_t data.
// Use %ls and %lc for wchar_t data instead.
// - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
// which treat them as char data. Use %ls and %lc for wchar_t data
// instead.
// - 'F', which is not identified by Windows wprintf documentation.
// - 'D', 'O', and 'U', which are deprecated and not available on all systems.
// Use %ld, %lo, and %lu instead.
//
// Note that there is no portable conversion specifier for char data when
// working with wprintf.
//
// This function is intended to be called from base::vswprintf.
BASE_API bool IsWprintfFormatPortable(const wchar_t* format);
// ASCII-specific tolower. The standard library's tolower is locale sensitive,
// so we don't want to use it here.
template <class Char> inline Char ToLowerASCII(Char c) {
return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
}
// ASCII-specific toupper. The standard library's toupper is locale sensitive,
// so we don't want to use it here.
template <class Char> inline Char ToUpperASCII(Char c) {
return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
}
// Function objects to aid in comparing/searching strings.
template<typename Char> struct CaseInsensitiveCompare {
public:
bool operator()(Char x, Char y) const {
// TODO(darin): Do we really want to do locale sensitive comparisons here?
// See http://crbug.com/24917
return tolower(x) == tolower(y);
}
};
template<typename Char> struct CaseInsensitiveCompareASCII {
public:
bool operator()(Char x, Char y) const {
return ToLowerASCII(x) == ToLowerASCII(y);
}
};
} // namespace base
#if defined(OS_WIN)
#include "base/string_util_win.h"
#elif defined(OS_POSIX)
#include "base/string_util_posix.h"
#else
#error Define string operations appropriately for your platform
#endif
// These threadsafe functions return references to globally unique empty
// strings.
//
// DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT CONSTRUCTORS.
// There is only one case where you should use these: functions which need to
// return a string by reference (e.g. as a class member accessor), and don't
// have an empty string to use (e.g. in an error case). These should not be
// used as initializers, function arguments, or return values for functions
// which return by value or outparam.
BASE_API const std::string& EmptyString();
BASE_API const std::wstring& EmptyWString();
BASE_API const string16& EmptyString16();
BASE_API extern const wchar_t kWhitespaceWide[];
BASE_API extern const char16 kWhitespaceUTF16[];
BASE_API extern const char kWhitespaceASCII[];
BASE_API extern const char kUtf8ByteOrderMark[];
// Removes characters in remove_chars from anywhere in input. Returns true if
// any characters were removed.
// NOTE: Safe to use the same variable for both input and output.
BASE_API bool RemoveChars(const string16& input,
const char16 remove_chars[],
string16* output);
BASE_API bool RemoveChars(const std::string& input,
const char remove_chars[],
std::string* output);
// Removes characters in trim_chars from the beginning and end of input.
// NOTE: Safe to use the same variable for both input and output.
BASE_API bool TrimString(const std::wstring& input,
const wchar_t trim_chars[],
std::wstring* output);
BASE_API bool TrimString(const string16& input,
const char16 trim_chars[],
string16* output);
BASE_API bool TrimString(const std::string& input,
const char trim_chars[],
std::string* output);
// Truncates a string to the nearest UTF-8 character that will leave
// the string less than or equal to the specified byte size.
BASE_API void TruncateUTF8ToByteSize(const std::string& input,
const size_t byte_size,
std::string* output);
// Trims any whitespace from either end of the input string. Returns where
// whitespace was found.
// The non-wide version has two functions:
// * TrimWhitespaceASCII()
// This function is for ASCII strings and only looks for ASCII whitespace;
// Please choose the best one according to your usage.
// NOTE: Safe to use the same variable for both input and output.
enum TrimPositions {
TRIM_NONE = 0,
TRIM_LEADING = 1 << 0,
TRIM_TRAILING = 1 << 1,
TRIM_ALL = TRIM_LEADING | TRIM_TRAILING,
};
BASE_API TrimPositions TrimWhitespace(const string16& input,
TrimPositions positions,
string16* output);
BASE_API TrimPositions TrimWhitespaceASCII(const std::string& input,
TrimPositions positions,
std::string* output);
// Deprecated. This function is only for backward compatibility and calls
// TrimWhitespaceASCII().
BASE_API TrimPositions TrimWhitespace(const std::string& input,
TrimPositions positions,
std::string* output);
// Searches for CR or LF characters. Removes all contiguous whitespace
// strings that contain them. This is useful when trying to deal with text
// copied from terminals.
// Returns |text|, with the following three transformations:
// (1) Leading and trailing whitespace is trimmed.
// (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
// sequences containing a CR or LF are trimmed.
// (3) All other whitespace sequences are converted to single spaces.
BASE_API std::wstring CollapseWhitespace(const std::wstring& text,
bool trim_sequences_with_line_breaks);
BASE_API string16 CollapseWhitespace(const string16& text,
bool trim_sequences_with_line_breaks);
BASE_API std::string CollapseWhitespaceASCII(
const std::string& text, bool trim_sequences_with_line_breaks);
// Returns true if the passed string is empty or contains only white-space
// characters.
BASE_API bool ContainsOnlyWhitespaceASCII(const std::string& str);
BASE_API bool ContainsOnlyWhitespace(const string16& str);
// Returns true if |input| is empty or contains only characters found in
// |characters|.
BASE_API bool ContainsOnlyChars(const std::wstring& input,
const std::wstring& characters);
BASE_API bool ContainsOnlyChars(const string16& input,
const string16& characters);
BASE_API bool ContainsOnlyChars(const std::string& input,
const std::string& characters);
// Converts to 7-bit ASCII by truncating. The result must be known to be ASCII
// beforehand.
BASE_API std::string WideToASCII(const std::wstring& wide);
BASE_API std::string UTF16ToASCII(const string16& utf16);
// Converts the given wide string to the corresponding Latin1. This will fail
// (return false) if any characters are more than 255.
BASE_API bool WideToLatin1(const std::wstring& wide, std::string* latin1);
// Returns true if the specified string matches the criteria. How can a wide
// string be 8-bit or UTF8? It contains only characters that are < 256 (in the
// first case) or characters that use only 8-bits and whose 8-bit
// representation looks like a UTF-8 string (the second case).
//
// Note that IsStringUTF8 checks not only if the input is structurally
// valid but also if it doesn't contain any non-character codepoint
// (e.g. U+FFFE). It's done on purpose because all the existing callers want
// to have the maximum 'discriminating' power from other encodings. If
// there's a use case for just checking the structural validity, we have to
// add a new function for that.
BASE_API bool IsStringUTF8(const std::string& str);
BASE_API bool IsStringASCII(const std::wstring& str);
BASE_API bool IsStringASCII(const base::StringPiece& str);
BASE_API bool IsStringASCII(const string16& str);
// Converts the elements of the given string. This version uses a pointer to
// clearly differentiate it from the non-pointer variant.
template <class str> inline void StringToLowerASCII(str* s) {
for (typename str::iterator i = s->begin(); i != s->end(); ++i)
*i = base::ToLowerASCII(*i);
}
template <class str> inline str StringToLowerASCII(const str& s) {
// for std::string and std::wstring
str output(s);
StringToLowerASCII(&output);
return output;
}
// Converts the elements of the given string. This version uses a pointer to
// clearly differentiate it from the non-pointer variant.
template <class str> inline void StringToUpperASCII(str* s) {
for (typename str::iterator i = s->begin(); i != s->end(); ++i)
*i = base::ToUpperASCII(*i);
}
template <class str> inline str StringToUpperASCII(const str& s) {
// for std::string and std::wstring
str output(s);
StringToUpperASCII(&output);
return output;
}
// Compare the lower-case form of the given string against the given ASCII
// string. This is useful for doing checking if an input string matches some
// token, and it is optimized to avoid intermediate string copies. This API is
// borrowed from the equivalent APIs in Mozilla.
BASE_API bool LowerCaseEqualsASCII(const std::string& a, const char* b);
BASE_API bool LowerCaseEqualsASCII(const std::wstring& a, const char* b);
BASE_API bool LowerCaseEqualsASCII(const string16& a, const char* b);
// Same thing, but with string iterators instead.
BASE_API bool LowerCaseEqualsASCII(std::string::const_iterator a_begin,
std::string::const_iterator a_end,
const char* b);
BASE_API bool LowerCaseEqualsASCII(std::wstring::const_iterator a_begin,
std::wstring::const_iterator a_end,
const char* b);
BASE_API bool LowerCaseEqualsASCII(string16::const_iterator a_begin,
string16::const_iterator a_end,
const char* b);
BASE_API bool LowerCaseEqualsASCII(const char* a_begin,
const char* a_end,
const char* b);
BASE_API bool LowerCaseEqualsASCII(const wchar_t* a_begin,
const wchar_t* a_end,
const char* b);
BASE_API bool LowerCaseEqualsASCII(const char16* a_begin,
const char16* a_end,
const char* b);
// Performs a case-sensitive string compare. The behavior is undefined if both
// strings are not ASCII.
BASE_API bool EqualsASCII(const string16& a, const base::StringPiece& b);
// Returns true if str starts with search, or false otherwise.
BASE_API bool StartsWithASCII(const std::string& str,
const std::string& search,
bool case_sensitive);
BASE_API bool StartsWith(const std::wstring& str,
const std::wstring& search,
bool case_sensitive);
BASE_API bool StartsWith(const string16& str,
const string16& search,
bool case_sensitive);
// Returns true if str ends with search, or false otherwise.
BASE_API bool EndsWith(const std::string& str,
const std::string& search,
bool case_sensitive);
BASE_API bool EndsWith(const std::wstring& str,
const std::wstring& search,
bool case_sensitive);
BASE_API bool EndsWith(const string16& str,
const string16& search,
bool case_sensitive);
// Determines the type of ASCII character, independent of locale (the C
// library versions will change based on locale).
template <typename Char>
inline bool IsAsciiWhitespace(Char c) {
return c == ' ' || c == '\r' || c == '\n' || c == '\t';
}
template <typename Char>
inline bool IsAsciiAlpha(Char c) {
return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
}
template <typename Char>
inline bool IsAsciiDigit(Char c) {
return c >= '0' && c <= '9';
}
template <typename Char>
inline bool IsHexDigit(Char c) {
return (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f');
}
template <typename Char>
inline Char HexDigitToInt(Char c) {
DCHECK(IsHexDigit(c));
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
return 0;
}
// Returns true if it's a whitespace character.
inline bool IsWhitespace(wchar_t c) {
return wcschr(kWhitespaceWide, c) != NULL;
}
// Return a byte string in human-readable format with a unit suffix. Not
// appropriate for use in any UI; use of FormatBytes and friends in ui/base is
// highly recommended instead. TODO(avi): Figure out how to get callers to use
// FormatBytes instead; remove this.
BASE_API string16 FormatBytesUnlocalized(int64 bytes);
// Starting at |start_offset| (usually 0), replace the first instance of
// |find_this| with |replace_with|.
BASE_API void ReplaceFirstSubstringAfterOffset(string16* str,
string16::size_type start_offset,
const string16& find_this,
const string16& replace_with);
BASE_API void ReplaceFirstSubstringAfterOffset(
std::string* str,
std::string::size_type start_offset,
const std::string& find_this,
const std::string& replace_with);
// Starting at |start_offset| (usually 0), look through |str| and replace all
// instances of |find_this| with |replace_with|.
//
// This does entire substrings; use std::replace in <algorithm> for single
// characters, for example:
// std::replace(str.begin(), str.end(), 'a', 'b');
BASE_API void ReplaceSubstringsAfterOffset(string16* str,
string16::size_type start_offset,
const string16& find_this,
const string16& replace_with);
BASE_API void ReplaceSubstringsAfterOffset(std::string* str,
std::string::size_type start_offset,
const std::string& find_this,
const std::string& replace_with);
// This is mpcomplete's pattern for saving a string copy when dealing with
// a function that writes results into a wchar_t[] and wanting the result to
// end up in a std::wstring. It ensures that the std::wstring's internal
// buffer has enough room to store the characters to be written into it, and
// sets its .length() attribute to the right value.
//
// The reserve() call allocates the memory required to hold the string
// plus a terminating null. This is done because resize() isn't
// guaranteed to reserve space for the null. The resize() call is
// simply the only way to change the string's 'length' member.
//
// XXX-performance: the call to wide.resize() takes linear time, since it fills
// the string's buffer with nulls. I call it to change the length of the
// string (needed because writing directly to the buffer doesn't do this).
// Perhaps there's a constant-time way to change the string's length.
template <class string_type>
inline typename string_type::value_type* WriteInto(string_type* str,
size_t length_with_null) {
str->reserve(length_with_null);
str->resize(length_with_null - 1);
return &((*str)[0]);
}
//-----------------------------------------------------------------------------
// Splits a string into its fields delimited by any of the characters in
// |delimiters|. Each field is added to the |tokens| vector. Returns the
// number of tokens found.
BASE_API size_t Tokenize(const std::wstring& str,
const std::wstring& delimiters,
std::vector<std::wstring>* tokens);
BASE_API size_t Tokenize(const string16& str,
const string16& delimiters,
std::vector<string16>* tokens);
BASE_API size_t Tokenize(const std::string& str,
const std::string& delimiters,
std::vector<std::string>* tokens);
BASE_API size_t Tokenize(const base::StringPiece& str,
const base::StringPiece& delimiters,
std::vector<base::StringPiece>* tokens);
// Does the opposite of SplitString().
BASE_API string16 JoinString(const std::vector<string16>& parts, char16 s);
BASE_API std::string JoinString(const std::vector<std::string>& parts, char s);
// Replace $1-$2-$3..$9 in the format string with |a|-|b|-|c|..|i| respectively.
// Additionally, any number of consecutive '$' characters is replaced by that
// number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
// NULL. This only allows you to use up to nine replacements.
BASE_API string16 ReplaceStringPlaceholders(const string16& format_string,
const std::vector<string16>& subst,
std::vector<size_t>* offsets);
BASE_API std::string ReplaceStringPlaceholders(
const base::StringPiece& format_string,
const std::vector<std::string>& subst,
std::vector<size_t>* offsets);
// Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
BASE_API string16 ReplaceStringPlaceholders(const string16& format_string,
const string16& a,
size_t* offset);
// Returns true if the string passed in matches the pattern. The pattern
// string can contain wildcards like * and ?
// The backslash character (\) is an escape character for * and ?
// We limit the patterns to having a max of 16 * or ? characters.
// ? matches 0 or 1 character, while * matches 0 or more characters.
BASE_API bool MatchPattern(const base::StringPiece& string,
const base::StringPiece& pattern);
BASE_API bool MatchPattern(const string16& string, const string16& pattern);
// Hack to convert any char-like type to its unsigned counterpart.
// For example, it will convert char, signed char and unsigned char to unsigned
// char.
template<typename T>
struct ToUnsigned {
typedef T Unsigned;
};
template<>
struct ToUnsigned<char> {
typedef unsigned char Unsigned;
};
template<>
struct ToUnsigned<signed char> {
typedef unsigned char Unsigned;
};
template<>
struct ToUnsigned<wchar_t> {
#if defined(WCHAR_T_IS_UTF16)
typedef unsigned short Unsigned;
#elif defined(WCHAR_T_IS_UTF32)
typedef uint32 Unsigned;
#endif
};
template<>
struct ToUnsigned<short> {
typedef unsigned short Unsigned;
};
#endif // BASE_STRING_UTIL_H_
| [
"jefftk@google.com"
] | jefftk@google.com |
c601e288c1d3bec5483b3c45f770265ef1fc41ae | 4faa3bbd0d15f9041cbf7a53b22e4adba904b3a2 | /C++/changeOfBase.cpp | 494e2d8259a52f937c0296830bead9caee5d1b97 | [] | no_license | ialmazan/Programming-Languages | fa0285cb74a1ac17240199c0643f0d119dd23003 | 79496ccf85a548536a5073999c5264d88b672852 | refs/heads/master | 2021-01-13T12:51:38.898843 | 2017-01-08T12:00:06 | 2017-01-08T12:00:06 | 78,339,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,483 | cpp | #include<iostream>
#include<sstream>
#include<string>
#include<math.h>
//ivan almazan
//912383996
using namespace std;
int toBaseTen(string number, int base)
{
int power = number.length() - 1;
int baseTen = 0;
for (unsigned int i = 0; i < number.length(); i++)
{
if (number[i] >= 48 && number[i] <= 57)
{
int digit = number[i] - '0';
baseTen += digit * pow(base, power);
}
else if (number[i] >= 65 && number[i] <= 90)
{
int digit = number[i] - '7';
baseTen += digit * pow(base, power);
}
else
cout << "Invalid Input " << endl;
power--;
}
return baseTen;
}
string toNewBase(int baseTen, int newBase)
{
string newNumber;
ostringstream ss;
int remainder = 0;
while (baseTen != 0)
{
remainder = baseTen % newBase;
if (remainder >= 10)
{
ss.str(string());
ss << (char)('A'+ remainder -10);
newNumber += ss.str();
}
else
{
ss.str(string());
ss << remainder;
newNumber += ss.str();
}
baseTen = baseTen / newBase;
}
return newNumber = string(newNumber.rbegin(),newNumber.rend());
}
int main()
{
string number, newNumber = " ";
int base, newBase, baseTen = 0;
cout << "Please enter the number's base: ";
cin >> base;
cout << "Please enter the number: ";
cin >> number;
cout << "Please enter the new base: ";
cin >> newBase;
baseTen = toBaseTen(number, base);
newNumber = toNewBase(baseTen, newBase);
cout << number << " base " << base << " is " << newNumber << " base " << newBase << endl;
return 0;
}
| [
"ialmazan@ucdavis.edu"
] | ialmazan@ucdavis.edu |
bbfc955e81327f19eb082845b0af0d0a729dfe26 | 125375ed5d676ad2aa5babe58b4df34bee568cb6 | /Inheritence MultiLevel Student/Inheritence MultiLevel Student/test.h | 93ba8a61a874a280553dd027b4e252b5c740c883 | [] | no_license | anjaliomer/C-Plus-Plus-Programs | 3c912a69c0589e2849a8c3df7029ae752a0c1586 | 24eccd968a54db15aeb9edb26ad326ccb4dff3c7 | refs/heads/master | 2020-03-15T07:57:16.498422 | 2018-05-15T16:09:33 | 2018-05-15T16:09:33 | 132,023,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | h | #pragma once
#include "student.h"
class test : public student
{
protected:
float sub_1;
float sub_2;
public:
void get_marks(float, float);
void put_marks(void);
};
| [
"anjaliom@buffalo.edu"
] | anjaliom@buffalo.edu |
ad34f816443241ec7f2af03ab3e60a2c5269975c | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/third_party/WebKit/Source/modules/imagebitmap/ImageBitmapRenderingContext.h | e6b2cccbdc2fd214400cce05bb9b2f066820334b | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 2,008 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ImageBitmapRenderingContext_h
#define ImageBitmapRenderingContext_h
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/canvas/CanvasRenderingContextFactory.h"
#include "modules/ModulesExport.h"
#include "wtf/RefPtr.h"
namespace blink {
class ImageBitmap;
class MODULES_EXPORT ImageBitmapRenderingContext final : public CanvasRenderingContext {
DEFINE_WRAPPERTYPEINFO();
public:
class Factory : public CanvasRenderingContextFactory {
WTF_MAKE_NONCOPYABLE(Factory);
public:
Factory() {}
~Factory() override {}
CanvasRenderingContext* create(HTMLCanvasElement*, const CanvasContextCreationAttributes&, Document&) override;
CanvasRenderingContext::ContextType getContextType() const override { return CanvasRenderingContext::ContextImageBitmap; }
};
// Script API
void transferFromImageBitmap(ImageBitmap*);
// CanvasRenderingContext implementation
ContextType getContextType() const override { return CanvasRenderingContext::ContextImageBitmap; }
bool hasAlpha() const override { return m_hasAlpha; }
void setIsHidden(bool) override { }
bool isContextLost() const override { return false; }
bool paint(GraphicsContext&, const IntRect&) override;
void setCanvasGetContextResult(RenderingContext&) final;
// TODO(junov): Implement GPU accelerated rendering using a layer bridge
WebLayer* platformLayer() const override { return nullptr; }
// TODO(junov): handle lost contexts when content is GPU-backed
void loseContext(LostContextMode) override { }
void stop() override;
virtual ~ImageBitmapRenderingContext();
private:
ImageBitmapRenderingContext(HTMLCanvasElement*, CanvasContextCreationAttributes, Document&);
bool m_hasAlpha;
RefPtr<Image> m_image;
};
} // blink
#endif
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
59b9f5703a35aa417f1e5b32ba3557b90477a98b | 0b22781c3265a4f426e6d529b150d1b91aea4bda | /BoxWorld/GameManager.h | 962f8e2fd941d03001d72799411792bf41f2db8f | [] | no_license | elenastroie/BoxWorld | 83f78a53f44132063fe58c1057b1ecef046f4ec7 | 54394e7668ac2bf7d6cf464c3b8c25c6ba7094a2 | refs/heads/master | 2022-11-08T19:42:35.925674 | 2020-06-29T17:58:33 | 2020-06-29T17:58:33 | 275,872,966 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,313 | h | #pragma once
#include <SFML/Window/Event.hpp>
#include "Level.h"
#include "LevelLoader.h"
#include "MoveDirection.h"
#include "SoundManager.h"
class GameManager
{
public:
virtual ~GameManager() = default;
GameManager() = delete;
GameManager(LevelLoader&, SoundManager&);
[[nodiscard]] const std::shared_ptr<Level>& GetCurrentLevel() const;
void MovePlayerTowardsDirection(MoveDirection moveDirection) const;
void ProcessEvent(const sf::Event&) const;
[[nodiscard]] bool IsLevelCompleted() const;
[[nodiscard]] uint8_t GetLevelNumber() const;
void LoadNextLevel();
void LoadLevel(uint8_t levelIndex);
virtual void RestartLevel() = 0;
static GameManager& GetInstance();
[[nodiscard]] LevelLoader& GetLevelLoader() const;
[[nodiscard]] SoundManager& GetSoundManager() const;
protected:
using TGrid = Grid<std::shared_ptr<GameObject>>;
using TObject = std::shared_ptr<GameObject>;
bool CanMove(const TObject&, TGrid&, MoveDirection) const;
public:
void CheckBoxesOnTarget() const;
void CheckBoxOnTarget(const std::shared_ptr<GameObject>&) const;
protected:
LevelLoader& m_levelLoader;
SoundManager& m_soundManager;
std::shared_ptr<Level> m_currentLevel{};
uint8_t m_levelNumber{};
static GameManager* s_instance;
};
| [
"58604489+elenastroie@users.noreply.github.com"
] | 58604489+elenastroie@users.noreply.github.com |
68085c62e2dc34c8d999eedf3f17f57bd84dc32e | 73b487a31d6a2c05860d836bff09b6c343b046ca | /Warmup/A Very Big Sum/main.cpp | ff4a786dad1dae1a15f9122b3aaac41fc2393ec4 | [] | no_license | karolmikolajczuk/HackerRank-Algorithms-ProblemSolving | 5da9a7829dcad17bf43e82caeef4293f89d77a63 | b128307953c2a7c082b307661b3ff3bfbfe30763 | refs/heads/master | 2021-04-24T04:55:39.443041 | 2020-03-25T23:09:35 | 2020-03-25T23:09:35 | 250,080,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
long long int a=0;
cin >> n;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
}
for (int i=0; i<n; i++){
a+=arr[i];
}
cout<<a;
return 0;
}
| [
"karol.mikolajczuk@outlook.com"
] | karol.mikolajczuk@outlook.com |
df05214a5b46192916cd0b671f504b72b2360d5f | d645db5569db9a94e2353399b222d46620f6ea8f | /P5/main.cpp | 710d17e08e6bcacafa9c046652f13ff9f178dcb7 | [] | no_license | DrEvilBrain/CS3113 | 6c6741e7c6d765e4a3eb9ae9231c3da32e617903 | dc2675446badd2b2a89012dbdbc445213f0ece34 | refs/heads/main | 2023-05-11T12:34:31.405832 | 2021-05-12T21:58:27 | 2021-05-12T21:58:27 | 337,232,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,803 | cpp | #include <vector>
#define GL_SILENCE_DEPRECATION
#ifdef _WINDOWS
#include <GL/glew.h>
#endif
#define GL_GLEXT_PROTOTYPES 1
#include <SDL.h>
#include <SDL_mixer.h>
#include <SDL_opengl.h>
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "ShaderProgram.h"
#include "Effects.h"
#include "Util.h"
#include "Entity.h"
#include "Map.h"
#include "Scene.h"
#include "MainMenu.h"
#include "Level1.h"
#include "Level2.h"
#include "Level3.h"
Scene* currentScene;
Scene* sceneList[4];
Effects* effects;
SDL_Window* displayWindow;
bool gameIsRunning = true;
ShaderProgram program;
glm::mat4 viewMatrix, modelMatrix, projectionMatrix;
// handles switching bewteen scenes
void SwitchToScene(Scene* scene)
{
currentScene = scene;
currentScene->Initialize();
}
void Initialize()
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
displayWindow = SDL_CreateWindow("Project 5: Operation Intrude", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
SDL_GL_MakeCurrent(displayWindow, context);
#ifdef _WINDOWS
glewInit();
#endif
glViewport(0, 0, 640, 480);
program.Load("shaders/vertex_textured.glsl", "shaders/fragment_textured.glsl");
viewMatrix = glm::mat4(1.0f);
modelMatrix = glm::mat4(1.0f);
float windowWidth = 5.0f;
float windowHeight = 3.75f;
float windowDepth = 1.0f;
projectionMatrix = glm::ortho(-windowWidth, windowWidth, -windowHeight, windowHeight, -windowDepth, windowDepth);
program.SetProjectionMatrix(projectionMatrix);
program.SetViewMatrix(viewMatrix);
glUseProgram(program.programID);
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// ***Initialize Scenes***
sceneList[0] = new MainMenu();
sceneList[1] = new Level1();
sceneList[2] = new Level2();
sceneList[3] = new Level3();
SwitchToScene(sceneList[0]);
// ***Initialize Audio***
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);
currentScene->state.music = Mix_LoadMUS("Assets/Audio/crypto.mp3");
Mix_PlayMusic(currentScene->state.music, -1);
Mix_VolumeMusic(MIX_MAX_VOLUME / 2);
// ***Initialize Effects***
effects = new Effects(projectionMatrix, viewMatrix);
effects->Start(NONE, 1);
}
// Controls:
// Left Arrow = Move Left
// Right Arrow = Move Right
// Spacebar = Jump
// Enter = Start/End Game
void ProcessInput()
{
currentScene->state.player->movement = glm::vec3(0);
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
case SDL_WINDOWEVENT_CLOSE:
gameIsRunning = false;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_SPACE:
// Handle jumping
if (currentScene->state.player->collidedBottom)
{
currentScene->state.player->jump = true;
}
break;
case SDLK_RETURN:
// begin game when on the main menu
if (currentScene == sceneList[0])
{
SwitchToScene(sceneList[1]);
currentScene->state.lives = sceneList[0]->state.lives;
}
// go back to main menu when game is over
else if (currentScene->state.isGameOver)
{
currentScene->state.isGameOver = false;
SwitchToScene(sceneList[0]);
}
break;
}
break; // SDL_KEYDOWN
}
}
const Uint8 *keys = SDL_GetKeyboardState(NULL);
// move left
if (keys[SDL_SCANCODE_LEFT] && !currentScene->state.isGameOver)
{
currentScene->state.player->movement.x += -1.0f;
currentScene->state.player->animIndices = currentScene->state.player->animLeft;
}
// move right
else if (keys[SDL_SCANCODE_RIGHT] && !currentScene->state.isGameOver)
{
currentScene->state.player->movement.x += 1.0f;
currentScene->state.player->animIndices = currentScene->state.player->animRight;
}
if (glm::length(currentScene->state.player->movement) > 1.0f)
{
currentScene->state.player->movement = glm::normalize(currentScene->state.player->movement);
}
}
#define FIXED_TIMESTEP 0.0166666f
float lastTicks = 0;
float accumulator = 0.0f;
void Update()
{
float ticks = (float)SDL_GetTicks() / 1000.0f;
float deltaTime = ticks - lastTicks;
lastTicks = ticks;
if (!currentScene->state.isGameOver)
{
deltaTime += accumulator;
if (deltaTime < FIXED_TIMESTEP)
{
accumulator = deltaTime;
return;
}
// Update. Notice it's FIXED_TIMESTEP. Not deltaTime
while (deltaTime >= FIXED_TIMESTEP)
{
currentScene->Update(FIXED_TIMESTEP);
effects->Update(FIXED_TIMESTEP);
deltaTime -= FIXED_TIMESTEP;
}
accumulator = deltaTime;
}
// camera scrolling
viewMatrix = glm::mat4(1.0f);
if (currentScene->state.player->position.x > 5)
{
viewMatrix = glm::translate(viewMatrix, glm::vec3(-(currentScene->state.player->position.x), 3.75, 0));
}
else
{
viewMatrix = glm::translate(viewMatrix, glm::vec3(-5, 3.75, 0));
}
// handle changing effects
if (currentScene->state.playingEffect != NONE)
{
effects->Start(currentScene->state.playingEffect, 1);
}
}
void Render()
{
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program.programID);
// update the viewmatrix for camera scrolling
program.SetViewMatrix(viewMatrix);
// render the scene
currentScene->Render(&program);
// render effects
effects->Render();
SDL_GL_SwapWindow(displayWindow);
}
void Shutdown()
{
SDL_Quit();
}
int main(int argc, char* argv[])
{
Initialize();
while (gameIsRunning)
{
ProcessInput();
Update();
if (currentScene->state.nextScene >= 0)
{
// make life count persist between scene transitions
sceneList[currentScene->state.nextScene]->state.lives = currentScene->state.lives;
// go to next scene
SwitchToScene(sceneList[currentScene->state.nextScene]);
}
Render();
}
Shutdown();
return 0;
}
| [
"drevilbrain@gmail.com"
] | drevilbrain@gmail.com |
cda25f4786f47f96296c17896d44db838999c978 | 63c71060f36866bca4ac27304cef6d5755fdc35c | /src/UtilComm1/UdpCommNew.h | 8d7d2b2579e4c2c978d43f30ed351feeca319346 | [] | no_license | 15831944/barry_dev | bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a | d4a83421458aa28ca293caa7a5567433e9358596 | refs/heads/master | 2022-03-24T07:00:26.810732 | 2015-12-22T07:19:58 | 2015-12-22T07:19:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | h | ////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005
// Packet Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification is not permitted unless authorized in writing by a duly
// appointed officer of Packet Engineering, Inc. or its derivatives
//
// Description:
//
// Modification History:
// 03/10/2012 Copied from UdpComm.h by Chen Ding
////////////////////////////////////////////////////////////////////////////
#ifndef Omn_UtilComm1_UdpCommNew_h
#define Omn_UtilComm1_UdpCommNew_h
#include "Debug/ErrId.h"
#include "Message/MsgId.h"
#include "Network/Ptrs.h"
#include "Thread/ThreadedObj.h"
#include "Thread/Ptrs.h"
#include "Util/String.h"
#include "Util/IpAddr.h"
#include "Util/Ptrs.h"
#include "Util/RCObjImp.h"
#include "UtilComm/Ptrs.h"
#include "UtilComm/CommProt.h"
#include "UtilComm/Comm.h"
#include "XmlParser/Ptrs.h"
class AosUdpCommNew : public OmnThreadedObj
{
OmnDefineRCObject;
private:
enum
{
eReadFailIntervalTimerSec = 3
};
OmnThreadPtr mReadingThread;
OmnString mName;
OmnIpAddr mLocalAddr;
int mLocalPort;
OmnUdpPtr mUdpConn;
OmnCommListenerPtr mRequester;
// Do not use the following
AosUdpCommNew(const AosUdpCommNew &rhs);
AosUdpCommNew & operator = (const AosUdpCommNew &rhs);
public:
AosUdpCommNew(const OmnString &localAddr,
const int port,
const OmnString &name);
virtual ~AosUdpCommNew();
// Writes
bool readFrom(OmnConnBuffPtr &buff,
const int timerSec,
const int timeruSec,
bool &isTimeout);
bool sendTo(const char *data, const int length,
const OmnIpAddr &remoteIpAddr,
const int remotePort);
inline bool sendTo(const OmnString &data,
const OmnString &remote_addr,
const int remote_port)
{
return sendTo(data.data(), data.length(), remote_addr, remote_port);
}
int getSock() const;
OmnString toString() const;
bool startReading(const OmnCommListenerPtr &requester);
bool stopReading(const OmnCommListenerPtr &requester);
bool forceStop();
// Implement OmnThreadedObj interface
virtual bool threadFunc(OmnThrdStatus::E &state,
const OmnThreadPtr &thread);
virtual bool signal(const int threadLogicId);
virtual bool checkThread(OmnString &errmsg, const int tid) const;
OmnIpAddr getLocalIpAddr() const {return mLocalAddr;}
int getLocalPort() const {return mLocalPort;}
void setLocalPort(const int port) {mLocalPort = port;}
bool isConnGood() const;
bool closeConn();
bool connect(OmnString &errmsg);
bool reconnect(OmnString &errmsg);
};
#endif
| [
"barryniu@jimodb.com"
] | barryniu@jimodb.com |
2651aaeac9381aa6879607af2e7b03c7953f4b25 | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp | 050bf3248ce7999c24a438a8cad4bbd159ee373d | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 2,433 | cpp | /*
* Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
* Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/svg/SVGZoomEvent.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGPointTearOff.h"
#include "core/svg/SVGRectTearOff.h"
namespace blink {
SVGZoomEvent::SVGZoomEvent()
: m_newScale(0.0f)
, m_previousScale(0.0f)
{
}
PassRefPtrWillBeRawPtr<SVGRectTearOff> SVGZoomEvent::zoomRectScreen() const
{
RefPtrWillBeRawPtr<SVGRectTearOff> rectTearOff = SVGRectTearOff::create(SVGRect::create(), 0, PropertyIsNotAnimVal);
rectTearOff->setIsReadOnlyProperty();
return rectTearOff.release();
}
float SVGZoomEvent::previousScale() const
{
return m_previousScale;
}
PassRefPtrWillBeRawPtr<SVGPointTearOff> SVGZoomEvent::previousTranslate() const
{
RefPtrWillBeRawPtr<SVGPointTearOff> pointTearOff = SVGPointTearOff::create(SVGPoint::create(m_previousTranslate), 0, PropertyIsNotAnimVal);
pointTearOff->setIsReadOnlyProperty();
return pointTearOff.release();
}
float SVGZoomEvent::newScale() const
{
return m_newScale;
}
PassRefPtrWillBeRawPtr<SVGPointTearOff> SVGZoomEvent::newTranslate() const
{
RefPtrWillBeRawPtr<SVGPointTearOff> pointTearOff = SVGPointTearOff::create(SVGPoint::create(m_newTranslate), 0, PropertyIsNotAnimVal);
pointTearOff->setIsReadOnlyProperty();
return pointTearOff.release();
}
const AtomicString& SVGZoomEvent::interfaceName() const
{
return EventNames::SVGZoomEvent;
}
DEFINE_TRACE(SVGZoomEvent)
{
UIEvent::trace(visitor);
}
} // namespace blink
| [
"22249030@qq.com"
] | 22249030@qq.com |
42d3f08f360284d23bbfbe05ee4a5843b47872ac | af7e29c65a9865662586f917b1fde5ef151e463f | /vcc/include/vcc/device.h | aa827cf6c3d9aa164407dd175a7495f55abec1af | [
"Apache-2.0"
] | permissive | caomw/vulkan-cpp-library | e3cde4f81d6d53701843e6f8cf5c5fd03cedc325 | fb329a0184c9e9bc1b2f280d861ae525603ec7f6 | refs/heads/master | 2021-01-12T06:08:54.627696 | 2016-12-23T00:58:30 | 2016-12-23T00:58:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | h | /*
* Copyright 2016 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.
*/
#ifndef DEVICE_H_
#define DEVICE_H_
#include <vcc/internal/raii.h>
#include <vcc/util.h>
namespace vcc {
namespace device {
struct queue_create_info_type {
uint32_t queueFamilyIndex;
std::vector<float> queuePriorities;
};
struct device_type
: public internal::movable_destructible<VkDevice, vkDestroyDevice> {
friend VCC_LIBRARY device_type create(VkPhysicalDevice physical_device,
const std::vector<queue_create_info_type> &queue_create_info,
const std::set<std::string> &layers,
const std::set<std::string> &extensions,
const VkPhysicalDeviceFeatures &features);
friend VkPhysicalDevice get_physical_device(const device_type &device);
device_type() = default;
device_type(const device_type&) = delete;
device_type(device_type&©) = default;
device_type &operator=(const device_type&) = delete;
device_type &operator=(device_type&©) = default;
private:
device_type(VkDevice device, VkPhysicalDevice physical_device)
: internal::movable_destructible<VkDevice, vkDestroyDevice>(device),
physical_device(physical_device) {}
internal::handle_type<VkPhysicalDevice> physical_device;
};
VCC_LIBRARY device_type create(VkPhysicalDevice physical_device,
const std::vector<queue_create_info_type> &queue_create_info,
const std::set<std::string> &layers,
const std::set<std::string> &extensions,
const VkPhysicalDeviceFeatures &features);
VCC_LIBRARY void wait_idle(const device_type &device);
inline VkPhysicalDevice get_physical_device(const device_type &device) {
return device.physical_device;
}
} // namespace device
} // namespace vcc
#endif /* DEVICE_H_ */
| [
"gardell@google.com"
] | gardell@google.com |
23697d02ca4aec938447067ab0ac8ccdcb7e9082 | d4a4d5661749d20b8271640410a4184bb3470d1f | /HostMonitor/BuildUWP/sample_uwp_cpp/SubScreen.xaml.cpp | 5d500215fdde99846b01d9abe15e7721466afc1e | [
"Apache-2.0"
] | permissive | 420041900/GuiLiteSamples | da779458d14aef1ddd181c6a91b7035ef22dcfe0 | b283a3ea33d85c6d9043db61ad81112593e0ddd3 | refs/heads/master | 2021-04-25T00:13:28.710235 | 2017-12-29T04:02:54 | 2017-12-29T04:02:54 | 115,693,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,282 | cpp | //
// SubScreen.xaml.cpp
// Implementation of the SubScreen class
//
#include "pch.h"
#include "SubScreen.xaml.h"
#include <robuffer.h>
using namespace sample_uwp_cpp;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Microsoft::WRL;
using namespace concurrency;
using namespace Windows::UI::ViewManagement;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
typedef struct
{
unsigned int dwMsgId;
unsigned int dwParam1;
unsigned int dwParam2;
}OUTMSGINFO;
extern "C" void* get_frame_buffer(int display_id, int* width, int* height);
extern "C" int send_hid_msg(void* buf, int len, int display_id);
SubScreen::SubScreen()
{
InitializeComponent();
initScreen();
}
void SubScreen::initScreen()
{
m_screen_sub->PointerPressed += ref new PointerEventHandler(this, &SubScreen::OnPointerPressed);
m_screen_sub->PointerReleased += ref new PointerEventHandler(this, &SubScreen::OnPointerRelease);
m_screen_sub->PointerMoved += ref new PointerEventHandler(this, &SubScreen::OnPointerMoved);
}
void SubScreen::set_attr(int index, int color_bytes)
{
m_index = index;
m_color_bytes = color_bytes;
}
byte* SubScreen::get_pixel_data(IBuffer^ pixelBuffer, unsigned int *length)
{
if (length != nullptr)
{
*length = pixelBuffer->Length;
}
// Query the IBufferByteAccess interface.
ComPtr<IBufferByteAccess> bufferByteAccess;
reinterpret_cast<IInspectable*>(pixelBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess));
// Retrieve the buffer data.
byte* pixels = nullptr;
bufferByteAccess->Buffer(&pixels);
return pixels;
}
void SubScreen::update_screen()
{
if (nullptr == m_fb_bitmap)
{
unsigned short* raw_data = (unsigned short*)get_frame_buffer(m_index, &m_fb_width, &m_fb_height);
if (raw_data)
{
m_fb_bitmap = ref new Windows::UI::Xaml::Media::Imaging::WriteableBitmap(m_fb_width, m_fb_height);
m_screen_sub->Source = m_fb_bitmap;
}
return;
}
unsigned int length;
byte* sourcePixels = get_pixel_data(m_fb_bitmap->PixelBuffer, &length);
void* raw_data = get_frame_buffer(m_index, NULL, NULL);
if (!raw_data)
{
return;
}
if (m_color_bytes == 4)
{
unsigned int* p_data = (unsigned int*)raw_data;
for (int i = 0; i < length; i += 4)
{
unsigned int rgb = *p_data++;
sourcePixels[i + 3] = 0xff;//transport
sourcePixels[i] = (rgb & 0xFF);
sourcePixels[i + 1] = ((rgb >> 8) & 0xFF);
sourcePixels[i + 2] = ((rgb >> 16) & 0xFF);
}
}
else//16 bits
{
unsigned short* p_data = (unsigned short*)raw_data;
for (int i = 0; i < length; i += 4)
{
unsigned short rgb = *p_data++;
sourcePixels[i + 3] = 0xff;//transport
sourcePixels[i] = ((rgb << 3) & 0xF8);
sourcePixels[i + 1] = ((rgb >> 3) & 0xFC);
sourcePixels[i + 2] = ((rgb >> 8) & 0xF8);
}
}
m_fb_bitmap->Invalidate();
}
void SubScreen::OnPointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
{
auto pointer = e->GetCurrentPoint(this);
int native_x = (pointer->Position.X * m_fb_width / ActualWidth);
int native_y = (pointer->Position.Y * m_fb_height / ActualHeight);
OUTMSGINFO msg;
msg.dwMsgId = 0x4700;
msg.dwParam1 = native_x;
msg.dwParam2 = native_y;
send_hid_msg(&msg, sizeof(msg), m_index);
m_is_dragging = true;
}
void SubScreen::OnPointerRelease(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
{
auto pointer = e->GetCurrentPoint(this);
int native_x = (pointer->Position.X * m_fb_width / ActualWidth);
int native_y = (pointer->Position.Y * m_fb_height / ActualHeight);
OUTMSGINFO msg;
msg.dwMsgId = 0x4600;
msg.dwParam1 = native_x;
msg.dwParam2 = native_y;
send_hid_msg(&msg, sizeof(msg), m_index);
m_is_dragging = false;
}
void SubScreen::OnPointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
{
if (m_is_dragging)
{
OnPointerPressed(sender, e);
}
} | [
"idea4good@outlook.com"
] | idea4good@outlook.com |
68f8bed300aab70f4afd95a6ad85d2748123b6a0 | 199911b50ee3db7d0b30bdc5047b365254c950fd | /ampas/ampas.ino | 35ccd0a6ddff35e28ed2f6362efb9f60267df129 | [] | no_license | wianoski/parseMqtt | 7b91dae8c91fd3746d29a179b3017db8e58cfc6b | 3d77bb5d5dfc2e8435640ae8e1de776681063a19 | refs/heads/master | 2022-12-12T00:10:57.745083 | 2019-10-01T09:01:42 | 2019-10-01T09:01:42 | 171,642,246 | 1 | 0 | null | 2022-12-10T00:57:46 | 2019-02-20T09:28:39 | JavaScript | UTF-8 | C++ | false | false | 15,196 | ino | #include <ESP8266WiFi.h>
// MQTT Library
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Adafruit_Fingerprint.h>
//# define Finger_Rx 7 //D5
//# define Finger_Tx 6 //D6
# define Finger_Rx 13 //D7
# define Finger_Tx 15 //D8
# define esp_Rx 3
# define esp_Tx 2
SoftwareSerial toNode(esp_Rx, esp_Tx);
SoftwareSerial toESP(Finger_Rx, Finger_Tx, false, 256);
Adafruit_Fingerprint finger = Adafruit_Fingerprint( & toESP);
const char* wifiSSID = "StudioIoT";
const char* wifiPassword = "tanyapakandrian";
//const char* wifiSSID = "Webs ploor";
//const char* wifiPassword = "bismillahx";
// MQTT Define
const char* mqttServerIP = "broker.hivemq.com";
//const char* mqttServerIP = "192.168.1.2";
const int mqttPort = 1883;
// MQTT Topic
char * device1 = "finger/found"; // pub & syv
WiFiClient myESP; // myESP become WIFI
PubSubClient client(myESP);
// WIfi Setup
void wifiSetup(){
WiFi.begin(wifiSSID,wifiPassword);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.println("Waiting, connection to Wifi..");
Serial.print("SSID : ");
Serial.println(wifiSSID);
}
Serial.println("Connected to the WiFI Network ");
Serial.print("Connected Network "); Serial.println(wifiSSID);
Serial.print("IP Local "); Serial.println(WiFi.localIP());
}
// publish data to topic
char dataPublish[50];
void publishMQTT(char * topics, String data) {
data.toCharArray(dataPublish, data.length() + 1);
client.publish(topics, dataPublish);
}
void reconnect() {
// MQTT Begin
while(!client.connected()){
Serial.println("Connecting to MQTT Server..");
Serial.print("IP MQTT Server : "); Serial.println(mqttServerIP);
bool hasConnection = client.connect("Esp-1"); // connect(id,username,password) -> true if connect
if(hasConnection){
Serial.println("Success connected to MQTT Broker");
} else {
Serial.print("Failed connected");
Serial.println(client.state());
delay(2000);
Serial.println("Try to connect...");
}
}
// client.publish(topicLatihan1, "Reconnecting");
// client.subscribe(topicLatihan1);
client.publish(device1, "Initializing"); // acc
client.subscribe(device1);
// client.subscribe(topicControlling);
}
void callback(char * topic, byte * payload, unsigned int length) {
Serial.println("--------");
Serial.println("Message Arrived");
Serial.print("Topic :");
Serial.println(topic);
Serial.print("Message : ");
String pesan = "";
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
pesan += (char) payload[i];
}
Serial.println();
// FOR TOPIC 1
// if (strcmp(topic, topicControlling) == 0) {
// if (pesan == "true") {
// Serial.println("LED 1 ON");
// // digitalWrite(LED1, HIGH);
// } else if (pesan == "false") {
// Serial.println("LED 1 OFF");
// // digitalWrite(LED1,LOW);
// }
// Serial.print("Masuk : ");
// Serial.println(pesan);
// }
Serial.print("Pesan masuk :");
Serial.println(pesan);
Serial.println("--------");
}
/*----------------------Wifi end here-----------------*/
uint8_t menu;
uint8_t id = 0;
uint8_t myArray[] = {
2,
3,
4
};
void setup() {
toNode.begin(57600);
Serial.begin(57600);
wifiSetup();
Serial.print(F("WiFi connected! IP address: "));
//Initialize MQTT Connection
client.setServer(mqttServerIP, mqttPort);
client.setCallback(callback); // callback for incoming message
while (!Serial); // For Yun/Leo/Micro/Zero/...
delay(100);
Serial.println("\n\nAdafruit Fingerprint sensor enrollment");
// set the data rate for the sensor serial port
finger.begin(57600);
if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
// while (1) { delay(1); }
}
}
uint8_t readnumber(void) {
uint8_t num = 0;
while (num == 0) {
while (!Serial.available());
num = Serial.parseInt();
}
return num;
}
uint8_t getFingerprintEnroll() {
int p = -1;
Serial.print("Waiting for valid finger to enroll as #");
Serial.println(id);
while (p != FINGERPRINT_OK) {
p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println(".");
break;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
break;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
break;
default:
Serial.println("Unknown error");
break;
}
}
// OK success!
p = finger.image2Tz(1);
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
Serial.println("Remove finger");
delay(2000);
p = 0;
while (p != FINGERPRINT_NOFINGER) {
p = finger.getImage();
}
Serial.print("ID ");
Serial.println(id);
p = -1;
Serial.println("Place same finger again");
while (p != FINGERPRINT_OK) {
p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.print(".");
break;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
break;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
break;
default:
Serial.println("Unknown error");
break;
}
}
// OK success!
p = finger.image2Tz(2);
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
Serial.print("Creating model for #");
Serial.println(id);
p = finger.createModel();
if (p == FINGERPRINT_OK) {
Serial.println("Prints matched!");
// Serial.println(searchDaftar(id));
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_ENROLLMISMATCH) {
Serial.println("Fingerprints did not match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
Serial.print("ID ");
Serial.println(id);
p = finger.storeModel(id);
if (p == FINGERPRINT_OK) {
Serial.println("Stored!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_BADLOCATION) {
Serial.println("Could not store in that location");
return p;
} else if (p == FINGERPRINT_FLASHERR) {
Serial.println("Error writing to flash");
return p;
} else {
Serial.println("Unknown error");
return p;
}
}
int getFingerprintIDez() {
Serial.println("waiting");
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;
p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;
p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;
// found a match!
Serial.print("Found Jari with ID #");
// toNode.s
Serial.print(finger.fingerID);
Serial.print(" with confidence of ");
Serial.println(finger.confidence);
// int foundFinger = finger.fingerID;
// String dataSent = "";
// dataSent = String(foundFinger);
// publishMQTT(device1, dataSent);
//
return finger.fingerID;
}
/*Start Loop*/
void loop() {
if (!client.connected()){
reconnect();
}
client.loop();
Serial.println("Please Choose the Menu ID (from 1 to 3)!");
Serial.println("1. Enroll fingerprint ");
Serial.println("2. To log in");
Serial.println("3. Empty fingerprint db ");
Serial.println("4. Show fingerprint template ");
menu = readnumber();
if (menu == 1) {
Serial.println("Ready to enroll a fingerprint!");
// Serial.println("masukkan Nomor Loker...");
id = readnumber();
if (id > 0 && id < 120) { // ID #0 not allowed, try again!
Serial.println("enroll boz");
getFingerprintEnroll();
};
} else if (menu == 2) {
finger.getTemplateCount();
Serial.print("Sensor contains ");
Serial.print(finger.templateCount);
Serial.println(" templates");
Serial.println("Waiting for valid finger...");
while (menu == 2) {
int in1 = getFingerprintIDez();
// int in2 = searchBuka(in1);
// Serial.println(in2);
if (in1 != -1) {
/*Subs begin*/
int triggerId = 1;
Serial.println(triggerId);
if(triggerId==1){
String foundJari = "found_jari";
String dataSent = "";
dataSent = String(foundJari);
publishMQTT(device1, foundJari);
break;
}
/*Subs end*/
// digitalWrite(in2, HIGH);
// delay(1000);
// digitalWrite(in2, LOW);
in1 = -1;
}
}
} else if (menu == 3) {
finger.emptyDatabase();
} else if (menu == 4) {
for (int finger = 1; finger < 10; finger++) {
downloadFingerprintTemplate(finger);
}
} else {
Serial.println("no choice");
return;
}
}
/*End of loop*/
//MATCHING
uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK success!
p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #");
Serial.print(finger.fingerID);
Serial.print(" with confidence of ");
Serial.println(finger.confidence);
return finger.fingerID;
}
// returns -1 if failed, otherwise returns ID #
//TEMPLATE TAPI GK PAHAM
uint8_t downloadFingerprintTemplate(uint16_t id) {
Serial.println("------------------------------------");
Serial.print("Attempting to load #");
Serial.println(id);
uint8_t p = finger.loadModel(id);
switch (p) {
case FINGERPRINT_OK:
Serial.print("Template ");
Serial.print(id);
Serial.println(" loaded");
break;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
default:
Serial.print("Unknown error ");
Serial.println(p);
return p;
}
// OK success!
Serial.print("Attempting to get #");
Serial.println(id);
p = finger.getModel();
switch (p) {
case FINGERPRINT_OK:
Serial.print("Template ");
Serial.print(id);
Serial.println(" transferring:");
break;
default:
Serial.print("Unknown error ");
Serial.println(p);
return p;
}
// one data packet is 267 bytes. in one data packet, 11 bytes are 'usesless' :D
uint8_t bytesReceived[534]; // 2 data packets
memset(bytesReceived, 0xff, 534);
uint32_t starttime = millis();
int i = 0;
while (i < 534 && (millis() - starttime) < 20000) {
if (toESP.available()) {
bytesReceived[i++] = toESP.read();
}
}
Serial.print(i);
Serial.println(" bytes read.");
Serial.println("Decoding packet...");
uint8_t fingerTemplate[512]; // the real template
memset(fingerTemplate, 0xff, 512);
// filtering only the data packets
int uindx = 9, index = 0;
while (index < 534) {
while (index < uindx) ++index;
uindx += 256;
while (index < uindx) {
fingerTemplate[index++] = bytesReceived[index];
}
uindx += 2;
while (index < uindx) ++index;
uindx = index + 9;
}
for (int i = 0; i < 512; ++i) {
//Serial.print("0x");
printHex(fingerTemplate[i], 2);
//Serial.print(", ");
}
Serial.println("\ndone.");
/*
uint8_t templateBuffer[256];
memset(templateBuffer, 0xff, 256); //zero out template buffer
int index=0;
uint32_t starttime = millis();
while ((index < 256) && ((millis() - starttime) < 1000))
{
if (toESP.available())
{
templateBuffer[index] = toESP.read();
index++;
}
}
Serial.print(index); Serial.println(" bytes read");
//dump entire templateBuffer. This prints out 16 lines of 16 bytes
for (int count= 0; count < 16; count++)
{
for (int i = 0; i < 16; i++)
{
Serial.print("0x");
Serial.print(templateBuffer[count*16+i], HEX);
Serial.print(", ");
}
Serial.println();
}*/
}
void printHex(int num, int precision) {
char tmp[16];
char format[128];
sprintf(format, "%%.%dX", precision);
sprintf(tmp, format, num);
Serial.print(tmp);
}
| [
"thirafi.wian@gmail.com"
] | thirafi.wian@gmail.com |
4897db444c423477269cd8ad88cee96db4c796b1 | 6d59b8fa0ac393720a687a8d5cbe80ab25ff97a4 | /aws-cpp-sdk-waf-regional/include/aws/waf-regional/model/TagInfoForResource.h | dfe769337f026ac1287c6ec9dcc1e2aca3dc8c09 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 175703252/aws-sdk-cpp | 20149ad1b06d5b7759fb01a45bf1214e298ba306 | c07bd636471ba79f709b03a489a1a036b655d3b2 | refs/heads/master | 2021-03-10T20:43:30.772193 | 2020-03-10T19:19:04 | 2020-03-10T19:19:04 | 246,483,735 | 1 | 0 | Apache-2.0 | 2020-03-11T05:34:57 | 2020-03-11T05:34:56 | null | UTF-8 | C++ | false | false | 3,276 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/waf-regional/WAFRegional_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/waf-regional/model/Tag.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace WAFRegional
{
namespace Model
{
class AWS_WAFREGIONAL_API TagInfoForResource
{
public:
TagInfoForResource();
TagInfoForResource(Aws::Utils::Json::JsonView jsonValue);
TagInfoForResource& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const Aws::String& GetResourceARN() const{ return m_resourceARN; }
inline bool ResourceARNHasBeenSet() const { return m_resourceARNHasBeenSet; }
inline void SetResourceARN(const Aws::String& value) { m_resourceARNHasBeenSet = true; m_resourceARN = value; }
inline void SetResourceARN(Aws::String&& value) { m_resourceARNHasBeenSet = true; m_resourceARN = std::move(value); }
inline void SetResourceARN(const char* value) { m_resourceARNHasBeenSet = true; m_resourceARN.assign(value); }
inline TagInfoForResource& WithResourceARN(const Aws::String& value) { SetResourceARN(value); return *this;}
inline TagInfoForResource& WithResourceARN(Aws::String&& value) { SetResourceARN(std::move(value)); return *this;}
inline TagInfoForResource& WithResourceARN(const char* value) { SetResourceARN(value); return *this;}
inline const Aws::Vector<Tag>& GetTagList() const{ return m_tagList; }
inline bool TagListHasBeenSet() const { return m_tagListHasBeenSet; }
inline void SetTagList(const Aws::Vector<Tag>& value) { m_tagListHasBeenSet = true; m_tagList = value; }
inline void SetTagList(Aws::Vector<Tag>&& value) { m_tagListHasBeenSet = true; m_tagList = std::move(value); }
inline TagInfoForResource& WithTagList(const Aws::Vector<Tag>& value) { SetTagList(value); return *this;}
inline TagInfoForResource& WithTagList(Aws::Vector<Tag>&& value) { SetTagList(std::move(value)); return *this;}
inline TagInfoForResource& AddTagList(const Tag& value) { m_tagListHasBeenSet = true; m_tagList.push_back(value); return *this; }
inline TagInfoForResource& AddTagList(Tag&& value) { m_tagListHasBeenSet = true; m_tagList.push_back(std::move(value)); return *this; }
private:
Aws::String m_resourceARN;
bool m_resourceARNHasBeenSet;
Aws::Vector<Tag> m_tagList;
bool m_tagListHasBeenSet;
};
} // namespace Model
} // namespace WAFRegional
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
9546483b98d2344b778d7eb5ffa0f6abdcc8bfd8 | 6ad19223633c1dea5be3927f1758cd45df3c259f | /lib/renderer/texture2d.h | 56ddcac83d947bcdbb29df80b750bcd2fbbf2912 | [] | no_license | JTippetts/Tetriarch | f6bb302958a1a3c807b46c728d0c5b7ca3f08590 | f0f481302216d0be848e4eb5bbd6553757f62421 | refs/heads/master | 2021-01-10T16:27:34.189712 | 2017-06-22T22:11:40 | 2017-06-22T22:11:40 | 49,109,696 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 724 | h | #ifndef TEXTURE2D_H
#define TEXTURE2D_H
#include "resource/resourcecache.h"
#include "resource/image.h"
#include "resource/yamlfile.h"
#include <GL/gl.h>
class Texture : public ResourceBase
{
public:
Texture(SystemManager *mom) : ResourceBase(mom){}
virtual ~Texture(){}
virtual void Load(std::string name)=0;
virtual void bind()=0;
protected:
};
class Texture2D : public Texture
{
public:
Texture2D(SystemManager *mom);
~Texture2D();
GLuint GetId(){return id_;}
void Load(std::string name);
void Create(int w, int h, int d, unsigned char *data);
void Create(Image *i);
void LoadFromDefinition(const YAML::Node &yaml);
void bind();
private:
GLuint id_;
};
#endif
| [
"vertexnormal@gmail.com"
] | vertexnormal@gmail.com |
a48805d76c86472536849ab9b4b6e87c0e8ffcf4 | 33394856a8de0e824ec49a3643e387cdbacca0c6 | /SolvedProblems/HDU/2143.cpp | 24d44257c55ed08b490ed81a3f45ad516fd9fc6f | [] | no_license | MoogleAndChocobo/ACM-Learning | caf116d713c24d14af166dac701e7812e495405b | 9a86daf172c3a74aab69f2054f222f51c5939830 | refs/heads/master | 2021-08-10T15:40:43.108255 | 2018-09-14T07:06:04 | 2018-09-14T07:06:04 | 129,596,917 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,885 | cpp | #include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <cctype>
#include <queue>
#include <set>
#include <map>
#include <iostream>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LF;
#define fli freopen("in.txt", "r", stdin);
#define flo freopen("out.txt", "w", stdout);
#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define dow(i, a, b) for(int i = a; i >= b; i--)
#define mem(a) memset(a, 0, sizeof(a))
#define mst(a, b) memset(a, b, sizeof(a))
#define sfi(a) scanf("%d", &a)
#define sfs(a) scanf("%s", a)
#define sfl(a) scanf("%lld", &a)
#define sfd(a) scanf("%lf", &a)
#define pb(a) push_back(a)
#define all(c) (c).begin(),(c).end()
#define YES puts("YES")
#define NO puts("NO")
#define yes puts("yes")
#define no puts("no")
#define Yes puts("Yes")
#define No pus("No")
const int MAX = 1e6 + 10;
const int N = 205;
const int INF = 0x3f3f3f3f;
const LL LINF = 0x3f3f3f3f3f3f3f;
const int MOD = 1007;
const double EPS = (double)1e-10;
const int LMON[15] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
const int CMON[15] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
const int diro[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
const int dirt[6][3] = {{0,0,1},{0,0,-1},{1,0,0},{-1,0,0},{0,1,0},{0,-1,0}};
int main()
{
#ifdef LOCAL
//~ fli
//~ flo
#endif //LOCAL
LL a, b, c;
while(~scanf("%lld%lld%lld", &a, &b, &c))
{
bool f = false;
if(a + b == c || a + c == b || b + c == a)
f = true;
if(a * b == c || a * c == b || b * c == a)
f = true;
if(a && (b % a == c || c % a == b))
f = true;
if(b && (a % b == c || c % b == a))
f = true;
if(c && (a % c == b || b % c == a))
f = true;
puts((f) ? "oh,lucky!" : "what a pity!");
}
return 0;
} | [
"1728708466@qq.com"
] | 1728708466@qq.com |
46c7c96318774840201e4afc8ca7ccbf4b0e8cf3 | 2bdfec46f4725c9c7c0ad54935802d84076ff3e5 | /test/mining-manager/t_PropIdTable.cpp | a248a039e60a70469f0c70601fdae9f96b796b41 | [
"Apache-2.0"
] | permissive | izenecloud/sf1r-ad-delivery | 66f73bc7764216a1faed3d8de0ab3a569b8d4900 | 998eadb243098446854615de9a96e58a24bd2f4f | refs/heads/master | 2021-01-19T14:09:42.842935 | 2014-09-23T10:41:15 | 2014-09-23T10:41:15 | 24,359,409 | 18 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,463 | cpp | ///
/// @file t_PropIdTable.cpp
/// @brief test PropIdTable to store property value ids for each doc
/// @author Jun Jiang <jun.jiang@izenesoft.com>
/// @date Created 2012-05-31
///
#include "PropIdTableTestFixture.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(PropIdTableTest)
typedef sf1r::PropIdTableTestFixture<uint16_t, uint32_t> PropIdTestFixture;
BOOST_FIXTURE_TEST_CASE(checkPropId, PropIdTestFixture)
{
checkIdList();
appendIdList("123");
appendIdList("");
appendIdList("456 789");
appendIdList("65535"); // 2^16-1
appendIdList("65535 65534 65533");
appendIdList("1 2 3 4 5 6 7 8 9");
appendIdList("");
appendIdList("");
appendIdList("");
appendIdList("9 7 5 3 1 2 4 6 8");
appendIdList("10000 1000 100 10 1");
checkIdList();
}
typedef sf1r::PropIdTableTestFixture<uint32_t, uint32_t> AttrIdTestFixture;
BOOST_FIXTURE_TEST_CASE(checkAttrId, AttrIdTestFixture)
{
checkIdList();
appendIdList("123");
appendIdList("");
appendIdList("456 789");
appendIdList("2147483647"); // 2^31-1
appendIdList("2147483647 2147483646 2147483645");
appendIdList("1 2 3 4 5 6 7 8 9");
appendIdList("");
appendIdList("");
appendIdList("");
appendIdList("9 7 5 3 1 2 4 6 8");
checkIdList();
checkOverFlow();
appendIdList("1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1");
checkIdList();
}
BOOST_AUTO_TEST_SUITE_END()
| [
"jun.jiang@izenesoft.com"
] | jun.jiang@izenesoft.com |
59b3e3424472c6bc8e5a30ae778ed23db15eb8fb | a9a912f0c350c22919eb54ade443360d26617074 | /GW2Radial/include/UnitQuad.h | 4193cc4ae8cfc8765d017974c6a8b735d728c0d2 | [
"MIT"
] | permissive | xvwyh/GW2Radial | ccbd2b5c5016459c6ca3ef14d94fe329488469a6 | e0f0d3f32df3de95d760d9dfd7c72564c0d1b6e5 | refs/heads/master | 2020-04-21T07:57:22.976040 | 2019-03-26T02:16:55 | 2019-03-26T02:16:55 | 169,404,879 | 0 | 0 | MIT | 2019-02-06T12:48:00 | 2019-02-06T12:48:00 | null | UTF-8 | C++ | false | false | 831 | h | #pragma once
#include <Main.h>
#include <d3d9.h>
#include <d3dx9.h>
namespace GW2Radial
{
struct ScreenVertex
{
D3DXVECTOR2 uv;
};
class UnitQuad
{
public:
explicit UnitQuad(IDirect3DDevice9* device);
UnitQuad(const UnitQuad& uq) = delete;
UnitQuad& operator=(UnitQuad uq) = delete;
UnitQuad(UnitQuad&& uq) = delete;
UnitQuad& operator=(UnitQuad&& uq) = delete;
~UnitQuad();
ScreenVertex points[4];
static uint size() { return sizeof(ScreenVertex) * 4; }
static uint stride() { return sizeof(ScreenVertex); }
static const D3DVERTEXELEMENT9* def();
void Bind(uint stream = 0, uint offset = 0) const;
void Draw(uint triCount = 2, uint startVert = 0) const;
private:
IDirect3DDevice9* device_ = nullptr;
IDirect3DVertexDeclaration9* vertexDeclaration_ = nullptr;
IDirect3DVertexBuffer9* buffer_ = nullptr;
};
} | [
"jpguertin.cg@gmail.com"
] | jpguertin.cg@gmail.com |
37830ac17967a419a94cf5bdd76c14a561e1927e | 4642a2dfeb5362ee8a786cbdb5510bdaeb66c225 | /cci/ch9/6.cc | a00abbc5d11a7d2c9eea779ed384ef575158ab9b | [] | no_license | arabindamoni/cci | ec144f2f8ef5d2940dcc2349f38adbf30d994dd6 | a19413953777f93d7a72ab6417e822a714439792 | refs/heads/master | 2021-05-04T10:50:44.963098 | 2019-06-25T04:43:06 | 2019-06-25T04:43:06 | 36,967,373 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cc | #include<iostream>
#include<ctime>
using namespace std;
bool find(int *arr,int m,int n,int i,int j,int key){
if(m<=i || n <=j) return false;
if(key == *(arr+m*i+j)) return true;
else if(key < *(arr+m*i+j)) return find(arr,m,n,i-1,j,key) || find(arr,m,n,i,j-1,key);
else return find(arr,m,n,i+1,j,key) || find(arr,m,n,i,j+1,key);
}
int main(){
clock_t start = clock();
int m =4, n=4;
int *arr = new int[m*n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
*(arr+m*i+j) = i+j;
}
}
cout << find(arr,m,n,0,0,0);
cout << endl;
cout << "Execution time: "<<(clock() - start)/(double)1000000 <<" seconds"<<endl;
return 0;
} | [
"arabindamoni@gmail.com"
] | arabindamoni@gmail.com |
c7e6285251c1b406e06b9ad41a62e911c3bc1dcb | 1d769fc15f9d70cc14d76e0d44ad35fccab494f1 | /packages/fsuipc-wasm/third_party/FSUIPC_WAPI/CDAIdBank.cpp | f9775199175f393c5b65c3480cc6d0c0636cb000 | [
"MIT"
] | permissive | koesie10/fsuipc-node | e4615b7ed4be5a47268e0c5dc2031e5c54bbefb3 | ebea4812e5306421fc5dabd4ff924982d5ce8c4b | refs/heads/main | 2023-08-09T05:52:53.437735 | 2022-10-22T11:12:39 | 2022-10-22T11:12:39 | 120,291,131 | 17 | 22 | MIT | 2023-08-05T07:15:32 | 2018-02-05T10:40:36 | C++ | UTF-8 | C++ | false | false | 2,579 | cpp | #include "CDAIdBank.h"
#include "SimConnect.h"
#include "Logger.h"
using namespace std;
using namespace CDAIdBankMSFS;
using namespace CPlusPlusLogging;
CDAIdBank::CDAIdBank(int id, HANDLE hSimConnect) {
nextId = id;
this->hSimConnect = hSimConnect;
}
CDAIdBank::~CDAIdBank() {
}
pair<string, int> CDAIdBank::getId(int size, string name) {
char szLogBuffer[512];
pair<string, int> returnVal;
std::multimap<string, pair<int, int>>::iterator it;
DWORD dwLastID;
// First, check if we have one available
it = availableBank.find(name);
if (it != availableBank.end()) {
// Check size matches
if (size == it->second.first) {
returnVal = make_pair(it->first, it->second.second);
availableBank.erase(it);
pair<string, pair<int, int>> out = make_pair(returnVal.first, make_pair(returnVal.second, size));
outBank.insert(out);
return returnVal;
}
else { // Lets remove
availableBank.erase(it);
}
}
// Create new CDA
string newName = string(name);
returnVal = make_pair(newName, nextId);
pair<string, pair<int, int>> out = make_pair(newName, make_pair(nextId, size));
outBank.insert(out);
// Set-up CDA
if (!SUCCEEDED(SimConnect_MapClientDataNameToID(hSimConnect, newName.c_str(), nextId))) {
sprintf_s(szLogBuffer, sizeof(szLogBuffer), "Error mapping CDA name %s to ID %d", newName.c_str(), nextId);
LOG_ERROR(szLogBuffer);
}
else {
SimConnect_GetLastSentPacketID(hSimConnect, &dwLastID);
sprintf_s(szLogBuffer, sizeof(szLogBuffer), "CDA name %s mapped to ID %d [requestId=%lu]", newName.c_str(), nextId, dwLastID);
LOG_DEBUG(szLogBuffer);
}
// Finally, Create the client data if it doesn't already exist
if (!SUCCEEDED(SimConnect_CreateClientData(hSimConnect, nextId, size, SIMCONNECT_CREATE_CLIENT_DATA_FLAG_READ_ONLY))) {
sprintf_s(szLogBuffer, sizeof(szLogBuffer), "Error creating client data area with id=%d and size=%d", nextId, size);
LOG_ERROR(szLogBuffer);
}
else {
SimConnect_GetLastSentPacketID(hSimConnect, &dwLastID);
sprintf_s(szLogBuffer, sizeof(szLogBuffer), "Client data area created with id=%d (size=%d) [requestID=%lu]", nextId, size, dwLastID);
LOG_DEBUG(szLogBuffer);
}
nextId++;
return returnVal;
}
void CDAIdBank::returnId(string name) {
std::map<string, pair<int, int>>::iterator it;
// First, check if we have one available
it = outBank.find(name);
if (it != outBank.end()) {
pair<int, int> p = outBank.at(name);
pair<string, pair<int, int>> returnedItem = make_pair(name, p);
outBank.erase(it);
availableBank.insert(returnedItem);
}
}
| [
"koen@vlaswinkel.info"
] | koen@vlaswinkel.info |
3aef84289ab0cf7a98451958cecd74d5a20e7ddc | b88b4aafc9a85e42f0e1087dce085a9266d5e340 | /sensors/Relay/Relay.ino | b740c1fd1ae2c17ce49375a98825f3d0db595488 | [] | no_license | minh281995/citygarden | 138aab22e4a46ebd180ddf9a1f3eb95f584c38b9 | 62bf3ffdd03642ec83a4bad750bec7664841851e | refs/heads/master | 2021-01-19T22:01:24.967523 | 2017-05-01T16:39:35 | 2017-05-01T16:39:35 | 88,738,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | ino | // Replay to turn on/off Bump
#define RELAYCONTROL_D_PIN 4
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(RELAYCONTROL_D_PIN, OUTPUT);
}
void loop() {
digitalWrite(RELAYCONTROL_D_PIN, HIGH);
delay(2000);
digitalWrite(RELAYCONTROL_D_PIN, LOW);
delay(2000);
// put your main code here, to run repeatedly:
}
| [
"geniusnm281995@gmail.com"
] | geniusnm281995@gmail.com |
df332288d78ea60789afa5a8f88dbad9ca5d62aa | 50c473bcf5b5ef67408b7d6e6c19ae4710d48207 | /hw1/Team Division Problem.cpp | 0f6634df4653caaa35c2b57f9bd2295e371f0490 | [] | no_license | gaserashraf/CMP2030 | 5d90cbf285ef5656d44d66bd0ba58a5c347d09a4 | d4234e73baca7194c67273eff9afa36453d0e187 | refs/heads/main | 2023-02-23T01:48:55.447675 | 2021-01-31T11:37:50 | 2021-01-31T11:37:50 | 334,640,327 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,464 | cpp | #include<iostream>
#include<stdio.h>
#include <sstream>
#include <cstdio>
#include<fstream>
#include<algorithm>
#include<vector>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <numeric>
#include <vector>
#include<unordered_map>
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
#define _USE_MATH_DEFINES
# define M_PI 3.14159265358979323846 /* pi */
#define ll long long
#define ld long double
#define vbe(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define clr(v, d) memset(v, d, sizeof(v))
#define rep(i, v) for(int i=0;i<sz(v);++i)
#define lp(i, n) for(int i=0;i<(int)(n);++i)
#define lpi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define lpd(i, j, n) for(int i=(j);i>=(int)(n);--i)
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
ll GCD(ll a, ll b) { return (a) ? GCD(b % a, a) : b; }
ll LCM(ll a, ll b) { return a * b / GCD(a, b); }
ll fastpow(ll b, ll p) { if (!p) return 1; ll ret = fastpow(b, p >> 1); ret *= ret; if (p & 1) ret *= b; return ret; }
string alpha = "abcdefghijklmnopqrstuvwxyz";
int divisor(int number)
{
int i;
for (i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return number / i;
}
}
return 1;
}
int myXOR(int x, int y)
{
int res = 0; // Initialize result
// Assuming 32-bit Integer
for (int i = 31; i >= 0; i--)
{
// Find current bits in x and y
bool b1 = x & (1 << i);
bool b2 = y & (1 << i);
// If both are 1 then 0 else xor is same as OR
bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);
// Update result
res <<= 1;
res |= xoredBit;
}
return res;
}
//std::getline(std::cin, a); //read string with spaces
void printDivisors(int n, vector<int>& v)
{
// Note that this loop runs till square root
for (int i = 1; i <= sqrt(n); i++)
{
if (n % i == 0)
{
// If divisors are equal, print only one
if (n / i == i && i > 1)
v.push_back(i);
else // Otherwise print both
{
if (i > 1)
v.push_back(i);
if (n / i > 1)
v.push_back(n / i);
}
}
}
}
int bin(vector<int>vec, int val)
{
int l = 0, r = vec.size() - 1, mid = r / 2;
while (l <= r)
{
mid = (l + r) / 2;
if (vec[mid]<val && vec[mid + 1]>val)
{
if (vec[mid + 1] == val)
return mid + 1;
return mid;
}
else if (vec[mid] > val)
{
r = mid - 1;
}
else if (vec[mid] < val)
{
l = mid + 1;
}
else if (vec[mid] == val)
return mid;
}
return -1;
}
void clear(vector<bool>v)
{
for (int i = 0; i < v.size(); i++)
v[i] = 0;
}
bool comp(const string& s1, const string& s2)
{
// Suppose s1 = 900, s2 = 9, then it compares
// 9900 with 9009.
return s2 + s1 < s1 + s2;
}
vector<string> split(const string& s, char delim) {
vector<string> result;
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
result.push_back(item);
}
return result;
}
int countWords(string str)
{
// breaking input into word using string stream
stringstream s(str); // Used for breaking words
string word; // to store individual words
int count = 0;
while (s >> word)
count++;
return count;
}
ll power(ll x, ll y, ll p, int& c)
{
int res = 1; // Initialize result
if (x >= p)
c++;
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
{
if (res * x >= p)
c++;
res = (res * x) % p;
}
// y must be even now
y = y >> 1; // y = y/2
if (x * x >= p)
c++;
x = (x * x) % p;
}
return res;
}
bool isPalindrome(string str)
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = str.length() - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
{
return 0;
}
}
return 1;
}
bool checkMuns(vector<int>vec)
{
lp(i, vec.size())
{
if (vec[i] < 0)
return 0;
}
return 1;
}
void fast()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
ll power(ll x, ll y, ll p)
{
ll res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
ll ceiLl(ll x, ll y)
{
return (x + y - 1) / y;
}
vector<ll> divisors(ll n)
{
vector<ll>ans;
ll i = 1;
for (; i * i < n; i++)
{
if (n % i == 0)
{
ans.push_back(i);
ans.push_back(n / i);
}
}
if (i * i == n)
ans.push_back(i);
return ans;
}
vector<ll> findDivisors(ll n)//form 1 to n
{
// Array to store the count
// of divisors
vector<ll> numFactors(n + 1);
// For every number from 1 to n
for (int i = 1; i <= n; i++) {
// Increase divisors count for
// every number divisible by i
for (int j = 1; j * i <= n; j++)
numFactors[i * j]++;
}
return numFactors;
}
vector<ll> factorization(ll n) // max n is 1e12
{ //O(sqrt(n))
vector<ll> primes;
for (ll i = 2; i * i <= n; ++i) // Improve start by i = 3.
{
if (n % i == 0)
{
primes.push_back(i);
while (n % i == 0)
{
n /= i;
}
} //Get every prime inside n.n i^ j is a new number
}
if (n > 1)
primes.push_back(n);
return primes;
}
bool isSubSeq(string a, string b)
{
int idx = 0;
for (int i = 0; i < a.length(); i++)
{
if (a[i] == b[idx])
idx++;
}
if (idx == b.length())
return 1;
else
return 0;
}
bool isSubStr(string a, string b)
{
for (int i = 0; i < a.length(); i++)
{
if (a.substr(i, b.length()) == b)
return 1;
}
return 0;
}
bool sortbysec(const pair<int, int>& a,
const pair<int, int>& b)
{
return (a.second < b.second);
}
bool isEqual(string a, string b)
{
if (a.size() != b.size())
return 0;
sort(vbe(a)); sort(vbe(b));
if (a == b)
return 1;
return 0;
}
string bin(unsigned n)
{
string ans = "";
unsigned i;
for (i = 1 << 14; i > 0; i = i / 2)
(n & i) ? ans += '1' : ans += '0';
return ans;
}
vector<vector<int>>vec;
vector<int>vis;
int n, m;
bool isaChild(int par, int ch)
{
lp(i, vec[par].size())
{
if (vec[par][i] == ch)
return 1;
}
lp(i, vec[ch].size())
{
if (vec[ch][i] == par)
return 1;
}
return 0;
}
bool isVildTeam(vector<int>vec)
{
if (!vec.size() || vec.size() > n)
return 0;
lp(i, vec.size())
{
lp(j, vec.size())
{
if (i == j)
continue;
if (isaChild(vec[i], vec[j]))
return 0;
}
}
return 1;
}
bool isVaild(string str)
{
lp(i, str.length())
{
lp(j, str.length())
{
if (i == j)
continue;
if (str[i] == str[j])
{
if (vec[i][j])
return 0;
}
}
}
return 1;
}
int ansf ;
void gaser2(int s, int len, vector<int>ans,int k)
{
if (s == k)
{
string str = "";
lp(i,n)
str += (ans[i]+'0');
if (isVaild(str))
{
set<char>sset;
lp(i, str.size())
sset.insert(str[i]);
ansf = min(ansf, int(sset.size()));
}
return;
}
lp(i, k)
{
ans[s] = i;
gaser2(s + 1, len, ans,k);
}
}
int main()
{
fast();
int t;
t = 1;
while (t--)
{
cin >> n>>m;
vec.resize(n);
ansf = n;
lp(i, n)
{
lp(i, n)
{
vec[i].push_back(0);
}
}
lp(i, m)
{
int u, v;
cin >> u >> v;
vec[u][v] = 1;
vec[v][u] = 1;
}
vector<int>ans(n, 0);
gaser2(0, n, ans,n-1);
cout << ansf;
/* gaser3(0);
vector<string>anss(vbe(allVildTeams));
ll ans = n;
for (ll mask = 0; mask < (1 << anss.size()); mask++) {
ll sumdis = 0, sums = 0, cnt = 0;
set<char>setnormal;
for (ll i = 0; i < anss.size(); i++) {
if ((1 << i) & mask) {
cnt++;
sums += anss[i].size();
lp(zz, anss[i].size())
{
setnormal.insert(anss[i][zz]);
}
}
}
sumdis += setnormal.size();
if ( sums==n&&sumdis == sums)
{
ans = min(ans, cnt);
}
}
cout << ans;*/
cout << "\n";
}
return 0;
}
//0 3 -2 5 -1
//-2 -1 0 3 5
// 0 1 2 3 4
/*
std::cout << std::fixed;
std::cout << std::setprecision(12);
*/ | [
"elkinggaser@gmail.com"
] | elkinggaser@gmail.com |
9d8c1de66380a889c05a1efffb86c9bd6cc88713 | a8181363694dc3130f1f3c3987bc9b1d6104b421 | /brownJavaToCpp/inheritance/src/Foo.cpp | fe094a666fbc46e53c7b9b2696de6eb7168fb2e7 | [] | no_license | twillis209/cpp | 821f295fa85dfa099ce4e5eaaf137530025a01c8 | a3f4dab0c68ec099c12201893766c155ce01176a | refs/heads/master | 2022-06-02T04:41:50.651122 | 2020-05-01T21:34:18 | 2020-05-01T21:34:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | cpp | #include "Foo.h"
A::A() {
m_a = 2;
}
A::~A() {
printf("A destructor called\n");
}
A::A(int a) {
printf("a: %d\n", a);
m_a = a;
}
void A::printField() {
printf("m_a: %d\n", m_a);
}
B::B() {
m_b = 4;
}
B::~B() {
printf("B destructor called\n");
}
B::B(int b) : A(1) {
printf("b: %d\n", b);
m_b = b;
}
void B::printField() {
printf("This is B's implementation of \'printField()\'\nm_b: %d\n", m_b);
printf("But I can also call my parent's implementation:\n");
A::printField();
}
void B::abstractMethod() {
printf("Now I'm implemented!\n");
}
| [
"tom.willis@live.com"
] | tom.willis@live.com |
42e2ba20d3c6749c606651f99a1a4dc445f600b8 | ba536d12bffabe9f1ccf8e8b48ff7a29c734ddcb | /archive/Gen 2 2016-2017/Software/PopUp_Archive_4.0-12-20-17/Testing and Development/PopUpDemo/TSL2561_LuxSensor/TSL2561_LuxSensor.ino | 613b5965b50a37f8eead5d4805176959bb5b5d13 | [
"MIT"
] | permissive | NOAA-PMEL/EcoFOCI_PopUp | 80f257a25f705c8bc9f424f0339748b10d72639b | 481e468106a3b6b43f64fabe7e53738e71a027bc | refs/heads/master | 2023-03-17T03:25:57.050915 | 2023-03-03T20:41:49 | 2023-03-03T20:41:49 | 151,126,374 | 1 | 1 | MIT | 2021-09-29T16:52:09 | 2018-10-01T17:11:23 | C | UTF-8 | C++ | false | false | 5,137 | ino | #include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
/* This driver uses the Adafruit unified sensor library (Adafruit_Sensor),
which provides a common 'type' for sensor data and some helper functions.
To use this driver you will also need to download the Adafruit_Sensor
library and include it in your libraries folder.
You should also assign a unique ID to this sensor for use with
the Adafruit Sensor API so that you can identify this particular
sensor in any data logs, etc. To assign a unique ID, simply
provide an appropriate value in the constructor below (12345
is used by default in this example).
Connections
===========
Connect SCL to analog 5
Connect SDA to analog 4
Connect VDD to 3.3V DC
Connect GROUND to common ground
I2C Address
===========
The address will be different depending on whether you leave
the ADDR pin floating (addr 0x39), or tie it to ground or vcc.
The default addess is 0x39, which assumes the ADDR pin is floating
(not connected to anything). If you set the ADDR pin high
or low, use TSL2561_ADDR_HIGH (0x49) or TSL2561_ADDR_LOW
(0x29) respectively.
History
=======
2013/JAN/31 - First version (KTOWN)
*/
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
/**************************************************************************/
/*
Displays some basic information on this sensor from the unified
sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
sensor_t sensor;
tsl.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}
/**************************************************************************/
/*
Configures the gain and integration time for the TSL2561
*/
/**************************************************************************/
void configureSensor(void)
{
/* You can also manually set the gain or enable auto-gain support */
// tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */
// tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */
tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */
/* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but slowest conversions */
/* Update these values depending on what you've set above! */
Serial.println("------------------------------------");
Serial.print ("Gain: "); Serial.println("Auto");
Serial.print ("Timing: "); Serial.println("402 ms");
Serial.println("------------------------------------");
}
/**************************************************************************/
/*
Arduino setup function (automatically called at startup)
*/
/**************************************************************************/
void setup(void)
{
Serial.begin(9600);
Serial.println("Light Sensor Test"); Serial.println("");
/* Initialise the sensor */
if(!tsl.begin())
{
/* There was a problem detecting the ADXL345 ... check your connections */
Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
while(1);
}
/* Display some basic information on this sensor */
displaySensorDetails();
/* Setup the sensor gain and integration time */
configureSensor();
/* We're ready to go! */
Serial.println("");
}
/**************************************************************************/
/*
Arduino loop function, called once 'setup' is complete (your own code
should go here)
*/
/**************************************************************************/
void loop(void)
{
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
if (event.light)
{
Serial.print(event.light); Serial.println(" lux");
}
else
{
/* If event.light = 0 lux the sensor is probably saturated
and no reliable data could be generated! */
Serial.println("Sensor overload");
}
delay(250);
}
| [
"daniel.p.langis@noaa.gov"
] | daniel.p.langis@noaa.gov |
e2367def9c13bf6cb93343fb2859392bec18f9eb | 0a5645154953b0a09d3f78753a1711aaa76928ff | /navigationkit/qt/src/maneuverimp.cpp | 3962c269b844d4402a4166cdee9ded84825f41f3 | [] | no_license | GENIVI/navigation-next | 3a6f26063350ac8862b4d0e2e9d3522f6f249328 | cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36 | refs/heads/master | 2023-08-04T17:44:45.239062 | 2023-07-25T19:22:19 | 2023-07-25T19:22:19 | 116,230,587 | 17 | 11 | null | 2018-05-18T20:00:38 | 2018-01-04T07:43:22 | C++ | UTF-8 | C++ | false | false | 5,273 | cpp | /*
Copyright (c) 2018, TeleCommunication Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the TeleCommunication Systems, Inc., nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL TELECOMMUNICATION SYSTEMS, INC.BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!--------------------------------------------------------------------------
@file routeinformationimp.cpp
@date 10/15/2014
@addtogroup navigationkit
*/
/*
* (C) Copyright 2014 by TeleCommunication Systems, Inc.
*
* The information contained herein is confidential, proprietary
* to TeleCommunication Systems, Inc., and considered a trade secret
* as defined in section 499C of the penal code of the State of
* California. Use of this information by anyone other than
* authorized employees of TeleCommunication Systems is granted only
* under a written non-disclosure agreement, expressly prescribing
* the scope and manner of such use.
---------------------------------------------------------------------------*/
#include "maneuverimp.h"
#include <vector>
namespace locationtoolkit
{
ManeuverImpl::ManeuverImpl(const nbnav::Maneuver& maneuver):mStackAdvise(false),
mIsDestination(false)
{
mManeuverId = (qint32)maneuver.GetManeuverID();
//get polyline
const std::vector<nbnav::Coordinates>& polyline = maneuver.GetPolyline();
for(size_t i = 0; i < polyline.size(); i++)
{
Coordinates *coordinate = new Coordinates();
coordinate->latitude = polyline[i].latitude;
coordinate->longitude = polyline[i].longitude;
mPolyline.push_back(coordinate);
}
mRouteTTF = maneuver.GetRoutingTTF().c_str();
mDistance = (qreal)maneuver.GetDistance();
mCommand = maneuver.GetCommand().c_str();
mPrimaryStreet = maneuver.GetPrimaryStreet().c_str();
mSecondaryStreet = maneuver.GetSecondaryStreet().c_str();
mTime = (qreal)maneuver.GetTime();
nbnav::Coordinates point = maneuver.GetPoint();
mPoint.latitude = point.latitude;
mPoint.longitude = point.longitude;
//FormattedTextBlock mMiManeuverText;
//FormattedTextBlock mKmManeuverText;
mMiDescription = maneuver.GetDescription(false, false).c_str();
mKmDescription = maneuver.GetDescription(true, false).c_str();
mTrafficDelay = (qreal)maneuver.GetTrafficDelay();
mStackAdvise = maneuver.GetStackAdvise();
mExitNumber = maneuver.GetExitNumber().c_str();
mIsDestination = maneuver.IsDestination();
}
ManeuverImpl::~ManeuverImpl()
{
QVector<Coordinates*>::iterator it;
for(it = mPolyline.begin(); it != mPolyline.end(); )
{
delete (*it);
it = mPolyline.erase(it);
}
}
qint32 ManeuverImpl::GetManeuverID() const
{
return mManeuverId;
}
const QVector<Coordinates*>& ManeuverImpl::GetPolyline() const
{
return mPolyline;
}
const QString& ManeuverImpl::GetRoutingTTF() const
{
return mRouteTTF;
}
qreal ManeuverImpl::GetDistance() const
{
return mDistance;
}
const QString& ManeuverImpl::GetPrimaryStreet() const
{
return mPrimaryStreet;
}
const QString& ManeuverImpl::GetSecondaryStreet() const
{
return mSecondaryStreet;
}
qreal ManeuverImpl::GetTime() const
{
return mTime;
}
const QString& ManeuverImpl::GetCommand() const
{
return mCommand;
}
const Coordinates& ManeuverImpl::GetPoint() const
{
return mPoint;
}
//FormattedTextBlock ManeuverImpl::GetManeuverText(QBool isMetric) const
//{
// return (isMetric == true) ? mMiManeuverText : mKmManeuverText;
//}
const QString& ManeuverImpl::GetDescription(bool isMetric) const
{
return (isMetric == false) ? mMiDescription : mKmDescription;
}
qreal ManeuverImpl::GetTrafficDelay() const
{
return mTrafficDelay;
}
bool ManeuverImpl::GetStackAdvise() const
{
return mStackAdvise;
}
const QString& ManeuverImpl::GetExitNumber() const
{
return mExitNumber;
}
bool ManeuverImpl::IsDestination() const
{
return mIsDestination;
}
}
| [
"caavula@telecomsys.com"
] | caavula@telecomsys.com |
6a827479ead1c6af5662d69ecaca60b5d78b7793 | 906d0f47cbf0f5b350188aeba6fad0656fb0d702 | /conf.cpp | 2c9ead28ed45dfdf81f9a5583a98878765d529b4 | [] | no_license | marceleng/dns_querier | b9570b9a4f8799bb25c82d37ad067347eb39142e | f89d4619e515f02f2b30bec8c3f1b0f169102d38 | refs/heads/master | 2021-01-12T22:16:23.532745 | 2016-01-25T17:26:29 | 2016-01-25T17:26:29 | 39,489,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | cpp | #include <sstream>
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include "conf.hpp"
void ConfParser::parse_file(std::string filename)
{
std::ifstream infile (filename.c_str());
bool in_domains = false;
std::string line;
std::string key;
std::string value;
while( std::getline(infile, line) ) {
if (line.size() != 0) {
//Remove comments if necessary
int eol = line.find("#");
if (eol != -1) {
line = line.substr(eol,line.size()-eol);
}
std::istringstream is_line(line);
//Handle the DOMAINS array
if (in_domains) {
this->m_domains.push_back(this->handle_array_line(line));
if (line.find("]") != std::string::npos) {
in_domains = false;
}
}
//Else look for the key=value structure
else if( std::getline(is_line, key, '=') ) {
if( std::getline(is_line, value) ) {
if (key.compare("DOMAINS")==0) {
in_domains = true;
this->m_domains.push_back(this->handle_array_line(value));
}
else {
store_line(key, value);
}
}
}
else {
std::cerr << "Non-valid line in conf file: "<<line<<std::endl;
exit(EXIT_FAILURE);
}
}
}
}
std::string ConfParser::handle_array_line(std::string line)
{
int offset = line.find_first_not_of(" \t\f\v\n\r[");
std::string result = line.substr(offset,line.size()-offset);
result = result.substr(0,result.find_last_of(",]"));
return result;
}
void ConfParser::store_line(std::string key, std::string value)
{
std::istringstream temp(value);
if (key.compare("RANDOM_PREFIX_SIZE")==0) {
temp >> (this->m_randomPrefixSize);
}
else if (key.compare("MYSQL_USER")==0) {
this->m_mysqlUser = value;
}
else if (key.compare("MYSQL_PASSWORD")==0) {
this->m_mysqlPass = value;
}
else if (key.compare("MYSQL_DB")==0) {
this->m_mysqlDB = value;
}
else if (key.compare("MYSQL_ADDRESS")==0) {
this->m_mysqlAddr = value;
}
else if (key.compare("MYSQL_PORT")==0) {
temp >> this->m_mysqlPort;
}
else if (key.compare("DOMAINS")==0) {
}
else {
std::cerr << "Unknown field in conf file: " << key << std::endl;
exit(EXIT_FAILURE);
}
}
/*
* GETTERS BLOCK
*/
const std::vector<std::string>& ConfParser::get_domains() const
{
return m_domains;
}
const std::string& ConfParser::get_mysql_addr() const
{
return m_mysqlAddr;
}
const std::string& ConfParser::get_mysql_db() const
{
return m_mysqlDB;
}
const std::string& ConfParser::get_mysql_pass() const
{
return m_mysqlPass;
}
uint32_t ConfParser::get_mysql_port() const
{
return m_mysqlPort;
}
const std::string& ConfParser::get_mysql_user() const
{
return m_mysqlUser;
}
uint32_t ConfParser::get_random_prefix_size() const
{
return m_randomPrefixSize;
}
| [
"marceleng@gmail.com"
] | marceleng@gmail.com |
9382a087da938435dbbc0c03444a755d5c1584b2 | b410dd5dcb7d9e9e078a757bdafe7fd52094438f | /GenPD/GenPD/source/constraint_attachment.cpp | e8e12dc78216aef9e871bb7a984e1ea098a45942 | [] | no_license | pielet/Quasi-Newton-Methods-for-Real-time-Simulation-of-Hyperelastic-Materials | 3a1ef252590887c34f87e900ac083b1ced791e68 | 4bf211305c6bb3a0a547ab9fab8de2fbf402792a | refs/heads/main | 2023-03-21T11:56:26.484010 | 2021-03-12T09:12:33 | 2021-03-12T09:12:33 | 347,000,052 | 1 | 0 | null | 2021-03-12T08:50:14 | 2021-03-12T08:50:14 | null | UTF-8 | C++ | false | false | 7,601 | cpp | // ---------------------------------------------------------------------------------//
// Copyright (c) 2015, Regents of the University of Pennsylvania //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions are met: //
// * Redistributions of source code must retain the above copyright //
// notice, this list of conditions and the following disclaimer. //
// * Redistributions in binary form must reproduce the above copyright //
// notice, this list of conditions and the following disclaimer in the //
// documentation and/or other materials provided with the distribution. //
// * Neither the name of the <organization> nor the //
// names of its contributors may be used to endorse or promote products //
// derived from this software without specific prior written permission. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND //
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY //
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //
// //
// Contact Tiantian Liu (ltt1598@gmail.com) if you have any questions. //
//----------------------------------------------------------------------------------//
#include "constraint.h"
#ifdef ENABLE_MATLAB_DEBUGGING
#include "matlab_debugger.h"
extern MatlabDebugger *g_debugger;
#endif
//----------AttachmentConstraint Class----------//
int AttachmentConstraint::m_hessian_triple_count = 3;
AttachmentConstraint::AttachmentConstraint(unsigned int p0, const EigenVector3& fixedpoint) :
Constraint(CONSTRAINT_TYPE_ATTACHMENT),
m_p0(p0),
m_fixd_point(fixedpoint)
{
}
AttachmentConstraint::AttachmentConstraint(ScalarType stiffness, unsigned int p0, const EigenVector3& fixedpoint) :
Constraint(CONSTRAINT_TYPE_ATTACHMENT, stiffness),
m_p0(p0),
m_fixd_point(fixedpoint)
{
}
AttachmentConstraint::AttachmentConstraint(const AttachmentConstraint& other) :
Constraint(other),
m_p0(other.m_p0),
m_fixd_point(other.m_fixd_point)
{
}
AttachmentConstraint::~AttachmentConstraint()
{
}
// 0.5*k*(current_length)^2
ScalarType AttachmentConstraint::EvaluateEnergy(const VectorX& x)
{
ScalarType e_i = 0.5*(m_stiffness)*(x.block_vector(m_p0) - m_fixd_point).squaredNorm();
m_energy = e_i;
return e_i;
}
ScalarType AttachmentConstraint::GetEnergy()
{
return m_energy;
}
// attachment spring gradient: k*(current_length)*current_direction
void AttachmentConstraint::EvaluateGradient(const VectorX& x, VectorX& gradient)
{
EigenVector3 g_i = (m_stiffness)*(x.block_vector(m_p0) - m_fixd_point);
gradient.block_vector(m_p0) += g_i;
}
void AttachmentConstraint::EvaluateGradient(const VectorX& x)
{
m_g = (m_stiffness)*(x.block_vector(m_p0) - m_fixd_point);
}
void AttachmentConstraint::GetGradient(VectorX& gradient)
{
gradient.block_vector(m_p0) += m_g;
}
ScalarType AttachmentConstraint::EvaluateEnergyAndGradient(const VectorX& x, VectorX& gradient)
{
EvaluateEnergyAndGradient(x);
gradient.block_vector(m_p0) += m_g;
return m_energy;
}
ScalarType AttachmentConstraint::EvaluateEnergyAndGradient(const VectorX& x)
{
// energy
m_energy = 0.5*(m_stiffness)*(x.block_vector(m_p0) - m_fixd_point).squaredNorm();
// gradient
m_g = (m_stiffness)*(x.block_vector(m_p0) - m_fixd_point);
return m_energy;
}
ScalarType AttachmentConstraint::GetEnergyAndGradient(VectorX& gradient)
{
gradient.block_vector(m_p0) += m_g;
return m_energy;
}
void AttachmentConstraint::EvaluateHessian(const VectorX& x, bool definiteness_fix /* = false */ /* = 1 */)
{
ScalarType ks = m_stiffness;
EigenVector3 H_d;
for (unsigned int i = 0; i != 3; i++)
{
H_d(i) = ks;
}
m_H = H_d.asDiagonal();
}
void AttachmentConstraint::EvaluateHessian(const VectorX& x, std::vector<SparseMatrixTriplet>& hessian_triplets, bool definiteness_fix)
{
EvaluateHessian(x, definiteness_fix);
for (unsigned int i = 0; i != 3; i++)
{
hessian_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + i, 3 * m_p0 + i, m_H(i, i)));
}
}
void AttachmentConstraint::GetHessian(std::vector<SparseMatrixTriplet>& hessian_triplets)
{
for (unsigned int i = 0; i != 3; i++)
{
hessian_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + i, 3 * m_p0 + i, m_H(i, i)));
}
}
void AttachmentConstraint::ApplyHessian(const VectorX& x, VectorX& b)
{
b.block_vector(m_p0) += m_H * x.block_vector(m_p0);
}
void AttachmentConstraint::EvaluateWeightedLaplacian(std::vector<SparseMatrixTriplet>& laplacian_triplets)
{
ScalarType ks = m_stiffness;
laplacian_triplets.push_back(SparseMatrixTriplet(3 * m_p0, 3 * m_p0, ks));
laplacian_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + 1, 3 * m_p0 + 1, ks));
laplacian_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + 2, 3 * m_p0 + 2, ks));
}
void AttachmentConstraint::EvaluateWeightedDiagonal(std::vector<SparseMatrixTriplet>& diagonal_triplets)
{
ScalarType ks = m_stiffness;
diagonal_triplets.push_back(SparseMatrixTriplet(3 * m_p0, 3 * m_p0, ks));
diagonal_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + 1, 3 * m_p0 + 1, ks));
diagonal_triplets.push_back(SparseMatrixTriplet(3 * m_p0 + 2, 3 * m_p0 + 2, ks));
}
void AttachmentConstraint::EvaluateWeightedLaplacian1D(std::vector<SparseMatrixTriplet>& laplacian_1d_triplets)
{
ScalarType ks = m_stiffness;
laplacian_1d_triplets.push_back(SparseMatrixTriplet(m_p0, m_p0, ks));
}
// IO
void AttachmentConstraint::WriteToFileOBJ(std::ofstream& outfile, int& existing_vertices)
{
// assume outfile is correctly open.
std::vector<glm::vec3>& vertices = m_attachment_constraint_body.GetPositions();
std::vector<unsigned short>& triangles = m_attachment_constraint_body.GetTriangulation();
glm::vec3 move_to = Eigen2GLM(m_fixd_point);
glm::vec3 v;
for (unsigned int i = 0; i < vertices.size(); i++)
{
v = vertices[i] + move_to;
// save positions
outfile << "v " << v[0] << " " << v[1] << " " << v[2] << std::endl;
}
outfile << std::endl;
for (unsigned int f = 0; f < triangles.size(); f += 3)
{
outfile << "f " << triangles[f + 0] + 1 + existing_vertices << " " << triangles[f + 1] + 1 + existing_vertices << " " << triangles[f + 2] + 1 + existing_vertices << std::endl;
}
outfile << std::endl;
existing_vertices += vertices.size();
}
void AttachmentConstraint::WriteToFileOBJHead(std::ofstream& outfile)
{
EigenVector3& v = m_fixd_point;
outfile << "// " << m_p0 << " " << v[0] << " " << v[1] << " " << v[2] << std::endl;
} | [
"jsy0325@foxmail.com"
] | jsy0325@foxmail.com |
f7dc408273e21a0d26df437351d8c892d50bdb14 | 09a323bd085f4b46c01aa9342159e50753adc977 | /experiment/consistent_hashing/stdafx.h | b9140c53ee0b1e78b0895fd1831f1f64215e767b | [
"BSD-3-Clause"
] | permissive | DavidSunny86/lugce | e1e441fec883371e41664124e62021761db1f73c | 24800092fa83458485c9ad6760f5490156385f78 | refs/heads/master | 2023-03-19T11:03:09.050544 | 2016-10-26T03:15:40 | 2016-10-26T03:15:40 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 358 | h | // stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#ifdef _WIN32
# include "targetver.h"
#endif
#include <map>
#include <string>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/functional/hash.hpp>
| [
"jadedrip@gmail.com"
] | jadedrip@gmail.com |
eb17ab0e5161fd519c7e023a0a1e75c0b53435d5 | 954648bb6ef5a836139a58d584239e41d7f39639 | /CacheAllocator.h | e4d399d5970b6f5ff991a41dbb37d384f5ac011a | [] | no_license | stanislav81/CachingAllocator | 23d2c604291fbbf36e537f66c5e44e3a84718227 | e3f72e5d887f30a11952badb51624ee250966cf5 | refs/heads/master | 2021-01-22T05:06:20.433718 | 2011-12-03T20:53:40 | 2011-12-03T20:53:40 | 2,809,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,537 | h | /*
* CacheAllocator.h
*
* Created on: 11.11.2011
* Author: stan
*/
#ifndef CACHEALLOCATOR_H_
#define CACHEALLOCATOR_H_
#include <map>
#include <list>
#include <iostream>
#include "FreeListNodeHashTable.h"
#include "HashTable.h"
using namespace std;
namespace cache_allocator {
class CacheAllocator {
std::map<size_t, FreeListNode*> tree;
std::map<size_t, FreeListNode*>::iterator it;
size_t m_hashTableSize;
HashTable *m_hashTable;
public:
CacheAllocator();
virtual ~CacheAllocator();
template <class T>
T *getBlock() {
size_t blockSize = sizeof (T);
FreeListNode *node;
char *array;
if (blockSize < m_hashTableSize )
{
node = m_hashTable->getNode(blockSize);
array = static_cast<char*>(node->getBlock());
}
else
{
it = tree.find(blockSize);
if (it == tree.end()) {
node = new FreeListNode(blockSize);
array = static_cast<char*>(node->getBlock());
tree[blockSize] = node;
} else {
array = static_cast<char*>((*it).second->getBlock());
}
}
new(array) T();
return (T*)(array);
}
template <class T>
T *getBlock(size_t number) {
size_t blockSize = sizeof (T) * number;
FreeListNode *node;
char *array;
if (blockSize < m_hashTableSize )
{
node = m_hashTable->getNode(blockSize);
array = static_cast<char*>(node->getBlock());
}
else
{
it = tree.find(blockSize);
if (it == tree.end()) {
node = new FreeListNode(blockSize);
array = static_cast<char*>(node->getBlock());
tree[blockSize] = node;
} else {
array = static_cast<char*>((*it).second->getBlock());
}
}
return (T*)(array);
}
template <class T>
void freeBlock(T *ptr) {
ChunkHeader *block = (ChunkHeader *)((char *)ptr - sizeof(ChunkHeader));
size_t chunkSize = sizeof (T);
size_t blockSize = block->size;
if (chunkSize == blockSize) {
ptr->~T();
} else {
for (size_t i = 0; i < blockSize/chunkSize; i++) {
T* chunk = (T*)((char *)ptr + chunkSize*i);
chunk->~T();
}
}
if (blockSize < m_hashTableSize)
{
FreeListNode *node = m_hashTable->getNode(blockSize);
node->freeBlock(ptr);
}
else
{
it = tree.find(blockSize);
if (it == tree.end()) {
cerr << "error: This block does not belong to the CacheAllocator" << endl;
} else {
(*it).second->freeBlock((void *)ptr);
}
}
}
void freeBlock(char *ptr) { freeSimpleType(ptr); }
void freeBlock(bool *ptr) { freeSimpleType(ptr); }
void freeBlock(int *ptr) { freeSimpleType(ptr); }
void freeBlock(size_t *ptr) { freeSimpleType(ptr); }
void freeBlock(long int *ptr) { freeSimpleType(ptr); }
void freeBlock(long long int *ptr) { freeSimpleType(ptr); }
void freeBlock(short *ptr) { freeSimpleType(ptr); }
void freeBlock(float *ptr) { freeSimpleType(ptr); }
void freeBlock(double *ptr) { freeSimpleType(ptr); }
void freeBlock(long double *ptr) { freeSimpleType(ptr); }
template<class T>
void prepareFreeList(size_t size) {
T** ptrArray = new T*[size];
for (size_t i = 0; i < size; i++) {
T *ptr = getBlock<T>();
ptrArray[i] = ptr;
}
for (size_t i = 0; i < size; i++) {
freeBlock(ptrArray[i]);
}
delete ptrArray;
}
void prepareFreeList(size_t number, size_t size) {
char** ptrArray = new char*[number];
for (size_t i = 0; i < size; i++) {
ptrArray[i] = getBlock<char>(size);
}
for (size_t i = 0; i < size; i++) {
freeBlock(ptrArray[i]);
}
delete ptrArray;
}
void collect() {
// TO DO !!!
// collect needed giant block from map tree
for (std::map<size_t, FreeListNode*>::iterator it = tree.begin(); it != tree.end(); ++it) {
//
}
// collect small block from hash table
FreeListNodeHashTable *headHashTable = m_hashTable->getHeadHashTable();
if (headHashTable) {
FreeListNodeHashTable *curr;
for (curr = headHashTable; curr != NULL; curr = curr->right) {
//
}
for (curr = headHashTable; curr != NULL; curr = curr->left) {
//
}
}
}
private:
inline void freeSimpleType(void * ptr) {
ChunkHeader *block = (ChunkHeader *)((char *)ptr - sizeof(ChunkHeader));
size_t blockSize = block->size;
if (blockSize < m_hashTableSize)
{
FreeListNode *node = m_hashTable->getNode(blockSize);
node->freeBlock(ptr);
}
else
{
it = tree.find(blockSize);
if (it == tree.end()) {
cerr << "error: This block does not belong to the CacheAllocator" << endl;
} else {
(*it).second->freeBlock((void *)ptr);
}
}
}
};
} /* namespace cache_allocator */
#endif /* CACHEALLOCATOR_H_ */
| [
"s.suhoparov@gmail.com"
] | s.suhoparov@gmail.com |
8ba9e0dc4fc1208902a6098b8e07247f97dfedac | 752138ec20c339a9f62be17f29a7c75a744c56aa | /old/3drender.h | c9eff8f6facfbd75e1ef304f512d8f55737d0522 | [] | no_license | refaim/3d-parser | 742b0444cec204df11685ed0cb029464a6f1932a | 57722e5f68ed7ef719578816ef32c33c19d27bf4 | refs/heads/master | 2021-01-01T19:56:25.341885 | 2011-05-17T21:47:18 | 2011-05-17T21:47:18 | 1,525,219 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,681 | h | // [12/23/2009 SERGEY] - revision
#pragma once
#include <vector>
#include <string>
#include "3dmatrix.h"
#include "3dvector.h"
//////////////////////////////////////////////////////////////////////////
#define DRAW_MATERIAL_BIT (1<<0)
#define DRAW_FACES_BIT (1<<1)
#define DRAW_NORMALS_BIT (1<<2)
#define DRAW_WIREFRAME_BIT (1<<3)
#define DRAW_TEXTURE_DIFFUSE_1_BIT (1<<4)
#define DRAW_TEXTURE_REFLECTION_BIT (1<<5)
#define DRAW_ENABLE_LIGHT (1<<6)
#define DRAW_DEFAULT_BITS (DRAW_MATERIAL_BIT|DRAW_FACES_BIT|DRAW_TEXTURE_DIFFUSE_1_BIT|DRAW_TEXTURE_REFLECTION_BIT|DRAW_ENABLE_LIGHT)
struct fcolors
{
float r; /* RGB Color components */
float g;
float b;
float a;
};
struct bitmaps
{
bool is_loaded;
std::string name; /* Bitmap file name */
}; /* Bit map definition */
struct mapsets
{
bitmaps map; /* The map settings */
};
struct S3DMaterial
{
std::string name; /* Name */
fcolors ambient; /* Ambient light color */
fcolors diffuse; /* Diffuse light color */
fcolors specular; /* Specular light color */
fcolors emission; /* Specular light color */
float shininess; /* Shininess factor */
float shinstrength; /* Shininess strength */
float selfillumpct; /* Self illumination percentage */
mapsets texture; /* Texture map settings */
mapsets reflect; /* Reflection map settings */
};
struct textverts
{
float u, v;
};
struct SFace
{
unsigned short int V1, V2, V3;
};
struct SSingleMesh
{
std::string matname; /*имя материала для этой меши*/
int MatIndex; /*локальный номер материала этой меши*/
std::vector<SFace> facearray; /*Список фейсов этой меши*/
};
struct S3DLocalCS
{
C3DMatrixF H_to_zero, H_from_zero, H;
C3DVectorF pivot;
};
struct S3DObject
{
std::string name; /* Object name */
std::string parent_name;
int parent_index;
std::vector<C3DVectorF> vertexarray; /* List of vertices */
std::vector<C3DVectorF> normalarray; /* List of vertices */
std::vector<textverts> textarray;
S3DLocalCS localCS;
std::vector<SSingleMesh> meshes; /* List of faces */
};
typedef std::vector<S3DMaterial> VMaterials;
typedef std::vector<S3DObject> VObjects;
struct SObjTree
{
int obj_index;
std::vector<SObjTree> children;
};
class C3DRender
{
public:
std::string name;
VMaterials m_materials;
VObjects m_objects;
SObjTree m_tree;
float MyDRAW_NORMALS_MUL;
bool is_protected;
public:
C3DRender ();
~C3DRender ();
public:
// не const
void Clear ();
void CalcNormals ();
void SetNormalsLen (float len) {MyDRAW_NORMALS_MUL = len;}
C3DMatrixF & GetObjectMatrix(int i);
C3DMatrixF & GetObjectMatrix(const char * cpcName);
void Protect () {is_protected = true;}
void UnProtect () {is_protected = false;}
void LoadTextures ();
// const
int GetObjectIndex (const char * cpcName) const;
int GetMaterialIndex (const char * cpcName) const;
bool IsEmpty () const;
float FindMaxScale () const;
void Draw (unsigned long type = DRAW_DEFAULT_BITS);
protected:
// не const
void FreeTextures ();
// const
void SetMaterial (unsigned long num, unsigned long type) const;
void BeginDraw (unsigned long type) const;
void DrawTree (unsigned long type, const SObjTree & tree) const;
void DrawObj (unsigned long type, int obj_index) const;
void EndDraw () const;
};
| [
"refaim.vl@gmail.com"
] | refaim.vl@gmail.com |
33cd64ed0563ae0a13b685988649fc7e08fe603b | 4476dbf7444e35f6a38261abdc6c17693299a6c6 | /src/node/SpriteNode.h | f3f1e9f07759c85d46eda8fa2a34c23e05b36eeb | [] | no_license | TimeSeriesTv/FastAnim | 75ee47b69d781b123409c4e3e1c10e9ee8a886a6 | 3056cdb3d43b46f2cc1dadb42893c1e3e848fe33 | refs/heads/master | 2020-12-04T08:47:16.776211 | 2016-10-15T13:32:05 | 2016-10-15T13:32:05 | 65,990,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,247 | h | //
// Created by Michał Łaszczewski on 27/07/16.
//
#ifndef FASTANIM_SPRITENODE_H
#define FASTANIM_SPRITENODE_H
#include <fastgfx.h>
#include <memory>
#include "Node.h"
#include "../value/Value.h"
namespace fanim {
class SpriteNode : public Node {
public:
std::shared_ptr<fgfx::SpriteLayer> layer;
std::shared_ptr<fgfx::Sprite> sprite;
std::shared_ptr<Value<glm::vec4>> color;
SpriteNode(
const std::shared_ptr<fgfx::SpriteLayer>& layerp,
const std::shared_ptr<fgfx::Sprite>& spritep,
const std::shared_ptr<Value<glm::vec4>>& colorp
) : layer(layerp), sprite(spritep), color(colorp) {}
virtual ~SpriteNode() override {}
virtual void render() override {
/*const float *values = (const float*)(&computedMatrix);
fgfx_log("COMPUTED SPACE MATRIX: %d -> %d\n%f %f %f %f\n%f %f %f %f\n%f %f %f %f\n%f %f %f %f\n",this,values,
values[0],values[1],values[2],values[3],values[4],values[5],values[6],values[7],
values[8],values[9],values[10],values[11],values[12],values[13],values[14],values[15]);*/
layer->bufferSprite(sprite, computedMatrix, color->get());
Node::render();
}
};
}
#endif //FASTANIM_SPRITENODE_H
| [
"michal@cloudforge.pl"
] | michal@cloudforge.pl |
23b20fbbbe7b2edf3532b5494586c9a28375af1a | cd1b2715278a6cc24de49f7bb3651594b8cdeaff | /Calculator/Complex.cpp | 33876f8481619a215e6303d4bd9bd455713378b3 | [] | no_license | HUAZAI66/friendly-funicular | fd645d8481b0ad8e5950d06f7d9cdd11980ccae2 | d0afaba4378d2a0dadd80a0481b2493c064672db | refs/heads/master | 2022-12-22T10:08:18.151016 | 2020-09-23T07:51:07 | 2020-09-23T07:51:07 | 297,894,739 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,110 | cpp | //有关复数运算
#include"Complex.h"
#include<qmath.h>
//有关复数运算
Complex& Complex:: operator = (Complex c)
{
this->Real=c.Real;
this->Imag=c.Imag;
return *this;
}
Complex operator + ( const Complex & c1, const Complex & c2 )
{
double r = c1.Real + c2.Real ;
double i = c1.Imag+c2.Imag ;
return Complex ( r, i ) ;
}
Complex operator - ( const Complex & c1, const Complex & c2 )
{
double r = c1.Real - c2.Real ;
double i = c1.Imag - c2.Imag ;
return Complex ( r, i ) ;
}
Complex operator* ( const Complex & c1, const Complex & c2 )
{
double r=c1.Real*c2.Real-c1.Imag*c2.Imag;
double i=c1.Real*c2.Imag+c1.Imag*c2.Real;
return Complex(r,i);
}
Complex operator/ ( const Complex & c1, const Complex & c2 )
{
double r=(c1.Real*c2.Real+c1.Imag*c2.Imag)/(c2.Real*c2.Real+c2.Imag*c2.Imag);
double i= (c1.Imag*c2.Real-c1.Real*c2.Imag)/(c2.Real*c2.Real+c2.Imag*c2.Imag);
return Complex(r,i);
}
void Complex::operator +=(const Complex &c)
{
this->Real+=c.Real;
this->Imag+=c.Imag;
return ;
}
void Complex::operator -=(const Complex &c)
{
this->Real-=c.Real;
this->Imag-=c.Imag;
return ;
}
void Complex::operator *=(const Complex &c)
{
*this=(*this)*c;
return;
}
void Complex::operator /=(const Complex &c)
{
*this=(*this)/c;
return;
}
bool Complex::isZero()
{
return (qAbs(Real)<=DBL_EPS&&qAbs(Imag)<=DBL_EPS);
}
void Complex::cAbs()
{
this->Real=qSqrt(Real*Real+Imag*Imag);
this->Imag=0;
return;
}
double Complex::cfabs()
{
return qSqrt(Real*Real+Imag*Imag);
}
void Complex::conj()
{
Imag=-Imag;
return ;
}
void Complex::cPow(Complex Index, bool isDeg)
{
double eps=1e-25;
double angle;
if(isDeg&&qAbs(this->getReal()-$e)<=DBL_EPS)
Index=Index*($pi/180);
if(fabs(Real)>eps)
angle=atan(Imag/Real);
else
angle=(Imag>0)?$pi/2:-$pi/2;
if(Real<0&&Imag>=0)
angle+=$pi;
if(Real<0&&Imag<0)
angle-=$pi;
double mo=log(sqrt(Real*Real+Imag*Imag)/exp(Index.Imag*angle));
double mod=exp(mo*Index.Real-angle*Index.Imag);
angle=angle*Index.Real+Index.Imag*mo;
if(angle<0)
while(angle<=-$pi)
angle+=2*$pi;
else
while(angle>$pi)
angle-=2*$pi;
Real=mod*cos(angle);
Imag=mod*sin(angle);
return ;
}
double Complex::getReal()
{
return Real;
}
double Complex::getImag()
{
return Imag;
}
QString Complex::toExponential(bool isDeg,int precision)
{
QString result;
double r=qSqrt(Real*Real+Imag*Imag);
if(qAbs(r)<=DBL_EPS)
{
bool isNegative=false;
if(Imag<0)
Imag=-Imag,isNegative=true;
result.setNum(Imag,'g',precision);
result+="$e^(";
if(isNegative)
result+='-';
if(isDeg)
result+="90i)";
else
result+="i*$pi/2)";
return result;
}
if(qAbs(Imag)<=DBL_EPS)
{
bool isNegative=false;
if(Real<0)
Real=-Real,isNegative=true;
result.setNum(Real,'g',precision);
if(isNegative)
{
if(isDeg)
result+="$e^(180i)";
else
result+="$e^(i*$pi)";
}
else
{
result+="$e^0";
}
return result;
}
double angle=atan(Imag/Real);
result.setNum(r,'g',precision);
if(qAbs(angle)<=DBL_EPS)
result+=QString("$e^0");
else if(isDeg)
{
angle=angle*180/$pi;
if(Imag>0&&Real<0)
angle+=180;
if(Imag<0&&Real<0)
angle-=180;
result+=QString("$e^(%1*i)").arg(angle);
}
else
{
angle/=$pi;
if(Imag>0&&Real<0)
angle+=$pi;
if(Imag<0&&Real<0)
angle-=$pi;
result+=QString("$e^(%1i*$pi)").arg(angle);
}
return result;
}
QString Complex::toString(int precision,double eps)
{
QString result;
if(qAbs(Real)<=eps)
{
if(qAbs(Imag)<=eps)
result = "0";
else if(Imag<0)
{
result="- ";
if(qAbs(Imag+1)>=eps)
result+=QString().setNum(-Imag,'g',precision);
result+='i';
}
else
{
if(qAbs(Imag-1)>=eps)
result.setNum(Imag,'g',precision);
result+='i';
}
}
else if(qAbs(Imag)<=eps)
{
result.setNum(Real,'g',precision);
}
else
{
if(Imag<0)
{
result.setNum(Real,'g',precision);
result+=" - ";
if(qAbs(Imag+1)>=eps)
result+=QString().setNum(-Imag,'g',precision);
result+='i';
}
else
{
result.setNum(Real,'g',precision);
result+=" + ";
if(qAbs(Imag-1)>=eps)
result+=QString().setNum(Imag,'g',precision);
result+='i';
}
}
return result;
}
void Complex::setComplex(QString str)
{
double real,imag;
if(str=="0"){
*this = 0;
return ;
}
if(!str.contains('i'))
{
real=str.toDouble();
imag=0;
}
else if(!str.contains(' '))
{
QString lef=str.left(str.length()-1);
if(lef=="-")
imag=-1;
else if(lef=="")
imag=1;
else
imag=lef.toDouble();
real=0;
}
else
{
int index=str.indexOf(' ');
real=str.left(index).toDouble();
str.remove(0,index);
str.remove(' ');
if(str[0]=='+')
str.remove('+');
QString lef=str.left(str.length()-1);
if(lef=="-")
imag=-1;
else if(lef=="")
imag=1;
else
imag=lef.toDouble();
}
*this = Complex(real,imag);
}
| [
"liujiju@com"
] | liujiju@com |
8acab5d3047609228d13390943860af6dab1f98c | d8515ec157f539cdd25d3422d119c26fcc36a498 | /My Code/chapter04/exercises/220.cpp | cffea89fad367567c4a0620bd0379d0e489a2556 | [] | no_license | huangbin5/Rujia_Liu | f361240e7ebbc21dde21add11d743aa62a1b1854 | 907bdd92b7a6872501b4420f6f8c9f03440ee26c | refs/heads/master | 2023-03-26T18:40:28.376455 | 2021-03-26T15:49:37 | 2021-03-26T15:49:37 | 351,832,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,107 | cpp | #include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
// #define DEBUG
struct position {
int x;
int y;
};
int N, wCount, bCount;
char board[9][9], current, command;
position rc, direction[8] = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 } };
vector<position> cadidates;
bool checkOne(int x, int y, bool& flag, bool& first) {
if (first && (board[x][y] == '-' || board[x][y] == current)) {
flag = false;
return true;
}
first = false;
if (board[x][y] == '-') {
flag = false;
return true;
}
if (board[x][y] == current)
return true;
return false;
}
void setBoard(int x, int y, int xx, int yy) {
int xStep = x == xx ? 0 : (x > xx ? -1 : 1);
int yStep = y == yy ? 0 : (y > yy ? -1 : 1);
for (int i = x + xStep, j = y + yStep; i != xx || j != yy; i += xStep, j += yStep)
board[i][j] = current;
int count = max(abs(x - xx) - 1, abs(y - yy) - 1);
if (current == 'W') {
wCount += count;
bCount -= count;
} else {
wCount -= count;
bCount += count;
}
}
bool check(int x, int y, bool change) {
bool flag, first;
for (int idx = 0; idx < 8; ++idx) {
flag = true, first = true;
int xx = direction[idx].x, yy = direction[idx].y;
for (int i = x + xx, j = y + yy; i > 0 && i < 9 && j > 0 && j < 9; i += xx, j += yy)
if (checkOne(i, j, flag, first))
if (flag)
if (change) {
setBoard(x, y, i, j);
break;
} else
return true;
else
break;
}
return false;
}
void getCadidates() {
cadidates.clear();
for (int i = 1; i < 9; ++i)
for (int j = 1; j < 9; ++j)
if (board[i][j] == '-' && check(i, j, false))
cadidates.push_back({ i, j });
}
void printCadidates() {
if (cadidates.empty())
printf("No legal move.");
else {
for (vector<position>::iterator it = cadidates.begin(); it != cadidates.end(); ++it) {
if (it != cadidates.begin())
printf(" ");
printf("(%d,%d)", it->x, it->y);
}
}
puts("");
}
void exchangeCurrent() { current = current == 'W' ? 'B' : 'W'; }
void putDown() {
check(rc.x, rc.y, true);
board[rc.x][rc.y] = current;
if (current == 'W')
++wCount;
else
++bCount;
printf("Black - %d White - %d\n", bCount, wCount);
exchangeCurrent();
}
void printBoard() {
for (int i = 1; i < 9; ++i) {
for (int j = 1; j < 9; ++j)
putchar(board[i][j]);
puts("");
}
}
int main() {
#ifdef DEBUG
freopen("d:\\input.txt", "r", stdin);
freopen("d:\\output.txt", "w", stdout);
#endif
scanf("%d", &N);
bool first = true;
while (N--) {
if (!first)
puts("");
wCount = 0, bCount = 0;
for (int i = 1; i < 9; ++i) {
getchar();
for (int j = 1; j < 9; ++j) {
board[i][j] = getchar();
if (board[i][j] == 'W')
++wCount;
if (board[i][j] == 'B')
++bCount;
}
}
getchar();
current = getchar();
while (getchar()) {
command = getchar();
switch (command) {
case 'L':
getCadidates();
printCadidates();
break;
case 'M':
rc.x = getchar() - '0';
rc.y = getchar() - '0';
getCadidates();
if (cadidates.empty())
exchangeCurrent();
putDown();
break;
case 'Q':
printBoard();
break;
default:
break;
}
if (command == 'Q')
break;
}
first = false;
}
return 0;
} | [
"2270144830@qq.com"
] | 2270144830@qq.com |
8eff4980234f813181255fc30abe6559389bec1b | 390bab42fb4a9589ff54a9eff7c96d1c250037de | /sw/iss/cpu/FixedPoint.cc | 45e61ea81bc80a97d23ca7223a4d862b0da5e347 | [] | no_license | hmellifera/aemb | 759b3e97c77c9cfe2d984ff87b2d4dca8bc48b54 | 2a12703f0e92de81b1319fda8f898c7618d6b500 | refs/heads/master | 2020-04-07T07:35:11.038050 | 2012-02-08T16:19:41 | 2012-02-08T16:19:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | cc | /*!
AEMB INSTRUCTION SET SIMULATOR
Copyright (C) 2009 Shawn Tan <shawn.tan@aeste.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
#include "FixedPoint.hh"
#include "FetchUnit.hh"
namespace aemb {
FixedPoint::FixedPoint()
{
}
FixedPoint::~FixedPoint()
{
}
} | [
"shawn.tan@aeste.my"
] | shawn.tan@aeste.my |
06f6e0367056c38cebf7474ee1267c89cc649e06 | e4b78be5038c92d22cc9917af4642e1686e72a16 | /register/AtlasRegistrationMethod.h | d4ab71a0428939cd798da79bcb423e8b73b36d52 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | NIRALUser/neoseg | f4003a00d781ca68907440109b78940e5928bb2b | 040cb52cd4d360f6207efc3b79791211616b2a9b | refs/heads/master | 2021-06-04T15:58:03.429941 | 2019-03-02T01:00:31 | 2019-03-02T01:00:31 | 24,958,406 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,145 | h |
////////////////////////////////////////////////////////////////////////////////
//
// Registration of a dataset to an atlas using affine transformation and
// MI image match metric
//
// Only for 3D!
//
// Given a list of filenames for atlas template and probabilities along with
// the dataset, this class generate images that are in the space of the first
// image (all data and probability images).
//
////////////////////////////////////////////////////////////////////////////////
// prastawa@cs.unc.edu 10/2003
#ifndef _AtlasRegistrationMethod_h
#define _AtlasRegistrationMethod_h
#include "itkAffineTransform.h"
#include "itkArray.h"
#include "itkImage.h"
#include "itkObject.h"
#include "DynArray.h"
#include "ChainedAffineTransform3D.h"
#include "PairRegistrationMethod.h"
#include <string>
template <class TOutputPixel, class TProbabilityPixel>
class AtlasRegistrationMethod : public itk::Object
{
public:
/** Standard class typedefs. */
typedef AtlasRegistrationMethod Self;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
// Image types
typedef itk::Image<TOutputPixel, 3> OutputImageType;
typedef typename OutputImageType::Pointer OutputImagePointer;
typedef typename OutputImageType::IndexType OutputImageIndexType;
typedef typename OutputImageType::OffsetType OutputImageOffsetType;
typedef typename OutputImageType::PixelType OutputImagePixelType;
typedef typename OutputImageType::SizeType OutputImageSizeType;
typedef typename OutputImageType::RegionType OutputImageRegionType;
typedef itk::Image<TProbabilityPixel, 3> ProbabilityImageType;
typedef typename ProbabilityImageType::Pointer ProbabilityImagePointer;
typedef typename ProbabilityImageType::IndexType ProbabilityImageIndexType;
typedef typename ProbabilityImageType::OffsetType ProbabilityImageOffsetType;
typedef typename ProbabilityImageType::PixelType ProbabilityImagePixelType;
typedef typename ProbabilityImageType::SizeType ProbabilityImageSizeType;
typedef typename ProbabilityImageType::RegionType ProbabilityImageRegionType;
typedef itk::Image<float, 3> InternalImageType;
typedef typename InternalImageType::Pointer InternalImagePointer;
typedef typename InternalImageType::IndexType InternalImageIndexType;
typedef typename InternalImageType::OffsetType InternalImageOffsetType;
typedef typename InternalImageType::PixelType InternalImagePixelType;
typedef typename InternalImageType::RegionType InternalImageRegionType;
typedef typename InternalImageType::SizeType InternalImageSizeType;
typedef itk::Image<unsigned char, 3> ByteImageType;
typedef typename ByteImageType::Pointer ByteImagePointer;
typedef typename ByteImageType::IndexType ByteImageIndexType;
typedef typename ByteImageType::OffsetType ByteImageOffsetType;
typedef typename ByteImageType::PixelType ByteImagePixelType;
typedef typename ByteImageType::RegionType ByteImageRegionType;
typedef typename ByteImageType::SizeType ByteImageSizeType;
typedef DynArray<ProbabilityImagePointer> ProbabilityImageList;
typedef DynArray<OutputImagePointer> OutputImageList;
typedef ChainedAffineTransform3D AffineTransformType;
typedef typename AffineTransformType::Pointer AffineTransformPointer;
typedef PairRegistrationMethod<float>::BSplineTransformType
BSplineTransformType;
typedef typename BSplineTransformType::Pointer BSplineTransformPointer;
typedef DynArray<std::string> StringList;
typedef itk::Array<unsigned char> FlagArrayType;
void WriteParameters();
void ReadParameters();
void SetSuffix(std::string suffix);
itkGetMacro(OutputDirectory, std::string);
itkSetMacro(OutputDirectory, std::string);
void SetTemplateFileName(std::string filename);
void SetProbabilityFileNames(StringList filenames);
void SetImageFileNames(StringList filenames);
void SetAtlasOrientation(std::string orient);
void SetImageOrientations(StringList orientations);
ProbabilityImageList GetProbabilities();
OutputImageList GetImages();
OutputImagePointer GetTemplate();
void RegisterImages();
void ResampleImages();
AffineTransformPointer GetTemplateAffineTransform()
{ return m_TemplateAffineTransform; }
BSplineTransformPointer GetTemplateBSplineTransform()
{ return m_TemplateBSplineTransform; }
DynArray<AffineTransformPointer> GetAffineTransforms()
{ return m_AffineTransforms; }
itkGetMacro(UseNonLinearInterpolation, bool);
itkSetMacro(UseNonLinearInterpolation, bool);
itkGetMacro(WarpAtlas, bool);
itkSetMacro(WarpAtlas, bool);
itkGetMacro(OutsideFOVCode, float);
itkSetMacro(OutsideFOVCode, float);
inline ByteImagePointer GetFOVMask() { return m_FOVMask; }
void SetWarpGridSize(unsigned int nx, unsigned int ny, unsigned int nz);
void Update();
protected:
AtlasRegistrationMethod();
~AtlasRegistrationMethod();
void VerifyInitialization();
void DoBSplineWarp();
OutputImagePointer CopyOutputImage(InternalImagePointer img);
ProbabilityImagePointer CopyProbabilityImage(InternalImagePointer img);
private:
std::string m_Suffix;
std::string m_OutputDirectory;
std::string m_TemplateFileName;
StringList m_ProbabilityFileNames;
StringList m_ImageFileNames;
std::string m_AtlasOrientation;
StringList m_ImageOrientations;
AffineTransformPointer m_TemplateAffineTransform;
DynArray<AffineTransformPointer> m_AffineTransforms;
DynArray<ProbabilityImagePointer> m_Probabilities;
DynArray<OutputImagePointer> m_Images;
OutputImagePointer m_Template;
bool m_UseNonLinearInterpolation;
FlagArrayType m_AffineTransformReadFlags;
bool m_DoneRegistration;
bool m_DoneResample;
float m_OutsideFOVCode;
ByteImagePointer m_FOVMask;
bool m_WarpAtlas;
unsigned int m_WarpGridX;
unsigned int m_WarpGridY;
unsigned int m_WarpGridZ;
BSplineTransformPointer m_TemplateBSplineTransform;
bool m_TemplateBSplineReadFlag;
bool m_Modified;
};
#ifndef MU_MANUAL_INSTANTIATION
#include "AtlasRegistrationMethod.txx"
#endif
#endif
| [
"fbudin@unc.edu"
] | fbudin@unc.edu |
eac7070744f28bed431b1415cff25c095b6401f9 | 4fd16e4fd56357918d3e1a99400663e576f6b170 | /src/models/Coordinate.cpp | ed626c7904a87c31176cc9321f29b3e50eb97506 | [] | no_license | vitorsm/lunarlander | d15ac55faa58e3690579924d91a9c5b859aa4282 | 3c6352468fbfc93eb678e6125696bc34d2e66efd | refs/heads/master | 2020-03-08T00:42:41.092634 | 2018-04-17T02:23:29 | 2018-04-17T02:23:29 | 127,812,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | /*
* Coordinate.cpp
*
* Created on: 2 de abr de 2018
* Author: vitor
*/
#include "Coordinate.h"
Coordinate::Coordinate(float x, float y) {
// TODO Auto-generated constructor stub
this->x = x;
this->y = y;
}
Coordinate::~Coordinate() {
// TODO Auto-generated destructor stub
}
float Coordinate::getX() {
return this->x;
}
float Coordinate::getY() {
return this->y;
}
void Coordinate::print() {
cout << "(" << this->x << ", " << this->y << ")";
}
void Coordinate::updateBySpeed(float *speed, long time, bool powerMotor) {
if ((this->x + speed[0] >= 0 && this->x + speed[0] <= Params::SCREEN_WIDTH))
this->x += speed[0];
if (this->y + speed[1] >= 0 && this->y + speed[1] <= Params::SCREEN_HEIGHT)
this->y += speed[1];
}
void Coordinate::setMaxWidthX() {
this->x = Params::SCREEN_WIDTH - 1;
}
| [
"vitor.sousa.moreira@hotmail.com"
] | vitor.sousa.moreira@hotmail.com |
79aebf465094d1738b04027f3639628fdd04b930 | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /glmBfp/src/fpUcHandling.h | a18581fc8e060d3c29f09821327cd2a3d2323ef0 | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,744 | h | /*
* fpUcHandling.h
*
* Created on: 09.11.2009
* Author: daniel
*/
#ifndef FPUCHANDLING_H_
#define FPUCHANDLING_H_
#include <types.h>
#include <numeric>
#include <rcppExport.h>
// ***************************************************************************************************//
// small helper function to structure code:
// get the maximum power set for a range of FP maximum degrees
MyDoubleVector
getMaxPowerSet(const PosIntVector& fpmaxs);
// ***************************************************************************************************//
// build array of vectors of ColumnVectors holding the required transformed values for the design matrices
// do not! center the column. This is done inside getFpMatrix, because the repeated powers case cannot
// be treated here.
AVectorArray
getTransformedCols(const PosIntVector& fpcards,
const PosIntVector& fppos,
const PosIntVector& fpmaxs,
const AMatrix& x);
// ***************************************************************************************************//
struct FpInfo
{ // collects all information on fractional polynomials needed to be passed down
PosInt nFps;
MyDoubleVector powerset;
PosIntVector fpcards;
PosIntVector fppos;
PosIntVector fpmaxs;
StrVector fpnames;
AVectorArray tcols;
PosInt maxFpDim;
// number of possible univariate fps for each FP?
IntVector numberPossibleFps;
// what is the multiset expressing a linear inclusion of a covariate?
Powers linearPowers;
// ctr
FpInfo(const PosIntVector& fpcards,
const PosIntVector& fppos,
const PosIntVector& fpmaxs,
const StrVector& fpnames,
const AMatrix& x) :
nFps(fpmaxs.size()), powerset(getMaxPowerSet(fpmaxs)), fpcards(fpcards),
fppos(fppos), fpmaxs(fpmaxs), fpnames(fpnames), tcols(getTransformedCols(fpcards, fppos, fpmaxs, x)),
maxFpDim(std::accumulate(fpmaxs.begin(), fpmaxs.end(), 0)),
numberPossibleFps(),
linearPowers()
{
// numbers of possible univariate fps?
for(PosInt i=0; i != nFps; ++i)
{
int thisNumber = 0;
for(PosInt deg = 0; deg <= fpmaxs[i]; ++deg)
{
thisNumber += Rf_choose(fpcards[i] - 1 + deg, deg);
}
numberPossibleFps.push_back(thisNumber);
}
// insert the index 5 for linear power 1
linearPowers.insert(5);
}
// convert inds m into powers vector
MyDoubleVector
inds2powers(const Powers& m) const;
// convert std::vector of powers into Powers object (i.e. a multiset)
Powers
vec2inds(const MyDoubleVector& p) const;
};
// ***************************************************************************************************//
// collects all information on uncertain fixed form covariates groups
struct UcInfo
{
const PosIntVector ucSizes;
const PosInt maxUcDim;
const PosIntVector ucIndices;
const std::vector <PosIntVector> ucColList;
const PosInt nUcGroups;
UcInfo(const PosIntVector& ucSizes,
const PosInt maxUcDim,
const PosIntVector& ucIndices,
const std::vector<PosIntVector>& ucColList) :
ucSizes(ucSizes), maxUcDim(maxUcDim), ucIndices(ucIndices),
ucColList(ucColList), nUcGroups(ucColList.size())
{
}
};
// ***************************************************************************************************//
// collects all information on fixed form covariates groups
struct FixInfo
{
const PosIntVector fixSizes;
const PosInt maxFixDim;
const PosIntVector fixIndices;
const std::vector <PosIntVector> fixColList;
const PosInt nFixGroups;
FixInfo(const PosIntVector& fixSizes,
const PosInt maxFixDim,
const PosIntVector& fixIndices,
const std::vector<PosIntVector>& fixColList) :
fixSizes(fixSizes), maxFixDim(maxFixDim), fixIndices(fixIndices),
fixColList(fixColList), nFixGroups(fixColList.size())
{
}
};
// ***************************************************************************************************//
// return iterator of random element of myset; should be enclosed in getRNGstate() etc.
template<class T>
typename T::iterator
discreteUniform(const T& container)
{
if (container.empty())
{
Rf_error("\ncontainer in call to discreteUniform is empty!\n");
}
double u = unif_rand();
typename T::size_type size = container.size();
typename T::const_iterator i = container.begin();
typename T::size_type j = 1;
while (u > 1.0 / size * j)
{
i++;
j++;
}
return i;
}
// ***************************************************************************************************//
// get random int x with lower <= x < upper; should be enclosed in getRNGstate() etc.
template<class INT>
INT
discreteUniform(const INT& lower, const INT& upper)
{
if (lower >= upper)
{
Rf_error("\nlower = %d >= %d = upper in discreteUniform call\n", lower,
upper);
}
double u = unif_rand();
INT size = upper - lower;
INT ret = lower;
while (u > 1.0 / size * (ret - lower + 1))
{
ret++;
}
return ret;
}
// ***************************************************************************************************//
// delete a number from a set
template<class T>
typename std::set<T>
removeElement(std::set<T> input, T element)
{
typename std::set<T>::iterator iter = input.begin();
while (iter != input.end())
{
if (*iter == element)
// A copy of iter is passed into erase(), ++ is executed after erase().
// Thus iter remains valid
input.erase(iter++);
else
++iter;
}
return input;
}
// ***************************************************************************************************//
// construct a sequence 1:maximum
template<class T>
typename std::set<T>
constructSequence(T maximum)
{
std::set<T> ret;
for (T i = 1; i <= maximum; ++i)
{
ret.insert(ret.end(), i);
}
return ret;
}
// ***************************************************************************************************//
// convert frequency vector into multiset
Powers
freqvec2Powers(IntVector& vec, const int &vecLength);
// ***************************************************************************************************//
#endif /* FPUCHANDLING_H_ */
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
53ec189d5e0586c17f9fd949d2aeaabfeb6b6187 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/core/v8/v8_html_form_controls_collection.cc | c79ace899590332dc5c35b680c1d2253e65899a7 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,381 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/core/v8/v8_html_form_controls_collection.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_element.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_node.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_radio_node_list.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_html_form_controls_collection_wrapper_type_info = {
gin::kEmbedderBlink,
V8HTMLFormControlsCollection::DomTemplate,
nullptr,
"HTMLFormControlsCollection",
V8HTMLCollection::GetWrapperTypeInfo(),
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in HTMLFormControlsCollection.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
const WrapperTypeInfo& HTMLFormControlsCollection::wrapper_type_info_ = v8_html_form_controls_collection_wrapper_type_info;
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, HTMLFormControlsCollection>::value,
"HTMLFormControlsCollection inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&HTMLFormControlsCollection::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"HTMLFormControlsCollection is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
namespace html_form_controls_collection_v8_internal {
static void NamedItemMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
HTMLFormControlsCollection* impl = V8HTMLFormControlsCollection::ToImpl(info.Holder());
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("namedItem", "HTMLFormControlsCollection", ExceptionMessages::NotEnoughArguments(1, info.Length())));
return;
}
V8StringResource<> name;
name = info[0];
if (!name.Prepare())
return;
RadioNodeListOrElement result;
impl->namedGetter(name, result);
V8SetReturnValue(info, result);
}
static void NamedPropertyGetter(const AtomicString& name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
HTMLFormControlsCollection* impl = V8HTMLFormControlsCollection::ToImpl(info.Holder());
RadioNodeListOrElement result;
impl->namedGetter(name, result);
if (result.IsNull())
return;
V8SetReturnValue(info, result);
}
static void NamedPropertyQuery(
const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
const CString& name_in_utf8 = name.Utf8();
ExceptionState exception_state(
info.GetIsolate(),
ExceptionState::kGetterContext,
"HTMLFormControlsCollection",
name_in_utf8.data());
HTMLFormControlsCollection* impl = V8HTMLFormControlsCollection::ToImpl(info.Holder());
bool result = impl->NamedPropertyQuery(name, exception_state);
if (!result)
return;
// https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty
// 2.7. If |O| implements an interface with a named property setter, then set
// desc.[[Writable]] to true, otherwise set it to false.
// 2.8. If |O| implements an interface with the
// [LegacyUnenumerableNamedProperties] extended attribute, then set
// desc.[[Enumerable]] to false, otherwise set it to true.
V8SetReturnValueInt(info, v8::DontEnum | v8::ReadOnly);
}
static void NamedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
ExceptionState exception_state(
info.GetIsolate(),
ExceptionState::kEnumerationContext,
"HTMLFormControlsCollection");
HTMLFormControlsCollection* impl = V8HTMLFormControlsCollection::ToImpl(info.Holder());
Vector<String> names;
impl->NamedPropertyEnumerator(names, exception_state);
if (exception_state.HadException())
return;
V8SetReturnValue(info, ToV8(names, info.Holder(), info.GetIsolate()).As<v8::Array>());
}
static void IndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
HTMLFormControlsCollection* impl = V8HTMLFormControlsCollection::ToImpl(info.Holder());
// We assume that all the implementations support length() method, although
// the spec doesn't require that length() must exist. It's okay that
// the interface does not have length attribute as long as the
// implementation supports length() member function.
if (index >= impl->length())
return; // Returns undefined due to out-of-range.
Node* result = impl->item(index);
V8SetReturnValueFast(info, result, impl);
}
static void IndexedPropertyDescriptor(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
// https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty
// Steps 1.1 to 1.2.4 are covered here: we rely on indexedPropertyGetter() to
// call the getter function and check that |index| is a valid property index,
// in which case it will have set info.GetReturnValue() to something other
// than undefined.
V8HTMLFormControlsCollection::IndexedPropertyGetterCallback(index, info);
v8::Local<v8::Value> getter_value = info.GetReturnValue().Get();
if (!getter_value->IsUndefined()) {
// 1.2.5. Let |desc| be a newly created Property Descriptor with no fields.
// 1.2.6. Set desc.[[Value]] to the result of converting value to an
// ECMAScript value.
// 1.2.7. If O implements an interface with an indexed property setter,
// then set desc.[[Writable]] to true, otherwise set it to false.
v8::PropertyDescriptor desc(getter_value, false);
// 1.2.8. Set desc.[[Enumerable]] and desc.[[Configurable]] to true.
desc.set_enumerable(true);
desc.set_configurable(true);
// 1.2.9. Return |desc|.
V8SetReturnValue(info, desc);
}
}
} // namespace html_form_controls_collection_v8_internal
void V8HTMLFormControlsCollection::NamedItemMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLFormControlsCollection_namedItem");
html_form_controls_collection_v8_internal::NamedItemMethod(info);
}
void V8HTMLFormControlsCollection::NamedPropertyGetterCallback(
v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLFormControlsCollection_NamedPropertyGetter");
if (!name->IsString())
return;
const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
html_form_controls_collection_v8_internal::NamedPropertyGetter(property_name, info);
}
void V8HTMLFormControlsCollection::NamedPropertyQueryCallback(
v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLFormControlsCollection_NamedPropertyQuery");
if (!name->IsString())
return;
const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>());
html_form_controls_collection_v8_internal::NamedPropertyQuery(property_name, info);
}
void V8HTMLFormControlsCollection::NamedPropertyEnumeratorCallback(
const v8::PropertyCallbackInfo<v8::Array>& info) {
html_form_controls_collection_v8_internal::NamedPropertyEnumerator(info);
}
void V8HTMLFormControlsCollection::IndexedPropertyGetterCallback(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLFormControlsCollection_IndexedPropertyGetter");
html_form_controls_collection_v8_internal::IndexedPropertyGetter(index, info);
}
void V8HTMLFormControlsCollection::IndexedPropertyDescriptorCallback(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) {
html_form_controls_collection_v8_internal::IndexedPropertyDescriptor(index, info);
}
void V8HTMLFormControlsCollection::IndexedPropertySetterCallback(
uint32_t index,
v8::Local<v8::Value> v8_value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
// No indexed property setter defined. Do not fall back to the default
// setter.
V8SetReturnValue(info, v8::Null(info.GetIsolate()));
if (info.ShouldThrowOnError()) {
ExceptionState exception_state(info.GetIsolate(),
ExceptionState::kIndexedSetterContext,
"HTMLFormControlsCollection");
exception_state.ThrowTypeError("Index property setter is not supported.");
}
}
void V8HTMLFormControlsCollection::IndexedPropertyDefinerCallback(
uint32_t index,
const v8::PropertyDescriptor& desc,
const v8::PropertyCallbackInfo<v8::Value>& info) {
// https://heycam.github.io/webidl/#legacy-platform-object-defineownproperty
// 3.9.3. [[DefineOwnProperty]]
// step 1.2. If O does not implement an interface with an indexed property
// setter, then return false.
//
// https://html.spec.whatwg.org/C/window-object.html#windowproxy-defineownproperty
// 7.4.6 [[DefineOwnProperty]] (P, Desc)
// step 2.1. If P is an array index property name, return false.
V8SetReturnValue(info, v8::Null(info.GetIsolate()));
if (info.ShouldThrowOnError()) {
ExceptionState exception_state(info.GetIsolate(),
ExceptionState::kIndexedSetterContext,
"HTMLFormControlsCollection");
exception_state.ThrowTypeError("Index property setter is not supported.");
}
}
static constexpr V8DOMConfiguration::MethodConfiguration kV8HTMLFormControlsCollectionMethods[] = {
{"namedItem", V8HTMLFormControlsCollection::NamedItemMethodCallback, 1, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds},
};
static void InstallV8HTMLFormControlsCollectionTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8HTMLFormControlsCollection::GetWrapperTypeInfo()->interface_name, V8HTMLCollection::DomTemplate(isolate, world), V8HTMLFormControlsCollection::kInternalFieldCount);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
V8DOMConfiguration::InstallMethods(
isolate, world, instance_template, prototype_template, interface_template,
signature, kV8HTMLFormControlsCollectionMethods, base::size(kV8HTMLFormControlsCollectionMethods));
// Indexed properties
v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(
V8HTMLFormControlsCollection::IndexedPropertyGetterCallback,
V8HTMLFormControlsCollection::IndexedPropertySetterCallback,
V8HTMLFormControlsCollection::IndexedPropertyDescriptorCallback,
nullptr,
IndexedPropertyEnumerator<HTMLFormControlsCollection>,
V8HTMLFormControlsCollection::IndexedPropertyDefinerCallback,
v8::Local<v8::Value>(),
v8::PropertyHandlerFlags::kNone);
instance_template->SetHandler(indexedPropertyHandlerConfig);
// Named properties
v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(V8HTMLFormControlsCollection::NamedPropertyGetterCallback, nullptr, V8HTMLFormControlsCollection::NamedPropertyQueryCallback, nullptr, V8HTMLFormControlsCollection::NamedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking)));
instance_template->SetHandler(namedPropertyHandlerConfig);
// Custom signature
V8HTMLFormControlsCollection::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interface_template);
}
void V8HTMLFormControlsCollection::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
v8::Local<v8::FunctionTemplate> V8HTMLFormControlsCollection::DomTemplate(
v8::Isolate* isolate, const DOMWrapperWorld& world) {
return V8DOMConfiguration::DomClassTemplate(
isolate, world, const_cast<WrapperTypeInfo*>(V8HTMLFormControlsCollection::GetWrapperTypeInfo()),
InstallV8HTMLFormControlsCollectionTemplate);
}
bool V8HTMLFormControlsCollection::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(V8HTMLFormControlsCollection::GetWrapperTypeInfo(), v8_value);
}
v8::Local<v8::Object> V8HTMLFormControlsCollection::FindInstanceInPrototypeChain(
v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(
V8HTMLFormControlsCollection::GetWrapperTypeInfo(), v8_value);
}
HTMLFormControlsCollection* V8HTMLFormControlsCollection::ToImplWithTypeCheck(
v8::Isolate* isolate, v8::Local<v8::Value> value) {
return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
HTMLFormControlsCollection* NativeValueTraits<HTMLFormControlsCollection>::NativeValue(
v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
HTMLFormControlsCollection* native_value = V8HTMLFormControlsCollection::ToImplWithTypeCheck(isolate, value);
if (!native_value) {
exception_state.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue(
"HTMLFormControlsCollection"));
}
return native_value;
}
} // namespace blink
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
56cc1a061c4a44cd0ef0c1129d2b3b70bdea0de0 | da08ffa22f0b5f170018f79d0c1826b17c523a74 | /src/slt/core/core_test.cpp | 1e58b9704549c17b319017a016b8cc3fec77581b | [
"Apache-2.0"
] | permissive | SharpLinesTech/slt_tech_core | 35ca550b8e052757ad63c6b2b97e16aa9218cdfc | cde0ff2c7ae9a0990860a5168fa60158c3470b81 | refs/heads/master | 2021-01-21T06:25:21.401215 | 2017-03-18T18:35:19 | 2017-03-18T18:35:19 | 83,232,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | #include "gtest/gtest.h"
#include "slt/core/core.h"
#include "slt/settings/settings.h"
slt::Setting<int> trivial(1, "trivial", "");
TEST(Settings, parse_argv) {
const char* argv[] = {"", "--trivial=3"};
{
slt::Core core(2, argv);
EXPECT_EQ(3, trivial.get());
}
// Setting should be back to normal
EXPECT_EQ(1, trivial.get());
}
TEST(Settings, invalid_setting) {
const char* argv[] = {"", "--unknown=3"};
EXPECT_THROW(slt::Core(2, argv), slt::SettingsError);
} | [
"francois@sharplinestech.com"
] | francois@sharplinestech.com |
6a88f5a7dbf8f7e0458b416863c31c7a9a0c4b6f | 62d40114057bc76fd7fe634eeaadad21f48c36a4 | /CCISolution/CCI/Q_16_17.h | 5bdb2cf1e3ac022c7b2c58feb0bfc553526497e3 | [] | no_license | sunrack/Algorithm | a25a536f9781b9ae6c52f8a960ed8b0ccc50f312 | 7711fc160b46e05e57e9e52cc729c73c462e5b51 | refs/heads/master | 2021-04-28T16:24:15.505656 | 2018-03-04T21:34:51 | 2018-03-04T21:34:51 | 122,011,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #pragma once
#include "QBase.h"
// Kadane's Algorithm
// Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum.
// https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0
// https://ide.geeksforgeeks.org/EtrjQF
class Q_16_17 :
public QBase
{
public:
static int Test();
static int FindMaxSubArrayFast(const int A[], int n);
static int FindMaxSubArraySlow(const int A[], int n);
}; | [
"sunrack@163.com"
] | sunrack@163.com |
3ba23b12f96cee9021a6b82d8516f63adc3e0439 | 42de52c952b7f38ccbbc1c99314eb484ba971541 | /Zeus/PhysX/Source/GeomUtils/src/GuGJKRaycast.h | 6e254940d3c499b5c0e1b285540e5004cd2f30d1 | [] | no_license | osu-capstone-nvidia-project-2013/Zeus | 5eec6ee9db2a6128fffb8abc1ff02b365f19bb85 | 4402cf2ca89b70dad408226bb49d8518f49b6879 | refs/heads/master | 2016-09-06T12:31:26.319679 | 2013-04-11T18:08:23 | 2013-04-11T18:08:23 | 6,286,357 | 1 | 1 | null | 2013-01-18T21:04:53 | 2012-10-18T22:20:43 | C | UTF-8 | C++ | false | false | 24,337 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_GJKRAYCAST_H
#define PX_GJKRAYCAST_H
//#include "GuGJKPenetrationWrapper.h"
#include "GuGJKSimplex.h"
#include "GuConvexSupportTable.h"
#include "GuGJKPenetration.h"
//#include "GuGJKPenetrationWrapper.h"
namespace physx
{
namespace Gu
{
#ifndef __SPU__
//template<class ConvexA, class ConvexB>
//bool gjkRayCast(ConvexA& a, ConvexB& b, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA)
//{
// using namespace Ps::aos;
// const Vec3V zeroV = V3Zero();
// const FloatV zero = FZero();
// const FloatV one = FOne();
// const BoolV bTrue = BTTTT();
// const FloatV maxDist = FloatV_From_F32(PX_MAX_REAL);
//
// FloatV _lambda = zero;//initialLambda;
// Vec3V x = V3ScaleAdd(r, _lambda, s);
// PxU32 size=1;
// const Vec3V bOriginalCenter = b.getCenter();
// b.setCenter(x);
// const Vec3V _initialSearchDir(V3Sub(a.getCenter(), b.getCenter()));
// const Vec3V initialSearchDir = V3Sel(FIsGrtr(V3Dot(_initialSearchDir, _initialSearchDir), zero), _initialSearchDir, V3UnitX());
// const Vec3V initialSupportA(a.supportSweep(V3Neg(initialSearchDir)));
// const Vec3V initialSupportB(b.supportSweep(initialSearchDir));
//
// Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set
// Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set
// Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set
//
// Vec3V v = V3Neg(Q[0]);
// Vec3V supportA = initialSupportA;
// Vec3V supportB = initialSupportB;
// Vec3V support = Q[0];
// const FloatV eps1 = FloatV_From_F32(0.0001f);
// const FloatV eps2 = FMul(eps1, eps1);
// Vec3V closA(initialSupportA), closB(initialSupportB);
// FloatV sDist = V3Dot(v, v);
// FloatV minDist = sDist;
// Vec3V closAA = initialSupportA;
// Vec3V closBB = initialSupportB;
//
// BoolV bNotTerminated = FIsGrtr(sDist, eps2);
// BoolV bCon = bTrue;
// Vec3V nor = v;
//
// while(BAllEq(bNotTerminated, bTrue))
// {
//
// minDist = sDist;
// closAA = closA;
// closBB = closB;
// supportA=a.supportSweep(v);
// supportB=b.supportSweep(V3Neg(v));
//
// //calculate the support point
// support = V3Sub(supportA, supportB);
// const Vec3V w = V3Neg(support);
// const FloatV vw = V3Dot(v, w);
// const FloatV vr = V3Dot(v, r);
// if(FAllGrtr(vw, zero))
// {
//
// if(FAllGrtrOrEq(vr, zero))
// {
// b.setCenter(bOriginalCenter);
// return false;
// }
// else
// {
// const FloatV _oldLambda = _lambda;
// _lambda = FSub(_lambda, FDiv(vw, vr));
// if(FAllGrtr(_lambda, _oldLambda))
// {
// if(FAllGrtr(_lambda, one))
// {
// b.setCenter(bOriginalCenter);
// return false;
// }
// const Vec3V bPreCenter = b.getCenter();
// x = V3ScaleAdd(r, _lambda, s);
// b.setCenter(x);
// const Vec3V offSet = V3Sub(x, bPreCenter);
// const Vec3V b0 = V3Add(B[0], offSet);
// const Vec3V b1 = V3Add(B[1], offSet);
// const Vec3V b2 = V3Add(B[2], offSet);
// B[0] = b0;
// B[1] = b1;
// B[2] = b2;
// Q[0]=V3Sub(A[0], b0);
// Q[1]=V3Sub(A[1], b1);
// Q[2]=V3Sub(A[2], b2);
// supportB = b.supportSweep(V3Neg(v));
// support = V3Sub(supportA, supportB);
// minDist = maxDist;
// nor = v;
// //size=0;
// }
// }
// }
// PX_ASSERT(size < 4);
// A[size]=supportA;
// B[size]=supportB;
// Q[size++]=support;
//
// //calculate the closest point between two convex hull
// const Vec3V tempV = GJKCPairDoSimplex(Q, A, B, support, supportA, supportB, size, closA, closB);
// v = V3Neg(tempV);
// sDist = V3Dot(tempV, tempV);
// bCon = FIsGrtr(minDist, sDist);
// bNotTerminated = BAnd(FIsGrtr(sDist, eps2), bCon);
// }
// lambda = _lambda;
// if(FAllEq(_lambda, zero))
// {
// //time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point
// b.setCenter(bOriginalCenter);
// const FloatV contactDist = getContactEps(a.getMargin(), b.getMargin());
// closestA = closAA;
// normal= V3Normalize(V3Sub(closAA, closBB));
// //hitPoint = x;
// if(GJKPenetration(a, b, contactDist, closA, closB, normal, sDist))
// {
// closestA = closA;
// }
// }
// else
// {
// //const FloatV stepBackRatio = FDiv(offset, V3Length(r));
// //lambda = FMax(FSub(lambda, stepBackRatio), zero);
// b.setCenter(bOriginalCenter);
// closA = V3Sel(bCon, closA, closAA);
// closestA = closA;
// normal = V3Neg(V3Normalize(nor));
// }
// return true;
//}
//template<class ConvexA, class ConvexB>
//bool gjkRelativeRayCast(ConvexA& a, ConvexB& b, const Ps::aos::PsMatTransformV& aToBRel, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA)
//{
// using namespace Ps::aos;
// const Vec3V zeroV = V3Zero();
// const FloatV zero = FZero();
// const FloatV one = FOne();
// const BoolV bTrue = BTTTT();
// const FloatV maxDist = FloatV_From_F32(PX_MAX_REAL);
//
// FloatV _lambda = zero;//initialLambda;
// Vec3V x = V3ScaleAdd(r, _lambda, s);
// PxU32 size=1;
// Ps::aos::PsMatTransformV aToB(aToBRel);
///* const Vec3V bOriginalCenter = b.getCenter();
// b.setCenter(x);*/
///* const Vec3V bOriginalCenter = V3Zero();
// b.setCenter(x);*/
// const Vec3V _initialSearchDir(aToB.p);//(V3Sub(a.getCenter(), b.getCenter()));
// const Vec3V initialSearchDir = V3Sel(FIsGrtr(V3Dot(_initialSearchDir, _initialSearchDir), zero), _initialSearchDir, V3UnitX());
// const Vec3V initialSupportA(a.supportSweepRelative(V3Neg(initialSearchDir), aToB));
// const Vec3V initialSupportB(b.supportSweepLocal(initialSearchDir));
//
// Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set
// Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set
// Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set
//
// Vec3V v = V3Neg(Q[0]);
// Vec3V supportA = initialSupportA;
// Vec3V supportB = initialSupportB;
// Vec3V support = Q[0];
// const FloatV eps1 = FloatV_From_F32(0.0001f);
// const FloatV eps2 = FMul(eps1, eps1);
// Vec3V closA(initialSupportA), closB(initialSupportB);
// FloatV sDist = V3Dot(v, v);
// FloatV minDist = sDist;
// Vec3V closAA = initialSupportA;
// Vec3V closBB = initialSupportB;
//
// BoolV bNotTerminated = FIsGrtr(sDist, eps2);
// BoolV bCon = bTrue;
// Vec3V nor = v;
//
// while(BAllEq(bNotTerminated, bTrue))
// {
//
// minDist = sDist;
// closAA = closA;
// closBB = closB;
// supportA=a.supportSweepRelative(v, aToB);
// supportB=b.supportSweepLocal(V3Neg(v));
//
// //calculate the support point
// support = V3Sub(supportA, supportB);
// const Vec3V w = V3Neg(support);
// const FloatV vw = V3Dot(v, w);
// const FloatV vr = V3Dot(v, r);
// if(FAllGrtr(vw, zero))
// {
//
// if(FAllGrtrOrEq(vr, zero))
// {
// //b.setCenter(bOriginalCenter);
// return false;
// }
// else
// {
// const FloatV _oldLambda = _lambda;
// _lambda = FSub(_lambda, FDiv(vw, vr));
// if(FAllGrtr(_lambda, _oldLambda))
// {
// if(FAllGrtr(_lambda, one))
// {
// // b.setCenter(bOriginalCenter);
// return false;
// }
// const Vec3V bPreCenter = aToB.p;
// x = V3ScaleAdd(r, _lambda, s);
// //b.setCenter(x);
// aToB.p = V3Neg(x);
// const Vec3V offSet = V3Sub(x, bPreCenter);
// const Vec3V a0 = V3Sub(A[0], offSet);
// const Vec3V a1 = V3Sub(A[1], offSet);
// const Vec3V a2 = V3Sub(A[2], offSet);
//
// A[0] = a0;
// A[1] = a1;
// A[2] = a2;
// Q[0]=V3Sub(a0, B[0]);
// Q[1]=V3Sub(a1, B[1]);
// Q[2]=V3Sub(a2, B[2]);
// supportA = a.supportSweepRelative(v, aToB);
// support = V3Sub(supportA, supportB);
// minDist = maxDist;
// nor = v;
// //size=0;
// }
// }
// }
// PX_ASSERT(size < 4);
// A[size]=supportA;
// B[size]=supportB;
// Q[size++]=support;
//
// //calculate the closest point between two convex hull
// const Vec3V tempV = GJKCPairDoSimplex(Q, A, B, support, supportA, supportB, size, closA, closB);
// v = V3Neg(tempV);
// sDist = V3Dot(tempV, tempV);
// bCon = FIsGrtr(minDist, sDist);
// bNotTerminated = BAnd(FIsGrtr(sDist, eps2), bCon);
// }
// lambda = _lambda;
// if(FAllEq(_lambda, zero))
// {
// //time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point
// //b.setCenter(bOriginalCenter);
// const FloatV contactDist = getContactEps(a.getMargin(), b.getMargin());
// closestA = closAA;
// normal= V3Normalize(V3Sub(closAA, closBB));
// //hitPoint = x;
// if(GJKRelativePenetration(a, b, aToBRel, contactDist, closA, closB, normal, sDist))
// {
// // in the local space of B
// closestA = closA;
// }
// }
// else
// {
// //const FloatV stepBackRatio = FDiv(offset, V3Length(r));
// //lambda = FMax(FSub(lambda, stepBackRatio), zero);
// //b.setCenter(bOriginalCenter);
// closA = V3Sel(bCon, closA, closAA);
// closestA = closA;
// normal = V3Neg(V3Normalize(nor));
// }
// return true;
//}
//ConvexA is in the local space of ConvexB
template<class ConvexA, class ConvexB>
bool _gjkLocalRayCast(ConvexA& a, ConvexB& b, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal _inflation/*, const bool initialOverlap*/)
{
using namespace Ps::aos;
const FloatV zero = FZero();
FloatV _lambda = zero;//initialLambda;
const FloatV inflation = FloatV_From_F32(_inflation);
const Vec3V zeroV = V3Zero();
const FloatV one = FOne();
const BoolV bTrue = BTTTT();
const FloatV maxDist = FloatV_From_F32(PX_MAX_REAL);
Vec3V x = V3ScaleAdd(r, _lambda, s);
PxU32 size=1;
const Vec3V dir = V3Sub(a.getCenter(), b.getCenter());
const Vec3V _initialSearchDir = V3Sel(FIsGrtr(V3Dot(dir, dir), FEps()), dir, V3UnitX());
const Vec3V initialSearchDir = V3Normalize(_initialSearchDir);
const Vec3V initialSupportA(a.supportSweepLocal(V3Neg(initialSearchDir)));
//const Vec3V initialSupportB(V3ScaleAdd(initialSearchDir, inflation, b.supportSweepLocal(initialSearchDir)));
const Vec3V initialSupportB(b.supportSweepLocal(initialSearchDir));
Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set
Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set
Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set
Vec3V v = V3Neg(Q[0]);
Vec3V supportA = initialSupportA;
Vec3V supportB = initialSupportB;
Vec3V support = Q[0];
//const FloatV onePerc = FloatV_From_F32(0.01f);
//const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin());
////const FloatV eps2 = FAdd(sqInflation, FMul(minMargin, onePerc));
//const FloatV eps2 = FMul(minMargin, onePerc);
const FloatV eps1 = FloatV_From_F32(0.0001f);
const FloatV eps2 = FMul(eps1, eps1);
const FloatV inflation2 = FAdd(FMul(inflation, inflation), eps2);
Vec3V closA(initialSupportA), closB(initialSupportB);
FloatV sDist = V3Dot(v, v);
FloatV minDist = sDist;
Vec3V closAA = initialSupportA;
//Vec3V closBB = initialSupportB;
BoolV bNotTerminated = FIsGrtr(sDist, eps2);
BoolV bCon = bTrue;
Vec3V nor = v;
while(BAllEq(bNotTerminated, bTrue))
{
minDist = sDist;
closAA = closA;
//closBB = closB;
const Vec3V vNorm = V3Normalize(v);
const Vec3V nvNorm = V3Neg(vNorm);
supportA=a.supportSweepLocal(vNorm);
//supportB=V3ScaleAdd(nvNorm, inflation, V3Add(x, b.supportSweepLocal(nvNorm)));
supportB=V3Add(x, b.supportSweepLocal(nvNorm));
//calculate the support point
support = V3Sub(supportA, supportB);
const Vec3V w = V3Neg(support);
const FloatV vw = FSub(V3Dot(vNorm, w), inflation);
const FloatV vr = V3Dot(vNorm, r);
if(FAllGrtr(vw, zero))
{
if(FAllGrtrOrEq(vr, zero))
{
return false;
}
else
{
const FloatV _oldLambda = _lambda;
_lambda = FSub(_lambda, FDiv(vw, vr));
if(FAllGrtr(_lambda, _oldLambda))
{
if(FAllGrtr(_lambda, one))
{
return false;
}
const Vec3V bPreCenter = x;
x = V3ScaleAdd(r, _lambda, s);
//aToB.p = V3Sub(aToB.p, x);
//aToB.p = V3Neg(x);
const Vec3V offSet =V3Sub(x, bPreCenter);
const Vec3V b0 = V3Add(B[0], offSet);
const Vec3V b1 = V3Add(B[1], offSet);
const Vec3V b2 = V3Add(B[2], offSet);
B[0] = b0;
B[1] = b1;
B[2] = b2;
Q[0]=V3Sub(A[0], b0);
Q[1]=V3Sub(A[1], b1);
Q[2]=V3Sub(A[2], b2);
//supportA = a.supportSweepRelative(v, aToB);
//supportB = V3Add(x, b.supportSweepLocal(V3Neg(v)));
//supportB = V3ScaleAdd(nvNorm, inflation, V3Add(x, b.supportSweepLocal(nvNorm)));
supportB = V3Add(x, b.supportSweepLocal(nvNorm));
//supportB = b.supportSweepLocal(V3Neg(v));
support = V3Sub(supportA, supportB);
minDist = maxDist;
nor = v;
//size=0;
}
}
}
PX_ASSERT(size < 4);
A[size]=supportA;
B[size]=supportB;
Q[size++]=support;
//calculate the closest point between two convex hull
const Vec3V tempV = GJKCPairDoSimplex(Q, A, B, support, supportA, supportB, size, closA, closB);
v = V3Neg(tempV);
sDist = V3Dot(tempV, tempV);
bCon = FIsGrtr(minDist, sDist);
bNotTerminated = BAnd(FIsGrtr(sDist, inflation2), bCon);
}
lambda = _lambda;
closestA = V3Sel(bCon, closA, closAA);
normal = V3Neg(V3Normalize(nor));
return true;
}
template<class ConvexA, class ConvexB>
bool gjkLocalRayCast(ConvexA& a, ConvexB& b, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap)
{
using namespace Ps::aos;
Vec3V closA;
Vec3V norm;
FloatV _lambda;
if(_gjkLocalRayCast(a, b, initialLambda, s, r, _lambda, norm, closA, _inflation))
{
if(FAllEq(_lambda, FZero()) && initialOverlap)
{
//time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point
const FloatV contactDist = getSweepContactEps(a.getMargin(), b.getMargin());
Vec3V closAA;
Vec3V closBB;
FloatV sDist;
PxU8 tmp =0;
if(gjkLocalPenetration(a, b, contactDist, closAA, closBB, norm, sDist, NULL, NULL, tmp))
{
closA = closAA;
}
else
{
// in the local space of B
//closestA = closA;
closA = closAA;
norm= V3Normalize(V3Sub(closAA, closBB));
}
}
closestA = closA;
normal = norm;
lambda = _lambda;
return true;
}
return false;
}
template<class ConvexA, class ConvexB>
bool _gjkRelativeRayCast(ConvexA& a, ConvexB& b, const Ps::aos::PsMatTransformV& aToB, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal _inflation/*, const bool initialOverlap*/)
{
using namespace Ps::aos;
const FloatV inflation = FloatV_From_F32(_inflation);
const Vec3V zeroV = V3Zero();
const FloatV zero = FZero();
const FloatV eps = FEps();
const FloatV one = FOne();
const BoolV bTrue = BTTTT();
const FloatV maxDist = FloatV_From_F32(PX_MAX_REAL);
FloatV _lambda = zero;//initialLambda;
Vec3V x = V3ScaleAdd(r, _lambda, s);
PxU32 size=1;
// PsMatTransformV aToB = aToBRel;
/* const Vec3V bOriginalCenter = V3Zero();
b.setCenter(x);*/
//const Vec3V _initialSearchDir(V3Normalize(aToB.p));//(V3Sub(a.getCenter(), b.getCenter()));
const Vec3V _initialSearchDir = V3Sel(FIsGrtr(V3Dot(aToB.p, aToB.p), eps), aToB.p, V3UnitX());
const Vec3V initialSearchDir = V3Normalize(_initialSearchDir);
const Vec3V initialSupportA(a.supportSweepRelative(V3Neg(initialSearchDir), aToB));
//const Vec3V initialSupportB(V3ScaleAdd(initialSearchDir, inflation, b.supportSweepLocal(initialSearchDir)));
const Vec3V initialSupportB(b.supportSweepLocal(initialSearchDir));
Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set
Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set
Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set
Vec3V v = V3Neg(Q[0]);
Vec3V supportA = initialSupportA;
Vec3V supportB = initialSupportB;
Vec3V support = Q[0];
//const FloatV onePerc = FloatV_From_F32(0.01f);
//const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin());
////const FloatV eps2 = FAdd(sqInflation, FMul(minMargin, onePerc));
//const FloatV eps2 = FMul(minMargin, onePerc);
const FloatV eps1 = FloatV_From_F32(0.0001f);
const FloatV eps2 = FMul(eps1, eps1);
const FloatV inflation2 = FAdd(FMul(inflation, inflation), eps2);
Vec3V closA(initialSupportA), closB(initialSupportB);
FloatV sDist = V3Dot(v, v);
FloatV minDist = sDist;
Vec3V closAA = initialSupportA;
//Vec3V closBB = initialSupportB;
BoolV bNotTerminated = FIsGrtr(sDist, eps2);
BoolV bCon = bTrue;
Vec3V nor = v;
while(BAllEq(bNotTerminated, bTrue))
{
minDist = sDist;
closAA = closA;
//closBB = closB;
const Vec3V vNorm = V3Normalize(v);
const Vec3V nvNorm = V3Neg(vNorm);
supportA=a.supportSweepRelative(vNorm, aToB);
//supportB=V3ScaleAdd(nvNorm, inflation, V3Add(x, b.supportSweepLocal(nvNorm)));
supportB=V3Add(x, b.supportSweepLocal(nvNorm));
//calculate the support point
support = V3Sub(supportA, supportB);
const Vec3V w = V3Neg(support);
const FloatV vw = FSub(V3Dot(vNorm, w), inflation);
const FloatV vr = V3Dot(vNorm, r);
if(FAllGrtr(vw, zero))
{
if(FAllGrtrOrEq(vr, zero))
{
return false;
}
else
{
const FloatV _oldLambda = _lambda;
_lambda = FSub(_lambda, FDiv(vw, vr));
if(FAllGrtr(_lambda, _oldLambda))
{
if(FAllGrtr(_lambda, one))
{
return false;
}
const Vec3V bPreCenter = x;
x = V3ScaleAdd(r, _lambda, s);
//aToB.p = V3Sub(aToB.p, x);
//aToB.p = V3Neg(x);
const Vec3V offSet =V3Sub(x, bPreCenter);
const Vec3V b0 = V3Add(B[0], offSet);
const Vec3V b1 = V3Add(B[1], offSet);
const Vec3V b2 = V3Add(B[2], offSet);
B[0] = b0;
B[1] = b1;
B[2] = b2;
Q[0]=V3Sub(A[0], b0);
Q[1]=V3Sub(A[1], b1);
Q[2]=V3Sub(A[2], b2);
//supportA = a.supportSweepRelative(v, aToB);
//supportB = V3Add(x, b.supportSweepLocal(V3Neg(v)));
//supportB = V3ScaleAdd(nvNorm, inflation, V3Add(x, b.supportSweepLocal(nvNorm)));
supportB = V3Add(x, b.supportSweepLocal(nvNorm));
//supportB = b.supportSweepLocal(V3Neg(v));
support = V3Sub(supportA, supportB);
minDist = maxDist;
nor = v;
//size=0;
}
}
}
PX_ASSERT(size < 4);
A[size]=supportA;
B[size]=supportB;
Q[size++]=support;
//calculate the closest point between two convex hull
const Vec3V tempV = GJKCPairDoSimplex(Q, A, B, support, supportA, supportB, size, closA, closB);
v = V3Neg(tempV);
sDist = V3Dot(tempV, tempV);
bCon = FIsGrtr(minDist, sDist);
bNotTerminated = BAnd(FIsGrtr(sDist, inflation2), bCon);
}
lambda = _lambda;
closestA = V3Sel(bCon, closA, closAA);
normal = V3Neg(V3Normalize(nor));
return true;
}
template<class ConvexA, class ConvexB>
bool gjkRelativeRayCast(ConvexA& a, ConvexB& b, const Ps::aos::PsMatTransformV& aToB, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap)
{
using namespace Ps::aos;
Vec3V closA;
Vec3V norm;
FloatV _lambda;
if(_gjkRelativeRayCast(a, b, aToB, initialLambda, s, r, _lambda, norm, closA, _inflation))
{
if(FAllEq(_lambda, FZero()) && initialOverlap)
{
//time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point
const FloatV contactDist = getSweepContactEps(a.getMargin(), b.getMargin());
Vec3V closAA;
Vec3V closBB;
FloatV sDist;
PxU8 tmp =0;
if(gjkRelativePenetration(a, b, aToB, contactDist, closAA, closBB, norm, sDist, NULL, NULL, tmp))
{
closA = closAA;
}
else
{
// in the local space of B
//closestA = closA;
closA = closAA;
norm= V3Normalize(V3Sub(closAA, closBB));
}
}
closestA = closA;
normal = norm;
lambda = _lambda;
return true;
}
return false;
}
#else
bool gjkRayCast(ConvexV& a, ConvexV& b, SupportMapPair* pair, const Ps::aos::Vec3VArg initialDir, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal inflation, const bool initialOverlap);
template<class ConvexA, class ConvexB>
bool gjkRelativeRayCast(ConvexA& a, ConvexB& b, const Ps::aos::PsMatTransformV& aToB, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal inflation, const bool initialOverlap)
{
SupportMapPairRelativeImpl<ConvexA, ConvexB> pair(a, b, aToB);
return gjkRayCast(a, b, &pair, aToB.p, initialLambda, s, r, lambda, normal, closestA, inflation, initialOverlap);
}
template<class ConvexA, class ConvexB>
bool gjkLocalRayCast(ConvexA& a, ConvexB& b, const Ps::aos::FloatVArg initialLambda, const Ps::aos::Vec3VArg s, const Ps::aos::Vec3VArg r, Ps::aos::FloatV& lambda, Ps::aos::Vec3V& normal, Ps::aos::Vec3V& closestA, const PxReal inflation, const bool initialOverlap)
{
using namespace Ps::aos;
SupportMapPairLocalImpl<ConvexA, ConvexB> pair(a, b);
const Vec3V initialDir = V3Sub(a.getCenter(), b.getCenter());
return gjkRayCast(a, b, &pair, initialDir, initialLambda, s, r, lambda, normal, closestA, inflation, initialOverlap);
}
#endif
}
}
#endif
| [
"clucasa@bat244-13.eecs.engineering.oregonstate.edu"
] | clucasa@bat244-13.eecs.engineering.oregonstate.edu |
9f4593d48342363d0f4958e3b55cfae0862704f5 | 158aee5b8cf0e13d29ee8a816425c43665013730 | /g++diffbenchmarktests/flagtests_exclude.cpp | e4058ff2a7aad06d2d8f15919853734d2f627c51 | [] | no_license | Leader-board/Laidlaw | 36e88924165fb807c9a491f2186c77e2354b4104 | 5b17258c8f1ac1ddeb92a1e8c603f1d1f9e6efa0 | refs/heads/master | 2020-06-15T13:04:55.673224 | 2019-07-04T23:09:07 | 2019-07-04T23:09:07 | 195,307,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,825 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <string.h>
#define opt1 132
#define opt2 46
#define opt3 15
// the set of optimisations that get enabled between O0 and O1
const char* optimisations[opt1] = { "-fno-aggressive-loop-optimizations",
"-fno-asynchronous-unwind-tables",
"-fno-auto-inc-dec",
"-fno-branch-count-reg",
"-fno-chkp-check-incomplete-type",
"-fno-chkp-check-read",
"-fno-chkp-check-write",
"-fno-chkp-instrument-calls",
"-fno-chkp-narrow-bounds",
"-fno-chkp-optimize",
"-fno-chkp-store-bounds",
"-fno-chkp-use-static-bounds",
"-fno-chkp-use-static-const-bounds",
"-fno-chkp-use-wrappers",
"-fno-combine-stack-adjustments",
"-fno-common",
"-fno-compare-elim",
"-fno-cprop-registers",
"-fno-defer-pop",
"-fno-delete-null-pointer-checks",
"-fno-dwarf2-cfi-asm",
"-fno-early-inlining",
"-fno-eliminate-unused-debug-types",
"-fno-exceptions",
"-fno-forward-propagate",
"-fno-fp-int-builtin-inexact",
"-fno-function-cse",
"-fno-gcse-lm",
"-fno-gnu-runtime",
"-fno-gnu-unique",
"-fno-guess-branch-probability",
"-fno-ident",
"-fno-if-conversion",
"-fno-if-conversion2",
"-fno-inline",
"-fno-inline-atomics",
"-fno-inline-functions-called-once",
"-fno-ipa-profile",
"-fno-ipa-pure-const",
"-fno-ipa-reference",
"-fno-ira-hoist-pressure",
"-fno-ira-share-save-slots",
"-fno-ira-share-spill-slots",
"-fno-ivopts",
"-fno-keep-static-consts",
"-fno-leading-underscore",
"-fno-lifetime-dse",
"-fno-lto-odr-type-merging",
"-fno-math-errno",
"-fno-merge-constants",
"-fno-merge-debug-strings",
"-fno-move-loop-invariants",
"-fno-omit-frame-pointer",
"-fno-peephole",
"-fno-plt",
"-fno-prefetch-loop-arrays",
"-fno-reg-struct-return",
"-fno-reorder-blocks",
"-fno-sched-critical-path-heuristic",
"-fno-sched-dep-count-heuristic",
"-fno-sched-group-heuristic",
"-fno-sched-interblock",
"-fno-sched-last-insn-heuristic",
"-fno-sched-rank-heuristic",
"-fno-sched-spec",
"-fno-sched-spec-insn-heuristic",
"-fno-sched-stalled-insns-dep",
"-fno-schedule-fusion",
"-fno-semantic-interposition",
"-fno-show-column",
"-fno-shrink-wrap",
"-fno-shrink-wrap-separate",
"-fno-signed-zeros",
"-fno-split-ivs-in-unroller",
"-fno-split-wide-types",
"-fno-ssa-backprop",
"-fno-ssa-phiopt",
"-fno-stdarg-opt",
"-fno-strict-volatile-bitfields",
"-fno-sync-libcalls",
"-fno-toplevel-reorder",
"-fno-trapping-math",
"-fno-tree-bit-ccp",
"-fno-tree-builtin-call-dce",
"-fno-tree-ccp",
"-fno-tree-ch",
"-fno-tree-coalesce-vars",
"-fno-tree-copy-prop",
"-fno-tree-cselim",
"-fno-tree-dce",
"-fno-tree-dominator-opts",
"-fno-tree-dse",
"-fno-tree-forwprop",
"-fno-tree-fre",
"-fno-tree-loop-if-convert",
"-fno-tree-loop-im",
"-fno-tree-loop-ivcanon",
"-fno-tree-loop-optimize",
"-fno-tree-parallelize-loops=4",
"-fno-tree-phiprop",
"-fno-tree-pta",
"-fno-tree-reassoc",
"-fno-tree-scev-cprop",
"-fno-tree-sink",
"-fno-tree-slsr",
"-fno-tree-sra",
"-fno-tree-ter",
"-fno-unit-at-a-time",
"-fno-unwind-tables",
"-fno-verbose-asm",
"-fno-zero-initialized-in-bss",
"-mno-128bit-long-double",
"-mno-64",
"-mno-80387",
"-mno-align-stringops",
"-mno-avx256-split-unaligned-load",
"-mno-avx256-split-unaligned-store",
"-mno-fancy-math-387",
"-mno-fp-ret-in-387",
"-mno-fxsr",
"-mno-glibc",
"-mno-ieee-fp",
"-mno-long-double-80",
"-mno-mmx",
"-mno-sse4",
"-mno-push-args",
"-mno-red-zone",
"-mno-sse",
"-mno-sse2",
"-mno-stv",
"-mno-tls-direct-seg-refs",
"-mno-vzeroupper" };
// the set of optimisations that get enabled between O1 and O2
const char* optimisations2[opt2] = { "-fno-align-functions",
"-fno-align-jumps",
"-fno-align-labels",
"-fno-align-loops",
"-fno-caller-saves",
"-fno-code-hoisting",
"-fno-crossjumping",
"-fno-cse-follow-jumps",
"-fno-cse-skip-blocks",
"-fno-delete-null-pointer-checks",
"-fno-devirtualize",
"-fno-devirtualize-speculatively",
"-fno-expensive-optimizations",
"-fno-gcse",
"-fno-gcse-lm",
"-fno-hoist-adjacent-loads",
"-fno-inline-small-functions",
"-fno-indirect-inlining",
"-fno-ipa-bit-cp",
"-fno-ipa-cp",
"-fno-ipa-icf",
"-fno-ipa-ra",
"-fno-ipa-sra",
"-fno-ipa-vrp",
"-fno-isolate-erroneous-paths-dereference",
"-fno-lra-remat",
"-fno-optimize-sibling-calls",
"-fno-optimize-strlen",
"-fno-partial-inlining",
"-fno-peephole2",
"-fno-reorder-blocks-algorithm=stc",
"-fno-reorder-blocks-and-partition",
"-fno-reorder-functions",
"-fno-rerun-cse-after-loop",
"-fno-schedule-insns",
"-fno-schedule-insns2",
"-fno-sched-interblock",
"-fno-sched-spec",
"-fno-store-merging",
"-fno-strict-aliasing",
"-fno-thread-jumps",
"-fno-tree-builtin-call-dce",
"-fno-tree-pre",
"-fno-tree-switch-conversion",
"-fno-tree-tail-merge",
"-fno-tree-vrp" };
// the set of optimisations that get enabled between O2 and O3
const char* optimisations3[opt3] = { "-fno-gcse-after-reload",
"-fno-inline-functions",
"-fno-ipa-cp-clone",
"-fno-loop-interchange",
"-fno-loop-unroll-and-jam",
"-fno-peel-loops",
"-fno-predictive-commoning",
"-fno-split-paths",
"-fno-tree-loop-distribute-patterns",
"-fno-tree-loop-distribution",
"-fno-tree-loop-vectorize",
"-fno-tree-partial-pre",
"-fno-tree-slp-vectorize",
"-fno-unswitch-loops",
"-fno-vect-cost-model"
};
using namespace std;
int main(int argc, char* argv[])
{
int mode = -1; // O1 or O2?
if (argc !=3)
{
printf("Arguments: flag filename\n");
exit(-1);
}
else if (strcmp(argv[1], "O0") == 0)
{
mode = 1;
}
else if (strcmp(argv[1], "O1") == 0)
{
mode = 2;
}
else if (strcmp(argv[1], "O2") == 0)
{
mode = 3;
}
else
{
printf("Arguments: flag filename\n");
exit(-1);
}
if (mode == 1)
{
for (int i = 0; i <= opt1 * 1 - 1; i++)
{
system("g++ -S -o benchO0.s benchmark.cpp -O1");
string str = "g++";
str = str + " -S -o " + "benchO0F.s " + "benchmark.cpp -O1 " + optimisations[i % opt1];
const char* c = str.c_str();
system(c);
cerr << setw(37) << optimisations[i % opt1] << '\t';
system("diff -y --suppress-common-lines benchO0F.s benchO0.s | wc -l");
system("rm benchO0.s benchO0F.s");
}
}
else if (mode == 2)
{
for (int i = 0; i <= opt2 * 1 - 1; i++)
{
system("g++ -S -o benchO1.s benchmark.cpp -O1");
string str = "g++";
str = str + " -S -o " + "benchO1F.s " + "benchmark.cpp " + optimisations2[i % opt2];
const char* c = str.c_str();
system(c);
cerr << optimisations2[i % opt2] << '\t';
system("diff -y --suppress-common-lines benchO1F.s benchO1.s | wc -l");
system("rm benchO1.s benchO1F.s");
}
}
else if (mode == 3)
{
for (int i = 0; i <= opt3 * 1 - 1; i++)
{
system("g++ -S -o benchO2.s benchmark.cpp -O2");
string str = "g++";
str = str + " -S -o " + "benchO2F.s " + "benchmark.cpp " + optimisations3[i % opt3];
const char* c = str.c_str();
system(c);
cerr << optimisations3[i % opt3] << '\t';
system("diff -y --suppress-common-lines benchO2F.s benchO2.s | wc -l");
system("rm benchO2.s benchO2F.s");
}
}
return 0;
}
| [
"vishnu9145@hotmail.com"
] | vishnu9145@hotmail.com |
d4923ce4a68f2939f7c78febfe0417017631c91a | 40420e55ae2b25709872cac5bdf39fe250519922 | /RSAction/Source/RSAction/Public/Player/SoldierLocalPlayer.h | ad680b41f3fed19613515aaf056f7e40781e89e0 | [] | no_license | magrlemon/RSActionII | 2d85709f05d63f5b1c39038e9918f86989ff9e29 | 26ae7910afdedfdf353f6fbd98f3e4a92b21dc7f | refs/heads/master | 2020-12-01T19:26:07.617189 | 2020-05-13T13:41:45 | 2020-05-13T13:41:45 | 230,740,815 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 689 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "SoldierPersistentUser.h"
#include "SoldierLocalPlayer.generated.h"
UCLASS(config=Engine, transient)
class USoldierLocalPlayer : public ULocalPlayer
{
GENERATED_UCLASS_BODY()
public:
virtual void SetControllerId(int32 NewControllerId) override;
virtual FString GetNickname() const;
class USoldierPersistentUser* GetPersistentUser() const;
/** Initializes the PersistentUser */
void LoadPersistentUser();
private:
/** Persistent user data stored between sessions (i.e. the user's savegame) */
UPROPERTY()
class USoldierPersistentUser* PersistentUser;
};
| [
"magr_lemon@126.com"
] | magr_lemon@126.com |
6590a79029ca5db74f04abcc3e8e1b960dfda1eb | 188cfc9daeff499a2a74f16665fa4c48b2a0d1d6 | /ui/settings/settings_agents.h | 59fce99b0055ceb477d37a9289c86a997b9e4f61 | [] | no_license | H0RIA/Greuceanu | 2187fd520f311f3290e963dc2912fc7742522f35 | f83263dd9e8dc255c781135bb31399f5b46f8ece | refs/heads/master | 2021-01-13T17:31:39.680965 | 2017-09-26T15:28:06 | 2017-09-26T15:28:06 | 81,807,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | h | /*!
\legalese
Copyright 2017 Horia Popa
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.
\endlegalese
*/
#ifndef SETTINGS_AGENTS
#define SETTINGS_AGENTS
#include "base.h"
#include "settings_page.h"
namespace UI
{
namespace Settings
{
class Agents : public SettingsPage
{
Q_OBJECT
public:
Agents(QWidget* parent = nullptr);
};
}
}
#endif // SETTINGS_AGENTS
| [
"horia@live.com"
] | horia@live.com |
25441e75b9dc770109241b257faca9e6a381219b | 971713859cee54860e32dce538a7d5e796487c68 | /unisim/unisim_lib/unisim/component/cxx/pci/ide/pci_master.hh | 840084ef0e546c17adb2432b38a58480b6df630b | [] | no_license | binsec/cav2021-artifacts | 3d790f1e067d1ca9c4123010e3af522b85703e54 | ab9e387122968f827f7d4df696c2ca3d56229594 | refs/heads/main | 2023-04-15T17:10:10.228821 | 2021-04-26T15:10:20 | 2021-04-26T15:10:20 | 361,684,640 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | hh | /*
* Copyright (c) 2007,
* Universitat Politecnica de Catalunya (UPC)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of UPC nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Paula Casero (pcasero@upc.edu), Alejandro Schenzle (schenzle@upc.edu)
*/
#ifndef __UNISIM_COMPONENT_CXX_PCI_IDE_PCI_MASTER_HH__
#define __UNISIM_COMPONENT_CXX_PCI_IDE_PCI_MASTER_HH__
namespace unisim {
namespace component {
namespace cxx {
namespace pci {
namespace ide {
template <class ADDRESS_TYPE>
class PCIMaster {
public:
virtual bool dmaRead(ADDRESS_TYPE addr, int len, uint8_t *data) = 0;
virtual bool dmaWrite(ADDRESS_TYPE addr, int len, const uint8_t *data) = 0;
virtual void postInt(int irqId) = 0;
virtual void clearInt(int irqId) = 0;
virtual void notify() = 0;
};
} // end of namespace ide
} // end of namespace pci
} // end of namespace cxx
} // end of namespace component
} // end of namespace unisim
#endif
| [
"guillaume.girol@cea.fr"
] | guillaume.girol@cea.fr |
9f024f77eb880d5ae011b78ca83f9df696071214 | ea585d086b5b7fd36fa038fdcdab0d681dfe0cee | /projetprog/EXP10/general/Vecteur3D.hpp | 84039992b6a04d201caf44b1192ff73c1ecd9d4f | [] | no_license | hildes/Grain-Simulation | 86d71a344d0958f9f84dc22461593e79d7a41f6a | 36b52eeb940e499ca873c0413dc9b726d1e48914 | refs/heads/master | 2023-04-15T18:32:59.319881 | 2023-03-15T21:44:23 | 2023-03-15T21:44:23 | 162,279,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,067 | hpp | //
// Vecteur3D.hpp
// Vecteur3D
//
// Created by alex bonell on 8/3/17.
// Copyright © 2017 alex bonell. All rights reserved.
//
#ifndef Vecteur3D_hpp
#define Vecteur3D_hpp
#include<array>
class Vecteur3D{
public:
//Constructeurs
Vecteur3D(double x=0.0, double y=0.0, double z=0.0);
~Vecteur3D(); //provoque une erreur Undefined symbols for architecture x86_64: "Vecteur3D::~Vecteur3D()", referenced from:
//Methodes
double getCoord_x() const;
double getCoord_y() const;
double getCoord_z() const;
void set_coord(size_t position, double coordonnee );
void affiche(std::ostream& out) const;
bool compare(Vecteur3D vecteur) const;
Vecteur3D oppose() const;
Vecteur3D mult(double scalaire) const;
double norme() const;
double norme2() const;
double produitScalaire( Vecteur3D autre) const;
Vecteur3D produitVectoriel(Vecteur3D autre) const;
const Vecteur3D& normalise();
//Operator interne
Vecteur3D& operator *=(double const & scalar);
bool operator==(Vecteur3D const& autre) const; //utilise compare
bool operator != (Vecteur3D const & autre) const;
Vecteur3D& operator+=(Vecteur3D const& autre);
Vecteur3D& operator-=(Vecteur3D const& autre);
Vecteur3D& operator^=(Vecteur3D const& autre);
Vecteur3D& operator-() ;
private:
std::array<double,3> coordonnees;
};
//Operateur externe
const Vecteur3D operator*(Vecteur3D const& x, double autre);
const Vecteur3D operator*(double autre, Vecteur3D const& x) ;
const double operator*(Vecteur3D x, Vecteur3D const& y);
std::ostream& operator<<(std::ostream& sortie, Vecteur3D const& v) ;
const Vecteur3D operator+(Vecteur3D x, Vecteur3D const& y); //utilise addition
const Vecteur3D operator-(Vecteur3D x,Vecteur3D const& y); //utilise soustraction
const Vecteur3D operator^(Vecteur3D x, const Vecteur3D& autre);
#endif /* Vecteur3D_hpp */
| [
"stanislas.hildebrandt@epfl.ch"
] | stanislas.hildebrandt@epfl.ch |
8f6be199e5fdc6409df96661effb20762dbf193c | 2f874d5907ad0e95a2285ffc3592b8f75ecca7cd | /src/ripple/validators/impl/Manager.cpp | e0b0b3b958b5d1e97e1ff5c5daa8b3dedb087cbd | [
"MIT-Wu",
"MIT",
"ISC",
"BSL-1.0"
] | permissive | dzcoin/DzCoinService | fb93809a37fad0a26bf26189266b44cf4c797865 | b0056717d6bcc1741f4fb3f3f166cd8ce78393f9 | refs/heads/master | 2021-01-20T20:28:41.639585 | 2016-08-15T06:21:51 | 2016-08-15T06:21:51 | 65,678,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,386 | cpp | //------------------------------------------------------------------------------
/*
this file is part of rippled: https://github.com/ripple/rippled
copyright (c) 2012, 2013 ripple labs inc.
permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
the software is provided "as is" and the author disclaims all warranties
with regard to this software including all implied warranties of
merchantability and fitness. in no event shall the author be liable for
any special , direct, indirect, or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether in an
action of contract, negligence or other tortious action, arising out of
or in connection with the use or performance of this software.
*/
//==============================================================================
#include <beastconfig.h>
#include <ripple/validators/manager.h>
#include <ripple/validators/make_manager.h>
#include <ripple/validators/impl/connectionimp.h>
#include <ripple/validators/impl/logic.h>
#include <ripple/validators/impl/storesqdb.h>
#include <beast/asio/placeholders.h>
#include <beast/asio/waitable_executor.h>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <beast/cxx14/memory.h> // <memory>
/** chosenvalidators (formerly known as unl)
motivation:
to protect the integrity of the shared ledger data structure, validators
independently sign ledgerhash objects with their ripplepublickey. these
signed validations are propagated through the peer to peer network so
that other nodes may inspect them. every peer and client on the network
gains confidence in a ledger and its associated chain of previous ledgers
by maintaining a suitably sized list of validator public keys that it
trusts.
the most important factors in choosing validators for a chosenvalidators
list (the name we will use to designate such a list) are the following:
- that different validators are not controlled by one entity
- that each validator participates in a majority of ledgers
- that a validator does not sign ledgers which fail consensus
this module maintains chosenvalidators list. the list is built from a set
of independent source objects, which may come from the configuration file,
a separate file, a url from some trusted domain, or from the network itself.
in order that rippled administrators may publish their chosenvalidators
list at a url on a trusted domain that they own, this module compiles
statistics on ledgers signed by validators and stores them in a database.
from this database reports and alerts may be generated so that up-to-date
information about the health of the set of chosenvalidators is always
availabile.
in addition to the automated statistics provided by the module, it is
expected that organizations and meta-organizations will form from
stakeholders such as gateways who publish their own lists and provide
"best practices" to further refine the quality of validators placed into
chosenvalidators list.
----------------------------------------------------------------------------
unorganized notes:
david:
maybe oc should have a url that you can query to get the latest list of uri's
for oc-approved organzations that publish lists of validators. the server and
client can ship with that master trust url and also the list of uri's at the
time it's released, in case for some reason it can't pull from oc. that would
make the default installation safe even against major changes in the
organizations that publish validator lists.
the difference is that if an organization that provides lists of validators
goes rogue, administrators don't have to act.
todo:
write up from end-user perspective on the deployment and administration
of this feature, on the wiki. "draft" or "propose" to mark it as provisional.
template: https://ripple.com/wiki/federation_protocol
- what to do if you're a publisher of validatorlist
- what to do if you're a rippled administrator
- overview of how chosenvalidators works
goals:
make default configuration of rippled secure.
* ship with trustedurilist
* also have a preset rankedvalidators
eliminate administrative burden of maintaining
produce the chosenvalidators list.
allow quantitative analysis of network health.
what determines that a validator is good?
- are they present (i.e. sending validations)
- are they on the consensus ledger
- what percentage of consensus rounds do they participate in
- are they stalling consensus
* measurements of constructive/destructive behavior is
calculated in units of percentage of ledgers for which
the behavior is measured.
what we want from the unique node list:
- some number of trusted roots (known by domain)
probably organizations whose job is to provide a list of validators
- we imagine the irga for example would establish some group whose job is to
maintain a list of validators. there would be a public list of criteria
that they would use to vet the validator. things like:
* not anonymous
* registered business
* physical location
* agree not to cease operations without notice / arbitrarily
* responsive to complaints
- identifiable jurisdiction
* homogeneity in the jurisdiction is a business risk
* if all validators are in the same jurisdiction this is a business risk
- opencoin sets criteria for the organizations
- rippled will ship with a list of trusted root "certificates"
in other words this is a list of trusted domains from which the software
can contact each trusted root and retrieve a list of "good" validators
and then do something with that information
- all the validation information would be public, including the broadcast
messages.
- the goal is to easily identify bad actors and assess network health
* malicious intent
* or, just hardware problems (faulty drive or memory)
*/
#include <ripple/core/jobqueue.h>
#include <memory>
namespace ripple {
/** executor which dispatches to jobqueue threads at a given jobtype. */
class job_executor
{
private:
struct impl
{
impl (jobqueue& ex_, jobtype type_, std::string const& name_)
: ex(ex_), type(type_), name(name_)
{
}
jobqueue& ex;
jobtype type;
std::string name;
};
std::shared_ptr<impl> impl_;
public:
job_executor (jobtype type, std::string const& name,
jobqueue& ex)
: impl_(std::make_shared<impl>(ex, type, name))
{
}
template <class handler>
void
post (handler&& handler)
{
impl_->ex.addjob(impl_->type, impl_->name,
std::forward<handler>(handler));
}
template <class handler>
void
dispatch (handler&& handler)
{
impl_->ex.addjob(impl_->type, impl_->name,
std::forward<handler>(handler));
}
template <class handler>
void
defer (handler&& handler)
{
impl_->ex.addjob(impl_->type, impl_->name,
std::forward<handler>(handler));
}
};
//------------------------------------------------------------------------------
namespace validators {
// template <class executor>
class managerimp
: public manager
, public beast::stoppable
{
public:
boost::asio::io_service& io_service_;
boost::asio::io_service::strand strand_;
beast::asio::waitable_executor exec_;
boost::asio::basic_waitable_timer<
std::chrono::steady_clock> timer_;
beast::journal journal_;
beast::file dbfile_;
storesqdb store_;
logic logic_;
managerimp (stoppable& parent, boost::asio::io_service& io_service,
beast::file const& pathtodbfileordirectory, beast::journal journal)
: stoppable ("validators::manager", parent)
, io_service_(io_service)
, strand_(io_service_)
, timer_(io_service_)
, journal_ (journal)
, dbfile_ (pathtodbfileordirectory)
, store_ (journal_)
, logic_ (store_, journal_)
{
if (dbfile_.isdirectory ())
dbfile_ = dbfile_.getchildfile("validators.sqlite");
}
~managerimp()
{
}
//--------------------------------------------------------------------------
//
// manager
//
//--------------------------------------------------------------------------
std::unique_ptr<connection>
newconnection (int id) override
{
return std::make_unique<connectionimp>(
id, logic_, get_seconds_clock());
}
void
onledgerclosed (ledgerindex index,
ledgerhash const& hash, ledgerhash const& parent) override
{
logic_.onledgerclosed (index, hash, parent);
}
//--------------------------------------------------------------------------
//
// stoppable
//
//--------------------------------------------------------------------------
void onprepare()
{
init();
}
void onstart()
{
}
void onstop()
{
boost::system::error_code ec;
timer_.cancel(ec);
logic_.stop();
exec_.async_wait([this]() { stopped(); });
}
//--------------------------------------------------------------------------
//
// propertystream
//
//--------------------------------------------------------------------------
void onwrite (beast::propertystream::map& map)
{
}
//--------------------------------------------------------------------------
//
// managerimp
//
//--------------------------------------------------------------------------
void init()
{
beast::error error (store_.open (dbfile_));
if (! error)
{
logic_.load ();
}
}
void
ontimer (boost::system::error_code ec)
{
if (ec)
{
if (ec != boost::asio::error::operation_aborted)
journal_.error <<
"ontimer: " << ec.message();
return;
}
logic_.ontimer();
timer_.expires_from_now(std::chrono::seconds(1), ec);
timer_.async_wait(strand_.wrap(exec_.wrap(
std::bind(&managerimp::ontimer, this,
beast::asio::placeholders::error))));
}
};
//------------------------------------------------------------------------------
manager::manager ()
: beast::propertystream::source ("validators")
{
}
std::unique_ptr<manager>
make_manager(beast::stoppable& parent,
boost::asio::io_service& io_service,
beast::file const& pathtodbfileordirectory,
beast::journal journal)
{
return std::make_unique<managerimp> (parent,
io_service, pathtodbfileordirectory, journal);
}
}
}
| [
"dzgrouphelp@foxmail.com"
] | dzgrouphelp@foxmail.com |
84a28e8bda6954730946db600fb80d33365b624f | 241117b2de0786b457f4728097f95b4701552e46 | /ch4/ex10.cpp | b763384e44f101e670b9ebc46160129a2d4ae91d | [] | no_license | verdastelo/schildt_beginners_guide_to_c- | 6a05f6f8c5eaa248ff9ebd50ba8a425f27d02f32 | d69e4c2a809d61afed480267ce42816eddd93855 | refs/heads/master | 2016-08-08T23:18:35.231991 | 2015-12-02T01:59:37 | 2015-12-02T01:59:37 | 45,785,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp | /*
This program looks up the square of a number
from a 2-D array.
*/
#include <iostream>
int main() {
int i = 0;
int square[10][2] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100},
};
std::cout << "Enter a number between 1 and 10: " << std::endl;
std::cin >> i;
for (int j = 0; j < 10; j++) {
if (square[j][0] == i) {
std::cout << "The square of "
<< i << " is "
<< square[j][1] << "." << std::endl;
}
}
return 0;
}
| [
"verda_stelo@hotmail.com"
] | verda_stelo@hotmail.com |
4d5dffdfb369bce8e93f442884817404f5786788 | 57ee4cbbca98a4802e138cd3c039a5532f4cc140 | /3rdparty/cryptopp/hex.cpp | ec09a05c32b46c541620bfc84496464d9f8ccbab | [
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | intel/umf | 8a9c27c5454b239e57253be0abfa0c69dcddf8ea | fa3db1ded78c80df5b3e0f02bab979a4abbeccdd | refs/heads/master | 2023-09-03T08:52:20.723979 | 2023-01-07T00:07:15 | 2023-01-07T00:07:15 | 39,856,779 | 14 | 8 | Apache-2.0 | 2019-07-03T19:34:13 | 2015-07-28T20:42:42 | C++ | UTF-8 | C++ | false | false | 1,193 | cpp | // hex.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "hex.h"
NAMESPACE_BEGIN(CryptoPP)
static const byte s_vecUpper[] = "0123456789ABCDEF";
static const byte s_vecLower[] = "0123456789abcdef";
void HexEncoder::IsolatedInitialize(const NameValuePairs ¶meters)
{
bool uppercase = parameters.GetValueWithDefault(Name::Uppercase(), true);
m_filter->Initialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::EncodingLookupArray(), uppercase ? &s_vecUpper[0] : &s_vecLower[0], false)(Name::Log2Base(), 4, true)));
}
void HexDecoder::IsolatedInitialize(const NameValuePairs ¶meters)
{
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::DecodingLookupArray(), GetDefaultDecodingLookupArray(), false)(Name::Log2Base(), 4, true)));
}
const int *HexDecoder::GetDefaultDecodingLookupArray()
{
static volatile bool s_initialized = false;
static int s_array[256];
if (!s_initialized)
{
InitializeDecodingLookupArray(s_array, s_vecUpper, 16, true);
s_initialized = true;
}
return s_array;
}
NAMESPACE_END
#endif
| [
"rostislav.vasilikhin@itseez.com"
] | rostislav.vasilikhin@itseez.com |
b93ff2b3632899711179492529528248e2c84eba | d29460c1caf20d506a8ee55ce4727b6f1b4f7a0e | /mathLib/Demo/turret.h | 22411016f22ae455f0bd4cb2cb32b54b04265179 | [] | no_license | Edacth/AIE-Assignments | aec58d03babdab255cfae03a0d19a35a00e4c19a | 79bbb76948006211d764aae0c7fef3949ea02e7f | refs/heads/master | 2020-04-01T03:26:33.278621 | 2019-03-06T22:58:54 | 2019-03-06T22:58:54 | 152,818,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | h | #pragma once
#include "raylib.h"
#undef PI
#include "transform2d.h"
#include "vec2.h"
class turret
{
public:
transform2d transform;
Texture2D texture;
turret();
turret(vec2 _localPos, Texture2D _texture);
void draw();
void update();
private:
};
| [
"cadeanderson99@gmail.com"
] | cadeanderson99@gmail.com |
1633d223d39684585fdd3ee144563422892d1756 | 90210d73ce2fff37dd086bf31f3a46eb0b741000 | /src/lib/base/objects/photo.cpp | cefbbb9affff63eb030ee11f1596e9052da1f77d | [] | no_license | SfietKonstantin/qfb | 0d8f7b53f45982a23cba98993bb2064d00b6ae8a | 24c743da91ac732601188ec1ff9cf9ac4d3e326d | refs/heads/master | 2021-01-25T08:43:30.142006 | 2013-02-01T13:25:44 | 2013-02-01T13:25:44 | 6,906,377 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,867 | cpp | /****************************************************************************************
* Copyright (C) 2013 Lucien XU <sfietkonstantin@free.fr> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
/**
* @file photo.cpp
* @brief Implementation of QFB::Photo
*/
#include "photo.h"
#include "private/helper_p.h"
#include "private/objectbase_p.h"
#include "private/object_creator_p.h"
namespace QFB
{
/**
* @internal
* @brief PHOTO_FROM_KEY
*/
static const char *PHOTO_FROM_KEY = "from";
/**
* @internal
* @brief PHOTO_ICON_KEY
*/
static const char *PHOTO_ICON_KEY = "icon";
/**
* @internal
* @brief PHOTO_PICTURE_KEY
*/
static const char *PHOTO_PICTURE_KEY = "picture";
/**
* @internal
* @brief PHOTO_SOURCE_KEY
*/
static const char *PHOTO_SOURCE_KEY = "source";
/**
* @internal
* @brief PHOTO_HEIGHT_KEY
*/
static const char *PHOTO_HEIGHT_KEY = "height";
/**
* @internal
* @brief PHOTO_WIDTH_KEY
*/
static const char *PHOTO_WIDTH_KEY = "width";
/**
* @internal
* @brief PHOTO_IMAGES_KEY
*/
static const char *PHOTO_IMAGES_KEY = "images";
/**
* @internal
* @brief PHOTO_LINK_KEY
*/
static const char *PHOTO_LINK_KEY = "link";
/**
* @internal
* @brief PHOTO_CREATED_TIME_KEY
*/
static const char *PHOTO_CREATED_TIME_KEY = "created_time";
/**
* @internal
* @brief PHOTO_UPDATED_TIME_KEY
*/
static const char *PHOTO_UPDATED_TIME_KEY = "updated_time";
/**
* @internal
* @brief PHOTO_POSITION_KEY
*/
static const char *PHOTO_POSITION_KEY = "position";
/**
* @internal
* @short Private class for QFB::Photo
*/
class PhotoPrivate: public ObjectBasePrivate
{
public:
/**
* @internal
* @short Default constructor
*/
explicit PhotoPrivate();
/**
* @internal
* @short From
*/
NamedObject * from;
/**
* @internal
* @short List of images
*/
QList<PhotoInformations *> images;
};
PhotoPrivate::PhotoPrivate():
ObjectBasePrivate()
{
}
////// End of private class //////
Photo::Photo(QObject *parent):
NamedObject(parent)
{
}
Photo::Photo(const QVariantMap propertiesMap, QObject *parent):
NamedObject(*(new PhotoPrivate), parent)
{
Q_D(Photo);
d->propertiesMap = propertiesMap;
// >>>>> custom object creation code
// TODO: check object creation
// It was done automatically by a script
// Create from
QVariantMap fromData = d->propertiesMap.take(PHOTO_FROM_KEY).toMap();
d->from = createObject<NamedObject>(fromData, this);
// Create images
QVariantList imagesData = d->propertiesMap.take(PHOTO_IMAGES_KEY).toList();
d->images = createList<PhotoInformations>(imagesData, this);
// <<<<< custom object creation code
}
NamedObject * Photo::from() const
{
Q_D(const Photo);
// >>>>> property from
return d->from;
// <<<<< property from
}
QString Photo::icon() const
{
Q_D(const Photo);
// >>>>> property icon
return d->propertiesMap.value(PHOTO_ICON_KEY).toString();
// <<<<< property icon
}
QString Photo::picture() const
{
Q_D(const Photo);
// >>>>> property picture
return d->propertiesMap.value(PHOTO_PICTURE_KEY).toString();
// <<<<< property picture
}
QUrl Photo::source() const
{
Q_D(const Photo);
// >>>>> property source
return parseUrl(d->propertiesMap.value(PHOTO_SOURCE_KEY).toString());
// <<<<< property source
}
int Photo::height() const
{
Q_D(const Photo);
// >>>>> property height
return d->propertiesMap.value(PHOTO_HEIGHT_KEY).toString().toInt();
// <<<<< property height
}
int Photo::width() const
{
Q_D(const Photo);
// >>>>> property width
return d->propertiesMap.value(PHOTO_WIDTH_KEY).toString().toInt();
// <<<<< property width
}
QList<PhotoInformations *> Photo::images() const
{
Q_D(const Photo);
// >>>>> property images
return d->images;
// <<<<< property images
}
QUrl Photo::link() const
{
Q_D(const Photo);
// >>>>> property link
return parseUrl(d->propertiesMap.value(PHOTO_LINK_KEY).toString());
// <<<<< property link
}
QDateTime Photo::createdTime() const
{
Q_D(const Photo);
// >>>>> property created_time
return d->propertiesMap.value(PHOTO_CREATED_TIME_KEY).toDateTime();
// <<<<< property created_time
}
QDateTime Photo::updatedTime() const
{
Q_D(const Photo);
// >>>>> property updated_time
return d->propertiesMap.value(PHOTO_UPDATED_TIME_KEY).toDateTime();
// <<<<< property updated_time
}
int Photo::position() const
{
Q_D(const Photo);
// >>>>> property position
return d->propertiesMap.value(PHOTO_POSITION_KEY).toString().toInt();
// <<<<< property position
}
// >>>>> custom source code
// <<<<< custom source code
}
| [
"sfietkonstantin@free.fr"
] | sfietkonstantin@free.fr |
2929d22a85ed76526a9a07785f3e933d2f6cb5d0 | ce9f7c31d0cca32e03029dada9f8d1cee522cd94 | /ActionGame/Game/Game/Back.h | d5b21408d1777fc7a883ee0f2472b646e645c9b3 | [] | no_license | triton03/triton03 | 0ddb7b0beab66ed94bbd852a9c7e83ccc807403f | e1e0facc9559238c586bcd856e09ce4883f01047 | refs/heads/master | 2021-01-12T12:25:47.672610 | 2017-01-18T05:41:18 | 2017-01-18T05:41:18 | 72,491,198 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 484 | h | #pragma once
class Back : public IGameObject {
CSkinModelData skinModelData; //スキンモデルデータ。
CSkinModel skinModel; //スキンモデル。
CAnimation animation; //アニメーション。
CLight light; //ライト。
CTexture normalMap;
public:
Back();
~Back(){}
void Init(const char* modelName);
void Start() override
{
}
void Update() override;
void Render(CRenderContext& renderContext) override;
private:
CQuaternion rotation;
}; | [
"a"
] | a |
fe5194872cb2b84fb7893302163dd5876ede3c14 | 45712bfe78ba4e66f5232a8dddd62d4ffa0a035d | /SmallGameboyEmulator/processor/instructions/i40_5f.cpp | dcb99a1ca191e66ffbf75fc7eef45eee0a0c0784 | [] | no_license | ToboterXP/SmallGameboyEmulator | fcedfbcd5f0069284d11e5ef8d0c9ef4b6bfa763 | 0adab4f5415345560bab12b3097c5771c9748fbf | refs/heads/master | 2020-09-30T23:23:48.333444 | 2019-12-11T14:53:02 | 2019-12-11T14:53:02 | 227,398,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | /*
* i40_5f.h
*
* Created on: 13.10.2019
* Author: Tobias
*/
#ifndef I40_5F_H_
#define I40_5F_H_
#include "i40_5f.h"
#include <cstdint>
#include <processor/Processor.h>
namespace proc {
int execute40_5f(uint8_t opcode, Processor * proc) {
switch (opcode) {
case 0x40: // ld b,b
return 1;
case 0x41: // ld b,c
proc->b = proc->c;
return 1;
case 0x42: //ld b,d
proc->b = proc->d;
return 1;
case 0x43: //ld b,e
proc->b = proc->e;
return 1;
case 0x44: //ld b,h
proc->b = proc->h;
return 1;
case 0x45: //ld b,l
proc->b = proc->l;
return 1;
case 0x46: //ld b,(hl)
proc->b = proc->memory->readMemory(proc->getHL());
return 2;
case 0x47: //ld b,a
proc->b = proc->a;
return 1;
case 0x48: //ld c,b
proc->c = proc->b;
return 1;
case 0x49: //ld c,c
return 1;
case 0x4a: //ld c,d
proc->c = proc->d;
return 1;
case 0x4b: //ld c,e
proc->c = proc->e;
return 1;
case 0x4c: //ld c,h
proc->c = proc->h;
return 1;
case 0x4d: //ld c,l
proc->c = proc->l;
return 1;
case 0x4e: //ld c,(hl)
proc->c = proc->memory->readMemory(proc->getHL());
return 2;
case 0x4f: //ld c,a
proc->c = proc->a;
return 1;
case 0x50: // ld d,b
proc->d = proc->b;
return 1;
case 0x51: // ld d,c
proc->d = proc->c;
return 1;
case 0x52: //ld d,d
return 1;
case 0x53: //ld d,e
proc->d = proc->e;
return 1;
case 0x54: //ld d,h
proc->d = proc->h;
return 1;
case 0x55: //ld d,l
proc->d = proc->l;
return 1;
case 0x56: //ld d,(hl)
proc->d = proc->memory->readMemory(proc->getHL());
return 2;
case 0x57: //ld d,a
proc->d = proc->a;
return 1;
case 0x58: //ld e,b
proc->e = proc->b;
return 1;
case 0x59: //ld e,c
proc->e = proc->c;
return 1;
case 0x5a: //ld e,d
proc->e = proc->d;
return 1;
case 0x5b: //ld e,e
return 1;
case 0x5c: //ld e,h
proc->e = proc->h;
return 1;
case 0x5d: //ld e,l
proc->e = proc->l;
return 1;
case 0x5e: //ld e,(hl)
proc->e = proc->memory->readMemory(proc->getHL());
return 2;
case 0x5f: //ld e,a
proc->e = proc->a;
return 1;
}
return 0;
}
}
#endif /* I40_5F_H_ */
| [
"55210408+ToboterXP@users.noreply.github.com"
] | 55210408+ToboterXP@users.noreply.github.com |
58297876f34c899b7689ef39d82b61c331a9aaf2 | bddbbe55b7bc38aad8b4d0a4644d6352674f88e1 | /hellocardboard-android/src/main/jni/hello_cardboard_app.cc | 299b8de6fe25a0f45cdb5371be464bc94f764b5e | [
"Apache-2.0",
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | keeprunning797/AlphaObject | 83c52c2861f2c8208c9c1129e946843018b661a0 | 4807867de5afcb845dfdec53f60c4b0d0d5bd58e | refs/heads/master | 2023-03-23T22:40:56.427862 | 2021-03-25T04:28:10 | 2021-03-25T04:28:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,627 | cc | /*
* Copyright 2019 Google LLC
*
* 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 "hello_cardboard_app.h"
#include "myLogic.h"
namespace ndk_hello_cardboard {
namespace {
// The objects are about 1 meter in radius, so the min/max target distance are
// set so that the objects are always within the room (which is about 5 meters
// across) and the reticle is always closer than any objects.
constexpr float kMinTargetDistance = 2.5f;
constexpr float kMaxTargetDistance = 3.5f;
constexpr float kMinTargetHeight = 0.5f;
constexpr float kMaxTargetHeight = kMinTargetHeight + 3.0f;
constexpr float kDefaultFloorHeight = -1.7f;
constexpr uint64_t kPredictionTimeWithoutVsyncNanos = 50000000;
// Angle threshold for determining whether the controller is pointing at the
// object.
constexpr float kAngleLimit = 0.2f;
// Number of different possible targets
constexpr int kTargetMeshCount = 3;
float angle = 5.0f;
float angle_cat = 5.0f;
// Simple shaders to render .obj files without any lighting.
constexpr const char* kObjVertexShader =
R"glsl(
uniform mat4 u_MVP;
attribute vec4 a_Position;
attribute vec2 a_UV;
varying vec2 v_UV;
void main() {
v_UV = a_UV;
gl_Position = u_MVP * a_Position;
})glsl";
constexpr const char* kObjFragmentShader =
R"glsl(
precision mediump float;
uniform sampler2D u_Texture;
varying vec2 v_UV;
void main() {
// The y coordinate of this sample's textures is reversed compared to
// what OpenGL expects, so we invert the y coordinate.
gl_FragColor = texture2D(u_Texture, vec2(v_UV.x, 1.0 - v_UV.y));
})glsl";
//⭐️❤️🌈 XION
constexpr constexpr char* xObjectVertexShader =
R"glsl(
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
out vec2 TexCoords;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
gl_Position = projection * view * model * vec4(aPos, 1.0);
TexCoords = aTexCoords;
}
)glsl";
constexpr constexpr char* xObjectFragmentShader =
R"glsl(
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D texture_diffuse1;
void main() {
FragColor = texture(texture_diffuse1, TexCoords);
}
)glsl";
} // anonymous namespace
HelloCardboardApp::HelloCardboardApp(JavaVM* vm, jobject obj, jobject asset_mgr_obj)
: head_tracker_(nullptr),
lens_distortion_(nullptr),
distortion_renderer_(nullptr),
screen_params_changed_(false),
device_params_changed_(false),
screen_width_(0),
screen_height_(0),
depthRenderBuffer_(0),
framebuffer_(0),
texture_(0),
obj_program_(0),
obj_position_param_(0),
obj_uv_param_(0),
obj_modelview_projection_param_(0),
target_object_meshes_(kTargetMeshCount),
target_object_not_selected_textures_(kTargetMeshCount),
target_object_selected_textures_(kTargetMeshCount),
cur_target_object_(RandomUniformInt(kTargetMeshCount)) {
JNIEnv* env;
vm->GetEnv((void**)&env, JNI_VERSION_1_6);
java_asset_mgr_ = env->NewGlobalRef(asset_mgr_obj);
asset_mgr_ = AAssetManager_fromJava(env, asset_mgr_obj);
Cardboard_initializeAndroid(vm, obj);
head_tracker_ = CardboardHeadTracker_create();
}
HelloCardboardApp::~HelloCardboardApp() {
CardboardHeadTracker_destroy(head_tracker_);
CardboardLensDistortion_destroy(lens_distortion_);
CardboardDistortionRenderer_destroy(distortion_renderer_);
}
void HelloCardboardApp::OnSurfaceCreated(JNIEnv* env) {
const int obj_vertex_shader =
LoadGLShader(GL_VERTEX_SHADER, kObjVertexShader);
const int obj_fragment_shader =
LoadGLShader(GL_FRAGMENT_SHADER, kObjFragmentShader);
obj_program_ = glCreateProgram();
glAttachShader(obj_program_, obj_vertex_shader);
glAttachShader(obj_program_, obj_fragment_shader);
glLinkProgram(obj_program_);
glUseProgram(obj_program_);
CHECKGLERROR("Obj program");
obj_position_param_ = glGetAttribLocation(obj_program_, "a_Position");
obj_uv_param_ = glGetAttribLocation(obj_program_, "a_UV");
obj_modelview_projection_param_ = glGetUniformLocation(obj_program_, "u_MVP");
CHECKGLERROR("Obj program params");
HELLOCARDBOARD_CHECK(room_.Initialize(env, asset_mgr_, "CubeRoom.obj",
obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(
room_tex_.Initialize(env, java_asset_mgr_, "CubeRoom_BakedDiffuse.png"));
/*
*
*
*/
HELLOCARDBOARD_CHECK(dog_.Initialize(env, asset_mgr_, "dog.obj",
obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(dog_tex_.Initialize(env, java_asset_mgr_, "dog_diffuse.png"));
HELLOCARDBOARD_CHECK(cat_.Initialize(env, asset_mgr_, "cat.obj",
obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(cat_tex_.Initialize(env, java_asset_mgr_, "cat_diffuse.png"));
HELLOCARDBOARD_CHECK(alpha_.Initialize(env, asset_mgr_, "QuadSphere.obj",
obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(alpha_tex_.Initialize(env, java_asset_mgr_, "sky.png"));
HELLOCARDBOARD_CHECK(target_object_meshes_[0].Initialize(
env, asset_mgr_, "Icosahedron.obj", obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(target_object_not_selected_textures_[0].Initialize(
env, java_asset_mgr_, "Icosahedron_Blue_BakedDiffuse.png"));
HELLOCARDBOARD_CHECK(target_object_selected_textures_[0].Initialize(
env, java_asset_mgr_, "Icosahedron_Pink_BakedDiffuse.png"));
HELLOCARDBOARD_CHECK(target_object_meshes_[1].Initialize(
env, asset_mgr_, "QuadSphere.obj", obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(target_object_not_selected_textures_[1].Initialize(
env, java_asset_mgr_, "QuadSphere_Blue_BakedDiffuse.png"));
HELLOCARDBOARD_CHECK(target_object_selected_textures_[1].Initialize(
env, java_asset_mgr_, "QuadSphere_Pink_BakedDiffuse.png"));
HELLOCARDBOARD_CHECK(target_object_meshes_[2].Initialize(
env, asset_mgr_, "TriSphere.obj", obj_position_param_, obj_uv_param_));
HELLOCARDBOARD_CHECK(target_object_not_selected_textures_[2].Initialize(
env, java_asset_mgr_, "TriSphere_Blue_BakedDiffuse.png"));
HELLOCARDBOARD_CHECK(target_object_selected_textures_[2].Initialize(
env, java_asset_mgr_, "TriSphere_Pink_BakedDiffuse.png"));
// Target object first appears directly in front of user.
model_target_ = GetTranslationMatrix({1.0f, 1.5f, kMinTargetDistance});
model_dog_ = GetTranslationMatrix({1.0f, kDefaultFloorHeight - 0.01f , 1.0f - kMaxTargetDistance});
model_cat_ = GetTranslationMatrix({1.0f, kDefaultFloorHeight, 1.0f - kMaxTargetDistance});
model_alpha_ = GetTranslationMatrix({1.0f, 1.5f, kMaxTargetDistance});
CHECKGLERROR("OnSurfaceCreated");
}
void HelloCardboardApp::SetScreenParams(int width, int height) {
screen_width_ = width;
screen_height_ = height;
screen_params_changed_ = true;
}
void HelloCardboardApp::OnDrawFrame() {
if (!UpdateDeviceParams()) {
return;
}
// Update Head Pose.
head_view_ = GetPose();
// Incorporate the floor height into the head_view
head_view_ =
head_view_ * GetTranslationMatrix({0.0f, kDefaultFloorHeight, 0.0f});
head_view_dog_ =
head_view_ * GetTranslationMatrix({0.0f, kDefaultFloorHeight + 1.66f, -3.0f});
head_view_cat_ =
head_view_ * GetTranslationMatrix({-1.7f, kDefaultFloorHeight + 1.66f, -3.0f});
head_view_alpha_ =
head_view_ * GetTranslationMatrix({1.0f, 2.0f, -1.0f});
//⭐️❤️🌈
angle += 0.7f;
if(angle_cat > 5.0f) angle_cat+=0.7f;
else if(angle_cat < 10.1f) angle_cat -=0.7f;
auto mat = model_dog_.m;
LOGD("(BEFORE)XION_START");
for(int i = 0;i < 4;++i) {
std::string str = "XION__\n\n" +
std::to_string(mat[i][0]) + ",\t" +
std::to_string(mat[i][1]) + ",\t"+
std::to_string(mat[i][2]) + ",\t"+
std::to_string(mat[i][3]) + ",\t" + "\n\n";
LOGD("%d|%s",i,str.c_str());
}
LOGD("(BEFORE)XION_END");
RotateX(model_dog_, angle, 0.0f, 1.0f, 0.0f);
RotateXX(model_cat_, angle_cat, 0.0f, 1.0f, 0.0f);
RotateX(model_alpha_, angle_cat, 0.0f, 1.0f, 0.0f);
LOGD("???|%f",angle);
mat = model_dog_.m;
LOGD("XION_START");
for(int i = 0;i < 4;++i) {
std::string str = "XION__\n\n" +
std::to_string(mat[i][0]) + ",\t" +
std::to_string(mat[i][1]) + ",\t"+
std::to_string(mat[i][2]) + ",\t"+
std::to_string(mat[i][3]) + ",\t" + "\n\n";
LOGD("%d|%s",i,str.c_str());
}
LOGD("XION_END");
//⭐️❤️🌈
// Bind buffer
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDisable(GL_SCISSOR_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw eyes views
for (int eye = 0; eye < 2; ++eye) {
glViewport(eye == kLeft ? 0 : screen_width_ / 2, 0, screen_width_ / 2,
screen_height_);
Matrix4x4 eye_matrix = GetMatrixFromGlArray(eye_matrices_[eye]);
Matrix4x4 eye_view = eye_matrix * head_view_;
/*
*
*/
Matrix4x4 eye_view_dog = eye_matrix * head_view_dog_;
Matrix4x4 eye_view_cat = eye_matrix * head_view_cat_;
Matrix4x4 eye_view_alpha = eye_matrix * head_view_alpha_;
Matrix4x4 projection_matrix =
GetMatrixFromGlArray(projection_matrices_[eye]);
Matrix4x4 modelview_target = eye_view * model_target_;
Matrix4x4 modelview_dog_ = eye_view_dog * model_dog_;
Matrix4x4 modelview_cat_ = eye_view_cat * model_cat_;
Matrix4x4 modelview_alpha_ = eye_view_alpha * model_alpha_;
auto mat = modelview_target.m;
// LOGD("(BEFORE)XION_START");
// for(int i = 0;i < 4;++i) {
// std::string str = "XION__\n\n" +
// std::to_string(mat[i][0]) + ",\t" +
// std::to_string(mat[i][1]) + ",\t"+
// std::to_string(mat[i][2]) + ",\t"+
// std::to_string(mat[i][3]) + ",\t" + "\n\n";
// LOGD("%d|%s",i,str.c_str());
// }
// LOGD("(BEFORE)XION_END");
const float SCALE_SIZE = 2.0f;
const float SCALE_SIZE_DOG = 0.025f;
const float SCALE_SIZE_ALPHA = 0.55f;
// 🌈️️ Dog Model Scaling and Logging
ScaleXX(modelview_target, SCALE_SIZE);
ScaleXX(modelview_dog_,SCALE_SIZE_DOG);
ScaleXX(modelview_cat_,SCALE_SIZE_DOG);
ScaleXX(modelview_alpha_, SCALE_SIZE_ALPHA);
//ScaleX(matrix, SCALE_SIZE, SCALE_SIZE, SCALE_SIZE);
// 🌈️️ Dog Model Scaling and Logging
// for(int i = 0;i < 4; ++i){
// const float SCALE_SIZE = 3.0f;
// ScaleM(modelview_dog_.m[i], SCALE_SIZE, SCALE_SIZE, SCALE_SIZE );
// LOGD("DOG____________________________START");
// for(int j = 0; j < 4; ++j)
// LOGD("DOG_%d|%d|%f",i,j,modelview_dog_.m[i][j]);
// LOGD("DOG___%d",i);
// LOGD("DOG____________________________END");
// }
modelview_projection_target_ = projection_matrix * modelview_target;
modelview_projection_room_ = projection_matrix * eye_view;
modelview_projection_dog_ = projection_matrix * modelview_dog_;
modelview_projection_cat_ = projection_matrix * modelview_cat_;
modelview_projection_alpha_ = projection_matrix * modelview_alpha_;
// Draw room and target
DrawWorld();
LOGD("DRAW");
}
// Render
CardboardDistortionRenderer_renderEyeToDisplay(
distortion_renderer_, /* target_display = */ 0, /* x = */ 0, /* y = */ 0,
screen_width_, screen_height_, &left_eye_texture_description_,
&right_eye_texture_description_);
CHECKGLERROR("onDrawFrame");
}
void HelloCardboardApp::OnTriggerEvent() {
if (IsPointingAtTarget()) {
HideTarget();
}
}
void HelloCardboardApp::OnPause() { CardboardHeadTracker_pause(head_tracker_); }
void HelloCardboardApp::OnResume() {
CardboardHeadTracker_resume(head_tracker_);
// Parameters may have changed.
device_params_changed_ = true;
// Check for device parameters existence in external storage. If they're
// missing, we must scan a Cardboard QR code and save the obtained parameters.
uint8_t* buffer;
int size;
CardboardQrCode_getSavedDeviceParams(&buffer, &size);
if (size == 0) {
SwitchViewer();
}
CardboardQrCode_destroy(buffer);
}
void HelloCardboardApp::SwitchViewer() {
CardboardQrCode_scanQrCodeAndSaveDeviceParams();
}
bool HelloCardboardApp::UpdateDeviceParams() {
// Checks if screen or device parameters changed
if (!screen_params_changed_ && !device_params_changed_) {
return true;
}
// Get saved device parameters
uint8_t* buffer;
int size;
CardboardQrCode_getSavedDeviceParams(&buffer, &size);
// If there are no parameters saved yet, returns false.
if (size == 0) {
return false;
}
CardboardLensDistortion_destroy(lens_distortion_);
lens_distortion_ = CardboardLensDistortion_create(
buffer, size, screen_width_, screen_height_);
CardboardQrCode_destroy(buffer);
GlSetup();
CardboardDistortionRenderer_destroy(distortion_renderer_);
distortion_renderer_ = CardboardOpenGlEs2DistortionRenderer_create();
CardboardMesh left_mesh;
CardboardMesh right_mesh;
CardboardLensDistortion_getDistortionMesh(lens_distortion_, kLeft,
&left_mesh);
CardboardLensDistortion_getDistortionMesh(lens_distortion_, kRight,
&right_mesh);
CardboardDistortionRenderer_setMesh(distortion_renderer_, &left_mesh, kLeft);
CardboardDistortionRenderer_setMesh(distortion_renderer_, &right_mesh,
kRight);
// Get eye matrices
CardboardLensDistortion_getEyeFromHeadMatrix(
lens_distortion_, kLeft, eye_matrices_[0]);
CardboardLensDistortion_getEyeFromHeadMatrix(
lens_distortion_, kRight, eye_matrices_[1]);
CardboardLensDistortion_getProjectionMatrix(
lens_distortion_, kLeft, kZNear, kZFar, projection_matrices_[0]);
CardboardLensDistortion_getProjectionMatrix(
lens_distortion_, kRight, kZNear, kZFar, projection_matrices_[1]);
screen_params_changed_ = false;
device_params_changed_ = false;
CHECKGLERROR("UpdateDeviceParams");
return true;
}
void HelloCardboardApp::GlSetup() {
LOGD("GL SETUP");
if (framebuffer_ != 0) {
GlTeardown();
}
// Create render texture.
glGenTextures(1, &texture_);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, screen_width_, screen_height_, 0,
GL_RGB, GL_UNSIGNED_BYTE, 0);
left_eye_texture_description_.texture = texture_;
left_eye_texture_description_.left_u = 0;
left_eye_texture_description_.right_u = 0.5;
left_eye_texture_description_.top_v = 1;
left_eye_texture_description_.bottom_v = 0;
right_eye_texture_description_.texture = texture_;
right_eye_texture_description_.left_u = 0.5;
right_eye_texture_description_.right_u = 1;
right_eye_texture_description_.top_v = 1;
right_eye_texture_description_.bottom_v = 0;
// Generate depth buffer to perform depth test.
glGenRenderbuffers(1, &depthRenderBuffer_);
glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBuffer_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, screen_width_,
screen_height_);
CHECKGLERROR("Create Render buffer");
// Create render target.
glGenFramebuffers(1, &framebuffer_);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
texture_, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, depthRenderBuffer_);
CHECKGLERROR("GlSetup");
}
void HelloCardboardApp::GlTeardown() {
if (framebuffer_ == 0) {
return;
}
glDeleteRenderbuffers(1, &depthRenderBuffer_);
depthRenderBuffer_ = 0;
glDeleteFramebuffers(1, &framebuffer_);
framebuffer_ = 0;
glDeleteTextures(1, &texture_);
texture_ = 0;
CHECKGLERROR("GlTeardown");
}
Matrix4x4 HelloCardboardApp::GetPose() {
std::array<float, 4> out_orientation;
std::array<float, 3> out_position;
long monotonic_time_nano = GetMonotonicTimeNano();
monotonic_time_nano += kPredictionTimeWithoutVsyncNanos;
CardboardHeadTracker_getPose(head_tracker_, monotonic_time_nano,
&out_position[0], &out_orientation[0]);
return GetTranslationMatrix(out_position) *
Quatf::FromXYZW(&out_orientation[0]).ToMatrix();
}
void HelloCardboardApp::DrawWorld() {
DrawRoom();
DrawTarget();
DrawDog();
DrawCat();
DrawAlpha();
}
void HelloCardboardApp::DrawTarget() {
glUseProgram(obj_program_);
std::array<float, 16> target_array = modelview_projection_target_.ToGlArray();
glUniformMatrix4fv(obj_modelview_projection_param_, 1, GL_FALSE,
target_array.data());
if (IsPointingAtTarget()) {
target_object_selected_textures_[cur_target_object_].Bind();
} else {
target_object_not_selected_textures_[cur_target_object_].Bind();
}
target_object_meshes_[cur_target_object_].Draw();
CHECKGLERROR("DrawTarget");
}
void HelloCardboardApp::DrawRoom() {
glUseProgram(obj_program_);
std::array<float, 16> room_array = modelview_projection_room_.ToGlArray();
glUniformMatrix4fv(obj_modelview_projection_param_, 1, GL_FALSE,
room_array.data());
room_tex_.Bind();
room_.Draw();
CHECKGLERROR("DrawRoom");
}
/*
*
*
*/
void HelloCardboardApp::DrawDog() {
glUseProgram(obj_program_);
std::array<float, 16> dog_array = modelview_projection_dog_.ToGlArray();
glUniformMatrix4fv(obj_modelview_projection_param_, 1, GL_FALSE, dog_array.data());
dog_tex_.Bind();
dog_.Draw();
CHECKGLERROR("DrawDog");
}
void HelloCardboardApp::DrawCat() {
glUseProgram(obj_program_);
std::array<float, 16> cat_array = modelview_projection_cat_.ToGlArray();
glUniformMatrix4fv(obj_modelview_projection_param_, 1, GL_FALSE, cat_array.data());
cat_tex_.Bind();
cat_.Draw();
CHECKGLERROR("DrawCat");
}
void HelloCardboardApp::DrawAlpha() {
glUseProgram(obj_program_);
std::array<float, 16> alpha_array = modelview_projection_alpha_.ToGlArray();
glUniformMatrix4fv(obj_modelview_projection_param_, 1, GL_FALSE, alpha_array.data());
alpha_tex_.Bind();
alpha_.Draw();
CHECKGLERROR("DrawAlpha");
}
void HelloCardboardApp::HideTarget() {
cur_target_object_ = RandomUniformInt(kTargetMeshCount);
float angle = RandomUniformFloat(-M_PI, M_PI);
float distance = RandomUniformFloat(kMinTargetDistance, kMaxTargetDistance);
float height = RandomUniformFloat(kMinTargetHeight, kMaxTargetHeight);
std::array<float, 3> target_position = {std::cos(angle) * distance, height,
std::sin(angle) * distance};
model_target_ = GetTranslationMatrix(target_position);
}
bool HelloCardboardApp::IsPointingAtTarget() {
// Compute vectors pointing towards the reticle and towards the target object
// in head space.
Matrix4x4 head_from_target = head_view_ * model_target_;
const std::array<float, 4> unit_quaternion = {0.f, 0.f, 0.f, 1.f};
const std::array<float, 4> point_vector = {0.f, 0.f, -1.f, 0.f};
const std::array<float, 4> target_vector = head_from_target * unit_quaternion;
float angle = AngleBetweenVectors(point_vector, target_vector);
return angle < kAngleLimit;
}
} // namespace ndk_hello_cardboard
| [
"zion.h719@gmail.com"
] | zion.h719@gmail.com |
5869d674579fe22d929f8a31b932e708fc0c388e | dda0a106fea97cfbcfaf82bd77eaa4056a62b2df | /吉田学園情報ビジネス専門学校 早川樹綺也/00_制作ゲーム/01_BeanBird/00_プロジェクト/tutorial.cpp | a31e37289fb2cc3212455f7f5cd5c059a9cc8c8e | [] | no_license | JukiyaHayakawa-1225/Yoshidagakuen_HayakawaJukiya | 1b9c9a25fb3b1e707a61a27db84df0eca876c484 | 8d3f88fb7cd13f2a57b55e2eda782a8d93737a3f | refs/heads/master | 2020-08-14T15:05:41.388077 | 2019-10-15T02:37:10 | 2019-10-15T02:37:10 | 187,962,297 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,524 | cpp | //=============================================================================
//
// チュートリアルの処理 [tutorial.cpp]
// Author : Jukiya Hayakawa
//
//=============================================================================
#include "tutorial.h"
#include "scene.h"
#include "scene2D.h"
#include "renderer.h"
#include "input.h"
#include "manager.h"
#include "bg.h"
#include "fade.h"
#include "sound.h"
//=============================================================================
// 静的メンバ変数宣言
//=============================================================================
//=============================================================================
// チュートリアルのコンストラクタ
//=============================================================================
CTutorial::CTutorial()
{
}
//=============================================================================
// チュートリアルのデストラクタ
//=============================================================================
CTutorial::~CTutorial()
{
}
//=============================================================================
// チュートリアルの生成
//=============================================================================
CTutorial *CTutorial::Create()
{
CTutorial *pTutorial = NULL;
if (pTutorial == NULL)
{
pTutorial = new CTutorial;
if (pTutorial != NULL)
{
pTutorial->Init();
}
}
return pTutorial;
}
//=============================================================================
// チュートリアルの初期化処理
//=============================================================================
HRESULT CTutorial::Init(void)
{
m_counter = 0;
//背景の読み込み
CBgTutorial::Load();
//背景の生成
CBgTutorial::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), SCREEN_WIDTH / 2,SCREEN_HEIGHT / 2,CBgTutorial::BG_0);
//CBgTutorial::Create(D3DXVECTOR3(SCREEN_WIDTH + 640, SCREEN_HEIGHT / 2, 0.0f), SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, CBgTutorial::BG_1);
return S_OK;
}
//=============================================================================
// チュートリアルの終了処理
//=============================================================================
void CTutorial::Uninit(void)
{
//背景の破棄
CBgTutorial::Unload();
CScene::ReleaseAll();
}
//=============================================================================
// チュートリアルの更新処理
//=============================================================================
void CTutorial::Update(void)
{
//キーボードの取得
CInputKeyboard *pInputKeyboard;
pInputKeyboard = CManager::GetKeyboard();
//ジョイパッドの取得
CInputJoypad *pInputJoypad;
pInputJoypad = CManager::GetJoypad();
//サウンドの取得
CSound *pSound;
pSound = CManager::GetSound();
CBgTutorial *pTutorial = NULL;
if (pTutorial->GetTutorialState() == CBgTutorial::STATE_NOMAL &&
m_counter == 0)
{
if (pInputKeyboard->GetTrigger(DIK_D) == true||
pInputKeyboard->GetTrigger(DIK_RIGHT) == true||
pInputJoypad->GetTrigger(CInputJoypad::DIJS_BUTTON_LSTICK_RIGHT) == true ||
pInputJoypad->GetTrigger(CInputJoypad::DIJS_BUTTON_RIGHT) == true)
{
pSound->PlaySound(CSound::SOUND_LABEL_SE_SLIDE);
m_counter++;
CBgTutorial::SetTutorialState(CBgTutorial::STATE_MOVE);
}
}
else if (pTutorial->GetTutorialState() == CBgTutorial::STATE_NOMAL &&
m_counter == 1)
{
if (pInputKeyboard->GetTrigger(DIK_A) == true ||
pInputKeyboard->GetTrigger(DIK_LEFT) == true ||
pInputJoypad->GetTrigger(CInputJoypad::DIJS_BUTTON_LSTICK_LEFT) == true ||
pInputJoypad->GetTrigger(CInputJoypad::DIJS_BUTTON_LEFT) == true)
{
pSound->PlaySound(CSound::SOUND_LABEL_SE_SLIDE);
m_counter--;
CBgTutorial::SetTutorialState(CBgTutorial::STATE_REMOVE);
}
}
if (m_counter == 1)
{
if (pInputJoypad->GetTrigger(CInputJoypad::DIJS_BUTTON_START) == true ||
pInputKeyboard->GetTrigger(DIK_RETURN) == true)
{// JoyPadのボタンまたはENTERキーが押された場合]
pSound->PlaySound(CSound::SOUND_LABEL_SE_KETTEI);
CFade::Create(CManager::MODE_GAME, D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), SCREEN_WIDTH, SCREEN_HEIGHT);
}
}
}
//=============================================================================
// チュートリアルの描画処理
//=============================================================================
void CTutorial::Draw(void)
{
} | [
"jb2017029@stu.yoshida-g.ac.jp"
] | jb2017029@stu.yoshida-g.ac.jp |
f42428ad0d8f76ca4e47ea447d27166ff3864a50 | 3545fdd2d66d12ed57aa1070d8cd2d46b723186c | / darkbasicpro --username LeeBamberTGC/DarkGDK/Code/Source/DarkSDKWorld.cpp | d7a4da37f381c36744958ec6c5a1afe294f29d59 | [] | no_license | jnonline/darkbasicpro | 07e244af729c24ea992988104cc78ecaf78db14b | 401f77e0473de7b80bb3e8229c6317f375c77bb2 | refs/heads/master | 2021-01-23T05:45:15.708249 | 2013-12-30T03:08:59 | 2013-12-30T03:08:59 | 35,435,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,648 | cpp |
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// TEXT COMMANDS ////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES /////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "..\Include\DarkSDKWorld.h"
#include "..\Include\globstruct.h"
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERNAL DB PRO FUNCTIONS ////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void LoadEx ( SDK_LPSTR szFilename, SDK_LPSTR szMap );
void DeleteEx ( void );
void SetupCullingCameraEx ( int iID );
void SetupCameraCollision ( int iID, int iEntityID, float fRadius, int iResponse );
void SetupObjectCollision ( int iID, int iEntityID, float fRadius, int iResponse );
void SetCollisionThreshholdEx ( int iID, float fSensitivity );
void SetupCollisionOffEx ( int iID );
void SetCameraCollisionRadiusEx ( int iID, int iEntityID, float fX, float fY, float fZ );
void SetObjectCollisionRadiusEx ( int iID, int iEntityID, float fX, float fY, float fZ );
void SetCollisionHeightAdjustmentEx ( int iID, float fHeight );
void SetHardwareMultiTexturingOnEx ( void );
void SetHardwareMultiTexturingOffEx ( void );
void ProcessCollisionEx ( int iID );
int GetCollisionResponseEx ( int iID );
DWORD GetCollisionXEx ( int iID );
DWORD GetCollisionYEx ( int iID );
DWORD GetCollisionZEx ( int iID );
void ConstructorWorld ( HINSTANCE hSetup, HINSTANCE hImage, HINSTANCE hCamera, HINSTANCE hObject );
void DestructorWorld ( void );
void SetErrorHandlerWorld ( LPVOID pErrorHandlerPtr );
void PassCoreDataWorld ( LPVOID pGlobPtr );
void RefreshD3DWorld ( int iMode );
void UpdateBSP ( void );
void Delete ( void );
void StartBSP ( void );
void EndBSP ( void );
void EndWorld ( void );
bool Load ( char* szFilename, char* szMap );
void SetupCullingCamera ( int iID );
void UpdateEx ( void );
void StartEx ( void );
void EndEx ( void );
void SetupCameraCollisionEx ( int iID, int iEntityID, float fRadius, int iResponse );
void SetupObjectCollisionEx ( int iID, int iEntityID, float fRadius, int iResponse );
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// DARK SDK FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void dbUpdateBSP ( void )
{
UpdateBSP ( );
}
void dbStartBSP ( void )
{
StartBSP ( );
}
void dbEndBSP ( void )
{
EndBSP ( );
}
void dbLoadBSP ( char* szFilename, char* szMap )
{
LoadEx ( ( DWORD ) szFilename, ( DWORD ) szMap );
}
void dbDeleteBSP ( void )
{
DeleteEx ( );
}
void dbSetBSPCamera ( int iID )
{
SetupCullingCameraEx ( iID );
}
void dbSetBSPCameraCollision ( int iID, int iEntityID, float fRadius, int iResponse )
{
SetupCameraCollision ( iID, iEntityID, fRadius, iResponse );
}
void dbSetBSPObjectCollision ( int iID, int iEntityID, float fRadius, int iResponse )
{
SetupObjectCollision ( iID, iEntityID, fRadius, iResponse );
}
void dbSetBSPCollisionThreshhold ( int iID, float fSensitivity )
{
SetCollisionThreshholdEx ( iID, fSensitivity );
}
void dbSetBSPCollisionOff ( int iID )
{
SetupCollisionOffEx ( iID );
}
void dbSetBSPCameraCollisionRadius ( int iID, int iEntityID, float fX, float fY, float fZ )
{
SetCameraCollisionRadiusEx ( iID, iEntityID, fX, fY, fZ );
}
void dbSetBSPObjectCollisionRadius ( int iID, int iEntityID, float fX, float fY, float fZ )
{
SetObjectCollisionRadiusEx ( iID, iEntityID, fX, fY, fZ );
}
void dbSetBSPCollisionHeightAdjustment ( int iID, float fHeight )
{
SetCollisionHeightAdjustmentEx ( iID, fHeight );
}
void dbSetBSPMultiTexturingOn ( void )
{
SetHardwareMultiTexturingOnEx ( );
}
void dbSetBSPMultiTexturingOff ( void )
{
SetHardwareMultiTexturingOffEx ( );
}
void dbProcessBSPCollision ( int iID )
{
ProcessCollisionEx ( iID );
}
int dbBSPCollisionHit ( int iID )
{
return GetCollisionResponseEx ( iID );
}
float dbBSPCollisionX ( int iID )
{
DWORD dwReturn = GetCollisionXEx ( iID );
return *( float* ) &dwReturn;
}
float dbBSPCollisionY ( int iID )
{
DWORD dwReturn = GetCollisionYEx ( iID );
return *( float* ) &dwReturn;
}
float dbBSPCollisionZ ( int iID )
{
DWORD dwReturn = GetCollisionZEx ( iID );
return *( float* ) &dwReturn;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void dbConstructorWorld ( HINSTANCE hSetup, HINSTANCE hImage, HINSTANCE hCamera, HINSTANCE hObject )
{
ConstructorWorld ( hSetup, hImage, hCamera, hObject );
}
void dbDestructorWorld ( void )
{
DestructorWorld ( );
}
void dbSetErrorHandlerWorld ( LPVOID pErrorHandlerPtr )
{
SetErrorHandlerWorld ( pErrorHandlerPtr );
}
void dbPassCoreDataWorld( LPVOID pGlobPtr )
{
PassCoreDataWorld ( pGlobPtr );
}
void dbRefreshD3DWorld ( int iMode )
{
RefreshD3DWorld ( iMode );
}
/*
void dbUpdate ( void )
{
Update ( );
}
void dbDelete ( void )
{
Delete ( );
}
void dbStart ( void )
{
Start ( );
}
void dbEndWorld ( void )
{
End ( );
}
bool dbLoad ( char* szFilename, char* szMap )
{
return Load ( szFilename, szMap );
}
void dbSetupCullingCamera ( int iID )
{
SetupCullingCamera ( iID );
}
void dbUpdateEx ( void )
{
UpdateEx ( );
}
void dbStartEx ( void )
{
StartEx ( );
}
void dbEndEx ( void )
{
EndEx ( );
}
void dbSetupCameraCollisionEx ( int iID, int iEntityID, float fRadius, int iResponse )
{
SetupCameraCollisionEx ( iID, iEntityID, fRadius, iResponse );
}
void dbSetupObjectCollisionEx ( int iID, int iEntityID, float fRadius, int iResponse )
{
SetupObjectCollisionEx ( iID, iEntityID, fRadius, iResponse );
}
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////// | [
"LeeBamberTGC@0d003e0e-0b79-11df-bf12-379292acd595"
] | LeeBamberTGC@0d003e0e-0b79-11df-bf12-379292acd595 |
62c7d49d124cf5215257a2226712a3b6ef215c24 | ad5eaa9a33248f38884a5a5f0d52788afa2bc901 | /chrome/browser/apps/app_service/app_service_proxy.cc | 89b9ec3dcec604570baa7a417087d72a4e79312f | [
"BSD-3-Clause"
] | permissive | dwb420/chromium | 2cc203d9cff6d64ccb4a2cbcad0aaad0a6778b4f | 6147f4cea449793bef7d5a4496a47184e2867401 | refs/heads/master | 2023-01-09T17:35:18.799896 | 2019-11-13T20:32:27 | 2019-11-13T20:32:27 | 221,362,316 | 0 | 0 | BSD-3-Clause | 2019-11-13T03:13:37 | 2019-11-13T03:13:36 | null | UTF-8 | C++ | false | false | 18,118 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include <utility>
#include "base/bind.h"
#include "base/location.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/apps/app_service/app_icon_source.h"
#include "chrome/browser/apps/app_service/app_service_metrics.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/uninstall_dialog.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/services/app_service/app_service_impl.h"
#include "chrome/services/app_service/public/cpp/instance_registry.h"
#include "chrome/services/app_service/public/cpp/intent_filter_util.h"
#include "chrome/services/app_service/public/cpp/intent_util.h"
#include "chrome/services/app_service/public/mojom/types.mojom.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/url_data_source.h"
#include "url/url_constants.h"
namespace {
apps::mojom::IntentFilterPtr FindBestMatchingFilter(
const apps::mojom::IntentPtr& intent) {
// TODO(crbug.com/853604): Update the matching util method to return how well
// the match is instead of just bool. And return the best match here. At the
// moment just return the url filter itself.
apps::mojom::IntentFilterPtr intent_filter;
if (intent->scheme.has_value() && intent->host.has_value() &&
intent->path.has_value()) {
intent_filter = apps_util::CreateIntentFilterForUrlScope(
GURL(intent->scheme.value() + url::kStandardSchemeSeparator +
intent->host.value() + intent->path.value()));
}
return intent_filter;
}
} // namespace
namespace apps {
AppServiceProxy::InnerIconLoader::InnerIconLoader(AppServiceProxy* host)
: host_(host), overriding_icon_loader_for_testing_(nullptr) {}
apps::mojom::IconKeyPtr AppServiceProxy::InnerIconLoader::GetIconKey(
const std::string& app_id) {
if (overriding_icon_loader_for_testing_) {
return overriding_icon_loader_for_testing_->GetIconKey(app_id);
}
apps::mojom::IconKeyPtr icon_key;
if (host_->app_service_.is_connected()) {
host_->cache_.ForOneApp(app_id, [&icon_key](const apps::AppUpdate& update) {
icon_key = update.IconKey();
});
}
return icon_key;
}
std::unique_ptr<IconLoader::Releaser>
AppServiceProxy::InnerIconLoader::LoadIconFromIconKey(
apps::mojom::AppType app_type,
const std::string& app_id,
apps::mojom::IconKeyPtr icon_key,
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
apps::mojom::Publisher::LoadIconCallback callback) {
if (overriding_icon_loader_for_testing_) {
return overriding_icon_loader_for_testing_->LoadIconFromIconKey(
app_type, app_id, std::move(icon_key), icon_compression,
size_hint_in_dip, allow_placeholder_icon, std::move(callback));
}
if (host_->app_service_.is_connected() && icon_key) {
// TODO(crbug.com/826982): Mojo doesn't guarantee the order of messages,
// so multiple calls to this method might not resolve their callbacks in
// order. As per khmel@, "you may have race here, assume you publish change
// for the app and app requested new icon. But new icon is not delivered
// yet and you resolve old one instead. Now new icon arrives asynchronously
// but you no longer notify the app or do?"
host_->app_service_->LoadIcon(app_type, app_id, std::move(icon_key),
icon_compression, size_hint_in_dip,
allow_placeholder_icon, std::move(callback));
} else {
std::move(callback).Run(apps::mojom::IconValue::New());
}
return nullptr;
}
AppServiceProxy::AppServiceProxy(Profile* profile)
: inner_icon_loader_(this),
icon_coalescer_(&inner_icon_loader_),
outer_icon_loader_(&icon_coalescer_,
apps::IconCache::GarbageCollectionPolicy::kEager),
profile_(profile) {
Initialize();
}
AppServiceProxy::~AppServiceProxy() = default;
void AppServiceProxy::ReInitializeForTesting(Profile* profile) {
// Some test code creates a profile and profile-linked services, like the App
// Service, before the profile is fully initialized. Such tests can call this
// after full profile initialization to ensure the App Service implementation
// has all of profile state it needs.
app_service_.reset();
profile_ = profile;
Initialize();
}
void AppServiceProxy::Initialize() {
if (!profile_) {
return;
}
// We only initialize the App Service for regular or guest profiles. Non-guest
// off-the-record profiles do not get an instance.
if (profile_->IsOffTheRecord() && !profile_->IsGuestSession()) {
return;
}
app_service_impl_ = std::make_unique<apps::AppServiceImpl>(
content::BrowserContext::GetConnectorFor(profile_));
app_service_impl_->BindReceiver(app_service_.BindNewPipeAndPassReceiver());
if (app_service_.is_connected()) {
// The AppServiceProxy is a subscriber: something that wants to be able to
// list all known apps.
mojo::PendingRemote<apps::mojom::Subscriber> subscriber;
receivers_.Add(this, subscriber.InitWithNewPipeAndPassReceiver());
app_service_->RegisterSubscriber(std::move(subscriber), nullptr);
#if defined(OS_CHROMEOS)
// The AppServiceProxy is also a publisher, of a variety of app types. That
// responsibility isn't intrinsically part of the AppServiceProxy, but doing
// that here, for each such app type, is as good a place as any.
built_in_chrome_os_apps_ =
std::make_unique<BuiltInChromeOsApps>(app_service_, profile_);
crostini_apps_ = std::make_unique<CrostiniApps>(app_service_, profile_);
extension_apps_ = std::make_unique<ExtensionApps>(
app_service_, profile_, apps::mojom::AppType::kExtension);
extension_web_apps_ = std::make_unique<ExtensionApps>(
app_service_, profile_, apps::mojom::AppType::kWeb);
// Asynchronously add app icon source, so we don't do too much work in the
// constructor.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&AppServiceProxy::AddAppIconSource,
weak_ptr_factory_.GetWeakPtr(), profile_));
#endif // OS_CHROMEOS
}
}
mojo::Remote<apps::mojom::AppService>& AppServiceProxy::AppService() {
return app_service_;
}
apps::AppRegistryCache& AppServiceProxy::AppRegistryCache() {
return cache_;
}
#if defined(OS_CHROMEOS)
apps::InstanceRegistry& AppServiceProxy::InstanceRegistry() {
return instance_registry_;
}
#endif
apps::PreferredApps& AppServiceProxy::PreferredApps() {
return preferred_apps_;
}
apps::mojom::IconKeyPtr AppServiceProxy::GetIconKey(const std::string& app_id) {
return outer_icon_loader_.GetIconKey(app_id);
}
std::unique_ptr<apps::IconLoader::Releaser>
AppServiceProxy::LoadIconFromIconKey(
apps::mojom::AppType app_type,
const std::string& app_id,
apps::mojom::IconKeyPtr icon_key,
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
apps::mojom::Publisher::LoadIconCallback callback) {
return outer_icon_loader_.LoadIconFromIconKey(
app_type, app_id, std::move(icon_key), icon_compression, size_hint_in_dip,
allow_placeholder_icon, std::move(callback));
}
void AppServiceProxy::Launch(const std::string& app_id,
int32_t event_flags,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
if (app_service_.is_connected()) {
cache_.ForOneApp(app_id, [this, event_flags, launch_source,
display_id](const apps::AppUpdate& update) {
if (update.Paused() == apps::mojom::OptionalBool::kTrue) {
return;
}
RecordAppLaunch(update.AppId(), launch_source);
app_service_->Launch(update.AppType(), update.AppId(), event_flags,
launch_source, display_id);
});
}
}
void AppServiceProxy::LaunchAppWithIntent(
const std::string& app_id,
apps::mojom::IntentPtr intent,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
if (app_service_.is_connected()) {
cache_.ForOneApp(app_id, [this, &intent, launch_source,
display_id](const apps::AppUpdate& update) {
if (update.Paused() == apps::mojom::OptionalBool::kTrue) {
return;
}
RecordAppLaunch(update.AppId(), launch_source);
app_service_->LaunchAppWithIntent(update.AppType(), update.AppId(),
std::move(intent), launch_source,
display_id);
});
}
}
void AppServiceProxy::LaunchAppWithUrl(const std::string& app_id,
GURL url,
apps::mojom::LaunchSource launch_source,
int64_t display_id) {
LaunchAppWithIntent(app_id, apps_util::CreateIntentFromUrl(url),
launch_source, display_id);
}
void AppServiceProxy::SetPermission(const std::string& app_id,
apps::mojom::PermissionPtr permission) {
if (app_service_.is_connected()) {
cache_.ForOneApp(
app_id, [this, &permission](const apps::AppUpdate& update) {
app_service_->SetPermission(update.AppType(), update.AppId(),
std::move(permission));
});
}
}
void AppServiceProxy::Uninstall(const std::string& app_id,
gfx::NativeWindow parent_window) {
if (app_service_.is_connected()) {
cache_.ForOneApp(
app_id, [this, parent_window](const apps::AppUpdate& update) {
apps::mojom::IconKeyPtr icon_key = update.IconKey();
uninstall_dialogs_.emplace(std::make_unique<UninstallDialog>(
profile_, update.AppType(), update.AppId(), update.Name(),
std::move(icon_key), this, parent_window,
base::BindOnce(&AppServiceProxy::OnUninstallDialogClosed,
weak_ptr_factory_.GetWeakPtr(), update.AppType(),
update.AppId())));
});
}
}
void AppServiceProxy::OnUninstallDialogClosed(
apps::mojom::AppType app_type,
const std::string& app_id,
bool uninstall,
bool clear_site_data,
bool report_abuse,
UninstallDialog* uninstall_dialog) {
if (uninstall)
app_service_->Uninstall(app_type, app_id, clear_site_data, report_abuse);
DCHECK(uninstall_dialog);
auto it = uninstall_dialogs_.find(uninstall_dialog);
DCHECK(it != uninstall_dialogs_.end());
uninstall_dialogs_.erase(it);
}
void AppServiceProxy::PauseApps(
const std::map<std::string, PauseData>& pause_data) {
if (!app_service_.is_connected())
return;
for (auto& data : pause_data) {
apps::mojom::AppType app_type = cache_.GetAppType(data.first);
constexpr bool kPaused = true;
UpdatePausedStatus(app_type, data.first, kPaused);
// TODO(crbug.com/1011235): Add the app running checking. If the app is not
// running, don't create the pause dialog, pause the app directly.
if (app_type != apps::mojom::AppType::kArc) {
// TODO(crbug.com/1011235): Add AppService interface to apply icon
// effects.
continue;
}
cache_.ForOneApp(data.first, [this, &data](const apps::AppUpdate& update) {
this->LoadIconForPauseDialog(update, data.second);
});
}
}
void AppServiceProxy::UnpauseApps(const std::set<std::string>& app_ids) {
if (!app_service_.is_connected())
return;
for (auto& app_id : app_ids) {
apps::mojom::AppType app_type = cache_.GetAppType(app_id);
constexpr bool kPaused = false;
UpdatePausedStatus(app_type, app_id, kPaused);
// TODO(crbug.com/1011235): Add AppService interface to recover icon
// effects.
}
}
void AppServiceProxy::OnPauseDialogClosed(apps::mojom::AppType app_type,
const std::string& app_id) {
// TODO(crbug.com/1011235): Add AppService interface to apply the icon effect
// and stop the running app.
}
void AppServiceProxy::OpenNativeSettings(const std::string& app_id) {
if (app_service_.is_connected()) {
cache_.ForOneApp(app_id, [this](const apps::AppUpdate& update) {
app_service_->OpenNativeSettings(update.AppType(), update.AppId());
});
}
}
void AppServiceProxy::FlushMojoCallsForTesting() {
app_service_impl_->FlushMojoCallsForTesting();
#if defined(OS_CHROMEOS)
built_in_chrome_os_apps_->FlushMojoCallsForTesting();
crostini_apps_->FlushMojoCallsForTesting();
extension_apps_->FlushMojoCallsForTesting();
extension_web_apps_->FlushMojoCallsForTesting();
#endif
receivers_.FlushForTesting();
}
apps::IconLoader* AppServiceProxy::OverrideInnerIconLoaderForTesting(
apps::IconLoader* icon_loader) {
apps::IconLoader* old =
inner_icon_loader_.overriding_icon_loader_for_testing_;
inner_icon_loader_.overriding_icon_loader_for_testing_ = icon_loader;
return old;
}
void AppServiceProxy::ReInitializeCrostiniForTesting(Profile* profile) {
#if defined(OS_CHROMEOS)
if (app_service_.is_connected()) {
crostini_apps_->ReInitializeForTesting(app_service_, profile);
}
#endif
}
std::vector<std::string> AppServiceProxy::GetAppIdsForUrl(const GURL& url) {
return GetAppIdsForIntent(apps_util::CreateIntentFromUrl(url));
}
std::vector<std::string> AppServiceProxy::GetAppIdsForIntent(
apps::mojom::IntentPtr intent) {
std::vector<std::string> app_ids;
if (app_service_.is_bound()) {
cache_.ForEachApp([&app_ids, &intent](const apps::AppUpdate& update) {
for (const auto& filter : update.IntentFilters()) {
if (apps_util::IntentMatchesFilter(intent, filter)) {
app_ids.push_back(update.AppId());
}
}
});
}
return app_ids;
}
void AppServiceProxy::SetArcIsRegistered() {
#if defined(OS_CHROMEOS)
if (arc_is_registered_) {
return;
}
arc_is_registered_ = true;
extension_apps_->ObserveArc();
extension_web_apps_->ObserveArc();
#endif
}
void AppServiceProxy::AddPreferredApp(const std::string& app_id,
const GURL& url) {
AddPreferredApp(app_id, apps_util::CreateIntentFromUrl(url));
}
void AppServiceProxy::AddPreferredApp(const std::string& app_id,
const apps::mojom::IntentPtr& intent) {
auto intent_filter = FindBestMatchingFilter(intent);
if (intent_filter) {
preferred_apps_.AddPreferredApp(app_id, intent_filter);
if (app_service_.is_connected()) {
cache_.ForOneApp(app_id, [this, &intent_filter,
&intent](const apps::AppUpdate& update) {
app_service_->AddPreferredApp(update.AppType(), update.AppId(),
std::move(intent_filter),
intent->Clone());
});
}
}
}
void AppServiceProxy::AddAppIconSource(Profile* profile) {
// Make the chrome://app-icon/ resource available.
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
void AppServiceProxy::Shutdown() {
uninstall_dialogs_.clear();
#if defined(OS_CHROMEOS)
if (app_service_.is_connected()) {
extension_apps_->Shutdown();
extension_web_apps_->Shutdown();
}
#endif // OS_CHROMEOS
}
void AppServiceProxy::OnApps(std::vector<apps::mojom::AppPtr> deltas) {
cache_.OnApps(std::move(deltas));
}
void AppServiceProxy::Clone(
mojo::PendingReceiver<apps::mojom::Subscriber> receiver) {
receivers_.Add(this, std::move(receiver));
}
void AppServiceProxy::OnPreferredAppSet(
const std::string& app_id,
apps::mojom::IntentFilterPtr intent_filter) {
preferred_apps_.AddPreferredApp(app_id, intent_filter);
}
void AppServiceProxy::InitializePreferredApps(base::Value preferred_apps) {
preferred_apps_.Init(
std::make_unique<base::Value>(std::move(preferred_apps)));
}
void AppServiceProxy::LoadIconForPauseDialog(const apps::AppUpdate& update,
const PauseData& pause_data) {
apps::mojom::IconKeyPtr icon_key = update.IconKey();
constexpr bool kAllowPlaceholderIcon = false;
constexpr int32_t kPauseIconSize = 48;
LoadIconFromIconKey(
update.AppType(), update.AppId(), std::move(icon_key),
apps::mojom::IconCompression::kUncompressed, kPauseIconSize,
kAllowPlaceholderIcon,
base::BindOnce(&AppServiceProxy::OnLoadIconForPauseDialog,
weak_ptr_factory_.GetWeakPtr(), update.AppType(),
update.AppId(), update.Name(), pause_data));
}
void AppServiceProxy::OnLoadIconForPauseDialog(
apps::mojom::AppType app_type,
const std::string& app_id,
const std::string& app_name,
const PauseData& pause_data,
apps::mojom::IconValuePtr icon_value) {
if (icon_value->icon_compression !=
apps::mojom::IconCompression::kUncompressed) {
OnPauseDialogClosed(app_type, app_id);
return;
}
AppServiceProxy::CreatePauseDialog(
app_name, icon_value->uncompressed, pause_data,
base::BindOnce(&AppServiceProxy::OnPauseDialogClosed,
weak_ptr_factory_.GetWeakPtr(), app_type, app_id));
}
void AppServiceProxy::UpdatePausedStatus(apps::mojom::AppType app_type,
const std::string& app_id,
bool paused) {
std::vector<apps::mojom::AppPtr> apps;
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = app_type;
app->app_id = app_id;
app->paused = (paused) ? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
apps.push_back(std::move(app));
cache_.OnApps(std::move(apps));
}
} // namespace apps
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
981e446a04813763d7ee618b4f5643518f055d8c | 800b71b4558e8a6ab7f6a7e94ecf1b1a4219395b | /Day-13.cpp | e3c87163c2357327087cd31dd37fcf6fb4ac8a0a | [] | no_license | Ashish-kumar7/ashish-cpp-thewireuschallenge2020 | 091d7c2bba2dc1bd08031c3bd77b1a34cb038e12 | 79689f812564e55df7ffb596f62ce53b29f01295 | refs/heads/master | 2022-12-24T08:01:50.021214 | 2020-10-03T16:15:27 | 2020-10-03T16:15:27 | 296,509,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | // author: Ashish Kumar
// day: 13
// #thewireuschallenge2020
// c++
#include <bits/stdc++.h>
using namespace std;
void solve(int n,char start,char dest,char help){
if(n==1){
cout<<" Move "<<n<< " from " << start <<" to " << dest <<endl;
return;
}
solve(n-1,start,help,dest);
cout<<" Move "<<n<< " from " << start <<" to " << dest <<endl;
solve(n-1,help,dest,start);
return ;
}
int main(){
int n;
cin>>n;
char start='A';
char dest='C';
char help='B';
solve(n,start,help,dest);
return 0;
} | [
"ashishkumar357ak@gmail.com"
] | ashishkumar357ak@gmail.com |
c1b500e43e926778189438bdc062ae2223dc8f6f | 38c833575af2f7731379fe145ba9ca82c4232e73 | /Volume11(ICPC-Domestic)/aoj1167_Pollock'sConjecture.cpp | 4da9f5e304bdf9728ace7a41971f5202a750d9e1 | [] | no_license | xuelei7/AOJ | b962fad9e814274b4c24ae1e891b37cae5c143f2 | 81f565ab8b3967a5db838e09f70154bb7a8af507 | refs/heads/main | 2023-08-26T08:39:46.392711 | 2021-11-10T14:27:04 | 2021-11-10T14:27:04 | 426,647,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (int)(a); (i) < (int)(b); (i)++)
#define rrep(i, a, b) for (int i = (int)(b) - 1; (i) >= (int)(a); (i)--)
#define all(v) v.begin(), v.end()
typedef long long ll;
template <class T> using V = vector<T>;
template <class T> using VV = vector<V<T>>;
/* 提出時これをコメントアウトする */
#define LOCAL true
#ifdef LOCAL
#define dbg(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl
#else
#define dbg(x) true
#endif
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
constexpr char endl = '\n';
V<int> v(1000010,1e9);
V<int> vv(1000010,1e9);
v[0] = 0;
vv[0] = 0;
rep(i,1,1000010) {
int mi = 1e9;
int mii = 1e9;
int k = 1;
while (k*(k+1)*(k+2)/6 <= i) {
mi = min(mi, v[i-k*(k+1)*(k+2)/6]);
if (k*(k+1)*(k+2)/6%2 == 1)
mii = min(mii, vv[i-k*(k+1)*(k+2)/6]);
k++;
}
v[i] = mi+1;
vv[i] = mii+1;
}
int n;
while (cin >> n, n) {
cout << v[n] << " " << vv[n] << endl;
}
return 0;
} | [
"yuxuelei52@hotmail.com"
] | yuxuelei52@hotmail.com |
dd5716c3b58d0ddbddf684f35ee3ca8508856836 | bd9e8e540957914b455b62ac42f38eba883f8d18 | /main.cc | 10c5e6d671f032c26204f7fec7f4366cce2b02c7 | [] | no_license | Hans-Zhang28/dungeon-crawl-game | cdfbc529ff44d4310b66d4952a09d09bdd8c502b | e800dda19084b817d79d4dce4d914ad80ae2de18 | refs/heads/master | 2021-01-10T17:45:40.972790 | 2016-01-22T22:12:31 | 2016-01-22T22:12:31 | 50,210,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cc | #include "controller.h"
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(0));
Controller c; // create a controller
if(argc == 2) // if we read in floor which has all things generated
{
string argfile=argv[1];
c.play(argfile, true);
}
else // if we randomly generate our own items
{
c.play("emptyboard.txt", false); // play the game
}
}
| [
"hanszhan28@hotmail.com"
] | hanszhan28@hotmail.com |
e0b3c107d843182cea119d041a7fb13fd5fb50f4 | db44687f3b9e143743db69b0bc1c331988137dec | /include/mpl_traj_solver/poly_traj.h | 048f33d66a454c90d82e1e9bbeedd893495ed99f | [
"Apache-2.0"
] | permissive | yugo1103/motion_primitive_library | a2d4c9bcc9eb74eaae755d3bed14a566f2fef9d7 | 393a3d5fb1cac744bfb7dbd078f76841eb2d61cd | refs/heads/master | 2020-03-24T20:20:09.694982 | 2019-10-23T12:24:34 | 2019-10-23T12:24:34 | 142,972,403 | 0 | 0 | Apache-2.0 | 2018-07-31T06:33:41 | 2018-07-31T06:33:41 | null | UTF-8 | C++ | false | false | 1,214 | h | /**
* @file poly_traj.h
* @brief Trajectory object for PolySolver
*/
#ifndef MPL_POLY_TRAJ_H
#define MPL_POLY_TRAJ_H
#include <mpl_basis/primitive.h>
#include <memory>
#include <deque>
/**
* @brief Trajectory class for solving n-th polynomial with PolySolver
*/
template <int Dim>
class PolyTraj {
public:
///Simple constructor
PolyTraj();
///Clear
void clear();
///Set waypoints
void setWaypoints(const vec_E<Waypoint<Dim>>& ws);
///Set time allocation
void setTime(const std::vector<decimal_t> &dts);
///Add coefficients
void addCoeff(const MatDNf<Dim>& coeff);
///Convert to Primitive class
vec_E<Primitive<Dim>> toPrimitives() const;
///Evaluate the waypoint at t
Waypoint<Dim> evaluate(decimal_t t) const;
///Get the total time for the trajectory
decimal_t getTotalTime() const;
///Get the p
MatDNf<Dim> p();
private:
std::vector<decimal_t> waypoint_times_;
std::vector<decimal_t> dts_;
vec_E<Waypoint<Dim>> waypoints_;
std::deque<MatDNf<Dim>, Eigen::aligned_allocator<MatDNf<Dim>>> coefficients_;
};
///PolyTraj in 2D
typedef PolyTraj<2> PolyTraj2D;
///PolyTraj in 3D
typedef PolyTraj<3> PolyTraj3D;
#endif
| [
"lskwdlskwd@gmail.com"
] | lskwdlskwd@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.